Problem 18, help reading in list from external file

For questions about problems on the Project Euler web site. No spoilers. Please include the question number in the subject line of your post.

Problem 18, help reading in list from external file

Postby bill_lesh » Tue Oct 22, 2013 7:59 pm

On this problem, I am trying to create a 2d array with all the numbers given in problem 18 (
Basically what I want is, if I have a file that looks like:
1 2
3 4
I want to read that in where list[0][0] = 1, list[0][1] = 2, list[1][0] = 3 and list[1][1] = 4 (i may have those indices switched, its been a while but that doesnt matter). How can I do this, where the numbers in the target file are seperated by spaces?
First I tried:
Code: Select all
f = open('file.txt', 'r')
for line in f:

but that doesnt work cause you can't append to a 2d array. Then I tried:
Code: Select all
with open('file.txt','r') as f:
f = open('file.txt', 'r')
for line in f.readlines():
     a = line.split(' ')

where l is defined as: l=np.zeros(shape=(15,15))

I tried the last one at the suggestion of a friend but it would even compile. I also tried the method:
datain = np.loadtxt('file.txt')
and all that did was append to the list the first element of each line.

What am I doing wrong and how can I read this data in to create a list like the one I want? Thanks in advance for any help.
- Bill
Last edited by micseydel on Tue Oct 22, 2013 8:12 pm, edited 1 time in total.
Reason: Code tags, first post lock.
Posts: 1
Joined: Tue Oct 22, 2013 7:07 pm

Re: Problem 18, help reading in list from external file

Postby stranac » Tue Oct 22, 2013 8:19 pm

A very basic way to do that:
Code: Select all
numbers = []
with open('file.txt') as f:
    for line in f:

That will contain numbers as strings.
You can use int() to make them actual numbers.
Friendship is magic!

R.I.P. Tracy M. You will be missed.
User avatar
Posts: 1790
Joined: Thu Feb 07, 2013 3:42 pm

Return to Project Euler

Who is online

Users browsing this forum: No registered users and 1 guest