Review

CSCI 1012

Announcements

  • Homework 12 is due Friday, 25 Apr 11:55 PM
    • Extra five days, not a Sunday
  • Next week (4/28): Unit 2 Exam
  • Optional Final Exam is May 5 (5:20-7:20pm)

Unit 2 Exam

  • 28 Apr – 3:45-5:00 PM – 1957 E St. 213
  • In person, on paper:
    • Identical format to quizzes and Unit 1 Exam
  • Notes permitted:
    • 1 side of one page (8.5” \(\times\) 11” or A4)
    • Notes must be hand-written by you
      • Talk to us if this is a challenge

Final Exam (Optional)

  • 5 May – 5:20-7:20 PM – 1957 E St. 213
  • Identical format as quizzes and midterms
  • 1 side of one page of notes permitted
  • Maximum score: 70%
    • Replaces all quizzes/exams it is higher than
  • We will tell you in advance if you can take it
    • Fall 2024: c. 2/3 of class had B+ or better without final

Course Evaluations are Live!

  • Course evaluations help us improve the course
  • If at least 85% of the class fills out the course evals, everybody will get an extra percent on their final grade
  • Please be constructive in your evaluations!
  • Link to submit course evals
  • Deadline: May 2nd

In-Class Exercises

  • File names:
    • ex1.py
    • ex2.py
    • ex3.py
  • Turn in on the submit server before the end of lecture for credit
  • Turn in one .zip with all the .py files
  • Unlimited attempts: we’ll provide solutions – pay attention!

In-Class Exercise 1

Write a function ex1 that takes a tuple as an argument:

  • All elements of the tuple will be ints

  • Return the difference between (i) the digits concatenated and (ii) the sum of the integers

  • ex1((4, 0)) returns int 36

    • 40 - (4 + 0) = 36
  • ex1((2, 4, 2, 9, 0, 3)) returns int 242883

    • 242903 - (2 + 4 + 2 + 9 + 0 + 3) = 242883

Submit as ex1.py

Review

  • str(4) gives the string '4'
  • int('4') gives the integer 4
  • Concatenating strings: 'abc' + 'def' gives 'abcdef'
  • Looping/iterating:
T = (1,2)
for i in range(len(T)):
  print('The current index is', i, '. The current element is', T[i])
The current index is 0  The current element is 1
The current index is 1  The current element is 2
for j in T:
  print(j)
1
2

Hints

  • You need to loop through the tuple to (i) concatenate all of the elements into a string (that you will then turn into an integer) and to (ii) add all of the elements to get the sum.

In-Class Exercise 2

Write a function ex2 that takes a string and a list as arguments. Your function will return the index of the first character in the string that appears in the list. If no characters in the string appear in the list return the boolean False. Submit as ex2.py

  • ex2('cat', [4, 2, 'c', 'a']) returns 0
    • 'c' appears in the list and is at index 0 in the string
  • ex2('cat', [4, 2, 'a']) returns 1
    • 'a' (index 1) is the first character that appears in the list
  • ex2('cat', [4, 2, 'z', 0, 'y']) returns False
    • None of the characters in 'cat' appear in the list

Review Part 1

  • Looping/iterating through strings:
s = 'happy'
for i in range(len(s)):
  print(i, s[i])
0 h
1 a
2 p
3 p
4 y
for j in s:
  print(j)
h
a
p
p
y

Review Part 2

  • Use in to check whether an element occurs in a string/list/dictionary/etc.
    • 's' in ['a', 'b', 's'] returns True
    • 't' in ['a', 'b', 's'] returns False
    • 's' in 'substring' returns True
    • 'a' in 'substring' returns False

Hint for Exercise 2

  • You’ll want to loop through the string and check whether the character at each index occurs in the list.

In-Class Exercise 3

Write a function ex3 that takes a list of strings as its argument. Return a new list that contains only the strings that are all lower-case.

  • ex3(['bob', 'hahah', 'madam', 'Boy']) returns ['bob', 'hahah', 'madam']
  • ex3(['Fun', 'Cat', 'Hat', 'yay']) returns ['yay']
  • ex3(['FUN', 'CAT', 'HAT']) returns []

Submit as ex3.py

Review Part 1

  • Looping/iterating through lists:
L = [4, 3]
for i in range(len(L)):
  print(i, L[i])
0 4
1 3
for j in L:
  print(j)
4
3

Review Part 2

  • You can append elements to a list:
L = [1,2,3]
L.append(4)
print(L)
[1, 2, 3, 4]
  • [1, 2, 3] + [4] gives [1, 2, 3, 4]

  • You can lower-case and upper-case strings:

    • 'HAPPY'.lower() gives the string 'happy'
s = 'happy'
print(s.upper())
HAPPY

Hint for Exercise 3

  • You’ll want to loop through the list, check whether the strings are lower-case (are the strings the same as a lower-cased version?), and append those that are

