python中递归函数两个变量_Python-在递归函数中使用共享变量

I'm using a recursive function to sort a list in Python, and I want to keep track of the number of sorts/merges as the function continues. However, when I declare/initialize the variable inside the function, it becomes a local variable inside each successive call of the function. If I declare the variable outside the function, the function thinks it doesn't exist (i.e. has no access to it). How can I share this value across different calls of the function?

I tried to use the "global" variable tag inside and outside the function like this:

global invcount ## I tried here, with and without the global tag

def inv_sort (listIn):

global invcount ## and here, with and without the global tag

if (invcount == undefined): ## can't figure this part out

invcount = 0

#do stuff

But I cannot figure out how to check for the undefined status of the global variable and give it a value on the first recursion call (because on all successive recursions it should have a value and be defined).

My first thought was to return the variable out of each call of the function, but I can't figure out how to pass two objects out of the function, and I already have to pass the list out for the recursion sort to work. My second attempt to resolve this issue involved me adding the variable invcount to the list I'm passing as the last element with an identifier, like "i27". Then I could just check for the presence of the identifier (the letter i in this example) in the last element and if present pop() it off at the beginning of the function call and re-add it during the recursion. In practice this is becoming really convoluted and while it may work eventually, I'm wondering if there is a more practical or easier solution.

Is there a way to share a variable without directly passing/returning it?

解决方案

There's couple of things you can do. Taking your example you should modify it like this:

invcount = 0

def inv_sort (listIn):

global invcount

invcount += 1

# do stuff

But this approach means that you should zero invcount before each call to inv_sort.

So actually its better to return invcount as a part of result. For example using tuples like this:

def inv_sort(listIn):

#somewhere in your code recursive call

recursive_result, recursive_invcount = inv_sort(argument)

# this_call_invcount includes recursive_invcount

return this_call_result, this_call_invcount

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值