You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python中如何用两个数字作为字典key存储LCM,要求数字顺序不影响查询

解决方案

你只需要将输入的两个数排序后生成固定顺序的元组作为字典key,即可消除输入顺序的影响:(7,8)和(8,7)排序后均为(7,8),会被判定为同一个key。

具体修改步骤

  • 每次查询、写入字典前,先对a、b做排序生成标准key:key = tuple(sorted((a, b)))
  • 所有用到(a,b)作为字典key的位置,全部替换为这个排序后的key即可

修改后完整代码

a = int(input("Give A: "))
b = int(input("Give B: "))

dic = {}

while a != 0 and b != 0:
    # 生成无顺序影响的标准key
    key = tuple(sorted((a, b)))
    if key in dic:
        print("Found in dictionary!")
        print("LCM for ", a, " and ", b, " is ", dic[key])
        
        a = int(input("Give A: "))
        b = int(input("Give B: "))
    else:
        if a > b:
            greater = a
        else:
            greater = b

        while(True):
            if((greater % a == 0) and (greater % b == 0)):
                lcm = greater
                dic[key] = lcm
                print ("Not found in dictionary!")
                print("LCM for ", a, " and ", b, " is ", dic[key])
                break
            else:           
                greater += 1
                
        a = int(input("Give A: "))
        b = int(input("Give B: "))
        
print ("Terminated + the values added so far were: " , dic)

可选优化

如果需要处理数值较大的场景,可以用最大公约数计算最小公倍数,比循环累加效率高很多,Python 3.5及以上版本内置了math.gcd方法,替换LCM计算逻辑即可:

import math
# 替换原来的while循环计算逻辑
lcm = a * b // math.gcd(a, b)

内容的提问来源于stack exchange,提问作者Janys02

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.27 07:45:03