Friday, December 21, 2018

Python Homework Solutions #1

Homework 1-1 Convert temperature from Fahrenheit to Celsius
# Convert from Fahrenheit to Celsius
degreesF, degreesC = 0, 0
degreesF = float(input('Enter the temperature in degrees F: '))
degreesC = 5/9*(degreesF - 32)
print(degreesF, 'degrees F =', degreesC, 'degrees C')
print(degreesF, 'degrees F = {:10.3f}'.format (degreesC), 'degrees C')

Python Inputs and outputs.

Using user inputs.
print('Please enter some text:')
x = input()
print('Text entered:', x)
print('Type:', type(x))
print('Please enter a number:', end='\n')
s1 = input()
print('Please enter another number:', end='\n')
s2 = input()
n1 = int(s1)
n2 = int(s2)
print(n1, '+', n2, '=', n1 + n2)

n1 = int( input( 'Enter number one:' ))
n2 = int( input( 'Enter number two:' ))
print(n1, '+', n2, '=', n1 + n2)

n1 = int(float( input( 'Enter number one:' )))
n2 = int(float( input( 'Enter number two:' )))
print(n1, '+', n2, '=', n1 + n2)
Python print outputs
a,b,c,d,e = 2,4,7,9,31
print (a,b,c,d,e)
print (a,b,c, end=' / ')
print (d,e, sep=':::')

print ('s'*20)
print('{0} {1}'.format(0, 10**0))
print('{0} {1}'.format(1, 10**1))

for i in range(10):
    print ('{0:>3} {1:>16}'.format(i, 10**i))

str = '''
This is a multiple lines
comments
# ! {} @
'''.format( "what have you" )
print ( str )

Python Homeworks #1

Homework 1-1 Conditionals
  1. Convert Gallons to Liters
  2. Convert temperature from Fahrenheit to Celsius
  3. Convert number to names
  4. Create a help menu providing phone numbers for agents, institutions.
Homework 1-2 Lists, Loops, Files
  1. Write a program that will print A to F vertically on each new line.
  2. Create an array or list of numbers and calculate all.
  3. Make it interactive and take inputs from users until 'q' or 'Q' is presssed.
  4. Take inputs from file and print output to a file.
Homework 1-3 Numbers and Type Conversions
  1. Compute the circumference area of a circle given the radius.
  2. Take two numbers and calculate their GCD.
  3. Take two numbers and output the max / min / mean / sum of both.
  4. Convert Coins to currency amount

Python Comprehensions!

Create Python comprehensions, and access elements
cubes = []
for i in range(5):
  cubes.append(i**3)

cubes = [i**3 for i in range(5)]
print (cubes)

cubes = [i**3 for i in range(30) if i % 3 == 0]
print (cubes)
Transform dictionaries using comprehensions
cities = { 'United States': 'San Jose', 'France': 'Paris', 'Italy': 'Rome' }
cities_transposed = { cities[key]: key for key in cities }
print (cities_transposed)
Using Comprehension in arithmetics
[ i**2 for i in range(8) ]
sum( i**2 for i in range(8) )
sum([ i**3 for i in range(8) ])
min([ i**3 for i in range(8) ])
max([ i**3 for i in range(8) ])
print ( sum( i**3 for i in range(8) ))

Python Dictionaries!

Create Python dictionaries, and access elements
cities = { 'United States': 'San Jose', 'France': 'Paris', 'Italy': 'Rome' }
cities['Italy']
Modify and merge data in dictionaries
# merge two dictionaries
more = {'Germany': 'Berlin', 'United Kingdom': 'London'}
cities.update( more )
Add and remove items in dictionaries
# adding
cities['Spain'] = 'Madrid'

try:
  cities['Germany']
except:
  print ('No Germinay city specified')

'Germany' in cities
# False
'Italy' in cities
# True

# delete items
del cities['United States']
Looping over the dictionaries
# loop over dict
for key in cities:
  print (key, cities[key])

for key in cities.keys():
  print (key, cities[key])

for value in cities.values():
  print (value)

for key,value in cities.items():
  print (key, value)

Python os library

Access OS interfaces
import os
import shutil
from os import path
from shutil import make_archive
from zipfile import ZipFile

