使用python匹配條件後如何從列表的開始迭代開始for循環 (How to start for-loop from the starting iteration of list after matching the condition using python)


問題描述

使用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 moeedL3viathancdlane)

參考文件

  1. How to start for‑loop from the starting iteration of list after matching the condition using python (CC BY‑SA 2.5/3.0/4.0)

#for-loop #Python #python-3.x #algorithm #recursion






相關問題

從R中的類引用列表中獲取類引用字段的最小值 (Get min value of a class reference field from a list of class references in R)

在 SQL Server 2008 中運行 WHILE 或 CURSOR 或兩者 (Running WHILE or CURSOR or both in SQL Server 2008)

danh sách trong python, vòng lặp for, mảng (list in python, loop for, array)

如何編寫一個程序來自動執行一組查詢 (How to write a procedure to execute set of queries automatically)

xPath 在使用 for-each 循環變量時找不到選擇器,但可以正常工作 (xPath not finding selector when using for-each loop variable, but works otherwise)

為什麼for循環重複輸出相同的記錄?JavaScript (Why for loop output same record repeatedly? JavaScript)

在 for 循環中將參數傳遞給 setTimeout (Passing argument to setTimeout in a for loop)

使用python匹配條件後如何從列表的開始迭代開始for循環 (How to start for-loop from the starting iteration of list after matching the condition using python)

BASH:在 for 循環中使用 continue (BASH: Using a continue in a for loop)

如何識別 For / Select / Loop 中的行號 (How do I identify the row number in a For / Select / Loop)

如何循環遍歷列表中的項目不斷附加在循環中的列表? (how to loop through a list where the items of the list are constantly appended in the loop?)

是否可以僅使用 for 循環來實現包含 for 循環的遞歸函數,該循環包含對上述函數的調用? (Can a recursive function containing a for loop that contains a call of the mentioned function be implemented using only for loops?)







留言討論