Reviewing Python Part 1

Python was the first programming language that I attempted to learn by myself, but it has been more than a year since I have used it consistently, so I am going to try to quickly go through the basics of python, numpy, and pandas to make machine learning code easier to understand

Reviewing Python with Learning Python, 5th ed., by Mark Lutz

Python was the first programming language that I attempted to learn by myself, but it has been more than a year since I have used it consistently, so I am going to try to quickly go through the basics of python, numpy, and pandas to make machine learning code easier to understand

Python Core Data Types

General

Definitions

Numeric Types

Objects

Expressions:

How does python know which operation to perform first? The answer is operator precedence. Python groups expressions with one or more operators according to precedence rules, and this grouping determins the order in which expression's parts are completed

Mixed types are converted to the more complicated operand, which is readonable. This appies generally only to numeric types

All python operators can be overloaded (implemented) by Python classes and C extension types to work on objects you create
Floating point number comparisons sometimes require massaging to become meaningful

Divsion

Built In Functions

c = set(a) - set(b)
"""
c only contains values that are in set a, but not in set b
"""
- Sets can be used to perform *order neutrality equality test* -> two sets are equal if every element in each set is in the other.

Booleans

Definitions:

Dynamic Typing

Python's types are determined automatically at runtimem not in response to declarations in the code -> dynamic typing

a = 3 
b = a # b and a both point to the same 3 object
a = 'spam' # b is still equals 3
a = [1,2,3]
b = a
a[1] = 5
print(b) # [1,5,3]
import copy
X = copy.copy(Y) # Make top level "shallow copy of object Y
X = copy.deepcopy(Y) # Make deep copy of any object Y: copy all nested parts

Two ways to check for equality in Python code:

L is M # same values, common
L == M # same objects, rare

String Fundamentals

In Python 3, there are three string types: str is used for Unicode text, bytes is used for binary data, and bytearray is a mutable variant of bytes. Files work in two modes: text, which represents content as str and implements unicode encodings and binary, which deals in raw bytes and does no data translation

Common String operations

String Notes

Lists and Dictionaries

Common List Literals and Operations

Common Dictionary Literals and Operations

D = {}
D = {'name':'Bob','age':40}
E = {'cto':{'name':'Bob', 'age': 40}}
D = dict(name="Bob",age=40)
D = dict([('name','Bob'),('age',40)])
keyslist = ['name','age']
valueslist = ['Bob',40]
D = dict(zip(keyslist,valueslist))
D = dict.fromkeys(['name','age']) # {'name':None,'age': None}
D = dict.fromkeys(['name','age'],0) # {'name':0,'age': 0}
D['name'] # indexing by key
E['cto']['age'] # indexing by key
'age' in D # membership: key present test
D.keys() # all keys
D.values() # all values
D.items() # all key vaue tuples
D.clear() # clear (remove all items)
D.copy() # copy (top level)
D2 = {}
D.update(D2) # merge by keys
default = 0
key = 'name'
D.get(key,default)
D.pop(key,default)
D.setdefault(key,default)
D.popitem()
len(D)
D[key] = 42
del D[key]
list(D.keys())
D1 = {'first': 'Frank', 'age': 2}
D2 = {'last': 'Brown', 'age': 2}
D1.keys() & D2.keys()
D.viewkeys(), D.viewvalues()
D = {x: x**2 for x in range(10)}

Tuples and Everything else

Common Tuple Literals and Operations

T = () # empty tuple
T = (0,) # A one item tuple
T = (0,'Mi',1.2,3) # A 4 item tuple
T = 0,'Mi',1.2,3 # A 4 item tuple
T = ('Bob',('dev','mgr')) # nested tuple
j = 1
i = 0
T[i]
T[1][j]
T[i:j]
len(T)
T1 = (1,2,3)
T2 = (4,5,6)
T1 + T2 # Concatenation
T1*3 # Repeat
for x in T1: print(x)
2 in T1 # Membership 
[x**2 for x in T2] # Comprehension
T.index('Bob')
T.count('Bob')
from collections import namedtuple
namedtuple('Emp',['name','job']) # Named Tuple Extension type 

Files

# Common File Operations

output = open(r'c:\spam','w') # create an output file
inp = open('data','r') # Create an input file 
inp = open('data') # Same as previous line ('r' is the deault)
aString = inp.read() # Read an entire file into a single string
aStrinbg = inp.readline() # Read next line
aList = inp.readlines() # Read entire file into list of line wstrings (with \n)
output.write(aString)
output.writelines(aList)
output.close() # Manual Close
output.flish() # Flush output bufer to disk without closing 
inp.seek(N) # Change file position to offset N for next operation 
for line in open('data'): print(line) # use line
open('f.txt',encoding="latin-1") 
open('f.bin','rb') # read binary file