# make a duplicate of an existing file
if path.exists ("w1.txt"):
    # get the path to the file in the current directory
    src = path.realpath ("w1.txt")

    # separate the path part from the filename
    fpath, fname = path.split (src) ## :h :t
    print ( "path:", fpath )
    print ( "file:", fname )

    # let's make a backup copy by appending "bak" to the name
    dst = src + '.bak'
    # now use th eshell to make a copy of the file
    shutil.copy (src,dst)

    # copy over the permissions, modification times, and other info
    shutil.copystat (src,dst)

    # rename the original file
    os.rename ("w1.txt", "new.txt")

    # common use
    os.getcwd()
    os.chdir()
    os.remove('file_to_remove.txt')

Create Archive Zip File
    # now put things into a ZIP archive
    fpath, fname = path.split (src) ## :h :t
    shutil.make_archive ("archive", "zip", fpath)

    # more fine_grained constrol over ZIP files
    with ZipFile ("w1.zip", "w") as newzip:
        newzip.write ("new.txt")
        newzip.write ("w1.txt.bak")

    os.system( "/bin/cp w1.txt.bak w1.txt" )
Find out OS system
import os
print (os.name) ## always posix for linux, windows or OS X
import platform
platform.platform()
os.path
import os.path
os.path.join ('path_name', 'sub_path', 'file_name')
>>> 'path_name/sub_path/file_name'
## on window system
os.path.join ('c:','path_name', 'sub_path', 'file_name')
>>> 'path_name\sub_path\file_name'
os.path.exists ('path_or_file_name')
os.path.isfile ('path_or_file_name')
os.path.isdir  ('path_or_file_name')
os.path.islink ('path_or_file_name')

os.popen
import os
filename = 'book.txt'
cmd = 'ls '+ filename
fp = os.popen( cmd )
res = fp.read()
stat = fp.close()

Python Lists!

Create Python lists, and access elements
friends = ["amy", "david", "stella", "niyu", "vivek", "michael"]
print (friends)
print (friends[0])
print (len(friends) )

for i in range(len(friends)):
    friends[i] += " smith"
print ( friends )

for i in range(len(friends)):
    friends[i] = "none"
print ( friends )
Mixing different data types
mixarray = [ 1, [9,8], (3,4), 'letter', {0:'first'}, 2, 5, 25 ]
mixarray[3]
mixarray[:3]
mixarray[-3:]             # last three elements
mixarray[8:8] = [88,99]   # insert after the last, 
                          # notice mixarray[8] would error out
mixarray[2:5] = [22,55]   # replace the elements,
                          # notice the length does not have to match
# array method: append, remove, extend, pop, sort, index, reversed
a = [2,3,4]
b = ['two','three','four']
h = zip(a, b)
Modify and merge elements in lists
mixarray.append( 'dog' )
print (mixarray)

mixarray.extend( 'cat' )
print (mixarray)

mixarray.extend( [ 'cat' ] )
print (mixarray)

mixarray += 'pig'
print (mixarray)

mixarray += [ 'pig', 'donald duck' ]
print (mixarray)
Slice Strings
filename = r"C:\dir\new"                     
filename = 'C:\\dir\\new'
filename = 'C:/User/myname/dirname'
a = ['amy','smith']
s = ' '.join(a)
s.join(" baz")
n = len(s)
Slice the lists
mixarray[2:3]
print (mixarray[5:])
mixarray[:8]
print (mixarray[4:-1]) 
print (mixarray[-1])

print (mixarray[:]) ## the while array
mixarray[2:4] = ['new1', 'new2'] ##  this replace [2] [3]
print (mixarray)
mixarray[2:3] = ['new3', 'new4'] ##  this replace mixarray[2] with two elements 'new3', 'new4'
print (mixarray)

newary = mixarray[:]             ## copy the whole array
newbry = mixarray[-2:]           ## last 2 elements
newcry = mixarray[::-1]          ## reverse the whole array
s = 'xxyyzzppqqmm'
t = s[slice(None,None,-1)]       ## same as s[::-1]
Insert and remove elements in lists
del mixarray[-2:] ## this delete the last 2 elements
print (mixarray)

mixarray.insert( 2, 'monkey' )
print (mixarray)

del mixarray[2]
mixarray.remove ('donald duck')
print (mixarray)
Looping over the lists
import
for i in mixarray:
    print ( i, end=' ' )
print()
for k,v in enumerate (mixarray):
    print ( k, ':', v, end=' / ' )
print()

from collections import Counter
Counter(mixarray)
# Counter(mixarray) # this will error out
s = "this is a string, a very long string"
Counter(s)
Counter(s[0])
Quick Reference

Wednesday, December 19, 2018

Python and files.

