[Tutor] Input Files

Peter Otten __peter__ at web.de
Wed Nov 19 19:59:48 CET 2014

niyanaxx95 at gmail.com wrote:

> How do I know write the loop code for the table for both inputfiles,
> Table1.txt and Table2.txt and make a third table from the elements
> multiplied in table1.txt and table2.txt. I'm trying to Check the size of
> the two tables to make sure they both have the same number of rows and
> columns o If the tables are not the same size print an error message 
> Once you have read the data from each file create a third table  The
> elements in the third table are the result of multiplying each element in
> the first table by the corresponding element in the second table:
> thirdTable [i] [j] = firstTable[i] [j] * secondTable[i] [j
> Here is my code so far:

>     def main():

Did you write this code yourself? I'm asking because

>         for i in range(row):
>             for j in range (column):
>                 table[i] [j] = int(table[i] [j])  # convert the string to
>                 an integer print(" %3d" % (table[i] [j]), end = " ")

the snippet above already loops over a single table. Assuming you have three 
tables called table1, table2, and table3 you can replace the

>                 table[i] [j] = int(table[i] [j])

part with

                  table3[i][j] = table2[i][j] * table3[i][j]

As you see all values in table3 are overwritten and thus don't matter. 
Therefore you can cheat and instead of building it from scratch with two 
for-loops just read "Table 2.txt" a second time.

>    def main(): 
>        print("Table One") 
>        (row1, column1, table1) = readInput("Table 1.txt") 
>        print("Table Two") 
>        (row2, column2, table2) = readInput("Table 2.txt") 

         # add code to compare row1 with row2 and column1 with column2 here

         (row3, column3, table3) = readInput("Table 2.txt") # sic!
         # add the table multiplication code here

This is not idiomatic Python, but once you have the script working in that 
basic form we can show you how to improve it with some of the cool features 
Python has to offer.

More information about the Tutor mailing list