递归中的全局变量。Python

2024-04-18 09:02:43 发布

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

好的,我使用的是Python2.7.3,下面是我的代码:

def lenRecur(s): 

    count = 0

    def isChar(c):
        c = c.lower()
        ans=''
        for s in c:
            if s in 'abcdefghijklmnopqrstuvwxyz':
                ans += s
        return ans

    def leng(s):
        global count
        if len(s)==0:
            return count
        else:
            count += 1
            return leng(s[1:])

    return leng(isChar(s))

我试图修改leng函数中的变量count。以下是我尝试过的事情:

  1. 如果我将变量count放在lenRecur函数之外,它第一次就可以正常工作,但是如果我在不重新启动python shell的情况下再试一次,那么计数(显然)不会重新启动,所以它会继续添加。
  2. 如果我为count = 1更改count += 1行,它也可以工作,但输出(显然)是1。

所以,我在这里的目标是使用递归来获得字符串的长度,但是我不知道如何跟踪字母的数量。我已经搜索了有关全局变量的信息,但是我仍然被困住了。我不知道我是否还没有理解它,或者我的代码有问题。

提前谢谢!


Tags: 函数代码inforreturnifdefcount
3条回答

您需要使变量计数为函数变量,如

def lenRecur(s):
    lenRecur.count = 0

但是,我发现代码有一些问题。

1)如果您试图通过递归查找字符串中的字母数,则此函数将执行以下操作:

def lenRecur(s):
    def leng(s, count = 0):
            if not s:
                    return count
            else:
                    count += int(s[0].isalpha())
                    return leng(s[1:], count)
    return leng(s)

但是我还是希望有一个单独的函数来完成任务,就像根本就没有leng方法一样。

2)如果你的目标是找到一个字符串中的字母数,我更喜欢列表理解

def alphalen(s):
    return sum([1 for ch in s if ch.isalpha()])

如果这不是学习的目的,我建议你避免递归。因为,该解决方案不能用于较大的字符串(例如,从文件内容中查找字母表计数)。可能会遇到超出最大递归深度的运行时错误。

尽管可以通过setrecursionlimit函数设置递归深度来解决这个问题,但我建议您使用其他简单的方法。有关设置递归限制here的详细信息。

我想你可以把count当作第二个论点

def anything(s):
    def leng(s, count):
        if not s:
            return count
        return leng(s[1:], count + 1)

    return leng(isChar(s), 0)

这应该比从外部作用域禁用对象(例如使用可变对象(listdict)或猴子修补函数本身更好。

count中的lenRecur而不是全局的。它是一个作用域变量。

在这样做之前,您需要使用Python 3;您正在寻找添加到python3的^{} statement

在Python2中,您可以通过为count使用可变(如列表)来解决此限制:

def lenRecur(s): 

    count = [0]

    # ...

    def leng(s):
        if len(s)==0:
            return count[0]
        else:
            count[0] += 1
            return lenIter(s[1:])

现在,您不再改变count名称本身;它保持不变,继续引用同一个列表。您所要做的就是改变count列表中包含的第一个元素

另一种“拼写”方法是将count设为函数属性:

def lenRecur(s): 

    # ...

    def leng(s):
        if len(s)==0:
            return leng.count
        else:
            leng.count += 1
            return lenIter(s[1:])

    leng.count = 0

现在count不再是lenRecur()的本地;它已成为不变的lenRecur()函数的属性。

对于你的具体问题,你实际上是想得太多了。只要递归求和:

def lenRecur(s):
    def characters_only(s):
        return ''.join([c for c in s if c.isalpha()])

    def len_recursive(s):
        if not s:
            return 0
        return 1 + len_recursive(s[1:])

    return len_recursive(characters_only(s))

演示:

>>> def lenRecur(s):
...     def characters_only(s):
...         return ''.join([c for c in s if c.isalpha()])
...     def len_recursive(s):
...         if not s:
...             return 0
...         return 1 + len_recursive(s[1:])
...     return len_recursive(characters_only(s))
... 
>>> lenRecur('The Quick Brown Fox')
16

相关问题 更多 >