【发布时间】:2026-01-08 17:25:06
【问题描述】:
我环顾四周,令人惊讶的是没有找到这个问题的答案。我认为这是因为通常内部/嵌套函数用于特定的东西(例如维护环境变量,工厂),而不是像我试图使用它们那样微不足道的东西。无论如何,我似乎找不到任何关于如何从外部函数正确调用内部函数的信息,而不必在文件中声明 inner() 以上outer()。问题出在 HackerRank (https://www.hackerrank.com/challenges/circular-array-rotation/problem) 上的这个问题。
def circularArrayRotation(a, k, queries):
def rotateArrayRightCircular(arr: list, iterations: int) -> list:
"""
Perform a 'right circular rotation' on an array for number of iterations.
Note: function actually moves last 'iterations' elements of array to front of array.
>>>rotateArrayRightCircular([0,1,2], 1)
[2,0,1]
>>>rotateArrayRightCircular([0,1,2,3,4,5], 3)
[3,4,5,0,1,2]
>>>rotateArrayRightCircular([0,1,2,3,4,5], 6)
[0,1,2,3,4,5]
"""
return arr[-1 * iterations:] + arr[0:-1 * iterations]
k = k % len(a)
a = rotateArrayRightCircular(a, k)
res = []
for n in queries:
res.append(a[n])
return res
上面的代码完成了我想要的,但是我必须将内部函数调用放在内部函数定义之后,这对我来说有点不雅。不同尝试的各种错误:
# trying 'self.inner()'
Traceback (most recent call last):
File "solution.py", line 52, in <module>
result = circularArrayRotation(a, k, queries)
File "solution.py", line 13, in circularArrayRotation
a = self.rotateArrayRightCircular(a, k)
NameError: name 'self' is not defined
# Removing 'self' and leaving the definition of inner() after the call to inner()
Traceback (most recent call last):
File "solution.py", line 52, in <module>
result = circularArrayRotation(a, k, queries)
File "solution.py", line 13, in circularArrayRotation
a = rotateArrayRightCircular(a, k)
UnboundLocalError: local variable 'rotateArrayRightCircular' referenced before assignment
知道如何在调用inner() 之后包含def inner()而不抛出错误吗?
【问题讨论】:
-
你总是必须定义函数(和其他变量)在你使用它们...
-
为什么是你的
rotateArrayRightCircular函数被定义在circularArrayRotation里面?为什么不直接在circularArrayRotation之外定义它,然后如果您的目标是这样,那么您可以在之后拥有它。
标签: python function-call nested-function