Python Flashcards

1
Q

Explain ‘os’ module usages

A

os.mkdir(aPath) os.listdir(aPath) os.path.isdir(aPath) os.system(command)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

Explain ‘sys’ module methods and variables.

A

sys. argv[] sys.exit() sys.builti­n_m­odu­le_­names # Linked C modules
sys. byteorder # Native byte order
sys. check_­int­erval Signal check frequency
sys. exec_p­refix #Root directory
sys. executable #Name of executable
sys. exitfunc #Exit function name
sys. modules #Loaded modules
sys. path #Search path
sys. platform #Current platform
sys. stdin, sys.stdout, sys.stderr # File objects for I/O
sys. versio­n_info #Python version info
sys. winver #Version number

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

Function definition in Python

A

Python function definition

def myFunction(arg1, arg2=5, arg3=”default’’):

return result

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

Python ‘List’ methods

A

append­(item)

pop(po­sition)

count(­item)

remove­(item)

extend­(list)

reverse()

index(­item)

sort()

insert­(po­sition, item)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

Python ‘String’ methods

A

capita­lize() *

lstrip()

center­(width)

partit­ion­(sep)

count(sub, start, end)

replac­e(old, new)

decode()

rfind(sub, start ,end)

encode()

rindex­(sub, start, end)

endswi­th(sub)

rjust(­width)

expand­tabs()

rparti­tio­n(sep)

find(sub, start, end)

rsplit­(sep)

index(sub, start, end)

rstrip()

isalnum() *

split(sep)

isalpha() *

splitl­ines()

isdigit() *

starts­wit­h(sub)

islower() *

strip()

isspace() *

swapcase() *

istitle() *

title() *

isupper() *

transl­ate­(table)

join()

upper() *

ljust(­width)

zfill(­width)

lower() *

* are local-dependent for 8 bit scales.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

Python ‘File’ methods

A

close()

readli­nes­(size)

flush()

seek(o­ffset)

fileno()

tell()

isatty()

trunca­te(­size)

next()

write(­string)

read(size)

writel­ine­s(list)

readli­ne(­size)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

Python indexes and slices

A

* Indexes and Slices of a=[0,1­,2,­3,4,5]

len(a) –> 6

a[0] –> 0

a[5] –> 5

a[-1] –> 5

a[-2] –> 4

a[1:] –> [1,2,3­,4,5]

a[:5] –> [0,1,2­,3,4]

a[:-2] –> [0,1,2,3]

a[1:3] –> [1,2]

a[1:-1] –> [1,2,3,4]

b=a[:] –> Shallow copy of a

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

Python String formating

A

arg_str = “ {0} {1} {3}”.format(arg1, arg2, arg3)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

Python loop using List

A

for pic in pic_list:

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

Python hash (dictionary): Definition

A

dict = {‘Alice’: ‘2341’, ‘Beth’: ‘9102’, ‘Cecil’: ‘3258’}

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

Python hash (dictionary): Value access

A

dict = {‘Name’: ‘Zara’, ‘Age’: 7, ‘Class’: ‘First’}

print “dict[‘Name’]: “, dict[‘Name’]

print “dict[‘Age’]: “, dict[‘Age’]

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

Python hash (dictionary): Removing elements

A

dict = {‘Name’: ‘Zara’, ‘Age’: 7, ‘Class’: ‘First’}

del dict[‘Name’] # remove entry with key ‘Name’

dict.clear() # remove all entries in dict

del dict # delete entire dictionary

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

Python hash (dictionary): Methods

A
  • dict.clear() # Removes all elements of dictionary
  • dict.copy() # Returns a shallow copy of dictionary dict
  • dict.fromkeys() # Create a new dictionary with keys from seq and values set to value.
  • dict.get(key, default=None) # For key key, returns value or default if key not in dictionary
  • dict.has_key(key) # Returns true if key in dictionary dict, false otherwise
  • dict.items() # Returns a list of dict’s (key, value) tuple pairs
  • dict.keys() # Returns list of dictionary dict’s keys
  • dict.setdefault(key, default=None) # Similar to get(), but will set dict[key]=default if key is not already in dict
  • dict.update(dict2) # Adds dictionary dict2’s key-values pairs to
  • dict.values() # Returns list of dictionary dict2’s values
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

Python hash (dictionary): functions on hash data structure

A
  • cmp(dict1, dict2) # Compares elements of both
  • str(dict) # Produces a printable string representation of a dictionary
  • type(variable) # Returns the type of the passed variable. If passed variable is dictionary then it would return a dictionary type.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

Example: Use Python ‘List’ as a stack

A

>>> stack = [3, 4, 5]
>>> stack.append(6)
>>> stack.append(7)
>>> stack
[3, 4, 5, 6, 7]
>>> stack.pop()
7
>>> stack
[3, 4, 5, 6]
>>> stack.pop()
6
>>> stack.pop()
5
>>> stack
[3, 4]

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

