python - 使用递归查看随机列表时如何跟踪偶数的数量

标签 python python-3.x recursion

这里有点新手。因此,在尝试使用递归函数时,我想尝试编写一个程序:

1:生成一个包含 10 个 0 - 20 之间的随机整数的列表

2:使用递归函数遍历列表并找出列表中的哪些元素是偶数

3:打印上述偶数个数字

我遇到的问题是如何打印结果。我似乎无法弄清楚调用函数时我想在函数中放入什么值( F(?) )

我尝试集成一个计数器来跟踪程序找到偶数的次数,但无论我如何努力使其成为全局变量,它总是会导致变量未定义的错误。

我该怎么办呢?我完全错了吗?

import random
numL = []
for i in range(10):
    x = random.randint(0,20)
    numL.append(x)

print(numL)

def F(x):
    if numL[x] % 2 == 0:
        return numL[x]
    else:
        return F(x+1)

print(F( ??? ))

在这个论坛上提出的第一个问题,希望我没问题,感谢您的帮助!

最佳答案

假设您想返回偶数列表,那么您需要考虑 4 种情况

  1. 这是列表中的最后一个数字,即使如此也返回该数字
  2. 这是列表中的最后一个数字,其奇数请勿重新运行该数字
  3. 还有更多号码需要检查,这个号码还是这样返回 这加上函数结果
  4. 还有更多号码需要检查,但返回的号码为奇数 只有函数结果而不是这个数字

所以我们可以将其编码为

import random

def get_even_nums(nums):
    num = nums[0]
    #This is our terminating case we definitivly return a value here
    if len(nums) == 1:
        return [num] if num % 2 == 0 else []
    else:
        #If we got here we will be recursivly calling the function
        #If its even number return that number plus the result of the function
        #it its not even then just return the reult of the function and not this num
        if num % 2 == 0:
            return [num] + get_even_nums(nums[1:])
        else:
            return get_even_nums(nums[1:])


numL = [random.randint(0, 20) for _ in range(10)]
print(numL)
print(get_even_nums(numL))

输出

[3, 6, 5, 10, 20, 18, 5, 0, 3, 9]
[6, 10, 20, 18, 0]

关于python - 使用递归查看随机列表时如何跟踪偶数的数量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58974952/

相关文章:

python - 如何标准化seaborn distplot?

python - 如何获取python中的内置模块列表?

python - 使用 pandas 对数据进行排序 - 根据其他列中的值对第一列进行排序

java - Jackson objectMapping 没有获取 JSON 数据

python - 转换字典python中的列表列表

python - 在所有条件下强制从文件名导入模块(更改模块、更改文件名)

python-3.x - 如何使用kv语言引用kivy中创建的不同屏幕的小部件?

python - 密码生成器的字符顺序如何随机化

c - 为什么这个 C 链表会损坏?

python - 在 Python 上使用回溯的子集总和