Difference between revisions of "CSC111 Programs Created in Class 2018"
(→NQueens.py) |
(→facebookNews.txt) |
||
Line 1,606: | Line 1,606: | ||
of whom had given explicit permission for this sharing. | of whom had given explicit permission for this sharing. | ||
</source> | </source> | ||
− | + | <br /> | |
+ | ==emails.txt== | ||
+ | <br /> | ||
+ | ::<source lang="text"> | ||
+ | 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 | ||
+ | </text> | ||
+ | <br /> | ||
[[Category:Python]][[Category:CSC111]] | [[Category:Python]][[Category:CSC111]] |
Revision as of 08:11, 19 March 2018
D. Thiebaut (talk) 12:30, 31 January 2018 (EST)
Contents
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
- <source lang="text">
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
</text>