失眠网,内容丰富有趣,生活中的好帮手!
失眠网 > python输入10个数 找出对称数_Python入门100道习题(7)——找对称数

python输入10个数 找出对称数_Python入门100道习题(7)——找对称数

时间:2020-11-24 01:21:09

相关推荐

python输入10个数 找出对称数_Python入门100道习题(7)——找对称数

问题描述

【问题描述】已知10个四位数输出所有对称数及个数 n,例如1221、2332都是对称数

【输入形式】10个整数,以空格分隔开

【输出形式】输入的整数中的所有对称数,对称数个数

【样例输入】1221 2243 2332 1435 1236 5623 4321 4356 6754 3234

【样例输出】1221 2332 2

【样例说明】为测试程序健壮性,输入数中可能包括3位数、5位数等

不考虑3位数、5位数的情形

#n是对称的四位数吗

def is_duicheng(n):

n_str = str(n)

return n_str[0] == n_str[3] and n_str[1] == n_str[2]

# if n_str[0] == n_str[3] and n_str[1] == n_str[2]:

# return True

# else:

# return False

#读入10个整数

line = input().split()

nums = []

for s in line:

nums.append(int(s))

#print("nums=", nums)

duicheng_list = []

for n in nums:

if is_duicheng(n):

duicheng_list.append(n)

for d in duicheng_list:

print(d, end=' ')

print(len(duicheng_list))

对上述代码,说明如下:

1. 第2到8行定义了判别一个整数是否是对称数的函数is_duicheng。函数是一组语句的集合。第19行调用了is_duicheng函数,传入要被判别的整数n。调用函数,就会执行函数包含的语句。第19行的n是实际参数,而第2行的n是形式参数,两者的名字可以不同。

2. 我们把4位数转换为字符串,然后比对第1,4位是否相同,第2,3位是否相同,都相同的话,就是对称的。

3. 第10到14行,输入10个整数。第15行,是打印这10个整数,帮助我们判断输入动作对了没有。

4. 第17行,duicheng_list变量用来存储对称的四位数。第18到20行求出所有对称的四位数。

5. 第22,23行,输出所有。这样,输出d的值后,在其尾部接一个空格,且不换行。第24行,输出对称数的个数,也就是duicheng_list的长度。它会接在前面的输出内容尾部。

考虑3位数、5位数的情形

在上一节的代码基础上,增加下面所列的第4,5行,就实现了考虑3位数,5位数的情形。

#n是对称的四位数吗

def is_duicheng(n):

n_str = str(n)

if len(n_str) != 4:

return False

return n_str[0] == n_str[3] and n_str[1] == n_str[2]

# if n_str[0] == n_str[3] and n_str[1] == n_str[2]:

# return True

# else:

# return False

#读入10个整数

line = input().split()

nums = []

for s in line:

nums.append(int(s))

#print("nums=", nums)

duicheng_list = []

for n in nums:

if is_duicheng(n):

duicheng_list.append(n)

for d in duicheng_list:

print(d, end=' ')

print(len(duicheng_list))

小结

判断对称数的做法是,把4位数转换为字符串,然后比对第1,4位是否相同,第2,3位是否相同,都相同的话,就是对称的。

用函数来定义判断对称数的逻辑,是好做法。

如果觉得《python输入10个数 找出对称数_Python入门100道习题(7)——找对称数》对你有帮助,请点赞、收藏,并留下你的观点哦!

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。