In: Computer Science
Copy the following Python fuction discussed in class into your file:
from random import * def makeRandomList(size, bound): a = [] for i in range(size): a.append(randint(0, bound)) return a
a. Add another function that receives a list as a parameter and computes the sum of the elements of the list. The header of the function should be
def sumList(a):
The function should return the result and not print it. If the list is empty, the function should return 0. Use a for loop iterating over the list.
Test the function in the console to see if it works.
b. Write a function that receives a list as a parameter and a value, and returns True if the value can be found in the list, and Falseif not. Use a for loop that goes over the list and compares each element to the value. If any of them is equal to the value, it returns True. Otherwise after the loop is done, you can return False. Thus, if the loop completes without a return statement happening, then the value is not in the list. The function header should look like this:
def searchList(a, val):
Test this second function a few times the same way as the first one.
c. Below the three functions, add a piece of code that
Test the program to make sure that it works fine.
PYTHON CODE:
from random import * def makeRandomList(size, bound): a = [] for i in range(size): a.append(randint(0, bound)) return a # Function to return sum of all elements in list a def sumList(a): # Initialize sum to 0 sum = 0 # Loop through list a for i in a: # Add list element i to sum sum += i # Return back sum of list elements return sum # Function to search for a given value in the list def searchList(a, val): # Loop through list a for i in a: # If list element i is equal to val if i == val: return True # val has not been found return False a = makeRandomList(10, 50) print('a =', a) sum = sumList(a) print('Sum =', sum) val = int(input('Enter a value: ')) result = searchList(a, val) print("result =", result)
SAMPLE OUTPUTS:
FOR ANY HELP JUST DROP A COMMENT