Home > Computer Programming > Python Quiz: Answers

Python Quiz: Answers

November 28, 2014 Leave a comment Go to comments

Here are the questions I asked you:

Problem 1:
Write a function “largest” which takes three numbers and returns the largest. (You may assume that all the numbers are different.) A call to the function would look like this:

largest(3, 4, 5)

Problem 2:
Write a function “findLast” that takes two arguments: a list called “numbers” and a number called “n”, and returns the last place at which n is found in the list of numbers. A call to the function would look like this:

mylist = [4, 7, 6, 8, 4, 3, 6, 8, 4, 6, 3, 2]
findLast(mylist, 6)

Problem 3:
Write a function that accepts numbers from the user and prints the mean of the numbers entered. The function should keep accepting numbers until “x” is entered. Output from the program might look like this:

Enter a number:
 Enter a number:
 Enter a number:
 Enter a number:
 Enter a number:
 Enter a number:
 Enter a number:
The mean of the numbers entered is 50.5.

Here are the answers:

def largest(a, b, c):
    if (a > b and a > c):
        return a
    elif (b > a and b > c):
        return b
        return c

def findLast(numbers, n):
    pos = -1
    count = 0
    for x in numbers:
        if x == n:
            pos = count
        count = count + 1
    return pos

def avgNums():
    sum = 0
    count = 0
    num = raw_input("Enter a number: ")
    while num != "x":
        sum = sum + int(num)
        count = count + 1
        num = raw_input("Enter a number: ")
    print ("The mean of the numbers is " + sum/count)

You will understand this material better if you answer these concept questions:

  • For the first problem, I told you that you could assume the input values would all be different. What would happen if two or more input values were the same? In what situations would the function work and in what situations what it not work? How could you change the function to make it always work?
  • In the second problem, why did I initialize pos to -1 and not 0? What does it mean if the function returns -1?
  • In problem 3, explain why I don’t need include if num == “x” before I print the mean. (Lots of you did include it!)
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s