Python代写:CS1110 Functions

代写Python基础作业,练习函数的用法。

Requirement

In this practice set, you will be writing quite a few short Python functions; but first, let’s discuss some sample python programs that are similar in nature those I will be asking you to write. Be sure to read through the handout before jumping to the programming practice problems! Do not copy and paste my sample code! Type it!

Sample Program 1

Suppose that you want to iterate through a list and print each element in that list. We could write this program out using a “for loop”. I will name this function iterateThroughList(myList), and refer to this function as Sample Program 1:

1
2
3
4
5
6
7
# CS:1110 Introduction to Computer Science
# This function takes, as an argument a list, myList, and prints the contents:

def iterateThroughList (myList):
#do this action for every element in the list (which is given when the function is called)
for element in myList:
print(element)

Let’s take a look at this function. The structure of this “for loop” uses two keywords: for and in. Keywords were briefly discussed in DA Assignment 1. This function iterates through myList, referring to each item in the list as element as it is being manipulated. We are printing each item, and then moving on to the next item in the list, until each item has been printed.
Now type the following program into the python script window:

1
2
3
4
5
6
7
8
# CS:1110 Introduction to Computer Science
# What does this function do?

def printStuff(n):
myList = range(0, n)
printf(myList)
for element in myList:
print(element * "hello")

Let’s take a look at what this function does. Run this program. Then type the following and think about the results:

>>> printStuff(5)
>>> printStuff(10)

Describe what this function does. What does the line “myList = range(0, n)” do?

Sample Program 2

Suppose that you want to create a list consisting of the integer 0 appearing n times. We could write this program out using a “for loop”. I will name this function createListFor(n) and refer to this function Sample Program 2:

1
2
3
4
5
6
7
8
9
10
11
12
13
# CS:1110 Introduction to Computer Science
# This function takes, as an argument, an integer n, and returns a list consisting of n entries, all of which are 0:

def createListFor(n):
#create an empty list
myList = []

#do this action n times
for value in range(0,n):
myList.append(0)

#return myList
return myList

Let’s take a look at this function. This function has to return a list of n zeros, so the first thing that we need to do is create an empty list. Then we need to insert the integer 0 to the list n times. The line “for value in range(0,n)” uses a function called “range”. This is a built-in function that basically iterates through the integers starting with 0 and ending with the value of (n - 1). Remember that in computer science we start counting at 0. So, if we need to do something n times, we can start at 0 and stop at (n - 1). The structure of this “for loop” uses the keyword “for” followed by a variable name (in this case, “value”) then another keyword “in” and then the function “range(0,n)”.

Included in this “for loop” (as indicated by the indentation) is the instruction “myList.append(0)”. This instruction does what you think it does: it will take the list myList and append the integer 0 to the list. Once we are done performing this action n times, we will leave the loop (again, indicated by the indentation) and then return the list that we created.

You should type this code into wing and run it (first press the green arrow to load the program into memory, and then call the function in the python shell to actually see what the function does) to make sure that it runs properly, and that you understand the role of the indentation. Next, experiment with this sample code.

  • Change the name of the variable “value” to “element” and run the program and call the function. Then change it back to “value”.
  • Indent the “return myList” line to include it in the “for loop” to see what happens. Then move it back to where it belongs.
  • Insert two print statements, one immediately before and one immediately after the line “myList.append(0)”: include the line “print(value)” on the line immediately before the line that appends 0 to the list, and include the line “print(myList)” on the line immediately after. Now run the program and call the function.
  • Change the line “print(myList)” to the line “print(“The list is: “ + str(myList))” and run the program and call the function.

For each of these changes, pay attention to the output that appears in the shell.

Sample Program 3

Suppose that you want to create a list consisting of the integer 0 appearing n times, but instead of using a “for loop” we will use a “while loop”. I will name this function createListWhile(n), and refer to this function as Sample Program 3:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
# CS:1110 Introduction to Computer Science
# This function takes, as an argument, an integer n, and returns a list consisting of n entries, all of which are 0.
# We will use a "while loop" rather than a "for loop":

def createListWhile(n):
#create an empty list
myList = []

#do this action n times
while (len(myList) < n)
myList.append(0)

#return the list
return myList

