python - 在调用高阶函数时存储变量
问题描述
如果我想用一个参数调用一个函数,而不使用任何花哨的东西,比如声明非局部变量或创建一个列表,我如何在每次调用我的函数时存储我的参数,以便它“记住”我以前调用过的先前参数? 我的想法如下:
# stac(x) is a function that returns another function (nested) or itself.
>>> stac(4)(5)(6)(4)(6)(7)(8)(3)(0)
# if 0, prints the previous numbers that was called most recently to first call
3
8
7
.
.
4
我想到的类似的事情是检测 stac(x) 中是否有重复的参数,这样每次如果 x 匹配前面的参数之一,它就会打印出 x。
# stac(x) is a function that returns another function (nested) or itself.
>>> stac(1)(2)(3)(4)(1)(3)(5)(7)
1
3
# since 1 and 3 is repeated
我对如何处理这个想法的想法是,我们返回一个在当前帧中定义的函数,这样,如果我们在新帧中的参数满足某个条件(或不满足),它会在我们第一次调用争论。虽然我不确定这是否有效。如果有人知道如何实现它,我将不胜感激!
解决方案
您需要可以访问您返回的每个对象的名称空间的东西,否则您将无法打印所有先前的参数。所以,是的,您可能需要一个列表或双端队列或其他一些可变容器。但是您可以将其设置为第一个函数调用的本地:
def stac1(n):
s = []
def k(n):
if n == 0:
print(*s, sep='\n')
return s
s.append(n)
return k
return k(n)
您的第二个示例可以以类似的方式实现,但使用集合而不是序列:
def stac2(n):
s = set()
def k(n):
if n in s:
print(n)
else:
s.add(n)
return k
return k(n)
虽然这在技术上使用共享容器,但每次调用都会stac
实例化自己的容器,因此没有全局共享状态。同时,如果拆分,这两个函数都不会正常运行:
>>> a = stac1(1)(2)
>>> a(3)(0)
1
2
3
[1, 2, 3]
>>> a(0)
1
2
3
[1, 2, 3]
# desired [1, 2]
>>> b = stac2(1)(2)
>>> b(5)(1)
1
>>> b(5)
5
# desired nothing
一种天真的方法是传递一个不可变的序列/冻结集,或至少一个副本,例如,作为k
. 不过,这相当缓慢和浪费,至少对于stac1
. 您可以改用链表,因此拆分后的每个分支都有自己的序列,而不必复制父级:
from functools import partial
def stac1b(n):
def k(p, n):
if n:
return partial(k, [n, p])
s = []
while p:
n, p = p
s.append(n)
s.reverse()
print(*s, sep='\n')
return s
return k(None, n)
stac2
处理起来有点困难。一方面,像所示的那样的链表方法stac1b
是可能的。缺点是必须对每个添加的元素执行完整的线性搜索。另一方面,传递集合的副本似乎很浪费,但会使查找速度更快。由于重复元素不需要副本,我将展示后一个选项:
def stac2b(n):
def k(s, n):
if n in s:
print(n)
return partial(k, s)
return partial(k, s | {n})
return k(set(), n)
推荐阅读
- angular - 如何使我的角度应用程序行为异步
- javascript - 在 React 中将图片从一个组件传递到另一个组件
- javascript - 如何根据卡片的选择将详细信息推送和弹出到javascript中的数组中?
- javascript - 根据从表单中选择的值在屏幕上显示数据
- android - Android:更改样式禁用按钮的文本颜色
- python - 在 Python 中对一系列数据进行分类的最佳方法
- json - 在颤动的下拉按钮上显示选定的数据
- html - 如何使背景图像和背景图像中的元素响应?
- python-3.x - 将单列内容分成多列?
- javascript - data-id 单击时向下滚动到项目