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