Question

In: Computer Science

Copy the following Python fuction discussed in class into your file: from random import * def...

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

  • calls the function makeRandomList to generate a list with a size of 10 and a bound of 50, stores it in a variable, and prints it.
  • Then it should call the function sumList to compute the sum and also print the result.
  • Finally, it should ask the user for a value, input it and store it in a variable, then call the function searchList with the list and this variable, and output the result.

Test the program to make sure that it works fine.

Solutions

Expert Solution

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


Related Solutions

PYTHON PROBLEM: TASKED TO FIND THE FLAW WITH THE FOLLOWING CODE: from itertools import count def...
PYTHON PROBLEM: TASKED TO FIND THE FLAW WITH THE FOLLOWING CODE: from itertools import count def take_e(n, gen):     return [elem for (i, elem) in enumerate(gen) if i < n] def take_zc(n, gen):     return [elem for (i, elem) in zip(count(), gen) if i < n] FIBONACCI UNBOUNDED: def fibonacci_unbounded():     """     Unbounded Fibonacci numbers generator     """     (a, b) = (0, 1)     while True:         # return a         yield a         (a, b) = (b, a + b) SUPPOSED TO RUN THIS TO ASSIST WITH...
write pseudocode for this program . thank you import random class cal():    def __init__(self, a,...
write pseudocode for this program . thank you import random class cal():    def __init__(self, a, b):        self.a = a        self.b = b    def add(self):        return self.a + self.b    def mul(self):        return self.a * self.b    def div(self):        return self.a / self.b    def sub(self):        return self.a - self.b def playQuiz():    print("0. Exit")    print("1. Add")    print("2. Subtraction")    print("3. Multiplication")    print("4. Division")...
Write a single python file to perform the following tasks: (a) Get dataset “from sklearn.datasets import...
Write a single python file to perform the following tasks: (a) Get dataset “from sklearn.datasets import load_iris”. Split the dataset into two sets: 20% of samples for training, and 80% of samples for testing. NOTE 1: Please use “from sklearn.model_selection import train_test_split” with “random_state=N” and “test_size=0.80”. NOTE 2: The offset/bias column is not needed here for augmenting the input features. (b) Generate the target output using one-hot encoding for both the training set and the test set. (c) Using the...
Create a preorder iterator for the class binarytree from the Python program below. class Binarytree: def...
Create a preorder iterator for the class binarytree from the Python program below. class Binarytree: def __init__(self, DataObject): self.data = DataObject self.parents = None self.left_child = None self.right_child = None @property def left_child(self): return self.__left_child @left_child.setter def left_child(self, node): self.__left_child = node if node is not None: node.parents = self @property def right_child(self): return self.__right_child @right_child.setter def right_child(self, node): self.__right_child = node if node is not None: node.parents = self def is_leafNode(self): if self.left_child is None and self.right_child is None:...
Please use Python! def getText(file): This function should open the file named file, and return the...
Please use Python! def getText(file): This function should open the file named file, and return the contents of the file formatted as a single string. During processing, you should (i) remove any blank lines, (ii) remove any lines consisting entirely of CAPITALIZED WORDS , and (iii) replace any explicit ’\n’ (newline) characters with spaces unless directly preceeded by a ’-’ (hyphen), in which case you should simply remove both the hyphen and the newline, restoring the original word. def getText(file):...
python class Node(): def __init__(self, value): pass class PostScript(): def __init__(self): pass    def push(self, value):...
python class Node(): def __init__(self, value): pass class PostScript(): def __init__(self): pass    def push(self, value): pass    def pop(self): return None    def peek(self): pass    def is_empty(self): pass def stack(self): pass    def exch(self): pass    def index(self): pass    def clear(self): pass    def dup(self): pass    def equal(self): pass    def depth(self): pass    stack = PostScript() def decode(command_list): for object in command_list: if object == '=': stack.equal() elif object == 'count': stack.depth() elif object ==...
Python I am creating a class in python. Here is my code below: import csv import...
Python I am creating a class in python. Here is my code below: import csv import json population = list() with open('PopChange.csv', 'r') as p: reader = csv.reader(p) next(reader) for line in reader: population.append(obj.POP(line)) population.append(obj.POP(line)) class POP: """ Extract the data """ def __init__(self, line): self.data = line # get elements self.id = self.data[0].strip() self.geography = self.data[1].strip() self.targetGeoId = self.data[2].strip() self.targetGeoId2 = self.data[3].strip() self.popApr1 = self.data[4].strip() self.popJul1 = self.data[5].strip() self.changePop = self.data[6].strip() The problem is, I get an error saying:  ...
import random # define functions def rollDice(): # function returns a random number between 1 and...
import random # define functions def rollDice(): # function returns a random number between 1 and 6 def userWon(t1, t2): # function accepts player total and computer total # function returns true if player wins # function returns false if computer wins def main(): # each player rolls two Dice player = rollDice() + rollDice() computer = rollDice() + rollDice() # ask the player if they want to roll again again = int(input("Please enter 1 to roll again. Enter 2...
#Python 3.7 "Has no attribute" error - def get():     import datetime     d = date_time_obj.date()...
#Python 3.7 "Has no attribute" error - def get():     import datetime     d = date_time_obj.date()     return(d) print(a["Date"]) print("3/14/2012".get()) How to write the "get" function (without any imput), to convery the format ""3/14/2012" to the format "2012-03-14", by simply using "3/14/2012".get() ?
Copy class CirclesViewer from Codecheck and complete it. You need to import the graphics package. After...
Copy class CirclesViewer from Codecheck and complete it. You need to import the graphics package. After completed, the program will ask the user to enter an integer between 1 and 10 then draw the specified number of circles. The radius starts at 10 and increments by 10 for each next one. They all touch the line x = 5 at the left and the line y = 10 at the top. Another way to look at this is that the...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT