1 of 56

Syntactic Sugar

Jake Shoudy

Nov 18, 2022

CSCI 110 - Lecture 33

2 of 56

Announcements

3 of 56

HW10

Last assignment

Classes and sorting

Due Monday November 21st at 11:59pm

4 of 56

Final Exam Date!

Tuesday 11/29 during normal lab hours

  • 8-10am
  • 12:30-2:20pm
  • 3-4:50pm

5 of 56

Final Exam Topics

Binary <-> Base 10

Data types

Operators (arithmetic, comparison, logical)

Variables

if / elif / else

while loops

Strings (length, index, slice)

Functions

For Loops

Will include short answer & coding questions

Lists

2D Lists

Big O

Sets

Dictionaries

Nested Dictionaries

Scope

Pass by Reference vs Pass by Value

Classes

Sorting

6 of 56

Reminder: NO CLASS NEXT WEEK

Cancelling class on Monday and Tuesday

Wednesday - Friday are school holidays

There will be a Kahoot review session on Monday the 28th

7 of 56

Practice Test!

I will release a practice test next week (goal is by Wednesday)

Take it on your own time over the following weekend and use it to study!!

8 of 56

Recap

9 of 56

Recursion

  • recursion: defining a problem in terms of itself.
  • recursive programming: Writing methods that call themselves to solve problems recursively.
    • An equally powerful substitute for iteration (loops)
    • Particularly well-suited to solving certain types of problems

10 of 56

Recursion

  • Every recursive algorithm involves at least 2 cases:
    • base case: A simple occurrence that can be answered directly.
    • recursive case: A more complex occurrence of the problem that cannot be directly answered, but can instead be described in terms of smaller occurrences of the same problem.
  • Some recursive algorithms have more than one base or recursive case, but all have at least one of each. – A crucial part of recursive programming is identifying these cases

11 of 56

Mystery Function

def mystery(num):

if num == 1:

return 1

else:

return num * mystery(num - 1)

12 of 56

Thinking recursively

mystery(5) = 5 * mystery(4)

4 * mystery(3)

3 * mystery(2)

2 * mystery(1)

13 of 56

Thinking recursively

mystery(5) = 5 * mystery(4)

4 * mystery(3)

3 * mystery(2)

2 * 1

14 of 56

Thinking recursively

mystery(5) = 5 * mystery(4)

4 * mystery(3)

3 * 2

15 of 56

Thinking recursively

mystery(5) = 5 * mystery(4)

4 * 6

16 of 56

Thinking recursively

mystery(5) = 5 * 24

17 of 56

Thinking recursively

mystery(5) = 120

18 of 56

Factorial!

def factorial(num):

if num == 1:

return 1

else:

return num * mystery(num - 1)

Base case

Recursive case

19 of 56

Recursive art!

20 of 56

Syntactic Sugar

21 of 56

Language Expressiveness

Think about human languages. There are some words that can’t be translated into English.

Schadenfreude

Schaden - freude

harm - joy

A German word meaning “A feeling of enjoyment that comes from seeing or hearing about the troubles of other people”

Programming languages are the same - some languages have concise ways to express ideas that are harder to express in other languages.

22 of 56

“Syntactic Sugar”

Syntactic Sugar isn’t an official coding term, but you’ll hear it used to describe types of constructs in coding languages that are pleasing.

It refers to any kind of syntax that makes the code “sweeter” for human use, whether for reading or writing the code.

Python is known for providing lots of “syntactic sugar”, and sometimes you’ll hear people describe using this syntactic sugar in Python as writing “Pythonic” code”

23 of 56

“Syntactic Sugar”

None of the new ideas from this lecture will enable you to do something you couldn’t do before.

They will just make some idea easier to implement than you could without them.

24 of 56

Boolean “zen”

25 of 56

Working with booleans

This code works!

def is_smaller(a, b):

if a < b == True:

return True

elif a >= b == True:

