简体   繁体   English

检查数字是否在两个不同数字的相同位置

[英]check if digit is at same position in two different numbers

Q)write a program to check at which position digits are same and print the position at which they are same. Q) 编写一个程序来检查数字在哪些位置相同并打印它们相同的位置。

for example, if n1=1234453 and n2=2444853 print Same at 1's position例如,如果 n1=1234453 和 n2=2444853 在 1 的位置打印相同

Same at 10th position与第 10 位相同

Same at 1000th position在第 1000 个位置相同

how to fix this so it works?如何解决这个问题,使其有效? it display's 3th position instead of 100th?它显示的是第 3 个位置而不是第 100 个位置?

n1=int(input())
n2=int(input())
ns1=str(n1)
ns2=str(n2)
l1=len(ns1)
for x in ns1:
    for y in ns2:
        if x==y:
            if int(ns1.index(x))==int(ns2.index(y)):
                print("Same at %dth position"%(ns1.index(x))
            else:
                print("No digits are same")
        else:
            print("No digits are same")

Use zip , enumerate and powers of 10 :使用zipenumerate10幂:

ns1 = "1234453"
ns2 = "2444853"

found = False
for i, (x, y) in enumerate(zip(ns1[::-1], ns2[::-1])):
    if x == y:
         found = True
         print(f"Same at {10**i}th position")
    # no else here!! just because of a mismatch at the first digit
    # does not mean there aren't any matches later
if not found:
    print("No digits are same")

# Same at 1th position
# Same at 10th position
# Same at 1000th position

Your nested loops are doing way too much work, looping through the entire second string for each char in the first.您的嵌套循环做了太多工作,为第一个字符中的每个字符循环遍历整个第二个字符串。 zip is much more efficient, just doing a pair-wise (parallel) iteration of both (reversed) strings. zip效率更高,只需对两个(反向)字符串进行成对(并行)迭代。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM