您好,我正在為學校解決這個問題而苦苦掙扎,無法讓我的代碼完成解決此問題所需的作業。
問題是:如果在其右側的每個元素(不僅僅是緊鄰其右側的一個元素)都嚴格小于該元素,則將專案串列中的一個元素定義為支配者。它要我計算串列中有多少分母。
def extract_increasing(digits):
countDem = 0
#check and see if there is anything in the list
if not digits:
return 0
#compare the first element to the one on the right of it
for x in range(len(digits)):
for y in range(x 1, len(digits)):
if digits[x] > digits[y]:
countDem = 1
return countDem
uj5u.com熱心網友回復:
下面的代碼應該檢查串列中的數字是否是支配者。
def is_dominator(lst, idx):
for i in range(idx 1, len(lst)):
if lst[i] >= lst[idx]:
return False
return True
digits = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
for i in digits:
print(is_dominator(digits, i))
uj5u.com熱心網友回復:
您的代碼中的錯誤是,每次下一個值滿足條件時,您都會為計數器添加一個。
for x in range(len(digits)):
for y in range(x 1, len(digits)):
if digits[x] > digits[y]:
countDem = 1
每次遇到 digits[x] > digits[y] 時,您都會在計數器上加一。只有在檢查了右側的所有值都滿足條件后,才應該添加一個。
isDem = False
for x in range(len(digits)):
for y in range(x 1, len(digits)):
if digits[x] > digits[y]:
isDem = True
else:
isDem = False
#Once you went through all the values to the right you can add one to the counter
if isDem ==True:
countDem = 1
希望有幫助!
uj5u.com熱心網友回復:
您從最后一個元素開始,并在每次迭代中始終保存 max_element,然后您總是知道是否存在比當前數字更大的數字。這更有效一些,因為它只在陣列中運行一次。
def dominator(li: list):
sol = 0
max_number = -math.inf
for i in range(len(li)-1, -1,-1):
if li[i] > max_number:
sol =1
max_number = li[i]
return sol
uj5u.com熱心網友回復:
嘗試串列理解
lst = [0, 10, 2, 6, 7]
new_lst = [v for k,v in enumerate(lst) if all(v > x for x in lst[k 1:])]
# [10, 7]
更新
def extract_increasing(digits: list) -> int:
countDem = 0
for x, y in enumerate(digits):
if all(y > a for a in digits[x 1:]):
countDem = 1
return countDem
lst = [0, 10, 2, 6, 7]
extract_increasing(lst) # -> 2
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/516927.html
標籤:Python循环迭代器
