目录
定义一个函数,输入名字列表,输入随机数量,提取相应数量的名字,当次提取的名字不能有重复
水仙花数的程序编写
方法一
for i in range(100,1000):
strs = str(i)
bai = strs[0]
shi = strs[1]
ge = strs[2]
if eval('{}**3+ {}**3+ {}**3'.format(bai,shi,ge))==i:
print(i)
方法二
for s in range(100,1000):
ge = s%10
shi = s%100//10
bai = s//100
if ge**3+shi**3+bai**3==s:
print(s)
方法三
for ge in range(10):
for shi in range(10):
for bai in range(1,10):
if ge**3+shi**3+bai**3==ge+shi*10+bai*100:
print(ge+shi*10+bai*100)
结果
370
371
153
407
求列表中的最大值和最小值
lists = [2,3,5,1,7,9,3,56,2]
max = lists[0]
min = lists[0]
for i in lists[1:]:
if min>i:
min = i
elif max<i:
max = i
print(max,min)
结果
56 1
斐波那契数列的程序编写
def hello():
a,b = 1,0
for x in range(20):
a,b = b,a+b
yield a
x = hello()
for i in x:
print(i)
用自己的代码实现Strip()的功能
strs = 'ttttttttttttdlgjsdklgjslkgjttttttttt'
def hello(strs,h='all',s=' '):
while h=='l' or h=='all':
if strs[0]==s:
strs = strs[1:]
else:
break
while h=='r' or h=='all':
if strs[-1]==s:
strs=strs[:-1]
else:
break
return strs
print(hello(strs,h='r',s='t'))#通过判断选择去左或者右边的字符,或者全部去除
结果
ttttttttttttdlgjsdklgjslkgj
编写程序对列表中的元素去重
方法一
lists = [1,1,1,2,2,2,3,3,3,3,3,4,4]
n_l = []
for i in lists:
if i not in n_l:
n_l.append(i)
print(n_l)
结果
[1, 2, 3, 4]
方法二
print(list(set(lists))) #利用集合的特性去重
统计列表中每个元素出现的个数
lists = [1,1,1,2,2,2,3,3,3,3,3,4,4]
n_l = []
for i in range(len(lists)):
i = lists[i]
flag = 0
n = 0
for a,b in n_l:
if a==i:
n_l[n] = [i,b+1]
flag = 1
n=n+1
if flag==0:
n_l.append([i, 1])
print(n_l)
结果
[[1, 3], [2, 3], [3, 5], [4, 2]]
九九乘法表
strs = ''
for i in range(1,10):
for ii in range(1,i+1):
strs+='{}x{}={} '.format(ii,i,i*ii)
strs = strs+'\n'
print(strs)
结果
1x1=1
1x2=2 2x2=4
1x3=3 2x3=6 3x3=9
1x4=4 2x4=8 3x4=12 4x4=16
1