Strings: Strings? concatenate (join) + make multiple copies using * compare: > =

Preview:

Citation preview

Strings:

Strings? concatenate (join) +

make multiple copies using *

compare: > < == >= <= !=

What else can we do?

A lot!

Len, indef f(x):

if "e" in x:

return("e is in your message.")

else:

return("e is not in your message.")

strvar = “puppies are cute”

print(f(strvar))

z = len("cat")

Strings PositionalGet a character at a particular index within a string

stringvar1 = “ binary”Index 012345

stringvar2 = “ computer”Index 012 3 4 5 6 7

So to use a particular item in the list:

x=stringvar2[3] #”p”

y=stringvar1[1] #”i”

z=stringvar2[0] #”c”

w=stringvar1[6] #???

Example:

def f(par):

randnum = randrange(0,6)

return(“you get “ + par[randnum])

print(f((stringvar1))

String:stringvar1 = “binary”

Index 012345

stringvar2 = “ computer”

Index 01234567

get the length of a string len(stringvar1) # will give you 6, not 5!

len(stringvar2) #will give you 8, not 7

Example:

def f(par):

y = len(par)

randnum = randrange(0,y) #Why does this work?

return(“you get “ + par[randnum])

print(f(stringvar2))

We can now do:def f(x,y):

if (x == len(y)):

return

else:

print(y[x])

return(f(x+1,y))

f(0,’kluge’)

Slicing (Different from Indexing) Copying parts of strings:

0 1 2 3 4 5

| p | i | z | z | a |

-5 -4 -3 -2 -1

def f(word):return(word[2:5] )

print(f(“pizza”))

def g():

word = “pizza”

return(word[1:3])

def h():

word = “pizza”

return(word[-4:-2])

def i():

word = “pizza”

return(word[-4:3])

Shortcuts 0 1 2 3 4 5

| p | i | z | z | a |

-5 -4 -3 -2 -1

word=“pizza”

word[0:4]

pizz

word[:4]

pizz

word[2:5]

zza

word[2:]

zza

# display a slice

def g(s,f,wd):

return("wd["+str(s)+":"+str(f)+"] is "+wd[s:f])

print(g(3,7,"sesquipedalian"))

Strings are Immutableword of the day

Can: x = "catamaran"

print(x.count("a"))

print(x.index('a'))

Can’t (if it changes the string, we can’t do it) x[3] = “y” #can’t do!

What does this do?

def f(str1):

str2 = “WuGmUmP”

if str1.upper() == str2.upper():

return(“You’re one of us!”)

else:

return(“You’re not one of us!”)

newstr = “wuGMuMp”print(f(newstr))

def rec(a,x,y):

if (x == len(a)):

return 0

elif (a[x] in y):

return 1 + rec(a,x+1,y)

else:

return rec(a, x+1, y)

 

a = "catamaran"

y = "aeiou"

print(str(rec(a,0,y)))

def rec(a,x,y):

if (x == len(a)):

return ""

elif (a[x] in y):

return rec(a,x+1,y)

else:

return (a[x] + rec(a, x+1, y))

a = "catamaran"

y = "aeiou"

print(str(rec(a,0,y)))

def f(x,y,z):

if y == len(x):

return(z)

else:

if (x[y] == "p"):

return(f(x,y+1,z+"m"))

else:

return(f(x,y+1,z+x[y]))

print(f("puppy",0,""))

def f(x,a):

if (x == len(a)//2):

return a[x]==a[len(a)//2]

else:

if a[x] != a[len(a)-(x+1)]:

return a[x] == a[len(a)-(x+1)]

else:

return(f(x+1,a))

print(f(0,"mom"))

print(f(0,"mommy"))

def g(x,y,z,q): if (x == len(y)): return z else: if (y[x] not in " ,!.:;?"): if q: return(g(x+1,y,z+1,False)) else: return(g(x+1,y,z,False)) else: return(g(x+1,y,z,True))

print(g(0,"Hello there, how are you today?",0,True))

def h(x,y,z,q):

if x == len(y):

return 0

else:

if y[x] in "\"'":

if (q == y[x]):

return(z)

elif q != y[x]:

return h(x+1,y,0,y[x])

else:

return h(x+1,y,z+1,q)

print(h(0,"He said, 'Houston, we have a problem' in the movie",0,'+'))

While Loopdef ThreeYearOld():

x = ""

while (x != "Because."):

x = input("But why?")

return("Oh. Okay.")

print(ThreeYearOld())

Look at this code: What is our starting condition?

What must be true in order for the loop to start? What will make the loop end?

What must become false? Does something INSIDE the loop that changes so that

eventually the loop will end? Does this all remind you of something?

Loops:

While Loops: Continue while condition is true

Must initialize to make condition true

In recursion we stop when the stopping contion is true – in while loops we stop when the while condition is false.

Something inside the loop must change so that the condition becomes false eventually.

What does this code print out?

def f(x, counter):while counter < x:

print(counter)counter = counter +

1 return(counter)print(f(5, 0))

def f2(x,counter): if (counter >= x): return (counter) else: print(counter) return(f2(x,counter+1))print(f2(5,0))

While loopsdef f(total,count):

while count >= 1: #This is the part that loops

total += count

count = count -1

return(total)

print(f(0, int(input("Enter a number"))))

Starting condition (What must be true to enter loop)?What makes the loop stop?

What inside the loop changes so that the loop will stop?

While loops

def f(total):

while count >= 1:

total += count

count = count -1

return(total)

print(f(0))

Starting condition?

What makes the loop stop?

What inside the loop changes so that the loop will stop?

While loops

def f(total, count):

while count >= 1:

total += count

count = count + 1

return(total)

print(f(0, 4))

Starting condition?

What makes the loop stop?

What inside the loop changes so that the loop will stop?

Loops: Anything that can be done recursively can be done with a while

loop (and vice versa) Certain problems work better with certain loops

loop must have a True/False condition

while count >= 1: While loops starts when the condition is True

It continues while the condition is True

It stops when the condition is False

Something must change inside the loop that will eventually make the True/False condition False

while count >= 1:

total += count

count = count -1

Differences (syntactic): We can initialize variables used by the while loop inside the

function (BUT BEFORE THE WHILE LOOP!) Why can’t we do this with recursion?

def f():x = 5counter = 0while counter < x:

print(counter)counter = counter + 1

return(counter)print(f())

def f(x, counter):while counter < x:

print(counter)counter = counter +

1 return(counter)print(f(5, 0))

In general, unless you know what you are doing, while loops should not call the function from within the function

In general, unless you know what you are doing, recursive function should not use while loops inside the function.

Write a function that takes as an input parameter an integer and uses a while loop to print out "ha" that number of times.

Starting condition?

What makes the loop stop? (your True/False condition?)

What inside the loop changes so that the loop will stop?def func(x):while (x > 0):

print("ha ",end= " ") x -= 1 returnfunc(5)

def func(x):stringvar = ""while (x > 0):

stringvar += "ha ") x -= 1 return(stringvar)print(func(5))

Recursive:def func(x):if x <= 0:returnelse:

print("ha ")return(func(x-1))

func(5)

Recursive:def func(x,stringvar):if x <= 0: return(stringvar)else: return(func(x-1,stringvar+"ha "))

print(func(5, ""))

What does this do?def w2(x,y): tot = 0 while (y > 0): tot += x y -= 1 return(tot)

print(w2(3,5))

What about this?

def g(y,z):

x = len(y)-1

while x >= 0:

z += y[x]

x-=1

return z

print(g("nilbog",""))

What does this do?

def f(message):

newmessage = ""

x = 0

while x < len(message):

if message[x] == "g":

newmessage += "l"

else:

newmessage += message[x]

x += 1

return(newmessage)

print(f("pogysyggabicaggy“))

This one?

def c2(x):

y = 0

k = 0

while (x > 0):

y += x%2 * 10**k

k += 1

x = x//2

return(y)

print(c2(10))

What does this one do?

def w4(x, z):

y = randrange(0,x)

print(y)

g = -1 #Why did I do this?

while (g != y):

g = randrange(0,x)

print(g)

z+= 1

print(z)

return("It took " + str(z))

print(w4(10,0))

Try: exponent: Write a function that takes as input parameters 2 integers and uses a while

loop to calculate x to the power of y (don’t use **)

def c(x,y):

z = 1;

while (y > 0):

z *= x

y -= 1

return z

Write a while loop that converts a binary number to an integer

def c3(x):

y = 0

k = 0

while (x > 0):

y += x%2 * 2 **k

k+=1

x = x//10

return(y)

def z(ct):

x = 0

while (ct >= 0):

x += ct

ct = ct - 1

return(x)

print(z(5))

Versus:def z(ct): x = 0 while (ct >= 0): ct = ct - 1 x += ct return(x)print(z(5))

Recommended