docx

advertisement
Lab 3: Strings/While Loops
Due Sun, Nov 1 at midnight
For this lab, you must work with a partner. You should choose a new partner.
Remember to turn in your peer review .
All functions should be commented appropriately.
Create a file called lab3.py. Include as comments your name, your partner’s name, class time, TA’s name, and
lab due date. Then include and comment the following functions:
Note: Unless otherwise noted, always include comments for each function that include the input type(s), the
output type, how your function calculates, and then at least two test cases. If test cases aren’t possible because
of random numbers or user input, then give examples of what should happen.
Attendance week 1: 2 pts
Attendance week 2: 2 pts
Part 1: Convert the following recursive functions to while loops:
# Problem 1 (2 pts)
def f(x,y):
if (x == 0):
return(y)
else:
return(f(x-1,y+x))
print(f(5,0))
#Problem 2: (3 pts)
def g(x,y):
if y == len(x):
print()
return
else:
print(x[y],end = ", ")
return(g(x,y+1))
k = "cats"
g(k,0)
#Problem 3: (3 pts)
def h(x,y,a,b):
if x == 5:
return y
else:
if (x % 2 == 1):
k = randrange(0,len(a))
return h(x+1,y+ a[k],a,b)
else:
k = randrange(0,len(b))
return h(x+1,y+ b[k],a,b)
print(h(0,"","aeiou","bcdfghjklmnpqrstvwxyz"))
#Problem 4: (3 pts)
def j(x,y,z):
if y == 0:
return z
else:
k = randrange(0,len(x))
if x[k] not in z:
return(j(x,y-1,z+ x[k]))
else:
return(j(x,y,z))
print(j("vampire",len("vampire"),""))
#Problem 5 (3 pts)
def k(x,y):
if (x < 0):
return k(x*-1,y)
elif (x < 10):
return(y)
else:
return k(x//10,y+1)
print(k(-28417,1))
#Problem 6: (4 pts) Note: for this problem, you could convert the number to a string,
#and then use 'in'. Don't do that. Use a while loop instead. Don't use #break.
def m(x,y):
if (x <= 0):
return False
else:
if (x%10 == y):
return True
else:
return m(x//10,y)
print(m(3214,2))
print(m(4231,5))
Part 2: Do the following using While loops (no recursion!)
#Problem 7. (5 pts) When I was a kid, I used to speak a language we called “gibberish” to my friend when we
didn’t want adults to understand us. For this language, every vowel would be replaced with ithag and then the
vowel. So, for instance,
–
For instance, the word “cat” would become “cithagat”
–
Monkey would become “mithagonkithagey”
Write the comments with input, output, and test cases for a function that uses a while loop to create a new word
in the “gibberish” language. So every time a vowel is encountered in a word, it is replaced with “ithag”,then the
vowel, then the rest of the word.
Problem 8: (5 pts) Many digital identification numbers such as ISBNs, credit card numbers, bank routing
numbers, and UPCs, and even routing packets, are designed with an extra bit, known as a parity bit, that
helps detect (and sometimes correct) human entry errors. In this problem we will modify this a bit to
assume a simple check-digit algorithm:
Parity will be determined by adding all the digits in the number up, minus the last digit (the right-most
digit). If the digits add up to an even number and the right-most digit is a 0, then the number is most
likely okay. If all the digits add up to an odd number and the right-most digit is a 1, then most likely the
number is okay. If the digits don’t match the parity number, then the number has probably been
corrupted. If the parity number is anything other than a 1 or a 0, the parity number has been corrupted,
Otherwise, as far as we know, the number is okay.
Write a function (including comments) that uses a while loop to check the number’s validity using the
above checking system. This function will return a Boolean value.
Problem 9: Simple encryption.
Part a: (6 pts)You’re going to take the alphabet (as a string) and create a new, randomly scrambled
version of the alphabet. Each letter must only occur once in the new randomly scrambled version of the
alphabet. So, for instance, my input was:
z = "abcdefghijklmnopqrstuvwxyz"
f9(z,"")
and my returned string was:
“hsyevxgrjlpntfqbzwmkadocui”
Note: just use all small letters. Let’s not deal with capital letters.
Side Note: this is something that, when written in its simplest manner, is nicest when written with a while
loop. It could end up looping for a long time when trying to find the last few letters that must be added
to the encrypted string. We could improve efficiency greatly by creating a new string of leftover letters
whenever we’ve added over half the letters to the new string.
Part b: (7 pts) Now, using the encrypted string above as input to your new function you are about to
write, encrypt a word and return that word.
For this, the easiest way to do it is to use the index method, which is built into python.
Index returns the index of the first occurrence of a character in a string. So, for instance, using
the above string z with the alphabet in it, to find the location of the character f in z, you’d do the
following:
ind = z.index(‘f’)
And ind would now hold 5
So, using the encrypted string above, if the input was ‘cat’, the returned value would be: ‘yhk’.
Problem 10: (2 pts) A teacher may want students to practice their multiplication tables. Each week it’s a
different number. So for instance, one week the students should practice their 4s multiplication tables,
and the next week their 6s multiplication tables.
Write a function that takes as an input parameter an integer. The function then generates a random
number between 0 and 12 including 12. The function then uses the input command to ask the user,
“what is randnum times x?” where randnum is the random number generated, and x is the input
parameter. So, for instance, if the input parameter was 5, and the random number generated was 7,
the user would be asked, “what is 7 times 5?”
The function should then take the answer the user entered and check whether the user was correct or
not, returning a Boolean value with True if the user was correct, and False if the user was wrong.
10b. (5 pts) Now create an online test. This test function will take as an input parameter an integer the
test_num) representing number you are testing and an integer representing the number right
(num_right) the user must get before they can quit the test. In the function, you will call the function
you created above inside a loop. The loop will keep track of the number of times the student answered
correctly (e.g., True is returned from the above function). If the student answers num_right correctly in
a row, the function returns a string saying “Congratulations! You finished!” If, however, the student
gets one wrong before getting num_right correct in a row, the count starts over at 0. Thus, there is only
one way to get out of the loop, and that is for the user to get the answer correct num_right times in a
row.
Problem 11
Wacky BlackJack: (6 pts) You’re going to write a function with a while loop that sort of replicates playing
blackjack. Your function should generate random numbers between 1 and 11 until the user enters “no”
in response to the input command, “Do you wish to continue?”. The user wants to come as close to 21
as possible without going over. (The loop should keep track of the total and print it out before asking if
the user wants to continue). Once the user has decided not to continue (they entered, “no”), the
function should generate another random number (below the loop), this time between 15 and 26
(including 26). This is the “dealer’s hand”. The function should print out the dealer’s score. Then, if the
Dealer’s hand is over 21, the user automatically wins and a string should be returned saying that the
user won. If the Dealer’s hand is 21 or under, and the user’s hand is over 21, the dealer wins and a
string should be returned saying that the dealer won. If the dealer’s hand is 21 or under and it is greater
than the user’s hand, a string should be returned saying that the dealer won. If the user’s hand is 21 or
under and greater than or equal to the dealer’s hand (we’re giving the user the advantage here), a string
should be returned saying that the user won.
Part b: (6 pts)
Write a function that uses the input function to ask if the user wants to play another round. If they do, it
uses a while loop to allow the user to place a bet (again, using the input function). Then call the function
in 7a to play a round of wacky blackjack, and keep track of the total amount of money they have while
they play (e.g., if they win, they double their bet, and if they lose, they lose it from their total.) Within
the loop, the input function must be used to ask if the user wants to play another round. The while loop
will continue while the user says “yes” and has some money left. You can start them out with 100
dollars. (Note: you are in essence calling a loop within a loop here.)
Problem 12: Guess the number:
Part a (5 pts) Write a recursive function that takes as input parameters a number, and then 2 other
numbers x and y, and finally a count parameter.
1. It uses the user input function to ask the user to guess a number between x and y.
2.
If the random number is the same as the input parameter number, it returns a count of the
number of “guesses” the computer had to make.
3. If the random number is too high, it first prints (str(randnum) + “is too high!”) and then recurses
with the range x to y changing so that you only guess between x and the random number (you’d
have to increase your count).
4. Do the same if the guess is too low.
Part b: (7 pts)
Now write the same exact function using while loops.
Part c: (1 pt)
Which is easier, the recursive version or the while loop?
Part d: (3 pts)
If you choose your guesses wisely, given the range of numbers in which you are guessing (e,g., 0-100, 050, etc.) AT MOST how many guesses will you make (hint: how many numbers do you rule out after each
guess?)
As a mental exercise, in the last lab you created a fractal using recursion. How easy would this be to do
using while loops?
Problem 13: Nested Loops:
For these problems you MUST use nested loops – you cannot use string multiplication:
Part A(8):
Write a non-recursive function that takes as input parameters 2 numbers. It then generates x (the first
input parameter) random numbers between 0 and y (the second input parameter). For each random
number, it then prints out that many stars across the page (using end = “”). So, for example, if the input
parameters were 6 and 10, I might get an output looking like this:
******
*
****
***
*****
*****
Part B(8):
Print out the multiplication tables as follows, if the input parameters are 6 and 4, you’d print out:
1
2
3
4
5
6
_
_
_
_
_
_
1*|
1
2
3
4
5
6
2*|
2
4
6
8
10
12
3*|
3
6
9
12
15
18
4*|
4
8
12
16
20
24
Note: for this one, you will probably want to use the tab for formatting, e.g., (end=”\t”)
Part C (10):
Now, given an input parameter x, create an ‘x’ shape using nested loops. So for instance, if the input
parameter was 4, you’d print out:
*
*
*
*
* *
*
* *
*
*
*
*
Download