递归方法返回原始值

发布于 2024-10-01 17:57:36 字数 613 浏览 2 评论 0原文

所以我正在尝试自学Python,并且正在做编码难题。我遇到过一个几乎要求排队以赢得比赛的最佳位置的人。主持比赛的人将站在奇数位置的人赶走。

例如,如果 1, 2, 3, 4, 5

它将消除奇数位置,留下 2, 4

将消除剩余的奇数位置,留下 4 作为获胜者。

当我调试代码时,代码似乎正常工作,但它返回 [1,2,3,4,5] 而不是预期的 [4]

这是我的代码:

def findWinner(contestants):
    if (len(contestants) != 1):
        remainingContestants = []
        for i, contestant in enumerate(contestants, 1):
            if (isEven(i)):
                remainingContestants.append(contestant)
        findWinner(remainingContestants)
    return contestants

我没有看到逻辑错误还是还有其他我没有看到的东西?

So I'm trying to learn python on my own, and am doing coding puzzles. I came across one that pretty much ask for the best position to stand in line to win a contest. The person running the contest gets rid of people standing in odd number positions.

So for example if 1, 2, 3, 4, 5

It would get rid of the odd positions leaving 2, 4

Would get rid of the remaining odd positions leaving 4 as the winner.

When I'm debugging the code seems to be working, but it's returning [1,2,3,4,5] instead of the expected [4]

Here is my code:

def findWinner(contestants):
    if (len(contestants) != 1):
        remainingContestants = []
        for i, contestant in enumerate(contestants, 1):
            if (isEven(i)):
                remainingContestants.append(contestant)
        findWinner(remainingContestants)
    return contestants

Am I not seeing a logic error or is there something else that I'm not seeing?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

原野 2024-10-08 17:57:36

您必须将递归函数中的值返回给调用者函数:

return findWinner(remainingContestants)

否则您将仅返回原始值而不进行任何更改。

def findWinner(contestants):
    if (len(contestants) != 1):
        remainingContestants = []
        for i, contestant in enumerate(contestants, 1):
            if (isEven(i)):
                remainingContestants.append(contestant)
        return findWinner(remainingContestants) # here the value must be return
    return contestants # without the return above, it will just return this value(original)

You must return the value from the recurse function to the caller function:

return findWinner(remainingContestants)

else you would return just the original value without any changes.

def findWinner(contestants):
    if (len(contestants) != 1):
        remainingContestants = []
        for i, contestant in enumerate(contestants, 1):
            if (isEven(i)):
                remainingContestants.append(contestant)
        return findWinner(remainingContestants) # here the value must be return
    return contestants # without the return above, it will just return this value(original)
铁憨憨 2024-10-08 17:57:36

这个怎么样:

def findWinner(contestants):
    return [contestants[2**int(math.log(len(contestants),2))-1]]

我知道这不是问题的真正内容,但我必须=P。我不能只是看着所有寻找比参赛者少 2 的最大幂的工作而不指出来。

或者如果您不喜欢“人工”解决方案并希望实际执行该过程:

def findWinner2(c):  
    while len(c) > 1:  
        c = [obj for index, obj in enumerate(c, 1) if index % 2 == 0]  #or c = c[1::2] thanks desfido  
    return c

How about this:

def findWinner(contestants):
    return [contestants[2**int(math.log(len(contestants),2))-1]]

I know its not what the questions really about but I had to =P. I cant just look at all that work for finding the greatest power of 2 less than contestants and not point it out.

or if you don't like the 'artificial' solution and would like to actually perform the process:

def findWinner2(c):  
    while len(c) > 1:  
        c = [obj for index, obj in enumerate(c, 1) if index % 2 == 0]  #or c = c[1::2] thanks desfido  
    return c
神经暖 2024-10-08 17:57:36

你应该使用

return findWinner(remaingContestants)

其他方式,当然,你的列表永远不会更新,所以你的 func 总是会返回包含内容,

但是,请参阅 PEP8 有关 python 代码的样式指南: http://www.python.org/dev/peps/pep-0008/

func isEven 可能有点矫枉过正......

if not num % 2

最后 写一下,不建议在python中使用递归;做一些像

def find_winner(alist):
    while len(alist) > 1:
        to_get_rid = []
        for pos, obj in enumerate(alist, 1):
            if pos % 2:
                to_get_rid.append(obj)
        alist = [x for x in alist if not (x in to_get_rid)]
    return alist

you shold use

return findWinner(remaingContestants)

otherwise, of course, your list will never be updated and so your func is gonna always return containts

however, see the PEP8 for style guide on python code: http://www.python.org/dev/peps/pep-0008/

the func isEven is probably an overkill...just write

if not num % 2

finally, recursion in python isn't recommended; make something like

def find_winner(alist):
    while len(alist) > 1:
        to_get_rid = []
        for pos, obj in enumerate(alist, 1):
            if pos % 2:
                to_get_rid.append(obj)
        alist = [x for x in alist if not (x in to_get_rid)]
    return alist
最佳男配角 2024-10-08 17:57:36

您迭代列表而不是使用切片是否有原因?对我来说不使用它们似乎不太Python-y。

此外,在列表为空的情况下,您可能需要做一些明智的事情。您当前将进入无限循环。

我将你的函数写为

def findWinner(contestants):
    if not contestants:
        raise Exception
    if len(contestants)==1:
        return contestants[0]
    return findWinner(contestants[1::2])

(就像@jon_darkstar的观点一样,这与你明确提出的问题有点相切,但仍然是参与你正在做的事情的一个很好的做法)

Is there a reason you're iterating over the list instead of using a slice? Doesn't seem very python-y to not use them to me.

Additionally, you might want to do something sensible in the case of an empty list. You'll currently go into an infinite loop.

I'd write your function as

def findWinner(contestants):
    if not contestants:
        raise Exception
    if len(contestants)==1:
        return contestants[0]
    return findWinner(contestants[1::2])

(much as @jon_darkstar's point, this is a bit tangential to the question you are explicitly asking, but still a good practice to engage in over what you're doing)

笑看君怀她人 2024-10-08 17:57:36

您在调用“findWinner”的行缺少回车符

You are missing a return at the line where you call "findWinner"

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文