【问题标题】:python ProjectEuler task 4 Using while looppython ProjectEuler任务4使用while循环
【发布时间】:2017-01-18 18:23:09
【问题描述】:

我想通过使用 python 来解决项目欧拉问题。 但我在执行以下任务时遇到问题:

回文数的两种读法相同。由两个 2 位数字的乘积构成的最大回文数是 9009 = 91 x 99。 找出由两个 3 位数乘积构成的最大回文数。

给定任务的代码:

def palindrome_number():
  n=0 
  lower_range = 100
  upper_range = 999
  while x >= lower_range or x <= upper_range and y >= lower_range or y <= upper_range:
    z = x * y
    while z > n:
      s = str(x * y)
      if s == s[::-1]:
        n = x * y
  print(n)

现在我不知道如何检查从 100 到 999 的所有 x 和 y 数字。 我认为它必须像我的代码一样,但它不起作用

【问题讨论】:

  • x 和 y 初始化为什么?
  • x 必须大于下限且小于上限,我想从 100 迭代到 999
  • 你为什么有一段时间,为什么不只是一个 if,而不是重复计算 x*y 使用 z。你还没有初始化 x 或 y 并且它们没有在哪里增加
  • 作为一个提示,“它不起作用”通常是没有用的。尝试包括具体错误、预期行为与您所看到的等等。
  • 好的,谢谢,我会提醒以后的问题

标签: python


【解决方案1】:

解决方案 1:使用生成器表达式

其实一行就可以解决问题:)

max(x*y for x in range(100, 1000) for y in range(100, 1000) if str(x*y)==str(x*y)[::-1])

解决方案 2:使用 for 循环

for 循环比while 循环更适合这种操作。下面是解决方案(我只用两个for 循环替换了您的while。第一个循环告诉变量x 从100 运行到999,第二个循环告诉y 做同样的事情。使用这两个循环您将尝试xy 的所有组合。)

def palindrome_number():
    n = 0
    lower_range = 100
    upper_range = 999
    for x in range(lower_range, upper_range+1):
        for y in range(lower_range, upper_range+1):
            z = x * y
            if z > n:  # an *if* suffices ;)
              s = str(x * y)
              if s == s[::-1]:
                n = x * y
    print(n)

解决方案 3:使用 while 循环

要使用 while 循环获得相同的结果,您必须注意更改 xy 以获得所有组合:

x = y = lower_range
while x >= lower_range and x <= upper_range:  # (*and* instead of *or*)
    while y >= lower_range and y <= upper_range:  # (again you want the >= *and* the <= to be fulfilled)
        z = x * y
        if z > n:
            s = str(x * y)
            if s == s[::-1]:
                n = x * y
        y += 1  # change y to get all combinations
    y = lower_range
    x += 1  # change x to get all combinations

【讨论】:

  • 感谢您的解决方案-但我不能用while循环来做到这一点吗?我不需要将增量添加到 x 和 y 吗?如果是这样 - 我该怎么做
  • 我用 while 添加了解决方案。注意第一行:如果你想要一个 while 循环,你必须初始化 x 和 y。增加 x 和 y 时也要注意缩进。
  • thx - 我想我已经接近理解 while 和 for 循环了。但是有没有可能使用while循环会花费大量时间来获得解决方案?因为这样做 - 循环继续进行
  • 别担心,它不会花很长时间 ;) while 循环的作用与 for 循环完全相同(只是开发人员需要做更多的事情 (x+=1))。它在 x 和 y 都达到 999 后退出。现在的计算机速度如此之快,它们会在几毫秒内尝试所有 900^2 x-y 组合:)
  • for 循环对我来说工作正常。但是 while 循环要么给我一个 0 作为解决方案(使用 repl.it python 3.0 时),要么只是不停止运行(使用视觉工作室)
猜你喜欢
  • 2016-06-21
  • 2018-09-01
  • 1970-01-01
  • 2014-11-02
  • 1970-01-01
  • 1970-01-01
  • 2014-07-19
  • 1970-01-01
  • 2023-03-10
相关资源
最近更新 更多