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
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
Materials adopted from Kaggle
2
3
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)
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.
6
from math import * from numpy import * print(pi, log(32, 2))
<ipython-input-10-9b512bc684f5> in <module>() 1 from math import * 2 from numpy import *
TypeError: return arrays must be of ArrayType
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
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)
9
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']]
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:] ?
12
test = [‘A’,’B’,’C’,’D’] test[0] = ‘D’ You could even do: test[0:3] = [‘D’,’D’,’D’]
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.
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)
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()
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’)
17
than square brackets t = (1, 2, 3) or t = 1, 2, 3
t[0] = 100
<ipython-input-36-155b9e8fb284> in <module>()
TypeError: 'tuple' object does not support item assignment
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)
21
22
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
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='')
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]
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
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')]
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='; ')
29
i = 0 while i < 10: print(i, end=' ') i += 1
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
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 ]
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])
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])
34
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}
36
'Saturn' in planet_to_initial True
for k in numbers: print("{} = {}".format(k, numbers[k]))
two = 2 three = 3 eleven = 11
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'
and values of a dictionary simultaneously.
for planet, initial in planet_to_initial.items(): print("{} begins with \"{}\"".format(planet.rjust(10), initial))