In [ ]:
int("24")
Out[ ]:
24
In [ ]:
520//60
Out[ ]:
8
In [ ]:
520%60
Out[ ]:
40

Dictionary (a set of key-value pairs)¶

keys will be limited to numbers and strings and should be unique; UNORDERED¶
In [ ]:
d = {}   # create empty dictionary

# add 'a':5
d['a'] = 5
print(d)

d['a'] = 7
print(d)

print(d['a'])

# how to check if a key is in a dictionary
'b' in d
{'a': 5}
{'a': 7}
7
Out[ ]:
False
In [ ]:
s = "this is a long sentence"
d = {}
d2 = {'a':20, 'b':46}  # create a non-empty dictionary

# Approach 1; go through each letter in s
for c in "abcdefghijklmnopqrstuvwxyz":
    d[c] = 0
    
for c in s:
    if c in d:
        d[c] = d[c] + 1  # d[c] += 1
    else:
        d[c] = 1

print(d)

# Approach 2; go through each letter in the alphabet
for c in "abcdefghijklmnopqrstuvwxyz":
    n = s.count(c)
    d[c] = n

print(d)
{'a': 1, 'b': 0, 'c': 1, 'd': 0, 'e': 3, 'f': 0, 'g': 1, 'h': 1, 'i': 2, 'j': 0, 'k': 0, 'l': 1, 'm': 0, 'n': 3, 'o': 1, 'p': 0, 'q': 0, 'r': 0, 's': 3, 't': 2, 'u': 0, 'v': 0, 'w': 0, 'x': 0, 'y': 0, 'z': 0, ' ': 4}
{'a': 1, 'b': 0, 'c': 1, 'd': 0, 'e': 3, 'f': 0, 'g': 1, 'h': 1, 'i': 2, 'j': 0, 'k': 0, 'l': 1, 'm': 0, 'n': 3, 'o': 1, 'p': 0, 'q': 0, 'r': 0, 's': 3, 't': 2, 'u': 0, 'v': 0, 'w': 0, 'x': 0, 'y': 0, 'z': 0, ' ': 4}
In [ ]:
s = "this is a long sentence"
s.count('e')
Out[ ]:
3

Set; UNORDERED; no duplicates¶

In [ ]:
# create new and empty set
s = set()
# create a new and non-empty set
t = {1,2,3}
print(s)
print(t)
s.add(10)
s.add(20)
s.add(30)
print(s)
s.remove(20)
print(s)
xs = list(s)
print(xs)
set()
{1, 2, 3}
{10, 20, 30}
{10, 30}
[10, 30]

ACCUMULATOR PATTERN¶

In [ ]:
d = {"John": 123, "Kelly":334, "Jon":100, "Alice":900}
xs = list(d)
print(xs)
ks = d.keys()
vs = d.values()
items = d.items()
print(ks)
print(vs)
print(items)

# ACCUMULATOR PATTERN
sum = 0  # accumulator variable
for key in d.keys():
    sum = sum + d[key]
print(sum)
['John', 'Kelly', 'Jon', 'Alice']
dict_keys(['John', 'Kelly', 'Jon', 'Alice'])
dict_values([123, 334, 100, 900])
dict_items([('John', 123), ('Kelly', 334), ('Jon', 100), ('Alice', 900)])
1457
In [ ]:
xs = [10,20,30,40]

product = 1  # accumulator variable
for val in xs:
    product = product * val
    
print(product)
In [ ]:
# produce a string of consonants in s
s = "this is a sentence"

result = ""
for c in s:
    if c not in 'aeiou ':
        result = result + c

print(result)
thsssntnc
In [ ]:
# produce a list of even numbers from a list of numbers
nums = [10,23,76,84,99]

result = []

for num in nums:
    if num%2 == 0:
        result.append(num)

print(result)
[10, 76, 84]
In [ ]:
xs = [("John",123), ("Kelly",334), ("Jon",100), ("Alice",900)]

d = {}
for (a,b) in xs:
    d[a] = b

print(d)
{'John': 123, 'Kelly': 334, 'Jon': 100, 'Alice': 900}

Functions¶

In [ ]:
def extract_digits(num):
    result = []
    while True:
        if num == 0:
            break
        digit = num%10
        num = num//10
        result.insert(0,digit)
        #result.append(digit)
    #result.reverse()
    return result
In [ ]:
def no_repeats1(num):
    digits = extract_digits(num)
    
    unique_digits = set()
    for digit in digits:
        if digit not in unique_digits:
            unique_digits.add(digit)
        else:
            return False
    
    return True
In [ ]:
def no_repeats2(num):
    digits = extract_digits(num)
    return len(digits) == len(set(digits))
In [ ]:
no_repeats1(5784658)
Out[ ]:
False
In [ ]:
no_repeats2(5468)
Out[ ]:
True
In [ ]:
extract_digits(5784658)
Out[ ]:
[5, 7, 8, 4, 6, 5, 8]
In [ ]:
57846%10
Out[ ]:
6
In [ ]:
57846//10
Out[ ]:
5784
In [ ]:
xs = [1,2,3]
xs.reverse()
print(xs)
[3, 2, 1]
In [ ]:
set([1,2,3,1,2])
Out[ ]:
{1, 2, 3}
In [ ]:
xs = [1,2,3,1,2]
len(xs) == len(set(xs))
In [ ]:
def main():   
    guess_num = 1
    target = produce_target()
    while True:
        user_guess = input("Enter guess number",guess_num, ": ")
        # do error check
        guess_num = guess_num + 1
        nbulls = numberOfBulls(target,user_guess)
        ncows = numberOfCows(target,user_guess)
        print("Bulls = ",nbulls,"Cows = ",ncows)
        if guess_num == 11:
            print("You lost")
            break
        if nbulls == 4:
            print("You won")
            break

main()
In [ ]:
xs = [1,2,3]
y = xs.reverse()
print(y)
None

Classes and Objects¶

In [ ]:
class Student():

    #constructor
    def __init__(self,n,m,cs):
        self.name = n
        self.major = m
        self.courses = cs
In [ ]:
s1 = Student("John","CSC",[])