使用递归遍历列表

时间:2021-07-29 19:58:10

标签: python list recursion

所以我是递归的新手,我正在尝试制作一个程序,您可以在其中输入一个列表,然后 python 测试每个整数(例如 9)并查看它后面的整数是否加倍。因此,如果我输入 2 4 8 16 32 的列表,将返回 4,而 -5 -10 0 6 12 9 36 将返回 2,因为 -5 后跟 -10 是一,而 6 后跟 12 是第二。这是我到目前为止的代码。我觉得我很亲近。但只有几件事阻碍了我。任何帮助都会很棒!

L = []
def countDouble(L):
    x = input(f'Enter a list of numbers separated by a space: ')
    y = (x.split(' '))
    print(y[1])
    print(y[0])
    count = 0
    
    y[0] += y[0]
    
# unsure of how to multiple y[0] by 2
    if y[0]*2 == y[1]:
        count += 1
    else:
        count += 0
        
#how would I traverse through the rest of the entered list using recursion?
        
    print(count)
    
countDouble(L)
  

5 个答案:

答案 0 :(得分:1)

如果您想/需要使用递归来解决它,以下方法可以解决问题:

def count_sequential_doubles(li, count=0):
    return count_sequential_doubles(li[1:], count + int(li[0] * 2 == li[1])) if len(li) > 1 else count

答案 1 :(得分:0)

最终编辑:OP 编辑​​了他的示例,因此我的其他代码不适用

人们提出了一些很好的问题,但本着提供帮助的精神,这里有一个递归函数,它返回所有双精度数的计数。

def get_doubles_count_with_recursion(a_list, count, previous=None):
    while a_list:
        try:
            first = previous if previous else a_list.pop(0)
            next_item = a_list.pop(0)
        except IndexError:
            return count
        if next_item / 2 == first:
            count += 1
        return get_doubles_count_with_recursion(a_list, count, next_item)
    return count

a_list = [1, 3, 5, 10, 11, 14, 28, 56, 88, 116, 232, 464, 500]
doubles = get_doubles_count_with_recursion(a_list, 0)
print(doubles == 5)

可能可以稍微清理一下,但它比其他人的更容易阅读;)

答案 2 :(得分:0)

我建议采用这种递归方式:

def countDouble(L):
    count = 0
    if len(L) == 1:
        return count
    else:
        if int(L[0])*2 == int(L[1]):
            count += 1
        return count + countDouble(L[1:])

x = input(f'Enter a list of numbers separated by a space: ')
y = (x.split(' '))

count = countDouble(y)
print(count)

答案 3 :(得分:0)

我强烈建议您阅读整个答案,但如果您对提示、注释和寻找解决方案的过程不感兴趣,这里有两个解决方案:

使用递归的解决方案(不推荐):

x = input()
y = x.split(' ')
count = 0
def countDouble(i):
    if(i+1 == len(y)):
        return 'recursion ends here when'
    if(int(y[i])*2==int(y[i+1])):
        count += 1
    countDouble(i+1)
countDouble(0)
print(count)

这个解决方案只是模仿了一个while循环:

使用 while 循环的解决方案(推荐):

x = input()
y = x.split(' ')
count = 0
i = 0
while(i < len(y) - 1):
    if(int(y[i]) * 2 == int(y[i+1])):
        count += 1
    i += 1
print(count)

在我继续之前,这里有一些提示和注意事项:(其中一些只有在之后才有意义)

  • 我假设您示例中的 14 是一个错字
  • 我没有将代码放入函数中,因为它不需要,但您可以轻松更改。
  • 在您的代码中,您将 L 作为参数传递给 countDouble() 函数,但您并未使用它。如果您不需要参数,请不要传递它。
  • 分割输入时,列表的值仍然是字符串。所以你必须在比较它们的值之前将它们转化为整数(例如,你可以用 int() 'function' 做到这一点) - 否则乘以 2 只会重复字符串。例如:'13'*2 是字符串 '1313'
  • 我不知道您为什么在第 9 行将 y[0] 添加到自身,但是根据此之后的代码会产生不正确的结果,您无需更改元素即可获得它们的值乘以 2。
  • 请注意,在 else 块中,没有任何变化。将 0 添加到计数不会改变它。所以你可以完全删除 else 块

虽然可以在递归中解决问题,但还有一些其他东西可以解决此类问题:循环。 问题本质上是对列表的每个元素重复简单的检查。

这就是我找到解决方案的方式

所以我们要运行以下“代码”:

if(y[0]*2 == y[1]):
    count += 1
if(y[1]*2 == y[2]):
    count += 1
if(y[2]*2 == y[3]):
    count += 1
...

当然计算机不理解“...”是什么意思,但它让我们对代码中的模式有了一个想法。现在我们可以执行以下操作:

  1. 将扩展的“代码”分成相似的部分。
  2. 识别模式中的变量 - 部分之间变化的值
  3. 找出所有变量的起始值
  4. 找出每个变量变化的规律
  5. 找到一个断点,即告诉我们已经到达最后一个重复部分的变量之一的条件。

以下是此特定问题的步骤:

  1. 这些部分是 if 语句
  2. 变量是我们比较的 y 中元素的索引
  3. 第一个索引从 0 开始,第二个从 1 开始
  4. 每个 if 语句后两个索引都加 1
  5. 当第二个索引大于 y 的最后一个索引时,我们已经检查了所有元素,我们可以停止

所以剩下的就是设置所需的变量,使用我们发现的中断条件进行while循环,在while循环中具有重复部分的一般情况,然后是变量的变化。 所以:

x = input(f'Enter a list of numbers separated by a space: ')
y = (x.split(' '))
count = 0
# setting the starting values of the variables
index1 = 0
index2 = 1
# creating a loop with the breaking condition
while(index2 < len(y)):
    # the general case of the repeated code:
    if(int(y[index1]) * 2 == int(y[index2])):
        count += 1
    # changing the variables for the next loop
    index1 += 1
    index2 += 1
print(count)

我们看到 index2 始终只是 index1 + 1。所以我们可以像这样替换它:

x = input(f'Enter a list of numbers separated by a space: ')
y = (x.split(' '))
count = 0
index1 = 0
while(index1 + 1 < len(y)):
    if(int(y[index1]) * 2 == int(y[index1 + 1])):
        count += 1
    index1 += 1
print(count)

注意:您可以使用类似于 while 循环的 for 循环

综上所述,您可以使用递归来解决问题,但递归只是模仿循环的过程: 在每次调用中,都会检查中断条件,运行重复的代码并且变量/参数会改变。 希望你觉得这个答案有用:)

答案 4 :(得分:-1)

如果我没看错你的问题,你想要计算所有对的数量,其中第二项是第一项的两倍。 (第一个列表中的 14 是一个错字)。在这种情况下,像这样的简单函数应该可以完成这项工作:

#a = [2,4,8,16,32]
a = [-5, -10, 0, 16, 32]

count = 0
for i, x in enumerate(a):
  # Stop before the list overflows
  if i < len(a) - 1:
    # If the next element is double the current one, increment the counter
    if a[i+1] == x * 2:
      count = count + 1
  else:
    break

print(count)
相关问题