Study your flashcards anywhere!

Download the official Cram app for free >

  • Shuffle
    Toggle On
    Toggle Off
  • Alphabetize
    Toggle On
    Toggle Off
  • Front First
    Toggle On
    Toggle Off
  • Both Sides
    Toggle On
    Toggle Off
  • Read
    Toggle On
    Toggle Off
Reading...
Front

How to study your flashcards.

Right/Left arrow keys: Navigate between flashcards.right arrow keyleft arrow key

Up/Down arrow keys: Flip the card between the front and back.down keyup key

H key: Show hint (3rd side).h key

A key: Read text to speech.a key

image

Play button

image

Play button

image

Progress

1/105

Click to flip

105 Cards in this Set

  • Front
  • Back
yield
saves the state and is the only statement that is needed to make a generator from a standard function defintion
with-statements
can take any object that are a context manager// which is anything that defines __enter__// and __exit__// introduced to 2.7
Where can you find the modules index?
http://docs.python.org/modindex.html
When you input a module, where does it go?
sys.modules
What is the danger of using from MODULE import *?
Can still call local variables. So you should always be explicit and say exactly what you are importing.
What is the best way to spend an hour stuck in an airport?
Review built-in functions
What are the key methods of the module struct?
pack and unpack
Useful ordering functions
sorted()
list.sort()
min()
max()
nsmallest()
nlargest()
bisect()
insort()
super() has two simple ordering rules
[1] children before parents. [2] parents in order specified
super()
also dependency injection. It lets you call into a supplier and ask who their suppliers are and then you can choose another supplier (such as if you want organic// or you can swap off a choose a new dictionary). Dependency injection is very hot in development// a must if you are doing larger projects. Super() gets you tons of re-use.
What is a static method?
Has to have a @staticmethod a way to stick a function inside a class// they don't need an instance// the only difference from the outside is they need a a prefic of the class
sorted(s//key=lambda r:r[2])
use the second field as the primary key
sorted()
returns a new list
reverse the string
index.html[::-1]
def: protocol
means use the same interface across programs.
module gc
you can use this module to collect garbage now// such as gc.collect() do it now. and gc.disable() don't do anything. GC is expensive// so you can control when it runs.
map vs. list comprehensions
Map is easy paralyzed so it gets a speed up with a system that has multiple cores
magic method means...
special method (__add__)
LLVM
low-level virtual machine
list-comprehensions
one of the most loved language features// very popular addition to Python// derived from notation used in mathematics// clean and beautiful// much more flexible then map// filter// reduce
key functions
[1] Specifies a custom sort order. [2] Applies to each key no more than once. [3] complex sort orders rely on multiple passes.
iterators
[1] They are the the most important concept. They make the language simple and clean. [2] They help everything fit together. sorted(set(open(somefilename))) same as # cat somefile | sort | uniq
iterator
an object with state that is responsible for producing a sequence of values// has a next() method that: * returns the next value in the sequence * updates the pointer to the next item * raises StopIteration when it is done is self-iterable -- meaning that it has an __iter__ method that returns self.
iter()
has a two argument form that takes a function and sentinel value. example: for block in iter(partial(f.read//20)//''):...
it is so foreign
that even very experienced programmers didn't know what to do with it when they first saw it.
introspection
adds a capability that is off-limits to static languages// lets us build tools like inspect// pydoc// help// metaclasses// doctests// unittest discovery// debuggers// etc
install means
to install mean to stick it somewhere on your path
if want the last two items in a list?
w[-2:] reads as Back up to and then take the rest of list.]
How to put two lists into a dictionary?
dict(zip(s//w))
How do you delete an element in a list?
del w[1]
help()
gets you the docstring
good technique is...
putting spaces inbetween methods
def: generators
easiest way to write an Iterator// simple syntax only adds the YIELD keyword// Remembers state between invocations: the stack including open loops and try-statements; the execution pointer; and local variables
Dunder for x < y
x.___lt__(y)
dunder
how you pronounce double under score for special methods// example. __add__ say// 'Dunder add'
Don't use getters() and setters() in python
use property()
dir()
gives you all methods associated to object
dict(enumerate('abc')) >> {0:'a'//1:'b'//'2:'c'}
enumerate consumes the string and gives you a tuple and then gets fed into dictionary that gives you a dictionary with key value pairs
deque
gets cache locality and used in scheduling. It's very fast. Short for 'double ended q' pronounced 'deck' or also 'dq'. IF popping stuff and everything is moving over in memory. What to you do? Use deque.
del w[1] IS THE SAME AS
w.__delitem__(1)
def: BLOB
binary large object
def: decorators
expressive easy on the eye works for functions methods and classes adds powerful layer of composable tools
copy a list
c = s[:]
with-statements
can take any object that are a context manager// which is anything that defines __enter__// and __exit__// introduced to 2.7
common organizing information for patterns
tuple for fields with heterogenous type// and then put those tuples in a list that are of the same type that you can loop over
Collections method
[1] another data structure to help you. [2] deque - Fast 0(1) appends and pop from both ends. d.append(10) adds to right. d.popleft() fetches from left side. [2] Named tuples - like regular tuples// but also allows access using named attributes. point = namedtuple('Point'//'x y'). p - Point(10//20) print p.x. [3] defaultdict - like a regular dictionary but supplies a factory function to fill-in missing values. [5] counter - a dictionary that knows how to count. [6 orderedDict - a dictionary that remembers insertion order.
clear
None. Remove all items from D.
Can you turn all you built-ins into decorators?
Yes! Great coder.
Cache is great// but what is the problem with it?
It grows without bound. There must be a better way. Look at LRU cache.
Bloom filters
heavily used by google for any front coming queries
bisect.insort(t, 50)
puts 50 in your list in the sorted order
bisect.bisect(t, 60)
tells you the position of 60
bad things to use in python
del. He tried to get it eliminated in Python 3
bacwards iteration
for x in reversed(seq)
association list
a list of tuples// which basically is a dictionary. It simulates a dictionary.
abstract base classes
uniform definition of what it means to be a sequence// mapping// etc. Mix-in capability// ability to override isinstance() and issubclass()
@classmethod
how to make new instances of the class with different instances of the argument. If you ever get in argument about how to best create a constructor// you should say all parties win
@cache
my program runs poorly// but cache solves it. if doing recursion// then cache. Great also for database look ups.
regex basics:
? 0 to 1 matches
* 0 to infinity matches
weak reference
is a reference that does not protect the referenced object from collection by a garbage collector (unlike a strong reference). An object referenced only by weak references is considered unreachable (or weakly reachable) and so may be collected at any time. Some garbage-collected languages feature or support various levels of weak references// such as Java// C#// Python// Perl or Lisp.
unbound method
if you access a method on a type or class// rather than an instance of the type or class// you get an unbound method// not attached to any particular instance of the type or class: when you call it// you need to pass as its first argument an instance of the type or class. means it is inherited from the super / base class and not defined in an instance
translation table
example (the string method maketrans is a utility function for making translation tables) A translation table is a string t of exactly 256 characters: when you pass t as the first argument of a translate method// each character c of the string on which you call the method is translated in the resulting string into the character t[ord(c)]..
surrogate pair
Two physical characters that represent a single logical character. Part of a convention for representing 32-bit code points in terms of two 16-bit code points.
static methods
simple functions with no self argument that are nested in a class and are designed to work on class attributes instead of instance attributes. Static methods never receive an automatic self argument// whether called through a class or an instance. They usually keep track of information that spans all instances// rather than providing behavior for instances. Static comes from they definitions being set staticially// not-dynamically.
State Design Pattern
where you have a main class that delegates to state classes State design pattern is like a coach delegating who is best for the job. problematic. In particular// the key feature of the classic State Design Pattern// that state objects are the ones that handle state switching (while// in the Strategy Design Pattern// the switching comes from the outside)// is just not enough of a big deal in Python to warrant considering the two design patterns as separate. See http://exciton.cs.rice.edu/JavaResources/DesignPatterns/ for good coverage of the classic design patterns// albeit in a Java context.
slots
slots: in the new-style object model in Python// which in Python 3.0 will fully replace the old-style// Python operations don't look up special methods at runtime: they only rely on slots held in a class objects. Such slots are update when a class object is built or modified. Therefore// a proxy object that wants to delegate some special methods to an object it's wrapping needs to belong to a specially made tailored class.
signature
the __index__ special method will have the signature: def __index__(self): return obj The signature of a function is a way of describing the parameters and parameter types with which a legal call to the function can be made. It contains the name of the function// its parameters and their type// and the return value. Signatures may also be referred to as function signatures// method signatures// or prototype definitions""
production code
code that must stay around for a long time and will be maintained across future versions of Python
predicit function
returns TRUE or FALSE. Note the naming convention.
directed acyclic graph
n mathematics and computer science// a directed acyclic graph is a directed graph with no directed cycles. That is// it is formed by a collection of vertices and directed edges// each edge connecting one vertex to another// such that there is no way to start at some vertex v and follow a sequence of edges that eventually loops back to v again DAGs may be used to model several different kinds of structure in mathematics and computer science. A collection of tasks that must be ordered into a sequence// subject to constraints that certain tasks must be performed earlier than others// may be represented as a DAG with a vertex for each task and an edge for each constraint; algorithms for topological ordering may be used to generate a valid sequence. DAGs may also be used to model processes in which information flows in a consistent direction through a network of processors. The reachability relation in a DAG forms apartial order// and any finite partial order may be represented by a DAG using reachability. Additionally// DAGs may be used as a space-efficient representation of a collection of sequences with overlapping subsequences. The corresponding concept for undirected graphs is a forest// an undirected graph without cycles. Choosing an orientation for a forest produces a special kind of directed acyclic graph called a polytree. However there are many other kinds of directed acyclic graph that are not formed by orienting the edges of an undirected acyclic graph. For this reason it may be more accurate to call directed acyclic graphs acyclic directed graphs or acyclic digraphs.
byte
8 bits words of data can hold up to 256 values that are used for handling strings.
bound method
one of Python's callable types (others include functions and generators.) Like a function// a bound method can be called but it is bound to the object that it was retrieved from. And when it is called// it operates on that object. iter = iter(iterable).next yield iter()
Borg Design Pattern
The Singleton Design Pattern has a catchy name// but unfortunately it also has the wrong focus for most purposes: it focuses on object identity// rather than on object state and behavior. The Borg design nonpattern makes all instances share state instead// and Python makes implementing this idea a snap. bounded: has a finite number of items
bitwise math
A bitwise operator works with the binary representation of a number rather than that number's value. The operandis treated as a set of bits// instead of as a single number. Bitwise operators are similar in most languages that support them.or//and//exclusive or// shifted by right # tabs// and so on. Note: this is different than boolean math. Because they allow greater precision// bitwise operators can make some code faster and more efficient
binding
The binding of names before the program is run is called static (also early); bindings performed as the program runs are dynamic (also late or virtual).
binary files
jpg images// etc. even txt if want. Binary works as base 10 in the same way. Each column represents a value// and when you have enough you move to the next column. The difference is that in our base 10 system we need to have 10 before we move to the next column. We can have any value 0-9// but once it goes above that// we add a column. In base two// you can only have 0 or 1 before moving on to the next column. The number one is represented as 1 in both base ten and binary// so let's move on to the number two. In base ten this is represented as a 2// however in binary we can only have a 0 or a 1 before moving on to the next column. The number 2 is written as 10. This means 1 in the 2s column and 0 in the 1s column.
accumulator functions
(sum( x )// max( x )// etc.)
tip: minimize multi-level subclassing
multi-level subclassing not the norm in python
The three techniques listed above provide the means to design cooperative classes that can be composed or reordered by subclasses.
???
The only constraint upon the object returned by the decorator is that it can be used as a function ‚ which basically means it must be callable. Thus// any classes we use as decorators must implement __call__
...
Naming style
result_append = result.append changed it from a method call to a function call. Do this when calling methods into loops
ter's second argument is
a sentinal
How to turn a string into a list?
list('abc')
How are most exceptions named?
Most exceptions are defined with names that end in Error, similar to the naming of the standard exceptions.
Favorite way to talk to HTTP services?
curl
faster way to write: result = []// for ci in 'Hello': result.append(ord(c))
map(ord//'Hello')
Elegant way to build up two-dimensional dictionaries (that is dicts of dicts)
d = defaultdict(dict) d['USA']['Canada'] = 888
What does "design by contract" mean?
pre-condition check and post condition check// it's a way to validate
When to use DEQUE?
use anytime need to add from left or right because it will speed things up enormously
note: Fast 0(1) appends and pop from both ends.
Defaultdict
like a regular dictionary but supplies a factory function to fill-in missing values. example. d = defaultdic(list) then d[k].append(v) # new keys create new lists
note: like a regular dictionary but supplies a factory function to fill-in missing values
decorators as macros
I think it’s safe to say that the goal of macros in a language is to provide a way to modify elements of the language. That’s what decorators do in Python — they modify functions// and in the case of class decorators// entire classes. This is why they usually provide a simpler alternative to metaclasses.
decorators
wrap functions from the inside out. example: @register// takes a function and outputs a function
(2) let you clean up your code and add additional functionality really quick to your program// such as logging// caching
Counter.most_common()
List the n most common elements and their counts from the most common to the least. If n is None// then list all element counts.
Counter
a dictionary that knows how to count. c = Counter()
closure
a function inside a function. It memorizes the outside function. Closure means I remember something from my enclosing environment. If you don't return
Bound methods are not sinful in python
other languages have odds with this
basic use of timeit for small constructs
python -m timeit 13 << 2""
All new exceptions must inherit from...
BaseException
abstract base class
Abstract base classes complement duck-typing by providing a way to define interfaces when other techniques like hasattr() would be clumsy or subtly wrong (for example with magic methods). ABCs introduce virtual subclasses// which are classes that don’t inherit from a class but are still recognized by isinstance() and issubclass(); see the abc module documentation. Python comes with many built-in ABCs for data structures (in the collections module)// numbers (in the numbers module)// and streams (in the io module). You can create your own ABCs with the abc module.
If a class relies on one parent class preceding another (for example// LoggingOD depends on LoggingDict coming before OrderedDict which comes before dict)// it is easy to add assertions to validate and document the intended method resolution order:
position = LoggingOD.__mro__.index assert position(LoggingDict) < position(OrderedDict) assert position(OrderedDict) < position(dict)
@decorator vs. @decorator()
first IS a decorator and the second returns a decorator
_format
localized verible
__mro__
Gives you the method resolution order of a objects inheritance tree which is linerized and always ends at object.
__bases__
Gives you the parents of the subclass
How do you append directories to your Python path?
import sys
sys.path.append("/home/me/mypy")