219k views
0 votes
Two files named numbers1.txt and numbers2.txt both have an unknown number of lines, each line consisting of a single positive integer. Write some code that reads a line from one file and then a line from the other file. The two integers are multiplied together and their product is added to a variable called scalar_product which should be initialized to zero. Your code should stop when it detects end of file in either file that it is reading. For example, if the sequence of integers in one file was "9 7 5 18 13 2 22 16" and "4 7 8 2" in the other file, your code would compute: 4*9 + 7*7 + 8*5 + 2*18 and thus store 161 into scalar_product.

User Gulnara
by
5.6k points

1 Answer

2 votes

Answer:

see explaination for program code

Step-by-step explanation:

scalar_product = 0

li=[]

li2=[]

#reading numbers1.txt and numbers2.txt intoli and li2 respectively

with open('numbers1.txt') as n1, open('numbers2.txt') as n2:

for line1 in n1:

li.append(int(line1))

for line2 in n2:

li2.append(int(line2))

#storing min list size into variable l

a=len(li)

b=len(li2)

if a<b:

l=a

else:

l=b

#calculating scalar product

for i in range(l):

scalar_product=scalar_product+li[i]*li2[i]

print("scalar product is",scalar_product)

User Granga
by
6.1k points