CS 330 - Artificial Intelligence - Python in one week II - - PowerPoint PPT Presentation

cs 330 artificial intelligence
SMART_READER_LITE
LIVE PREVIEW

CS 330 - Artificial Intelligence - Python in one week II - - PowerPoint PPT Presentation

1 CS 330 - Artificial Intelligence - Python in one week II Instructor: Renzhi Cao Computer Science Department Pacific Lutheran University Fall 2019 Materials adopted from Kaggle Overview Learning Python in a week Future Homework


slide-1
SLIDE 1

CS 330 - Artificial Intelligence

  • Python in one week II

Instructor: Renzhi Cao Computer Science Department Pacific Lutheran University Fall 2019 1

Materials adopted from Kaggle

slide-2
SLIDE 2

Overview

  • Learning Python in a week

2

  • Discussion: Postpone quiz #1 to next Tuesday?

Go over Python on Thursday?

  • Reminder: extra credit by attending the

symposium

  • Future Homework submission link:

https://www.cs.plu.edu/submit

slide-3
SLIDE 3

Overview

  • Debugging:

3

print(“Hello” + 133); # print something smallNumber(10) # call a function def smalNumber(a,b) if a < b: print(a) print(b)

slide-4
SLIDE 4

Python introduction

  • import

4

import math print("It's math! It has type {}".format(type(math))) print(dir(math)) print("pi to 4 significant digits = {:.4}".format(math.pi)) math.log(32, 2)

slide-5
SLIDE 5

Python introduction

  • import

5

import math as mt mt.pi from math import * print(pi, log(32, 2)) import * makes all the module's variables directly accessible to you (without any dotted prefix). Bad news: some purists might grumble at you for doing this.

slide-6
SLIDE 6

Python introduction

  • import

6

from math import * from numpy import * print(pi, log(32, 2))

  • TypeError Traceback (most recent call last)

<ipython-input-10-9b512bc684f5> in <module>() 1 from math import * 2 from numpy import *

  • ---> 3 print(pi, log(32, 2))

TypeError: return arrays must be of ArrayType

slide-7
SLIDE 7

Python introduction

  • import

7

from math import * from numpy import * print(pi, log(32, 2)) The problem in this case is that the math and numpy modules both have functions called log, but they have different semantics. Because we import from numpy second, its log overwrites (or "shadows") the log variable we imported from math. from math import log, pi from numpy import asarray

slide-8
SLIDE 8

Python introduction

  • Three tools to understand strange objects

8

1: type() (what is this thing?) type(rolls) 2: dir() (what can I do with it?) print(dir(rolls)) 3: help() (tell me more) help(rolls.ravel)

slide-9
SLIDE 9

Python introduction

  • syntax, variable assignment, numbers
  • functions and getting help
  • booleans and conditionals
  • lists and objects
  • loops and list comprehensions
  • strings and dictionaries
  • files and trees

9

slide-10
SLIDE 10

Lists and objects

Lists

Lists in Python represent ordered sequences of values. They can be defined with comma-separated values between square

  • brackets. For example, here is a list of the first few prime

numbers:

10

