python - 递归和随机分组列表

标签 python python-3.x algorithm list recursion

我正在尝试编写一个创建二分分组列表 f 的函数。前任。如果我的输入如下:

[a, b, c, d, e, f, g, h]

我想选择随机整数,它会一次又一次地递归地将它分成更小的子列表,直到子列表的长度最大为二,比如:

[[a, [b, c]], [d, [[e, f], [g, h]]]]

这是我到目前为止所得到的,但仍然给了我 类型错误(列表索引必须是整数或切片,而不是列表):

def split_list(l):
    if l.__len__() > 2:
        pivot = np.random.random_integers(0, l.__len__() - 1)
        print(pivot, l)
        l = [RandomTree.split_list(l[:pivot])][RandomTree.split_list(l[pivot:])]
    return l

我被卡住了,如果有任何建议,我将不胜感激。

最佳答案

您的问题对所使用的数据类型不是很清楚,并且似乎使用了一种非传统类型的递归(可能作为类的一部分)。对于错误向下滚动一点。

我冒昧地稍微修改了代码并使用了普通的 random 库,所以你正在寻找的可能看起来像

import random # at the module-declaration part of your program

def split_list (l):
    if len(l) < 2:
        return l
    pivot = random.randint(1, len(l) - 1)
    return [RandomTree.split_list(l[:pivot]) + RandomTree.split_list(l[pivot:])]

我们在单个元素列表上停止递归,如果我们还没有停止,则进一步应用递归,使用从可能范围中提取的随机索引(注意 random.randint 生成具有指定边界的索引包括)。


您的错误是没有在返回值的两个部分之间使用任何连接运算符。

[A][B] 不会连接两个列表,而是尝试从 A< 索引 B (在您的情况下)中给出的列表,这是一种类型错误的用法。

因此您可以使用原始函数(使用已弃用的 numpy random)作为

def split_list(l):
    if l.__len__() > 2:
        pivot = np.random.random_integers(0, l.__len__() - 1)
        l = [RandomTree.split_list(l[:pivot])] + [RandomTree.split_list(l[pivot:])]
    return l

关于python - 递归和随机分组列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48360056/

相关文章:

python - 如何迭代 Django 模板中的列表?

python - 如何在 google colab 上安装 poppler

python - 正则表达式匹配字符串 "Hello, name"

algorithm - 在 BST 中查找所有小于 x 的数字

java - 降低数据集的粒度

algorithm - 作业 : Algorithm to determine the two most popular items in a shopping cart

javascript - 如何根据 Xml 中的条件使字段不可见。奥杜 14

python 最大负值

python - 如何使用python从github正确下载json文件

python - 并行执行具有不同参数的相同 Python 程序