Reputation: 49
As you can see from the title I'm having troubles with that error in my python program.
Basically, what I do in this part, is that I take the input file which can be a txt file containing something like this:
0,2 3,0 4,5 7,8 9,6 10,5 12,8 15,20 17,21 21,10
1,3 3,4 5,9 6,8 11,3 12,4 20,20
0,0 6,6 12,5 19,6
and convert it into an array of arrays with each number converted into an int.
This is the function:
A = []
# l = line
# e = element
# with the functions under here we take the input and store it as an array of arrays.
def e_split(e):
temp = []
for tv in e.split(","):
temp.append(int(tv))
return temp
def l_split(l):
temp = []
for e in l.split(" "):
temp.append(e_split(e))
return temp
for l in fileinput.input():
A.append(l_split(l))
With the input given above the resulting A should be (and it is, since it works)
A = [[[0, 2], [3, 0], [4, 5], [7, 8], [9, 6], [10, 5], [12, 8], [15, 20], [17, 21], [21, 10]], [[1, 3], [3, 4], [5, 9], [6, 8], [11, 3], [12, 4], [20, 20]], [[0, 0], [6, 6], [12, 5], [19, 6]]]
The error given in the title occurs when I change my input file with another one like this:
2,1 3,6 6,4 8,2 10,4 12,6 14,1 17,-2 18,1 21,1 23,3 24,-2 26,-2 27,1
3,2 5,0 7,-3 10,-1 11,0 14,-1 15,-4 18,-4 21,-8 22,-12 24,-16 25,-18 27,-16
2,3 5,4 7,-1 8,4 11,7 12,5 13,3 14,6 16,9 18,13 19,18 21,15 22,14 24,12 26,17
3,10 4,14 7,11 8,10 9,7 12,6 13,2 16,6 19,3 20,7 23,2 26,1 27,0 29,2
2,10 5,14 8,18 9,20 12,22 13,27 14,26 16,27 18,24 20,22 21,17 23,14 26,10
2,3 5,2 8,3 9,3 11,-2 13,0 14,-5 15,-1 17,-1 20,3 21,8 23,3 25,5
3,1 5,2 8,6 11,11 13,13 14,14 17,19 18,15 19,17 21,16 22,11 23,15 26,19 29,24
Here's the tracerback:
Traceback (most recent call last):
File "max_growth_period.py", line 29, in <module>
A.append(l_split(l))
File "max_growth_period.py", line 24, in l_split
temp.append(e_split(e))
File "max_growth_period.py", line 17, in e_split
temp.append(int(tv.replace("\n", "")))
ValueError: invalid literal for int() with base 10: ''
It's 2 days that I'm trying to find the problem but I still haven't managed to.
SOLVED:
Thanks to @zondo I just managed to solve this problem. Basically, since in the second input file I had some spaces that I didn't notice at the end of each line, I just had to rewrite l.split(" ")
as l.split()
.
Thanks to everyone for the help btw!
Upvotes: 1
Views: 4968
Reputation: 20336
Your problem is that you use .split(" ")
>>> "this ".split(" ")
['this', '']
Since your lines have spaces at the end, you are creating a list that includes a blank string.
>>> "this ".split()
['this']
If you remove the argument to .split()
, that should fix your problem.
Upvotes: 2