刷题

第2天的作业打卡

给定任意一个整数

  1. 输出该整数有多少个数字是大于0的
  2. 输出该整数中有多少个偶数数字,有多少个奇数数字

可以当成字符串来处理,也可以当成整数来处理。

当成整数来处理

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
positive_numbers=[]
odd_numbers=[]
even_numbers=[]

try:
number = int(input("An integer please: "))
except ValueError:
print('Input is not an integer, giving up.')
sys.exit()

while number:
number, digit = divmod(number, 10)
if digit != 0:
positive_numbers.insert(0, digit)
if digit % 2 == 0:
even_numbers.insert(0, digit)
else:
odd_numbers.insert(0, digit)

res1=', '.join(str(item) for item in positive_numbers)
res2=', '.join(str(item) for item in even_numbers)
res3=', '.join(str(item) for item in odd_numbers)

当成字符串来处理

精简前

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
def postive_numbers(value):
p_n = 0
res = []
for character in value:
if int(character) > 0:
p_n += 1
res.append(character)
output = ', '.join(res)
print(f'有{p_n}个数字大于0, 分别是{output}')

def odd_or_not(value):
o_n = 0
e_n = 0
res1, res2 = [], []
for character in value:
if int(character) % 2 != 0:
o_n += 1
res1.append(character)
else:
e_n += 1
res2.append(character)
output1 = ', '.join(res1)
output2 = ', '.join(res2)
print(f'有{e_n}个偶数数字: 分别是{output2},有{o_n}个奇数数字: 分别是{output1}')

if __name__ == '__main__':
value=input("An integer please: ")
postive_numbers(value)
odd_or_not(value)

精简后

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
def postive_numbers(value):
res = [character for character in value if int(character) > 0]
output = ', '.join(res)
print(f'有{len(res)}个数字大于0, 分别是{output}')

def odd_or_not(value):
res1 = [character for character in value if int(character) % 2 != 0]
res2 = [character for character in value if int(character) % 2 == 0]
output1 = ', '.join(res1)
output2 = ', '.join(res2)
print(f'有{len(res2)}个偶数数字: 分别是{output2}, 有{len(res1)}个奇数数字: 分别是{output1}')

if __name__ == '__main__':
value = input("An integer please: ")
postive_numbers(value)
odd_or_not(value)