简体   繁体   English

递归和Python问题

[英]Recursion and Python issue

I have been trying to understand recursion. 我一直试图理解递归。 But I don't think I've quite got a hang of it. 但我不认为我已经掌握了它。

Here the outline for my code: 这是我的代码的大纲:

def f():

    used = [anything]
    new = []

    while i < something:
        new.append(i)
        i += 1

    for i in new:
        if i in used:
            f()
        else:
            return new

Now, I don't think I can use this because I'm not iterating and there is no base case. 现在,我认为我不能使用它,因为我没有迭代,也没有基本情况。 I need to keep running this program till I get a set of values (picked randomly) that are not in used. 我需要继续运行这个程序,直到我得到一组未使用的值(随机选取)。 What would be the best way to achieve that? 实现这一目标的最佳方法是什么? Create another function? 创建另一个功能?

Any help would be greatly appreciated. 任何帮助将不胜感激。

Thanks! 谢谢!

First of all, you need to add parameters, otherwise it's not really recursive. 首先,您需要添加参数,否则它不是真正的递归。 The gist is like this 要点是这样的

f(x):
    x-=1
    if x < 5:
        return x
    else:
        f(x)

The point of recursion is to call the function inside itself with a new parameter. 递归点是使用新参数调用自身内部的函数。 x changes value every time so eventually if will drop below 5 and you'll return x (which will be 4). x每次都会改变值,所以最终如果会降到5以下,你将返回x(将是4)。 So it would be f(7),subtract 1, f(6), subtract 1, f(5), subtract 1, f(4), return 4. 所以它将是f(7),减1,f(6),减1,f(5),减1,f(4),返回4。

You also don't define i or something, so you'll have an infinite loop because i will always be less, in fact, I'm surprised the code works, because neither is ever defined. 你也没有定义i或者什么东西,所以你会有一个无限循环因为我总是会少一些,事实上,我对代码的工作感到惊讶,因为它们都没有被定义过。

You should add parameters of the function, and transfer proper parameter to recursive function calls. 您应该添加函数的参数,并将适当的参数传递给递归函数调用。

For example: 例如:

def f(new, used, i):

I think that a regular while loop will solve this problem more sensibly than a recursive call. 我认为定期的while循环将比递归调用更明智地解决这个问题。 I don't fully understand what you are trying to achieve with this code, but here it is rewritten with your tropes: 我不完全理解你用这段代码想要实现的目标,但是这里用你的比喻重写:

def f(used):

    new = []

    while len(new) == 0 :
        while i < something:
            new.append(i)
            i += 1

        for i in new:
            if i in used:
                new = []
                break

    return new

I think the example you are focusing on is a poor example of recursion. 我认为你关注的例子是递归的一个不好的例子。 It is almost easier to see an iterative solution to your problem. 查看问题的迭代解决方案几乎更容易。 With a perfect example of recursion, it is hard to see any other solution than a recursive solution. 有了一个完美的递归示例,很难看到任何其他解决方案而不是递归解决方案。

One of the classic examples of recursion is navigating a tree oriented data structure. 递归的一个典型例子是导航面向树的数据结构。

Here is a simple example (hardly tested...): 这是一个简单的例子(几乎没有测试......):

#!/usr/bin/python

tree = {'text': '1',
        'brnch': [{
                  'text': '1.1',
                  'brnch': [{
                            'text': '1.1.1',
                            'brnch': [{
                                      'text': '1.1.1.1',
                                      'brnch': []}]},
                           {'text': '1.1.2',
                            'brnch': []},
                           {'text': '1.1.3',
                            'brnch': []}]},
                 {'text': '1.2',
                  'brnch': []}]}

def recurse_traverse(tree):
    print ' ' * recurse_traverse.level + tree['text']
    for branch in tree['brnch']:
        recurse_traverse.level += 1
        recurse_traverse(branch)
        recurse_traverse.level -= 1

if __name__ == '__main__':
    import os
    print "testing", os.path.abspath(__file__)   
    recurse_traverse.level = 1
    recurse_traverse(tree)

The fine online book Think Like a Computer Scientist has more examples of recursion . 精美的在线书籍Think Like a Computer Scientist有更多的递归示例。

If I understand correctly, you're asking for a recursive function to generate a list of pseudo-random values that are not included in another list. 如果我理解正确,你要求一个递归函数来生成一个未包含在另一个列表中的伪随机值列表。 This recursive function will generate a size number of pseudo-random values that do not exist in used . 此递归函数将生成used不存在的size数量的伪随机值。

from sets import Set
import random

used = Set([1,2,3,4,5])

def f(new, size):
  # Check if we have enough 'new' values that are not in the 'used' set
  if len(new.difference(used)) < size:
    new.add(random.randint(0,100)) # Generate a pseudo-random value and
                                   # add it to the 'new' set
                                   # Values are between 0-100 inclusive
                                   # but you can change that to whatever you like
    new = f(new, size) # Append our results to `new`, this will get the result set
  return new.difference(used) # Return only the different 
                              # values between the two sets

result = f(Set(), 10) # Start with a blank set and a request for a result with 10 values
print(result)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM