题目1
输入一行字符,分别统计出其中英文字母、空格、数字和其它字符的个数。
程序分析
- 利用while语句,条件为输入的字符不为’\n’。
- 用isdigit函数判断是否数字。
- 用isalpha判断是否字母。
代码实现
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17s = input("Please input a string:")
digit = 0
alpha = 0
space = 0
other = 0
while s != '\\n':
for i in s:
if i.isdigit():
digit += 1
elif i.isalpha():
alpha += 1
elif i.isspace():
space += 1
else:
other += 1
print("数字个数:{0};字母个数:{1};空格个数:{2};其他字符个数:{3}".format(digit, alpha, space, other))
break
输出结果
题目2
计算0!+1!+….+n!
程序分析
- 0! == 1。1! == 1。
- 先计算 n!,然后再循环求和
- 根据 n! = n (n-1) (n-2) …. 1,采用循环方式计算n!
- 根据 n! = n * (n - 1)!,采用递归方式计算n!
代码实现
普通函数
1
2
3
4
5def factor1(x):
res = 1
for a in range(2, x + 1):
res *= a
return res
递归函数
1 | def factorial(n): |
输出结果
调用普通函数
1 | cal = 0 |
结果为154
调用递归函数
1 | cal = 0 |
结果为154