Let’s compare this function to the first sample program. It starts out the same: we need to create an empty list, and then append things to this list. The difference is in how we iterate. In this function, we are using a different built-in function: len(). Notice that we are writing functions that make use of other functions! We can think of individual functions as modules; many of our more complex functions will be written using this modular framework. But, let’s get back to our length function: len() takes as an argument a list and returns its length. As an aside, play with the length function. What happens if you try to find the length of an integer? Of a Boolean? Of a float? Of a string? This is where you let your curiosity run wild! What is the length of an empty list? Hopefully you tried to find out by typing

>>> len([])

and saw that the response was 0.

Ok, let’s get back to the sample program. The continuation condition in this “while loop” checks to see if the length of our list is the right size. If it is not, we need to keep appending things to the list. Once the length of the list is the correct value, we will exit the iterative loop and return the list that we created.

Type this function into Wing, run the program and call the function in the shell. Do not “copy and paste”. Typing is good exercise! You should get the desired results. Make the following changes to this sample program:

  • Modify this function so that the list contains n entries of the string “yibbie”.
  • Modify this function so that it uses a counter to keep track of the number of times that “yibbie” has been inserted into the list.

Making changes to a program is a great way to become familiar with the syntax of Python.

Sample Program 4

Suppose you want to create a list that contains a bunch of random numbers. You could need 10 numbers, 100 numbers, or 100,000 numbers. Perhaps you will need to create several such lists, each containing a different number of numbers. Rather than manually typing the first numbers that come to you (which wouldn’t really fit the criteria), you want to automate the process. Let’s take a look at a sample program that tries to accomplish this goal, which I will refer to as Sample Program 4. Feel free to type this program into Wing, paying attention to the indentation. Remember that indentation is one of the keys to Python:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
# CS:1110 Introduction to Computer Science
# This function takes, as an argument, an integer n, and returns a list of n random integers with values between
# 0 and 9.

import random
def randomNumbers(n):
#create an empty list
myList = []

#introduce a Boolean, called needMoreNumbers, to keep track of whether or not we need more numbers
needMoreNumbers = True

#we will iterate through the process, creating new numbers if we need them. A boolean is either True or False.
# if the boolean needMoreNumbers is False, we will exit this loop. but until we reset the boolean
# needMoreNumbers to be False, we will continue to iterate through this loop

while (needMoreNumbers):
#create a random integer between 0 and 9, inclusive
randomNumber = int(random.random() * 10)

#add the random number to the list of random numbers using the append() method
myList.append(randomNumber)

#decrease the number of numbers to create by 1, to make progress towards
#getting out of the loop
n=n-1

#decide whether or not to keep going:
if (n < 1):
needMoreNumbers = False

return myList

Let me point out a few things in that code that you probably haven’t seen before. One component that you may not have seen before is the use of random, both at the beginning of the program with an import statement, and towards the end, where random.random() appears. The import statement tells the Python interpreter that it should load the library called random. A library is simply a collection of useful algorithms or programs that a programmer may wish to use. In this case, we’ll use a specific function in that library, called random(). This specific function has been given the name random. The function, random(), simply returns - you guessed it - a random number. However, it returns a random decimal number between 0 and 1 (more precisely, it returns a number in the interval [0, 1)…there is a mathematical difference between square braces and parentheses). We want integer numbers in a given range, say 0 - 9, so we’ll just multiply this random number by 10 and “cast it” (or convert it) to an integer, effectively giving us a random number between 0 and 9 (in this case). There are several other ways to generate a random number that is an integer within a given range. See how many ways you can do this (feel free to use Google). I will discuss a few different ways in class.

We typically import all libraries at the beginning of a series of functions in a file. You only need to import a library ONCE in a given file or scripting window. Once a library is imported, it is available to use in every function in the scripting window. For example, if you need the random library and the math library, you’ll have the following as the first two lines of your script, followed by your various functions:

1
2
3
4
5
6
7
8
import random
import math

def myFirstFunction(a, b):
#type some code. This function has access to the functions in both imported libraries

def mySecondFunction(value, words):
#type some code. This function also has access to the functions in both imported libraries

Another type of variable being used is a Boolean (I realize that in class I tend to focus on 4 data types…I tend to take Booleans for granted). A Boolean type of variable is a variable that can only take on one of two values: True or False. The words True and False have special meaning in python (they would not make good variable names). In some languages, Boolean variables take on the values YES/NO, or 0/1, or true/false (not capitalized). Boolean variables are useful when checking the result of a particular condition: if the condition is met, the value assigned to the variable will be True, and if the condition is not met, the value assigned to the variable will be False. You can set a variable to be either True or False, and then determine its type:

>>> myBool = True
>>> type(myBool)

