Project Euler#17的意外结果(Python 3 vs Python 2.7)

时间:2014-09-03 04:11:38

标签: python python-2.7 python-3.x

所以我正在通过Project Euler#17工作,试图找到答案,而不是真正的目标是提高效率。然而,在阅读了我打印的每一个数字(我认为)后,我找不到正确答案正是100个字符的答案。所以我决定来找SO,当我在事故中使用Python 2.7在线编译时,我得到了截然不同的结果!我不确定为什么在Python 2.7中编译它会导致一个非常错误的答案,而在Python 3中它几乎没有。无论如何,这里是我在网上编译的两个地方:

正确答案,我的Python 3答案,我的Python 2.7答案: 21124,21224,1863

Python 3: http://ideone.com/ugfSV1

Python 2.7:我不知道如何分享它,因此您只需手动复制并粘贴以下代码http://www.compileonline.com/execute_python_online.php

这是我的算法:

import time

start = time.time()

singles = {0: "",
           1: "one",
           2: "two",
           3: "three",
           4: "four",
           5: "five",
           6: "six",
           7: "seven",
           8: "eight",
           9: "nine",
           10: "ten",
           11: "eleven",
           12: "twelve",
           13: "thirteen",
           14: "fourteen",
           15: "fifteen",
           16: "sixteen",
           17: "seventeen",
           18: "eighteen",
           19: "nineteen"}

tens = {2: "twenty",
        3: "thirty",
        4: "fourty",
        5: "fifty",
        6: "sixty",
        7: "seventy",
        8: "eighty",
        9: "ninety"}

hundred = "hundred"
count = 0

for num in range(1001):

    if len(str(num)) == 4:
        word = "onethousand"

    elif len(str(num)) == 3:
        first = singles[num // 100] + hundred

        if num % 100 == 0:
            first = singles[num // 100] + hundred
            second = ""

        elif num % 100 < 20:
            first += "and"
            second = singles[num % 100]

        elif num % 100 < 100:
            first += "and"
            second = tens[(num % 100) // 10]

        if isinstance(((num % 100) / 10), float) and (num % 100 > 20):
            third = singles[(num % 100) % 10]
        else:
            third = ""

        word = first + second + third

    elif len(str(num)) == 2:
        if num > 19:
            first = tens[num // 10]
            second = singles[num % 10]
            word = first + second
        else:
            word = singles[num]

    elif len(str(num)) == 1:
        word = singles[num]

    print(word)
    count += len(word)

print("The total number of letters in all words from 1 to 1000 is: {}".format(
    count))

print("Time: {}".format(time.time() - start))

2 个答案:

答案 0 :(得分:3)

isinstance(((num % 100) / 10), float)在Python 3上始终为true,在Python 2上始终为false(假设numint)。有关此更改,请参阅PEP 238

答案 1 :(得分:-1)

一些错误。

&#34; 40&#34;不是&#34;四十&#34;

&#34;一千&#34;不是&#34; onethousand&#34;

&#34; 21&#34;不是&#34;二十四&#34;你没有插入连字符的逻辑

&#34;一百&#34;不是&#34;一百个&#34;你的逻辑并没有用空格填充

&#34;一百零一个&#34;不是&#34; onehundredandone&#34;再次,缺少插入空格的逻辑

&#34;二百一十一&#34;不是&#34;两百人&#34;缺少为200-999

插入 的逻辑