阵列的排列-Python

发布于 2025-02-02 03:20:48 字数 1005 浏览 2 评论 0原文

我正在尝试获取输入阵列的所有排列,由于某种原因,无论我尝试多么努力,都无法获得正确的答案。以下是样本输入

输入:array = [1,2,3]

输出:[[1,2,3],[1,3,2],[2,1,[2,1, 3],[2,3,1],[3,1,2],[3,2,1]]

我试图通过一直到那里的基本案例来递归地做到这一点仅是一个元素。然后,我将一次添加一个元素,然后将其放在数组的每个可能位置。以下是我

def get_permutations(array):
    # Base case
    if len(array) <= 1:
        return [array]

    all_chars_except_last = array[:-1]
    last_char = array[-1]

    permutations_of_all_char_except_last = get_permutations(all_chars_except_last)

    # Put the last char in all possible positions for each of the above permutations
    permutations = []
    for permutation_of_all_chars_except_last in permutations_of_all_char_except_last:
        for position in range(len(all_chars_except_last)+1):
            permutation = permutation_of_all_chars_except_last.insert(position, last_char)
        
            permutations.append(permutation)
    return permutations

关于我的代码的去向的递归尝试建议!我只是想在这个正在编码的美好世界中提高自己的技能!

I am trying to get all of the permutations of an input array and for some reason cannot get the right answer no matter how hard I try. Below is a sample input

Input: array = [1, 2, 3]

Output: [[1,2,3], [1,3,2], [2,1,3], [2,3,1], [3,1,2], [3,2,1]]

I am trying to do this recursively by going all the way down to the base case of there only being one element. Then I am going to add one element at a time and put it in every possible position of the array. Below is my recursive attempt

def get_permutations(array):
    # Base case
    if len(array) <= 1:
        return [array]

    all_chars_except_last = array[:-1]
    last_char = array[-1]

    permutations_of_all_char_except_last = get_permutations(all_chars_except_last)

    # Put the last char in all possible positions for each of the above permutations
    permutations = []
    for permutation_of_all_chars_except_last in permutations_of_all_char_except_last:
        for position in range(len(all_chars_except_last)+1):
            permutation = permutation_of_all_chars_except_last.insert(position, last_char)
        
            permutations.append(permutation)
    return permutations

Advice as to where my code is going would be very much appreciated! I am just trying to increase my skills in this wonderful world that is coding!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

月下客 2025-02-09 03:20:48

代码的问题在于insert方法不会返回列表,而是none。此外,insert突变您调用的列表,这也是不希望的。

因此,您需要用创建新列表的语句替换该语句而不突变原始列表:

permutation = permutation_of_all_chars_except_last[:position] + [last_char] + permutation_of_all_chars_except_last[position:]

或者,或者首先取一个副本,然后调用insert

permutation = permutation_of_all_chars_except_last[:]
permutation.insert(position, last_char)

The problem with your code is that the insert method does not return the list, but None. Moreover, insert mutates the list you call it on, which is undesired also.

So you need to replace that statement with a statement that creates a new list without mutating the original:

permutation = permutation_of_all_chars_except_last[:position] + [last_char] + permutation_of_all_chars_except_last[position:]

Or, alternatively, first take a copy and then call insert:

permutation = permutation_of_all_chars_except_last[:]
permutation.insert(position, last_char)
故笙诉离歌 2025-02-09 03:20:48

由于您是出于学习目的而这样做的,并提高了您的编码技能,因此我会根据发电机添加其他实现。大多数传统递归实现的问题在于,它可以随着阵列长度的增加而迅速地吞噬所有记忆。

def get_permutations(array):
    if len(array) <= 1:
        yield array
    else:
        for perm in get_permutations(array[1:]):
            for i in range(len(array)):
                yield perm[:i] + array[0:1] + perm[i:]

置换阵列将在消费时实现,因此将保留内存。

list(get_permutations([1,2,3]))
# [[1, 2, 3], [2, 1, 3], [2, 3, 1], [1, 3, 2], [3, 1, 2], [3, 2, 1]]

此外,在ietrtools之类的模块中存在有效的实现:

import itertools as it
list(it.permutations([1, 2, 3]))
# [(1, 2, 3), (1, 3, 2), (2, 1, 3), (2, 3, 1), (3, 1, 2), (3, 2, 1)]

Since you are doing this for learning purposes and to increase your skills in coding, I'm adding other implementations based on generators. The problem with most traditional recursive implementations is that it can eat up all your memory quite fast with increasing array length.

def get_permutations(array):
    if len(array) <= 1:
        yield array
    else:
        for perm in get_permutations(array[1:]):
            for i in range(len(array)):
                yield perm[:i] + array[0:1] + perm[i:]

The permutation arrays will get materialized at the moment of consumption, so memory will be preserved.

list(get_permutations([1,2,3]))
# [[1, 2, 3], [2, 1, 3], [2, 3, 1], [1, 3, 2], [3, 1, 2], [3, 2, 1]]

Moreover, efficient implementations exist in modules like ietrtools:

import itertools as it
list(it.permutations([1, 2, 3]))
# [(1, 2, 3), (1, 3, 2), (2, 1, 3), (2, 3, 1), (3, 1, 2), (3, 2, 1)]
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文