CSC111 Programs Created in Class 2018

From dftwiki3
Revision as of 10:18, 2 April 2018 by Thiebaut (talk | contribs) (playDice.py)
Jump to: navigation, search

D. Thiebaut (talk) 12:30, 31 January 2018 (EST)


1/30/18

# wedWeek1.py
# D. Thiebaut
# Demo program week 1


# variables
age = 20
year = 2018

# compute year born
print( year - age )


# example of for loop
for name in [ "smith", 23, 3.14159, "hello" ]:
    print( name )

"""
challenge: print the following lines
***
Mae
*****
Alice
*******
Felicia
"""

for name in [ "Mae", "Alice", "Felicia" ]:
    print( '*' * len( name ) )
    print( name )


"""
new challenge: print the following lines
*
Mae
********
Alice
****
Felicia
**
"""

for name in [ "*", "Mae", "********", "Alice", "****", "Felicia", "**" ]:
    print( name )

02/05/18


Table of Fahrenheit to Celsius conversion

# 020518.py
# D. Thiebaut
#
# print table of temperatures
# start at 100 F down to -30 F
# in steps of 10
# using the formula: Celsius = (Farhenheit - 32 ) * 5 / 9

# print the header 
print( "Fahrenheit --> Celsius" )

# display the table of temperatures
# ranging from 100 down to -30F.
for fTemp in range( 100, -31, -10 ):
    cTemp = ( fTemp - 32 ) * 5 / 9
    print( fTemp, '-->', cTemp )

Problem: get user name and grade and display user information and grade as a bar graph.

# barGraph.py
# D. Thiebaut
# this program prompts the user for her information
# and grade and displays a bar-graph.
#
#First name?  Dominique
#Last name?   Thiebaut
#Id?          990123456
#Final grade? 90
#
#+———————————————————————————————————-———————————-+
#|Dominique Thiebaut                    990123456 |
#+———————————————————————————————————-———————————-+
#      00...10...20...30...40...50...60...70...80...90...100
#grade: #############################################
#class: ########################################
#
#

# input section
fName = input( "First name?  " )
lName = input( "Last name?   " )
Id    = input( "Id?          " )
final = input( "Final grade? " )

# output section
print( fName, lName, Id )
bar = "+———————————————————————————————————-———————————-+"
barLen = len( bar )
print( "barLen =", barLen )
nameIdLen = len( fName )+1+len( lName ) + len( Id )+1
print( "nameIdLen =", nameIdLen )

print( bar )
print( "|", fName, lName, ' '*(barLen-nameIdLen), Id, '|' )
print( bar )

2/7/18


We didn't have time to cover this problem, because of the snow storm... But it simply displays an 8 by 8 chessboard using hash tags.

# chessBoard.py
# D. Thiebaut
# displays an 8x8 chessboard, as shown below.
"""
###   ###   ###   ###   
###   ###   ###   ###   
###   ###   ###   ###   
   ###   ###   ###   ###
   ###   ###   ###   ###
   ###   ###   ###   ###
###   ###   ###   ###   
###   ###   ###   ###   
###   ###   ###   ###   
   ###   ###   ###   ###
   ###   ###   ###   ###
   ###   ###   ###   ###
###   ###   ###   ###   
###   ###   ###   ###   
###   ###   ###   ###   
   ###   ###   ###   ###
   ###   ###   ###   ###
   ###   ###   ###   ###
###   ###   ###   ###   
###   ###   ###   ###   
###   ###   ###   ###   
   ###   ###   ###   ###
   ###   ###   ###   ###
   ###   ###   ###   ###
"""
numRows = eval( input( "Number of rows?    " ) )
numCols = eval( input( "Number of columns? " ) )
white="   "
black="###"

