开发者

function that produces a two dimensional list from files containing numbers

开发者 https://www.devze.com 2023-02-12 05:33 出处:网络
Write a function table() that takes a parameter a string representing a file name and a number n.The function should open and read the contents of the corresponding file.The file will contain one line

Write a function table() that takes a parameter a string representing a file name and a number n. The function should open and read the contents of the corresponding file. The file will contain one line with exactly n*n numbers separated by blank spaces. The function table() should create and return an n x n two-dimensional list containing the n*n num开发者_如何学Gobers as follows: The first row of the table will contain the first n numbers, the second row will contain the next n numbers, and so on until the nth row. The following shows what table() should display when run on the files data1.txt and data2.txt.

table('data1.txt', 3)

[['3', '4', '5'], ['6', '7', '8'], ['9', '10', '11']]

table('data2.txt', 4)

[['3', '4', '5', '6'], ['7', '8', '9', '10'], ['11', '12', '13', '14'], ['15', '16', '17', '18']]

Clearly a homework question, so NO answers, just pointers to help me get started. I have no clue where to start.


I assume when you say "no answers", you mean no code.

  • Open the file.
  • Read the command line argument (n).
  • Create a list (x).
  • Enter a loop, executed n times.
    • Read n entries from the file into another list (y) (probably a sub-loop).
    • Add list y to list x.

Breaking things into individual small goals like that often makes the task easier.


First, this page shows some ways of reading a file. When you read a line of a file, you are going to get back a string. Look into methods that will make it easy to break up that string into n parts. Finally, you will want to read about how to operate on lists, this tutorial will help.


Pointers: Create an n*n size matrix, use a two nested for loops from 0 to n-1 and read each element sequentially into [i][j] where i is the iterator in the outer loop and j the one in the inner loop.

0

精彩评论

暂无评论...
验证码 换一张
取 消