Python嵌套循环没有输出

2024-04-23 14:11:56 发布

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

我刚开始学python。我试图检查整数x是否是回文的,然后将它除以一个介于范围(从最大的y开始,即999)y=999998,…,100之间的数字。如果x/y=z,z也是一个3位整数,则结束。否则从x中减去1,并执行相同的步骤。你知道吗

def EuQ4():
    x=998001
    p=999
    while 10000 < x:
        x=x-1
        if str(x)== str(x)[::-1]:
            while p>100:
                if x%p==0:
                    Pal=x/p
                    if Pal < 999:
                        print (Pal,p)
                        break
                    else:
                        x=x-1
                else:
                    p=p-1
        else:
            x=x-1
EuQ4()

这是Euler项目的第4个问题,即找出由两个3位数的乘积构成的最大回文。你知道吗


Tags: 项目ifdef步骤数字整数elseprint
3条回答

p=999放在while p > 100之前或使用for p in range(999, 100, -1)。你知道吗

p = 999
while p > 100

我觉得你打电话x=x-1太多次了。你知道吗

很抱歉,读你的问题伤了我的头。如果您试图在尝试这些问题的同时学习Python,那么我将提出这个替代答案—它不会回答您的问题,但它确实会带来解决方案,而且我认为它更像Python。这个问题要求找出由两个3位数的乘积构成的最大回文。所以输入应该是3位数。此代码将允许您指定位数max和min(作为整数)。你知道吗

我并不是建议这是Euler问题提出的最佳解决方案,而是让您了解Python的一系列特性的解决方案。你知道吗

def min_value(integer):
    min_val = '1'
    for n in range(0,integer-1):
       min_val+='0'
    return int(min_val)

def max_value(integer):
    max_val = '9'
    for n in range(0,integer-1):
       max_val += '9'
   return int(max_val) +1

def find_max_palindrones(x,y):
    minimum_value = min_value(x)
    maximum_value = max_value(y)
    palindrones = []
    working_range = [number for number in range(minimum_value,maximum_value,1)]
    for x_value in working_range:
        for y_value in working_range:
            product = x_value * y_value
            orig_order = [item for item in str(product)]
            rev_order = [item for item in str(product)[::-1]]
            if orig_order == rev_order:
                palindrones.append(product)
    max_p = max(palindrones)
    return max_p

>>>find_max_palindrones(3,3)
906609

这里有一些逻辑错误。有些原因导致循环永远不会结束。例如,当x % p == 0Pal较大999时会发生什么?你会得到一个无限循环。你知道吗

我做了一些修改,但它仍然需要一些工作。你知道吗

def EuQ4():
    x = 998001
    while 10000 < x:
        if str(x) == str(x)[::-1]:
            print("{} is a pali!".format(x))
            # Move it here so each time it stats at the right
            # number or else it will just skip it after it does it once.
            p = 999
            while p > 100:
                if x % p == 0:
                    pali = int(x / p)
                    if pali < 999:
                        print(pali, p)
                        return
                p -= 1
        x -= 1

EuQ4()

编辑:

我通过在IDE中使用调试器发现了这些错误。通过逐行检查代码几次,您可以轻松地完成相同的操作。你知道吗

相关问题 更多 >