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

2024-05-17 15:33:29 发布

您现在位置:Python中文网/ 问答频道 /正文

所以我遇到了这个小问题,我向自己挑战,要写我的第一个程序来解决它。问题是要找到一个10位数字,如果取前n位,结果数字必须可以被n整除(例如1236,其中1可以被1整除,12可以被2整除,123可以被3整除,1236可以被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

另外,如果有人对如何使这条线更优雅的想法,我洗耳恭听

提前感谢您的所有贡献


Tags: andinforifetc数字numeven
1条回答
网友
1楼 · 发布于 2024-05-17 15:33:29

在我看来,您描述的错误似乎来自类型转换。您正在将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循环检查失败而不是成功。这是一个有趣的问题,所以我花了一点时间在上面,哈哈。可以调用以下函数来代替长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

希望这是有启发性的

相关问题 更多 >