1. 求任意给定的数值列表中的最小值。 不可使用min函数,要求使用两种方法解决, 其中一种方法要求使用reduce()函数解决。
第一种
L
=[1,2,3,4,5,6]
t
=L
[0]
for i
in L
:
if t
>i
:
t
=i
print("最小值为:",t
)
结果: 第二种
from functools
import reduce
def f(x
,y
):
if x
>y
: return y
else : return x
L
=[1,2,3,4,5,6,-1,0]
print("最小值为:",reduce(f
, L
))
结果:
2. 实现isPrime()函数,参数为整数。函数功能是:如果整数是质数,则返回True,否则返回False。运用filter()函数得到200以内的全部质数,并输出结果。
def isPrime(num
):
if num
==1:
return False
for i
in range(2,num
):
if num
%i
==0 :
return False
elif num
==2:
return True
return True
print(list(filter(isPrime
,range(1,201))))
结果:
3. 编写一个函数,其功能是随机生成5个8位密码,密码中所用的字符需要从26个字母和0~9这10个数字中随机选取, 要求每一个8位密码的首字符不能相同。函数返回一个列表,列表中的元素就是生成的5个8位密码。
import random
s
= ["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z","A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z","0","1","2","3","4","5","6","7","8","9"]
for i
in range(5):
for i
in range(8):
print (random
.choice
(s
),end
="")
print("\n")
结果:
4. 定义一个递归函数实现与内置函数len()函数相同的功能。
def flen(L
):
if not L
:
return
else:
L
.pop
()
return flen
(L
)+1
print(len([1,2,3,4,5,6,7,8,9]))
结果:
5. 使用reduce()、map(),以及lambda表达式计算前n个自然数的立方和,n由用户输入。
from functools
import reduce
def f(x
,y
):
return x
+y
n
=eval(input("您想要前几个自然数的立方和:"))
L
=reduce(f
,map(lambda x
:x
**3,range(n
+1)))
print(L
)
结果:
6. 编写一个函数,返回任意字符串短语的首字母缩略词。例如:“random access memory”得到其缩略词位“RAM”。L=“random access memory”.split(" ")
def bw(L
):
L
=L
.split
(" ")
for i
in L
:
print(i
[0].capitalize
(),end
=(""))
return ""
L
='random access memory'
print(bw
(L
))
结果:
7. 编写一个函数,返回任意英文句子中的平均单词长度。
def rlen(eng
):
danci
=1
zimu
=0
for i
in eng
:
if i
!=" " and i
!="." and i
!="?":
zimu
+=1
elif i
==" ":
danci
+=1
return zimu
/danci
L
=("english is a.")
print(rlen
(L
))
结果:
8. 编写一个函数,判别任意两个字符串s1,s2是否具有相同字符, 如果存在相同字符则返回True,以及共同的字符;如果不存在相同字符, 则返回False,None。例如:s1 = “abcde”, s2 = “befghi”,则函数返回True,“be”。
def restimate(s1
,s2
):
l
=[]
for i
in s1
:
for j
in s2
:
if i
==j
:
l
.append
(i
)
if l
:
l
="".join
(l
)
return True,l
else:
return False,None
s1
= 'abcde'
s2
= 'befghi'
print(restimate
(s1
,s2
))
结果:
9.利用reduce、filter、lambda求1-100的偶数和 from functools import reduce
def f(x
,y
):
return x
+y
L
=reduce(f
,filter(lambda x
:not x
%2, range(1,101)))
print(L
)
结果:
学习仅供参考,如有错误望指出
转载请注明原文地址:https://blackberry.8miu.com/read-42481.html