有没有什么方法可以减少这个cod的时间和代码

2024-03-29 09:57:46 发布

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

我写了一个运行时间为O(n^2)的程序,有没有可能在不使用嵌套的forloops和内置函数的情况下降低代码和复杂度,这是一个匹配的整数问题,输出是[4,5]


a = 12345
b = 49085
l1 = []
l2 = []
l_match = []
while(a != 0):
    c = a % 10
    l1.append(c)
    a //= 10
while(b!= 0):
    d = b % 10
    l2.append(d)
    b //= 10
for i in range(len(l1)):
    for j in range(len(l2)):
        if l1[i] == l2[j]:
            match = l1[i]
            l_match.append(match)
print(l_match)


Tags: 函数in程序l1forlenmatch时间
3条回答

时间复杂度

def find_chars_order_n(value1,value2):
  hsh = {}
  resp = set()     #Set is used to have unique Characters
  if str(value1) and str(value2):
    str1 = list(str(value1))
    str2 = list(str(value2))
  for elm in str2:
    hsh[elm] = elm
  for elm in str1:
    if hsh[elm]:
      resp.add(elm)
  # resp = str1 & str2 #using set intersection
  if resp:
    return list(resp))
  else:
    return None

if __name__ == "__main__":
  print(find_chars_order_n(1400,4011))

如果我理解正确,如果我错了就纠正我,目标是找到两个数字之间的共同数字。你知道吗

如果是这样的话,一种更简单的匹配普通整数的方法是通过一个集合从两个数字中得到唯一的数字,然后计算它们之间的交集

a = 12345
b = 49085

#Convert both numbers into a set to get unique digits
set_a = set(str(a))
set_b = set(str(b))

#Get common digits between both numbers
common = [int(a) for a in set_a.intersection(set_b)]

print(common)

输出将是

[5, 4]

您可以将每个数字转换为一组数字字符,以便使用集合交集以线性时间复杂度获得两个数字之间的公共数字:

list(map(int, set(str(b)).intersection(set(str(a)))))

这将返回:

[4, 5]

相关问题 更多 >