P ython p rogramming e xercises



Yüklə 1,51 Mb.
Pdf görüntüsü
səhifə36/124
tarix14.05.2023
ölçüsü1,51 Mb.
#113537
1   ...   32   33   34   35   36   37   38   39   ...   124
PythonProgrammingExercisesGentlyExplained

Solution Template 
Try to first write a solution from scratch. But if you have difficulty, you can use the following 
partial program as a starting place. Copy the following code from https://invpy.com/sumproduct-
template.py and paste it into your code editor. Replace the underscores with code to make a working 
program: 
def calculateSum(numbers): 
# Start the sum result at 0: 
result = ____ 
# Loop over all the numbers in the numbers parameter, and add them 
# to the running sum result: 
for number in ____: 
result += ____ 
# Return the final sum result: 
return ____ 
def calculateProduct(numbers): 
# Start the product result at 1: 
result = ____ 
# Loop over all the numbers in the numbers parameter, and multiply
# them by the running product result: 
for number in ____: 
result ____ number 
# Return the final product result: 
return ____ 
The complete solution for this exercise is given in Appendix A and https://invpy.com/sumproduct.py


Python Programming Exercises, Gently Explained 
43 
You can view each step of this program as it runs under a debugger at https://invpy.com/sumproduct-
debug/
Further Reading 
Just like in Exercise #12 ―Smallest & Biggest‖ we can generate a list of one million numbers, and 
then calculate the sum and product of these numbers. Multiplying one million numbers creates an 
astronomically large number, so we’ll limit our test to a mere ten thousand numbers. Write the 
following program and save it in a file named testsumproduct.py. Run it from the same folder as your 
sumproduct.py file so that it can import it as a module: 
import random, sumproduct 
numbers = [] 
for i in range(10000): 
numbers.append(random.randint(1, 1000000000)) 
print('Numbers:', numbers) 
print(' Sum is', sumproduct.calculateSum(numbers)) 
print('Product is', sumproduct.calculateProduct(numbers)) 
When run, this program displays the million numbers between 1 and 1,000,000,000 it generated
along with the sum and product of the numbers in that list.


44 

Yüklə 1,51 Mb.

Dostları ilə paylaş:
1   ...   32   33   34   35   36   37   38   39   ...   124




Verilənlər bazası müəlliflik hüququ ilə müdafiə olunur ©azkurs.org 2025
rəhbərliyinə müraciət

gir | qeydiyyatdan keç
    Ana səhifə


yükləyin