我想动态查找正确的序号根,例如:
111 = 111st
112 = 112nd
113 = 113rd ...
我试过其他的解决办法,但找不到好的
这是我的代码:
for number in range(1, 114):
print(number)
ex1 = 11
ex2 = 12
ex3 = 13
if number == ex1:
print("is the " + str(number) + "th number.")
elif number % 10 == 1 or not ex1:
print("is the " + str(number) + "st number.")
elif number == ex2:
print("is the " + str(number) + "nd number.")
elif number % 10 == 2 or not ex2:
print("is the " + str(number) + "nd number.")
elif number == ex3:
print("is the " + str(number) + "rd number.")
elif number % 10 == 3 or not ex3:
print("is the " + str(number) + "rd number")
else:
print("is the " + str(number) + "th number.")
因此,问题是
111
显示为111st
,而不是111th
你有
11
作为ex1
,我假设是“异常1”的缩写,但是你的条件:显然不匹配
111
相反,你可以做:
这对于{}、{}、{}等都是正确的
旁注:
显然不是你想要的。这被解释为:
not ex1
不依赖于number
,并且总是以相同的方式进行计算(False
)。但是,由于您已经分别检查了ex1
,因此在这里正确地检查是多余的如果您想更正此问题,这样就不需要检查
ex1
两次,您可以这样做:我认为在这种情况下,使用
!=
比使用not
更清晰,并且我认为将变量赋值给11
没有任何好处这是一个非常好的解决方案:
为人类编辑
注意:变量名称不适用于生产环境,我试图使lambda函数的每个步骤都更加明确强>
考虑
找到的解决方案非常简单和聪明,我可能永远也不会想到我自己,正在使用一些聪明的数学技巧来寻找数字的偏移。 但是,根据要求,我简化了函数并添加了一些解释
第一步。这个字符串更好地理解为“tsnr”“htdd”|左边是字符串的“根”,右边是字符串的末端。(更多解释见下文)
第二步
is_num_divisible_by_ten
-->;使用floor division可以得到正确或错误的结果第三步
is_num_reminder_0_3
如果检查N和10的提醒是否在0&;3,返回真/假标志第四步
are_both_false_or_both_true
乘以2 bool值,在Python中,True是1,False是0,就像do-->;1 * 0. 仅当两个值均为真或均为假时,变量才为真,否则始终为假第五步
get_index
->;返回0或1或2或3第六步。在这里,hacky部分和从get_index接收到的索引是
hacking_string
变量与indexing-and-slicing:get_索引值始终是以下其中之一:“tsnr”和采取的步骤(4)这些“rhtdd”中的任何一个,因此可能的组合为:
最后
在math.stackexchange上询问它背后的确切数学可能更好,或者如果有人知道添加评论或编辑我的答案会更好
参考资料(这不是我的解决方案)
向导
注意,11、12和13有th后缀。
另请注意,您可以在
print
函数(默认值\n
)中更改行尾:然后,我建议您使用格式化字符串使用
f"{data} constant text"
或"{} constant text".format(data)
以下是我对您问题的解决方案:
我希望我能帮上忙
相关问题 更多 >
编程相关推荐