【问题标题】:Recursively implement the function halves that takes two positive integers a and b, and returns a list containing the value a递归实现接受两个正整数 a 和 b 的函数的一半,并返回一个包含值 a 的列表
【发布时间】:2022-11-14 22:41:16
【问题描述】:

递归实现函数 halves,它接受两个正整数 a 和 b,并返回一个列表,其中包含值 a(转换为浮点类型)和 a 的所有大于 b 的连续一半。 我试过这样,但它返回一个空列表,我不明白发生了什么:

def metades(a, b):
    if a < b: return []
    if a > b:

        lst = []
        a = float(a/2) 
        lst.append(a)

        return lst and metades(a,b)

print(metades(100,3))

应该返回:

[100.0、50.0、25.0、12.5、6.25、3.125]

返回:

[]

【问题讨论】:

标签: python arrays math


【解决方案1】:

要处理递归函数中的列表,您必须将其放入函数的参数中:

def metades(a, b, res = None):

    res = res or []

    if a <= b: return res
    if a > b:
        res.append(a)  # put first append and then division to retrieve also first value of 'a'
        a = float(a / 2)

        return metades(a, b, res)

print(metades(100,2))

输出将是:

[100, 50.0, 25.0, 12.5, 6.25, 3.125]

【讨论】:

  • a / 2 已经是float,无需显式转换。也可以直接传给metades(a / 2, b, res)
  • 此外,这里还有 Mutable Default Arguments 问题。尝试第二次调用函数
  • 好的不错,但是现在又出现了另一个问题,当输入是: print(metades(32,2) 应该返回:[32.0, 16.0, 8.0, 4.0] 返回:[32, 16.0, 8.0, 4.0, 2.0]
  • @Yevhen Kuzmovych 非常感谢!正如现在编写的代码,如果我们不强制转换为浮点数,第一个元素将是一个 int。除此之外,通过在递归函数中添加一个额外的“if to is None:”,我们不是延长了执行时间(尽管只是稍微延长了一点)吗?
  • 你不应该在函数定义中将空列表作为默认参数传递
【解决方案2】:
# your code goes here
def metades(a, b):
        result = []
        if a >= b:
            result.append(float(a))
            result.extend(metades(a/2, b))
        return result
    
print(metades(100,3))




print(metades(100,3))

输出

[100, 50.0, 25.0, 12.5, 6.25, 3.125]

【讨论】:

  • a / 2 已经是float,无需显式转换。
  • 好的不错,但是现在又出现了另一个问题,当输入是: print(metades(32,2) 应该返回:[32.0, 16.0, 8.0, 4.0] 返回:[32, 16.0, 8.0, 4.0, 2.0]
  • @Tumes 更新了解决方案
  • 谢谢!!! @sahasrara62
猜你喜欢
  • 2020-08-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-04-21
  • 2013-05-29
  • 2016-06-21
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多