27
loading...
This website collects cookies to deliver better user experience
MET CS 521 O1 Information Structures with Python (2021 Fall 1)
int
bool
float
complex
char
list
tuple
set
dictionary
string
dog_age = 6
vs expressions dog_age + 1
hash()
for quick comparisons (still confused on this)deepcopy()
makes new object==
vs is
==
checks valuesis
checks id
to see if same exact objectchr()
and ord()
range(start, stop, step)
stop
number[start:stop:jump]
string[-1]
{:[alignment][width][decimal precision][type descriptor]}
while
and for
open
,read
, readlines
, write
, writelines
close
numbers = [13, 72, 11, 43, 66, 82]
# iterate to get even numbers
evens_from_nums = []
for num in numbers:
if num % 2 == 0:
evens_from_nums.append(num)
# list comprehension to get even numbers
# same as above, just shorthand
odds_from_nums_again = [num for num in numbers if num % 2 == 0]
.reverse()
enumerate()
for indexed collections
sort()
vs sorted()
sort()
changes things in placesorted()
orders things and creates a new listlist[1][2]
would give index 1 of main list then index 2 of the nested listappend()
pop()
extend()
insert()
remove()
sort()
reverse()
list[::-1]
(gives no start or stop and a -1
step)[:]
(shallow copy?)tuple = ("cat",)
note the trailing comma, otherwise this would not be a tupleappend()
)items()
all key-value pairs as a list of tupleskeys()
all keys as a list of listvalues()
all values as a list of listzip()
2 or more lists together. Tuples by defaultupdate()
(note: for keys that already exist, values will be replaced)small_set <= big_set
vs superset big_set >= small_set
&
or intersection()
creates new set of all elements that are the same|
or union()
creates new set of all elements of both lists-
or difference()
creates new set of all elements in 1st set but not 2nd set^
or symmetric_difference()
creates new set of all elements that are differentsplit()
returns a liststacks
can be made with liststrue_thing if condition else false_thing # ternary syntax
throw_ball() if dog_wants_play else pet_dog() # ternary example
except IndexError as e
to later use e
(the error)finally
it runs every time, not required thoughdef feed_dog(dog_weight):
feed_dog(25.5)
None
if there is no return statementdef pet_cat(time="now"):
if you don't give a different time, cat will be pet now
def func(*args):
this requires a tuple as inputfeed_dog(dog_age=5, dog_weight = 25.5)
def feed_dog(dog_weight: float, dog_age: int):
#syntax
def function_name(param1, param2):
'''what it does, inputs, and outputs'''
# code for your function to do
function_name(arg1, arg2)
# example
def feed_dog(dog_weight: float, dog_age: int):
'''calculate/output how much to feed dog with given dog weight arg'''
pass
feed_dog(25.5, 5)
# -----other ways to call/invoke-----
# how to invoke with out of order args
feed_dog(dog_age=5, dog_weight = 25.5) # also useful when there are a lot of params
# use a dictionary for function args
dog_dict = {"dog_weight":25.5, "dog_age":5} # same names as params
feed_dog(**dog_dict) # using ** to pass a dict
yield
instead of return
return
yield
give results and wait until next time function is called__iter__()
__next__()
Lambda Function
lambda args: expression
map()
filter()
reduce()
Recursion
Classes
dict()
, set()
, list()
etc)self
allows an object to keep it's own data (like this
in js/c++/java)
import copy
class Dog():
__stomach = 1 # a static variable w/ name mangling
# define a constructor
def __init__(self, name):
self.__name = name # w/ name mangling
def __copy__(self): # shallow copy
return Dog(self.__name) # w/ name mangling
def __str__(self):
'''give a string when you print(instance_variable)'''
return 'dog with name: ' + str(self.__name) # w/ name mangling
def add(a,b): #
return Dog(a.__name + b.__name)
def get_stomachs(self): # getter/accessor
return self.__stomach
def eat_dinner(self): # self is like `this` in js/c++/java
'''a class method for the dog to eat dinner'''
# use Class_Name.variable to get the static variable
print(f"{name} reports for dinner with their {Dog.stomach} stomach")
dog_one = Dog("wiley") # makes a Dog just like list() makes a list
dog_one_come = dog_one.eat_dinner()
dog_copy = copy.copy(dog_one)
print(dog_one) # prints return of __str__
__repr__()
"official" object description (example: <__main__.Dog object at 0x7f545b6db8d0>
)__
before name like __stomach
to prevent accidental changing. Dog._Dog__stomach = 4
it would just be less of a chance to do it by accident+
,-
,<
,>
,==
,!=
,&
,!
in a way they weren't already built to do by using "magic methods"def add(self, other): #
return Dog(self.__name + other.__name)
print()
and len()
can be used across different classes and functions__init__
Abstract Classes
Unit Tests
assert
statements to test the expected outputbreak
and continue