In-Class Exercise 4

Write a function ex4 that takes a tuple as an argument and returns a dictionary where the keys are the unique elements that occured in the tuple and the values are the number of times they occurred.

  • ex4(('bob', 'hahah', 'madam', 'bob')) returns {'bob': 2, 'hahah': 1, 'madam': 1}
  • ex4(('a', 'a', 'a', 'b')) returns {'a': 3, 'b': 1}

Submit as ex4.py

Review Part 1

  • You can access elements of a dictionary via the keys:
gradebook = {'Jill': 100, 'Leo': 94, 'Maria': 85, 'Bruno': 90}
print(gradebook['Leo'])
94
  • If you try to access a key that’s not in the dictionary, you will get a Key Error. Use in to check whether something is a key in the dictionary first.

Review Part 2

  • Dictionaries are great for counting things:
s = "aaabbc"
counter = {}
for char in s:
  if char in counter:
    counter[char] += 1
  else:
    counter[char] = 1

Hint for Exercise 4

  • As on the last slide, you’ll want to similarly loop through the tuple and increment the counts in a dictionary

In-Class Exercise 5

Write a function ex5 that takes a list of integers/floats. Your function will return the string 'positive' if the product of all of the numbers is greater than 0, 'negative' if the product of all of the numbers is less than 0, or 'zero' if the product of all of the numbers is 0.

  • ex5([1, 2, 4, 0]) returns 'zero'
  • ex5([1, 2, -1]) returns 'negative'
  • ex5([1, 2, 4]) returns 'positive'
  • ex5([-1, 2, -1]) returns 'positive'

Submit as ex5.py

Review Part 1

  • Looping/iterating through lists:
L = [4, 3]
for i in range(len(L)):
  print(i, L[i])
0 4
1 3
for j in L:
  print(j)
4
3

Review Part 2

  • If/Elif/Else Statements
if (CONDITION1):
  # Indented code that executes if CONDITION1 is True
elif (CONDITION 2):
  # Indented code that executes if CONDITION1 is False 
  # and CONDITION2 is True
elif (CONDITION 3):
  # Indented code that executes if CONDITION1 and CONDITION2 are False 
  # and CONDITION 3 is True
else:
  # Indented code that executes if CONDITION1, CONDITION2, CONDITION3 
  # are all False

Hint for Exercise 5:

  • One approach: Loop through the elements in the list and multiply them in one-by-one to get the final product. Then check whether this final value is positive, negative, or zero.

In-Class Exercise 6

Write a function ex6 that takes a lowercase string as its argument. If the substring consisting of the first two characters of the string occur later alphabetically than the substring consisting of the last two characters of the string, return a new string where those substrings are swapped. Otherwise, return the original string. Submit as ex6.py

  • ex6('elephant') returns 'elephant'
    • 'el' < 'nt', so we don’t change the string
  • ex6('telephone') returns 'nelephote'
    • 'te' > 'ne', so we return 'ne' + 'lepho' + 'te'

Review

  • You can retrieve a substring of a string
    • Uses: a start position, a stop-before position, and a spacing, separated by colons
s = "concatenate"
s[1:3]
'on'
s = "concatenate"
s[0:3:2]
'cn'
  • The comparison operators > and < between strings check for alphabetical order for lowercase letters.

Extra Exercise 7

Write a function ex7 that takes a list (of strings) as its argument. If the first element of the list is later alphabetically than the last element of the list, swap them. Otherwise, keep the list the same. Return the resulting list.

  • ex7(['b', 'c', 'd', 'a']) returns ['a', 'c', 'd', 'b']
  • ex7(['a', 'c', 'd', 'b']) returns ['a', 'c', 'd', 'b']
  • ex7(['a', 'd']) returns ['a', 'd']
  • ex7(['d', 'a']) returns ['a', 'd']

Extra Exercise 8

Write a function ex8 that takes a string as input and returns the first character that only occurs once.

  • ex8('grant') returns 'g'
  • ex8('lollipop') returns 'i'
  • ex8('ababc') returns 'c'
  • ex8('baaaa') returns 'b'

Extra Exercise 9

Write a function ex9 that takes a string as input and returns the first substring where each subsequent character is later alphabetically.

  • ex9('abcda') returns 'abcd'
  • ex9('ba') returns 'b'
  • ex9('abcd') returns 'abcd'
  • ex9('aba') returns 'ab'

Extra Exercise 10

Write a function ex10 that reverses In-Class Exercise 4. It will take a dictionary as its argument and will return a tuple where each key in the dictionary occurs the number of times decided by the key’s value in the dictionary. The elements in the tuple can occur in any order.

  • ex10({'bob': 2, 'hahah': 1, 'madam': 1}) returns ('bob', 'bob', 'hahah', 'madam')
  • ex10({‘a’: 3, ‘b’: 1}`) returns (‘a’, ‘a’, ‘a’, ‘b’)