Q)write a program to check at which position digits are same and print the position at which they are same.
for example, if n1=1234453 and n2=2444853 print Same at 1's position
Same at 10th position
Same at 1000th position
how to fix this so it works? it display's 3th position instead of 100th?
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")
CodePudding user response:
Use zip
, enumerate
and powers of 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
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.
Some docs:
zip
enumerate
- slice notation: docs, extensive thread here