Home > Software design >  unexpected EOF while parsing - how do i fix my code?
unexpected EOF while parsing - how do i fix my code?

Time:05-24

I've got

desc = ['(4,1);(1,4)', '(2,3);(3,2)', '(4,2);(2,4);(1,3);(3,1)', '(1,2);(2,1);(4,3);(3,4)'] 

and I want the output to be

[[(4, 1), (1, 4)], [(2, 3), (3, 2)], [(4, 2), (2, 4), (1, 3), (3, 1)], [(1, 2), (2, 1), (4, 3), (3, 4)]]

So far I've tried:

for x in range(len(desc)):
    desc[x] = desc[x].split(';')
    for y in range(len(desc[x])):
        desc[x][y] = eval(desc[x][y])
 

but there is a syntax error saying 'unexpected EOF while parsing. How do I fix my code?

For the last two lines of my code I was just trying to extract the tuples from the strings containing them, is there anything else I could use except for eval()?

CodePudding user response:

Unexpected EOF is caused by the indentation of the second for loop.

for x in range(len(desc)):
    desc[x] = desc[x].split(';')
        for y in range(len(desc[x])): # this has one tab to much 
            desc[x][y] = eval(desc[x][y])

This is how it should look like:

for x in range(len(desc)):
    desc[x] = desc[x].split(';')
    for y in range(len(desc[x])): 
        desc[x][y] = eval(desc[x][y])

CodePudding user response:

You want to split each item of your list with the separator ';'. You need to parse your list :

for element in desc and split each element according to this separator : temp = element.split(';'). You can then add to your output list the list [temp[0], temp[1]]

desc = ['(4,1);(1,4)', '(2,3);(3,2)', '(4,2);(2,4);(1,3);(3,1)', '(1,2);(2,1);(4,3);(3,4)']
output = []

for element in desc:
    temps = element.split(";")
    output.append([temps[0], temps[1]])

print(output)
# [['(4,1)', '(1,4)'], ['(2,3)', '(3,2)'], ['(4,2)', '(2,4)'], ['(1,2)', '(2,1)']]

To remove the '' you have to transform your items into actual tuples with the integers inside :

desc = ['(4,1);(1,4)', '(2,3);(3,2)', '(4,2);(2,4);(1,3);(3,1)', '(1,2);(2,1);(4,3);(3,4)']
output = []

for element in desc:
    temps = element.split(";")
    tuples_to_add = []
    for i in temps:
        tuples_to_add.append(tuple([int(i.strip('()')[0]), int(i.strip('()')[-1])]))

    output.append(tuples_to_add)

print(output)
[[(4, 1), (1, 4)], [(2, 3), (3, 2)], [(4, 2), (2, 4), (1, 3), (3, 1)], [(1, 2), (2, 1), (4, 3), (3, 4)]]
  • Related