Make sure to review Midterm 1 and midterm 2, all samples for
midterms as well. Review all of the homework, class examples and
readings exercises. Make sure to do the readings as well and
review all of the class notes.
1) Given:
>>> a_list = ["a", "b", "c", "d", "e", "f"]
>>> a_list[1:3]
['b', 'c']
>>> a_list[:4]
['a', 'b', 'c', 'd']
>>> a_list[3:]
['d', 'e', 'f']
>>> a_list[:]
['a', 'b', 'c', 'd', 'e', 'f']
>>> a_list[-‐1]
[ 'f']
>>> a_list[::-‐1]
['f', 'e', 'd','c', 'b', a']
How do you reverse the list using one line? a_list.reverse()
How do you add the value 7 to the end of the list?
a_list.append(7)
How do you find in element ‘a’ exists in list?
If ‘a’ in a_list:
How do you count how many times the value ‘c’ exists?
print(a__list.count(‘f’))
How do you remove the value “d” from list?
a_list.remove(‘d’)
How do you find the length of the list?
Len(a_list)
1) Call a function to initialize a list randomly (values should be
between 1 and 100 inclusive and these values should be
divisible evenly by 3 and 5.
Then print the list.
import random
def rand(list):
for i in range(1,101,1):
# only select random numbers divisible evenly by 3 & 5
if (i%3 ==0 and i%5 ==0):
list.append(random.randint(1,10))
print("list in rand function: ", list)
def total(list):
''' function to print and compute total of elements in a list '''
tot=0
for item in list: tot += item
print("Total is: ", tot)
def main():
num =[]
print("list in main: ", num)
rand(num)# you are now passing the address in memory where list is stored print("list in main: ", num)
total(num)# compute total for all list values/elements
2) Read a list of words from file, and then search to see if that
list includes the word “Python”. Count how many times
“Python” appears in the file. If the word “python” appeared
in the file, then write “python” and the number of times the
word “python” appeared into a file?
def searchFile(oldFile, newFile): f1 = open(oldFile, "r") f2 = open(newFile, "w") count=0 while True: text = f1.readline() if text == "": break
if ("python" in text or "Python" in text): count += 1
f2.write(text) # if you find python then write it to file
if count > 0:
# print the count of Python in file
f2.write("The number of times python appeared in file is : " + str( count) + "\n") f1.close() f2.close() def main(): oldFile = "languages.txt" newFile = 'python.txt' searchFile(oldFile, newFile) main()
3) [Sale application] Write a program that will call a function to
decrease all of the list elements values (prices) by 40%
when the items are on sale. Then call another function to
increase all of the list elements values (prices) by 40% when
the sale is over.
def main():
prices = [100,20,50]
print ("Prices from main before function call: ", prices)
bf(prices)
print ("Prices from main after function bf call: ", prices)
orig(prices)
print ("Prices from main before function orig call: ", prices)
def bf(prices):
for i in range (len(prices)):
prices[i]= prices[i] *.6
def orig(prices):
for i in range (len(prices)):
prices[i]= prices[i]/.6
main()
4) Ask the user to enter integers 1 to 12 for the month. Then,
print the month such as January if the user entered 1 and
December if the user entered 12.
import random
def main():
monthNumber = input('Enter the month using a number from 1-‐ 12: ') mnumber= int(monthNumber)
months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'Oct','November', 'December'] print('You picked: '+ printMonth(months,mnumber))
# Select a month at random from months list
randomMonth = pickRandomMonth(months)
print("Month picked at random is: ", randomMonth)
def printMonth(months, mnumber): if mnumber < 1 or mnumber > 12: month = 'Error ' else: month = months[mnumber -‐ 1] return month def pickRandomMonth(months):
rnum = random.randint(1, (len(months)-‐1)) ranmonth = months[rnum] return ranmonth main()
5) Select a word from a list randomly and then ask the user to
guess it in three trials. Make sure to give hints on the 2
ndand
third trials such as the length of the string and the first
character of the word.
''' read files a list of words and then assign all of the words to a list
and then choose one word at random from the list. Then play a guess the secret word game in three trials.
'''
import random
names=[] #Global list
# function to read words from file and assign it to a list
def readfile(myfile): # read file
myfile = open(myfile, "r")
for line in myfile: name=line.rstrip('\n') names.append(name)
def game(word):
#play guess the secret word in 3 trials trial =1 secret="" secret= word.lower() keepgoing= True while(keepgoing):
guess = input("try to guess the secret word: ")
if ((guess.lower()) == secret):
print("Congratulations! You won in: ", trial, " trials") keepgoing = False
break
if trial == 3:
print("Sorry! You lost the game. You used all your three chances", ". The secret word is: ", word)
keepgoing = False break
else:
print("You have ", (3-‐ trial), " trials remaining!") trial += 1
# function to select one word at random from list def selectrandom():
word = random.choice(names)
print("word is :", word) return word
def main():
# printing words.txt (names)
print()
#call function to read from file words.txt readfile('words.txt')
#call function to select a word at random from list word = selectrandom() game(word) main()