問題描述
使用python匹配條件後如何從列表的開始迭代開始for循環 (How to start for‑loop from the starting iteration of list after matching the condition using python)
嘗試完成以下任務:
for element in list:
if condition is true:
remove element from list
start the for loop again with element removed list
為此我嘗試過,
def func(list, p1, p2):
for element in list:
if condition is true:
new_list = remove element from list
func(new_list, p1, p2)
#Here p1, p2 are used in condition.
我收到錯誤,因為超出了最大遞歸深度。
更新完整代碼:
def winner(array, current_player, a, b):
bob = alice = 0
def winner_recursive(array, current_player, a, b):
nonlocal bob, alice
for cn in array:
if cn % current_player == 0:
array.remove(cn)
if current_player == a:
bob += 1
current_player = b
else:
alice += 1
current_player = a
return winner_recursive(array, current_player, a, b)
winner_recursive(array, current_player, a, b)
if bob > alice:
return 'BOB'
elif bob < alice:
return 'ALICE'
else:
if current_player == a:
return 'ALICE'
else:
return 'BOB'
t = int(input())
for _ in range(t):
N, a, b = map(int, input().split())
arr = list(map(int, input().split()))
cp = a
arr.sort(reverse=True)
print(winner(arr, cp, a, b))
輸入上述代碼
2
5 3 2
1 2 3 4 5
5 2 4
1 2 3 4 5
預期輸出:
ALICE
BOB
誰能幫我通過遞歸或最好的pythonic方法來完成這項任務?
注意: 其他類似的 SO 問題,涉及數字範圍。在這裡,我正在嘗試循環使用列表。
參考解法
方法 1:
You should indent the function call, such that it doesn't always get triggered:
def func(list, p1, p2):
for element in list:
if condition:
new_list = remove element from list
func(new_list, p1, p2)
However, you can do without recursion:
while True:
for element in list:
if condition:
list.remove(element)
break
else:
break # we didn't break out of the inner loop, so we're done
方法 2:
The problem is you're having your recursive function winner()
working on two different problems. You need to extract just the recursive part:
def take_turn(array, a, b):
global current_player
for number in array:
if number % current_player == 0:
array.remove(number)
if current_player == a:
current_player = b
else:
current_player = a
take_turn(array, a, b)
break # sub‑optimal play
curent_player = None
t = int(input())
for _ in range(t):
_, b, a = map(int, input().split())
array = list(map(int, input().split()))
current_player = b # Bob plays first
take_turn(array, a, b)
# loser is the player stuck unable to make a move
print('ALICE' if current_player == b else 'BOB')
This doesn't get the correct result, as it doesn't play optimally ‑‑ it simply gets the recursion working. It may also fail if the array gets large enough, depending on how Python's recursion depth limit is set.
(by shaik moeed、L3viathan、cdlane)