如何实现一种高效的 Python 算法来查找匹配的数字? [英] How to implement an efficient Python algorithm for finding matching digits?

查看:20
本文介绍了如何实现一种高效的 Python 算法来查找匹配的数字?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有 2 个相同数字的数字 A 和 B(都具有不同的数字),我需要找到 X(A 和 B 中的数字数量,并且在相同的位置)和 Y(数字的数量)A 和 B 中的数字,但位置不同).例如,如果 A = 4567 和 B = 4567,X 将是 4,Y 将是 0.如果 A = 3456 和 B = 4567,X 将是 0,Y 将是 3.不考虑效率,我的代码是如下:

Let's say I have 2 same-digit numbers A and B (both with distinct digits), I need to find X (number of digits in both A and B, and also in the same position), and Y (number of digits in both A and B, but are not in the same position). For example, if A = 4567 and B = 4567, X would be 4, Y would be 0. If A = 3456 and B = 4567, X would be 0 and Y would be 3. Without considering the efficiency, my code is as follows:

def compare(num1, num2):
  x = 0
  y = 0
  for i in range(4):
     if str(num1)[i] in str(num2) and str(num1)[i] == str(num2)[i]:
        x += 1
     elif str(num1)[i] in str(num2):
        y += 1
  return ('X = %d, Y = %d'%(x,y))

但是,我认为这不是解决此问题的最有效方法.谁能提供更有效的解决方案?谢谢...

However, I don't think this is the most efficient way of solving this problem. Could anyone offer a more efficient solution? Thanks...

推荐答案

使用 dict 减少比较次数.

Using a dict reduces number of comparisons.

str(num1)[i] in str(num2): 再次扫描整个字符串.你可以避免这种情况.

str(num1)[i] in str(num2): scans the entire string again. You could avoid this.

def compare(num1, num2):
    x = 0
    y = 0
    result = {}

    num1 = str(num1)
    num2 = str(num2)

    for i in range(0,len(num1)):
        result[num1[i]] = i

    for i in range(0,len(num2)):
        if num2[i] in result:
            if result[num2[i]] == i:
                x +=1;
            else:
                y +=1;

    return ('X = %d, Y = %d'%(x,y))


print(compare(4567,4567))
print(compare(3456,4567))

这篇关于如何实现一种高效的 Python 算法来查找匹配的数字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