Open file for reading
f = open ("myfile.txt", "r")
if f.mode == "r":
    data = f.read() ## read the whole file
    line = f.readline() ## read a line
Open file for writing, the regular way
f = open ("myfile.txt", "w")
for i in range (10):
    f.write ( i, "line" )

# append more lines
f = open ("myfile.txt", "a")
f.write ("That's all")
f.close()
Be a pythonist!
data = open ("myfile.txt").read()      ## return whole file as one single string
data = open ("myfile.txt").readline()  ## return one line as a string
data = open ("myfile.txt").readlines() ## return whole file as list of strings, with '\n'

f = "myfile.txt"
with open( f ) as fh:
    lines = list( map( str.rstrip, fh.readlines() ))

Tuesday, December 18, 2018

Python date, time and datetime objects.

Import date, time and datetime classes
from datetime import date
from datetime import time
from datetime import datetime

## Using objects of class type date, time, datetime
today = date.today()
print ( "Today's date is", today )
print ( "Today :", today.month, today.day, today.year )
weekday = "Sunday"    if today.weekday() == 6 else ""
weekday = "Monday"    if today.weekday() == 0 else weekday
weekday = "Tuesday"   if today.weekday() == 1 else weekday
weekday = "Wednesday" if today.weekday() == 2 else weekday
weekday = "Thursday"  if today.weekday() == 3 else weekday
weekday = "Friday"    if today.weekday() == 4 else weekday
weekday = "Saturday"  if today.weekday() == 5 else weekday
print ( "Today : {} / {}-{}-{}".format ( weekday, today.month, today.day, today.year ))

today = datetime.now()
print ( "Now is", today )

days = [ "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun" ]
wkday = date.weekday (today) ## returns the same as today.weekday()
print ( "Today : {} / {}-{}-{}".format ( days[wkday], today.month, today.day, today.year ))
Datetime formatting
print ( today.strftime ("%Y") ) ## full year, ex. 2019
print ( today.strftime ("%a") ) ## abbreviated day, ex. Tue
print ( today.strftime ("%d") ) ## day number, ex. 18
print ( today.strftime ("%B") ) ## full month, ex. December
print ( today.strftime ("%y") ) ## abbreviated year, ex. 19 for year 2019
print ( today.strftime ("%c") ) ## locale's date and time, ex. Tue Dec 18 21:36:09 2019
print ( today.strftime ("%x") ) ## locale's date, ex. 12/18/19
print ( today.strftime ("%X") ) ## locale's time, ex. 21:36:09

print ( today.strftime ("%A, %d %b, %Y") ) ## prints "Tuesday, 18 Dec, 2018"

# for time formatting #
# %I/%H - 12/24 hour system, %M - minute, %S - second, %p - locale's AM/PM
print ( today.strftime ("%H:%M:%S %p") ) ## 24-Hour:Minute:Second:AM/PM
print ( today.strftime ("%I:%M") )       ## 12-Hour:Minute
Timedeltas
# timedeltas #
from datetime import timedelta
print ( "One year from today :", datetime.now() + timedelta (days=365) )
print ( timedelta (days=222, hours=3, minutes=4) )
print ( "Today:", datetime.now() )
print ( "3 weeks and 3 days from now :", datetime.now() + timedelta(weeks = 3, days=3) )
print ( "3 weeks and 3 days from now :" + str(datetime.now() + timedelta(weeks = 3, days=3)) )
# how many days till Halloween

t1 = datetime.now() - timedelta(weeks=2)
t1str = t1.strftime ("%A %B %d, %Y")
print ( t1str + " is two weeks old." )

# how many days till Halloween
today = date.today()
halloween = date(today.year, 10,30)
if halloween < today:
    print ( "Halloween has passed by {} days".format( (today - halloween).days ))
    halloween = halloween.replace (year=today.year + 1)

time_to_halloween = abs(halloween - today)
print ( "There are", time_to_halloween.days, "more days to Halloween." )

Calendars
import calendar
# To start the calendar on Sunday as first column
c = calendar.TextCalendar (calendar.SUNDAY)
cstr = c.formatmonth (2019, 1, 0, 0)
print (cstr)

# returns multiple '0', say two '0' if 2019/1/1 starts on Tuesday
for i in c.itermonthdays (2019, 1):
    print (i)
for name in calendar.month_name:
    print (name)
for name in calendar.day_name:
    print (name)

ta = datetime.datetime (year=2018, month=1, day=1)
tb = datetime.datetime (year=2018, month=2, day=1)
tb-ta
ta-tb
print (tb-ta)

