是否为质素
def isPrime(n):
r=True
for i in range(2,n):
if n%i==0:
r=False
return r
isPrime(19)
匿名函数
def p():
poly=lambda x,y,z:1+2*x+y*y+z*y
print(poly(1,2,3))
p()
计算50的阶乘
import math
def ma():
result = math.factorial(50)
print(result)
ma()
是否为子集,并输出差集
def subset(set1,set2):
Y=set1.issubset(set2)
answer = [Y,set2-set1]
return answer
print(subset({1,2,3},{1,2,3,4,5}))
交集的长度
def intersect(set1,set2):
answer = len(set1&set2)
return answer
print(intersect({1,2,3},{3,4,5}))
两个列表元素相加
def add(lis):
answer=[lis[0][i]+lis[1][i] for i in range(min([len(i) for i in lis]))]
return answer
print(add([[1,2,3,4],[5,6,7]]))
字符串字母不重复
def single(string):
answer=not [ i for i in string if string.count(i)>1]
return answer
print(single('catC'))
矩阵列表输出某一列
def acquire(nestedlist,column):
outcome =[nestedlist[i][column-1] for i in range(len(nestedlist)) ]
return outcome
print(acquire([[1,2,3],[5,6,8],[9,11,15]],2))
两个字典的合并
def dic():
dict1 = {'sky':'blue','cloud':'white'}
dict2 = {'water':'transparent','grass':'green','rose':'red'}
merged_dict=dict(dict1,**dict2)
print(merged_dict)
dic()
斐波那契数列
def fic(n):
if not isinstance(n,int):
return 'n should be an integer'
elif n <= 0:
return 'n should be greater than 0'
else:
if n == 1:
sequence = [0]
if n == 2:
sequence = [0,1]
if n > 2:
sequence = [int((5**(-0.5))*(((1+5**(0.5))/2)**i-((1-5**(0.5))/2)**i)) for i in range(n) ]
return sequence
print(fic(10))
列表倒序
def nu():
a = ['god','my','oh']
b = a[::-1]
print(b)
nu()
列表元素合为一个字符串
def ne():
strlist = ['ab','cde','f']
string = ''.join(strlist)
print(string)
ne()
列表合并排序
def merge_list(list1,list2):
result = list1+list2
result.sort()
return result
print(merge_list([2,1],[10,0]))
字符串按长度切片为列表
def separate(string, maxlength):
result =[ string[i:i+maxlength] for i in range(0,len(string),maxlength) ]
return result
print(separate('abcdef',2) )
字母大小写互换
def swap(s):
swap = s.swapcase()
return swap
print(swap('abC'))