This article is participating in Python Theme Month. See the link to the event for more details
Hello, everybody. I found another interesting little thing today. I’m an old poem about funny gadgets.
I believe that many people are beginners in Python. They clearly learned the syntax, but feel like nothing. In fact, optical practice is not good. We have to actually put the code on the screen and run it to get results.
For prime
Def _odd_iter(): n=1 while True: N =n+2 yield n def _not_divisible(n): Yield 2 it=_odd_iter() Yield n it=filter(_not_divisible(n),it)# Build new sequence for n in primes(): if n<100: print(n) else: breakCopy the code
Yang hui triangle
Def triangles(): N=[1], using a triangles triangles(say, triangles): yield N N=[1]+[N[i]+N[i+1] for i in range(len(N)-1)]+[1] n=0 for t in triangles(): print(t) n=n+1 if n==10: breakCopy the code
Hanoi
def move(A,C):
print(A,'--->',C)
def hanoi(n,A,B,C):
if n==1:
move(A,C)
else:
hanoi(n-1,A,C,B)
move(A,C)
hanoi(n-1,B,A,C)
hanoi(3,'A','B','C')
Copy the code
Palindrome judgment
Def f(n): return STR (n)== STR (n)[::-1] print(list(filter(f,range(1,1000))))) # def f(n): return STR (n)== STR (n)[::-1] print(list(filter(f,range(1,1000)) s=str(n) l=len(s) i=0 while i<l-i-1: if s[i]! =s[l-i-1]: return False I = I +1 return True print(list(filter(is_palindrome,range(1,1000)))))Copy the code
O s = a + aa + aaa + aaaa + aa… The value of a
Where a is a number. For example, 2+22+222+2222+22222(there are 5 numbers added together), and the addition of several numbers is controlled by the keyboard.
#! /usr/bin/python from functools import reduce Tn = 0 Sn = [] n = int(input('n = ')) a = int(input('a = ')) for count in Range (n): Tn = Tn + a a = a * 10 sn. append(Tn) print (Tn) Sn = reduce(lambda x,y: x + y,Sn)Copy the code
And the number of
A number is called complete if it is exactly equal to the sum of its factors. For example, 6=1+2+3. Program to find all finals up to 1000.
#! /usr/bin/python # -* -coding: utf-8 -* -from sys import stdout for j in range(2,1001): k = [] n = -1 s = j for i in range(1,j): if j % i == 0: n += 1 s -= i k.append(i) if s == 0: print (j) for i in range(n): stdout.write(str(k[i])) stdout.write(' ') print (k[n])Copy the code
Programming wants to be good, contact is indispensable. More classic exercises, please move to the public number: like the code poem