return False

26 of 56

Working with booleans

Better!

def is_smaller(a, b):

if a < b:

return True

else:

return False

27 of 56

Boolean “zen”

Best!

def is_smaller(a, b):

return a < b

28 of 56

Ternary Operator

29 of 56

Ternary Operator

The ternary operator (meaning “having three parts”) is an expression that will evaluate to one of two values, based on what the condition inside evaluates to.

<val1> if <condition> else <val2>

30 of 56

Ternary Operator

Without Ternary Operator

def generate_ticket(speed_over):

if speed_over < 10:

ticket = 0

else:

ticket = 100

print("Pay $" + str(ticket))

def generate_ticket(speed_over):

ticket = 0 if speed_over < 10 else 100

print("Pay $" + str(ticket))

With Ternary Operator

You can use the ternary operator to simplify your code in situations where both cases in the conditional just set a value to a variable.

31 of 56

List Comprehensions

32 of 56

Motivation - Creating Sequences

Make me a list of the powers of 2 from 1 to 10.

The way we already know: use a range, use `**` to exponentiate, add to list

4 lines seems like a lot of lines...

powers_of_two = []

for i in range(1, 11):

result = 2 ** i

powers_of_two.append(result)

print(powers_of_two)

33 of 56

List Comprehensions

We can use the list comprehension construct to quickly and easily generate a list involving iteration over an existing sequence.

The syntax is designed to read like English: "Compute the expression for each element in the sequence (if the conditional is true for that element)."

[<expression> for <element> in <sequence> if <conditional>]

The conditional part is optional

34 of 56

List Comprehension

Using list comprehension to generate the first 10 powers of two...

powers_of_two = [2 ** i for i in range(1, 11)]

35 of 56

List Comprehension Examples

Let’s look at a more complicated example:

This list comprehension will:

  • Compute the expression i**2
  • For each element i in the sequence [1, 2, 3, 4]
  • Where i % 2 == 0 (i is an even number)

lst = [i**2 for i in [1, 2, 3, 4] if i % 2 == 0]

Expression

Sequence

Conditional

Element Variable name

36 of 56

List Comprehension Examples

Without List Comprehension

With List Comprehension

lst = []

for i in [1, 2, 3, 4]:

if i % 2 == 0:

lst.append(i**2)

lst = [i**2 for i in [1, 2, 3, 4] if i % 2 == 0]

37 of 56

List Comprehension Examples

Filter a list of number down to just positive numbers

It’s a one-line function!

def filter_positives(nums):

return [x for x in nums if x > 0]

38 of 56

List Comprehension Examples

Can do this for sequence of any type! For example, getting a list of all capital letters.

word = "fisk"

res = [char.upper() for char in word]

print(res)

>> ['F', 'I', 'S', 'K']

39 of 56

List Comprehensions

Be careful! List comprehensions are a powerful but dangerous tool, because they can get very complicated and are harder to read and debug.

For example, what does this list comprehension do? So hard to read!

Just because you can do something with a list comprehension doesn’t mean you should do it with a list comprehension.

[y for x in text if len(x)>3 for y in x]

Important Note

40 of 56

Iterable Unpacking

41 of 56

Iterables

An iterable is anything that you can iterate over. You’ve been using them all along, this is just a name to describe any of:

  • List
  • Set
  • Tuple
  • Dictionary
  • Strings
  • Range

42 of 56

Iterable Unpacking

It is a common pattern to want to assign values in an iterable to individual variables.

Iterable unpacking lets you do this in a prettier way.

coordinates = [10, 23]

x = coordinates[0]

y = coordinates[1]

# Using iterable unpacking

x, y = coordinates

43 of 56

Returning Multiple Values

Note that you can use this to return multiple values from a function!

def min_and_max(nums):

min_num = nums[0]

max_num = nums[0]

for num in nums:

if num > max_num:

max_num = num

if num < min_num:

min_num = num

