递归中的全局变量.Python [英] Global variables in recursion. Python

查看:37
本文介绍了递归中的全局变量.Python的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好的,我使用的是 Python 2.7.3,这是我的代码:

def lenRecur(s):计数 = 0def isChar(c):c = c.lower()答案=''对于 c 中的 s:如果 s 在 'abcdefghijklmnopqrstuvwxyz':答案 += s返回答案定义长度:全局计数如果 len(s)==0:返回计数别的:计数 += 1返回长度(s[1:])返回长度(isChar(s))

我正在尝试修改 leng 函数内的变量 count.以下是我尝试过的事情:

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

所以,我的目标是使用递归获取字符串的长度,但我不知道如何跟踪字母的数量.我已经搜索了有关全局变量的信息,但仍然卡住了.不知道是我还没看懂,还是我的代码有问题.

提前致谢!

解决方案

countlenRecur不是一个全局的.它是一个作用域变量.

您需要先使用 Python 3,然后才能以这种方式工作;您正在寻找添加到的 nonlocal 语句Python 3.

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

def lenRecur(s):计数 = [0]# ...定义长度:如果 len(s)==0:返回计数[0]别的:计数[0] += 1返回 lenIter(s[1:])

现在您不再更改count 名称本身;它保持不变,它一直引用同一个列表.您所做的就是改变 count 列表中的第一个 contained 元素.

另一种拼写"是使 count 成为一个函数属性:

def lenRecur(s):# ...定义长度:如果 len(s)==0:返回长度.计数别的:长度计数 += 1返回 lenIter(s[1:])长度.计数 = 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):如果不是:返回 0返回 1 + len_recursive(s[1:])返回 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):...如果不是:...返回0...返回 1 + len_recursive(s[1:])...返回 len_recursive(characters_only(s))...>>>lenRecur('The Quick Brown Fox')16

OK, i'm using Python 2.7.3 and here is my code:

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))

I'm trying to modify the variable count inside the leng function. Here are the things that I've tried:

  1. If I put the variable count outside the lenRecur function it works fine the first time, but if I try again without restarting python shell, the count (obviously) doesn't restart, so it keeps adding.
  2. If I change the count += 1 line for count = 1 it also works, but the output is (obviously) one.

So, my goal here is to get the length of the string using recursion, but I don't know how to keep track of the number of letters. I've searched for information about global variables, but I am still stuck. I don't know if i haven't understood it yet, or if I have a problem in my code.

Thanks in advance!

解决方案

count in lenRecur is not a global. It is a scoped variable.

You'll need to use Python 3 before you can make that work in this way; you are looking for the nonlocal statement added to Python 3.

In Python 2, you can work around this limitation by using a mutable (such as a list) for count instead:

def lenRecur(s): 

    count = [0]

    # ...

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

Now you are no longer altering the count name itself; it remains unchanged, it keeps referring to the same list. All you are doing is altering the first element contained in the count list.

An alternative 'spelling' would be to make count a function attribute:

def lenRecur(s): 

    # ...

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

    leng.count = 0

Now count is no longer local to lenRecur(); it has become an attribute on the unchanging lenRecur() function instead.

For your specific problem, you are actually overthinking things. Just have the recursion do the summing:

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))

Demo:

>>> 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

这篇关于递归中的全局变量.Python的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