100+Python挑战性编程练习 -- day 1

Question 1

写一个程序,找出2000到3200之间所有能被7整除但不是5的倍数的数。所获得的数字应以逗号分隔的顺序打印在一行上。

  1. 使用循环
for i in range(2000,3201):
    if i%7 == 0 and i%5!=0:
        print(i,end=',')
print("\b")
  1. 使用生成器和列表解析
print(*(i for i in range(2000, 3201) if i%7 == 0 and i%5 != 0), sep=",")

Question 2

写一个程序,可以计算一个给定数的阶乘。结果应以逗号分隔的顺序打印在单行上。假设向程序提供以下输入:8 然后,输出应为:40320

  1. 使用循环
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)
  1. 使用Lambda函数
n = int(input())
def shortFact(x): return 1 if x <= 1 else x*shortFact(x-1)
print(shortFact(n))
  1. 使用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}

  1. 使用循环
n = int(input())
ans = {}
for i in range (1,n+1):
    ans[i] = i * i
print(ans)
  1. 使用字典推导
n = int(input())
ans={i : i*i for i in range(1,n+1)}
print(ans)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值