11. MIT_CS6001-Python#
11.1. Python basics#
a=3
a+2.0
import random
var_list=['panda', 'Panda', 'PANDA']
cute=0
regal=0
ugly=0
for i in range(100):
var=var_list[int(random.random()*3)]
if var=="panda":
print("Cute!")
cute+=1
elif var=="Panda":
print("Regal")
regal+=1
else:
print("Ugly...")
ugly+=1
print('Cute: '+str(cute))
print('Regal: '+str(regal))
print('Ugly: '+str(ugly))
if cute>=45:
print('Very cute!')
elif cute>=35:
print('Cute!')
if regal>=45:
print('Very regal')
elif regal>=35:
print('Regal')
if ugly>=45:
print('Very ugly...')
elif ugly>=35:
print('Ugly...')
n=0
while(n<5):
print(n)
n=n+1
a=a+1.0
a
a=3
3>4
4>+4
True or False
a=3
a==5.0
a=3
a==5.0
a
b=10
c=b>9
c
3+5.0
5/2
round(2.6)
5*2==5.0*2.0
'a'+'bc'
3*'bc'
'abcd'[2]
11.2. Simple program#
n=0
for n in range(5):
print(n)
n=n+1
mysum=0
for i in range(5,11,2):
mysum+=i
if mysum==5:
break
print(mysum)
import random
happy=random.random()*5
if int(happy)>2:
print('hello world')
end=6
n=1
total=0
while n<=end:
total+=n
n+=1
print(total)
num = 10
for num in range(5):
print(num)
print(num)
count = 0
for letter in 'Snow!':
print('Letter # ' + str(count) + ' is ' + str(letter))
count += 1
break
print(count)
num = 10
while True:
if num < 7:
print('Breaking out of loop')
break
print(num)
num -= 1
print('Outside of loop')
iteration = 0
count = 0
while iteration < 5:
for letter in "hello, world":
count += 1
print("Iteration " + str(iteration) + "; count is: " + str(count))
iteration += 1
for iteration in range(5):
count = 0
while True:
for letter in "hello, world":
count += 1
print("Iteration " + str(iteration) + "; count is: " + str(count))
break
for iteration in range(1):
count = 0
for i in range(1000):
for letter in "hello, world":
count += 1
print("Iteration " + str(iteration) + "; count is: " + str(count))
number = 0
for x in range(len(s)):
if s[x:x+3] == "bob":
number += 1
print('Number of times bob occurs is: '+str(number))
11.3. Structured Types#
s='pneumonoultramicroscopicsilicovolcanoconiosis'
tmp=s[0]
tmp1=[]
index=0
for index in range(len(s)-1):
if (s[index].lower() <= s[index+1].lower()):
tmp1 += s[index+1]
index +=1
if len(tmp)<len(tmp1):
print(tmp1)
['u', 'o', 'o', 'u', 't', 'm', 'r', 's', 'o', 'p', 's', 'l', 'o', 'v', 'n', 'o', 'o', 'o', 's', 's']
an_letters="aeiouAEIOU"
word=input("I will cheer for you! Enter a word: ")
times=int(input("Enthusiasm level (1-10): "))
i=0
while i<len(word):
char=word[i]
if char in an_letters:
print("Give me an "+char+"! "+char)
else:
print("Give me a "+char+"! "+char)
i+=1
print("What does that spell?")
for i in range(times):
print(word, "!!!")
iteration = 0
count = 0
while iteration < 5:
# the variable 'letter' in the loop stands for every
# character, including spaces and commas!
for letter in "hello, world":
count += 1
print("Iteration " + str(iteration) + "; count is: " + str(count))
iteration += 1
Iteration 0; count is: 12
Iteration 1; count is: 24
Iteration 2; count is: 36
Iteration 3; count is: 48
Iteration 4; count is: 60
iteration = 0
while iteration < 5:
count = 0
for letter in "hello, world":
count += 1
print("Iteration " + str(iteration) + "; count is: " + str(count))
iteration += 1
Iteration 0; count is: 12
Iteration 1; count is: 12
Iteration 2; count is: 12
Iteration 3; count is: 12
Iteration 4; count is: 12
iteration = 0
while iteration < 5:
count = 0
for letter in "hello, world":
count += 1
if iteration % 2 == 0:
break
print("Iteration " + str(iteration) + "; count is: " + str(count))
iteration += 1
Iteration 0; count is: 1
Iteration 1; count is: 12
Iteration 2; count is: 1
Iteration 3; count is: 12
Iteration 4; count is: 1
while True: # This will be an infinite loop.
try:
pass
except:
raise KeyError() # This won't be executed.
x = 25
epsilon = 0.01
step = 0.1
guess = 0.0
while guess <= x:
if abs(guess**2 -x) < epsilon:
break
else:
guess += step
if abs(guess**2 - x) >= epsilon:
print('failed')
else:
print('succeeded: ' + str(guess))
x = 25
epsilon = 0.01
step = 0.1
guess = 0.0
while guess <= x:
if abs(guess**2 -x) >= epsilon:
guess += step
if abs(guess**2 - x) >= epsilon:
print('failed')
else:
print('succeeded: ' + str(guess))
# Notice how if we have two print statements
print("Hi")
print("there")
# The output will have each string on a separate line:
print('')
# Now try adding the following:
print("Hi",end='')
print("there")
print("Hi",end='*')
print("there")
# The output will place the subsequent string on the same line
# and will connect the two prints with the character given by end
epsilon=0.0025
y=int(input('Enter integer'))
guess=y/2.0
numGuesses=0
while abs(guess*guess-y)>=epsilon:
numGuesses+=1
guess=guess-(((guess**2)-y)/(2*guess))
print('numGuesses='+str(numGuesses))
print('Square root of '+str(y)+' is about '+str(guess))
def a(x):
'''
x: int or float.
'''
return x + 1
def b(x):
'''
x: int or float.
'''
return x + 1.0
def c(x, y):
'''
x: int or float.
y: int or float.
'''
return x + y
def d(x, y):
'''
x: Can be of any type.
y: Can be of any type.
'''
return x > y
def e(x, y, z):
'''
x: Can be of any type.
y: Can be of any type.
z: Can be of any type.
'''
return x >= y and x <= z
def f(x, y):
'''
x: int or float.
y: int or float
'''
x + y - 2
print(a(5))
print(b(5))
print(c(5,7))
print(d(7,5))
print(e(7,5,11))
print(f(7,5))
decrypted_message='What is the decrypted message?'
words=decrypted_message.split()
print(words)
words='one two three four five six seven eight nine ten'
if 'one' in words:
print('True')
else:
print('False')
word=list('one two three four five six seven eight nine ten')
print(word)
def a(x, y, z):
if x:
return y
else:
return z
def b(q, r):
return a(q>r, q, r)
print(a(3>2, a, b))
def fib(x):
#returns fibonacci of x
if x==0 or x==1:
return 1
else:
return fib(x-1)+fib(x-2)
fib(1)
fib(2)
fib(0)
fib(12)
fib(24)
fib(36)
def fib3(x):
#returns fibonacci of x
if x==36:
return 24157817
elif x==37:
return 39088169
else:
return fib(x-1)+fib(x-2)
fib3(38)
fib(60)
def gcdIter(a, b):
'''
a, b: positive integers
returns: a positive integer, the greatest common divisor of a & b.
'''
# Your code here
testValue = min(a, b)
# Keep looping until testValue divides both a & b evenly
while a % testValue != 0 or b % testValue != 0:
testValue -= 1
return testValue
list=['h', 'g', 'd']
len(list)
def isWordGuessed(secretWord, lettersGuessed):
'''
secretWord: string, the word the user is guessing
lettersGuessed: list, what letters have been guessed so far
returns: boolean, True if all the letters of secretWord are in lettersGuessed;
False otherwise
'''
# FILL IN YOUR CODE HERE...
for x in range(len(secretWord)):
if secretWord[x] in lettersGuessed == False:
return False
elif x != len(secretWord)-1:
x+=1
else:
break
break
if secretWord[len(secretWord)-1] in lettersGuessed == False:
return False
else:
return True
print(isWordGuessed('waeguifgwe', ['g', 'a', 'i', 'k', 'd', 'c']))
alphabet = 'abcdefghijklmnopqrstuvwxyz'
def getAvailableLetters(lettersGuessed):
'''
lettersGuessed: list, what letters have been guessed so far
returns: string, comprised of letters that represents what letters have not
yet been guessed.
'''
# FILL IN YOUR CODE HERE...
for n in range(26):
if alphabet[n] in lettersGuessed == True:
alphabet.replace(alphabet[x], '')
break
break
print(alphabet)
lettersGuessed=['a', 'e', 'i', 'o', 'u']
getAvailableLetters(lettersGuessed)
alphabet[2]
x=684756534523542
epsilon=0.01
ans=(high+low)/2.0
while abs(ans**2-x)>=epsilon:
print('low =', low, 'high =', high, 'ans =', ans)
numGuesses+=1
if ans**2<x:
low=ans
else:
high=ans
ans=(high+low)/2.0
print('numGuesses =', numGuesses)
print(ans, 'is close to square root of', x)
#Newton-Raphson for square root
epsilon=0.01
k=24.0
while abs(guess*guess-k)>=epsilon:
guess=guess-(((guess**2)-k)/(2*guess))
numGuesses+=1
print('Number of guesses:', numGuesses)
print('Square root of', k, 'is about', guess)
round(5.5436274587)
t1=(1, 'two', [3, 'three'])
print(t1)
type(t1[2])
t2=('1', 3, 'one')
type(t2)
print(t2[1])
l1=[1, 3, 'three', 'one']
type(l1)
print(l1[1])
string=('n48fh38')
type(string)
print(string[5])
l2=[(1, 'one', 3, 'three'), 2, 5, 'two', 'four']
type(l2)
type(l2[0])
def Square(x):
return SquareHelper(abs(x), abs(x))
def SquareHelper(n, x):
if n == 0:
return 0
return SquareHelper(n-1, x) + x
Square(353)
def f(x):
a = []
while x > 0:
a.append(x)
f(x-1)
type(f(x))
def myLog(x, b):
logarithm=0
while x>=b:
logarithm+=1
x/=b
return logarithm
myLog(68, 3)
def getSublists(L,n):
if n==len(L):
return L
else:
result = [L[i:i+n] for i in range(len(L) - n + 1)]
return result
L=[4, 5, 7, 3, 8, 3, 8]
n=4
getSublists(L, n)
def unique_keys(aDict):
value_count = {}
unique_keys_list = []
for key, value in aDict.items():
value_count[value] = value_count.get(value, 0) + 1
for key, value in aDict.items():
if value_count[value] == 1:
unique_keys_list.append(key)
return sorted(unique_keys_list)
def general_poly(L):
def polynomial_function(x):
result = 0
k = len(L) - 1
for coefficient in L:
result += coefficient * (x ** k)
k -= 1
return result
return polynomial_function
general_poly([1, 0, 0, 1, 0, 1, 0])(2)
try:
a=int(input("Tell me one number:"))
b=int(input("Tell me another number:"))
print(a/b)
print("Okay")
except:
print("Bug in user input")
print("Outside")
try:
a=int(input("Tell me one number:"))
b=int(input("Tell me another number"))
print("a/b = ", a/b)
print("a+b = ", a+b)
except ValueError:
print("could not convert to number")
except ZeroDivisionError:
print("cannot divide by 0")
except:
print("something else went very wrong")
def fancy_divide(numbers,index):
try:
denom = numbers[index]
for i in range(len(numbers)):
numbers[i] /= denom
except IndexError:
print("-1")
else:
print("1")
finally:
print("0")
fancy_divide([0, 2, 4], 1)
import random
import string
VOWELS = 'aeiou'
CONSONANTS = 'bcdfghjklmnpqrstvwxyz'
HAND_SIZE = 7
SCRABBLE_LETTER_VALUES = {
'a': 1, 'b': 3, 'c': 3, 'd': 2, 'e': 1, 'f': 4, 'g': 2, 'h': 4, 'i': 1, 'j': 8, 'k': 5, 'l': 1, 'm': 3, 'n': 1, 'o': 1, 'p': 3, 'q': 10, 'r': 1, 's': 1, 't': 1, 'u': 1, 'v': 4, 'w': 4, 'x': 8, 'y': 4, 'z': 10
}
# -----------------------------------
# Helper code
# (you don't need to understand this helper code)
WORDLIST_FILENAME = "words.txt"
def loadWords():
"""
Returns a list of valid words. Words are strings of lowercase letters.
Depending on the size of the word list, this function may
take a while to finish.
"""
print("Loading word list from file...")
# inFile: file
inFile = open(WORDLIST_FILENAME, 'r')
# wordList: list of strings
wordList = []
for line in inFile:
wordList.append(line.strip().lower())
print(" ", len(wordList), "words loaded.")
return wordList
def getFrequencyDict(sequence):
"""
Returns a dictionary where the keys are elements of the sequence
and the values are integer counts, for the number of times that
an element is repeated in the sequence.
sequence: string or list
return: dictionary
"""
# freqs: dictionary (element_type -> int)
freq = {}
for x in sequence:
freq[x] = freq.get(x,0) + 1
return freq
# (end of helper code)
# -----------------------------------
#
# Problem #1: Scoring a word
#
def getWordScore(word, n):
"""
Returns the score for a word. Assumes the word is a valid word.
The score for a word is the sum of the points for letters in the
word, multiplied by the length of the word, PLUS 50 points if all n
letters are used on the first turn.
Letters are scored as in Scrabble; A is worth 1, B is worth 3, C is
worth 3, D is worth 2, E is worth 1, and so on (see SCRABBLE_LETTER_VALUES)
word: string (lowercase letters)
n: integer (HAND_SIZE; i.e., hand size required for additional points)
returns: int >= 0
"""
score=0
word.lower()
for char in word:
score+=SCRABBLE_LETTER_VALUES[char]
score*=len(word)
if len(word)==n:
score+=50
return score
getWordScore('waybill', 7)
def displayHand(hand):
"""
Displays the letters currently in the hand.
For example:
>>> displayHand({'a':1, 'x':2, 'l':3, 'e':1})
Should print out something like:
a x x l l l e
The order of the letters is unimportant.
hand: dictionary (string -> int)
"""
for letter in hand.keys():
for j in range(hand[letter]):
print(letter,end=" ") # print all on the same line
print()
hand={'a': 1, 'e': 2, 's': 1}
displayHand(hand)
# The 6.00 Word Game
import random
import string
VOWELS = 'aeiou'
CONSONANTS = 'bcdfghjklmnpqrstvwxyz'
HAND_SIZE = 7
SCRABBLE_LETTER_VALUES = {
'a': 1, 'b': 3, 'c': 3, 'd': 2, 'e': 1, 'f': 4, 'g': 2, 'h': 4, 'i': 1, 'j': 8, 'k': 5, 'l': 1, 'm': 3, 'n': 1, 'o': 1, 'p': 3, 'q': 10, 'r': 1, 's': 1, 't': 1, 'u': 1, 'v': 4, 'w': 4, 'x': 8, 'y': 4, 'z': 10
}
# -----------------------------------
# Helper code
# (you don't need to understand this helper code)
WORDLIST_FILENAME = "words.txt"
def loadWords():
"""
Returns a list of valid words. Words are strings of lowercase letters.
Depending on the size of the word list, this function may
take a while to finish.
"""
print("Loading word list from file...")
# inFile: file
inFile = open(WORDLIST_FILENAME, 'r')
# wordList: list of strings
wordList = []
for line in inFile:
wordList.append(line.strip().lower())
print(" ", len(wordList), "words loaded.")
return wordList
def getFrequencyDict(sequence):
"""
Returns a dictionary where the keys are elements of the sequence
and the values are integer counts, for the number of times that
an element is repeated in the sequence.
sequence: string or list
return: dictionary
"""
# freqs: dictionary (element_type -> int)
freq = {}
for x in sequence:
freq[x] = freq.get(x,0) + 1
return freq
# (end of helper code)
# -----------------------------------
#
# Problem #1: Scoring a word
#
def getWordScore(word, n):
"""
Returns the score for a word. Assumes the word is a valid word.
The score for a word is the sum of the points for letters in the
word, multiplied by the length of the word, PLUS 50 points if all n
letters are used on the first turn.
Letters are scored as in Scrabble; A is worth 1, B is worth 3, C is
worth 3, D is worth 2, E is worth 1, and so on (see SCRABBLE_LETTER_VALUES)
word: string (lowercase letters)
n: integer (HAND_SIZE; i.e., hand size required for additional points)
returns: int >= 0
"""
score=0
if len(word)==n:
score+=50
word.lower()
for char in word:
score+=SCRABBLE_LETTER_VALUES[char]
return score
#
# Problem #2: Make sure you understand how this function works and what it does!
#
def displayHand(hand):
"""
Displays the letters currently in the hand.
For example:
>>> displayHand({'a':1, 'x':2, 'l':3, 'e':1})
Should print out something like:
a x x l l l e
The order of the letters is unimportant.
hand: dictionary (string -> int)
"""
for letter in hand.keys():
for j in range(hand[letter]):
print(letter,end=" ") # print all on the same line
print() # print an empty line
#
# Problem #2: Make sure you understand how this function works and what it does!
#
def dealHand(n):
"""
Returns a random hand containing n lowercase letters.
At least n/3 the letters in the hand should be VOWELS.
Hands are represented as dictionaries. The keys are
letters and the values are the number of times the
particular letter is repeated in that hand.
n: int >= 0
returns: dictionary (string -> int)
"""
hand={}
numVowels = n // 3
for i in range(numVowels):
x = VOWELS[random.randrange(0,len(VOWELS))]
hand[x] = hand.get(x, 0) + 1
for i in range(numVowels, n):
x = CONSONANTS[random.randrange(0,len(CONSONANTS))]
hand[x] = hand.get(x, 0) + 1
return hand
#
# Problem #2: Update a hand by removing letters
#
def updateHand(hand, word):
"""
Assumes that 'hand' has all the letters in word.
In other words, this assumes that however many times
a letter appears in 'word', 'hand' has at least as
many of that letter in it.
Updates the hand: uses up the letters in the given word
and returns the new hand, without those letters in it.
Has no side effects: does not modify hand.
word: string
hand: dictionary (string -> int)
returns: dictionary (string -> int)
"""
for letter in hand:
if letter in word:
updatedHand[letter] -= word.count(letter)
if updatedHand[letter] <= 0:
del updatedHand[letter]
return updatedHand # Return the updated hand after processing the word
#
# Problem #3: Test word validity
#
def isValidWord(word, hand, wordList):
"""
Returns True if word is in the wordList and is entirely
composed of letters in the hand. Otherwise, returns False.
Does not mutate hand or wordList.
word: string
hand: dictionary (string -> int)
wordList: list of lowercase strings
"""
if word in wordList==False:
return False
for char in word:
if char in hand==False:
return False
return True
#
# Problem #4: Playing a hand
#
def calculateHandlen(hand):
"""
Returns the length (number of letters) in the current hand.
hand: dictionary (string-> int)
returns: integer
"""
def playHand(hand, wordList, n):
total_score = 0
while calculateHandlen(hand) > 0:
print("Current Hand:", end=" ")
displayHand(hand)
word = input('Enter word, or a "." to indicate that you are finished: ')
if word == '.':
break
if not isValidWord(word, hand, wordList):
print("Invalid word, please try again.")
continue
score = getWordScore(word, n)
total_score += score
print('"{}" earned {} points. Total: {} points'.format(word, score, total_score))
hand = updateHand(hand, word)
print("Total score:", total_score)
a='a'
b='b'
a=b
a
11.4. OOP(Object Oriented Programming)#
11.4.1. Classes and inheritance#
class Clock(object):
def __init__(self, time):
self.time = time
def print_time(self):
time = '6:30'
print(self.time)
clock = Clock('5:30')
clock.print_time()
class Clock(object):
def __init__(self, time):
self.time = time
def print_time(self, time):
print(time)
clock = Clock('5:30')
clock.print_time('10:30')
class Weird(object):
def __init__(self, x, y):
self.y = y
self.x = x
def getX(self):
return x
def getY(self):
return y
class Wild(object):
def __init__(self, x, y):
self.y = y
self.x = x
def getX(self):
return self.x
def getY(self):
return self.y
X = 7
Y = 8
w1 = Weird(X, Y)
print(w1.getX())
print(w1.getY())
w2 = Wild(X, Y)
print(w2.getX())
print(w2.getY())
w3 = Wild(17, 18)
print(w3.getX())
w4 = Wild(X, 18)
print(w4.getX())
X = w4.getX() + w3.getX() + w2.getX()
print(X)
print(w4.getX())
Y = w4.getY() + w3.getY()
Y = Y + w2.getY()
print(Y)
print(w2.getY())
print(w4.getY())
11.4.2. An extended example#
class Spell(object):
def __init__(self, incantation, name):
self.name = name
self.incantation = incantation
def __str__(self):
return self.name + ' ' + self.incantation + '\n' + self.getDescription()
def getDescription(self):
return 'No description'
def execute(self):
print(self.incantation)
class Accio(Spell):
def __init__(self):
Spell.__init__(self, 'Accio', 'Summoning Charm')
class Confundo(Spell):
def __init__(self):
Spell.__init__(self, 'Confundo', 'Confundus Charm')
def getDescription(self):
return 'Causes the victim to become confused and befuddled.'
def studySpell(spell):
print(spell)
spell = Accio()
spell.execute()
studySpell(spell)
studySpell(Confundo())
class A(object):
def __init__(self):
self.a = 1
def x(self):
print("A.x")
def y(self):
print("A.y")
def z(self):
print("A.z")
class B(A):
def __init__(self):
A.__init__(self)
self.a = 2
self.b = 3
def y(self):
print("B.y")
def z(self):
print("B.z")
class C(object):
def __init__(self):
self.a = 4
self.c = 5
def y(self):
print("C.y")
def z(self):
print("C.z")
class D(C, B):
def __init__(self):
C.__init__(self)
B.__init__(self)
self.d = 6
def z(self):
print("D.z")
obj = D()
print(obj.c)
print(obj.d)
obj.x()
print(5)
from random import *
rav4_times=0
corolla_times=0
zst_times=0
zs_times=0
rav4_most=0
corolla_most=0
zst_most=0
zs_most=0
for i in range(20):
for i in range(2500):
types_of_makes=['Toyota', 'MG']
type_of_models=['Corolla', 'Rav4']
types_of_models=['ZST', 'ZS']
typeCar=types_of_makes[int(random()*2)]
if typeCar=='Toyota':
typeModel=type_of_models[int(random()*2)]
else:
typeModel=types_of_models[int(random()*2)]
if typeModel=='Rav4':
rav4_times+=1
elif typeModel=='Corolla':
corolla_times+=1
elif typeModel=='ZST':
zst_times+=1
else:
zs_times+=1
print(typeCar+', '+typeModel+', 2020')
print('Rav4_times: '+str(rav4_times))
print('Corolla_times: '+str(corolla_times))
print('ZST_times: '+str(zst_times))
print('ZS_times: '+str(zs_times))
if rav4_times>=corolla_times and rav4_times>=zs_times and rav4_times>=zst_times:
print('Most Rav4s')
rav4_most+=1
elif corolla_times>=rav4_times and corolla_times>=zs_times and corolla_times>=zst_times:
print('Most Corollas')
corolla_most+=1
elif zst_times>=rav4_times and zst_times>=corolla_times and zst_times>=zs_times:
print('Most ZSTs')
zst_most+=1
else:
print('Most ZSes')
zs_most+=1
print('Rav4_times: '+str(rav4_times))
print('Corolla_times: '+str(corolla_times))
print('ZST_times: '+str(zst_times))
print('ZS_times: '+str(zs_times))
if rav4_most>=corolla_most and rav4_most>=zs_most and rav4_most>=zst_most:
print('Most Rav4s overall')
elif corolla_most>=rav4_most and corolla_most>=zs_most and corolla_most>=zst_most:
print('Most Corollas overall')
elif zst_most>=rav4_most and zst_most>=corolla_most and zst_most>=zs_most:
print('Most ZSTs overall')
else:
print('Most ZSes overall')
def generator1():
if True:
yield 1
def generator2():
if False:
yield 1
g1 = generator1()
g2 = generator2()
print(type(g1))
print(type(g2))
def genPrimesFn():
'''Function to return 1000000 prime numbers'''
primes = [] # primes generated so far
last = 1 # last number tried
while len(primes) < 1000000:
last += 1
for p in primes:
if last % p == 0:
break
else:
primes.append(last)
return primes
def genPrimesFn():
'''Function to print every 10th prime
number, until you've printed 20 of them.'''
primes = [] # primes generated so far
last = 1 # last number tried
counter = 1
while True:
last += 1
for p in primes:
if last % p == 0:
break
else:
primes.append(last)
counter += 1
if counter % 10 == 0:
# Print every 10th prime
print(last)
if counter % (20*10) == 0:
# Quit when we've printed the 10th prime 20 times (ie we've
# printed the 200th prime)
return
def genPrimesFn():
'''Function to keep printing the prime number until the user stops the program.
This way uses user input; you can also just run an infinite loop (while True)
that the user can quit out of by hitting control-c'''
primes = [] # primes generated so far
last = 1 # last number tried
uinp = 'y' # Assume we want to at least print the first prime...
while uinp != 'n':
last += 1
for p in primes:
if last % p == 0:
break
else:
primes.append(last)
print(last)
uinp = input("Print the next prime? [y/n] ")
while uinp != 'y' and uinp != 'n':
print("Sorry, I did not understand your input. Please enter 'y' for yes, or 'n' for no.")
uinp = input("Print the next prime? [y/n] ")
import string
print(string.ascii_lowercase)
print(string.ascii_uppercase)
import string
alphabet = string.ascii_lowercase
shift = 17
letter = 'a'
position = alphabet.index(letter)
shifted_position = (position + shift) % 26
shifted_letter = alphabet[shifted_position]
print(shifted_letter)
def build_shift_dict(shift):
shift_dict = {}
alphabet = string.ascii_lowercase + string.ascii_uppercase
for letter in alphabet:
if letter.islower():
base = ord('a')
else:
base = ord('A')
position = ord(letter) - base
shifted_position = (position + shift) % 26
shifted_letter = chr(base + shifted_position)
shift_dict[letter] = shifted_letter
return shift_dict
# Test the function
shift_amount = 3
shifted_dict = build_shift_dict(shift_amount)
print(shifted_dict)
'pneumonoultramicroscopicsilicovolcanoconiosis'.split('h')
import string
### DO NOT MODIFY THIS FUNCTION ###
def load_words(file_name):
'''
file_name (string): the name of the file containing
the list of words to load
Returns: a list of valid words. Words are strings of lowercase letters.
Depending on the size of the word list, this function may
take a while to finish.
'''
print('Loading word list from file...')
# inFile: file
in_file = open(file_name, 'r')
# line: string
line = in_file.readline()
# word_list: list of strings
word_list = line.split()
print(' ', len(word_list), 'words loaded.')
in_file.close()
return word_list
### DO NOT MODIFY THIS FUNCTION ###
def is_word(word_list, word):
'''
Determines if word is a valid word, ignoring
capitalization and punctuation
word_list (list): list of words in the dictionary.
word (string): a possible word.
Returns: True if word is in word_list, False otherwise
Example:
>>> is_word(word_list, 'bat') returns
True
>>> is_word(word_list, 'asdf') returns
False
'''
word = word.lower()
word = word.strip(" !@#$%^&*()-_+={}[]|\:;'<>?,./\"")
return word in word_list
### DO NOT MODIFY THIS FUNCTION ###
def get_story_string():
"""
Returns: a joke in encrypted text.
"""
f = open("story.txt", "r")
story = str(f.read())
f.close()
return story
WORDLIST_FILENAME = 'words.txt'
class Message(object):
### DO NOT MODIFY THIS METHOD ###
def __init__(self, text):
'''
Initializes a Message object
text (string): the message's text
a Message object has two attributes:
self.message_text (string, determined by input text)
self.valid_words (list, determined using helper function load_words
'''
self.message_text = text
self.valid_words = load_words(WORDLIST_FILENAME)
### DO NOT MODIFY THIS METHOD ###
def get_message_text(self):
'''
Used to safely access self.message_text outside of the class
Returns: self.message_text
'''
return self.message_text
### DO NOT MODIFY THIS METHOD ###
def get_valid_words(self):
'''
Used to safely access a copy of self.valid_words outside of the class
Returns: a COPY of self.valid_words
'''
return self.valid_words[:]
def build_shift_dict(self, shift):
'''
Creates a dictionary that can be used to apply a cipher to a letter.
The dictionary maps every uppercase and lowercase letter to a
character shifted down the alphabet by the input shift. The dictionary
should have 52 keys of all the uppercase letters and all the lowercase
letters only.
shift (integer): the amount by which to shift every letter of the
alphabet. 0 <= shift < 26
Returns: a dictionary mapping a letter (string) to
another letter (string).
'''
shift_dict = {}
alphabet = string.ascii_lowercase + string.ascii_uppercase
for letter in alphabet:
if letter.islower():
base = ord('a')
else:
base = ord('A')
position = ord(letter) - base
shifted_position = (position + shift) % 26
shifted_letter = chr(base + shifted_position)
shift_dict[letter] = shifted_letter
return shift_dict
def apply_shift(self, shift):
'''
Applies the Caesar Cipher to self.message_text with the input shift.
Creates a new string that is self.message_text shifted down the
alphabet by some number of characters determined by the input shift
shift (integer): the shift with which to encrypt the message.
0 <= shift < 26
Returns: the message text (string) in which every character is shifted
down the alphabet by the input shift
'''
shifted_text = ""
for char in self.message_text:
if char.isalpha():
if char.islower():
shifted_text += chr((ord(char) - ord('a') + shift) % 26 + ord('a'))
elif char.isupper():
shifted_text += chr((ord(char) - ord('A') + shift) % 26 + ord('A'))
else:
shifted_text += char
return shifted_text
class PlaintextMessage(Message):
def __init__(self, text, shift):
'''
Initializes a PlaintextMessage object
text (string): the message's text
shift (integer): the shift associated with this message
A PlaintextMessage object inherits from Message and has five attributes:
self.message_text (string, determined by input text)
self.valid_words (list, determined using helper function load_words)
self.shift (integer, determined by input shift)
self.encrypting_dict (dictionary, built using shift)
self.message_text_encrypted (string, created using shift)
Hint: consider using the parent class constructor so less
code is repeated
'''
Message.__init__(self, text) # Call the parent class constructor
self.shift = shift
self.encrypting_dict = self.build_shift_dict(shift)
self.message_text_encrypted = self.apply_shift(shift)
def get_shift(self):
'''
Used to safely access self.shift outside of the class
Returns: self.shift
'''
def get_encrypting_dict(self):
'''
Used to safely access a copy self.encrypting_dict outside of the class
Returns: a COPY of self.encrypting_dict
'''
def get_message_text_encrypted(self):
'''
Used to safely access self.message_text_encrypted outside of the class
Returns: self.message_text_encrypted
'''
def change_shift(self, shift):
'''
Changes self.shift of the PlaintextMessage and updates other
attributes determined by shift (ie. self.encrypting_dict and
message_text_encrypted).
shift (integer): the new shift that should be associated with this message.
0 <= shift < 26
Returns: nothing
'''
self.shift=shift
self.apply_shift(shift)
class CiphertextMessage(Message):
def __init__(self, text):
'''
Initializes a CiphertextMessage object
text (string): the message's text
a CiphertextMessage object has two attributes:
self.message_text (string, determined by input text)
self.valid_words (list, determined using helper function load_words)
'''
self.message_text = text
self.valid_words = load_words('words.txt')
def decrypt_message(self):
'''
Decrypt self.message_text by trying every possible shift value
and find the "best" one. We will define "best" as the shift that
creates the maximum number of real words when we use apply_shift(shift)
on the message text. If s is the original shift value used to encrypt
the message, then we would expect 26 - s to be the best shift value
for decrypting it.
Note: if multiple shifts are equally good such that they all create
the maximum number of you may choose any of those shifts (and their
corresponding decrypted messages) to return
Returns: a tuple of the best shift value used to decrypt the message
and the decrypted message text using that shift value
'''
total=0
max_real_words=0
for shift in range(26):
decrypted_message = self.apply_shift(26 - shift)
words = decrypted_message.split()
for word in words:
if word in self.valid_words:
total+=1
if total > max_real_words:
max_real_words = total
best_shift = 26 - shift
decrypted_text = decrypted_message
return (best_shift, decrypted_text)
#Example test case (PlaintextMessage)
plaintext = PlaintextMessage('hello', 2)
print('Expected Output: jgnnq')
print('Actual Output:', plaintext.get_message_text_encrypted())
#Example test case (CiphertextMessage)
ciphertext = CiphertextMessage('jgnnq')
print('Expected Output:', (24, 'hello'))
print('Actual Output:', ciphertext.decrypt_message())
plaintext = PlaintextMessage('hello', 2)
print('Expected Output: jgnnq')
print('Actual Output:', plaintext.get_message_text_encrypted())
class Animal(object):
def __init__(self, age):
self.age=age
self.name=None
def get_age(self):
return self.age
def get_name(self):
return self.name
def set_age(self, newage):
self.age=newage
def set_name(self, newname=''):
self.name=newname
def __str__(self):
return 'animal:'+str(self.name)+':'+str(self.age)
class Rabbit(Animal):
tag=1
def __init__(self, age, parent1=None, parent2=None):
Animal.__init__(self, age)
self.parent1=parent1
self.parent2=parent2
self.rid=Rabbit.tag
Rabbit.tag+=1
def get_rid(self):
return str(self.rid).zfill(3)
def get_parent1(self):
return self.parent1
def get_parent2(self):
return self.parent2
peter=Rabbit(2)
peter.set_name('Peter')
print(peter)
hopsy=Rabbit(3)
hopsy.set_name('Hopsy')
print(hopsy)
cotton=Rabbit(1, peter, hopsy)
cotton.set_name('Cottontail')
print(cotton)
11.5. Algorithmic Complexity#
11.5.1. Computational Complexity#
def search_for_elmt(L, e):
for i in L:
if i==e:
return True
return False
# Example case below
L=[]
n=1
for i in range(100000000):
L.append(n)
n+=1
e=187376452367454457654574756465745647
search_for_elmt(L, e)
def lenRecur(s):
answer=0
while True:
if s == '':
return answer
while s != '':
answer+=20
s=s[20:]
def fact_iter(n):
# assumes n an int>=0
answer=1
while n>1:
answer*=n
n-=1
return answer
fact_iter(99999)
def intToStr(i):
digits='0123456789'
if i ==0:
return '0'
result=''
while i>0:
result=digits[i%10]+result
i=i//10
return result
intToStr(9)
def genSubsets(L):
res=[]
if len(L)==0:
return[[]]
smaller=genSubsets(L[:-1])
extra=L[-1:]
new=[]
for small in smaller:
new.append(small+extra)
return smaller+new
L=[1, 2, 3, 4]
genSubsets(L)
def h(n):
answer=0
s=str(n)
for c in s:
answer+=int(c)
return answer
h(1234567890)
n=0
def modten(n):
print(n&10)
return n%10
for i in range(25):
n+=1
modten(n)
11.5.2. Searching and Sorting Algorithms#
def foo(L):
val = L[0]
while (True):
val = L[val]
a = [1, 2, 3, 4, 0]
b = [3, 0, 2, 4, 1]
c = [3, 2, 4, 1, 5]
foo(a)
num = 5
L = [2, 0, 1, 5, 3, 4]
val = 0
for i in range(0, num):
val = L[L[val]]
print(val)
from random import *
score=0
door_num=[1, 2, 3, 4, 5, 6, 7, 8, 9, 0]
brave=True
while brave:
ghost_door=door_num[randint(0, 9)]
door=int(input('Enter an integer between 0 and 9'))
if ghost_door==door:
brave=False
break
print('Lucky')
score+=1
print('Unlucky')
print(score)
def search(L, e):
for i in range(len(L)):
if L[i] == e:
return True
if L[i] > e:
return False
return False
def search1(L, e):
for i in L:
if i == e:
return True
if i > e:
return False
return False
def search2(L, e):
for i in L:
if i == e:
return True
elif i > e:
return False
return False
L=[1, 2, 3, 4, 5]
search2(L, 6)
def play_game():
score=0
health=100
shots=20
damage=5
damages=10
passcodes=[1, 2, 3]
while shots>0 and health>0:
passcode=randint(1, 3)
password=int(input('Enter integer from 1 to 3'))
password1=int(input('Enter a different integer from 1 to 3'))
if passcode==password:
print('Direct shot')
health-=damages
elif password1==passcode:
print('Hit')
health-=damage
else:
print('Missed')
shots-=1
print(health)
print(shots)
if health<=0:
print('You won')
elif shots==0:
print('You died')
from random import *
play_game()
def selSort(L):
for i in range(len(L) - 1):
minIndx = i
minVal = L[i]
j = i+1
while j < len(L):
if minVal > L[j]:
minIndx = j
minVal = L[j]
j += 1
if minIndx != i:
temp = L[i]
L[i] = L[minIndx]
L[minIndx] = temp
def newSort(L):
for i in range(len(L) - 1):
j=i+1
while j < len(L):
if L[i] > L[j]:
temp = L[i]
L[i] = L[j]
L[j] = temp
j += 1
def newSort(L):
for i in range(len(L) - 1):
j=i+1
while j < len(L):
if L[i] > L[j]:
temp = L[i]
L[i] = L[j]
L[j] = temp
j += 1
def merge(left, right):
result=[]
i, j=0, 0
while i<len(left) and j<len(right):
if left[i]<right[j]:
result.append(left[i])
i+=1
else:
result.append(right[j])
j+=1
while (i<len(left)):
result.append(left[i])
i+=1
while (j<len(right)):
result.append(right[j])
j+=1
return result
def bubble_sort(L):
swap = True
while swap:
swap = False
for j in range(1, len(L)):
if L[j - 1] > L[j]:
swap = True
# Swap elements
L[j - 1], L[j] = L[j], L[j - 1]
left=[1, 9, 4, 7, 3, 8, 0]
right=[6, 2, 9, 4, 3, 0, 1, 8, 5]
merge(left, right)
# The 6.00 Word Game
import random
import string
VOWELS = 'aeiou'
CONSONANTS = 'bcdfghjklmnpqrstvwxyz'
HAND_SIZE = 7
SCRABBLE_LETTER_VALUES = {
'a': 1, 'b': 3, 'c': 3, 'd': 2, 'e': 1, 'f': 4, 'g': 2, 'h': 4, 'i': 1, 'j': 8, 'k': 5, 'l': 1, 'm': 3, 'n': 1, 'o': 1, 'p': 3, 'q': 10, 'r': 1, 's': 1, 't': 1, 'u': 1, 'v': 4, 'w': 4, 'x': 8, 'y': 4, 'z': 10
}
Letters=['e', 'e', 'e', 'e', 'e', 'e', 'e', 'e', 'e', 'e', 'e', 'e', 'a', 'a', 'a', 'a', 'a', 'a', 'a', 'a', 'a', 'i', 'i', 'i', 'i', 'i', 'i', 'i', 'i', 'i', 'o', 'o', 'o', 'o', 'o', 'o', 'o', 'o', 'n', 'n', 'n', 'n', 'n', 'n', 'r', 'r', 'r', 'r', 'r', 'r', 't', 't', 't', 't', 't', 't', 'l', 'l', 'l', 'l', 's', 's', 's', 's', 'u', 'u', 'u', 'u', 'd', 'd', 'd', 'd', 'g', 'g', 'g', 'b', 'b', 'c', 'c', 'm', 'm', 'p', 'p', 'f', 'f', 'h', 'h', 'v', 'v', 'w', 'w', 'y', 'y', 'k', 'j', 'x', 'q', 'z']
# -----------------------------------
# Helper code
# (you don't need to understand this helper code)
WORDLIST_FILENAME = "words.txt"
def loadWords():
"""
Returns a list of valid words. Words are strings of lowercase letters.
Depending on the size of the word list, this function may
take a while to finish.
"""
print("Loading word list from file...")
# inFile: file
inFile = open('words.txt', 'r')
# wordList: list of strings
wordList = []
for line in inFile:
wordList.append(line.strip().lower())
print(" ", len(wordList), "words loaded.")
return wordList
def getFrequencyDict(sequence):
"""
Returns a dictionary where the keys are elements of the sequence
and the values are integer counts, for the number of times that
an element is repeated in the sequence.
sequence: string or list
return: dictionary
"""
# freqs: dictionary (element_type -> int)
freq = {}
for x in sequence:
freq[x] = freq.get(x,0) + 1
return freq
# (end of helper code)
# -----------------------------------
#
def getWordScore(word, n):
"""
Returns the score for a word. Assumes the word is a valid word.
The score for a word is the sum of the points for letters in the
word, multiplied by the length of the word, PLUS 50 points if all n
letters are used on the first turn.
Letters are scored as in Scrabble; A is worth 1, B is worth 3, C is
worth 3, D is worth 2, E is worth 1, and so on (see SCRABBLE_LETTER_VALUES)
word: string (lowercase letters)
n: integer (HAND_SIZE; i.e., hand size required for additional points)
returns: int >= 0
"""
# TO DO ... <-- Remove this comment when you code this function
score=0
word.lower()
for char in word:
score+=SCRABBLE_LETTER_VALUES[char]
score*=len(word)
if len(word)==n:
score+=50
return score
def updateHand(hand, word):
"""
Assumes that 'hand' has all the letters in word.
In other words, this assumes that however many times
a letter appears in 'word', 'hand' has at least as
many of that letter in it.
Updates the hand: uses up the letters in the given word
and returns the new hand, without those letters in it.
Has no side effects: does not modify hand.
word: string
hand: dictionary (string -> int)
returns: dictionary (string -> int)
"""
# TO DO ... <-- Remove this comment when you code this function
newHand = hand.copy() # Create a copy of the original hand dictionary
for letter in word:
newHand[letter] = newHand.get(letter, 0) - 1 # Decrement the count of the letter in the new hand
return newHand
def displayHand(hand):
"""
Displays the letters currently in the hand.
For example:
>>> displayHand({'a':1, 'x':2, 'l':3, 'e':1})
Should print out something like:
a x x l l l e
The order of the letters is unimportant.
hand: dictionary (string -> int)
"""
for letter in hand.keys():
for j in range(hand[letter]):
print(letter,end=" ") # print all on the same line
print()
def dealHand(n):
"""
Returns a random hand containing n lowercase letters.
At least n/3 the letters in the hand should be VOWELS.
Hands are represented as dictionaries. The keys are
letters and the values are the number of times the
particular letter is repeated in that hand.
n: int >= 0
returns: dictionary (string -> int)
"""
hand={}
for i in range(n):
x = Letters[random.randint(0,97)]
hand[x] = hand.get(x, 0) + 1
return hand
import copy
def isValidWord(word, hand, wordList):
"""
Returns True if word is in the wordList and is entirely
composed of letters in the hand. Otherwise, returns False.
Does not mutate hand or wordList.
word: string
hand: dictionary (string -> int)
wordList: list of lowercase strings
"""
hand_new = copy.deepcopy(hand)
if word not in wordList:
return False
for char in word:
if char not in hand_new or hand_new[char] == 0:
return False
hand_new[char] -= 1
return True
def calculateHandlen(hand):
"""
Returns the length (number of letters) in the current hand.
hand: dictionary (string int)
returns: integer
"""
length = 0
for letter in hand:
length += hand[letter]
return length
def playHand(hand, wordList, n):
total_score = 0
while calculateHandlen(hand) > 0:
print("Current Hand:", end=" ")
displayHand(hand)
word = input('Enter word, or a "." to indicate that you are finished: ')
if word == '.':
break
if not isValidWord(word, hand, wordList):
print("Invalid word, please try again.")
continue
score = getWordScore(word, n)
total_score += score
print('"{}" earned {} points. Total: {} points'.format(word, score, total_score))
hand = updateHand(hand, word)
print("Total score:", total_score)
hand={'p':2, 'n':4, 'e':1, 'u':2, 'm':2, 'o':9, 'l':3, 't':1, 'r':2, 'a':2, 'i':6, 'c':6, 's':4, 'v':1}
wordList = "words2.txt"
playHand(hand, wordList, 45)
from random import *
def pick_3():
num=[1, 2, 3, 4, 5, 6, 7, 8, 9, 0]
win_num=[]
num1=num[:]
your_num=[]
winnings=0
for i in range(3):
your_num.append(num[int(random()*len(num1))])
num1.remove(your_num[len(your_num)-1])
your_sort=bubble_sort(your_num)
for i in range(1000):
for i in range(3):
win_num.append(num[int(random()*len(num))])
num.remove(win_num[len(win_num)-1])
win_sort=bubble_sort(win_num)
if win_sort==your_sort:
winnings+=50
elif your_sort[0] in win_sort and your_sort[1] in win_sort:
winnings+=5
elif your_sort[0] in win_sort and your_sort[2] in win_sort:
winnings+=5
elif your_sort[1] in win_sort and your_sort[2] in win_sort:
winnings+=5
elif your_sort[0] in win_sort:
winnings+=1
elif your_sort[1] in win_sort:
winnings+=1
elif your_sort[2] in win_sort:
winnings+=1
print(winnings)
from random import *
pick_3()
import copy
import random
def pick_2():
num=[1, 2, 3, 4, 5]
num1=copy.deepcopy(num)
winnings=0
win_num=0
your_num=0
your_num.append(randint(1, 5))
num.remove(your_num[0])
your_num.append(randint(1, 5))
num.remove(your_num[1])
def multlist(m, n):
'''
m is the multiplication factor
n is a list.
'''
result = []
for i in range(len(n)):
result.append(m*n[i])
return result
m=5
n=[1, 8, 3, 0, 9, 4, 7]
multlist(m, n)
def foo(n):
if n <= 1:
return 1
return foo(n/2) + 1
def genPrimes():
# Initialize to have 2
primes = [2]
yield 2
x = 3 # Start checking from 3
while True:
is_prime = True
# Check divisibility by primes less than or equal to the square root of x
for p in primes:
if p * p > x:
break
if x % p == 0:
is_prime = False
break
if is_prime:
yield x
primes.append(x)
x += 2 # Check only odd numbers to skip even numbers
# Example usage:
prime_generator = genPrimes()
for _ in range(100000):
print(next(prime_generator))
11.6. Plotting#
import pylab as plt
mySamples = []
myLinear = []
myQuadratic = []
myCubic = []
myExponential = []
for i in range(0, 30):
mySamples.append(i)
myLinear.append(i)
myQuadratic.append(i**2)
myCubic.append(i**3)
myExponential.append(1.5**i)
plt.figure('lin')
plt.clf()
plt.title('linear')
plt.xlabel('sample points')
plt.ylabel('linear function')
plt.plot(mySamples, myLinear, label='linear')
plt.legend()
plt.show()
plt.figure('quad')
plt.clf()
plt.title('quadratic')
plt.xlabel('sample points')
plt.ylabel('quadratic function')
plt.plot(mySamples, myQuadratic, label='quadratic')
plt.legend()
plt.show()
plt.figure('cube')
plt.clf()
plt.title('cubic')
plt.xlabel('sample points')
plt.ylabel('cubic function')
plt.plot(mySamples, myCubic, label='cubic')
plt.legend()
plt.show()
plt.figure('expo')
plt.clf()
plt.title('exponential')
plt.xlabel('sample points')
plt.ylabel('exponential function')
plt.plot(mySamples, myExponential, label='exponential')
plt.legend()
plt.show()
plt.figure('lin vs quad')
plt.title('linear vs quadratic')
plt.xlabel('sample points')
plt.ylabel('functions')
plt.plot(mySamples, myLinear, label='linear')
plt.plot(mySamples, myQuadratic, label='quadratic')
plt.legend()
plt.show()
plt.figure('cube vs expo')
plt.title('cubic vs exponential')
plt.xlabel('sample points')
plt.ylabel('functions')
plt.plot(mySamples, myCubic, label='cubic')
plt.plot(mySamples, myExponential, label='exponential')
plt.legend()
plt.show()
plt.figure('quad vs cube')
plt.title('quadratic vs cubic')
plt.xlabel('sample points')
plt.ylabel('functions')
plt.plot(mySamples, myQuadratic, label='quadratic')
plt.plot(mySamples, myCubic, label='cubic')
plt.legend()
plt.show()
def retire(monthly, rate, terms):
savings=[0]
base=[0]
mRate=rate/12
for i in range(terms):
base+=[i]
savings+=[savings[-1]*(1+mRate)+monthly]
return base, savings
retire(300, 0.055, 120)
11.7. Final Exam#
L = [1,2,3]
type(L)
list
def is_triangular(k):
"""
k, a positive integer
returns True if k is triangular or False if not
"""
n=1
while k>0:
k-=n
n+=1
if k==0:
return True
else:
return False
is_triangular(8)
False
def longest_run(L):
current_run=[]
long_run=[]
n=0
if len(L)==0:
return 0
elif len(L)==1:
return L[0]
else:
while n<len(L)-1:
try:
while L[n+1]==L[n]:
n+=1
current_run.append(L[n])
if L[n+1]>L[n]:
while L[n+1]>=L[n]:
current_run.append(L[n])
n+=1
current_run.append(L[n+1])
print(current_run)
print(long_run)
else:
while L[n+1]<=L[n]:
current_run.append(L[n])
n+=1
current_run.append(L[n+1])
print(current_run)
print(long_run)
except IndexError:
pass
if len(current_run)>len(long_run):
long_run=current_run
current_run=[]
sum_run=sum(long_run)+L[len(L)-1]
return sum_run
L=[1, 8, 9]
longest_run(L)
18
def search(L, e):
"""Assumes L is a list, the elements of which are in
ascending order.
Returns True if e is in L and False otherwise"""
for i in range(len(L)):
if L[i] == e:
return True
if L[i] > e:
return False
return False
def f(n):
def g(m):
m = 0
for i in range(m):
print(m)
for i in range(n):
print(g(n))
L=[1, 8, 3, 9, 32, 0, 2, 4]
L_s=bubble_sort(L)
e=3
search(L_s, e)
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
Cell In[74], line 4
2 L_s=bubble_sort(L)
3 e=3
----> 4 search(L_s, e)
Cell In[67], line 5, in search(L, e)
1 def search(L, e):
2 """Assumes L is a list, the elements of which are in
3 ascending order.
4 Returns True if e is in L and False otherwise"""
----> 5 for i in range(len(L)):
6 if L[i] == e:
7 return True
TypeError: object of type 'NoneType' has no len()
class Person(object):
def __init__(self, name):
self.name = name
def say(self, stuff):
return self.name + ' says: ' + stuff
def __str__(self):
return self.name
class Lecturer(Person):
def lecture(self, stuff):
return 'I believe that ' + Person.say(self, stuff)
class Professor(Lecturer):
def say(self, stuff):
return self.name + ' says: ' + self.lecture(stuff)
class ArrogantProfessor(Professor):
def say (self, stuff):
return self.name+' says: It is obvious that '+Person.say(self, stuff)
def lecture(self, stuff):
return 'It is obvious that '+ Person.say(self, stuff)
j=Person('jonny')
lj=Lecturer('jonny')
pj=Professor('jonny')
aj=ArrogantProfessor('jonny')
j.say('the sky is blue')
'jonny says: the sky is blue'
j.name
'jonny'
lj.say('the sky is blue')
'jonny says: the sky is blue'
lj.lecture('the sky is blue')
'I believe that jonny says: the sky is blue'
pj.say('the sky is blue')
'jonny says: I believe that jonny says: the sky is blue'
pj.lecture('the sky is blue')
'I believe that jonny says: the sky is blue'
aj.say('the sky is blue')
'jonny says: It is obvious that jonny says: the sky is blue'
aj.lecture('the sky is blue')
'It is obvious that jonny says: the sky is blue'
def cipher(map_from, map_to, code):
key_code = {} # Step 1: Create an empty dictionary for mapping
decoded = "" # Initialize an empty string for the decoded result
# Step 2: Build the key_code dictionary
for i in range(len(map_from)):
key_code[map_from[i]] = map_to[i]
# Step 3: Decode the input code using the key_code mapping
for letter in code:
decoded += key_code[letter]
return (key_code, decoded) # Return the tuple of key_code and decoded result
import string
map_from=string.ascii_lowercase
map_to=string.ascii_uppercase
code='pneumonoultramicroscopicsilicovolcanoconiosis'
cipher(map_from, map_to, code)
({'a': 'A',
'b': 'B',
'c': 'C',
'd': 'D',
'e': 'E',
'f': 'F',
'g': 'G',
'h': 'H',
'i': 'I',
'j': 'J',
'k': 'K',
'l': 'L',
'm': 'M',
'n': 'N',
'o': 'O',
'p': 'P',
'q': 'Q',
'r': 'R',
's': 'S',
't': 'T',
'u': 'U',
'v': 'V',
'w': 'W',
'x': 'X',
'y': 'Y',
'z': 'Z'},
'PNEUMONOULTRAMICROSCOPICSILICOVOLCANOCONIOSIS')
import random
m=[]
w=[]
isin=False
won=False
times=0
while len(m)<6:
num=random.randint(1, 45)
if num in m:
isin=True
if not isin:
m.append(num)
isin=False
for i in range(10000000):
if won==False:
wins=random.randint(1, 45)
if wins in w:
isin=True
if not isin:
w.append(wins)
if won==False:
times+=1
if m!=w:
pass
else:
won=True
else:
break
if won==True:
print('Won')
else:
print("Didn't win yet")
print(times)
---------------------------------------------------------------------------
KeyboardInterrupt Traceback (most recent call last)
Cell In[42], line 8
6 times=0
7 while len(m)<6:
----> 8 num=random.randint(1, 45)
9 if num in m:
10 isin=True
File c:\ProgramData\anaconda3\lib\random.py:370, in Random.randint(self, a, b)
366 def randint(self, a, b):
367 """Return random integer in range [a, b], including both end points.
368 """
--> 370 return self.randrange(a, b+1)
File c:\ProgramData\anaconda3\lib\random.py:338, in Random.randrange(self, start, stop, step)
336 width = istop - istart
337 try:
--> 338 istep = _index(step)
339 except TypeError:
340 istep = int(step)
KeyboardInterrupt:
def longest_run(L):
longest_length = 1
current_length = 1
longest_sum = L[0]
current_sum = L[0]
start_index = 0
is_increasing = None
for i in range(1, len(L)):
if L[i] >= L[i - 1]:
if is_increasing is None or is_increasing:
current_length += 1
current_sum += L[i]
else:
current_length = 2
current_sum = L[i - 1] + L[i]
start_index = i - 1
is_increasing = True
elif L[i] <= L[i - 1]:
if is_increasing is None or not is_increasing:
current_length += 1
current_sum += L[i]
else:
current_length = 2
current_sum = L[i - 1] + L[i]
start_index = i - 1
is_increasing = False
else:
current_length += 1
current_sum += L[i]
if current_length > longest_length or (current_length == longest_length and start_index < longest_start):
longest_length = current_length
longest_sum = current_sum
longest_start = start_index
return longest_sum
def longest_run(L):
longest_length = 1
current_length = 1
longest_sum = L[0]
current_sum = L[0]
start_index = 0
is_increasing = None
for i in range(1, len(L)):
if L[i] > L[i - 1]:
if is_increasing is None or is_increasing:
current_length += 1
current_sum += L[i]
else:
current_length = 2
current_sum = L[i - 1] + L[i]
start_index = i - 1
is_increasing = True
elif L[i] < L[i - 1]:
if is_increasing is None or not is_increasing:
current_length += 1
current_sum += L[i]
else:
if current_length == 1:
start_index = i
current_length = 2
current_sum = L[i - 1] + L[i]
is_increasing = False
else:
if current_length == 1:
start_index = i
current_length += 1
current_sum += L[i]
if current_length > longest_length or (current_length == longest_length and start_index < longest_start):
longest_length = current_length
longest_sum = current_sum
longest_start = start_index
return longest_sum
# Test cases
print(longest_run([1, 2, 3, 4, 5, 6, 7, 8, 9])) # Output: 45
print(longest_run([1, 2, 3, 2, 1])) # Output: 6
print(longest_run([3, 2, 1, 2, 3])) # Output: 6
print(longest_run([1, 2, 1, 2, 1, 2, 1, 2, 1])) # Output: 3
print(longest_run([1, 2, 3, 4, 5, 0, 10, 1, 2, 3, 4, 5])) # Output: 15
print(longest_run([1, 2, 3, 10, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1])) # Output: 65
print(longest_run([100, 200, 300, -100, -200, -1500, -5000])) # Output: -6500
45
6
6
3
15
55
-6500
longest_run([1, 2, 3, 10, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1])
55