Reminder: if L
is a list then L[-1]
is the last element of the list, and L[-2]
is the one before last elements, etc.. Same for strings.
L = ["a","b","c","d","e"]
print(f"L[-1]={L[-1]}")
print(f"L[-2]={L[-2]}")
x = "boaz"
print(x[-2])
Question from lab: A Palindrome is a string that is the same if you read it forward and backwards:
Which one is a Palindrome?
kayak
?
banana
?
racecar
?
aaabaaa
?
Write a function pal4(s)
that takes as input s
of length 4, and returns True
if s
is a Palindrome and False
otherwise.
def pal4(s):
...
print(pal4("abba"))
print(pal4("boaz"))
def pal4(s):
if s[0]==s[-1] and s[1]==s[-2]:
return True
return False
# version with _or_:
def pal4_or(s):
if s[0]!=s[-1] or s[1]!=s[-2]:
return False
return True
check_words = ["abba", "boaz", "naan", "help", "deed"]
for word in check_words:
if pal4_or(word)==pal4(word):
print(f"pal4 and pal4_or agree on {word}")
else:
print(f"pal4and pal4_or disagree on {word}!!!!")
Write a function pal6(s)
that takes as input s
of length 6, and returns True
if s
is a Palindrome and False
otherwise. Use or
def pal6(s):
...
def pal6(s):
if s[0]!=s[-1] or s[1]!=s[-2] or s[2] != s[-3]:
return False
return True
pal6("abccba")
Write function pal(s)
that works for Palindromes for every even length. As bonus, make it work for every length
def pal(s):
...
def pal(s):
n = len(s)//2
for i in range(n):
if s[i] != s[-i-1]:
return False
return True
pal("hello")
pal("aaaaabcbaaaaa")
Write a function reverse(s)
that takes a string s
and returns its reverse.
reverse("boaz")
will be "zaob"
Hint: if x
is a string and a
is a letter then x = x+ a
changes x
so that now a
is added to end of the string x
and x = a + x
changes x
to the string where a
is added to the beginning the previous x
.
def reverse(s):
...
def reverse(s):
res = ""
for a in s:
res = a + res
return res
reverse("boaz")
Exercise: Use reverse
to give a function to compute pal
(Palindromes). Can you do it in three lines? How about in one?
def pal(s):
...
def pal(s):
if s==reverse(s):
return True
return False
def pal(s):
return s == reverse(s)
pal("racecar")
If L
is a list then L[2:7]
is the elements of L
in positions 2 until 6. Same for string.
L = ["a","b","c","d","e","f","g"]
# What will be printed
print(L[2:4])
print(L[4:7])
If L
is a list then L[2:]
is the elements of L
in positions 2 until the end, L[:7]
is the elements of L
from the beginning until position 6. Same for strings.
s = "JamCoders"
a = s[:3]
b = s[3:]
print(a)
print(b)
def passing_grade(score):
if score > 50:
return True
return False
print(passing_grade(60))
print(passing_grade(25))
def passing_grade(score): # print version
if score > 50:
print("True")
print("False")
if passing_grade(99):
print("That's a great grade")
def passing_grade(score): # print version
if score > 50:
return True
return False
if passing_grade(99):
print("That's a great grade")
Suppose we have the passing_grade
function above. Write a function passed
that takes as input two lists students
and grades
and prints the names of the students that passed.
def passed(students,grades):
...
def passed(students,grades):
n = len(students)
for i in range(n):
if passing_grade(grades[i]):
print(students[i])
students = [ "Bereket", "Annamira", "Elijah", "Orr", "Jabari", "Annakai", "Tyler" ]
# let's make grades random for fairness
import random
grades = []
for i in range(len(students)):
grades.append(random.randint(1,100))
grades
passed(students,grades)
We will write a function enc(s)
that takes a string s
and outputs it to a string where a
is replaced with z
, b
is replaced with y
, and so on
So enc(car)
is yaj
.
# If a and b are strings, then a.find(b) gives the first position where b is in a. Otherwise it gives -1
x = "abcdefg"
y = "h"
print(x.find(y))
from string import ascii_letters
print(ascii_letters)
lowercase = ascii_letters[:26]
print(lowercase)
Write a function enc(s)
that takes a string s
and outputs it to a string where a
is replaced with z
, b
is replaced with y
, and so on
Can use:
lowercase
that contains all lowercase letters.find
operation: a.find(b)
is the first position of b
in a
We'll use it to decode ytjmnsdd
def enc(s):
...
def enc(s):
res = ""
for a in s:
i = lowercase.find(a)
res += lowercase[-i]
return res
enc("ytjmnsdd")
# Variables inside a function have no relation to variables outside the function
# See what happens when "i" is printed inside and outside the function
i = 0
def func(x):
i = 10
print("i=",i, "x=",x)
func(5)
print("i=",i)
# Variables across functions have no relation to each other
# A variable declared inside a function will have no relation to outside the function
# Why is there an error?
def func1(x):
j = 10
print("j=",j, "x=",x)
def func2(x):
j = 5
func1(x)
print("x=",x)
func2(3)
print(j)
# Why is this the output?
k = 0
for i in range(3):
print(k)
# How about here?
k = 0
for i in range(3):
k = 6
print(k)
# This is a reminder of what a loop looks like
for i in range(20):
print('still in loop')
print('Loop completed!')
# There are two keywords for loops that you will need to know
# The first is "break"
# Break will exit a for loop once it is executed
for i in range(4):
print(i)
if i == 2:
break
print("---")
print('Loop completed!')
# The other keyword you need to know is "continue"
# "continue" will make it so that the rest of the loop body is not executed
# but ONLY for the time it is called
# Notice that "10" is not printed
for i in range(4):
print(i)
if i == 2:
continue
print("---")
print('Loop completed!')
# You can have continue and break in the same loop
for i in range(6):
if i == 2:
continue
if i == 4:
break
print(i)
print('Loop completed!')
# This is the generic syntax for a while loop
while CONTIDION:
LOOP_BODY
# A "while loop" is a loop that executes while CONDITION is true
# The CONDITION is evaluated once the loop body finishes, and only then
i = 0
while i < 10:
print(i)
i += 1
print('Loop completed!')
# If CONDITION is False at the start of the loop, the loop body will not execute!
i = 0
while i < 0:
print(i)
i += 1
print('Loop completed!')
# What is different about this and the one two above?
i = 0
while i < 10:
i += 1
print(i)
print('Loop completed!')
# WARNING!!!!
# You can have loops that run forever.
# These are really really bad.
# Make sure the loop terminates.
while True:
print('hi!')
# WARNING!!!!!
# Even if you don't mean to, the loop can run forever.
# DO NOT do this.
i = 0
while i < 10:
print(i)
print('Loop completed!') # This will never execute!
# You can use "continue" in while loops
# The syntax and behavior is exactly the same as in for loop
i = 0
while i < 10:
i += 1
if i == 5:
continue
print(i)
print('Loop completed!')
# WARNING!!!!
# This loop will also run forever. Why?
# Don't do this.
i = 0
while i < 10:
if i == 5:
continue
print(i)
i += 1
print('Loop completed!')
# You can also use "break" in while loops
# The syntax and usage is exactly the same as in for loops
i = 0
while True:
if i > 10:
break
print(i)
i += 1
# What will happen?
i = 0
while True:
i += 1
if i > 10:
break
print(i)