这里确实需要一些帮助。学习 Python 的超级早。
目标是获取一个数字并查看数字是否按升序排列。
到目前为止我所拥有的是:
a = int(input("Enter a 4-digit number: "))
b = [int(i) for i in str(a)]
if b[0] > b[1]:
print "Not ascending"
elif b[1] > b[2]:
print "Not ascending"
elif b[2] > b[3]:
print "Not ascending"
else:
print "Ascending!"
我的问题是,如何才能使输入的数字数量不受限制?因此,如果有人输入 7 位数字,它会执行相同的过程直到最后一位数字。
第一步对所有输入进行排序
b = [int(i) for i in str(a)]
第二步,将原始输入与排序列表进行比较,列表中的所有元素都可以用字符串(数字字符串)连接,因此您只能比较一次。
c = sorted(b)
''.join([str(i) for i in b]) > ''.join([str(i) for i in c]):
print "Not ascending"
else:
print "Ascending!"
或者使用 std lib,按照您的方式检查每个元素和下一个元素:
every_check = [b[i] <= b[i+1] for i in xrange(len(b)-1)]
[真,真,假,假]
and use all()
检查是否全部True
if all(every_check):
print "Ascending!"
else:
print "Not ascending"
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)