Write a program that includes the following three functions. (Refer to exercises
ID: 3888449 • Letter: W
Question
Write a program that includes the following three functions. (Refer to exercises 11, 12, 13, and 14 of Chapter 6.) Functions squareEach(nums) In this function, nums is a list of numbers. It modifies the list by squaring each entry. sumList(nums) In this function, nums is a list of numbers. It returns the sum of numbers in the list. toNumbers(strList) In this function, strList is a list of strings, each of which represents a number. It modifies each entry in the list by converting it to a number. Use the functions above to implement a program that computes the sum of the squares of numbers read from the file. You should create and save a file with one line and a list of numbers, each separated by a space. An example would be a file with the following contents: 13 34 14 53 56 76. Your program should prompt for a “file name” (the name you used when you saved the file) and print or display the sum of the squares of the values in the file. Hint: use readlines().
Explanation / Answer
Python 2.7 code
# function to convert strings into numbers
def toNumbers(strList):
numbers = []
for s in strList:
numbers.append(int(s))
return numbers
# function to square the numbers
def squareEach(nums):
squares = []
for n in nums:
squares.append(n*n);
return squares
# function to summ numbers in
def sumList(nums):
summ = 0;
for n in nums:
summ = summ + n
return summ;
print "Enter the file name!"
filename = raw_input(); # input filename
with open(filename,'r') as f: # read numbers from file
line = f.readline()
strList = line.strip().split(" ") # create list of strings
nums = toNumbers(strList) # create list of numbers
squares = squareEach(nums) # create list of squares
summ = sumList(squares) # get sum
print summ
Sample Output:
Enter the file name!
out.txt
13242
out.txt
13 34 14 53 56 76
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.