::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: :: 2021-01-13WhiteboardCS212.txt :: Introduction to CS212 Robert Heckendorn Python simple, forgiving, compact and readable scripting numerical analysis/machine learning prototyping language implementation numerous modules/packages Goal learn and practice python looking at a variety of popular modules get things done in python python is a useful tool in your tool box talking about how to program have fun Assumptions You aren't new to computing maybe you've programmed a little before Assignments 10-12 assignments mostly to be small Lecture zoom + whiteboards txt files Office hours/help appointment for zoom email me - 100 msgs a day write me a second time ask questions in class (chat - speak) CSAC - (CS help center) homework submission on class page no late papers! tests and emails difference between your output and expected output gives your submission a timestamp! use timestamp to talk to me about your full code last submitted before deadline is the one graded use submission to recover demaged files get access to python 3 loading python 3 loading packages numpy... (anaconda) GRADING HAPPENS ON THE CS DEPARTMENT TEST MACHINE ONLY CS machines are LINUX grading points ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: :: 2021-01-15WhiteboardCS212.txt :: Python Pros: easy to code clean concise syntax not strongly typed (few declarations) easy to read good error messages lots of support including IDEs (integrated development environments) lots of prebuilt packages implemented in a very simple transparent way flexible!! Cons: not strongly typed (few declarations) slow slow slow compiled language code --> Compiler --> Intel/A15 interpeted language (Python) code --> Python "Compiler" --> virtual machine --> Intel/A15 file.py python VM DOWNLOADING AND SETUP python3.8 recommend: anaconda.com includes R a free statisical package also use: python.org or miniconda into a command line window PATH variable python3 TASK for Wednesday: downloaded and have command line access to python3, import turtle OPTIONAL TASK: if you are on windows find a UNIX commandline wrapper for your command window. FUTURE TASK: might want to copy files between machines scp command IDEs idle VSCode Jupyter Notebook recommend: use your favorite editor and a file pwd - current directory mkdir dirname - make new directory ls - list files (dir command in Windows) cd newdir - change current directory e file.py - my text editor (txt) cat a b c - concatenate and print files ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: :: 2021-01-20WhiteboardCS212.txt :: Upcoming packages or moducles turtle matplotlib unix commands three ways to execute python import and namespaces ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: :: 2021-01-22WhiteboardCS212.txt :: Names Name Spaces Scoping - local, global, static, namespaces(modules that we can import) lexically known in a given area of the *text* of the program strings: "dogs" 'cats' """dogs say "it's a nice day". """ '''dogs say "it's a nice day". ''' The example we worked on in class: ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: :: pp.py :: #!/usr/bin/env python3 """this is my whole module more stuff more stuff more stuff more stuff more stuff more stuff """ def fact(m) : """factorial computation 1*2*3*...*m""" n = 1 # local for i in range(2, m+1) : # range goes upto but NOT including final number n *= i return n def factr(m) : """recursive factorial computation 1*2*3*...*m""" if m < 2 : return 1 else : print(m) return factr(m-1) * m def main(): n = 10 # local print(n, factr(n)) print(n) ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: :: 2021-01-25WhiteboardCS212.txt :: Types: int float bool none ------------------------------------ Objects: ask the data to do an action (a method) d.capitalize() Functions: ask the action to work on the data len(d) ------------------------------------ str which is the name of the string class is an object class string constants are: "stuff", 'stuff', """stuff""", '''stuff''' you can "escape" characters with backslash: tab \t, newline \n, formfeed \f, null \0, ... including \" and \' ------------------------------------ mutable vs inmutable str, int, floats, bool, none are all immutable ------------------------------------ numbering in strings and lists and ... d o g s a n d c a t s 0 1 2 3 4 5 6 7 8 9 ------------------------------------- From out live python session: >>> d = "dogs" >>> len(d) 4 >>> d.len() Traceback (most recent call last): File "", line 1, in AttributeError: 'str' object has no attribute 'len' >>> d.capitalize() 'Dogs' >>> dir(str) # tell me all the symbols in str, which is the string class: ['__add__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'capitalize', 'casefold', 'center', 'count', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'format_map', 'index', 'isalnum', 'isalpha', 'isascii', 'isdecimal', 'isdigit', 'isidentifier', 'islower', 'isnumeric', 'isprintable', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'maketrans', 'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill'] >>> d 'dogs' >>> d.swapcase() 'DOGS' >>> help(str) # use help to tell me about the string class >>> help(str.swapcase) # use help to tell me about swapcase in the string class >>> d 'dogs' >>> x = 666 >>> x 666 >>> x = "dogs" >>> x 'dogs' >>> x.capitalize() 'Dogs' >>> x 'dogs' >>> x = x.capitalize() >>> x 'Dogs' >>> x = x.append(" ") Traceback (most recent call last): File "", line 1, in AttributeError: 'str' object has no attribute 'append' >>> "dogs" + " and " + "cats" 'dogs and cats' >>> 33 * "dogs and " 'dogs and dogs and dogs and dogs and dogs and dogs and dogs and dogs and dogs and dogs and dogs and dogs and dogs and dogs and dogs and dogs and dogs and dogs and dogs and dogs and dogs and dogs and dogs and dogs and dogs and dogs and dogs and dogs and dogs and dogs and dogs and dogs and dogs and ' >>> 33 * "dogs and " + "dogs" 'dogs and dogs and dogs and dogs and dogs and dogs and dogs and dogs and dogs and dogs and dogs and dogs and dogs and dogs and dogs and dogs and dogs and dogs and dogs and dogs and dogs and dogs and dogs and dogs and dogs and dogs and dogs and dogs and dogs and dogs and dogs and dogs and dogs and dogs' >>> dc = "dogs" + " and " + "cats" + File "", line 1 dc = "dogs" + " and " + "cats" + ^ SyntaxError: invalid syntax >>> dc = "dogs" + " and " + "cats" >>> dc 'dogs and cats' >>> upper(dc) # upper is a method and not a function Traceback (most recent call last): File "", line 1, in NameError: name 'upper' is not defined >>> dc.upper() 'DOGS AND CATS' >>> dc = dc + " and horses" >>> dc 'dogs and cats and horses' >>> dc.title() 'Dogs And Cats And Horses' >>> dc.find("and") 5 >>> dc 'dogs and cats and horses' >>> dc[1] 'o' >>> dc[0] 'd' >>> dc[2] 'g' >>> dc[5:8] 'and' >>> dc[0:8] 'dogs and' >>> dc[:8] 'dogs and' >>> dc[8:] ' cats and horses' >>> dc[:7] 'dogs an' >>> dc[7:] 'd cats and horses' >>> dc[7:1000] 'd cats and horses' >>> dc[7:] 'd cats and horses' >>> dc[7:len(dc)] 'd cats and horses' >>> len(dc) 24 >>> dc[7:len(dc)-1] 'd cats and horse' >>> dc[7:-1] 'd cats and horse' >>> dc[7:-2] 'd cats and hors' >>> dc[7:len(dc)-2] 'd cats and hors' >>> quit() ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: :: 2021-01-27WhiteboardCS212.txt :: factor: 60? -> 2 60 = 2*(x) = 2*(2*3*5) secret part in parens 60 = 2*30 factor: 30? 30 = 2*15 = 2*(3*5) secret part in parens factor: 15? 15 = 3*5 = 3*(5) secret part in parens factor: 5? 2*2*3*5 ------------------- factor: 282 factor 282? -> 2 282 = 2*x = 2*(141) = 2*(mystery) so x must = 141! factor 141? -> 3 282 = 2*x = 2*(141) = 2*(3*y) = 2*3*(mystery) = 2*3*(y) factor 141//3? -> factor 47? 141 = 3*47 282 2*3*47 ------------------- factor 385 = 5*x x=77 factor 77 = 7*x x=11 factor 11 = 11*1 ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: :: 2021-01-29WhiteboardCS212.txt :: #!/usr/bin/env python3 # def isfactor(m, n) : # """Does n divide m evenly?""" # if (m//n)*n == m : # return True # else : # return False # def isfactor(m, n) : # """Does n divide m evenly?""" # return (m//n)*n == m def isfactor(m, n) : """Does n divide m evenly?""" return m%n == 0 def main() : for m in range(300, 310+1) : print() for i in range(1, 10+1) : print(m, i, isfactor(m, i)) main() ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: :: 2021-02-01WhiteboardCS212.txt :: ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: :: ioforsysstdin.py :: #!/usr/local/bin/python3 import sys # for will actually read line + newline directly from a stdin object for x in sys.stdin : print('"{0}"'.format(x)) ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: :: ioinput.py :: #!/usr/local/bin/python3 # no import needed for input # reads one line. Input takes an optional argument to prompt the user # NOTE: the newline is NOT included in the returned data x = input() print('"{0}"'.format(x)) ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: :: ioread.py :: #!/usr/local/bin/python3 import sys # reads the whole file as a single string x = sys.stdin.read() print('"{0}"'.format(x)) ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: :: ioreadline.py :: #!/usr/local/bin/python3 import sys # reads one line with newline x = sys.stdin.readline() print('"{0}"'.format(x)) ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: :: ioreadlines.py :: #!/usr/local/bin/python3 import sys # reads the whole file in putting each line + newline as an item in a list x = sys.stdin.readlines() print('"{0}"'.format(x)) ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: :: 2021-02-10WhiteboardCS212.txt :: MobileMeerkat3: mkdir X MobileMeerkat3: go Z OLD: /Users/meerkat/Desktop/Desktop/Teaching/CS212/S21/Python TRY: Z go from /Users/meerkat/Desktop/Desktop/Teaching/CS212/S21/Python to /Users/meerkat/Desktop/Desktop/Teaching/CS212/S21/Python/Z (classified as down) /Users/meerkat/Desktop/Desktop/Teaching/CS212/S21/Python/Z to /Users/meerkat/Desktop/Desktop/Teaching/CS212/S21/Python/.down /Users/meerkat/Desktop/Desktop/Teaching/CS212/S21/Python to /Users/meerkat/Desktop/Desktop/Teaching/CS212/S21/Python/Z/.up SUCCESS to go to "/Users/meerkat/Desktop/Desktop/Teaching/CS212/S21/Python/Z" MobileMeerkat3: back /Users/meerkat/Desktop/Desktop/Teaching/CS212/S21/Python MobileMeerkat3: go X OLD: /Users/meerkat/Desktop/Desktop/Teaching/CS212/S21/Python TRY: X go from /Users/meerkat/Desktop/Desktop/Teaching/CS212/S21/Python to /Users/meerkat/Desktop/Desktop/Teaching/CS212/S21/Python/X (classified as down) /Users/meerkat/Desktop/Desktop/Teaching/CS212/S21/Python/X to /Users/meerkat/Desktop/Desktop/Teaching/CS212/S21/Python/.down /Users/meerkat/Desktop/Desktop/Teaching/CS212/S21/Python to /Users/meerkat/Desktop/Desktop/Teaching/CS212/S21/Python/X/.up SUCCESS to go to "/Users/meerkat/Desktop/Desktop/Teaching/CS212/S21/Python/X" MobileMeerkat3: cs MobileMeerkat3: ls MobileMeerkat3: pwd /Users/meerkat/Desktop/Desktop/Teaching/CS212/S21/Python/X MobileMeerkat3: cs MobileMeerkat3: e fact.py MobileMeerkat3: chmod a+x fact.py MobileMeerkat3: fact.py fact: 10 fact: 9 fact: 8 fact: 7 fact: 6 fact: 5 fact: 4 fact: 3 fact: 2 fact: 1 3628800 MobileMeerkat3: e fact.py MobileMeerkat3: fact.py fact: 2 fact: 1 2 2 fact: 3 fact: 2 fact: 1 3 6 fact: 5 fact: 4 fact: 3 fact: 2 fact: 1 5 120 fact: 7 fact: 6 fact: 5 fact: 4 fact: 3 fact: 2 fact: 1 7 5040 fact: 11 fact: 10 fact: 9 fact: 8 fact: 7 fact: 6 fact: 5 fact: 4 fact: 3 fact: 2 fact: 1 11 39916800 fact: 13 fact: 12 fact: 11 fact: 10 fact: 9 fact: 8 fact: 7 fact: 6 fact: 5 fact: 4 fact: 3 fact: 2 fact: 1 13 6227020800 MobileMeerkat3: e fact.py MobileMeerkat3: cs MobileMeerkat3: python3 Python 3.8.5 (default, Sep 4 2020, 02:22:02) [Clang 10.0.0 ] :: Anaconda, Inc. on darwin Type "help", "copyright", "credits" or "license" for more information. >>> d = [] >>> type(d) >>> d = {} >>> type(d) >>> d {} >>> d["one"] = "eins" >>> d["one"] 'eins' >>> d["two"] Traceback (most recent call last): File "", line 1, in KeyError: 'two' >>> d["two"] = "zwei" >>> d["two"] 'zwei' >>> d["one"] 'eins' >>> d[1] = "eins" >>> d[1] 'eins' >>> d["one"] 'eins' >>> d {'one': 'eins', 'two': 'zwei', 1: 'eins'} >>> d[("dog", 33)] = "dog stuff" >>> d[("dog", 33)] 'dog stuff' >>> d[["dog", 33]] Traceback (most recent call last): File "", line 1, in TypeError: unhashable type: 'list' >>> >>> d["three"] = "drei" >>> d {'one': 'eins', 'two': 'zwei', 1: 'eins', ('dog', 33): 'dog stuff', 'three': 'drei'} >>> d.keys() dict_keys(['one', 'two', 1, ('dog', 33), 'three']) >>> for k in d.keys() : print(k) ... one two 1 ('dog', 33) three >>> list(d.keys()) ['one', 'two', 1, ('dog', 33), 'three'] >>> for k in d.keys() : print(k, d[k]) ... one eins two zwei 1 eins ('dog', 33) dog stuff three drei >>> for k in d : print(k) ... one two 1 ('dog', 33) three >>> for k in d.values() : print(k) ... eins zwei eins dog stuff drei >>> for k in d.items() : print(k) ... ('one', 'eins') ('two', 'zwei') (1, 'eins') (('dog', 33), 'dog stuff') ('three', 'drei') >>> sorted(d.keys()) Traceback (most recent call last): File "", line 1, in TypeError: '<' not supported between instances of 'int' and 'str' >>> d["four"] Traceback (most recent call last): File "", line 1, in KeyError: 'four' >>> d.get("four", "No value here") 'No value here' >>> "four" in d False >>> "four" not in d True >>> d {'one': 'eins', 'two': 'zwei', 1: 'eins', ('dog', 33): 'dog stuff', 'three': 'drei'} >>> "the number is: {}".format(331) 'the number is: 331' >>> print("the number is: {}".format(331)) the number is: 331 >>> print("the number is: {} and not {}".format(331, 666)) the number is: 331 and not 666 >>> print("the number is: {} and not {}%".format(331, 666)) the number is: 331 and not 666% >>> print("the number is: {} and not {}%".format(331, 666)) the number is: 331 and not 666% >>> print("the number is: {0} and not {1}".format(331, 666)) the number is: 331 and not 666 >>> print("the number is: {1} and not {0}".format(331, 666)) the number is: 666 and not 331 >>> print("the number is: {1} yes really {1}".format(331, 666)) the number is: 666 yes really 666 >>> import math >>> math.pi 3.141592653589793 >>> pi = math.pi >>> pi 3.141592653589793 >>> "pi is {6.1f}".format(pi) Traceback (most recent call last): File "", line 1, in IndexError: Replacement index 6 out of range for positional args tuple >>> "pi is {0:6.1f}".format(pi) 'pi is 3.1' >>> >>> "pi is {0}".format(pi) 'pi is 3.141592653589793' >>> "pi is {0:6.1f}".format(pi) 'pi is 3.1' >>> "pi is {0:<6.1f}".format(pi) 'pi is 3.1 ' >>> "pi is {0:>6.1f}".format(pi) 'pi is 3.1' >>> "pi is {0:^6.1f}".format(pi) 'pi is 3.1 ' >>> "in hex it is {:x}".format(100) 'in hex it is 64' >>> "in hex it is {:b}".format(100) 'in hex it is 1100100' >>> "pi is {0:6.1e}".format(pi) 'pi is 3.1e+00' >>> "pi is {0:6.1e}".format(pi*4) 'pi is 1.3e+01' >>> "{}".format(3331) '3331' >>> "{:10}".format(3331) ' 3331' >>> "{:>10}".format(3331) ' 3331' >>> "{:<10}".format(3331) '3331 ' >>> "{:^10}".format(3331) ' 3331 ' >>> ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: :: 2021-02-12WhiteboardCS212.txt :: alphabet keyword --> key keyword:dogsandcats key: dogsancts + be...xyz from kw remainder alpha="abcdefghijklmnopqrstuvwxyz" alpha: abcdefghijklmnopqrstuvwxyz key: cdoeaz... clear: deaf code: eacz makeKey(keyword) encaesar(keyword, s) decaesar(keyword, s) >>> "".maketrans("dog", "abc") {100: 97, 111: 98, 103: 99} >>> type("".maketrans("dog", "abc")) >>> "dogs and hogs".translate("".maketrans("dog", "abc")) 'abcs ana hbcs' >>> t = "".maketrans("dog", "abc") >>> "frogs eat dogs".translate(t) 'frbcs eat abcs' >>> ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: :: mycodes.py :: #!/usr/bin/env python3 """Provides functions for encoding and decoding a string All functions assume the message is lower case with all spaces and punctuation removed. """ alpha="abcdefghijklmnopqrstuvwxyz" def makeKey(keyword) : """Makes a key from a keyword or phrase""" leftover = alpha keyword = keyword.replace(" ", "") key = "" for c in list(keyword) : leftover = leftover.replace(c, "") if c not in key : key += c return key + leftover def encaesar(keyword, s) : """This will encode a string using a caesar cipher with given keyword""" return s.translate("".maketrans(alpha, makeKey(keyword))) def decaesar(keyword, s) : """This will encode a string using a caesar cipher with given keyword""" return s.translate("".maketrans(makeKey(keyword), alpha)) def _testMe() : print(makeKey("what a beautiful day")) s = "Be yourself. Everyone else is already taken.".lower().replace(" ", "").replace(".", "") print(s) kw = "dogs and cats" e = encaesar(kw, s) print(e) print(decaesar(kw, encaesar(kw, s))) if __name__ == "__main__" : _testMe() ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: :: 2021-02-24WhiteboardCS212.txt :: Here is the in class program (notice I added the screen.tracer(0, 0) command to speed it up.) tree.txt is best drawn with a smaller angle like 40 degrees and longer length like 200. hilbert curve is best draw with short edges and angle of 90. In our homework we'll make it so it is possible to changes these in our lsystem file rather than in the python program. ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: :: yurtle.py :: #!/usr/bin/env python3 from turtle import (Screen, Turtle) screen = Screen() def stopit(x, y) : """A call-back routine for button click on draw screen""" print("bye bye") quit() def openDraw() : """open a canvas to draw upon and return a turtle to draw with""" width = 1400 height = 1200 screen.setup(width, height) screen.bgcolor("black") screen.setworldcoordinates(-width//2, -height//2, width//2, height//2) screen.onclick(stopit) screen.tracer(0,0) # do this for speedier drawing! t = Turtle() t.pensize(3) t.hideturtle() t.pencolor("red") return t # return the turtle defs = {} def runDraw(t, instructions) : """do the drawing using character based instructions""" size = 100 angle = 90 scale = 1.0 shrinkRatio = .6108 positions = [] angles = [] scales = [] addr = 0 depth = 0 depthLimit = 5; while addr < len(instructions) : instr = instructions[addr] if instr in defs : if depth < depthLimit : instructions = defs[instr] + '\\' + instructions[addr+1:] print(instructions) depth += 1 addr = -1 elif instr == '\\' : depth -= 1 elif instr == '=' : # =SF+F+F+F name = instructions[addr+1] code = instructions[addr+2:] defs[name] = code print(defs) instructions = "" elif instr == 'F' : t.forward(size*scale) elif instr == '>' : scale *= shrinkRatio elif instr == '<' : scale /= shrinkRatio elif instr == '+' : t.left(angle) elif instr == '-' : t.right(angle) elif instr == '[' : scales.append(scale) positions.append(t.pos()) angles.append(t.heading()) elif instr == ']' : scale = scales.pop() t.penup() t.goto(positions.pop()) t.setheading(angles.pop()) t.pendown() elif instr == 'c' : t.clear() elif instr == 'p' : screen.mainloop() elif instr == 'q' : quit() else : # if the instruction is not recognized then do nothing!!! pass addr += 1 def main() : t = openDraw() while True : runDraw(t, input("Command me:")) screen.update() # update the scree drawing here main() ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: :: tree.txt :: =X{[-F>X]}{[+F>X]} FX p ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: :: hilbert.txt :: =A{+BF-AFA-FB+} =B-AF+BFB+FA- A p ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: :: 2021-02-26WhiteboardCS212.txt :: #!/usr/bin/env python3 """An example of a class and instances using the Dog class""" class Dog : """A dog class""" def __init__(self, name, size="medium", birthday="unknown", breed="corgi") : """create a Dog""" self.name = name self.size = size self.birthday = birthday self.breed = breed def __str__(self) : return f"Dog Name: {self.name} Size: {self.size} Breed: {self.breed}" def print(self) : """print a Dog""" # print("Dog Name: {} Size: {}".format(self.name, self.size)) print(f"Dog Name: {self.name} Size: {self.size}") d = Dog("snoopy", breed="pug", size="small") e = Dog("lassie") d.print() print(d) Dog.print(d) ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: :: 2021-03-01WhiteboardCS212.txt :: ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: :: dogs.py :: #!/usr/bin/env python3 """An example of a class and instances using the Dog class""" class Dog : """A dog class""" __numberOfDogs = 0 @classmethod def getNumberOfDogs(cls) : return cls.__numberOfDogs def __init__(self, name, size="medium", birthday="unknown", breed="corgi") : """create a Dog""" self.name = name self.size = size self.birthday = birthday self.breed = breed Dog.__numberOfDogs += 1 self.id = Dog.__numberOfDogs def __str__(self) : return f"Dog Name: {self.name} Size: {self.size} Breed: {self.breed} Id: {self.id}" def print(self) : """print a Dog""" print(self.__str__()) # print("Dog Name: {} Size: {}".format(self.name, self.size)) # print(f"Dog Name: {self.name} Size: {self.size}") d = Dog("zappo", breed="pug", size="small") e = Dog("snoopy", "medium", breed="begal") f = Dog("lassie") print(d) print(e) print(f) print(Dog.getNumberOfDogs()) print(d.getNumberOfDogs()) # misspell of a property leads to the illusion that I have set the real property d.nname = "Fido" print(d) print(d.nname) print(dir(d)) print(dir(e)) ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: :: dogs2.py :: #!/usr/bin/env python3 """An example of a class and instances using the Dog class""" # inheritance class Mammal : """A Mammal class""" def __init__(self, name, size="medium") : self.name = name self.size = size class Dog (Mammal) : """A dog class""" __numberOfDogs = 0 @classmethod def getNumberOfDogs(cls) : return cls.__numberOfDogs def __init__(self, name, size="medium", birthday="unknown", breed="corgi") : """create a Dog""" super().__init__(name, size) self.birthday = birthday self.breed = breed Dog.__numberOfDogs += 1 self.id = Dog.__numberOfDogs def __str__(self) : return f"Dog Name: {self.name} Size: {self.size} Breed: {self.breed} Id: {self.id}" def print(self) : """print a Dog""" print(self.__str__()) # print("Dog Name: {} Size: {}".format(self.name, self.size)) # print(f"Dog Name: {self.name} Size: {self.size}") d = Dog("zappo", breed="pug", size="small") e = Dog("snoopy", "medium", breed="begal") f = Dog("lassie") print(d) print(e) print(f) print(Dog.getNumberOfDogs()) print(d.getNumberOfDogs()) d.nname = "able" print(d) print(d.nname) print(dir(d)) print(dir(e)) print("test") d.print() Dog.print() ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: :: 2021-03-08WhiteboardCS212.txt :: d = {} d["spanish.txt"] is the dictionary of lines in the file spanish.txt! d["spanish.txt"]["1"] = "uno" d["english.txt"]["1"] = "one" d["roman.txt"]["1"] = "one i 000001 01" # vague outline for key in setofallthekeys : # notice the use of set print(key) for file in listoffiles : # how do you get a list of files? do you have it handy? print(d[file][key]) key value value 1 uno one eins one i 000001 01 10 dias ten - ten x 001010 12 11 once eleven - eleven xi 001011 13 12 doce twelve - twelve xii 001100 14 13 trece thirteen - thirteen xiii 001101 15 14 catorce fourteen - fourteen xiv 001110 16 15 quince fifteen - - 16 - sixteen - - 2 dos two zwei two ii 000010 02 20 - - - twenty xx 010100 24 3 tres three drei three iii 000011 03 4 quatro four vier four iv 000100 04 40 - - - forty xl 101000 50 5 cinco five funf five v 000101 05 50 - - - fifty l 110010 62 6 sies six sechs six vi 000110 06 63 - - - sixtythree lxiii 111111 77 7 seite seven sieben seven vii 000111 07 8 ocho eight - eight viii 001000 10 9 nueve nine - nine ix 001001 11 examples we tried: joincol.py spanish.txt 2 english.txt 1 german.txt 2 roman.txt 3 joincol.py english.txt 2 roman.txt 1 ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: :: 2021-03-12WhiteboardCS212.txt :: ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: :: s.py :: #!/usr/bin/env python3 """An example of a scatter plot in matplotlib for CS212""" from matplotlib import pyplot as plt import sys data = sys.stdin.readlines() # get the data data = [ d.split() for d in data] v = [ float(d[0]) for d in data] p = [ float(d[1]) for d in data] city = [ d[2] for d in data] # plot the data plt.scatter(v, p) plt.plot([0,10000],[0, 10000]) # you can do multiple plots on top of one another # label the plot plt.title("Crime in 100 Largest Cities in US") plt.xlabel("Violent Crime per 100,000") plt.ylabel("Property Crime per 100,000") # plot range # plt.axis("square") smallest = min(min(v), min(p)) largest = max(max(v), max(p)) plt.xlim(smallest, largest) plt.ylim(smallest, largest) # tick locations (label) ticks = list(range(0, 7001, 2000)) #plt.xticks([0, 7000], ["dog", "cat"]) # (locations, labels) plt.xticks(ticks, ticks) plt.yticks(ticks, ticks) # label the points for i in range(len(city)) : # you could put code in here to decide which cities to annotate plt.annotate(city[i], (v[i], p[i])) # note tuple and not indiviual x, y # show it plt.show() ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: :: z3.txt :: 740.25 5453.83 Mobile 1203.29 5415.82 Anchorage 259.47 2329.61 Chandler 85.51 1385.85 Gilbert 488.22 4530.37 Glendale 415.83 2171.99 Mesa 760.93 3670.71 Phoenix 157.24 2172.01 Scottsdale 801.77 5251.70 Tucson 354.56 2630.45 Anaheim 479.33 4068.43 Bakersfield 298.04 1432.27 ChulaVista 182.34 2150.46 Fremont 565.00 3841.40 Fresno 61.21 1316.48 Irvine 657.83 2672.48 LongBeach 761.31 2535.92 LosAngeles 1299.32 5982.84 Oakland 508.81 3058.32 Riverside 675.60 2936.62 Sacramento 1291.09 3867.73 SanBernardino 366.61 1842.97 SanDiego 715.00 6168.02 SanFrancisco 403.65 2440.70 SanJose 488.53 2090.27 SantaAna 162.70 1424.08 SantaClarita 1414.56 3627.34 Stockton 608.39 3003.66 Aurora 524.15 3216.78 ColoradoSprings 675.61 3667.06 Denver 948.74 4156.22 Washington 198.52 2213.55 Hialeah 631.32 3526.68 Jacksonville 720.94 4014.18 Miami 744.06 5454.57 Orlando 698.49 4312.66 StPetersburg 464.41 1743.68 Tampa 935.72 4776.43 Atlanta 462.66 3431.29 Savannah 246.37 2774.38 Honolulu 279.16 2444.64 Boise 1098.86 3263.80 Chicago 357.55 3179.61 FortWayne 1333.96 4411.87 Indianapolis 670.11 4413.26 DesMoines 1022.29 5535.64 Wichita 350.88 3782.13 Lexington 647.03 4122.23 LouisvilleMetro 1026.81 5594.03 BatonRouge 1121.41 4243.84 NewOrleans 2027.01 4928.11 Baltimore 669.20 2089.02 Boston 2056.67 4540.60 Detroit 1101.27 4641.37 Minneapolis 650.81 3565.42 StPaul 1724.31 4543.79 KansasCity 2082.29 6041.24 StLouis 647.32 3880.17 Omaha 185.11 1833.04 Henderson 618.90 2943.38 LasVegas 1014.69 2386.03 NorthLasVegas 673.56 3085.73 Reno 509.51 1806.98 JerseyCity 896.45 2395.01 Newark 1369.14 7365.84 Albuquerque 1019.25 3836.14 Buffalo 538.90 1448.59 NewYork 947.12 5049.88 Cincinnati 1556.76 4916.04 Cleveland 513.41 3944.94 Columbus 787.34 3752.51 OklahomaCity 1040.83 5455.61 Tulsa 515.70 5677.02 Portland 947.58 3063.48 Philadelphia 656.36 3114.42 Pittsburgh 2003.32 6297.83 Memphis 1138.17 3817.96 Nashville 516.89 3197.72 Arlington 414.84 3189.57 Austin 702.49 3565.31 CorpusChristi 774.64 3185.09 Dallas 378.85 1818.88 ElPaso 560.21 3215.32 FortWorth 316.62 3032.47 Garland 1095.23 4128.41 Houston 226.80 2539.43 Irving 321.86 2483.61 Laredo 149.79 1733.74 Plano 707.50 4844.84 SanAntonio 418.96 2272.21 Chesapeake 555.90 3748.93 Norfolk 137.56 1934.62 VirginiaBeach 632.69 5258.64 Seattle 626.54 7231.44 Spokane 374.44 2662.11 Madison 1597.36 3792.04 Milwaukee ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: :: 2021-03-22WhiteboardCS212.txt :: #!/usr/bin/env python3 import sys args = sys.argv[1:] # grab command line arguments print(sys.argv[0], " is executing") print("command line argument list: ", args) # stuff happens # option number 1: for file in listOfFiles : inputfile = open(file, "r") for line in inputfile : do stuff by line use split # option number 2: for file in listOfFiles : with open(file, "r") as inputfile : for line in inputfile : do stuff by line use split -------------------------------------------------------------- dod = {} dod["italian.txt"] = {} dod[file] = {} loop on combiningcolumnvalue : loop on files : dod["german.txt"]["one"] dod["italian.txt"]["one"] ... setOfComb = set of combinators (combining values are in the combining column) for index in setOfComb : loop on files : dod["german.txt"]["one"] dod["italian.txt"]["one"] ... ---------------------- dictfile[file].keys() # gives me the keys of the dictionary. list(dictfile[file].keys()) set(dictfile[italian].keys()) | set(dictfile[german].keys()) diction["dog"] -> "bark" diction.get("dog", "no value") -> "bark" or "no value" ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: :: 2021-03-24WhiteboardCS212.txt :: ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: :: q.py :: #!/usr/bin/env python3 """Use crime4col.txt for the data""" from matplotlib import pyplot as plt import math import sys plt.style.use("classic") # use basic colorful plots # expects lines with violentCrime propertyCrime City Population columns data = sys.stdin.readlines() # grab the columns of data data = [d.split() for d in data] # list comprehension city = [ d[0] for d in data ] v = [ float(d[1]) for d in data ] p = [ float(d[2]) for d in data ] pop = [ 100*(math.log10(float(d[3]))-5) for d in data ] plt.axes().set_aspect(2) # set before drawing plt.scatter(p, v, c=pop, s=pop, marker="s") plt.xlabel("Property Crime per 100k") plt.ylabel("Violent Crime per 100k") plt.title("Crime in 100 Largest Cities in US") plt.xlim(0, max(p)*1.15) plt.ylim(0, max(v)*1.05) for i in range(len(city)) : # this is written very C-like using an array if city[i] in ["PortlandOR", "SpokaneWA", "SeattleWA", "BoiseID"] : c = "red" else : c = "black" plt.annotate(city[i], (p[i], v[i]), color=c) # label each city plt.show() ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: :: qq.py :: #!/usr/bin/env python3 """ run as: qq.py < crimeLL.txt """ from matplotlib import pyplot as plt import math import sys plt.style.use("classic") # expects lines with violentCrime propertyCrime City Population columns city = [] v = [] p = [] pop = [] lat = [] long = [] for line in sys.stdin : data = line.split() cityName = data[0] population = 100*(math.log10(float(data[1]))-5) if data[2]=="-" : continue violentCrime = float(data[2])/10 if data[7]=="-" : continue propertyCrime = float(data[7])/10 if data[12]=="-" : continue latitude = float(data[12]) longitude = float(data[13]) # remove AK and HI if longitude < -125 : continue city.append(cityName) v.append(violentCrime) p.append(propertyCrime) pop.append(population) lat.append(latitude) long.append(longitude) plt.scatter(long, lat, c=v, s=pop, marker="s") plt.colorbar().set_label("Violence") # plot colorbar with label plt.xlabel("Long") plt.ylabel("Lat") plt.title("Violent Crime per 100k") for i in range(len(city)) : if city[i] in ["PortlandOR", "SpokaneWA", "SeattleWA", "BoiseID"] : c = "red" else : c = "black" plt.annotate(city[i], (long[i], lat[i]), color=c) plt.show() ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: :: qqsub.py :: #!/usr/bin/env python3 """ run as: qqsub.py < crimeLL.txt """ from matplotlib import pyplot as plt import math import sys plt.style.use("classic") (fig, axs) = plt.subplots(1, 2) # number of rows and cols defaults to num rows fig.suptitle("Crime") # expects lines with violentCrime propertyCrime City Population columns city = [] v = [] p = [] pop = [] lat = [] long = [] for line in sys.stdin : data = line.split() cityName = data[0] population = 100*(math.log10(float(data[1]))-5) if data[2]=="-" : continue violentCrime = float(data[2])/10 if data[7]=="-" : continue propertyCrime = float(data[7])/10 if data[12]=="-" : continue latitude = float(data[12]) longitude = float(data[13]) # remove AK and HI if longitude < -125 : continue city.append(cityName) v.append(violentCrime) p.append(propertyCrime) pop.append(population) lat.append(latitude) long.append(longitude) # plot 1 axs[0].set_xlabel("Long") axs[0].set_ylabel("Lat") axs[0].set_title("Violent Crime per 100k") axs[0].scatter(long, lat, c=v, s=pop, marker="s") # plot 2 axs[1].set_xlabel("Long") axs[1].set_ylabel("Lat") axs[1].set_title("Property Crime per 100k") axs[1].scatter(long, lat, c=p, s=pop, marker="s") # label everyone for i in range(len(city)) : axs[0].annotate(city[i], (long[i], lat[i])) axs[1].annotate(city[i], (long[i], lat[i])) plt.show() ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: :: signalErr.py :: #!/usr/bin/env python3 from matplotlib import pyplot as plt import math import sys plt.style.use("classic") data = sys.stdin.readlines() data = [d.split() for d in data] x = [ float(d[0]) for d in data ] y = [ float(d[1]) for d in data ] yerr = [ float(d[2]) for d in data ] plt.errorbar(x, y, yerr=yerr, marker="s", capsize=10, elinewidth=2) plt.xlabel("Bit position") plt.ylabel("Entropy") plt.title("Signal Detection by Entropy (over 100 runs)") plt.show() ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: :: 2021-03-31WhiteboardCS212.txt :: #!/usr/bin/env python3 """ doc """ import math import image # cImage size = 1000 win = image.ImageWin(size, size, "Image") # do stuff to image here pic = image.FileImage("horseLg.png") h = pic.getHeight() w = pic.getWidth() print(w, "x", h) pic.draw(win) targets = [] while True : try : pos = win.getMouse() targets.append(tuple(pic.get_pixel(pos[0], pos[1]))) except : break; print(targets) # set up the color limit maxcolor = math.sqrt(3)*255 limit = 0.30*maxcolor # paint with black and white pixels white = image.Pixel(255, 255, 255) black = image.Pixel(0, 0, 0) newpic = image.EmptyImage(w, h) for y in range(h) : for x in range(w) : p = pic.get_pixel(x, y) if math.hypot(p[0], p[1], p[2]) < limit : c = black else : c = white newpic.set_pixel(x, y, c) # draw the newly painted picture newpic.draw(win) # wait input("pause") ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: :: 2021-04-02WhiteboardCS212.txt :: ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: :: iocsv.py :: #!/usr/bin/env python3 import csv with open("jobsNZ.csv", "r") as f : reader = csv.reader(f) header = next(reader) # first read print(header) for row in reader : try : print(int(row[0]), row[1]) except ValueError : break ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: :: ioinput.py :: #!/usr/bin/env python3 """input a line with optional prompt removing newline""" # import sys x = input("what is your word?") print('"{0}"'.format(x)) ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: :: ioread.py :: #!/usr/bin/env python3 """input whole file as a single string""" import sys x = sys.stdin.read() print('"{0}"'.format(x)) ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: :: ioreadline.py :: #!/usr/bin/env python3 """input a line of input with newline""" import sys x = sys.stdin.readline() print('"{0}"'.format(x)) ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: :: ioreadlines.py :: #!/usr/bin/env python3 """input the whole file and make a list of lines""" import sys x = sys.stdin.readlines() print('"{0}"'.format(x)) ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: :: ioreadopen.py :: #!/usr/bin/env python3 f = open("z.txt", "r") for x in f : print('"{0}"'.format(x)) f.close() # the polite thing to do ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: :: ioreadwith.py :: #!/usr/bin/env python3 with open("z.txt", "r") as f : for x in f : print('"{0}"'.format(x)) # f.close() # the polite thing to do ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: :: iosysstdin.py :: #!/usr/bin/env python3 """ looping printing each line + nl""" import sys for x in sys.stdin : print('"{0}"'.format(x)) ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: :: italian.csv :: 1,uno,one 2,due,two 3,tre,three 4,quattro,four 5,chique,five 6,sei,six 7,sette,seven ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: :: z.txt :: chambermaid vengeance cabins awhile druggist overthrown avg pray grimed inbreed ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: :: 2021-04-05WhiteboardCS212.txt :: ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: :: iocsv.py :: #!/usr/bin/env python3 import csv with open("jobsNZ.csv", "r") as f : reader = csv.reader(f) header = next(reader) # first read print(header) for row in reader : try : print(int(row[0]), row[1]) except ValueError : print("bad value: ", row) ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: :: iocsvdict.py :: #!/usr/bin/env python3 import csv with open("jobsNZ.csv", "r") as f : reader = csv.DictReader(f) for row in reader : try : print(int(row["Code"]), row["Occupation"], row["Number Employed"]) except ValueError : print("bad value: ", row) ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: :: rexp.py :: #!/usr/bin/python3 import re regexp = re.compile("Software") with open("jobsNZ.csv", "r") as f : for line in f : if regexp.search(line) : print(line.strip()) ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: :: 2021-04-14WhiteboardCS212.txt :: MobileMeerkat3: python3 Python 3.8.5 (default, Sep 4 2020, 02:22:02) [Clang 10.0.0 ] :: Anaconda, Inc. on darwin Type "help", "copyright", "credits" or "license" for more information. >>> import numpy as np >>> x = [3, 1, 4, 1, 5, 9] >>> x [3, 1, 4, 1, 5, 9] >>> a = np.array(x) >>> type(a) >>> np.array([1, 2, 3]) array([1, 2, 3]) >>> print(np.array([1, 2, 3])) [1 2 3] >>> 45 45 >>> print(45) 45 >>> a array([3, 1, 4, 1, 5, 9]) >>> print(a) [3 1 4 1 5 9] >>> a.__repr__() 'array([3, 1, 4, 1, 5, 9])' >>> a.__str__() '[3 1 4 1 5 9]' >>> a array([3, 1, 4, 1, 5, 9]) >>> print(a) [3 1 4 1 5 9] >>> a2 = np.array([[4, 9, 2], [3, 5, 7], [8, 1, 6]]) >>> a2 array([[4, 9, 2], [3, 5, 7], [8, 1, 6]]) >>> print(a2) [[4 9 2] [3 5 7] [8 1 6]] >>> np.arange(5) array([0, 1, 2, 3, 4]) >>> np.arange(5, 10) array([5, 6, 7, 8, 9]) >>> np.arange(5, 10, 2) array([5, 7, 9]) >>> np.arange(5, 10, 0.4) array([5. , 5.4, 5.8, 6.2, 6.6, 7. , 7.4, 7.8, 8.2, 8.6, 9. , 9.4, 9.8]) >>> np.linspace(0, 5, 5) array([0. , 1.25, 2.5 , 3.75, 5. ]) >>> np.ones(5) array([1., 1., 1., 1., 1.]) >>> print(np.ones(5)) [1. 1. 1. 1. 1.] >>> print(np.zeros(5)) [0. 0. 0. 0. 0.] >>> print(np.zeros((5, 5))) [[0. 0. 0. 0. 0.] [0. 0. 0. 0. 0.] [0. 0. 0. 0. 0.] [0. 0. 0. 0. 0.] [0. 0. 0. 0. 0.]] >>> print(np.ones((5, 5))) [[1. 1. 1. 1. 1.] [1. 1. 1. 1. 1.] [1. 1. 1. 1. 1.] [1. 1. 1. 1. 1.] [1. 1. 1. 1. 1.]] >>> print(np.eye((5, 5))) # does NOT take a tuple! Traceback (most recent call last): File "", line 1, in File "/Users/meerkat/opt/anaconda3/lib/python3.8/site-packages/numpy/lib/twodim_base.py", line 199, in eye m = zeros((N, M), dtype=dtype, order=order) TypeError: 'tuple' object cannot be interpreted as an integer >>> print(np.eye(5, 5)) [[1. 0. 0. 0. 0.] [0. 1. 0. 0. 0.] [0. 0. 1. 0. 0.] [0. 0. 0. 1. 0.] [0. 0. 0. 0. 1.]] >>> print(np.eye(4, 5)) [[1. 0. 0. 0. 0.] [0. 1. 0. 0. 0.] [0. 0. 1. 0. 0.] [0. 0. 0. 1. 0.]] >>> a2 array([[4, 9, 2], [3, 5, 7], [8, 1, 6]]) >>> a2[1] array([3, 5, 7]) >>> a2[1][2] 7 >>> a2[1, 2] 7 >>> a2[1, 2] = 78 >>> a2 array([[ 4, 9, 2], [ 3, 5, 78], [ 8, 1, 6]]) ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: :: 2021-04-16WhiteboardCS212.txt :: MobileMeerkat3: python3 Python 3.8.5 (default, Sep 4 2020, 02:22:02) [Clang 10.0.0 ] :: Anaconda, Inc. on darwin Type "help", "copyright", "credits" or "license" for more information. >>> import numpy as np >>> x = [3, 1, 4, 1, 5, 9] >>> x [3, 1, 4, 1, 5, 9] >>> x = np.array([3, 1, 4, 1, 5, 9]) >>> x array([3, 1, 4, 1, 5, 9]) >>> print(x) [3 1 4 1 5 9] >>> a2 = np.array([[4, 9, 2], [3, 5, 7], [8, 1, 6]]) >>> >>> print(a2) [[4 9 2] [3 5 7] [8 1 6]] >>> np.arange(0, 10, .6) array([0. , 0.6, 1.2, 1.8, 2.4, 3. , 3.6, 4.2, 4.8, 5.4, 6. , 6.6, 7.2, 7.8, 8.4, 9. , 9.6]) >>> np.linspace(0, 10, 5) array([ 0. , 2.5, 5. , 7.5, 10. ]) >>> np.zeros((4, 4)) array([[0., 0., 0., 0.], [0., 0., 0., 0.], [0., 0., 0., 0.], [0., 0., 0., 0.]]) >>> np.zeros((1, 2, 3)) # 3D array array([[[0., 0., 0.], [0., 0., 0.]]]) >>> x = np.zeros((4, 4)) # 2D array >>> x[0, 3] 0.0 >>> x = np.eye((4, 4)) # does not use a tuple >>> x = np.eye(4, 4) #OK >>> x array([[1., 0., 0., 0.], [0., 1., 0., 0.], [0., 0., 1., 0.], [0., 0., 0., 1.]]) >>> x = np.arange(0, 16) >>> len(x) 16 >>> np.reshape(x, (4, 4)) array([[ 0, 1, 2, 3], [ 4, 5, 6, 7], [ 8, 9, 10, 11], [12, 13, 14, 15]]) >>> x44 = np.reshape(x, (4, 4)) >>> x array([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]) >>> x44 array([[ 0, 1, 2, 3], [ 4, 5, 6, 7], [ 8, 9, 10, 11], [12, 13, 14, 15]]) >>> np.shape(x44) (4, 4) >>> np.shape(x) (16,) >>> len((16,)) 1 >>> np.reshape(x44, (2, 8)) array([[ 0, 1, 2, 3, 4, 5, 6, 7], [ 8, 9, 10, 11, 12, 13, 14, 15]]) >>> x44 array([[ 0, 1, 2, 3], [ 4, 5, 6, 7], [ 8, 9, 10, 11], [12, 13, 14, 15]]) >>> np.reshape(x44, (2, 2, 2, 2)) array([[[[ 0, 1], [ 2, 3]], [[ 4, 5], [ 6, 7]]], [[[ 8, 9], [10, 11]], [[12, 13], [14, 15]]]]) >>> x44 array([[ 0, 1, 2, 3], [ 4, 5, 6, 7], [ 8, 9, 10, 11], [12, 13, 14, 15]]) >>> x44[0] array([0, 1, 2, 3]) >>> x44[0][3] 3 >>> x44[0] = x44[2] # does NOT make a copy just points to the same array >>> x44 array([[ 8, 9, 10, 11], [ 4, 5, 6, 7], [ 8, 9, 10, 11], [12, 13, 14, 15]]) >>> z = x44 >>> z array([[ 8, 9, 10, 11], [ 4, 5, 6, 7], [ 8, 9, 10, 11], [12, 13, 14, 15]]) >>> x44[0] = x44[3] >>> x44 array([[12, 13, 14, 15], [ 4, 5, 6, 7], [ 8, 9, 10, 11], [12, 13, 14, 15]]) >>> z array([[12, 13, 14, 15], [ 4, 5, 6, 7], [ 8, 9, 10, 11], [12, 13, 14, 15]]) >>> x44.copy() # make a "deep" copy so really different array array([[12, 13, 14, 15], [ 4, 5, 6, 7], [ 8, 9, 10, 11], [12, 13, 14, 15]]) >>> z = x44.copy() >>> x44[3] = x44[1] >>> x44 array([[12, 13, 14, 15], [ 4, 5, 6, 7], [ 8, 9, 10, 11], [ 4, 5, 6, 7]]) >>> z array([[12, 13, 14, 15], [ 4, 5, 6, 7], [ 8, 9, 10, 11], [12, 13, 14, 15]]) >>> y = "dog" >>> z = "dog" >>> x44 array([[12, 13, 14, 15], [ 4, 5, 6, 7], [ 8, 9, 10, 11], [ 4, 5, 6, 7]]) >>> np.shape(x44) (4, 4) >>> np.size(x44) 16 >>> np.ndim(x44) 2 >>> np.ndim(x) 1 >>> x array([12, 13, 14, 15, 4, 5, 6, 7, 8, 9, 10, 11, 4, 5, 6, 7]) >>> x = np.arange(0, 16) >>> x array([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]) >>> np.reshape(x, (4, 4)) array([[ 0, 1, 2, 3], [ 4, 5, 6, 7], [ 8, 9, 10, 11], [12, 13, 14, 15]]) >>> x44 = np.reshape(x, (4, 4)) >>> np.sum(x44) 120 >>> np.sum(x) 120 >>> np.sum(x44, axis=0) # axis is an important parameter in much numpy array([24, 28, 32, 36]) >>> np.sum(x44, axis=1) array([ 6, 22, 38, 54]) >>> np.max(x44, axis=1) array([ 3, 7, 11, 15]) >>> np.min(x44, axis=1) array([ 0, 4, 8, 12]) >>> x44 array([[ 0, 1, 2, 3], [ 4, 5, 6, 7], [ 8, 9, 10, 11], [12, 13, 14, 15]]) >>> x44 + np.ones((4, 4)) array([[ 1., 2., 3., 4.], [ 5., 6., 7., 8.], [ 9., 10., 11., 12.], [13., 14., 15., 16.]]) >>> x44 * x44 array([[ 0, 1, 4, 9], [ 16, 25, 36, 49], [ 64, 81, 100, 121], [144, 169, 196, 225]]) >>> np.dot(x44, x44) array([[ 56, 62, 68, 74], [152, 174, 196, 218], [248, 286, 324, 362], [344, 398, 452, 506]]) >>> np.dot(x44, np.ones((4, 4))) array([[ 6., 6., 6., 6.], [22., 22., 22., 22.], [38., 38., 38., 38.], [54., 54., 54., 54.]]) >>> np.dot(x44, np.eye(4, 4)) array([[ 0., 1., 2., 3.], [ 4., 5., 6., 7.], [ 8., 9., 10., 11.], [12., 13., 14., 15.]]) >>> np.dot(x44, np.eye(4, 4)) == x44 array([[ True, True, True, True], [ True, True, True, True], [ True, True, True, True], [ True, True, True, True]]) >>> pow(x44, 2) array([[ 0, 1, 4, 9], [ 16, 25, 36, 49], [ 64, 81, 100, 121], [144, 169, 196, 225]]) >>> np.pow(x44, 2) # error there is no pow in numpy >>> pow(2, x44) array([[ 1, 2, 4, 8], [ 16, 32, 64, 128], [ 256, 512, 1024, 2048], [ 4096, 8192, 16384, 32768]]) >>> np.transpose(x44) array([[ 0, 4, 8, 12], [ 1, 5, 9, 13], [ 2, 6, 10, 14], [ 3, 7, 11, 15]]) >>> v = np.arange(0, 4) >>> v array([0, 1, 2, 3]) >>> np.dot(x44, v) array([14, 38, 62, 86]) >>> np.dot(v, x44) array([56, 62, 68, 74]) >>> np.array([[1, 2, 3, 4]]) array([[1, 2, 3, 4]]) >>> r = np.array([[1, 2, 3, 4]]) >>> v = np.array([1, 2, 3, 4]) >>> np.array_equal(v, r) False >>> c = np.array([[1], [2], [3], [4]]) >>> np.array_equal(r, c) False >>> np.array_equal(v, c) False # np.allclose can be used to ask if two same shaped arrays are with given tolerances ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: :: 2021-04-26WhiteboardCS212.txt :: ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: :: g.py :: #!/usr/bin/env python3 class Digraph : """A genreal purpose digraph class""" def __init__(self, name, loopsAllowed=True) : self.loopsAllowed = loopsAllowed self.name = name # the name of my graph self.verts = {} # dictionary of vertices def __str__(self) : s = f"Digraph: {self.name}\n" for v in self.verts.keys() : s += f" {v} --> {self.verts[v]}\n" return s def addV(self, name) : """Add a vertex""" if name in self.verts : print(f"ERROR(addV): name '{name}' is already a vertex.") else : self.verts[name] = [] def addE(self, fname, tname) : """Add a edge""" if fname not in self.verts : print(f"ERROR(addE): name '{fname}' is not a vertex.") elif tname not in self.verts : print(f"ERROR(addE): name '{tname}' is not a vertex.") elif tname in self.verts[fname] : print(f"ERROR(addE): there is already an edge from '{fname}' to '{tname}'.") elif tname==fname and not self.loopsAllowed : print(f"ERROR(addE): can't loop back from '{fname}' to '{tname}'.") else : self.verts[fname].append(tname) def numV(self) : """Number of vertices""" return len(self.verts) def numE(self) : """Number of edges""" return sum(map(len, self.verts.values())) def test() : # g = Digraph("A great test graph", loopsAllowed=False) g = Digraph("A great test graph") g.addV("Chicago") g.addV("Portland") g.addV("Seattle") g.addV("Spokane") g.addE("Spokane", "Seattle") g.addE("Spokane", "Portland") g.addE("Portland", "Portland") print("DO SOME ERROR STUFF") g.addE("Spokane", "The Moon") g.addV("Spokane") g.addE("Spokane", "Seattle") print("PRINT GRAPH") print(g.numV()) print(g.numE()) print(g) # run tests if stand alone otherwise import it. if __name__ == "__main__" : test()