Search code examples
pythonlistintegerconcatenationtypeerror

The program is: Please enter a 3 digits number: 635 The permutations are: 635, 653, 365, 356, 563, 536


def permutation_generate(lst):
    if len(lst)== 0:
        return []
    
    if len(lst)==1:
        return [1]
    
    l =[]
    for i in range(len(lst)):
        m = lst[i]
        
        remLst= lst[:i]+ lst[i+1:]
        for p in permutation_generate(remLst):
            l.append([m]+p)
        return l
    
data= list(input("Please enter a 3 digits number:\n"))
print("The permutations are:")
for p in permutation_generate(data):
    print(*p,sep='', end="")
    

#TypeError: can only concatenate list (not "int") to list #What is the solution of the error?


Solution

  • On line 13 your function permutation_generate(remLst) returns a list [1] and you start iterating over it in a for loop. So p is 1 of type int thats why on line 14 you get the error trying to concatenate [m]+int won't work. [m]+[p] would work.

    And for your task take a look at itertools module of python standard library