Some code I (Fibonacci, For...else ..., try and return, Classmethod, count)

Source: Internet
Author: User

1. Fibonacci
 from Import Islice def fib ():     = 0, 1 while      True:        yield  a        = B, A +bprint List (Islice (FIB (), 5))    #  [0, 1, 1, 2, 3]
2. For......else ... Usage (for example, to find prime numbers)

Normal version:

1 defprint_prime (n):2      forIinchXrange (2, N):3Found =True4          forJinchXrange (2, i):5             ifI% J = =0:6Found =False7                  Break8         iffound:9             Print '%d is a prime number'%i

For......else ... Version

1 defprint_prime (n):2      forIinchXrange (2, N):3          forJinchXrange (2, i):4             ifI% J = =0:5                  Break6         Else:7             Print '%d is a prime number'% i

When the loop ' natural ' is terminated (the loop condition is false), the ELSE clause is executed once, and when the loop is interrupted by a break statement, the else clauses are not executed.

Similar to the For statement, the ELSE clause in the while statement has the same semantics: the else block is executed when the loop ends normally and the loop condition is not true.

Try...except...else...finally ... Statement, else is executed when there is no exception.

3. Try and return
1 defReturntest (a):2     Try:3         ifA <=0:4             RaiseValueError ('data can not be negative')5         Else:6             returna7     exceptValueError as E:8         Printe9     finally:Ten         Print 'The end' One         return-1 A    - PrintReturntest (0)#-1 - PrintReturntest (2)#-1

Returntest (0) returns-1, does not explain.

Returntest (2) returns-1, because A>0 executes the else score, but because of a finally statement, the statement in finally is executed before the return a statement of the Else statement is executed. At this point, because there is a return in the finally statement, the program returns directly, so the return in the Else statement is never executed.

In the actual application development process, it is not recommended to return using the return statement in finally.

4. @classmethod
1 classFruit (object):2Total =03     4 @classmethod5     defPrint_total (CLS):6         PrintCls.total7         8 @classmethod9     defset (CLS, value):TenCls.total =value One          A classApple (Fruit): -     Pass -  the classOrange (Fruit): -     Pass -  - 
+ Apple. Set (200) -Apple. Print_total ()#200 non-classmethod cannot be called, first instantiate + 22
at Orange. Set (300) - Orange. Print_total ()# -

Normal inheritance is a method that requires a subclass to refactor the parent class. When the @classmethod is called, the implicit passed-in parameter is the class corresponding to the object.

5. Number of statistics
1  fromCollectionsImportCounter2 3data = ['a','2', 2, 4, 5,'2','b', 4, 7,'a', 5,'D','a','Z']4 PrintCounter (data)5 #Counter ({' A ': 3, 4:2, 5:2, ' 2 ': 2, 2:1, ' B ': 1, 7:1, ' Z ': 1, ' d ': 1})

Counter is primarily used to count hash objects, providing different initialization methods in 3:

1Counter ('Success')#can iterate over objects2Counter (s=3, c=2, e=1, u=1)#keyword Parameters3Counter ({'s': 3,'C': 2,'u': 1,'e': 1})#Dictionary

Use the elements () method to get the key value in the counter

1 List (Counter (data). elements ()) 2 # [' A ', ' a ', ' a ', 2, ' B ', 4, 4, 5, 5, 7, ' 2 ', ' 2 ', ' Z ', ' d ']

Use the Most_common (n) method to find the top N most frequently occurring elements and their corresponding number of times.

1 # [(' A ', 3), (4, 2)]

When the access element is not present, 0 is returned by default instead of throwing the keyerror exception.

1 (Counter (data)) ['y']    #  0

Use the update () method to implement total element statistics addition for counter objects.

Use the Subtract () method to implement the statistic values of the elements in the Counter object, and the input and output statistics are allowed to be 0 or negative.

Some code I (Fibonacci, For...else ..., try and return, Classmethod, count)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.