bar1 = ""
bar2 = ""
for i in range( numCols//2 ):
    bar1 = bar1 + white + black
    bar2 = bar2 + black + white

for i in range( numRows//2 ):
    # display 2 lines of squares
    # alternating the colors
    # 5    ###   ###   ###   ###
    #     ###   ###   ###   ###
    #     ###   ###   ###   ###
    #  ###   ###   ###   ###   
    #  ###   ###   ###   ###   
    #  ###   ###   ###   ###   
    for n in range( 3 ):
        print( bar1 )
    for n in range( 3 ):
        print( bar2 )


2/9/18


# barGraph.py
# D. Thiebaut
# this program prompts the user for her information
# and grade and displays a bar-graph.
#
#First name?  Dominique
#Last name?   Thiebaut
#Id?          990123456
#Final grade? 90
#
#+———————————————————————————————————-———————————-+
#|Dominique Thiebaut                    990123456 |
#+———————————————————————————————————-———————————-+
#      00...10...20...30...40...50...60...70...80...90...100
#grade: #############################################
#class: ########################################
#
#

# box geometry
bar = "+———————————————————————————————————-———————————-+"
barLen = len( bar )

# input section
fName      = input( "First name? " )
fNameLen   = len( fName )
lName      = input( "Last name?  " )
lNameLen   = len( lName )
Id         = input( "Id?         " )
IdLen      = len( Id )
numSpaces  = barLen -3 -(fNameLen+1+lNameLen+IdLen)
grade      = eval( input( "Final grade? " ) )
classGrade = 80

# output section
print( bar )
print( '|' + fName, ' ', lName, ' '*(numSpaces), Id, ' |', sep='' )
print( bar )

# print the scale
print( "      00...10...20...30...40...50...60...70...80...90...100" )

# print the student grade as a bar
numHashTags = grade // 2
print( "grade:", '#' * numHashTags )

#print the class grade as a bar
numHashTags = classGrade // 2
print( "class:", '#' * numHashTags )


2/12/18


# teller.py
# D. Thiebaut
# simulates teller machine program
# prompts user, displays number of bills

# input amount to withdraw (use eval)
amount = eval( input( "Amount to withdraw? " ) )
amount = abs( amount )
print( "Amount:", amount )


# compute number of bills, 20, 10, 5, 1
no20s  = amount // 20
amount = amount % 20  # leftover after giving out all the 20s 

no10s  = amount // 10 
amount = amount % 10 # leftover after giving out all the 10s 

no5s   = amount // 5
amount = amount % 5 # leftover after giving out all the 5s 

no1s   = amount


# display number of bills
print( no20s, "$20-bill(s)" )
print( no10s, "$10-bill(s)" )
print( no5s, "$5-bill(s)" )
print( no1s, "$1-bill(s)" )


2/14/18


# generate a table of the powers of 2
"""
    0    1
    1    2
    2    4
    3    8
    4   16
    5   32
    6   64
    7  128
    8  256
    9  512
1234567890123
"""
for i in range( 10 ):
    print( "{0:5}{1:5}".format( i, 2**i ) )


# display the following table:
# 1: len(Doc    )= 3
# 2: len(Grumpy )= 6
# 3: len(Happy  )= 5
# 4: len(Sleepy )= 6
# 5: len(Dopey  )= 5
# 6: len(Bashful)= 7
# 7: len(Sneezy )= 6

count = 1
for name in ["Doc", "Grumpy", "Happy", 
                    "Sleepy", "Dopey", "Bashful",
                    "Sneezy" ]:
    print( "{0:1}: len({1:<7})= {2:1}"
            .format( count, name, len(name) ) )
    count = count + 1


2/16/18


# accumulate.py
# D. Thiebaut
# solution programs for 2/16/18

# --------------------------------------
# sum of all the numbers from 1 to 100
total = 0
#print( "initial total:", total )
for i in range( 0, 100+1, 5):
    #print( i, total )
    total = total + i
    #print( "after sum:", i, total )
    #print()

print( total )

# --------------------------------------
# average of [100, 95,100, 90, 60, 85]
total = 0
count = 0
for i in [100, 95,100, 90, 60, 85]:
    total = total + i
    print( "i =", i )
    count = count + 1
    print( "count = ", count )
    
print( "total = ", total, "count = ", count )
print( "average = ", total/count )


# --------------------------------------
a = "#"
b = "+"
final = ""
# from numbers to string
print( "before loop: a=", a, "b=", b )
for i in   [1,2,1,1,3,4]:
    #print( i * a, end="", sep="" )
    print( "i=", i, "a=", a, "b=", b )
    final = final + i*a
    print( "final =", final )
    a, b = b, a

print( "final string = ", final )


2/19/18


Different ways to print all the strings in a list.

def main():
    farm = ["pig", "dog", "horse", "hen" ]

    #--------------------------------------------------
    print( "method 1" )
    print( """pig
dog
horse
hen""" )

    #--------------------------------------------------
    print( "method 2" )
    print( farm )
    
    #--------------------------------------------------
    print( "method 3" )
    print( "pig\ndog\nhorse\nhen" )
    
    #--------------------------------------------------
    print( "method 4" )
    print( list( farm ) )

    #--------------------------------------------------
    print( "method 5" )
    print( farm[0], farm[1], farm[2], farm[3] )
    
    #--------------------------------------------------
    print( "method 6" )
    print( farm[0], farm[1], farm[2], farm[3], sep="\n" )
    
    #--------------------------------------------------
    print( "method 7" )
    for n in [0,1,2,3]:
       print( farm[n] )

    #--------------------------------------------------
    print( "method 8" )
    for animal in farm:
            print( animal )

    #--------------------------------------------------
    print( "method 9" )
    for animal in farm:
        for c in range( len( animal ) ):
            print( animal[c], sep="", end="")
        print(" " )
        
    #--------------------------------------------------
    print( "method 10" )
    for i in range( len( farm ) ):
        print( farm[i] )

    #--------------------------------------------------
    print( "method 11" )
    for i in range( -1, -len(farm), -1 ):
            print( farm[ i ] )

    #--------------------------------------------------
    print( "method 12" )
    for i in range( -1, -len(farm)-1, -1 ):
            print( farm[ i ] )

    #--------------------------------------------------
    print( "method 13" )
    for i in range( -len(farm), 0, 1 ):
            print(farm[i] )

main()


02/21/18


>>> name = "H:/Documents/solutionsHw4.doc"

>>> name
'H:/Documents/solutionsHw4.doc'
>>> drive = name[0:2]
>>> drive
'H:'
>>> name
'H:/Documents/solutionsHw4.doc'
>>> ext = name[-3: ]
>>> ext
'doc'
>>> newName = name[0:-3]
>>> newName
'H:/Documents/solutionsHw4.'
>>> newName = name[0:-3] + "txt"
>>> newName
'H:/Documents/solutionsHw4.txt'
>>> fname = "Alex"
>>> lname = "Booth"
>>> account = fname[0:1] + lname
>>> account
'ABooth'
>>> account = fname[0] + lname
>>> account
'ABooth'


>>> date = "02212018"
>>> wanted = "21 Feb 2018"
>>> date
'02212018'
>>> wanted
'21 Feb 2018'
>>> months = [ "Jan", "Feb", "Mar", "Apr", "May", "Jun"
	   ,"Jul", "Aug", "Sep", "Oct", "Nov", "Dec" ]
>>> months
['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
>>> months[1]
'Feb'
>>> months[2]
'Mar'
>>> months = ["Dummy", 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
>>> months[2]
'Feb'
>>> day = date[2:4]
>>> day
'21'
>>> month = date[0:2]
>>> month
'02'
>>> int( month )
2
>>> months[ int( month ) ]
'Feb'
>>> date
'02212018'
>>> year = date[4: ]
>>> year
'2018'
>>> print( day, months[ int( month ) ], year )
21 Feb 2018
>>> date
'02212018'
>>> day
'21'
>>> month
'02'
>>> year
'2018'
>>> months
['Dummy', 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
>>> months[ int( month ) ]
'Feb'


>>> fname = "Maria"
>>> lname = "Luce"
>>> name = fname + lname
>>> name
'MariaLuce'
>>> for i in range( len( name ) ):
	print( i )

	
0
1
2
3
4
5
6
7
8
>>> for i in range( len( name ) ):
	print( i, name[0:i] )

	
0 
1 M
2 Ma
3 Mar
4 Mari
5 Maria
6 MariaL
7 MariaLu
8 MariaLuc

>>> for i in range( len(name ) ):
	print( i, name[0:i+1] )

	
0 M
1 Ma
2 Mar
3 Mari
4 Maria
5 MariaL
6 MariaLu
7 MariaLuc
8 MariaLuce
>>> for i in range( len( name ) ):
	print( name[0:i+1] )

	
M
Ma
Mar
Mari
Maria
MariaL
MariaLu
MariaLuc
MariaLuce


>>> farm = [ "pig", "dog", "cat" ]
>>> farm
['pig', 'dog', 'cat']
>>> farm[0]
'pig'
>>> farm[1]
'dog'
>>> farm[-1]
'cat'
>>> 
>>> 
>>> farm[ 0 ] = "horse"
>>> farm
['horse', 'dog', 'cat']
>>> farm[2] = "mouse"
>>> farm
['horse', 'dog', 'mouse']
>>> farm[-1] = "cat"
>>> farm
['horse', 'dog', 'cat']
>>> name = "Smith College"
>>> 
>>> 
>>> 
>>> 
>>> name[0]
'S'
>>> name[-1]
'e'
>>> name[2]
'i'
>>> name[0] = 'Z'
Traceback (most recent call last):
  File "<pyshell#94>", line 1, in <module>
    name[0] = 'Z'
TypeError: 'str' object does not support item assignment   <--- strings are immutable!
>>> farm2 = ( "cat", "dog", "mouse" )
>>> farm2[1]
'dog'
>>> farm2[1] = "horse"
Traceback (most recent call last):
  File "<pyshell#97>", line 1, in <module>
    farm2[1] = "horse"
TypeError: 'tuple' object does not support item assignment
>>> animal = "horse"
>>> animal[0] = 'H'
Traceback (most recent call last):
  File "<pyshell#99>", line 1, in <module>
    animal[0] = 'H'
TypeError: 'str' object does not support item assignment
>>> animal = 'H' + animal[1: ]
>>> animal
'Horse'



>>> greeting = "hello there"
>>> greeting.upper()
'HELLO THERE'
>>> greeting
'hello there'
>>> greeting = greeting.upper()
>>> greeting
'HELLO THERE'
>>> lname = "Max"
>>> fname = "Joe"
>>> fname[0] + lname
'JMax'
>>> account = fname[0] + lname
>>> account
'JMax'
>>> account = account.lower()
>>> account
'jmax'
>>> title = "CSC111 Intro to CS"
>>> title.center( 60 )
'                     CSC111 Intro to CS                     '
>>> title
'CSC111 Intro to CS'
>>> print( title.center( 60 ) )
                     CSC111 Intro to CS                     
>>> name = "alex booth"
>>> name.capitalize()
'Alex booth'
>>> name
'alex booth'
>>> name.title()
'Alex Booth'
>>> name = "MICKEY MOUSE"
>>> name.capitalize()
'Mickey mouse'
>>> name.title()
'Mickey Mouse'
>>> name
'MICKEY MOUSE'
>>> name = name.title()
>>> name
'Mickey Mouse'
>>> name.find( 'z' )
-1
>>> name.find( 'o' )
8
>>> name.find( 'M' )
0
>>> name.find( 'c' )
2
>>> name.find( "ou" )
8
>>> name
'Mickey Mouse'
>>> name.replace( "Mickey", "Minnie" )
'Minnie Mouse'
>>> name
'Mickey Mouse'
>>> name.replace( "Mouse", "Cat" )
'Mickey Cat'
>>> name
'Mickey Mouse'
>>> name.replace( 'M', 'Z' )
'Zickey Zouse'
>>> name
'Mickey Mouse'
>>>


2/23/18


# examples
# D. Thiebaut

line = "The quick red fox jumped over the lazy brown sleeping dog"
line.split( " " )   # that's a space



poem = """Chocolate
Chocolate is the first luxury.
It has so many things wrapped up in it:
Deliciousness in the moment,
childhood memories,
and that grin-inducing
feeling of getting a reward for being good.
--Mariska Hargitay"""

Working with Text Files


Here's the text to store in the text file called chocolate.txt. You can use Notepad or TextEdit to do that. Make sure you use ".txt" as the extension, and select "plain text" or "plain ASCII" as the format.

Strength is the capacity to break

a Hershey bar into four pieces

with your bare hands - and then

eat just one of the pieces.

-Judith Viorst


And here's the program that reads this file

# readChocolateFile.py
# D. Thiebaut
# Opens a text file and displays it contents.
# Note: you need to have a file called chocolate.txt
# in the same directory/folder where you have saved
# this program!!!
@

def main():
    # open file
    file = open( "chocolate.txt", "r" )

    # read each line from file and display it
    for line in file:
        print( line )

    # close the file
    file.close()

main()

2/26/18


# readChocolateFile.py
# D. Thiebaut
# Opens a text file and displays it contents.
# Note: you need to have a file called chocolate.txt
# in the same directory/folder where you have saved
# this program!!!


def main():
    # open file
    file = open( "chocolate.txt", "r" )

    # read each line from file and display it
    for line in file:
        print( line.strip() )

    # close the file
    file.close()

main()

# ----------------------------------------------------------------------


def singHappyBirthday( minion ):
    print( "Happy birthday to you" )
    print( "Happy birthday to you" )
    print( "Happy birthday, dear", minion )
    print( "Happy birthday to you" )
    print( )
    
def main():
    for minion in [ "Dave", "Stuart", "Jerry", "Jorge" ]:
        singHappyBirthday( minion )

main()

# ----------------------------------------------------------------------

# DaveEats.py
# D. Thiebaut


def DaveEats( fruit ):
    print( "Dave opens their mouth" )
    print( "and eats the", fruit )
    print()



def main():
    for fruit in [ "banana", "apple", "orange" ]:
        DaveEats( fruit )
        
    
main()

# ----------------------------------------------------------------------

# printBarSayHello.py
# D. Thiebaut


def printBar():
    print( 60 * '-' )


def sayHello():
    print( )
    print( "Hello, and welcome!" )
    print( )

def main():
    printBar()
    printBar()

main()
 

# ----------------------------------------------------------------------

3/2/2018


functionBootCamp2


# functionBootCamp2.py
# D. Thiebaut

def cutDNA( DNA, marker ):
    DNA = DNA.upper()
    marker = marker.upper()
      
    index = DNA.find( marker )
    index2 = index + len( marker )
    leftOver = DNA[ index2: ]
    return leftOver

def main():
    dna = "ACGTTTA"
    marker = "G"

    print( cutDNA( dna, marker ) )

    print( cutDNA( "AAAAATTTT", "at" ) )

main()


bootCamp3.py



Program developed in Class


The assignment is to write a program that gets lines from a text file, representing a memo, and words from another text file, representing words to censure out of the memo. The program then takes both list of strings and blocks out all the bad words from the memo.

def block( bad, line ):
    """ takes a line and a bad word and replaces
    the bad word with xs"""
    xbad = "x" * len( bad )
    line = line.replace( bad, xbad )
    return line

def getMemo():
    memo = [ "Send 10 tons of burgers to White House",
             "before midnight", "That's a lot of burgers!" ]
    return memo

def getBad():
    bad = [ "burger", "tons", "House" ]
    return bad

def processMemo( lines, bad ):
    newLines = [ ]
    for line in lines:
        line = block( bad, line )
        newLines.append( line )
    return newLines

def main():
    lines = getMemo( )
    bads   = getBad()

    for bad in bads:
        lines = processMemo( lines, bad )

    for line in lines:
        print( line )
        
main()


Good Preparation for Homework #5


The same program is developed in several steps (versions) below. We start with a very simplified version of what we have to implement, and one step at a time we add more functionality, using functions.

Version 1


# censureText.py
# D. Thiebaut
# This program opens two text files,
# one containing lines of text, the other one
# containing a list of words to remove,
# and prints the contents of the first file
# with words blocked out.

def getMemo():
    """gets the memo to be censured"""
    return "Please deliver 10 burgers and 1 bottle of ketchup"

def getBadWord():
    """gets the word to block out"""
    return "burger"

def main():
    # get a line of text, and a bad word 
    line = getMemo( )
    bad  = getBadWord( )

    # modify line by removing the bad word
    line = line.replace( bad, "x" )
    print( line )
    
main()

Version 2


In this version, we create a new function called block() that gets a line and a bad word, and replaces the bad word in line by a series of xs. Block() returns the new version of the line.

The main program now calls block() to block out the bad word in the line, gets the line back and prints it.

# censureText.py
# D. Thiebaut
# This program opens two text files,
# one containing lines of text, the other one
# containing a list of words to remove,
# and prints the contents of the first file
# with words blocked out.

def getMemo():
    """gets the memo to be censured"""
    return "Please deliver 10 burgers and 1 bottle of ketchup"

def getBadWord():
    """gets the word to block out"""
    return "burger"

def block( line, bad ):
    # create a word with 'x' the same length
    # as the bad word
    badx = "x" * len( bad )

    # modify the line and replace bad with "xx...x"
    line = line.replace( bad, badx )
    return line
    
def main():
    # get a line of text, and a bad word 
    line = getMemo( )
    bad  = getBadWord( )

    # modify line by removing the bad word
    line = block( line, bad )

    # display the resulting line
    print( line )
    
main()


Version 3


In this version, instead of working with just one word, we work with a list of bad words. We change the name of getBadWord() to getBadWords() to reflect the fact that it is returning a list of words. We now have for loop in the main program to iterate through all the bad words.

You may want to remove the #-sign in the main program to see what is happening with the code.

# censureText.py
# D. Thiebaut
# This program opens two text files,
# one containing lines of text, the other one
# containing a list of words to remove,
# and prints the contents of the first file
# with words blocked out.

def getMemo():
    """gets the memo to be censured"""
    return "Please deliver 10 burgers and 1 bottle of ketchup"

def getBadWords():
    """gets the word to block out"""
    badWords = [ "burger", "ketchup" ]
    return badWords

def block( line, bad ):
    # create a word with 'x' the same length
    # as the bad word
    badx = "x" * len( bad )

    # modify the line and replace bad with "xx...x"
    line = line.replace( bad, badx )
    return line
    
def main():
    # get a line of text, and a bad word 
    line = getMemo( )
    badWords  = getBadWords( )

    # modify line by removing the bad word
    for bad in badWords:
        #print( "blocking out word:", bad )
        #print( "line before:      ", line )
        line = block( line, bad )
        #print( "line after:       ", line )
        #print()

    # display the resulting line
    print( line )
    
main()


Output
blocking out word: burger
line before:       Please deliver 10 burgers and 1 bottle of ketchup
line after:        Please deliver 10 xxxxxxs and 1 bottle of ketchup

blocking out word: ketchup
line before:       Please deliver 10 xxxxxxs and 1 bottle of ketchup
line after:        Please deliver 10 xxxxxxs and 1 bottle of xxxxxxx

Please deliver 10 xxxxxxs and 1 bottle of xxxxxxx


Version 4


We're making the code more modular by taking some code from main and packaging into a new function, called blockAllWordsInOneLine().
No new behavior is brought in, just moving some code out of main to keep main short and easy to read.

# censureText.py
# D. Thiebaut
# This program opens two text files,
# one containing lines of text, the other one
# containing a list of words to remove,
# and prints the contents of the first file
# with words blocked out.

def getMemo():
    """gets the memo to be censured"""
    return "Please deliver 10 burgers and 1 bottle of ketchup"

def getBadWords():
    """gets the word to block out"""
    badWords = [ "burger", "ketchup" ]
    return badWords

def block( line, bad ):
    # create a word with 'x' the same length
    # as the bad word
    badx = "x" * len( bad )

    # modify the line and replace bad with "xx...x"
    line = line.replace( bad, badx )
    return line

def blockAllWordsInOneLine( line, badWords ):
    """ gets one line and a list of bad words and
    blocks out all the bad words in the line.  Returns
    the edited line.
    """
    for bad in badWords:
        line = block( line, bad )
    return line

def main():
    # get a line of text, and a bad word 
    line = getMemo( )
    badWords  = getBadWords( )

    # modify line by removing the bad word
    line = blockAllWordsInOneLine( line, badWords )
        
    # display the resulting line
    print( line )
    
main()


Version 5


We now make the function getMemo() return a list of lines, rather than just one line.
The main program must be changed, since it is now getting a list of strings rather than one string. A for-loop is all that we need. Not much change, but much more powerful program!

# censureText.py
# D. Thiebaut
# This program opens two text files,
# one containing lines of text, the other one
# containing a list of words to remove,
# and prints the contents of the first file
# with words blocked out.

def getMemo():
    """gets the memo to be censured"""
    memo = [ "Please deliver 10 burgers and 1 bottle of ketchup",
             "Make it 20 burgers and a caisse of ketchup",
             "burgers and ketchup are the best food!" ]
    
    return memo

def getBadWords():
    """gets the word to block out"""
    badWords = [ "burger", "ketchup" ]
    return badWords

def block( line, bad ):
    # create a word with 'x' the same length
    # as the bad word
    badx = "x" * len( bad )

    # modify the line and replace bad with "xx...x"
    line = line.replace( bad, badx )
    return line

def blockAllWordsInOneLine( line, badWords ):
    """ gets one line and a list of bad words and
    blocks out all the bad words in the line.  Returns
    the edited line.
    """
    for bad in badWords:
        line = block( line, bad )
    return line

def main():
    # get a line of text, and a bad word 
    lines = getMemo( )
    badWords  = getBadWords( )

    for line in lines:
        # modify line by removing the bad word
        line = blockAllWordsInOneLine( line, badWords )
        
        # display the resulting line
        print( line )
    
main()


Please deliver 10 xxxxxxs and 1 bottle of xxxxxxx
Make it 20 xxxxxxs and a caisse of xxxxxxx
xxxxxxs and xxxxxxx are the best food!


Version 6


In this version we change the getMemo() function so that it gets the lines of the memo from the file memo.txt. This file is already defined in the same directory where we save our programs. For this example, memo.txt contains the following lines:

We need 10 tons of burgers and 1 ton of ketchup 
sent to the President before midnight.


# censureText.py
# D. Thiebaut
# This program opens two text files,
# one containing lines of text, the other one
# containing a list of words to remove,
# and prints the contents of the first file
# with words blocked out.

def getMemo():
    """gets the memo to be censured from the file memo.txt"""
    #memo = [ "Please deliver 10 burgers and 1 bottle of ketchup",
    #         "Make it 20 burgers and a caisse of ketchup",
    #         "burgers and ketchup are the best food!" ]

    # open the file for reading
    file = open( 'memo.txt', 'r' )

    # add each line of the file to memo (list)
    memo = []
    for line in file:
        memo.append( line.strip() )

    # close the file
    file.close()

    # return the list of string read from the file
    return memo

def getBadWords():
    """gets the word to block out"""
    badWords = [ "burger", "ketchup" ]
    return badWords

def block( line, bad ):
    # create a word with 'x' the same length
    # as the bad word
    badx = "x" * len( bad )

    # modify the line and replace bad with "xx...x"
    line = line.replace( bad, badx )
    return line

def blockAllWordsInOneLine( line, badWords ):
    """ gets one line and a list of bad words and
    blocks out all the bad words in the line.  Returns
    the edited line.
    """
    for bad in badWords:
        line = block( line, bad )
    return line

def main():
    # get a line of text, and a bad word 
    lines = getMemo( )
    badWords  = getBadWords( )

    for line in lines:
        # modify line by removing the bad word
        line = blockAllWordsInOneLine( line, badWords )
        
        # display the resulting line
        print( line )
    
main()


Output


We need 10 tons of xxxxxxs and 1 ton of xxxxxxx
sent to the President before midnight.


Version 7


Since we were successful getting the lines from file for the memo, we are doing the same thing for the bad words.

The file badwords.txt contains the following words:

burger
ketchup
President


# censureText.py
# D. Thiebaut
# This program opens two text files,
# one containing lines of text, the other one
# containing a list of words to remove,
# and prints the contents of the first file
# with words blocked out.

def getMemo():
    """gets the memo to be censured from the file memo.txt"""
    #memo = [ "Please deliver 10 burgers and 1 bottle of ketchup",
    #         "Make it 20 burgers and a caisse of ketchup",
    #         "burgers and ketchup are the best food!" ]

    # open the file for reading
    file = open( 'memo.txt', 'r' )

    # add each line of the file to memo (list)
    memo = []
    for line in file:
        memo.append( line.strip() )

    # close the file
    file.close()

    # return the list of string read from the file
    return memo

def getBadWords():
    """gets the list of words to block out from file"""
    # open the file for reading
    file = open( 'badwords.txt', 'r' )

    # add each line of the file to list of bad words
    bads = []
    for line in file:
        bad = line.strip()
        bads.append( bad )
        
    # close the file
    file.close()

    # return the list of string read from the file
    return bads


def block( line, bad ):
    # create a word with 'x' the same length
    # as the bad word
    badx = "x" * len( bad )

    # modify the line and replace bad with "xx...x"
    line = line.replace( bad, badx )
    return line

def blockAllWordsInOneLine( line, badWords ):
    """ gets one line and a list of bad words and
    blocks out all the bad words in the line.  Returns
    the edited line.
    """
    for bad in badWords:
        line = block( line, bad )
    return line

def main():
    # get a line of text, and a bad word 
    lines = getMemo( )
    badWords  = getBadWords( )

    for line in lines:
        # modify line by removing the bad word
        line = blockAllWordsInOneLine( line, badWords )
        
        # display the resulting line
        print( line )
    
main()


Output
We need 10 tons of xxxxxxs and 1 ton of xxxxxxx
sent to the xxxxxxxxx before midnight.


03/09/18


libraryDemo.py


# libraryDemo.py
# D. Thiebaut

from myLibrary import *

def main():
    lines = [ "Soon there'll be lunch", "Spring into action",
              "Break bad habits!" ]

    for line in lines:
        print( getFirstWordOf( line ), end=" " )

    print()

main()


myLibrary.py


# myLibrary.py
# D. Thiebaut


def getFirstWordOf( line ):
    '''receives a line assumed not to be empty
    and returns its first words.  Uses whitespace
    to split the line into words.
    '''
    words = line.strip().split()
    return words[0]


NQueens.py


#! /opt/local/bin/python
# D. Thiebaut
# Usage:
#   nqueens.py N
# where N is the number of queens wanted, i.e. the dimension
# of the board.
# The program will look for the first available solution where N queens
# can be put on the board such that they cannot take each other.

import sys
import time
QUEEN = -10
EMPTY = 0

class timePerfClass:
    """A class to keep track of processor and user time.
    use by first calling start(), then stop(), then 
    printElapsed()"""

    def __init__(self):
        self.clockStart = time.clock() # init all 4 counters
        self.clockEnd   = time.clock() # to current time
        self.timeStart  = time.time()
        self.timeEnd    = time.time()

    def start( self ):
        """set the start counters to current time"""
        self.clockStart = time.clock()
        self.timeStart  = time.time()

    def stop( self ):
        """set the end counters to current time"""
        self.clockEnd   = time.clock()
        self.timeEnd    = time.time()

    def printElapsed( self ):
        """print the difference between end and start counters"""
        print "processor time:   ", (self.clockEnd-self.clockStart), "sec"
        print "user time     :   ", (self.timeEnd-self.timeStart), "sec"


def makeBoard( N ):
    """create a 2-D array of ints with dimension N
    Returns the 2D array"""
    board = []
    for i in range( N ):
        board.append( [] )
        for j in range( N ):
            board[i].append( EMPTY )
    return board
    
def goHome():
    """when used  in a terminal window that supports ANSI codes,
    brings the cursor back to top left position"""
    sys.stderr.write( "\x1b[0;0H" )

def displaySolution( board ):
  """display the solution, in the form of a series of column numbers"""
  list = []
  for i in range( len( board ) ):
      for j in range( len( board ) ):
          if board[ i ][ j ]==QUEEN:
              list.append( str( j ) )
  print "Solution = ", ','.join( list )

def displayBoard( board, home=False ):
    """display the 2D array, showing empty cells as .
    and queens as Q"""
    if home: goHome()
    for i in range( len( board ) ):
        for j in range( len( board ) ):
            if board[i][j]==QUEEN: 
               print 'Q',
            else: 
               print '.',
        print
    displaySolution( board )
    
def markLowerBoard( board, row, col, offset ):
    """Once a queen is positioned at location (row,col), 
    all the cells on a lower diagonal and lower vertical
    of this queen must be marqued as unavailable so that
    another queen cannot be put in this place"""

    N = len( board )
    diagleft = col-1
    diagright = col+1
    # mark all lower rows on diagonals and vertical
    for r in range( row+1, N ):
        if diagleft >=0:  board[r][diagleft] += offset
        if diagright <N:  board[r][diagright] += offset
        board[r][col] += offset
        diagleft  -= 1
        diagright += 1

def tryRow( board, row,  N, display=False ):
    """ put a queen on give row, and recursively try all queens
    on successive rows"""
    if row >= N:
       return True #we found a solution!

    if display:
        displayBoard( board, True )
    for col in range( N ):
        if board[row][col] == EMPTY:
            # put a queen here
            board[ row ][ col ] = QUEEN
            markLowerBoard( board, row, col, +1 )
            ok = tryRow( board, row+1, N )
            if not ok:
                # backtrack
                board[ row ][ col ] = EMPTY
                markLowerBoard( board, row, col, -1 )
            else:
                return True
    return False           
           
       
# ---------------------------------------------------------------------------
def main():
    if len( sys.argv ) < 2:
        print "Syntax: nqueens.py N"
        print "        where N is the # of queens"
        return

    #--- start measurement ---
    perf = timePerfClass()
    perf.start()

    #--- get dimension, create board, and solve! ---
    N = int( sys.argv[1] )
    board = makeBoard( N )
    ok = tryRow( board, 0, N )

    #--- stop measurement ---
    perf.stop()
    perf.printElapsed()
    
    if ok:
         print "Success!"
         displayBoard( board )

if __name__=="__main__":
    main()



03/19/18


facebookNews.txt


This file is taken from a news article published on 3/18/2018 about Facebook.

Lawmakers in the United States and Britain are calling on Facebook chief executive Mark Zuckerberg 
to explain how the names, preferences and other information from tens of millions of users ended up 
in the hands of a data analysis firm connected with President Trump's 2016 campaign.

The demands came in response to news reports Saturday about how the firm, Cambridge Analytica, used 
a feature once available to Facebook app developers to collect information on 270,000 people and, 
in the process, gain access to data on tens of millions of their Facebook friends  few, if any, 
of whom had given explicit permission for this sharing.


emails.txt


Lauryn@smith.edu
Amaris@smith.edu
Lujun@smith.edu
Cora@smith.edu
smithy@umass.edu
Olive@smith.edu
Giuliana@smith.edu
Marina@smith.edu
Aliyah@smith.edu
Itzel@hampshire.edu
Rui@smith.edu
Perla@smith.edu
Julissa@smith.edu
Linda@smith.edu
Carolina@smith.edu
Beatrice@smith.edu
Carly@smith.edu
Iris@umass.edu
Lu@smith.edu
Armani@smith.edu
Julianna@smith.edu
Mattie@smith.edu
Diya@smith.edu
Maria@smith.edu
Payten@smith.edu
Caroline@amherst.edu
Gemma@smith.edu
Jade@smith.edu
Scarlet@smith.edu
Alejandra@smith.edu
Phoebe@smith.edu
Harper@smith.edu
Tianna@smith.edu
Litzy@smith.edu
Adison@mtholyoke.edu
Isabell@smith.edu
Yuliana@smith.edu
Lillian@smith.edu
Callie@smith.edu
Hadley@smith.edu
Camille@smith.edu
Tara@smith.edu
Desirae@smith.edu
Miya@smith.edu
Laura@smith.edu
Leticia@smith.edu
Emily@smith.edu
Krista@smith.edu
Ashtyn@smith.edu
Alina@smith.edu
Tiara@smith.edu
Cameron@smith.edu
Amaya@smith.edu
Jewel@smith.edu
Brenda@smith.edu
Angel@smith.edu
Anahi@smith.edu
Lara@smith.edu
Regina@smith.edu
Mylie@smith.edu
Kyra@smith.edu
Lindsay@smith.edu
Katherine@smith.edu
Raven@smith.edu
Chloe@smith.edu
Wendy@smith.edu
Amara@smith.edu
Adelyn@smith.edu
Sharon@smith.edu
Carlee@smith.edu
Aisha@smith.edu
Chana@smith.edu
Paisley@smith.edu
Amelie@smith.edu
Dixie@smith.edu
America@smith.edu
Karla@smith.edu
Alana@smith.edu
Dulce@smith.edu
Marlene@smith.edu
Serena@smith.edu
Annabel@smith.edu
Karley@smith.edu
Lyla@smith.edu
Sandra@smith.edu
Breanna@smith.edu
Gracelyn@smith.edu
Crystal@smith.edu
Taniya@smith.edu
Jazmin@smith.edu
Madalyn@smith.edu
Holly@smith.edu
Janiya@smith.edu
Paige@smith.edu
Jaylene@smith.edu
Cecelia@smith.edu
Jaylynn@smith.edu
Tori@smith.edu
Madeline@smith.edu
Aliza@smith.edu
Rebekah@smith.edu
Kimora@smith.edu
Mayra@smith.edu
Shea@smith.edu
Ana@smith.edu
Britney@smith.edu
Aleena@smith.edu
Yaritza@smith.edu
Bridget@smith.edu
Lindsey@smith.edu
Ava@smith.edu
Yareli@smith.edu
Violet@smith.edu
Londyn@smith.edu
Tatum@smith.edu
Patience@smith.edu
Ayana@smith.edu
Lizbeth@smith.edu
Madison@smith.edu
Elisabeth@smith.edu
Halle@smith.edu
Hallie@smith.edu
Ashley@smith.edu
Evelyn@smith.edu
Evelin@smith.edu


writeThankYous.py


# writeThankYous.py
# D. Thiebaut

def writeFile( fileName, name, amount ):
    file1 = open( fileName, "w" )
    thankYou = "Dear {0:1}, thank you very much for your gift of ${1:1}!\n".format( name, amount )
    file1.write( thankYou )
    file1.close()
    
def main():
    names = [("Alex", 100), ("Joe", 10), ("Fifi", 50)]

    for name, amount in names:
        #print( tuple )
        #name = tuple[0]
        #amount = tuple[1]
        #print( "name = ", name, "amount = ", amount )
        fileName = name + ".txt"
        writeFile( fileName, name, amount )

main()

readEmails2.py


# readEmails.py
# D. Thiebaut

def writePoem( fileName, text ):
    file3 = open( fileName, "w" )
    file3.write( text )
    file3.close()
    
def numberOfLines( fileName ):
    file1 = open( fileName, "r" )
    text = file1.read().strip()
    file1.close()
    lines = text.split( "\n"  )
    return len( lines )
    
def main():
    #print( "number of emails = ", numberOfLines( "emails.txt" ) )
    text = """The quick red fox
    jumped over the lazy brown dog"""
    writePoem( "poem.txt", text )
    
    
main()


03/21/18

randomColor1.py


# randomColor1.py
# your name here
# generates a rectangle with a random width
# and height, and a given color on the screen.

from graphics import *
from random import *

def main():
    win = GraphWin("Lab 7", 600,600)

    # create rectangle with these 2 corners
    r = Rectangle( Point(50,50), Point(300,300) )

    # create a color from 3 different RGB values
    red   = randint( 0, 255 )
    green = randint( 0, 255 )
    blue  = randint( 0, 255 )
    color = color_rgb( red, green, blue )

    # set the rectangle's color with this color
    r.setFill( color )

    # draw the rectangle
    r.draw( win )

    # wait for user to click on the window before closing
    win.getMouse()
    win.close()
    
main()


animation.py


# animation.py
# D. Thiebaut
# Moves a red circle on the graphics window.
# Waits for user to click the mouse in order to stop.
from graphics import *

def main():
    win = GraphWin( "Lab 7 Moving ball", 600, 400 )

    # create and draw a red circle
    center = Point( 100, 100 )
    circ     = Circle( center, 30 )
    circ.setFill( 'red' )
    circ.draw( win )

    # set initial direction of ball
    dx = 1.5
    dy = 0.25
    
    # move ball on screen
    while win.checkMouse() == None:
        circ.move( dx, dy )
        #x = circ.getCenter().getX()
        #y = circ.getCenter().getY()
    
    win.close()    # Close window when done

main()


3/23/18


tellerWithIfsPrep.py

# teller.py
# D. Thiebaut
# simulates teller machine program
# prompts user, displays number of bills

def getAmount():
    # get amount from user
    amount = eval( input( "Amount to withdraw? " ) )
    amount = abs( int( amount ) )
    
    # return valid amount
    return amount

def breakDown( amount, denom ):
    numBills = amount // denom
    amount   = amount % denom
    return numBills, amount

def display( numBills, denom ):
    print( "{0:2} ${1:1}-bill(s)".format( numBills, denom ) )

def main():
    # get amount from user
    amount = getAmount()
    print( "Amount:", amount )

    # break it down into 20, 10, 5, and 1 $bills
    no20s, amount = breakDown( amount, 20 )
    no10s, amount = breakDown( amount, 10 )
    no5s,  no1s   = breakDown( amount, 5 )

    # display number of bills
    display( no20s, 20 )
    display( no10s, 10 )
    display( no5s,  5 )
    display( no1s,  1 )

main()


stopForLoop.py

# stopForLoop.py
# D. Thiebaut
# (there are better ways to do this,
# but when we don't know about the
# "break" statement, this will do!

def main():

    plays = [ "SS", "PP", "PS", "SP", "PR", "RR", "RR" ]

    count = 0
    for players in plays:
        if count < 3:
            print( "processing", players )
            
        count = count + 1

main()


filterVowels.py

# filterVowels.py
# D. Thiebaut
# gets a string from user
# and keep only the vowels in the string

def main():
    answer = input( "> " ).strip().lower()
    valid = ""
    for letter in answer:
        if letter in [ 'a', 'e', 'i', 'o', 'u' ]:
            valid = valid + letter

    print( "valid letters = ", valid )

main()


RPSSkeleton.py


# RPSSkeleton.py
# D. Thiebaut
# implements a skeleton game of Rock, Paper, Scissors

# 3 constants indicating the output of 1 play
PLAYER1WINS = 1
PLAYER2WINS = 2
TIE = 0

def check( P1, P2 ):
    '''given two upper case letters in P1, and P2 equal to
    "R", "S", or "P", decides which of P1 or P2 is the winner.'''

    # tie?
    if P1 == P2:
        return TIE
    else:
        # no tie, so check for all other possible combinations
        # of P1 and P2.
        if P1 == "R":
            if P2 == "S":
                return PLAYER1WINS
            else:
                return PLAYER2WINS
        if P1 == "S":
            if P2 == "R":
                return PLAYER2WINS
            else:
                return PLAYER1WINS
        if P1 == "P":
            if P2 == "S":
                return PLAYER2WINS
            else:
                return PLAYER1WINS
            
            
            
def main():
    # keep track of the score of each player
    score1 = 0
    score2 = 0

    # create a list of possible plays...
    plays = [ "RR", "RS", "SP", "PP", "PR" ]

    # evaluate the outcome of each play in the list
    for play in plays:
        #play = input( "> " ).strip().upper()
        print( "play = ", play )

        # define Player 1 and Player 2
        P1 = play[0]
        P2 = play[1]

        # output will be PLAYER1WINS, PLAYER2WINS, or TIE
        outcome = check( P1, P2 )

        # display who the winner is
        if outcome == PLAYER1WINS:
            print( "Player 1 wins" )
            score1 = score1 + 1
        if outcome == PLAYER2WINS:
            print( "Player 2 wins" )
            score2 = score2 + 1
        if outcome == TIE:
            print( "It's a tie!" )

        # update the user with the current score
        print( "Player1:", score1, "  Player2:", score2 )
        
main()


3/26/18


distanceDemo.py


# distanceDemo.py
# D. Thiebaut
# A simple program that tests a function returning
# the distance between 2 graphic points (using the
# graphics.py library)
from math import *
from graphics import *

def distance( x1, y1, x2, y2 ):
    '''returns the distance between two points with
    coordinates (x1,y1) and (x2,y2)'''
    return sqrt( (x1-x2)*(x1-x2) +
                 (y1-y2)*(y1-y2) )

def distanceP( p1, p2 ):
    '''returns the distance between two graphics
    points'''
    x1, y1 = p1.getX(), p1.getY()
    x2, y2 = p2.getX(), p2.getY()
    return distance( x1, y1, x2, y2 )

def main():
    point1 = Point( 3, 5 )  # difference in x = 4
    point2 = Point( 7, 8 )  # difference in y = 3 ==> distance is 5
    d = distanceP( point1, point2 )
    print( "distance =", d )

main()


Eliza1.py


# Eliza1.py
# D. Thiebaut
# A very short beginning program for Eliza
from time import sleep
from os import system

# --------------------------------------------------------------------------
# just print the string to the console
# will be transformed to something better later...
def myprint( string ):
    print( string )
    #system('say ' + string )
    #sleep( 0.5 )
    
# sayGoodBye
# say goodbye to the user.
def sayGoodBye( name ):
    myprint( "Good bye " + name )

# isGoodBye
# checks to see if what the user said is one of the keywords for
# ending the conversation.
def isGoodBye( userAnswer ):
    if userAnswer.lower().strip() in [ "bye", "goodbye", "ciao" ]:
        return True
    else:
        return False

def greetings():
    myprint( "Hello there!" )
    myprint( "What is your name?" )
    name = input( "> " )
    myprint( "Welcome " + name )
    return name

# --------------------------------------------------------------------------
# main function
# --------------------------------------------------------------------------                   
def main():

     # greet user and get her name
     userName = greetings()
     
     # conversation: get user input, and respond
     for i in range( 1000 ):

         # get user's statement
         userAnswer = input( "> " )

         # if it is a goodbye statement, exit the loop
         if isGoodBye( userAnswer ) == True:
             break

         # tell the user to continue speaking
         myprint( "Please tell me more..." )


     # if we're here, it's because the loop stopped.
     # say goodbye to the user
     sayGoodBye( userName )
            
         
main()


Eliza2.py


# Eliza2.py
# D. Thiebaut (created in class on 3/28)
# A very short beginning program for Eliza
from time import sleep
from os import system
from random import choice

# --------------------------------------------------------------------------
# just print the string to the console
# will be transformed to something better later...
def myprint( string ):
    print( string )
    #system('say ' + string )
    #sleep( 0.5 )
    
# sayGoodBye
# say goodbye to the user.
def sayGoodBye( name ):
    myprint( "Good bye " + name )

# isGoodBye
# checks to see if what the user said is one of the keywords for
# ending the conversation.
def isGoodBye( userAnswer ):
    if userAnswer.lower().strip() in [ "bye", "goodbye", "ciao" ]:
        return True
    else:
        return False

def greetings():
    myprint( "Hello there!" )
    myprint( "What is your name?" )
    name = input( "> " )
    myprint( "Welcome " + name )
    return name

# --------------------------------------------------------------------------
# main function
# --------------------------------------------------------------------------                   
def main():

     prompts = ["Please go on...", "Please tell me more...",
            "Interesting... Go on, please", 
            "Yes?  Really? Go on",
            "Weird... I'm not sure what to think of that..." ]

     family = [ "mother", "father", "brother", "sister" ]
     
     # greet user and get her name
     userName = greetings()
     
     # conversation: get user input, and respond
     for i in range( 1000 ):

         # get user's statement
         userAnswer = input( "> " )

         # if it is a goodbye statement, exit the loop
         if isGoodBye( userAnswer ) == True:
             break # break out of for-loop

         familyMatter = False
         for word in family:
             if userAnswer.lower().find( word ) != -1:
                 familyMatter = True

         if familyMatter == True:
             myprint( "tell me more about your family" )
         else:
             # tell the user to continue speaking
             myprint( choice( prompts ) )


     # if we're here, it's because the loop stopped.
     # say goodbye to the user
     sayGoodBye( userName )
            
         
main()

3/30/18


YesNo.py


# get a YES/NO answer from user
def getAnswerYesNo():
   x = input( "Continue (Yes/No)? " ).upper()
   while x != "NO" and x != "YES":
       print( "Invalid input, must be YES or NO" )
       x = input( "Continue (Yes/No)? " ).upper()
   return x

def getAnswerYesNo2():
   x = input( "Continue (Yes/No)? " )
   while not x.upper() in [ "NO", "YES", "NOPE", "YEAH" ]:
       print( "Invalid input, must be YES or NO" )
       x = input( "Continue (Yes/No)? " )
   return x

def main():
    ans = getAnswerYesNo()    
    print( ans )                

    ans = getAnswerYesNo2()    
    print( ans )                

main()


Eliza3.py


# Eliza3.py
# D. Thiebaut
# This version of Eliza implements reflection and detection
# of negative comments
from time import sleep
from os import system
from random import choice

# --------------------------------------------------------------------------
# just print the string to the console
# will be transformed to something better later...
def myprint( string ):
    print( string )
    # system('say ' + string )
    # sleep( 0.5 )
    
# sayGoodBye
# say goodbye to the user.
def sayGoodBye( name ):
    myprint( "Good bye " + name )

# isGoodBye
# checks to see if what the user said is one of the keywords for
# ending the conversation.
def isGoodBye( userAnswer ):
    if userAnswer.lower().strip() in [ "bye", "goodbye", "ciao" ]:
        return True
    else:
        return False

def greetings():
    myprint( "Hello there!" )
    myprint( "What is your name?" )
    name = input( "> " )
    myprint( "Welcome " + name )
    return name

# --------------------------------------------------------------------------
# main function
# --------------------------------------------------------------------------                   
def main():

     prompts = ["Please go on...", "Please tell me more..." ]
     negPrompts = [ "My, my, why so negative?", "Really?", "Why not?" ]
     family = [ "mother", "father", "brother", "sister" ]
     
     # greet user and get her name
     userName = greetings()
     
     # conversation: get user input, and respond
     timeToStop = False
     while timeToStop==False:

         # get user's statement
         userAnswer = input( "> " )

         # if it is a goodbye statement, exit the loop
         if isGoodBye( userAnswer ) == True:
             timeToStop = True
             continue

         # is the patient talking about a family member?
         for word in family:
             if userAnswer.lower().find( word ) != -1:
                 myprint( "tell me more about your family" )
                 continue


         # reflection
         # "I XXXX you" --> "You XXXX me?"
         words = userAnswer.strip().split()
         if len( words )==3 and words[0]=="I" and words[2]=="you":
             myprint( "You " + words[1] + " me?" )
             prompts.append( "Is that why you " + words[1] + " me?" )
             continue
             
         # negative answers
         if userAnswer.upper() in [ "NO", "NEVER", "NOPE", "NADA", "NON" ]:
             myprint( choice( negPrompts ) )
             continue
         
         # if we're here, it's because none of the tests above were true,
         # and we didn't detect a negative answer, a family matter, or a
         # reflection.  So we just print a random prompt.
         myprint( choice( prompts ) )


     # if we're here, it's because the loop stopped.
     # say goodbye to the user
     sayGoodBye( userName )
            
         
main()


4/2/18


readCSV.py


# readCSVFile.py
# D. Thiebaut
# Example of a program that reads a CSV file
# and displays some of its contents.

def readCSV( fileName ):
    file = open( fileName, 'r' )
    Records = [ ]
    lines = file.readlines()
    for line in lines:
        #words = line.replace( '"','').strip().split( ',' )
        words = line.replace( '"','').strip().split( ',' )
        Records.append( words )
    file.close()
    return Records

def main():
    fileName = input( "File name? " )
    recs = readCSV( fileName )
    for i in range( len( recs ) ):
        record = recs[i]
        # record is a tuple
        # join each word in the tuple by a tab, and print
        # resulting string
        print( "Record ", i, "=", "\t".join( record ) )

main()


dieClass.py


# dieClass.py
# D. Thiebaut
# A class for the definition of a simple
# die, with any number of sides

# libraries
from random import *

# a class for a die
class Die:
    def __init__( self, n ):
         self.noSides = n
         self.value   = 1

    def roll( self ):
         self.value = randrange( 1, self.noSides+1 )

    def getValue( self ):
         return self.value


playDice.py


# playDice.py
# D. Thiebaut
# Uses the Class.py class
# and plays with a few dice

from dieClass import Die

def main():
    # Create 2 dice, one with 6 sides
    d1 = Die( 6 )
    d2 = Die( 8 )

    for play in range( 10 ):
        print( "\nPlay No.", play+1 )
        # Roll both dice
        d1.roll( )
        d2.roll( )

        # display their value
        print( "Die 1: ",  d1.getValue() )
        print( "Die 2: ",  d2.getValue() )

main()


Main Program for Cat Objects


# cats1.py
# D. Thiebaut
# Define a Cat class, and
# use it to create a collection of
# cats.

# -----------------------------------------------------------
# add class definition here!


# -----------------------------------------------------------
# main program
def main():
    """ main program.  Creates a list of cats and displays
    groups sharing the same property.
        Minou, 3, vac, stray
        Max, 1, not-vac, Burmese
        Gizmo, 2, vac, Bengal
        Garfield, 4, not-vac, Orange Tabby
    """
    cats = []
    cat = Cat( "Minou", "stray", True, 3 )
    cats.append( cat )
    
    cats.append( Cat( "Max", "Burmese", False, 1 ) )
    cats.append( Cat( "Gizmo", "Bengal", True, 2 ) )
    cats.append( Cat( "Garfield", "Orange Tabby", False, 4 ) )

    # print the list of all the cats
    print( "\nComplete List:" )
    for cat in cats:
        print( cat )

   


main()