Turning Ideas into Object-oriented design, but why?

The basics, isn't it enough?
You learn the syntax and write some code. You learn the fundamentals and then you hit a wall.
Okay, this is getting dry and academic...
Before you take off, just bear with me a few more lines and see if you are still interested.
But why bother? I can sit down and code away just like that...
Just type any code, any code and you feel like progress and it's an easy emotional hit, but it's an illusion. You think you can suss out everything along the way and just go by the seat of the pants. Sometimes that works, right? 
How many of those code written this way are you still using?
Difference between a few lines of code and a future proof app.
It is about creating better and more complex applications, writing code faster with less pain, less bugs. It's about "future proof" and future proof means to be flexible, maintainable and extensible for new changes to come.
From idea to application
Maybe the first thing that comes to your mind is, "now what do I do?", when the blinking cursor in the IDE editor is daring you. Maybe you are seasoned programmer and you jump right to coding. Good software starts with good designs. It's time to grab some paper and pencil. 
You need something you can write on the back of a napkin and understand how to break it into right pieces. Then you know exactly what code to write.
Jargons and terminology
Terminology is not a formalized fixed way of thinking. It is necessary for communication in any professions. Think of chefs using cooking terms, musicians using chord, scales and symbols, we need a system to speak to our fellow programmers too. Knowing the right vocabulary saves us time from making silly mistakes, and from explaining the same ideas over and over again.
Okay then, what is Object-oriented?
What is Class, Object, Instance?
What is Polymorphism, Abstraction, Encapsulation, and blah?
I think we need a good night sleep before we open the can of worms.
Time for a break.

Python Class

Python Class is easy
# Example class

class Animal():
    def whoami (self):
        print ("I am an animal.")

    def sound_like (self, string):
        print ("Animal sounds like: " + string)

    def get_limps (self, i):
        print ("Animal has " + i + " limps.")

a = Animal()
a.whoami()
 
Inheritance
# Example class inheritance

class Dog (Animal):
    def whoami (self):
        Animal.whoami (self)
        super().whoami()
        print ("I am a Dog!")

b = Dog()
b.whoami()
 

Python Loops

Loops are for repetitive operations
# Example Loops
# this loop from 0 to 99
for i in range (100):
    print ( i )

# range (a,b) will loop from a to b
#   and a must be less than b
for i in range (3,5):
    print ( i )

# What is 3 doing here? Three is a crowd, or not?
for i in range (10,20,3):
    print ( i )

# Break or continue? That is the question.
for i in range ( 0, 9 ):
    if ( i == 7 ): break
    if ( i % 2 == 0 ): continue

# Lazy Ann's version
for i in range(10):
    if i == 7: break
    if i%2: continue

# Look! I can do days too!
days = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" ]
for d in days:
    print ( d )
# Python has while loop too.
i = 0
while i < 3:
    print ( i )
    i += 1
 
## Remember, python does not do "i++"

while True:
    print ( "I am in loop!" )
    if True:
        break
## See? You have to break it otherwise it goes on and on and on...

# No, python does not have do while loop

# But it has something cool called 'enumerator'
for i, d in enumerate (days):
    print (i, d)

# descinding
for i in range (9,1,-1):
    print (i)

x = range(10)
z = list(range(10))
y = list( 10-i for i in x )
print (x)
print (z)
print (y)

Python Conditionals

Conditionals is about decision making
# Example conditionals

## Some new tricks, one line
print ("foo" if True else "bar")
a = 3 if i == 4 else 99

i = 3
if i in [ 1,2,3 ]:
    print ( i )

x, y = 2, 9
if ( x > y ):
    z = x - y
elif:
    z = x + y
else:
    z = 0

def function_p ( *args ):
    numargs = len ( args )
    if numargs < 1: raise TypeError ( "requires at least one argument" )
    elif numargs == 1: pass
    else: raise TypeError ( "Too many arguments" )

## Nah, Python does not have switch-case statement like Java

## Python short-circuit logical AND
## Python does not have logical "&&"
if True and True:
    print ( "It is true!" )

a = ord('a')
b = 15
c = 0xf
d = 0b1111
print (a)
print (b)
print (c)
print (d)
print (hex(b))
print (bin(b))

Python Templates!

Python3
#!/usr/bin/python3
#
# Python Template
#
def main():
    print ("Hello World!") 

if __name__ == "__main__"
    main()
Python2
#!/usr/bin/python3
#
# Python Template
#
def main():
    print "Hello World!" 

if __name__ == "__main__"
    main()

