JamCoders

💾 Download

Indexing lists and palindromes

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.

In [ ]:
L = ["a","b","c","d","e"]
print(f"L[-1]={L[-1]}")
print(f"L[-2]={L[-2]}")
L[-1]=e
L[-2]=d
In [ ]:
x = "boaz"
print(x[-2])
a

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.

In [ ]:
def pal4(s):
    ...
In [ ]:
print(pal4("abba"))
print(pal4("boaz"))
True
False
In [ ]:
def pal4(s):
    if s[0]==s[-1] and s[1]==s[-2]:
        return True
    return False
In [ ]:
# version with _or_:
def pal4_or(s):
    if s[0]!=s[-1] or s[1]!=s[-2]:
        return False
    return True
In [ ]:
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}!!!!")
pal4 and pal4_or agree on abba
pal4 and pal4_or agree on boaz
pal4 and pal4_or agree on naan
pal4 and pal4_or agree on help
pal4 and pal4_or agree on deed

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

In [ ]:
def pal6(s):
    ...
In [ ]:
def pal6(s):
    if s[0]!=s[-1] or s[1]!=s[-2] or s[2] != s[-3]:
        return False
    return True
In [ ]:
pal6("abccba")
Out[ ]:
True

Write function pal(s) that works for Palindromes for every even length. As bonus, make it work for every length

In [ ]:
def pal(s):
    ...
In [ ]:
def pal(s):
    n = len(s)//2
    for i in range(n):
        if s[i] != s[-i-1]:
            return False
    return True
In [ ]:
pal("hello")
Out[ ]:
False
In [ ]:
pal("aaaaabcbaaaaa")
Out[ ]:
True

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.

In [ ]:
def reverse(s):
    ...
In [ ]:
def reverse(s):
    res = ""
    for a in s:
        res = a + res
    return res
In [ ]:
reverse("boaz")
Out[ ]:
'zaob'

Exercise: Use reverse to give a function to compute pal (Palindromes). Can you do it in three lines? How about in one?

In [ ]:
def pal(s):
    ...
In [ ]:
def pal(s):
    if s==reverse(s):
        return True
    return False
In [ ]:
def pal(s):
    return s == reverse(s)
In [ ]:
pal("racecar")
Out[ ]:
True

Slicing

If L is a list then L[2:7] is the elements of L in positions 2 until 6. Same for string.

In [ ]:
L = ["a","b","c","d","e","f","g"]
# What will be printed
print(L[2:4])
print(L[4:7])
['c', 'd']
['e', 'f', 'g']

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.

In [ ]:
s = "JamCoders"
a = s[:3]
b = s[3:]
print(a)
print(b)
Jam
Coders

Questions?

More function examples

In [ ]:
def passing_grade(score):
    if score > 50:
        return True
    return False
print(passing_grade(60))
print(passing_grade(25))

Reminder - difference between print and return

In [ ]:
def passing_grade(score): # print version
    if score > 50:
        print("True")
    print("False")
In [ ]:
if passing_grade(99):
    print("That's a great grade")
In [ ]:
def passing_grade(score): # print version
    if score > 50:
        return True
    return False
In [ ]:
if passing_grade(99):
    print("That's a great grade")

Using a function

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.

In [ ]:
def passed(students,grades):
    ...
In [ ]:
def passed(students,grades):
    n = len(students)
    for i in range(n):
        if passing_grade(grades[i]):
            print(students[i])
In [ ]:
students = [ "Bereket", "Annamira", "Elijah", "Orr", "Jabari", "Annakai", "Tyler" ]
In [ ]:
# let's make grades random for fairness
import random
grades = []
for i in range(len(students)):
    grades.append(random.randint(1,100))

grades
In [ ]:
passed(students,grades)

Secret codes

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.

In [ ]:
# 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))
-1
In [ ]:
from string import ascii_letters
print(ascii_letters)
abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ
In [ ]:
lowercase = ascii_letters[:26]
print(lowercase)
abcdefghijklmnopqrstuvwxyz

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:

  • The string lowercase that contains all lowercase letters.
  • The find operation: a.find(b) is the first position of b in a

We'll use it to decode ytjmnsdd

In [ ]:
def enc(s):
    ...
In [ ]:
def enc(s):
    res = ""
    for a in s:
        i = lowercase.find(a)
        res += lowercase[-i]
    return res
In [ ]:
enc("ytjmnsdd")
Out[ ]:
'chronixx'

Functions (variable scoping)

In [ ]:
# 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)
In [ ]:
# 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)
In [ ]:
# Why is this the output?

k = 0
for i in range(3):
    print(k)
In [ ]:
# How about here?

k = 0
for i in range(3):
    k = 6
    print(k)

Advanced for loop keywords

In [ ]:
# This is a reminder of what a loop looks like

for i in range(20):
    print('still in loop')
print('Loop completed!')
In [ ]:
# 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!')
In [ ]:
# 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!')
In [ ]:
# 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!')

While loops

In [ ]:
# This is the generic syntax for a while loop

while CONTIDION:
    LOOP_BODY
In [ ]:
# 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!')
In [ ]:
# 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!')
In [ ]:
# What is different about this and the one two above?

i = 0
while i < 10:
    i += 1
    print(i)
print('Loop completed!')
In [ ]:
# WARNING!!!!
# You can have loops that run forever.
# These are really really bad.
# Make sure the loop terminates.

while True:
    print('hi!')
In [ ]:
# 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!
In [ ]:
# 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!')
In [ ]:
# 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!')
In [ ]:
# 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
In [ ]:
# What will happen?

i = 0
while True:
    i += 1
    if i > 10:
        break
    print(i)
In [ ]:

In [ ]: