我正在尝试让我的程序返回0到9之间w整数的相反数字。
例如:
0 1 2 3 4 5 6 7 8 9
9 8 7 6 5 4 3 2 1 0
因此,当用户输入3位数字(如 245 )时,它应返回 754
我写了这样的东西,但是只能用1位数字!
number = input (" Enter the number! ")
if number == 0:
number = 9
elif number == 1:
number = 8
elif number == 2:
number = 7
elif number == 3:
number = 6
elif number == 4:
number = 5
elif number == 5:
number = 4
elif number == 6:
number = 3
elif number == 7:
number = 2
elif number == 8:
number = 1
elif number == 9:
number = 0
else:
print "You didn't enter a number"
print number
也没有那么动态!任何帮助将非常感激!谢谢
答案 0 :(得分:3)
使用第一个字符串中的索引来查找下一个字符串:
dateObj
样品运行:
s = '0123456789'
t = '9876543210'
num = input('Enter number: ')
result = ''.join([t[s.index(x)] for x in num])
或者,您可以不使用Enter number: 245
754
和查找就可以这样做:
s
答案 1 :(得分:2)
只需从最大可能数目中减去输入,您就会获得“翻转”行为:
value = input('Enter number: ')
result = 9 - int(value)
# If the input is 3, the output would be 6, as 9 - 3 = 6
对于较大的数字,您可以执行相同的操作,但要遍历每个数字:
result = ''.join([(9 - int(x)) for x in value])
作为纯粹基于数学的解决方案,您可以使用输入的长度并自动生成最大数量(在注释中记入RafazZ):
result = (10**len(value)-1) - int(value)
# If the input is 251, the output would be 748, as:
# len('251') = 3
# 10**3 - 1 = 999
# 999 - 251 = 748