Python Class Definition

A
class Person:
     def \_\_init\_\_(self,pos):
         self.pos = pos
         self.alive = 1
     def \_\_str\_\_(self):
         return "Person #%d, %s" % (self.pos, self.alive)
     # Creates a chain of linked people
     # Returns the last one in the chain
     def createChain(self,n):
         if n\>0:
             self.succ = Person(self.pos+1)
             return self.succ.createChain(n-1)
         else:
             return self
    # Kills in a circle, getting every nth living person
     # When there is only one remaining, the lone survivor is returned
     def kill(self,pos,nth,remaining):
         if self.alive == 0: return self.succ.kill(pos,nth,remaining)
         if remaining == 1: return self
         if pos == nth:
             self.alive = 0
             pos=0
             remaining-=1
         return self.succ.kill(pos+1,nth,remaining)
17
Q

Python sorting using ‘sorted’ – this is super cool!

A

>>> a = [‘ccc’, ‘aaaa’, ‘d’, ‘bb’]
>>> sorted(a)
[‘aaaa’, ‘bb’, ‘ccc’, ‘d’]
>>> sorted(a)
[‘aaaa’, ‘bb’, ‘ccc’, ‘d’]
>>> len
<built-in function len>
>>> sorted(a, key=len)
[‘d’, ‘bb’, ‘ccc’, ‘aaaa’]

18
Q

Given a Python list of strings, how do you sort by the last character of each string?

A

>>> a = [‘ccc’, ‘aaaz’, ‘d’, ‘bb’]
>>> def last(s): return s[-1]

>>> sorted(a, key=last)
[‘bb’, ‘ccc’, ‘d’, ‘aaaz’]
>>> “:”.join(a)
‘ccc:aaaz:d:bb’

19
Q

Python tuple

A
  • a = (1, 2, 3)
  • Tuple is immutable, i.e. can’t grow or shrink or change elements.
  • (x, y) = (1, 2) # parallel assignment as in Perl
  • One can write a function that returns a tuple to make ‘sorted’ sort according to multiple items.
20
Q

Python hashtable (dictionary)

A
  • Constant time key-lookup!!!
  • d = { } # Use squigly bracket for dictionary
  • (key, value) pair assignments
    • d[‘a’] = ‘alpha’
    • d[‘o’] = ‘omega’
    • d[‘g’] = ‘gamma’
  • Check whether a key is in the hashtable ‘d’
    • ‘o’ in d –> return True
    • ‘x’ in d –> return False
  • Methods
    • d.keys() –> return all the keys
    • d.values() –> return all the values
    • d.items() –> return all the (key, value) pair “tuples”
  • Look through hashtables
    • for k in sorted(d.keys()): print ‘key:’, k, ‘->’, d[k]

      key: a -> alpha
      key: g -> gamma
      key: o -> omega
    • for t in d.items(): print t

      (‘a’, ‘alpha’)
      (‘g’, ‘gamma’)
      (‘o’, ‘omega’)
21
Q

Example of using (Python) hashtable

A
  • Example1:
    • Apache log file of 20M GET request. Use IP address as key, and value is the number of requests.
    • From this, one can know how many requests are made from each IP address.
  • In a sense, ‘dictionary’ helps us get some structure out of unstructured data.
  • Example2: Google runs as a big giant hashtable by word.
    • ‘Britney’ –> a list of URLs
    • ‘Jaewon’ –> another list of URLs
22
Q

Python files: Let’s create Unix ‘cat’ command in Python

A

def cat(filename):
f = open(filename, ‘rU’)
for line in f:
print line, # Note: The comma at the end removes the new line char!
f.close()

def cat2(filename):
   f = open(filename, 'rU')
   lines = f.readlines() # Read the entire lines as array of lines
   print lines
   f.close()
def cat3(filename):
   f = open(filename, 'rU')
   text = f.read() # Read the entire file as a string
   print text
   f.close()
23
Q

Python regular expression module ‘re’: Basic examples

A

import re

  ## Search for pattern 'iii' in string 'piiig'.
   ## All of the pattern must match, but it may appear anywhere.
   ## On success, match.group() is matched text.
   match = re.search(r'iii', 'piiig') =\>  found, match.group() == "iii"
   match = re.search(r'igs', 'piiig') =\>  not found, match == None
  ## . = any char but \n
   match = re.search(r'..g', 'piiig') =\>  found, match.group() == "iig"
  ## \d = digit char, \w = word char
   match = re.search(r'\d\d\d', 'p123g') =\>  found, match.group() == "123"
   match = re.search(r'\w\w\w', '@@abcd!!') =\>  found, match.group() == "abc"
24
Q

Python regular expression module ‘re’: Repetition examples

A

