【问题标题】:Trying to find LCM(least common multiple) with Python试图用 Python 找到 LCM(最小公倍数)
【发布时间】:2021-01-06 16:28:42
【问题描述】:

我的代码是这样的:

num1 = int(input(": "))
num2 = int(input(": "))
list1 = []
x, z, y = 0, 0, 0
while x < 100:
    z += num1
    y += num2
    list1.append(z)
    list1.append(y)
    x += 1
for i in list1:
    if list1.count(i) > 1:
        print(i)
        break

它工作正常,但我想改变

while x < 100:

因为这是草率的:

num1 = int(input(": "))
num2 = int(input(": "))
list1 = []
x, z, y = 0, 0, 0
for i in list1:
  while list1.count(i) < 2:
    z += num1
    y += num2
    list1.append(z)
    list1.append(y)
    x += 1
else:
    print(i)

NameError: name 'i' is not defined 发生。 我是这里的新成员,刚刚开始学习 Python。 有什么帮助吗?提前致谢!

【问题讨论】:

  • 当前缩进elsefor 循环的一部分,而不是while 循环的一部分。由于 list1 是空变量,因此我永远不会被分配,因此会引发您在尝试打印时看到的错误。

标签: python python-3.x for-loop while-loop lcm


【解决方案1】:

常见错误。你只是没有缩进其他。至少在我运行代码时解决了这个问题。 别的: 打印(一)

【讨论】:

    【解决方案2】:

    “i”未定义错误的原因是您在与 for 循环相同的级别编写了 print(i) 语句。 i 变量只能被 inside for 循环而不是它之外的语句访问。

    您的代码也找不到 LCM,因为您犯了在空列表上调用 for 循环的错误。如果列表为空,for 循环甚至不会运行一次。

    为了简化您的代码,我建议完全取消列表并使用简单的 if-else 语句和 while 循环

    这是我的方法 -

    num1 = int(input(": "))
    num2 = int(input(": "))
    
    greaterNum = None
    LCM = None
    
    if num1 > num2:
        greaterNum = num1
    else:
        greaterNum = num2
    
    while True:
        if((greaterNum%num1 == 0) and (greaterNum%num2 == 0)):
            LCM = greaterNum
            print(LCM)
            break
        else:
            greaterNum += 1
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-03-27
      • 2021-07-16
      • 1970-01-01
      • 1970-01-01
      • 2020-07-11
      • 2020-10-12
      • 1970-01-01
      相关资源
      最近更新 更多