python - 欧拉计划 #17 的意外结果(Python 3 与 Python 2.7)

标签 python python-2.7 python-3.x

所以我正在研究欧拉项目#17,试图找到答案,而不是真正的目标是提高效率。然而,在阅读了打印的每个数字(我认为)之后,我找不到导致答案比正确答案精确 100 个字符的原因。所以我决定来一探究竟,当我偶然使用 Python 2.7 在线编译它时,我得到了完全不同的结果!我不知道为什么在 Python 2.7 中编译它会导致一个明显错误的答案,而在 Python 3 中它几乎没有关闭。无论如何,这是我在网上编译的两个地方:

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

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

最佳答案

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

关于python - 欧拉计划 #17 的意外结果(Python 3 与 Python 2.7),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25636099/

相关文章:

python - Pytest中如何控制增量测试用例

python - 在 PyQt 中将变量从一个类传递到另一个类

python - 在带有参数的列表中插入函数并使用它们

python - 在 Python 3.3 中格式化时间字符串

使用 fcgiwrap 的 nginx 上的 Python - 在从上游读取响应 header 时上游过早关闭 FastCGI stdout

python - Django user_passes_test 用法

javascript - Odoo 10 添加按钮到 POS

python-3.x - 如何避免 "ValueError: Separator is not found, and chunk exceed the limit"

Python绘制流程图、插图图

Python 从一个类继承但覆盖调用另一个类的方法?