簡體   English   中英

歐拉計划:兩個三位數數字的最大回文產品

[英]Project Euler: Largest palindrome product of two 3-digit number

我得到580085 ,為什么會出錯? 還有另一種方法可以檢查數字是否是回文嗎?

def reverse(str, aux=''):
    count = len(str)
    while count > 0:
        aux += str[count-1]
        count -= 1
    return aux

def palindrome(num):
    j = str(num)
    if j == reverse(j):
        return 1
    else:
        return 0

i = 999
found = 0
while i > 99 and not found:
    j = 999
    while j > 99 and not found:
        if palindrome(i * j):
            found = 1
            print(i * j)
        else:
            j -= 1
    if not found:
        i -= 1

我的帖子主要是代碼,但我無話可說。

新代碼:

def reverse(str, aux=''):
    count = len(str)
    while count > 0:
        aux += str[count-1]
        count -= 1
    return aux

def palindrome(num):
    j = str(num)
    if j == reverse(j):
        return 1
    else:
        return 0

i = 999
max = 0
while i > 99:
    j = 999
    while j > 99:
        num = i * j
        if palindrome(num):
            if num > max:
                max = num
                print(max)
        j -= 1
    i -= 1

花了一些時間研究了這個問題。 我嘗試采用相反的方法(從回文數開始,找到它們的分隔線(如果有))。 Win10上使用Py354

code.py

import time
from math import sqrt


def reverse(str, aux=''):
    count = len(str)
    while count > 0:
        aux += str[count-1]
        count -= 1
    return aux


def palindrome(num):
    j = str(num)
    if j == reverse(j):
        return 1
    else:
        return 0


def question_makhfi_0():
    ret = 0
    i = 999
    found = 0
    while i > 99 and not found:
        j = 999
        while j > 99 and not found:
            if palindrome(i * j):
                found = 1
                ret = i * j
            else:
                j -= 1
        if not found:
            i -= 1
    return ret, i, j


def answer_makhfi_0():
    i = 999
    _max = 0
    while i > 99:
        j = 999
        while j > 99:
            num = i * j
            if palindrome(num):
                if num > _max:
                    _max = num
                    factor0, factor1 = i, j
            j -= 1
        i -= 1
    return _max, factor0, factor1


"""
def answer_makhfi__0_improved_0():
    i = j = 999
    prod = i * j
    step = 0
    while prod > 100000:
        if step % 2:
            i -= 1
        else:
            j -= 1
        prod = i * j
        prod_str = str(prod)
        if prod_str == prod_str[::-1]:
            return prod
        step += 1
"""


def answer_cfati_0():
    pal = 999999
    while pal >= 900009:
        if pal % 10 == 9:
            pal_str = str(pal)
            if pal_str == pal_str[::-1]:
                pal_sqrt = sqrt(pal)
                for factor0 in range(101, int(pal_sqrt) + 1):
                    if pal % factor0 == 0:
                        factor1 = int(pal / factor0)
                        if 100 <= factor1 <= 999:
                            return pal, factor0, factor1
        pal -= 10
    #return pal


def time_func(f, *args):
    t0 = time.time()
    res = f(*args)
    t1 = time.time()
    return t1 - t0, res


if __name__ == "__main__":
    for func in [question_makhfi_0, answer_makhfi_0, answer_cfati_0]:
        print("\nStarting: {}".format(func.__name__))
        #print(func.__name__)
        res = time_func(func)
        print("  Time: {:.6f}\n  Result: {}".format(*res))

注意事項

  • 將您的代碼轉換為函數(進行所有必需的調整,並忽略涉及性能的所有內容)
  • 添加了一個額外的函數來衡量執行時間
  • answer_makhfi_0
    • _max代替max以避免隱藏內置名稱
    • 在末尾添加了return語句(無論如何,效率都很低)
  • answer_cfati_0
    • 該代碼假定有一個回文數在[900009, 999999]范圍內,可以表示為2(3位數)數字乘積。 可以公平地假設(測試對此表示支持)。 但是,如果針對防彈代碼,則此表單將無法執行,我將不得不對其進行一些調整(這將是性能損失的原因)
    • 它使用各種數學/邏輯“捷徑”來避免無用的計算(我認為代碼也可以在該方向上得到改進)。

輸出

 "e\\Work\\Dev\\StackOverflow\\q47999634>"e:\\Work\\Dev\\VEnvs\\py35x64_test\\Scripts\\python.exe" code.py Starting: question_makhfi_0 Time: 0.008551 Result: (580085, 995, 583) Starting: answer_makhfi_0 Time: 1.457818 Result: (906609, 993, 913) Starting: answer_cfati_0 Time: 0.012599 Result: (906609, 913, 993) 

根據輸出, 原始代碼與代碼之間的差異( 一次運行,隨時間變化):

  • 最大的回文數:906609 - 906609
  • 時間來計算的話:1.457818 - 0.012599

@ EDIT0

  • 感謝您的評論,我在代碼中發現了(嚴重)邏輯錯誤(以及一些小錯誤):它返回998899781 * 1279 )。 修復它們后,性能下降了一個數量級,但仍然很快
  • 修改后的函數還返回因子(用於檢查)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM