使用循环动态查找序号:查找第四个

2024-10-01 13:36:27 发布

您现在位置:Python中文网/ 问答频道 /正文

我想动态查找正确的序号根,例如:

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.")

Tags: orthenumberisnot动态rdprint
3条回答

因此,问题是111显示为111st,而不是111th

你有11作为ex1,我假设是“异常1”的缩写,但是你的条件:

if number == ex1:

显然不匹配111

相反,你可以做:

if number % 100 == ex1:

这对于{}、{}、{}等都是正确的

旁注:

elif number % 10 == 1 or not ex1:

显然不是你想要的。这被解释为:

elif (number % 10 == 1) or (not ex1):

not ex1不依赖于number,并且总是以相同的方式进行计算(False)。但是,由于您已经分别检查了ex1,因此在这里正确地检查是多余的

如果您想更正此问题,这样就不需要检查ex1两次,您可以这样做:

if number % 10 == 1 and number % 100 != 11:

我认为在这种情况下,使用!=比使用not更清晰,并且我认为将变量赋值给11没有任何好处

这是一个非常好的解决方案:

ordinal = lambda n: "%d%s" % (n, "tsnrhtdd"[(n // 10 % 10 != 1) * (n % 10 < 4) * n % 10::4])


for number in range(1, 114):
    print(f'the {ordinal(number)} number. :) ')

为人类编辑

注意:变量名称不适用于生产环境,我试图使lambda函数的每个步骤都更加明确

def get_ordinal(n):

    hacking_string = "tsnrhtdd"                                # 1)
    is_num_divisible_by_ten = (n // 10 % 10 != 1)              # 2)         
    is_num_reminder_0_3= (n % 10 < 4)                          # 3)
    are_both_false_or_both_true= is_num_divisible_by_ten * is_num_between_0_3  # 4)
    get_index = are_both_false_or_both_true* n % 10  # 5)
    
    return f'{number}{hacking_string[get_index::4]}'  #6)  ---> starts at t | s | n | r
    
for number in range(1, 114):
    print(f'the {get_ordinal(number)} number. :) ')

考虑

找到的解决方案非常简单和聪明,我可能永远也不会想到我自己,正在使用一些聪明的数学技巧来寻找数字的偏移。 但是,根据要求,我简化了函数并添加了一些解释

  • 第一步。这个字符串更好地理解为“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”中的任何一个,因此可能的组合为:

get_index = 0 = "th"  
get_index = 1 = "st"
get_index = 2 = "nd"
get_index = 3 = "rd"

最后

math.stackexchange上询问它背后的确切数学可能更好,或者如果有人知道添加评论或编辑我的答案会更好

参考资料(这不是我的解决方案)

向导

注意,11、12和13有th后缀。
另请注意,您可以在print函数(默认值\n)中更改行尾:

print('text', end=' ')
print('another text')

然后,我建议您使用格式化字符串使用f"{data} constant text""{} constant text".format(data)

以下是我对您问题的解决方案:

def getSuffix(n):
    if n < 0: raise Exception("Ordinal negative numbers are not allowed")
    if n % 100 in [11, 12, 13]: return 'th'
    if n % 10 == 1: return 'st'
    if n % 10 == 2: return 'nd'
    if n % 10 == 3: return 'rd'
    return 'th'


for number in range(1, 114):
    print(f"{number} is the {number}{getSuffix(number)} number")

我希望我能帮上忙

相关问题 更多 >