【问题标题】:Why arr is undefined in this case?为什么在这种情况下 arr 未定义?
【发布时间】:2019-07-19 23:28:16
【问题描述】:

为什么在这种情况下我不能将数组长度设置为默认参数?

def q_helper(arr, start=0, end=len(arr)-1):
    pivot = arr[start]
    swapIdx = start
    for i in range(len(arr)):
        if pivot > arr[i]:
            swapIdx += 1
            swap(arr, swapIdx, i)
        swap(arr, start, swapIdx)
    return swapIdx

【问题讨论】:

标签: python-3.x algorithm sorting


【解决方案1】:

简短的回答是:您不能根据先前的参数设置默认参数,因为 python 需要在定义函数时(而不是在调用它时)知道值。

更长的答案可能是:如果您正在寻找一种有点 Pythonic 的方式来做您想做的事情,我建议将默认值设置为 None,然后将变量设置为您想要的任何值(如果它恰好是) None。像这样的:

def q_helper(arr, start=0, end=None):
    if end is None:
        end = len(arr) - 1  # if not set, set it to one less than the array's length

【讨论】:

    猜你喜欢
    • 2020-05-16
    • 1970-01-01
    • 2018-06-18
    • 1970-01-01
    • 2016-01-18
    • 1970-01-01
    • 1970-01-01
    • 2013-04-23
    • 2014-05-05
    相关资源
    最近更新 更多