primes = [2, 3, 5, 7] planets = ['Mercury', 'Venus', 'Earth', 'Mars', 'Jupiter', 'Saturn', 'Uranus', 'Neptune'] hands = [ ['J', 'Q', 'K'], ['2', 100, '2'], [6, 'A', '3'], # (Comma after the last element is optional) ] # (I could also have written this on one line, but it can get hard to read) hands = [['J', 'Q', 'K'], ['2', 100, '2'], [6, 'A', '3']]

slide-11
SLIDE 11

Lists and objects

Lists

Indexing is based on square bracket indexing.

11

planets = ['Mercury', 'Venus', 'Earth', 'Mars', 'Jupiter', 'Saturn', 'Uranus', ‘Neptune'] planets[0] would be ‘Mercury’. Which planet is furthest from the sun? planets[-1] What are the first three planets? planets[0:3] Guess what is: planets[:3], planets[3:], planets[1:-1], planets[-3:] ?

slide-12
SLIDE 12

Lists and objects

Lists

List is mutable.

12

test = [‘A’,’B’,’C’,’D’] test[0] = ‘D’ You could even do: test[0:3] = [‘D’,’D’,’D’]

slide-13
SLIDE 13

Lists and objects

Lists related functions

13

len: gives the length of the list len(planets) sorted: returns a sorted version of a list: sorted(planets) sum: does what you might expect: sum(primes) And also min, max.

slide-14
SLIDE 14

Lists and objects

Everything in Python is an object

14

For example, numbers in Python carry around an associated variable called imag representing their imaginary part. (You'll probably never need to use this unless you're doing some very weird math.) x = 12 # x is a real number, so its imaginary part is 0. print(x.imag) # Here's how to make a complex number, in case you've ever been curious: c = 12 + 3j print(c.imag)

slide-15
SLIDE 15

Lists and objects The things an object carries around can also include functions. A function attached to an object is called a method. (Non- function things attached to an object, such as imag, are called attributes).

15

For example, numbers have a method called bit_length. Again, we access it using dot syntax: x.bit_length To actually call it, you could do: x.bit_length()

slide-16
SLIDE 16

Lists and objects

Lists related methods

16

list.append modifies a list by adding an item to the end: planets.append('Pluto') # Pluto is a planet darn it! list.pop removes and returns the last element of a list: planets.pop() list.index: get index of searching: planets.index('Earth') The index method may through exception if the element is not in your list. To avoid it, you could: if ‘Pluto’ in planets: return planets.index(‘Pluto’)

slide-17
SLIDE 17

Lists and objects

Tuples: similar to list.

17

  • 1. The syntax for creating them uses (optional) parentheses rather

than square brackets t = (1, 2, 3) or t = 1, 2, 3

  • 2. They cannot be modified (they are immutable).

t[0] = 100

  • TypeError Traceback (most recent call last)

<ipython-input-36-155b9e8fb284> in <module>()

  • ---> 1 t[0] = 100

TypeError: 'tuple' object does not support item assignment

slide-18
SLIDE 18

Lists and objects

Tuples are often used for functions that have multiple return values.

18

Example: the as_integer_ratio() method of float objects returns a numerator and a denominator in the form of a tuple: x = 0.125 x.as_integer_ratio() will return (1,8) You could do: numerator, denominator = x.as_integer_ratio() Guess the output? a = 1 b = 0 a, b = b, a print(a, b)

slide-19
SLIDE 19

Exercise

  • Try: CS330_ex4.py
slide-20
SLIDE 20

10 mins break

slide-21
SLIDE 21

Review

21

  • syntax, variable assignment, numbers
  • functions and getting help
  • booleans and conditionals
  • lists and objects
  • loops and list comprehensions
  • strings and dictionaries
  • files and trees
slide-22
SLIDE 22

Python introduction

  • syntax, variable assignment, numbers
  • functions and getting help
  • booleans and conditionals
  • lists and objects
  • loops and list comprehensions
  • strings and dictionaries
  • files and trees

22

slide-23
SLIDE 23

Loops and list comprehensions

Loops

Loops are a way to repeatedly execute some code statement.

23

planets = ['Mercury', 'Venus', 'Earth', 'Mars', 'Jupiter', 'Saturn', 'Uranus', 'Neptune'] for planet in planets: print(planet, end=' ') # print all on same line multiplicands = (2, 2, 2, 3, 3, 5) product = 1 for mult in multiplicands: product = product * mult product

slide-24
SLIDE 24

Loops and list comprehensions

24

s = 'steganograpHy is the practicE of conceaLing a file, message, image, or video within another fiLe, message, image, Or video.' msg = '' # print all the uppercase letters in s, one at a time for char in s: if char.isupper(): print(char, end='')

slide-25
SLIDE 25

Loops and list comprehensions

range

range() is a function that returns a sequence of numbers. It turns out to be very useful for writing loops.

25

For example, if we want to repeat some action 5 times: for i in range(5): print("Doing important work. i =", i) help(range) list(range(5)) => [0, 1, 2, 3, 4]

slide-26
SLIDE 26

Loops and list comprehensions

range

for any list L, for i in range(len(L)): will iterate over all its valid indices.

26

nums = [1, 2, 4, 8, 16] for i in range(len(nums)): nums[i] = nums[i] * 2 nums nums = [1, 2, 4, 8, 16] for i in range(3, len(nums)): # if you want to count from index 3 nums[i] = nums[i] * 2 nums

slide-27
SLIDE 27

Loops and list comprehensions

enumerate

for foo in x loops over the elements of a list and for i in range(len(x)) loops over the indices of a list. What if you want to do both?

27

def double_odds(nums): for i, num in enumerate(nums): if num % 2 == 1: nums[i] = num * 2 x = list(range(10)) double_odds(x) x Given a list, enumerate returns an object which iterates over the indices and the values of the list. list(enumerate(['a', ‘b’])) => [(0, 'a'), (1, 'b')]

slide-28
SLIDE 28

Loops and list comprehensions We can use this unpacking syntax any time we iterate over a collection of tuples.

28

nums = [ ('one', 1, 'I'), ('two', 2, 'II'), ('three', 3, 'III'), ('four', 4, 'IV'), ] for word, integer, roman_numeral in nums: print(integer, word, roman_numeral, sep=' = ', end='; ') for tup in nums: word = tup[0] integer = tup[1] roman_numeral = tup[2] print(integer, word, roman_numeral, sep=' = ', end='; ')

slide-29
SLIDE 29

Loops and list comprehensions

while loop

29

i = 0 while i < 10: print(i, end=' ') i += 1

slide-30
SLIDE 30

Loops and list comprehensions

List comprehensions

List comprehensions are one of Python's most beloved and unique features. The easiest way to understand them is probably to just look at a few examples:

30

squares = [n**2 for n in range(10)] squares squares = [] for n in range(10): squares.append(n**2) squares short_planets = [planet for planet in planets if len(planet) < 6] short_planets

slide-31
SLIDE 31

Loops and list comprehensions

List comprehensions

Here's an example of filtering with an if condition and applying some transformation to the loop variable:

31

# str.upper() returns an all-caps version of a string loud_short_planets = [planet.upper() + '!' for planet in planets if len(planet) < 6] loud_short_planets [ planet.upper() + '!' for planet in planets if len(planet) < 6 ]

slide-32
SLIDE 32

Loops and list comprehensions

List comprehensions

List comprehensions combined with some of the functions we've seen like min, max, sum, len, and sorted, can lead to some pretty impressive one-line solutions for problems that would otherwise require several lines of code.

32

def count_negatives(nums): “"" Return the number of negative numbers in the given list. >>> count_negatives([5, -1, -2, 0, 3]) 2 """ n_negative = 0 for num in nums: if num < 0: n_negative = n_negative + 1 return n_negative def count_negatives(nums): return len([num for num in nums if num < 0])

slide-33
SLIDE 33

Loops and list comprehensions

List comprehensions

List comprehensions combined with some of the functions we've seen like min, max, sum, len, and sorted, can lead to some pretty impressive one-line solutions for problems that would otherwise require several lines of code.

33

def count_negatives(nums): return len([num for num in nums if num < 0]) def count_negatives(nums): # Reminder: in the day 3 exercise we learned about a quirk of Python where it calculates # something like True + True + False + True to be equal to 3. return sum([num < 0 for num in nums])

slide-34
SLIDE 34

Python introduction

  • syntax, variable assignment, numbers
  • functions and getting help
  • booleans and conditionals
  • lists and objects
  • loops and list comprehensions and dictionaries
  • strings
  • files and trees

34

slide-35
SLIDE 35

Strings and dictionaries

Dictionaries

Dictionaries are a built-in Python data structure for mapping keys to values.

35

numbers = {'one':1, 'two':2, 'three':3} What would be the output of numbers[‘one’]? numbers['eleven'] = 11 numbers {'eleven': 11, 'one': 1, 'three': 3, 'two': 2} numbers['one'] = 'Pluto' numbers {'eleven': 11, 'one': 'Pluto', 'three': 3, 'two': 2}

slide-36
SLIDE 36

Strings and dictionaries

in operator

The in operator tells us whether something is a key in the dictionary

36

'Saturn' in planet_to_initial True

A for loop over a dictionary will loop over its keys

for k in numbers: print("{} = {}".format(k, numbers[k]))

  • ne = Pluto

two = 2 three = 3 eleven = 11

slide-37
SLIDE 37

Strings and dictionaries

Access keys or values in dictionary

  • We can access a collection of all the keys or all the values

with dict.keys() and dict.values(), respectively.

37

# Get all the initials, sort them alphabetically, and put them in a space- separated string. ' '.join(sorted(planet_to_initial.values())) 'E J M M N S U V'

  • The very useful dict.items() method lets us iterate over the keys

and values of a dictionary simultaneously.

for planet, initial in planet_to_initial.items(): print("{} begins with \"{}\"".format(planet.rjust(10), initial))

slide-38
SLIDE 38

Exercise

  • CS330_ex5.py
slide-39
SLIDE 39