Question: I am studying for a computer science exam, and two questions are giving me trouble. One asks me to write a while loop, and the

I am studying for a computer science exam, and two questions are giving me trouble. One asks me to write a while loop, and the other a for loop. I have the answer key, but I am trying to understand what each line is doing so I can replicate it on the test. I am going to post the question and answer here, and if someone could please describe to me what each line of the code is doing I would be very grateful.

8. For parts (a) and (b) below, suppose that the function getNums() returns a Python list containing at least one random integer. Using the variable nums as defined below:

(a) Write a snippet of Python code that uses a while loop to determine the maximum value in the list. Do not make use of built-in functions to determine the maximum value (i.e., craft an efficient algorithm that does so manually); however, you may use a built-in function to get the size of the list. Here's something to get you started:

nums = getNums()

a = 1

max = nums[0]

while a < len(nums):

if nums[a] > max:

max = nums[a]

a += 1

return max

(b) Write a snippet of Python code that uses a for loop to calculate the sum of the values in the list. Do not make use of built-in functions to compute the sum (i.e., craft an efficient algorithm that does so manually); however, you may use a built-in function to get the size of the list. Here's something to get you started:

nums = getNums() sum = 0

for n in nums:

sum += n

return sum

For example, in part A, what is the purpose of setting a = 1? What is the purpose of defining max = nums[0]. What is the significance of the 0? Any help is appreciated. Thanks!

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!