python - 比较并计算两个数字之间相同的数字

标签 python

我正在编写一个接收两个四位数字(mn)的函数,用于计算 m 之间有多少位相同n,包括左侧的重复项和零。问题是,我的教授只教我们如何使用循环,不希望我们使用列表和交集,而我却做不到。

例如,如果m = 331n = 3,则应返回2作为相等位数,如果n = 33,它应该返回 3 个相同的数字。

>>> compare_digits(331, 3)
2
>>> compare_digits(332, 33)
3

编辑:这是我之前创建的代码,它对相同数字的计数超出了应有的范围,但中心思想是使用 % 和//来读取每个数字,但它不起作用......

def compare_digits(m, n):
read_ndigits = 0
same_digits = 0
while read_ndigits < 4:  #number of digits
    current_n = n % 10
    read_mdigits = 0
    while read_mdigits < 4:
        current_m = m % 10
        if current_n == current_m:
            same_digits += 1
        m //= 10
        read_mdigits += 1
    n //= 10
    read_ndigits += 1

return same_digits

输出非常困惑,我什至无法识别任何模式。

最佳答案

您可以使用collections.Counter()与设置交集:

from collections import Counter

def compare_digits(m, n):
    m_counts = Counter(str(m).zfill(4))
    n_counts = Counter(str(n).zfill(4))

    return sum(min(m_counts[k], n_counts[k]) for k in m_counts.keys() & n_counts.keys())

print(compare_digits(331, 3))  # 2
print(compare_digits(332, 33)) # 3
print(compare_digits(3, 331))  # 2

关于python - 比较并计算两个数字之间相同的数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55436600/

相关文章:

python - 更改 taiga-back 默认端口 (8000)

python - 了解 numpy 内存映射的性能

PyCharm 中的 Python3 语法

python - 收到错误并没有返回 HttpResponse 对象。到底是怎么回事?

python - "lxml.etree.XPathEvalError: Invalid expression"带有 Unicode 元素名称

python - 无法重启 buildbot master

python - numpy.savetxt 的分隔符

python - SqlAlchemy 加入没有外键的表

python - 无法将 16 位数字转换为人类可读的日期

python - 规范化单行多列?