i+ = one or more i’s, as many as possible.
match = re.search(r’pi+’, ‘piiig’) => found, match.group() == “piii”

  ## Finds the first/leftmost solution, and within it drives the +
   ## as far as possible (aka 'leftmost and largest').
   ## In this example, note that it does not get to the second set of i's.
   match = re.search(r'i+', 'piigiiii') =\>  found, match.group() == "ii"
  ## \s\* = zero or more whitespace chars
   ## Here look for 3 digits, possibly separated by whitespace.
   match = re.search(r'\d\s\*\d\s\*\d', 'xx1 2   3xx') =\>  found, match.group() == "1 2   3"
   match = re.search(r'\d\s\*\d\s\*\d', 'xx12  3xx') =\>  found, match.group() == "12  3"
   match = re.search(r'\d\s\*\d\s\*\d', 'xx123xx') =\>  found, match.group() == "123"
  ## ^ = matches the start of string, so this fails:
   match = re.search(r'^b\w+', 'foobar') =\>  not found, match == None
   ## but without the ^ it succeeds:
   match = re.search(r'b\w+', 'foobar') =\>  found, match.group() == "bar"
25
Q

Python regular expression module ‘re’: Email example

A

str = ‘purple alice-b@google.com monkey dishwasher’
match = re.search(‘([\w.-]+)@([\w.-]+)’, str)
if match:
print match.group()
print match.group(1)
print match.group(2)

  ## Suppose we have a text with many email addresses
   str = 'purple alice@google.com, blah monkey bob@abc.com blah dishwasher'
  ## Here re.findall() returns a list of all the found email strings
   emails = re.findall(r'[\w\.-]+@[\w\.-]+', str)
   for email in emails:
     print email
  # Open file
   f = open('test.txt', 'r')
   strings = re.findall(r'some pattern', f.read())
26
Q

Python regular expression module ‘re’: Email example 2

A

str = ‘purple alice@google.com, blah monkey bob@abc.com blah dishwasher’
tuples = re.findall(r’([\w.-]+)@([\w.-]+)’, str)
for tuple in tuples:
print tuple[0] # username
print tuple[1] # host

27
Q

Python sort

A
strs = ['aa', 'BB', 'zz', 'CC']
   print sorted(strs)
   print sorted(strs, reverse=True)
  strs = ['ccc', 'aaaa', 'd', 'bb']
   print sorted(strs, key=len)
  ## "key" argument specifying str.lower function to use for sorting
   print sorted(strs, key=str.lower)
  ## Say we have a list of strings we want to sort by the last letter of the string.
   strs = ['xc', 'zb', 'yd' ,'wa']
  ## Write a little function that takes a string, and returns its last letter.
   ## This will be the key function (takes in 1 value, returns 1 value).
   def MyFn(s):
     return s[-1]
  ## Now pass key=MyFn to sorted() to sort by the last letter:
   print sorted(strs, key=MyFn)
28
Q

Formatted String in Python

A

“Person %d, %s” % (a_number, a_string)

29
Q

Python urllib module example

A
Given a url, try to retrieve it. If it's text/html,
 ## print its base url and its text.
 def wget(url):
   ufile = urllib.urlopen(url)  ## get file-like object for url
   info = ufile.info()   ## meta-info about the url content
   if info.gettype() == 'text/html':
     print 'base url:' + ufile.geturl()
     text = ufile.read()  ## read all its text
     print text
30
Q

Python ‘urllib’ module example

A

import urllib

Given a url, try to retrieve it. If it's text/html,
 ## print its base url and its text.
 def wget(url):
   ufile = urllib.urlopen(url)  ## get file-like object for url
   info = ufile.info()   ## meta-info about the url content
   if info.gettype() == 'text/html':
     print 'base url:' + ufile.geturl()
     text = ufile.read()  ## read all its text
     print text
31
Q

How do you express the following mathematical sets in Python?

  • S = {x² : x in {0 … 9}}
  • V = (1, 2, 4, 8, …, 2¹²)
  • M = {x | x in S and x even}
A

>>> S = [x**2 for x in range(10)]
>>> V = [2**i for i in range(13)]
>>> M = [x for x in S if x % 2 == 0]

32
Q

Creating 2D list in Python: List comprehension

A

A pattern that often came up in Python was

bar = []
for item in some_iterable:
bar.append(SOME EXPRESSION)

which helped motivate the introduction of list comprehensions, which convert that snippet to

bar = [SOME EXPRESSION for item in some_iterable]

which is shorter and sometimes clearer.

>>> a = []
>>> for i in xrange(3):
… a.append([])
… for j in xrange(3):
a[i].append(i+j)

>>> a
[[0, 1, 2], [1, 2, 3], [2, 3, 4]]
>>> n = 5
>>> init_val = 3
>>> a_n_by_n_array = [[init_val]*n for x in xrange(n)]

33
Q

A sparsely populated array in Python

A

using a dictionary keyed with a tuple
dict = {}
key = (a,b)
dict[key] = value