天天看點

python推導式及函數練習

from functools import reduce
# 猴子吃桃
sum=[reduce(lambda x,y:(x+1)*2,range(1,(13-j))) for j in range(2,12)]
print(sum)
# 素數
su=[i for i in range(2,101) if 0 not in [i%j for j in range(2,i-1)]]
print(su)
prime=filter(lambda x: not [x%i for i in range(2,x) if x%i==0], range(2,101))
print(list(prime))
 
#用枚舉對坐标和值拆分
from enum import Enum
for index in enumerate(y):
    print(index)
a=[1,2]
b=[4,3]
for i,d1 in enumerate(a):
    for j,d2 in enumerate(b):
        if(i==j):
            print(d1,d2)
for i in zip(a,b):
    print(i)
# 對x轉置
x=[[1,2,3,4],[5,6,7,8],[9,10,11,12]]
x1=[[i[w] for i in x] for w in range(len(x[0]))]
print(x1)
 
#求水仙花數
sh=[i for i in range(100,1000) if i==sum(int(j)**3 for  j in str(i))]
print(sh)
 
#c排列計算
def c(n,m):
    if(n==m):
        return 1
    else:
        def j(n):
            if (n == 1):
                return 1
            else:
                return n * j(n - 1)
    return j(n)/(j(m)*j(n-m))
print(c(4,2))
 
#列印楊輝三角
def y(t):
    x1=[1]
    x2=[1,1]
    for i in range(t):
        if(i==0):
            print(x1)
        elif(i==1):
            print(x2)
        else:
                x3=[]
                x3.append(1)
                for j in range(1,i):
                    x3.append(x2[j]+x2[j-1])
                x3.append(1)
                x2=x3
                print(x3)
y(9)
 
#統計大小寫字母的個數
def str(*n):
    s,l=0,0
    for i in n:
        if(i.isupper()):
            s+=1
        if(i.islower()):
            l+=1
    return s,l
x=("A","S","d","w","Q")
print(str(*x))
 
#逆序
def resort(l,k):
    x=l[:k]
    x.reverse()
    y=l[k:]
    y.reverse()
    r=x+y
    return list(reversed(r))
li=list(range(20))
print(resort(li,5))