Ec 02 2023
Ec 02 2023
Evolutionary Computation
EE-6950, Fall 2023
Lecture # 2 - Python Review & SW Development Best Practices
Outline
Note: Today we will do a very rapid review of Python. Will highlight language
peculiarities, especially for those coming from C++, Java, etc.
IV. Homework #1
2
I. Python programming fundamentals
What is Python?
• Python:
• A high-level, general purpose interpreted programming language
• Object-oriented
• Dynamically typed
• Automatic memory management (garbage collection)
• Highly introspective and malleable
• In addition to OO, also supports Functional style programming
• Cross platform
• Everything is an object!
4
How To Run Python Programs
• Interactive interpreter:
python3
Python 3.7.8 (v3.7.8:4b47a5b6ba, Jun 27 2020, 04:47:50)
[Clang 6.0 (clang-600.0.57)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> print('Hello World!')
Hello World!
>>>
python3 –m Hello
Hello World!
• Shell scripts:
#!/usr/bin/env python
import Hello
Hello.main()
Hello World!
5
fi
Getting Help: The interactive interpreter is your friend
Example:
>>> dir(list)
['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__',
'__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__',
'__iadd__', '__imul__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__',
'__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__',
'__reversed__', '__rmul__', '__setattr__', '__setitem__', '__sizeof__', '__str__',
'__subclasshook__', 'append', 'clear', 'copy', 'count', 'extend', 'index', 'insert', 'pop',
'remove', 'reverse', 'sort']
>>>
fi
Getting Help: The interactive interpreter is your friend
Example:
>>> from random import Random
>>> help(Random.shuffle)
Help on function shuffle in module random:
shuffle(self, x, random=None)
Shuffle list x in place, and return None.
Optional argument random is a 0-argument function returning a random float in [0.0, 1.0);
if it is the default None, the standard random.random will be used.
(END)
fi
Getting Help: The online Python documentation
• https://docs.python.org
8
Installing Packages/Libraries – pip
9
Python Code Structure - Whitespace
10
fi
Python Code Structure – Comments & Help
>>>help(TestFunction)
11
Code Organization – Modules & Packages
• Modules:
- Each le with a .py suf x is a module
- Each module has its own namespace
• PYTHONPATH
- When importing modules and packages, python interpreter will search local path, the python
interpreter system path, and all paths listed in the PYTHONPATH environment variable
- This allows you to better organize your python les and packages (for example, no need to
keep them all in the current working directory)
12
fi
fi
fi
fi
Modules & Packages -- Importing
13
fi
Module & Package Import Examples
>>> import TestModule
>>> TestModule.TestFunction(123)
14
Variables & Dynamic Typing
• Variables are not declared, just assigned eevee$ python3
>>> x
• A variable is created the rst time you Traceback (most recent call last):
assign it a value
File "<stdin>", line 1, in <module>
• Variables are references to objects NameError: name 'x' is not defined
>>> x="hello"
• Type information is with the object, not >>> print(x)
the reference hello
• Everything in Python is an object >>> y=123.4
>>> print(y)
- Basic datatypes
- Functions 123.4
- Class instances >>> y+10
- Classes 133.4
- Modules >>> x+" world"
- Heck, even Types! 'hello world'
- Yup…pretty much everything! >>>
15
fi
Everything is an object
eevee$ python3
>>> x=1.2e4
>>> type(x)
<class 'float'>
>>>
>>> y=[1,2,3]
>>> type(y)
<class 'list'>
>>>
>>> def TestFunction(x):
... return x
...
>>> z=TestFunction
>>> type(z)
<class 'function'>
>>>
>>> a=float
>>> type(a)
<class 'type'>
>>>
>>> import random
>>> b=random
>>> type(b)
<class 'module'>
>>>
16
Basic datatypes
17
Basic datatypes generally work exactly the way you’d expect them to!
19
Strings
20
String operators, functions
• There are many, many useful built-in methods for working with strings. Here
are a few…
21
Lists
22
Lists: “Backwards” indexing
• a = x[-1]
• b = x[-2]
23
List operators, functions
• There are many useful built-in methods for working with lists.
24
Tuples
25
Dictionaries
• A set of key-value pairs >>> d = {1: 'hello', 'two': 42, 'blah': [1,2,3]}
>>> d
• Dictionaries are mutable {1:
>>>
'hello', 'two': 42, 'blah': [1, 2, 3]}
d['blah']
[1, 2, 3]
26
Dictionary operators, functions
27
Copying Dictionaries and Lists
28
Sets
29
Files
30
Data Type Summary
• Integers: 2323
• Floating Point: 32.3, 3.1E2
• Complex: 3 + 2j, 1j
• Booleans: True, False
• None type: None
• Strings: “this is a string”
• Lists: l = [ 1,2,3]
• Tuples: t = (1,2,3)
• Dictionaries: d = {‘hello’ : ‘there’, 2 : 15}
• Sets: s ={123, ‘abc’}
• Files: f=open(‘data.txt’, ’r’)
31
Next up, control and loop statements…
32
If statements
33
while statements
34
for loops
35
for loops: the range function
36
Next up, functions
• def
37
Function Basics
38
fi
Functions are first-class objects
39
Function Parameters: Defaults
40
Function Parameters: Named
• Pay attention, you will nd this very >>> def foo (a,b,c) :
useful! ... print a, b, c
...
• Call by name >>> foo(c = 10, a = 2, b = 14)
2 14 10
• Any positional arguments must come >>> foo(3, c = 2, b = 19)
before named ones in a call 3 19 2
41
fi
Exceptions: Hierarchical stack traces
• Exceptions automatically generate hierarchical stack traces
42
Some useful additional packages and libraries.
• System, os, and le-system: import os, import sys, import shutil
• Serialization: YAML, JSON
• Random numbers – import random
• Graphs – networkx
• Scienti c data visualization – matplotlib
• Matrices and linear algebra – numpy
• Scienti c number crunching – scipy
• Machine Learning – scikit-learn, Tensor ow, PyTorch
• Image processing – Pillow (formerly PIL), OpenCV
• Many more available…
43
fi
fi
fi
A few notes on Python computational efficiency
44
II. Object-oriented Python
Classes and Object-oriented programming
46
Objects and Classes – remember?
Classes Instances
Class name
Data
Functions
47
A simple example: Point class
# A Simple Point class (represents an x,y coordinate)
#
class Point:
# __init__ function is the constructor
def __init__(self,x=0,y=0):
self.x=x
self.y=y
48
The Constructor Method
49
fi
Point class example: Object instances
• Point class de nition can be used to
generate multiple object instances
- Each instance has its own data
- Each instance can be manipulated
independently
50
fi
Point class example: Object instances
51
fi
Class Inheritance
52
fi
fi
Class inheritance – Python syntax
53
Class inheritance – Animals
54
Class inheritance – Animals
55
Class inheritance – Super-class access
class Derived(Base):
def __init__(self):
super().__init__() #this will call Base’s __init__
print(“This is the derived ctor!”)
56
Class inheritance – Super-class access
class B(A):
def __init__(self):
super().__init__()
print("Called Init B!")
class C(B):
def __init__(self):
super().__init__()
print("Called Init C!")
Called Init A!
c=C() Called Init B!
Called Init C!
57
III. Software Development Best Practices
Software Development Best Practices
59
Software Development Cycle
60
Modularization
61
Modularization: Benefits
• Why Modularization?
- Facilities code re-use (components can be used in many di erent programs)
- Much easier to debug!
- Much easier to test
- Much easier to maintain
- Much easier to collaborate on larger projects with multiple developers
62
Version Control
63
fi
Version Control: Overview
• Version control tools “automatically” maintain/track all changes to your les over time
64
fi
fi
ff
fi
fi
Version Control: File change timeline
• Version control system maintains a timeline for all changes in
all versions of your les and software releases
65
fi
Git Demo/Tutorial
• This grad student (Brian Yu) in Harvard's CS Dep't made a
nice YouTube tutorial on Git & GitHub
• https://youtu.be/MJUJ4wbFm_A
66
Testing: Overview
• Algorithm and functional veri cation testing
- Test that your algorithms and computational code give correct results and reasonable
performance
• Unit testing
- Suites of smaller, more focused tests that check behavior of speci c aspects of
functions, classes, etc.
- Usually run by an automated framework
- Python has built-in unit-test framework called PyUnit. This can be accessed with
import unittest
• Nightly automated regression testing
- For production software usually there is a test harness that runs suites of regression
tests nightly, and reports any failures back to the developers
- Nightly tests may work in conjunction with version control system to automate traceback
to nd source of failures (which check-in or changelist)
67
fi
fi
Testing: Python unittest
68
Testing: unittest output (one test fails)
• python testMytest.py
F..
======================================================================
FAIL: test_isupper (__main__.TestStringMethods)
----------------------------------------------------------------------
Traceback (most recent call last):
File ”testMytest.py", line 9, in test_isupper
self.assertTrue('FOo'.isupper())
AssertionError: False is not true
----------------------------------------------------------------------
Ran 3 tests in 0.000s
FAILED (failures=1)
69
Repeatability: Overview
Multiple Runs
Note: Yes, there are a few applications that need true randomness (e.g.,
cryptography, uuid’s), but these are generally the exception
70
Repeatability: Determinism is good!
71
Debugging: A few tips…
72
Documentation: Overview
73
fi
Bug Tracking: Overview
74
IV. Homework #01
- Due by Sept 21 @ noon
- Submit to iLearning
Homework #1: Welcome to Madagascar
• Submit to iLearning:
• Due by Sept 21 @ noon
• Submit only your python program
76
Homework #1: Welcome to Madagascar
For this assignment, use input data le: assign1_input.txt
- This le contains a collection of animals (zebra, lion, hippo, gira e, penguin, gorilla)
that want to escape from NCHU’s Central Park!
- But they are in a hurry, and have cluttered up the park with integers everywhere!
- Some of penguins have even hurt themselves, so they are misspelled as "pengiun"
- There is also a hidden treasure, but we only know it’s a very very large integer.
- Animal names are separated either by new lines or %’s
- Example:
zebra%zebra%zebra
lion
1234
penguin
pengiun%penguin%pengiun
54687
77
fi
fi
Homework #1: Welcome to Madagascar
Start with hw1_skeleton.py. There is a “Decoder” in it to help you discover
the treasure. The contents of the le are shown below:
78
fi
Homework #1: Welcome to Madagascar - Criteria
1. Find all integers in the le:
•Add them to a Python list, sort largest to smallest (example: [10, 4, 1]), and you’ll
notice that there is only one very large number (compared to others) in your list.
That’s our encoded treasure!
•Use the decoder (we have already given in the code) to reveal it, then replace the
encoded number with the treasure. (Hint: It might be something related to our
course.) After that, write the Python list out to le ‘animals.out’
•Add all the integers ( except the encoded treasure) together & take the natural log of
the total. Write this value to le ‘animals.out’ using exponential format with 2 digits
of precision (example: 1.23e+05)
2. Some penguin’s have been spelled incorrectly as ‘pengiun’. Fix the spelling,
and write out a corrected version of the le to ‘ xed.out’
79
fi
fi
Homework #1: Welcome to Madagascar - Criteria
3. Create a Python dictionary with animal names as keys and a count of
occurrences as values. Example: {‘lion’: 5, ‘hippo’:11}. Write the nal
dictionary out to le ‘animals.out’
4. Calculate the total number of animals encountered in the le, then write out
the total as a dictionary, as follows:
80
fi
Homework #1: Welcome to Madagascar - Result Example
Final output le ‘animals.out’ should look something like this:
81
fi
Next week:
- Back to EC!