return min_num, max_num

nums = [4, 2, 10, 6, -1, 3]

mini, maxi = min_and_max(nums)

44 of 56

Dictionary Comprehensions

45 of 56

Dictionary Comprehensions

Very similar to List Comprehensions, we can use Dictionary Comprehension syntax to make creating dictionaries based on an iterable easier.

The syntax is designed to read like English: "Compute the key expression and associated value expression for each element in the sequence (if some conditional is true)."

{<key expression>:<value expression> for <element> in <sequence> if <conditional>}

The conditional part is optional

46 of 56

Dictionary Comprehension Examples

powers_of_2 = {i:2**i for i in range(5)}

print(powers_of_2)

>> {0: 1, 1: 2, 2: 4, 3: 8, 4}

47 of 56

Filtering Dictionaries with Comprehensions

The `.items()` function of a dictionary returns a list of key, value tuples in the dictionary.

grades = {"Alex": 90, "Sarah": 95, "Andre": 87}

print(grades.items())

>> [('Alex', 90), ('Sarah', 95), ('Andre', 87)]

48 of 56

Filtering Dictionaries with Comprehensions

Combining this with iterable unpacking, we can access both the key and value of a dictionary inside a dictionary comprehension.

For example, to filter a dictionary down to just the keys/values where the key starts with an A:

grades = {"Alex": 90, "Sarah": 95, "Andre": 87}

a_grades = {k:v for k,v in grades.items() if k[0] == "A"}

print(a_grades)

>> {'Alex': 90, 'Andre': 87}

49 of 56

Conclusion

50 of 56

You all have learned SO MUCH

Binary <-> Base 10

Data types

Operators (arithmetic, comparison, logical)

Variables

if / elif / else

while loops

Strings (length, index, slice)

Functions

For Loops

Lists

2D Lists

Mutability

Images

Big O

Sets

Dictionaries

Nested Dictionaries

Scope

Pass by Reference vs Pass by Value

Classes

Sorting

Recursion

Terminal

Unit testing and Integration Testing

51 of 56

What’s next?

csci110.org will stay up forever. Reference the website/slides to review material as needed, or share with friends who want to learn to code.

Decide whether to take take more CS classes. I encourage you all to learn more CS, but I know not everyone has the time or desire...that said, it is a fun field to study and fantastic field to get a job in.

52 of 56

If you will take more CS classes...

Bias for learning concepts over languages. To that end, where the option exists, I advise you take classes in a wider array of languages, as each language exposes you to new concepts.

Make sure to try a systems class (operating systems or networking), a theory class (algorithms), and a machine learning class to know a bit about each subfield.

If you’re at all interested in software engineering, security, systems, computer architecture, and most anything else within Computer Science:

  • Learn other lower-level languages - make sure to take a C++ class.

For those of you only interested in data science, mathematical modeling, etc...

  • Python is very commonly used for these, along with R. Get good at Python.

53 of 56

If you aren’t taking more CS classes...

Go forth into your field armed with the problem solving techniques you’ve learned in this class. You may find that CS will be very useful in your field in the next 5-10 years, and you’ll be prepared.

Remember that you can always come back and learn more in the future. For self-paced CS courses, I recommend the following:

  • coursera.org
  • edx.org
  • YouTube tutorials

54 of 56

Practice!

Whether you’re planning on interviewing for software engineering internships/jobs or just want more coding practice here are a couple of resources:

  • codingbat (simpler lists and string questions)
  • Leetcode*
  • Hackerrank*

* Wide range of difficulty here so don’t get discouraged :) Most questions are labeled with difficulty. Start with just the “easy” problems

55 of 56

Reach Out!

As you navigate your time in college, and start your careers after graduating, stay in touch. Let me know how things are going, ask for advice on classes to take, or topics to learn, or tutorials to follow.

Talk to me or any Fisk TAs while we’re here, csci110.org/staff.

56 of 56

THANK YOU!