Question 1
写一个程序,找出2000到3200之间所有能被7整除但不是5的倍数的数。所获得的数字应以逗号分隔的顺序打印在一行上。
- 使用循环
for i in range(2000,3201):
if i%7 == 0 and i%5!=0:
print(i,end=',')
print("\b")
- 使用生成器和列表解析
print(*(i for i in range(2000, 3201) if i%7 == 0 and i%5 != 0), sep=",")
Question 2
写一个程序,可以计算一个给定数的阶乘。结果应以逗号分隔的顺序打印在单行上。假设向程序提供以下输入:8 然后,输出应为:40320
- 使用循环
n = int(input()) #input() function takes input as string type
#int() converts it to integer type
fact = 1
for i in range(1,n+1):
fact = fact * i
print(fact)
- 使用Lambda函数
n = int(input())
def shortFact(x): return 1 if x <= 1 else x*shortFact(x-1)
print(shortFact(n))
- 使用reduce方法
from functools import reduce
def fun(acc, item):
return acc*item
num = int(input())
print(reduce(fun,range(1, num+1), 1))
Question 3
对于给定的整数n,编写一个程序来生成一个字典,其中包含(i,i x i),使得是1和n之间的整数(包括两者)。然后程序应该打印字典。假设向程序提供以下输入:8 然后,输出应为: {1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64}
- 使用循环
n = int(input())
ans = {}
for i in range (1,n+1):
ans[i] = i * i
print(ans)
- 使用字典推导
n = int(input())
ans={i : i*i for i in range(1,n+1)}
print(ans)