繁体   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