cs 330 artificial intelligence
play

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


  1. 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

  2. Overview • Learning Python in a week • Future Homework submission link: https://www.cs.plu.edu/submit • Reminder: extra credit by attending the symposium • Discussion: Postpone quiz #1 to next Tuesday? Go over Python on Thursday? 2

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

  4. Python introduction • import 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) 4

  5. Python introduction • import 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. 5

  6. Python introduction • import 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 6

  7. Python introduction • import 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 7

  8. Python introduction • Three tools to understand strange objects 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) 8

  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

  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: 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']] 10

  11. Lists and objects Lists Indexing is based on square bracket indexing. 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:] ? 11

  12. Lists and objects Lists List is mutable. test = [‘A’,’B’,’C’,’D’] test[0] = ‘D’ You could even do: test[0:3] = [‘D’,’D’,’D’] 12

  13. Lists and objects Lists related functions 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. 13

  14. Lists and objects Everything in Python is an object 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) 14

  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). 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() 15

  16. Lists and objects Lists related methods 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’) 16

  17. Lists and objects Tuples: similar to list. 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 17

  18. Lists and objects Tuples are often used for functions that have multiple return values. 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) 18

  19. Exercise • Try: CS330_ex4.py

  20. 10 mins break

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

  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

  23. Loops and list comprehensions Loops Loops are a way to repeatedly execute some code statement. 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 23

  24. Loops and list comprehensions 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='') 24

  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. 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] 25

  26. Loops and list comprehensions range for any list L, for i in range(len(L)): will iterate over all its valid indices. 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 26

  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? 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')] 27

  28. Loops and list comprehensions We can use this unpacking syntax any time we iterate over a collection of tuples. for tup in nums: word = tup[0] integer = tup[1] roman_numeral = tup[2] print(integer, word, roman_numeral, sep=' = ', nums = [ end='; ') ('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='; ') 28

  29. Loops and list comprehensions while loop i = 0 while i < 10: print(i, end=' ') i += 1 29

  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: squares = [] squares = [n**2 for n in range(10)] for n in range(10): squares squares.append(n**2) squares short_planets = [planet for planet in planets if len(planet) < 6] short_planets 30

Recommend


More recommend