簡體   English   中英

前 n 位可被 n 整除的 10 位數字

[英]10 digit number whose first n digits are divisible by n

所以我遇到了這個小問題,我挑戰自己編寫我的第一個程序來解決它。 問題是要找到一個 10 位數字,如果您取前 n 位數字,則結果數字必須能被 n 整除(例如 1236,其中 1 可被 1 整除,12 可被 2 整除,123 可被 3 整除,1236 可被 n 整除) 4)。 我的代碼有點笨拙,我不介意,但我收到了我不理解的錯誤消息。

from itertools import permutations

oddperm = permutations([1,3,7,9])
evenperm = permutations([2,4,6,8])


for odd in oddperm:
    for even in evenperm:
        num1 = (even[0]*(10**7)) + (even[1]*(10**5)) + (even[2]*10**3) + (even[3]*10)
        num2 = (odd[0]*10**8 )+ (odd[1]*10**6) + (5*10**4) + (odd[2]*10**2) + (odd[3])
        num = str((num1+num2)*10)
        if (num[0]*10 + num[1]) % 2 == 0 and #etc etc etc and (num[0]*10**8 + num[1]*10**7 + num[2]*10**6 + num[3]*10**5 + 5*10**4 + num[5]*10**3 + num[6]*10**2 + num[7]*10 + num[8]) % 9 == 0:
            print(num)
            break
    else:
        continue

麻煩在我得到

TypeError                                 Traceback (most recent call last)
<ipython-input-75-cb75172b012c> in <module>
     10         num2 = (odd[0]*10**8 )+ (odd[1]*10**6) + (5*10**4) + (odd[2]*10**2) + (odd[3])
     11         num = str((num1+num2)*10)
---> 12         if (num[0]*10 + num[1]) % 2 == 0 and ... and (num[0]*10**8 + num[1]*10**7 + num[2]*10**6 + num[3]*10**5 + 5*10**4 + num[5]*10**3 + num[6]*10**2 + num[7]*10 + num[8]) % 9 == 0:
     13             print(num)
     14             break

TypeError: not all arguments converted during string formatting

此外,如果有人知道如何使這條線更優雅,我會全力以赴。

在此先感謝您的任何和所有貢獻!

在我看來,您描述的錯誤來自類型轉換。 您正在將num轉換為字符串,然后使用索引來獲取數字的某個數字(這很好),但在您可以對數字進行任何數學運算之前,您需要將其轉換回 int。

# num gets converted to a string
num = str((num1+num2)*10)
# num's digits get converted back into integers
if (int(num[0])*10 + int(num[1])) % 2 == 0:
    print(num)

此外,為了使您對每個數字的檢查更加優雅,您可以使用 for 循環並檢查失敗而不是成功。 這是一個有趣的問題,所以我花了一些時間在上面,哈哈。 可以調用以下 function 代替 long if (int(num[0])*10 + int(num[1])) % 2 == 0 and... etc: ,將其更改為簡單的if check_num(num):

def check_num(num:str):
    # define powers in advance for convenience
    powers = [10**p for p in range(len(num))]
    # check that the number satisfies the desired property
    place = 1
    while place < len(num):
        sum = 0
        # check each digit
        for i in range(place+1):
            sum += int(num[i]) * powers[place - i]
        # check for failure
        if sum % (place+1) != 0:
            return False
        # check the next place
        place += 1
    # we made it all the way through
    return True

希望這是有啟發性的。

暫無
暫無

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

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