Answered step by step
Verified Expert Solution
Link Copied!

Question

1 Approved Answer

Python 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

Python

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.

This is what I came up with.

from future_builtins import zip
scalar_product = 0
with open('numbers1.txt') as n1, open('numbers2.txt') as n2:
 for line1, line2 in zip(n1, n2):
 scalar_product += int(line1) * int(line2)

This is what It said

More Hints: Correct solutions that use as tend to also use data1 Correct solutions that use as tend to also use data2 Problems Detected: It appears your code resulted in an execution error when running this test case, and did not run to completion Test case did not run to completion

Step by Step Solution

There are 3 Steps involved in it

Step: 1

blur-text-image

Get Instant Access to Expert-Tailored Solutions

See step-by-step solutions with expert insights and AI powered tools for academic success

Step: 2

blur-text-image_2

Step: 3

blur-text-image_3

Ace Your Homework with AI

Get the answers you need in no time with our AI-driven, step-by-step assistance

Get Started

Recommended Textbook for

Rules In Database Systems Third International Workshop Rids 97 Sk Vde Sweden June 26 28 1997 Proceedings Lncs 1312

Authors: Andreas Geppert ,Mikael Berndtsson

1997th Edition

3540635165, 978-3540635161

More Books

Students also viewed these Databases questions