Intro to
Programming
(with Python)

Fall 2016
course
navigation

Oct 27

discuss & demo midterm projects

Your work is in the protected midterms folder.

assignment

Your next assignment is posted, and due Tuesday, on chapter 10.

defining objects/classes continued ...

Questions about anything we've done?

__str__

Look at the __str__ method :
class Person(object): def __init__(self, name=''): self.name = name def __str__(self): return "Person('{}')".format(self.name)
or even just
class Foo: def __str__(self): return '<Foo thingimabob>'
Then try creating and printing one of 'em.

more tricks with class

An example of inheritance, a class variable, __str__, and a container class :

practice

In class coding project : create fraction.py which implements a Fraction class, which displays as i/j and implements some of the standard math operations.
It should do something like this :
>>> from fraction import Fraction >>> Fraction(1,2) + Fraction(1/3) 4/6
(If we really want to get fancy we could have it have it convert that to 2/3 on its own ...)

aside

functional programming example :FizzBuzz (see http://wiki.c2.com/?FizzBuzzTest )
This takes a bit of printing and/or explaining ...
""" functional fizzbuzz from ghost.io & hackernews https://news.ycombinator.com/item?id=12797886 http://klipse.ghost.io/the-most-elegant-implementation-of-fizzbuzz/ """ from itertools import cycle, imap, count, islice from operator import add def fizzbuzz(n): fizzes = cycle(["", "", "Fizz"]) # . . Fizz . . Fizz . . Fizz buzzes = cycle(["", "", "", "", "Buzz"]) # . . . . Buzz . . . . words = imap(add, fizzes, buzzes) # . . Fizz . Buzz Fizz . . Fizz numbers = imap(str, count(1)) # 1 2 3 4 5 6 7 8 9 _fizzbuzz = imap(max, words, numbers) # 1 2 Fizz 4 Buzz Fizz 7 8 Fizz return islice(_fizzbuzz, n) # n terms from lazy infiite iterator for i in fizzbuzz(100): print i
procedural : # http://codereview.stackexchange.com/questions/9751/ultra-beginner-python-fizzbuzz-am-i-missing-something for num in xrange(1,101): msg = '' if num % 3 == 0: msg += 'Fizz' if num % 5 == 0: msg += 'Buzz' print msg or num
http://cs.marlboro.edu/ courses/ fall2016/python/ notes/ Oct_27
last modified Thursday October 27 2016 11:10 am EDT