Question

When running the following code in a little script, I get the following error:

Traceback (most recent call last):
  File "/Users/PeterVanvoorden/Documents/GroepT/Thesis/f_python_standalone/python_files/Working_Files/testcase.py", line 9, in <module>
    permutations_01.determin_all_permutations()
  File "/Users/PeterVanvoorden/Documents/GroepT/Thesis/f_python_standalone/python_files/Working_Files/permutations_01.py", line 8, in determin_all_permutations
    config.permutations = [[1] + x for x in config.permutations]
TypeError: can only concatenate list (not "tuple") to list

Code:

import itertools
import config

def determin_all_permutations():
    L = list(xrange(config.number))
    List = [x+2 for x in L]
    config.permutations = list(itertools.permutations(List,config.number))
    config.permutations = [[1] + x for x in config.permutations]


def determin_lowest_price_permutation():
    length = len(L)
    a = 1
    while a <= length:
        point_a = L[a]
        point_b = L[a+1]

# Array with data cost connecting properties will exist of:
# * first column = ID first property [0]
# * second column = ID second property [1]
# * third column = distance between two properties [2]
# * forth column = estimated cost [3]

        position  = 0
        TF = False

        if TF == False:
            if point_a == config.properties_array[position][0] and point_b == config.properties_array[position][1] and TF == False:
                config.current_price = config.current_price + config.properties_array[position][3]
                config.current_path = config.current_path + [config.properties_array[position][2]]
                TF = True

            else:
                position += 1

        else:
            position = 0
            TF = False

I don't get why this error is occurring. When I test line 8

config.permutations = [[1] + x for x in config.permutations]

in a normal situation by making a list in Shell for ex:

List = [1,1,1],[1,1,1]
([1,1,1],[1,1,1])
List = [[0] + x for x in List]
List
([0,1,1,1],[0,1,1,1])

it works, but when using the exact same code in a method, I get the error about adding a tuple... Isn't [1] a list?

Can somebody help me?

Thanks!

Was it helpful?

Solution

In what you executed on the shell, List is made up of lists [1,1,1] and [1,1,1], not tuples. Hence doing List = [[0] + x for x in List] works without errors.

Where as in your code, list(itertools.permutations(List,config.number)) returns a list of tuples, like:

[(2, 4, 8, 5, 11, 10, 9, 3, 7, 6), (2, 4, 8, 5, 11, 10, 9, 6, 3, 7),...]

which explains the error.

Doing this:

config.permutations = [[1] + list(x) for x in config.permutations]

fixes the issue.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top