没有递归,如何实现这个函数?

2024-09-30 22:27:24 发布

您现在位置:Python中文网/ 问答频道 /正文

我想做一个宾果游戏,我有一些挣扎,但最终解决了它。 然而,我的主要“问题”(更像是,我听说它的编程不好)是,我的函数在else语句中调用它内部的函数。我不认为这是你应该怎么做的,但我没有找到任何办法来解决这个问题。。因为这个函数是从另一个名为menu()的函数调用的,所以当我使用循环时,如果为false,它将返回到菜单。你知道吗

这是我的密码:

def selectingNumbers():
    numbers = []
    dupl = []
    j = 0
    print("Now you are gonna select 5 number\n")
    while j < 5:
        nummer = int(input("Your choice:\n"))
        numbers.append(int(nummer))
        j = j+1
    for i in numbers:
        if i not in dupl:
            dupl.append(i) #New list without duplicates
    if dupl == numbers: #Comparing new list with old list
        print("No equal numbers found")
        dragning(numbers)
    else:
        print("Equal numbers found")
        selectingNumbers() #Is there a better way to do it?

我也有一些问题,在开始的时候,我知道我可以使用set()函数,但我想保持原来的列表,并比较新的和旧的一个,我可以做一个更好的方式与“真正的”编程,而不是导入模块?你知道吗

希望你能回答或指导我这两个问题的替代品,如果是这样,说为什么我的代码是“坏”如果是。你知道吗


Tags: 函数inif编程elselistintprint
2条回答

递归并不“坏”。事实上,它有时可以大大简化问题的解决方案。但是对于你的代码来说,这是不必要的。幸运的是,它有时可以被一个循环代替。在您的代码中,它看起来可以循环,直到它从用户那里得到一个不包含任何重复项的列表。这意味着它可以重写如下所示(我还简化了其他一些事情):

def selectingNumbers():
    while True:
        print("Now you are gonna select 5 different numbers\n")
        numbers = []
        for _ in range(5):
            number = int(input("Your choice:\n"))
            numbers.append(number)

        unique = set(numbers)  # will remove any duplicates

        if len(unique) == len(numbers):  # no dups?
            print("No equal numbers found")
            break  #  < - terminates loop
        else:
            print("Equal numbers found")
            # allow loop to continue

    dragning(numbers)

你必须决定是否要用递归来解决这个问题。此行是递归调用:

 selectingNumbers() #Is there a better way to do it?

这是好的,并不意味着糟糕的编程。但是,函数的其余部分并不适合递归函数。你重置了你的变量,因此没有真正的基本情况。参见google,或here以获取示例。你知道吗

递归对于初学者来说很混乱,所以我将采用只迭代的方法。Here is a bingo python example。你知道吗

此外,我不确定这条线是否有效:

if dupl == numbers:  #Comparing new list with old list

我对python不太熟悉,但根据我的经验,数组被视为对象,因此在这一行中,您将要求python比较两个在内存中具有唯一引用的独立对象。所以它们永远不会相等,即使它们内部的值是相同的,因为它们都是分开引用的。I found this link to answer that concern.

相关问题 更多 >