Reputation: 1
I am working on a practice coding interview on filtered.ai and am having trouble working with the input. filtered.ai uses for line in inputfile.input() the first line is my sum variable and the second is what will be turned into an array.
I was able to remove the new line character and get to one list which is a good start. Now I am left with a list arr = ['5 ', '1 2 2 3 1']
import fileinput
import sys
arr = []
for line in fileinput.input():
line = line.replace('\n',' ')
arr.append(line)
#sys.stdout.write(line)
print(arr)
I would like to have one list to work with where the first value is always the sum value and the second is the list to manipulate/process logic on.
I would like arr = [[5],[1,2,2,3,1]]
Upvotes: 0
Views: 195
Reputation: 674
This may be more readable
arr = ['5 ', '1 2 2 3 1']
ans = []
for a in arr:
a = a.rstrip().split()
a = [int(x) for x in a]
ans.append(a)
ans
Upvotes: 0
Reputation: 3624
If your inputs are in a file called 'file.txt', then you can use the following:
with open('file.txt') as f:
arr = f.read().split('\n')
nums_sum = int(arr[0])
nums = map(int, arr[1].split())
result = [[nums_sum], list(nums)]
If the file content is:
10
2 2 6
Then your result will be:
[[10], [2, 2, 6]]
Upvotes: 0
Reputation: 1519
You can do this with a list comprehension
arr = [[int(x) for x in string.split()] for string in arr]
Returns:
[[5], [1, 2, 2, 3, 1]]
Upvotes: 2