When comparing quantities, the result is a Boolean. For example, type the following into the Python shell and look at the results:

>>>5 > 10
>>>4 > 10

Another thing to realize is that we are working with a new data type. You have already been introduced to strings (data type str), integers (data type int) and floats (data type float). In this program, we are actually working with two new types of data: Booleans and lists. A list has type “list”. Type the following into the Python shell:

>>>myList = [1, 2, 3, 4, 5]
>>>type (myList)

A list is a very interesting (and useful) data type, and python has a bunch of convenient built-in functions that can be used to manipulate lists. We will spend some time with lists in the next couple of weeks, learning about their properties and how to work with them. An empty list can be created using square brackets: [ ]. Lists are ordered (based on their index value), and something can be inserted into a list by using the append() function. You can get the length of a list (or the number of elements in the list) using the function len(name of list). The following code creates an empty list called myList and then adds the string “hello” to this list:

>>>myList = [ ]
>>>myList.append("hello")

Try this in the little window in python. At this point, myList contains one element. Verify this by typing:

>>>myList

You should see a list consisting of one element, the word “hello”. If you type

>>>len(myList)

You should get 1. To see if you understand this, add the word “world” to myList. Verify that the length of myList is now 2.

>>>myList
>>>len(myList)

Type (don’t copy and paste, but actually type) Sample Program 4 into python, and run it (i.e. call this function) for various values of n. Does it produce the correct number of values? Look at the list to verify that it is doing what you expect it to. Be sure to think about each LINE of the program. Whenever you implement another person’s code, you should take the time to understand it, and play around with it to see how it can be modified to serve a similar purpose. You should understand the logic in the “while” statement. There may be other ways to loop through the process to generate a fixed number of values. Can you modify this code so that the range of values is always between 0 and 250? Can you modify this code so that the function uses a “for” loop rather than a “while” loop? These are rhetorical questions…no need to submit an answer here…at least, not yet. Here is where your fun begins!

Practice Problem 1

Write a function called randNum(n), which does what the previous sample code (Sample Program 4) does, but uses a “for loop” instead of a “while loop” to accomplish the same task. Think of the function randomNumbers(n) as a “helper function” in the sense that it will help you write more complex functions.

Practice Problem 2

Write a function called randNumMaxFor(n, maxValue), which generates a list of n random numbers between 0 and maxValue, inclusive. This function should use a “for loop” to generate the list.

Practice Problem 3

Write a function called randNumMaxWhile(n, maxValue), which generates a list of n random numbers between 0 and maxValue, inclusive. This function should use a “while loop” to generate the list.

Practice Problem 4

Write a function called randNumMinFor(n, minValue), which generates a list of n random numbers between minValue and 1000, inclusive. This function should use a “for loop” to generate the list.

Practice Problem 5

Write a function called randNumMinWhile(n, minValue), which generates a list of n random numbers between minValue and 1000, inclusive. This function should use a “while loop” to generate the list.

Practice Problem 6

Write a function called randNumMinMaxFor(n, minValue, maxValue), which generates a list of n random numbers between minValue and maxValue, inclusive. This function should use a “for loop” to generate the list.

Practice Problem 7

Write a function called randNumMinMaxWhile(n, minValue, maxValue), which generates a list of n random numbers between minValue and maxValue, inclusive. This function should use a “while loop” to generate the list.

Sample Program 5

Suppose that you want to write a function that takes, as arguments, a list of numbers and a target value, and counts the number of times that the target value appears in the list. The pseudocode description would look something like this:

initialize a counter to 0
for each element in the list:
compare the element with the target
if they are the same:
add 1 to the counter
return the value in the counter, which represents the number of values in the list that were equal to the target value

Turning this algorithm into Python is fairly straightforward. Be sure to pay close attention to the indentation in this program. In particular, note the indentation of the “return” statement.

1
2
3
4
5
6
7
8
9
10
11
12
# CS:1110 Introduction to Computer Science
# This takes, as arguments, two values: a list and a target value. It returns the
# number of times that the target value appears in the list.

def countTarget(myList, target):
#initialize the counter to zero
counter = 0
for element in myList:
#compare the value in the list to the target value...if they are the same, increment the counter
if element == target:
counter = counter + 1
return counter

I have mentioned the use of == as an equivalence operation: the == is used to check if the element on the left is equal to the element on the right. The result of this comparison is a Boolean: it will either be True or False. Note that we can’t use =, since for Python that means “assignment,” as in:

a = 10

