глючная перестановка в питоне - PullRequest
0 голосов
/ 10 октября 2019

Я написал код Java для перестановки, но мне не удалось перевести на Python. Они оба проходят мимо значений, но я не могу понять, почему. Выходные данные дают мне [[1, 2, 3], [1, 2, 3], [1, 2, 3enter code here]]

def permutation(nums):
    nums.sort()
    ans = []
    backTrack([], ans, nums)
    return ans

def backTrack(tempList, ans, nums):
    if len(tempList) == len(nums):
        newList = tempList[:]
        ans.append(newList)
    else:
        for i in range(len(nums)):
            if nums[i] in tempList:
                continue
            tempList.append(nums[i])
            backTrack(tempList, ans, nums)
            tempList = tempList[:-1]

ans = permutation([1, 2, 3])
print(ans)

Ответы [ 2 ]

1 голос
/ 22 октября 2019

ЕСЛИ вы пытаетесь сделать, если для класса я нашел отличный, который объясняет это.

https://www.geeksforgeeks.org/generate-all-the-permutation-of-a-list-in-python/

Я изменил пару вещей.

import sys
# Python function to print permutations of a given list 
def permutation(data): 

    # If data is empty then there are no permutations 
    if len(data) == 0: 
        return [] 

    # If there is only one element in data then, only 
    # one permuatation is possible 
    if len(data) == 1: 
        return [data] 

    # Find the permutations for lst if there are 
    # more than 1 characters 

    l = [] # empty list that will store current permutation 

    # Iterate the input(data) and calculate the permutation 
    for i in range(len(data)): 
       m = data[i] 

       # Extract data[i] or m from the list.  remLst is 
       # remaining list 
       remLst = data[:i] + data[i+1:] 

       # Generating all permutations where m is first 
       # element 
       for p in permutation(remLst): 
           l.append([m] + p) 
    return l 


# Driver program to test above function 
#data = list('123') 
for p in permutation(list(sys.argv[1])): 
    print(p)
1 голос
/ 10 октября 2019

Просто измените:

tempList = tempList[:-1]

Кому:

tempList.pop()

Причина в том, что tempList = tempList[:-1] создает новый список в текущей области (текущая функциявызов) . Следовательно, родительская функция, которая вызывала эту функцию, будет по-прежнему указывать на старый список , т. Е. Родительская функция будет иметь значение tempList, отличное от ожидаемого.

...