Monday, December 17, 2018

Python Variables, Conditionals, Loops, Functions, just a feel.

Are you local? Or global?
# Example variables
p, q = 10, 20
t = True
f = False
s = "a string"
d = 33.567
x = 123
y = 456

def function_a():
    global y
    x = 987
    y = "banana"
    print ( x ) 

function_a()
print ( x )
print ( y )
del x ## remove a variable and undefine it
Conditionals
# Example conditionals
if True:
    print ( "It is true!" )

if i in [ 1,2,3 ]:
    print ( i )

x, y = 2, 9
if ( x > y ):
    z = x - y
elif:
    z = x + y
else:
    z = 0
Loops
# Example loops
for i in range(100):
    print ( i )

days = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" ]
for d in days:
    print ( d )

while True:
    print ("It is still going!")
## Ok, don't do this, this is an infinite loop! 
## You just did!? just type [Ctrl-C], phew...

Functions
# Example functions
def function_q():
    pass

def function_x( a,b ):
    return a + b

def functiona( a, b=100 ):
    c = a
    for i in range( b ):
        c += i
    return c

def function_y( list=[] ):
    pass

def function_z( hash={} ):
    print ( "in function_z" )
    ## without return, function returns None

function_q()
function_x( 1,2 )
function_y()
function_z()

## Try these, can you guess what will be printed?
print (function_z())
print (function_z)

Sunday, December 16, 2018

Python literals!

Numbers, Strings, and Boolean
# Example
x = 0
x = "string"
x = True
x = False
print ( x ) 
But, wait, it is strong typed!
# Example
a = 1
b = 2
s = "string"
print ( a )
print ( a,b )
print ( s )
print ( " The number is " + 123 ) ## Ding ding ding! Error! 
    ## I know what you are thinking, "but this works in Java, right?"
Here is how to help them get along!
# Example
print ( " The number is " + str(123) )

## You know what, this works too! I love python!
print ( " The number is ", 123 )
Operators
# Example
x = x + 1
x += 1
x -= 1
y = x // 3
y = x % 3
x *= y + z
x = x * (y+z)
x /= y + z
x = x / (y+z)


What do you think this will do?
x =+ 5
y =- 3

Python scripting 101!

Braces? Semicolons? Meh.
# Example
def main():
    print ("Hello World!") 
You guessed it!  '#' comments out the rest of line
# Example
def main(): # this is the main function
    print ("Hello World!") # this prints Hello World!
Unlike the command-line interpreter, you need to print to see it!
# Example
def main():
    a = 1
    b = 2
    a + b ## this will not be printed
    c = a + b
    print ( "The result is", c )
    print ( a,b,c )
    print ("Hello World!") 
    # undefine a variable in real time
    del c
Everything is object in python!
We'll cover this later... 
Can it run on its own? Sure it can.
#!/usr/local/bin/python3
def main():
    print ("Hello World!") 

if __name__ == "__main__":
    main()

## make sure you change the file to be executable in shell.
## % chmod +x hw.py

Meet Python Command Line Intepreter!

Python is not a compiled language like C, C++ or Java. It does not need to be compiled into executable before you run it.

Python is a interpreted language.

% python3
import this

>>> 2+2
4
>>> print( "Hello World!" )
Hello World!
>>> a = 1
>>> b = 2
>>> a+b
3
>>> exit()

## or key in Ctrl-D

Python Editor and IDE.

Do I have Python3 Installed?
python3 --version
How do I download Python3?
https://www.python.org
Click here to Start!

Click the Downloads tab, and choose Python3 or Python2.
Where do I download Visual Studio?
https://code.visualstudio.com
Click here to Start!
Where do I download IntelliJ?
https://www.jetbrains.com/idea/
Click here to Start!
Where do I download Komodo-edit?
https://www.activestate.com/komodo-edit/
Click here to Start!
Where do I download Anaconda?
https://www.anaconda.com/download/#macos/
Click here to Start!
Where do I download Xcode?
Go to Apple Store and search for Xcode. 
The first application should be it!

Hello World! Who's there?

Python2:
print "Hello World!"
Python3:
print ( "Hello World!" )
C:
#include <stdio.h>

int main (void)
{
    printf ("Hello World!\n");
    return 0;
}
C++:
#include <iostream>
using namespace std;

int main (void)
{
    cout << "Hello World!\n");
    return 0;
}
Java:
public class HelloWorld {
    public static void main (String[] args) {
        System.out.println ("Hello, World!");
    }
}