So we need some other mechanism to indicate that we are comparing two items, not making an assignment: == fits that bill quite nicely. Type this into Wing and try to execute the code, just to make sure you understand how it’s supposed to work. Don’t just try to copy and paste it…you learn by typing! You’ll need to provide a list of values in order to test this function. The first program should help you with that. You can call functions that have been written earlier in the script in subsequent functions. To illustrate this structure:

1
2
3
4
5
6
7
8
9
10
def myFun(value1, value2):
return value1 * value2

def newFunction(number):
newVariable1 = myFun(4, number) #notice that I am calling myFun(value1, value2) here
newVariable2 = myFun(7, number) #and I am using specific values for value1 and value2
if (newVariable2 % newVariable1 == 0):
return "Yikes"
else:
return "Foo Bar"

Practice Problem 8

Modify Sample Program 5 so that instead of returning the number of times that the target value appears in the list, it returns the number of values in the list that are GREATER THAN the target value. Call this function countAboveTarget(myList, target). Keep in mind that this function trusts that whenever it is “called”, the user passes along a list and a target value. For example,

>>>countAboveTarget([1,2,3,4,5,3,4,2],4)

would return the value 1, because there is only one value in the list that is greater than 4.

Practice Problem 9

Modify my fifth sample function so that instead of returning the number of times that the target value appears in the list, it returns the number of values in the list that are LESS THAN the target value. Call this function countBelowTarget(myList, target). Keep in mind that this function trusts that whenever it is “called”, the user passes along a list and a target value. For example,

>>>countBelowTarget([1,2,3,4,5,3,4,2],4)

would return the value 5, because there are five values in the list that are less than 4.

Practice Problem 10

Write a function, called usingFunctionsGreater(n), that takes, as an argument, a positive integer n. It should do the following, in order:

  • Generate three random numbers between 200 and 625, inclusive. - For these three numbers, o identify the smallest random number and assign the value to the variable minValue, o identify the middle random number and assign the value to the variable myTarget, o identify the largest random number and assign the value to the variable maxValue. o NOTE: Do not use the built-in sorting function in Python to determine which values are the smallest, largest, or middle. Use conditional statements.
  • Next, call the function that you wrote in Practice Problem 7 to generate a list of n random numbers between minValue and maxValue, inclusive. Name the list that you create myList.
  • Pass myList and the value of myTarget, into the function that you wrote in Practice Problem 9 in order to find the number of elements in the list that are greater than myTarget. Return this value.

Be sure to name this function usingFunctionsGreater(n).

Practice Problem 11

Write a function, called usingFunctionsLess(n), that takes, as an argument, a positive integer n. It should do the following, in order:

  • Generate three random numbers between 200 and 625, inclusive.
  • For these three numbers:
    • Identify the smallest random number and assign its value to the variable minValue,
    • Identify the middle random number and assign its value to the variable myTarget,
    • Identify the largest random number and assign its value to the variable maxValue.
    • NOTE: use conditional statements to determine this order…do not use any built-in functions
  • Next, call the function that you wrote in Practice Problem 7 to generate a list of n random numbers between minValue and maxValue, inclusive. Name the list that you create myList.
  • Pass myList and the value of myTarget, into the function that you wrote in Practice Problem 9 in order to find the number of elements in the list that are less than myTarget. Return this value.

Be sure to name this function usingFunctionsLess(n).

Practice Problem 12

Write a function that takes, as an argument, a positive integer n. It should do the following, in order:

  • Call the function you wrote in Practice Problem 1, randomNum(n), to create a list consisting of n random numbers between 0 and 9.
  • Return the average of the numbers in the list.
    • NOTE: Do not use the built-in “sum” function in Python. You must write your own function that adds the values in the list together.

Name this function calculateAverage(n).

For example, calculateAverage(5) will use the function randomNum(5) to create a list consisting of 5 random numbers (say, [4, 5, 8, 3, 2]) and then it will calculate, and return, the average of these numbers (in this example, the average of the numbers in the list is 4.4). So in this example, the function would return the value 4.4.

That concludes the problems in this programming practice assignment. Remember that if you have any questions on these problems, be sure to ask the TAs for help. They will be going over these problems during the study groups during the week. You should save your program file, for future reference, using the naming convention LastNameFirstNamePP1.py. For example, if I were to save this file, I would name it SzecseiDenisePP1.py. Remember that if you are using a Mac, you need to include the extension when you save the file (so that Wing knows that it is a python program.