1. Basic

iteration

  • dict.items(): the Python function items()will iterate over a dictionary and return those key/value pairs.
  • dict.keys():  the keys() function returns an array of the dictionary’s keys
  • dict.values(): the values() function returns an array of the dictionary’s values
  • with comma, we can print in one line instead of several
    • for letter in "Eric":
          print letter,  # note the comma!
      # => "E" "r" "i" "c"
  • list comprehension: a powerful way to generate lists using the for/in and if keywords e.g. evens_to_50 = [i for i in range(51) if i % 2 == 0]
  • list slicing: [start:end:stride] Where start describes where the slice starts (inclusive), end is where it ends (exclusive), and stride describes the space between items in the sliced list.
  • lambda: anonymous function  lambda x: x % 3 == 0
  • filter(condition, list)
  • for i in range(1,11): numbers 1 -10, left inclusive, right exclusive

bitwise operators

  • 5 >> 4  # Right Shift      0
    5 << 1  # Left Shift        10
    8 & 5   # Bitwise AND     0
    9 | 4   # Bitwise OR        13
    12 ^ 42 # Bitwise XOR   38
    ~88     # Bitwise NOT     -89
  • print 0b1 + 0b11          4
    print 0b11 * 0b11        9
  • (1) bin()/oct()/hex() function: print number into binary/base 8/base 16
  • e.g. bin(2)=10  bin(10)=1010
  • (2) int() function: return the value of that number in base ten
  • e.g. int(“10”,2)=2  int(bin(5),2)=5  int(“0b100”,2)=4
  • (3) shift: shifting all the 1s and 0s left or right by the specified number of slots
  • e.g. 0b1100>>2 = 0b11    0b1<<2 = 0b100
  • (4) & function: turn on if the corresponding bits of both numbers are 1
  • e.g. 0b111 & 0b1010 = 0b10     0 & 0 = 0 0 & 1 = 0 1 & 0 = 0 1 & 1 = 1
  • (5) | function: turn on if either of the corresponding bits of either number are 1
  • e.g. 0b110 | 0b1010 = 0b1110   0 | 0 = 0 0 | 1 = 1 1 | 0 = 1 1 | 1 = 1
  • (6) ^ function: turn on if either of the bits of the two numbers are 1,but not both
  • e.g. 0b1110 ^ 0b101=0b1011  0 ^ 0 = 0 0 ^ 1 = 1 1 ^ 0 = 1 1 ^ 1 = 0
  • (7) ~ function: equal to adding one to the number and then making it negative
  • e.g. ~1 =-2   ~123=-124

Class

  • class ClassName(object):
  • __init__(self)
  • instance:  newObject= ClassName(“Peter”, “Red”, 20)
  • Member variable: information that belongs to the class object
  • Inheritance:  one class takes on the attributes and methods of another
  • super() : access the attributes or methods of a superclass
class DerivedClass(Base/SuperClass):
   def some_method(self, args):
       super(DerivedClass, self).method(args)

Input/Output

  • open() function: f = open("output.txt", "w")      w–write,  r–read-only,             r+ — read and write,  a–append
  • .write() function: take string argument
  • .close() function
  • my_file.closed: True when the file is closed andFalse otherwise                            if my_file.closed==False:
    my_file.close()
    print my_file.closed
  • __exit__(): automatically close our files    with   as                                                with open(“text.txt”, “w”) as textfile:
    textfile.write(“Success!”)

2. Example

1. simple decoding

garbled = “!XeXgXaXsXsXeXmX XtXeXrXcXeXsX XeXhXtX XmXaX XI”
message=garbled[::-2]
print message

garbled = “IXXX aXXmX aXXXnXoXXXXXtXhXeXXXXrX sXXXXeXcXXXrXeXt mXXeXsXXXsXaXXXXXXgXeX!XX”
message=filter(lambda i: i!=”X”,garbled)
print message

2. turn on or turn off binary

(1) mask & : turn on

def check_bit4(x):
mask=0b1000
desired=x&mask
if desired >0:
return “on”
else:
return “off”

(2)mask | : turn on

a = 0b10111011
mask=0b100
result=a|mask
print bin(result)

(3)mask ^ : flip out

a = 0b11101110
mask =0b11111111
print bin(a^mask)

(4)mask ^ slide: flip out

def flip_bit(number,n):
mask=(0b1<<(n-1))
return bin(number^mask)

3. Class Overview

(1) Fruit example

class Fruit(object):
“””A class that makes various tasty fruits.”””
def __init__(self, name, color, flavor, poisonous):
self.name = name
self.color = color
self.flavor = flavor
self.poisonous = poisonous

def description(self):
print “I’m a %s %s and I taste %s.” % (self.color, self.name, self.flavor)

def is_edible(self):
if not self.poisonous:
print “Yep! I’m edible.”
else:
print “Don’t eat me! I am super poisonous.”

lemon = Fruit(“lemon”, “yellow”, “sour”, False)

lemon.description()
lemon.is_edible()

(2) Shopping Cart example

class ShoppingCart(object):
“””Creates shopping cart objects
for users of our fine website.”””
items_in_cart = {}
def __init__(self, customer_name):
self.customer_name = customer_name

def add_item(self, product, price):
“””Add product to the cart.”””
if not product in self.items_in_cart:
self.items_in_cart[product] = price
print product + ” added.”
else:
print product + ” is already in the cart.”

def remove_item(self, product):
“””Remove product from the cart.”””
if product in self.items_in_cart:
del self.items_in_cart[product]
print product + ” removed.”
else:
print product + ” is not in the cart.”

my_cart=ShoppingCart(“Alice”)
my_cart.add_item(“Electric Toothbrush”, 35)

(3) Employee wage example

class Employee(object):
“””Models real-life employees!”””
def __init__(self, employee_name):
self.employee_name = employee_name

def calculate_wage(self, hours):
self.hours = hours
return hours * 20.00

# Add your code below!
class PartTimeEmployee(Employee):
def calculate_wage(self, hours):
self.hours = hours
return hours * 12.00
def full_time_wage(self, hours):
return super(PartTimeEmployee, self).calculate_wage(hours)

milton = PartTimeEmployee(“Milton”)
print milton.full_time_wage(10)

4. Input/Output

(1) Output

my_list = [i**2 for i in range(1,11)]

f = open(“output.txt”, “w”)

for item in my_list:
f.write(str(item) + “\n”)

f.close()

(2) Input: read

my_file=open(“output.txt”,”r”)

print my_file.read()

my_file.close()

(3) Input: Write

with open(“text.txt”,”w”) as my_file:
my_file.write(“Almost done!”)

Advertisements