我有以下練習。
相同符號的鄰居 給定一個數字序列,找到并列印第一個具有相同符號的相鄰元素。如果沒有這樣的對,列印 NONE。請注意,輸出必須與示例中指示的相同。
示例 輸入:-1 2 -3 -4 -5 1 2 輸出:-3 -4
這是我的代碼,但是當我嘗試在對符號不同的情況下捕獲案例時它不起作用,有人可以幫忙嗎?代碼作業正常,但是當我添加 ELSE 時,事情就會崩潰。
s = input()
my_list_str = s.split()
my_list = []
for beta in my_list_str:
my_list.append(int(beta))
for i in range(len(my_list)-1):
if my_list[i]>0 and my_list[i 1] >0:
print (my_list[i], end =' ')
print (my_list[i 1])
break
elif my_list[i]<0 and my_list[i 1] <0:
print (my_list[i], end =' ')
print (my_list[i 1])
break
else:
print ('NONE')
uj5u.com熱心網友回復:
只需添加一個找到的標志
s = input()
my_list_str = s.split()
my_list = []
for beta in my_list_str:
my_list.append(int(beta))
found=False
for i in range(len(my_list)-1):
if my_list[i]>0 and my_list[i 1] >0:
print (my_list[i], end =' ')
print (my_list[i 1])
found=True
break
elif my_list[i]<0 and my_list[i 1] <0:
print (my_list[i], end =' ')
print (my_list[i 1])
found=True
break
if not found:
print ('NONE')
你應該檢查一次 else 部分
uj5u.com熱心網友回復:
我建議跟蹤以前和當前數字的符號以及找到的標志。例如像這樣:
list = [-1, 2, -3, 4, -5, 1]
prev_sign = -1
found = 0
for i in range(len(list)):
this_sign = list[i] < 0
if this_sign == prev_sign:
print("{} {}".format(list[i - 1], list[i]))
found = 1
break
prev_sign = this_sign
if not found:
print("NONE")
或者更簡潔,for 回圈可能如下所示:
for i in range(1, len(list)):
if (list[i] < 0) == (list[i - 1] < 0):
print("{} {}".format(list[i - 1], list[i]))
found = 1
break
uj5u.com熱心網友回復:
我在代碼中看到的一個錯誤是在 for 回圈中放置了 else 陳述句。在現有代碼中,如果前兩個元素的符號不匹配,那么它將立即列印“NONE”,因為它到達該 else 陳述句,并將繼續列印“NONE”,直到找到匹配的鄰居。我會按如下方式重寫您的 for 回圈:
found_pair = False
for i in range(len(my_list)-1):
if my_list[i] * my_list[i 1] > 0: # matching sign
found_pair = (my_list[i], my_list[i 1])
break
if found_pair:
print(found_pair[0], found_pair[1])
else:
print('NONE')
在上面的代碼中,結果必須只在完成 for 回圈后列印一次。如果找到一對,則將其存盤并中斷,否則我們將在不分配的情況下耗盡回圈found_pair,導致“NONE”在最后僅列印一次。如果這不起作用或者您有任何問題,請告訴我!
大衛
uj5u.com熱心網友回復:
很多關于found旗幟的建議,但你不需要一個。這就是else一個for回圈進來:
lst = [-1, 2, -3, 4, -5, 1]
# zip lst with a slice of itself to get corresponding
# elements offset by 1 position
for a, b in zip(lst, lst[1:]):
if a * b > 0:
print(f"Found pair {a} {b}")
break
else:
print("NONE")
else 只會在for回圈完成時觸發(不是提前結束break)
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/324842.html
