Strings continued
String literals
See here.
The in operator
# for strings t and s, (t in s) is the same as
# isSubstring(t, s) from homework 1-4.
print("h" in "hello") # prints True
print("hell" in "hello") # prints True
print("ll" in "hello") # prints True
print("H" in "hello") # prints False
print("" in "hello") # prints True
print("k" not in "hello") # prints True
Built-in constants
See here.
String methods
See here.
String formatting
See here.
Example: Caesar shift
def encrypt(message, shiftNum):
result = ""
for char in message:
result += shift(char, shiftNum)
return result
# Shift a single character by shiftNum.
# The following is a very "Pythonic" implementation.
def shift(c, shiftNum):
shiftNum %= 26
if (not c.alpha()): return c
alph = string.ascii_lower if (c.islower()) else string.ascii_upper
shiftedAlph = alph[shiftNum:] + alph[:shiftNum]
return shiftedAlph[alph.find(c)]
# The following is a more standard approach.
def shift(c, shiftNum):
shiftNum = shiftNum % 26
if(not char.isalpha()): return char
shifted = ord(char) + shiftNum
if ( ((char <= 'Z') and (shifted > ord('Z'))) or
((char <= 'z') and (shifted > ord('z'))) ):
return chr(shifted - 26)
else:
return chr(shifted)
Monte Carlo method
Odds of Mere winning
In the first bet, Mere rolls a dice 4 times. He wins if he gets a 1.
import random
def mereOdds():
trials = 100*1000
successes = 0
for trial in range(trials):
if(mereWins()):
successes += 1
return successes/trials
def mereWins():
for i in range(4):
dieValue = random.randint(1,6)
if(dieValue == 1): return True
return False
print(mereOdds())
In the second bet, Mere rolls two dice 24 times. He wins if he gets 1-1.
import random
def mereOdds():
trials = 100*1000
successes = 0
for trial in range(trials):
if(mereWins()):
successes += 1
return successes/trials
def mereWins():
for i in range(24):
dieValue1 = random.randint(1,6)
dieValue2 = random.randint(1,6)
if(dieValue1 == 1 and dieValue2 == 1): return True
return False
print(mereOdds())
Birthday problem
Assume there are n people in a room. We want to estimate the probability that there are 2 people in the room who share a birthday.
import random
def birthdayOdds(n):
trials = 10*1000
successes = 0
for trial in range(trials):
if(trialSucceeds(n)): successes += 1
return successes/trials
def trialSucceeds(n):
seenBirthdays = ""
for i in range(n):
randomBirthday = "$" + str(random.randint(1,365)) + "$"
if(randomBirthday in seenBirthdays): return True
else: seenBirthdays += randomBirthday
return False
for n in range(50):
print(n, birthdayOdds(n))
Estimating Pi
import random
def estimatePi():
throws = 100*1000
numInCircle = 0 # successes
for throw in range(throws):
x = random.uniform(-1,1)
y = random.uniform(-1,1)
if(inUnitCircle(x,y)): # trial succeeds
numInCircle += 1
return 4*numInCircle/throws
def inUnitCircle(x,y):
return x**2 + y**2 <= 1
print(estimatePi())
Monty Hall problem
import random
# What are the odds of winning if you switch?
def montyHall():
trials = 10*1000
successes = 0
for trial in range(trials):
if(trialSucceeds()): successes += 1
return successes/trials
def trialSucceeds():
prize = random.randint(1,3)
choice = random.randint(1,3)
reveal = random.randint(1,3)
while(reveal == prize or reveal == choice):
reveal = random.randint(1,3)
switch = (1+2+3) - reveal - choice
return (switch == prize)
print(montyHall())