检查数字是否在两个不同数字中的相同位置
check if digit is at same position in two different numbers
Q)编写一个程序来检查哪个位置的数字相同,并打印它们相同的位置。
例如,如果 n1=1234453 和 n2=2444853 打印
1的位置相同
同第10位
第1000位相同
如何解决这个问题使其正常工作?它显示第 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")
使用zip
、enumerate
和10
的幂:
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
您的嵌套循环做的工作太多了,为第一个字符中的每个字符循环遍历整个第二个字符串。 zip
效率更高,只需对两个(反向)字符串进行成对(并行)迭代。
部分文档:
Q)编写一个程序来检查哪个位置的数字相同,并打印它们相同的位置。
例如,如果 n1=1234453 和 n2=2444853 打印 1的位置相同
同第10位
第1000位相同
如何解决这个问题使其正常工作?它显示第 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")
使用zip
、enumerate
和10
的幂:
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
您的嵌套循环做的工作太多了,为第一个字符中的每个字符循环遍历整个第二个字符串。 zip
效率更高,只需对两个(反向)字符串进行成对(并行)迭代。
部分文档: