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")
uj5u.com熱心網友回復:
使用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效率更高,只需對兩個(反向)字串進行成對(并行)迭代。
一些檔案:
zipenumerate- 切片符號:docs,這里有廣泛的執行緒
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/325783.html
標籤:Python for循环 if 语句 条件语句 嵌套循环
下一篇:如何僅獲取整數或浮點數輸入
