├── README.md ├── chap01 ├── exercise_2.py ├── exercise_3.py ├── exercise_5.py ├── exercise_6.xlsx ├── exercise_6a.py ├── exercise_6b.py ├── exercise_6c.py └── exercise_7.py ├── chap02 ├── annualized_interest.py ├── avg2.py ├── convert.py ├── discuss4.py ├── discuss6.py ├── exercise_1.py ├── exercise_11.py ├── exercise_2.py ├── exercise_4.py ├── exercise_5.py ├── exercise_8.py ├── exercise_9.py ├── futval.py └── interest_compounded_quarterly.py ├── chap03 ├── approximate_pi.py ├── area_of_triangle.py ├── change.py ├── discus4.py ├── exercise_10.py ├── exercise_11.py ├── exercise_12.py ├── exercise_13.py ├── exercise_14.py ├── exercise_17.py ├── exercise_2.py ├── exercise_3.py ├── exercise_4.py ├── exercise_5.py ├── exercise_6.py ├── exercise_7.py ├── exercise_8.py ├── factorial.py ├── fibonacci.py ├── quadratic.py └── vol_and_srfArea_of_sphere.py ├── chap04 ├── click.py ├── convert_gui.py ├── discuss3.py ├── exercise_1.py ├── exercise_10.py ├── exercise_11.py ├── exercise_2.py ├── exercise_3.py ├── exercise_7.py ├── exercise_8.py ├── exercise_9.py ├── futval_graph.py ├── futval_graph2.py ├── futval_graph3.py └── triangle.py ├── chap05 ├── change2.py ├── dateconvert.py ├── dateconvert2.py ├── discussion_output.py ├── exercise_1.py ├── exercise_10.py ├── exercise_11.py ├── exercise_12.py ├── exercise_13.py ├── exercise_14.py ├── exercise_15.py ├── exercise_16.py ├── exercise_2.py ├── exercise_3.py ├── exercise_4.py ├── exercise_5.py ├── exercise_6.py ├── exercise_7.py ├── exercise_8.py ├── exercise_8x.py ├── exercise_9.py ├── month.py ├── month2.py ├── notes.py ├── numbers2text.py ├── numbers2text2.py ├── scores.txt ├── sean_test.txt ├── student_test.txt ├── test.py ├── text2numbers.py ├── userfile.py └── username.py ├── chap06 ├── addinterest2.py ├── addinterest3.py ├── drawBar.py ├── ex14test.txt ├── exercise_1.py ├── exercise_10.py ├── exercise_11.py ├── exercise_12.py ├── exercise_13.py ├── exercise_14.py ├── exercise_15.py ├── exercise_16.py ├── exercise_17.py ├── exercise_2.py ├── exercise_3.py ├── exercise_4.py ├── exercise_5.py ├── exercise_6.py ├── exercise_7.py ├── exercise_8.py ├── exercise_9.py ├── futval_graph3*.py ├── happy.py ├── test.py ├── test_img.gif ├── test_img.jpg └── triangle2.py ├── chap07 ├── exercise_1.py ├── exercise_10.py ├── exercise_11.py ├── exercise_12.py ├── exercise_13.py ├── exercise_14.py ├── exercise_15.py ├── exercise_16.py ├── exercise_17.py ├── exercise_18.py ├── exercise_2.py ├── exercise_3.py ├── exercise_4.py ├── exercise_5.py ├── exercise_6.py ├── exercise_7.py ├── exercise_8.py ├── exercise_9.py └── test.py ├── chap08 ├── average1.py ├── average2.py ├── average3.py ├── average4.py ├── average5.py ├── average6.py ├── average7.py ├── discuss3.py ├── exercise_1.py ├── exercise_10.py ├── exercise_10.txt ├── exercise_11.py ├── exercise_12.py ├── exercise_12.txt ├── exercise_13.py ├── exercise_14(gray).png ├── exercise_14.png ├── exercise_14.py ├── exercise_15(negative).png ├── exercise_15.png ├── exercise_15.py ├── exercise_2*.py ├── exercise_2.py ├── exercise_3.py ├── exercise_4.py ├── exercise_5*.py ├── exercise_5.py ├── exercise_5_refactor.py ├── exercise_6*.py ├── exercise_6.py ├── exercise_7*.py ├── exercise_7.py ├── exercise_8.py ├── exercise_9.py └── notes.py ├── chap09 ├── exercise_1.py ├── exercise_10.py ├── exercise_11.py ├── exercise_12.py ├── exercise_13.py ├── exercise_14.py ├── exercise_15.py ├── exercise_2.py ├── exercise_3.py ├── exercise_4.py ├── exercise_5.py ├── exercise_6.py ├── exercise_7.py ├── exercise_8.py ├── exercise_9*.py ├── exercise_9.py └── rball.py ├── chap10 ├── Playing_Card_Images │ ├── 10C.png │ ├── 10D.png │ ├── 10H.png │ ├── 10S.png │ ├── 11C.png │ ├── 11D.png │ ├── 11H.png │ ├── 11S.png │ ├── 12C.png │ ├── 12D.png │ ├── 12H.png │ ├── 12S.png │ ├── 13C.png │ ├── 13D.png │ ├── 13H.png │ ├── 13S.png │ ├── 1C.png │ ├── 1D.png │ ├── 1H.png │ ├── 1S.png │ ├── 2C.png │ ├── 2D.png │ ├── 2H.png │ ├── 2S.png │ ├── 3C.png │ ├── 3D.png │ ├── 3H.png │ ├── 3S.png │ ├── 4C.png │ ├── 4D.png │ ├── 4H.png │ ├── 4S.png │ ├── 5C.png │ ├── 5D.png │ ├── 5H.png │ ├── 5S.png │ ├── 6C.png │ ├── 6D.png │ ├── 6H.png │ ├── 6S.png │ ├── 7C.png │ ├── 7D.png │ ├── 7H.png │ ├── 7S.png │ ├── 8C.png │ ├── 8D.png │ ├── 8H.png │ ├── 8S.png │ ├── 9C.png │ ├── 9D.png │ ├── 9H.png │ ├── 9S.png │ ├── __init__.py │ ├── aces.png │ ├── back_cards-07.png │ ├── blue_back.png │ ├── gray_back.png │ ├── green_back.png │ ├── honor_clubs.png │ ├── honor_diamond.png │ ├── honor_heart-14.png │ ├── honors_spade-14.png │ ├── playingcard.py │ ├── purple_back.png │ ├── red_back.png │ └── yellow_back.png ├── button.py ├── cball3.py ├── cball4.py ├── cbutton.py ├── cube.py ├── dieview.py ├── discuss_3.py ├── exercise_1.py ├── exercise_10.py ├── exercise_11.py ├── exercise_12.py ├── exercise_13.py ├── exercise_14.py ├── exercise_15.py ├── exercise_16.py ├── exercise_17.py ├── exercise_2.py ├── exercise_3.py ├── exercise_4.py ├── exercise_5.py ├── exercise_6.py ├── exercise_7.py ├── exercise_8.py ├── exercise_9.py ├── face.py ├── gpa.py ├── gpa.txt ├── msdie.py ├── playingcard.py ├── projectile.py ├── regression.py ├── roller.py ├── sphere.py └── tracker.py ├── chap11 ├── Playing_Card_Images │ ├── 10C.png │ ├── 10D.png │ ├── 10H.png │ ├── 10S.png │ ├── 11C.png │ ├── 11D.png │ ├── 11H.png │ ├── 11S.png │ ├── 12C.png │ ├── 12D.png │ ├── 12H.png │ ├── 12S.png │ ├── 13C.png │ ├── 13D.png │ ├── 13H.png │ ├── 13S.png │ ├── 1C.png │ ├── 1D.png │ ├── 1H.png │ ├── 1S.png │ ├── 2C.png │ ├── 2D.png │ ├── 2H.png │ ├── 2S.png │ ├── 3C.png │ ├── 3D.png │ ├── 3H.png │ ├── 3S.png │ ├── 4C.png │ ├── 4D.png │ ├── 4H.png │ ├── 4S.png │ ├── 5C.png │ ├── 5D.png │ ├── 5H.png │ ├── 5S.png │ ├── 6C.png │ ├── 6D.png │ ├── 6H.png │ ├── 6S.png │ ├── 7C.png │ ├── 7D.png │ ├── 7H.png │ ├── 7S.png │ ├── 8C.png │ ├── 8D.png │ ├── 8H.png │ ├── 8S.png │ ├── 9C.png │ ├── 9D.png │ ├── 9H.png │ ├── 9S.png │ ├── __init__.py │ ├── aces.png │ ├── back_cards-07.png │ ├── blue_back.png │ ├── gray_back.png │ ├── green_back.png │ ├── honor_clubs.png │ ├── honor_diamond.png │ ├── honor_heart-14.png │ ├── honors_spade-14.png │ ├── playingcard.py │ ├── purple_back.png │ ├── red_back.png │ └── yellow_back.png ├── button.py ├── calc.pyw ├── dieview2.py ├── discuss1.txt ├── exercise_1.py ├── exercise_10.py ├── exercise_11(1).txt ├── exercise_11.py ├── exercise_11.txt ├── exercise_12.py ├── exercise_12.txt ├── exercise_13.py ├── exercise_14.py ├── exercise_15.py ├── exercise_16.py ├── exercise_17.py ├── exercise_18.py ├── exercise_19.py ├── exercise_2.py ├── exercise_3.py ├── exercise_4.py ├── exercise_5.py ├── exercise_6.py ├── exercise_7.py ├── exercise_8.py ├── exercise_9.py ├── gpa.py ├── gpa1.txt ├── gpa_(sortfast).txt ├── gpasort.py ├── playingcard.py ├── stats.py └── wordfreq.py ├── chap12 ├── atmmanager.py ├── button.py ├── conferenceAttendees.json ├── consolereader.py ├── dice.py ├── exercise_1.py ├── exercise_2.py ├── exercise_3.py ├── exercise_4.py ├── exercise_5.py ├── exercise_6.py ├── exercise_7.py ├── exercise_8.py ├── json_test.py ├── new_atmusers.json ├── objrball.py ├── playingcard.py ├── poker.pyw ├── pokerapp.py ├── textatm.py └── textpoker.py ├── chap13 ├── eng_dictionary.txt ├── exercise_1.py ├── exercise_10.py ├── exercise_11.py ├── exercise_2.py ├── exercise_3.py ├── exercise_4.py ├── exercise_5.py ├── exercise_6.py ├── exercise_7.py ├── exercise_8.py ├── exercise_9.py └── testdoc.txt └── graphics.py /chap01/exercise_2.py: -------------------------------------------------------------------------------- 1 | print("This Program ilustrates a chaotic function") 2 | x = eval(input("Enter Number")) 3 | for i in range(10): 4 | x = 3.9 * x * (1-x) 5 | print(x) 6 | -------------------------------------------------------------------------------- /chap01/exercise_3.py: -------------------------------------------------------------------------------- 1 | print("This Program ilustrates a chaotic function") 2 | x = eval(input("Enter Number")) 3 | for i in range(10): 4 | x = 2.0 * x * (1-x) 5 | print(x) 6 | -------------------------------------------------------------------------------- /chap01/exercise_5.py: -------------------------------------------------------------------------------- 1 | print("This Program ilustrates a chaotic function") 2 | n = eval(input("How many numbers should I print? ")) 3 | x = eval(input("Enter a value between 0 and 1: ")) 4 | for i in range(n): 5 | x = 2.0 * x * (1-x) 6 | print(x) 7 | -------------------------------------------------------------------------------- /chap01/exercise_6.xlsx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/drycode/zelle-python/ccd781784bf2a635d1f6e84ec2173d2ae7d50098/chap01/exercise_6.xlsx -------------------------------------------------------------------------------- /chap01/exercise_6a.py: -------------------------------------------------------------------------------- 1 | print("This Program ilustrates a chaotic function") 2 | n = eval(input("How many numbers should I print? ")) 3 | x = eval(input("Enter a value between 0 and 1: ")) 4 | for i in range(n): 5 | x = 3.9 * x * (1-x) 6 | print(x) 7 | -------------------------------------------------------------------------------- /chap01/exercise_6b.py: -------------------------------------------------------------------------------- 1 | print("This Program ilustrates a chaotic function") 2 | n = eval(input("How many numbers should I print? ")) 3 | x = eval(input("Enter a value between 0 and 1: ")) 4 | for i in range(n): 5 | x = 3.9 * (x - x * x) 6 | print(x) 7 | -------------------------------------------------------------------------------- /chap01/exercise_6c.py: -------------------------------------------------------------------------------- 1 | print("This Program ilustrates a chaotic function") 2 | n = eval(input("How many numbers should I print? ")) 3 | x = eval(input("Enter a value between 0 and 1: ")) 4 | for i in range(n): 5 | x = 3.9 * x - 3.9 * x * x 6 | print(x) 7 | -------------------------------------------------------------------------------- /chap01/exercise_7.py: -------------------------------------------------------------------------------- 1 | print("This Program ilustrates a chaotic function") 2 | n = eval(input("How many numbers should I print? ")) 3 | x = eval(input("Enter a value between 0 and 1: ")) 4 | y = eval(input("Enter a different value between 0 and 1: ")) 5 | for i in range(n): 6 | x = 3.9 * x - 3.9 * x * x 7 | y = 3.9 * y - 3.9 * y * y 8 | print(x, y) 9 | -------------------------------------------------------------------------------- /chap02/annualized_interest.py: -------------------------------------------------------------------------------- 1 | def main(): 2 | print("This program calculates the future value\n", "of an annualized investment.") 3 | principal = eval(input("Enter the initial principal: ")) 4 | apr = eval(input("Enter the annual interest rate in perecents: ")) 5 | year = eval(input("Enter the length of investment in years: ")) 6 | deposit = eval(input("Enter the amount to be deposited each month: ")) 7 | 8 | for i in range (year): 9 | principal = (principal * (1 + (apr * .01))) + (deposit * 12) 10 | print("The value in", year, "years is", principal) 11 | 12 | main() 13 | -------------------------------------------------------------------------------- /chap02/avg2.py: -------------------------------------------------------------------------------- 1 | def main(): 2 | print("This program computes the average of two exam scores.") 3 | 4 | score1, score2 = eval(input("Enter two scores separated by a comma: ")) 5 | average = (score1 + score2) / 2 6 | 7 | print("The average of the scores is:", average) 8 | 9 | main() 10 | -------------------------------------------------------------------------------- /chap02/convert.py: -------------------------------------------------------------------------------- 1 | def main(): 2 | celsius = eval(input("What is the Celsius temperature? ")) 3 | fahrenheit = 9/5 * celius + 32 4 | print("The temperature is ", fahrenheit, "degrees Fahrenheit.") 5 | 6 | main() 7 | -------------------------------------------------------------------------------- /chap02/discuss4.py: -------------------------------------------------------------------------------- 1 | for i in range(5): 2 | print(i * i) 3 | 4 | for d in [3,1,4,1,5]: 5 | print(d, end=" ") 6 | 7 | for i in range(4): 8 | print("hello") 9 | 10 | for i in range(5): 11 | print(i, 2**i) 12 | -------------------------------------------------------------------------------- /chap02/discuss6.py: -------------------------------------------------------------------------------- 1 | print("Rectangle!", "America!", "Monday", "Butthole!", sep="\n") 2 | -------------------------------------------------------------------------------- /chap02/exercise_1.py: -------------------------------------------------------------------------------- 1 | def main(): 2 | print("Welcome! This program will kindly convert", "\n", "your degrees Celsius into Fahrenheit.") 3 | celsius = eval(input("What is the Celsius temperature? ")) 4 | fahrenheit = (celsius - 32) * 5/9 5 | print("The temperature is ", fahrenheit, "degrees Fahrenheit.") 6 | 7 | main() 8 | -------------------------------------------------------------------------------- /chap02/exercise_11.py: -------------------------------------------------------------------------------- 1 | def main(): 2 | print("Calculator") 3 | for i in range(100): 4 | x = eval(input()) 5 | print(x) 6 | 7 | main() 8 | -------------------------------------------------------------------------------- /chap02/exercise_2.py: -------------------------------------------------------------------------------- 1 | def main(): 2 | print("This program computes the average of three exam scores.") 3 | 4 | score1, score2, score3 = eval(input("Enter three scores separated by commas: ")) 5 | average = (score1 + score2 + score3) / 3 6 | 7 | print("The average of the scores is:", average) 8 | 9 | main() 10 | -------------------------------------------------------------------------------- /chap02/exercise_4.py: -------------------------------------------------------------------------------- 1 | def main(): 2 | for i in range(11): 3 | celsius = i * 10 4 | fahrenheit = 9/5 * celsius + 32 5 | print((i * 10), fahrenheit) 6 | 7 | main() 8 | -------------------------------------------------------------------------------- /chap02/exercise_5.py: -------------------------------------------------------------------------------- 1 | def main(): 2 | print("This program calculates the future value\n", "of a 10-year investment.") 3 | principal = eval(input("Enter the initial principal: ")) 4 | apr = eval(input("Enter the annual interest rate in perecents: ")) 5 | year = eval(input("Enter the length of investment in years: ")) 6 | 7 | for i in range (year): 8 | principal = principal * (1 + (apr * .01)) 9 | print("The value in", year, "years is", principal) 10 | 11 | main() 12 | -------------------------------------------------------------------------------- /chap02/exercise_8.py: -------------------------------------------------------------------------------- 1 | def main(): 2 | print("Welcome! This program will kindly convert", "\n", "your degrees Fahrenheit into Celsius.") 3 | fahrenheit = eval(input("What is the Fahrenheit temperature? ")) 4 | celsius = (fahrenheit - 32) * 5/9 5 | print("The temperature is ", celsius, "degrees Fahrenheit.") 6 | 7 | main() 8 | -------------------------------------------------------------------------------- /chap02/exercise_9.py: -------------------------------------------------------------------------------- 1 | def main(): 2 | print("Welcome! This program will kindly convert", "\n", "your distance in kilometers to miles.") 3 | km = eval(input("What is the distance in km? ")) 4 | miles = km * .62 5 | print("The distance is ", miles, "miles.") 6 | 7 | main() 8 | -------------------------------------------------------------------------------- /chap02/futval.py: -------------------------------------------------------------------------------- 1 | def main(): 2 | print("This program calculates the future value\n", "of a 10-year investment.") 3 | principal = eval(input("Enter the initial principal: ")) 4 | apr = eval(input("Enter the annual interest rate: ")) 5 | 6 | for i in range (10): 7 | principal = principal * (1 + apr) 8 | 9 | print("The value in 10 years is:", principal) 10 | 11 | main() 12 | -------------------------------------------------------------------------------- /chap02/interest_compounded_quarterly.py: -------------------------------------------------------------------------------- 1 | def main(): 2 | print("This program calculates the future value\n", "of an investment compounded quarterly.") 3 | principal = eval(input("Enter the initial principal: ")) 4 | apr = eval(input("Enter the annual interest rate in perecents: ")) 5 | year = eval(input("Enter the length of investment in years: ")) 6 | deposit = eval(input("Enter the amount to be deposited each month: ")) 7 | 8 | for i in range (year * 4): 9 | principal = (principal * (1 + (apr/4 * .01))) + (deposit * 12) 10 | print("The value in", year, "years is", principal) 11 | 12 | main() 13 | -------------------------------------------------------------------------------- /chap03/approximate_pi.py: -------------------------------------------------------------------------------- 1 | 2 | import math 3 | def main(): 4 | n = eval(input("Enter how many terms: ")) 5 | x = 0 6 | m = 1 7 | for i in range(1, 2 * n + 1, 2): 8 | x = x + (m * 4/i) 9 | m = -m 10 | print(math.pi - x) 11 | main() 12 | -------------------------------------------------------------------------------- /chap03/area_of_triangle.py: -------------------------------------------------------------------------------- 1 | import math as m 2 | def main(): 3 | a, b, c = eval(input("Input the 3 sides of the triangle, separated by commas: ")) 4 | s = (a + b + c) / 2 5 | A = m.sqrt(s * (s-a) * (s-b) * (s-c)) 6 | print("The area of this triangle is: ", round(A, 2)) 7 | 8 | main() 9 | -------------------------------------------------------------------------------- /chap03/change.py: -------------------------------------------------------------------------------- 1 | # A Program to calculate the value of some change in dollars 2 | 3 | def main(): 4 | print("Change Counter") 5 | print() 6 | print("Please enter the count of each coin type.") 7 | quarters = eval(input("Quarters: ")) 8 | dimes = eval(input("Dimes: ")) 9 | nickels = eval(input("Nickels: ")) 10 | pennies = eval(input("Pennies: ")) 11 | total = quarters * .25 + dimes * .10 + nickels * .05 + pennies * .01 12 | print() 13 | print("The total value of your change is", total) 14 | 15 | main() 16 | -------------------------------------------------------------------------------- /chap03/discus4.py: -------------------------------------------------------------------------------- 1 | for i in range(1,11): 2 | print(i*i) 3 | 4 | for i in [1,3,5,7,9]: 5 | print(i, ":", i**3) 6 | 7 | x = 2 8 | y = 10 9 | for j in range (0, y, x): 10 | print(j, end=" ") 11 | 12 | ans = 0 13 | for i in range(1, 11): 14 | ans = ans + i*i 15 | print(i) 16 | print(ans) 17 | -------------------------------------------------------------------------------- /chap03/exercise_10.py: -------------------------------------------------------------------------------- 1 | import math as m 2 | def main(): 3 | height, angle = eval(input("What is the height of the house in ft, and the angle of the ladder in degrees? ")) 4 | length = height / (m.sin((m.pi / 180 * angle))) 5 | print("The ladder must be", round(length, 2), "ft in length") 6 | 7 | main() 8 | -------------------------------------------------------------------------------- /chap03/exercise_11.py: -------------------------------------------------------------------------------- 1 | #Sum of the first n natural numbers 2 | def main(): 3 | n = eval(input("What is the value of n? ")) 4 | sum = 1 5 | for factor in range (2, n+1): 6 | sum = sum + factor 7 | print("The sum of of the first", n, "natural numbers is", sum) 8 | 9 | main() 10 | -------------------------------------------------------------------------------- /chap03/exercise_12.py: -------------------------------------------------------------------------------- 1 | #Sum of the cubes of the first n natural numbers 2 | def main(): 3 | n = eval(input("What is the value of n? ")) 4 | cube = 1 5 | for factor in range (2, n+1): 6 | cube = cube + factor ** 3 7 | print("The cube of the first", n, "natural numbers is", cube) 8 | 9 | main() 10 | -------------------------------------------------------------------------------- /chap03/exercise_13.py: -------------------------------------------------------------------------------- 1 | def main(): 2 | n = eval(input("How many numbers would you like to add? ")) 3 | x = eval(input(": ")) 4 | for factor in range (2, n+1): 5 | y = eval(input(": ")) 6 | x = x + y 7 | print("Your final sum is: ", x) 8 | 9 | main() 10 | -------------------------------------------------------------------------------- /chap03/exercise_14.py: -------------------------------------------------------------------------------- 1 | def main(): 2 | n = eval(input("How many numbers would you like to average? ")) 3 | x = eval(input(": ")) 4 | for factor in range (2, n+1): 5 | y = eval(input(": ")) 6 | x = float(x) + float(y) 7 | print("Your final average is: ", x / n) 8 | 9 | main() 10 | -------------------------------------------------------------------------------- /chap03/exercise_17.py: -------------------------------------------------------------------------------- 1 | import math as m 2 | 3 | def main(): 4 | x = eval(input("Enter a value: ")) 5 | y = eval(input("How many iterations of Newton's formula would you like?: ")) 6 | 7 | g = x / 2 8 | 9 | for i in range (y): 10 | g = (g + x / g) / 2 11 | print(g, ":", (g - m.sqrt(x))) 12 | main() 13 | 14 | -------------------------------------------------------------------------------- /chap03/exercise_2.py: -------------------------------------------------------------------------------- 1 | import math as m 2 | 3 | def main(): 4 | price, d = eval(input("Please enter the cost of the Pizza, and how big it was: ")) 5 | A = m.pi * ((.5 * d) ** 2) 6 | price_sqin = price / A 7 | print("The price per square inch is", round(price_sqin, 2)) 8 | 9 | main() 10 | -------------------------------------------------------------------------------- /chap03/exercise_3.py: -------------------------------------------------------------------------------- 1 | import math as m 2 | 3 | def main(): 4 | H, C, O = eval(input("Enter the number of Hydrogen, Carbon, and Oxygen atoms separated by commas: ")) 5 | mol_weight = H * 1.0079 + C * 12.011 + O * 15.9994 6 | print("The molecular weight of the hydrocarbon is", mol_weight, "g/mol") 7 | 8 | main() 9 | -------------------------------------------------------------------------------- /chap03/exercise_4.py: -------------------------------------------------------------------------------- 1 | #Input from user Time Elapsed 2 | #Process 1100 x Time, then divide distance traveled by 5280 3 | #output in miles 4 | def main(): 5 | time_elapsed = eval(input("How long was the time elapsed between flash and the sound of thunder? ")) 6 | miles = 1100 * time_elapsed / 5280 7 | print("Lightning struck", miles, "miles away.") 8 | 9 | main() 10 | -------------------------------------------------------------------------------- /chap03/exercise_5.py: -------------------------------------------------------------------------------- 1 | def main(): 2 | lbs = eval(input("How many pounds of coffee is in the order? ")) 3 | cost = (10.50 + .86) * lbs + 1.50 4 | print("Your order will cost a total of $", round(cost, 2)) 5 | 6 | main() 7 | -------------------------------------------------------------------------------- /chap03/exercise_6.py: -------------------------------------------------------------------------------- 1 | def main(): 2 | x1, y1 = eval(input("Enter the first point values of x,y: ")) 3 | x2, y2 = eval(input("Enter the second point values of x,y: ")) 4 | slope = (y2 - y1) / (x2 - x1) 5 | print("The slope of the line is", slope) 6 | main() 7 | -------------------------------------------------------------------------------- /chap03/exercise_7.py: -------------------------------------------------------------------------------- 1 | import math as m 2 | def main(): 3 | x1, y1 = eval(input("Enter the first point values of x,y: ")) 4 | x2, y2 = eval(input("Enter the second point values of x,y: ")) 5 | distance = m.sqrt((x2 - x1)**2 + (y2 - y1)**2) 6 | print("The distance between these two points is", distance) 7 | 8 | main() 9 | -------------------------------------------------------------------------------- /chap03/exercise_8.py: -------------------------------------------------------------------------------- 1 | import math as m 2 | 3 | def main(): 4 | year = eval(input("Input the 4 digit year")) 5 | C = year // 100 6 | epact = (8 + (C//4) - C + ((8 * C + 13) // 25) + 11 * (year % 19)) % 30 7 | print("the Gregorian Epact value is", epact) 8 | 9 | main() 10 | -------------------------------------------------------------------------------- /chap03/factorial.py: -------------------------------------------------------------------------------- 1 | def main(): 2 | n = eval(input("Please enter a whole number: ")) 3 | fact = 1 4 | for factor in range(n,1,-1): 5 | fact = fact * factor 6 | print("The factorial of", n, "is", fact) 7 | 8 | main() 9 | -------------------------------------------------------------------------------- /chap03/fibonacci.py: -------------------------------------------------------------------------------- 1 | import math as m 2 | def main(): 3 | n = eval(input("What number in the Fibonnaci sequence would you like to see?: ")) 4 | x = 1 5 | y = 0 6 | 7 | for i in range (n+1): 8 | z = x + y 9 | x = y 10 | y = z 11 | print(i, ":", y) 12 | main() 13 | -------------------------------------------------------------------------------- /chap03/quadratic.py: -------------------------------------------------------------------------------- 1 | # A program that computes the real roots of a quadratic equation. 2 | # Note: this program crashes if the equation has no real roots 3 | # ValueError: math domain error 4 | 5 | import math 6 | def main(): 7 | print("This program finds the real solutions to a quadratic") 8 | print() 9 | 10 | a, b, c = eval(input("Please enter the coefficients (a, b, c): " 11 | 12 | discRoot = math.sqrt(b * b - 4 * a * c) 13 | root1 = (-b + discRoot) / (2 * a) 14 | root2 = (-b - discRoot) / (2 * a) 15 | 16 | print() 17 | print("The solutions are:", root1, root2 ) 18 | 19 | main() 20 | -------------------------------------------------------------------------------- /chap03/vol_and_srfArea_of_sphere.py: -------------------------------------------------------------------------------- 1 | import math 2 | 3 | def main(): 4 | print("Given radius, this program will calculate the volume and\n","surface area of a sphere") 5 | r = (eval(input("Input a value for the radius: "))) 6 | V = 4/3 * math.pi * (r ** 3) 7 | A = 4 * math.pi * (r*r) 8 | print("A sphere with radius", r, "has volume", round(V, 3), "and surface area", round(A, 3),".") 9 | 10 | main() 11 | -------------------------------------------------------------------------------- /chap04/click.py: -------------------------------------------------------------------------------- 1 | from graphics import * 2 | 3 | def main(): 4 | win = GraphWin("Click me!") 5 | for i in range (10): 6 | p = win.getMouse() 7 | print("You clicked at:", p.getX(), ":", p.getY()) 8 | 9 | main() 10 | -------------------------------------------------------------------------------- /chap04/convert_gui.py: -------------------------------------------------------------------------------- 1 | #program to convert Celsius to Fahrenheit using 2 | #a simple graphical interface 3 | 4 | from graphics import * 5 | 6 | def main (): 7 | win = GraphWin("Celsius Converter", 400, 300) 8 | win.setCoords(0.0, 0.0, 3.0, 4.0) 9 | 10 | #Draw interface 11 | Text(Point(1,3), "Celsius Temperature:").draw(win) 12 | Text(Point(1,1), "Fahrenheit Temperature:").draw(win) 13 | input = Entry(Point(2,3), 5) 14 | input.setText("0.0") 15 | input.draw(win) 16 | output = Text(Point(2,1), "") 17 | output.draw(win) 18 | button = Text(Point(1.5,2.0), "Convert It") 19 | button.draw(win) 20 | Rectangle(Point(1,1.5), Point(2,2.5)).draw(win) 21 | 22 | #wait for mouse click 23 | win.getMouse() 24 | 25 | # convert input 26 | celsius = eval(input.getText()) 27 | fahrenheit = 9.0/5.0 * celsius + 32 28 | 29 | #display output and change button 30 | output.setText(fahrenheit) 31 | button.setText("Quit") 32 | 33 | #wait for click and then Quit 34 | win.getMouse() 35 | win.close() 36 | 37 | main() 38 | -------------------------------------------------------------------------------- /chap04/discuss3.py: -------------------------------------------------------------------------------- 1 | from graphics import * 2 | 3 | def main(): 4 | win = GraphWin() 5 | shape = Circle(Point(50,50),20) 6 | shape.setOutline("red") 7 | shape.setFill("red") 8 | shape.draw(win) 9 | for i in range(10): 10 | p = win.getMouse() 11 | c = shape.getCenter() 12 | dx = p.getX() - c.getX() 13 | dy = p.getY() - c.getY() 14 | shape.move(dx,dy) 15 | win.close() 16 | main() 17 | -------------------------------------------------------------------------------- /chap04/exercise_1.py: -------------------------------------------------------------------------------- 1 | from graphics import * 2 | 3 | def main(): 4 | win = GraphWin() 5 | win.setCoords(0.0, 0.0, 10.0, 10.0) 6 | square = Rectangle(Point(4,4), Point(6,6)) 7 | square.setOutline("red") 8 | square.setFill("red") 9 | square.draw(win) 10 | for i in range(10): 11 | p = win.getMouse() 12 | c = square.getCenter() 13 | dx = p.getX() - c.getX() 14 | dy = p.getY() - c.getY() 15 | s2 = square.clone() 16 | s2.draw(win) 17 | s2.move(dx, dy) 18 | square = s2 19 | message = Text(Point(5,9),"Click anywhere to close") 20 | message.draw(win) 21 | win.getMouse() 22 | win.close() 23 | main() 24 | -------------------------------------------------------------------------------- /chap04/exercise_10.py: -------------------------------------------------------------------------------- 1 | from graphics import * 2 | import math as m 3 | 4 | def main(): 5 | win = GraphWin("Line Drawing Tool", 400, 400) 6 | win.setCoords(-10, -10, 10, 10) 7 | #Prompt the User for 3 mouse clicks 8 | message = Text(Point(-5, 8), "Click on 3 points to create a Triangle") 9 | message.draw(win) 10 | 11 | #Store coordinates in variables x1, x2 etc 12 | point1 = win.getMouse() 13 | point2 = win.getMouse() 14 | point3 = win.getMouse() 15 | x1 = point1.getX() 16 | x2 = point2.getX() 17 | y1 = point1.getY() 18 | y2 = point2.getY() 19 | x3 = point3.getX() 20 | y3 = point3.getY() 21 | #Calculate Perimeter 22 | a = m.sqrt((x2-x1)**2 + (y2-y1)**2) 23 | b = m.sqrt((x3-x1)**2 + (y3-y1)**2) 24 | c = m.sqrt((x3-x2)**2 + (y3-y2)**2) 25 | perimeter = a + b + c 26 | #Calculate Area 27 | s = perimeter/2 28 | area = m.sqrt(s*(s-a)*(s-b)*(s-c)) 29 | 30 | #Draw Rectangle 31 | line1 = Line(point1, point2) 32 | line1.draw(win) 33 | line2 = Line(point2, point3) 34 | line2.draw(win) 35 | line3 = Line(point3, point1) 36 | line3.draw(win) 37 | #Print the Perimeter and area of the rectangle 38 | message2 = Text(Point(-5, 7), ("The area of the triangle is", round(area, 2))) 39 | message2.draw(win) 40 | message3 = Text(Point(-5, 6), ("The perimeter of the triangle is", round(perimeter, 2))) 41 | message3.draw(win) 42 | 43 | main() 44 | -------------------------------------------------------------------------------- /chap04/exercise_2.py: -------------------------------------------------------------------------------- 1 | from graphics import * 2 | 3 | def main(): 4 | win = GraphWin() 5 | win.setCoords(0, 0, 10, 10) 6 | c = Circle(Point(5,5), 5) 7 | c.setOutline("green4") 8 | c.setFill("white") 9 | c.setWidth(5) 10 | c.draw(win) 11 | 12 | c2 = Circle(Point(5,5), 4) 13 | c2.setOutline("green4") 14 | c2.setFill("red") 15 | c2.setWidth(5) 16 | c2.draw(win) 17 | 18 | c3 = Circle(Point(5,5), 3) 19 | c3.setOutline("green4") 20 | c3.setFill("blue") 21 | c3.setWidth(5) 22 | c3.draw(win) 23 | 24 | c4 = Circle(Point(5,5), 2) 25 | c4.setOutline("green4") 26 | c4.setFill("black") 27 | c4.setWidth(5) 28 | c4.draw(win) 29 | 30 | c5 = Circle(Point(5,5), 1) 31 | c5.setOutline("green4") 32 | c5.setFill("white") 33 | c5.setWidth(5) 34 | c5.draw(win) 35 | main() 36 | -------------------------------------------------------------------------------- /chap04/exercise_3.py: -------------------------------------------------------------------------------- 1 | from graphics import * 2 | 3 | def main(): 4 | win = GraphWin("Face", 900, 900) 5 | win.setCoords(0,0,10,10) 6 | head = Oval(Point(1.5,0.75), Point(8.5,9.25)) 7 | head.draw(win) 8 | 9 | c = Circle(Point(4.1, 6.75), .75) 10 | c.draw(win) 11 | 12 | c2 = c.clone() 13 | c2.move(2, 0) 14 | c2.draw(win) 15 | 16 | mouth = Rectangle(Point(3,3),Point(7,4)) 17 | mouth.draw(win) 18 | 19 | teeth = Rectangle(Point(3,3), Point(3.5, 4)) 20 | teeth.draw(win) 21 | 22 | for i in range (7): 23 | t2 = teeth.clone() 24 | t2.move(.5, 0) 25 | t2.draw(win) 26 | teeth = t2 27 | 28 | lip = Line(Point(3,3.5), Point(7,3.5)) 29 | lip.draw(win) 30 | main() 31 | -------------------------------------------------------------------------------- /chap04/exercise_7.py: -------------------------------------------------------------------------------- 1 | from graphics import * 2 | import math as m 3 | 4 | def main(): 5 | #Create a square window and set coordinates -10,-10 to 10,10 6 | win = GraphWin("Intersection of a line through a Circle", 500,500) 7 | win.setCoords(-10, -10, 10, 10) 8 | 9 | #Input: Radius of the circle and the y-intercept of the line 10 | r = eval(input("What is the radius of the circle? ")) 11 | y = eval(input("Where does the line cross the y axis? ")) 12 | 13 | #Draw a circle centered at 0,0 14 | c = Circle(Point(0,0), r) 15 | c.draw(win) 16 | 17 | #Draw a horizontal line across the window with teh given y-intercept 18 | line = Line(Point(-10, y), Point(10, y)) 19 | line.draw(win) 20 | 21 | #Compute x 22 | x = m.sqrt(r**2 - y**2) 23 | 24 | #Print the two x values of intersection textually 25 | print(-x, x) 26 | 27 | #Print the two x values graphically 28 | x1 = Text(Point(-x, y + 2),-x) 29 | x2 = Text(Point(x, y + 2), x) 30 | x1.draw(win) 31 | x2.draw(win) 32 | 33 | 34 | 35 | main() 36 | -------------------------------------------------------------------------------- /chap04/exercise_8.py: -------------------------------------------------------------------------------- 1 | import math as m 2 | from graphics import * 3 | 4 | def main(): 5 | win = GraphWin("Line Drawing Tool", 400, 400) 6 | win.setCoords(-10, -10, 10, 10) 7 | #Prompt the User for 2 mouse clicks 8 | message = Text(Point(-5, 8), "Click on 2 points to create a line") 9 | message.draw(win) 10 | #Store coordinates in variables x1, x2 etc 11 | point1 = win.getMouse() 12 | point2 = win.getMouse() 13 | x1 = point1.getX() 14 | x2 = point2.getX() 15 | y1 = point1.getY() 16 | y2 = point2.getY() 17 | 18 | #Create a Line w/ midpoint "cyan" 19 | line = Line(point1, point2) 20 | line.draw(win) 21 | mx, my = (x1+x2)/2, (y1+y2)/2 22 | win.plot(mx, my, "cyan") 23 | 24 | #Calculate the length and slope of the Line 25 | length = m.sqrt((x2 - x1)**2 + (y2 - y1)**2) 26 | slope = (y2-y1)/(x2 -x1) 27 | #Print length and slope of line 28 | message2 = Text(Point(-5, 7), ("The length of the line is: ", round(length, 2))) 29 | message2.draw(win) 30 | message3 = Text(Point(-5, 6), ("The slope of the line is: ", round(slope, 2))) 31 | message3.draw(win) 32 | 33 | main() 34 | -------------------------------------------------------------------------------- /chap04/exercise_9.py: -------------------------------------------------------------------------------- 1 | from graphics import * 2 | 3 | def main(): 4 | win = GraphWin("Line Drawing Tool", 400, 400) 5 | win.setCoords(-10, -10, 10, 10) 6 | #Prompt the User for 2 mouse clicks 7 | message = Text(Point(-5, 8), "Click on 2 points to create a Rectangle") 8 | message.draw(win) 9 | 10 | #Store coordinates in variables x1, x2 etc 11 | point1 = win.getMouse() 12 | point2 = win.getMouse() 13 | x1 = point1.getX() 14 | x2 = point2.getX() 15 | y1 = point1.getY() 16 | y2 = point2.getY() 17 | #Calculate Perimeter and Area 18 | area = (x2 - x1)*(y2 - y1) 19 | perimeter = 2 * ((x2-x1)+(y2-y1)) 20 | #Draw Rectangle 21 | r = Rectangle(point1, point2) 22 | r.draw(win) 23 | #Print the Perimeter and area of the rectangle 24 | message2 = Text(Point(-5, 7), ("The area of the rectangle is", round(area, 2))) 25 | message2.draw(win) 26 | message3 = Text(Point(-5, 6), ("The perimeter of the rectangle is", round(perimeter, 2))) 27 | message3.draw(win) 28 | 29 | main() 30 | -------------------------------------------------------------------------------- /chap04/futval_graph.py: -------------------------------------------------------------------------------- 1 | from graphics import * 2 | 3 | def main(): 4 | #Introduction 5 | print("This program plots the growth of a 10-year investment.") 6 | 7 | #Get principal and interest rate 8 | principal = eval(input("Enter the initial principal: ")) 9 | apr = eval(input("Enter the annual interest rate: ")) 10 | 11 | #Create a graphics window with laels on the left edge 12 | win = GraphWin("Investment Growth Chart", 320, 240) 13 | win.setBackground("white") 14 | Text(Point(20, 230), ' 0.0K').draw(win) 15 | Text(Point(20, 180), ' 2.5K').draw(win) 16 | Text(Point(20, 130), ' 5.0K').draw(win) 17 | Text(Point(20, 80), ' 7.5K').draw(win) 18 | Text(Point(20, 30), '10.0K').draw(win) 19 | 20 | #Draw bar for intial principal 21 | height = principal * 0.02 22 | bar = Rectangle(Point(40, 230), Point(65, 230-height)) 23 | bar.setFill("green") 24 | bar.setWidth(2) 25 | bar.draw(win) 26 | 27 | 28 | for year in range (1,11): 29 | #Calculate value for the next year 30 | principal = principal * (1 + .01 * apr) 31 | #draw bar for this value 32 | x11 = year * 25 + 40 33 | height = principal * 0.02 34 | bar = Rectangle(Point(x11, 230), Point(x11+25, 230-height)) 35 | bar.setFill("Green") 36 | bar.setWidth(2) 37 | bar.draw(win) 38 | 39 | input("Press to quit") 40 | win.close() 41 | 42 | main() 43 | 44 | 45 | main() 46 | -------------------------------------------------------------------------------- /chap04/futval_graph2.py: -------------------------------------------------------------------------------- 1 | from graphics import * 2 | 3 | def main(): 4 | #Introduction 5 | print("This program plots the growth of a 10-year investment.") 6 | 7 | #Get principal and interest rate 8 | principal = eval(input("Enter the initial principal: ")) 9 | apr = eval(input("Enter the annual interest rate: ")) 10 | 11 | #Create a graphics window with laels on the left edge 12 | win = GraphWin("Investment Growth Chart", 320, 240) 13 | win.setBackground("white") 14 | win.setCoords(-1.75, -200, 11.5, 10400.0) 15 | Text(Point(-1, 0), ' 0.0K').draw(win) 16 | Text(Point(-1, 2500), ' 2.5K').draw(win) 17 | Text(Point(-1, 5000), ' 5.0K').draw(win) 18 | Text(Point(-1, 7500), ' 7.5K').draw(win) 19 | Text(Point(-1, 10000), '10.0K').draw(win) 20 | 21 | #Draw bar for intial principal 22 | height = principal * 0.02 23 | bar = Rectangle(Point(0, 0), Point(1, principal)) 24 | bar.setFill("green") 25 | bar.setWidth(2) 26 | bar.draw(win) 27 | 28 | 29 | for year in range (1,11): 30 | #Calculate value for the next year 31 | principal = principal * (1 + .01 * apr) 32 | #draw bar for this value 33 | x11 = year * 25 + 40 34 | height = principal * 0.02 35 | bar = Rectangle(Point(year, 0), Point(year+1, principal)) 36 | bar.setFill("Green") 37 | bar.setWidth(2) 38 | bar.draw(win) 39 | 40 | input("Press to quit") 41 | win.close() 42 | 43 | main() 44 | 45 | 46 | -------------------------------------------------------------------------------- /chap04/triangle.py: -------------------------------------------------------------------------------- 1 | from graphics import * 2 | 3 | def main(): 4 | win = GraphWin("Draw a Triangle") 5 | win.setCoords(0.0, 0.0, 10.0, 10.0) 6 | message = Text(Point(5, 0.5), "Click on three points") 7 | message.draw(win) 8 | p1 = win.getMouse() 9 | p1.draw(win) 10 | p2 = win.getMouse() 11 | p2.draw(win) 12 | p3 = win.getMouse() 13 | p3.draw(win) 14 | triangle = Polygon(p1, p2, p3) 15 | triangle.setFill("peachpuff") 16 | triangle.setOutline("cyan") 17 | triangle.draw(win) 18 | 19 | message.setText("click anywhere to quit.") 20 | win.getMouse() 21 | 22 | main() 23 | -------------------------------------------------------------------------------- /chap05/change2.py: -------------------------------------------------------------------------------- 1 | def main(): 2 | print("Change Counter\n") 3 | 4 | print("Please enter the count of each coin type.") 5 | quarters = eval(input("Quarters: ")) 6 | dimes = eval(input("Dimes: ")) 7 | nickels = eval(input("Nickels: ")) 8 | pennies = eval(input("Pennies: ")) 9 | 10 | total = quarters * .25 + dimes * .10 + nickels * .05 + pennies * .01 11 | 12 | print("The total value of your change is ${0}.{1:0>2}".format(total//100, total%100)) 13 | 14 | main() 15 | -------------------------------------------------------------------------------- /chap05/dateconvert.py: -------------------------------------------------------------------------------- 1 | def main(): 2 | #get the date 3 | dateStr = input("Enter a date (mm/dd/yyy): ") 4 | 5 | #split into components 6 | monthStr, dayStr, yearStr = dateStr.split("/") 7 | 8 | #convert monthStr to the month name 9 | months = ["January", "February", "March", "April", "May", "June", 10 | "July", "August", "September", "October", "November", "December"] 11 | monthStr = months[int(monthStr)-1] 12 | 13 | #output 14 | print("The converted date is:", monthStr, dayStr+",", yearStr) 15 | 16 | main() 17 | -------------------------------------------------------------------------------- /chap05/dateconvert2.py: -------------------------------------------------------------------------------- 1 | def main(): 2 | #get the date 3 | day, month, year = eval(input("Enter a day, month, and year in numbers: ")) 4 | 5 | date1 = str(month)+"/"+str(day)+"/"+str(year) 6 | 7 | months = ["January", "February", "March", "April", "May", "June", 8 | "July", "August", "September", "October", "November", "December"] 9 | 10 | monthStr = months[month-1] 11 | date2 = monthStr+" " + str(day) + ", " + str(year) 12 | 13 | #output 14 | print("The converted date is", date1, "or", date2+".") 15 | 16 | main() 17 | -------------------------------------------------------------------------------- /chap05/exercise_1.py: -------------------------------------------------------------------------------- 1 | def main(): 2 | #get the date 3 | day, month, year = eval(input("Enter a day, month, and year in numbers: ")) 4 | 5 | months = ["January", "February", "March", "April", "May", "June", 6 | "July", "August", "September", "October", "November", "December"] 7 | 8 | monthStr = months[month-1] 9 | 10 | #output 11 | print("The converted date is {1}/{0}/{2}, or {3} {0},{2}").format(day, month, year, monthStr) 12 | 13 | main() 14 | -------------------------------------------------------------------------------- /chap05/exercise_10.py: -------------------------------------------------------------------------------- 1 | #word count 2 | def main(): 3 | text = input("Input: \n") 4 | 5 | #initialize output list 6 | numWords = [] 7 | 8 | #loop for duration of input list split 9 | for string in text.split(): 10 | #create a temporary variable to store the first 11 | #letter of each word 12 | x = string[0] 13 | numWords.append(x) 14 | 15 | letTotal = 0 16 | for string in text.split(): 17 | letTotal = len(string) + letTotal 18 | wordAvg = letTotal / (len(numWords)) 19 | #conjoin listed output strings and print 20 | print(wordAvg) 21 | 22 | main() 23 | -------------------------------------------------------------------------------- /chap05/exercise_11.py: -------------------------------------------------------------------------------- 1 | def main(): 2 | print("This Program ilustrates a chaotic function") 3 | 4 | #n = eval(input("How many numbers should I print? ")) 5 | #x, y = eval(input("Enter 2 values between 0 and 1 separated by a comma: ")) 6 | n = 10 7 | x = .25 8 | y = .26 9 | 10 | print("Index {0:>9}{1:>10}".format(x, y)) 11 | print("--------------------") 12 | for i in range(n): 13 | x = 3.9 * x - 3.9 * x * x 14 | y = 3.9 * y - 3.9 * y * y 15 | print("{2:^3}{0:>12.5f}{1:>10.5f}".format(x, y, (i+1))) 16 | 17 | main() 18 | -------------------------------------------------------------------------------- /chap05/exercise_12.py: -------------------------------------------------------------------------------- 1 | def main(): 2 | print("This program calculates the future value\n", "of a 10-year investment.") 3 | #principal = eval(input("Enter the initial principal: ")) 4 | #apr = eval(input("Enter the annual interest rate: ")) 5 | 6 | principal = 900 7 | apr = 5 8 | 9 | print("{0:<} {1:>10}".format("Year", "Value")) 10 | print("----------------") 11 | 12 | for i in range (10): 13 | principal = principal * (1 + .01 * apr) 14 | 15 | print("{0:>2} ${1:<}.{2:0^2}".format(i+1, int(principal), int(principal%1 * 100))) 16 | 17 | main() 18 | -------------------------------------------------------------------------------- /chap05/exercise_13.py: -------------------------------------------------------------------------------- 1 | #word count 2 | def main(): 3 | fname = input("Enter filename: ") 4 | infile = open(fname, "r") 5 | data = infile.read() 6 | 7 | #initialize output list 8 | numWords = [] 9 | 10 | #loop for duration of input list split 11 | for string in data.split(): 12 | #create a temporary variable to store the first 13 | #letter of each word 14 | x = string[0] 15 | numWords.append(x) 16 | 17 | letTotal = 0 18 | for string in data.split(): 19 | letTotal = len(string) + letTotal 20 | wordAvg = letTotal / (len(numWords)) 21 | #conjoin listed output strings and print 22 | print("The Avg word lenth is {0}".format(wordAvg)) 23 | print("The total number of letters is {0}".format(letTotal)) 24 | print("The number of words is {0}".format(len(numWords))) 25 | main() 26 | -------------------------------------------------------------------------------- /chap05/exercise_14.py: -------------------------------------------------------------------------------- 1 | #This program calculates avg word length, counts lines, total characters, and total words 2 | def main(): 3 | fname = input("Enter filename: ") 4 | infile = open(fname, "r") 5 | data = infile.read() 6 | 7 | 8 | #initialize output list 9 | numWords = [] 10 | letTotal = 0 11 | #loop for duration of input list split 12 | for string in data.split(): 13 | #create a temporary variable to store the first 14 | #letter of each word 15 | x = string[0] 16 | numWords.append(x) 17 | letTotal = len(string) + letTotal 18 | wordAvg = letTotal / (len(numWords)) 19 | infile.close() 20 | 21 | infile = open(fname, "r") 22 | fileLines = infile.readlines() 23 | 24 | lines = [] 25 | for line in fileLines: 26 | lines.append(line) 27 | print("There are {0} lines in the file.".format(len(lines))) 28 | 29 | #conjoin listed output strings and print 30 | print("The avg word length is {0}".format(wordAvg)) 31 | print("The total number of letters is {0}".format(letTotal)) 32 | print("The number of words is {0}".format(len(numWords))) 33 | infile.close() 34 | main() 35 | -------------------------------------------------------------------------------- /chap05/exercise_15.py: -------------------------------------------------------------------------------- 1 | #This program plots student exam scores on a horizontal bar chart 2 | #open student_test.txt 3 | from graphics import * 4 | def main(): 5 | fname = input("Enter filename: ") 6 | infile = open(fname, "r") 7 | 8 | #grab number of students and assign to numStud 9 | numStud = int(infile.readline()) 10 | 11 | #grab name and grade and assign to lists studName and grade 12 | studName = [] 13 | grade = [] 14 | lines = [] 15 | for line in infile.readlines(): 16 | x, y = line.split(": ") 17 | #strip \n 18 | y = y[0:-1] 19 | studName.append(x) 20 | grade.append(y) 21 | 22 | print(studName) 23 | print(grade) 24 | 25 | #initialize graphWin of size 400, (100 x numStud) 26 | win = GraphWin("Student Grade Chart", 400, 50 * numStud) 27 | 28 | #setCoords: -10, 0, 100, (10 x (numStud + 2)) 29 | win.setCoords(-30, (10 * numStud + 2), 120, 0) 30 | 31 | #draw text studName 32 | for i in range (numStud): 33 | s = studName[i].rjust(10) 34 | Text(Point(-20, 15 + numStud * .8 * i), s).draw(win) 35 | #draw Rectangle and clone 36 | for i in range (numStud): 37 | r = Rectangle(Point(0, 13 + numStud * .8 *i), Point(grade[i], 17 + numStud * .8 * i)) 38 | r.draw(win) 39 | #close file 40 | infile.close() 41 | main() 42 | -------------------------------------------------------------------------------- /chap05/exercise_16.py: -------------------------------------------------------------------------------- 1 | #this program draws a quiz score histogram 2 | from graphics import * 3 | 4 | def main(): 5 | #read file from disk 6 | fname = input("Enter filename: ") 7 | infile = open(fname, "r") 8 | 9 | #create 11 items in List as accumulator variable for scores 0-10 10 | scores = [0,0,0,0,0,0,0,0,0,0,0] 11 | 12 | #for counting total students 13 | students = 0 14 | 15 | #loop through each line and use list index as counter for 16 | #each scores number 17 | for line in infile.readlines(): 18 | scores[int(line)] = scores[int(line)]+1 19 | students = students + 1 20 | 21 | #draw a bar graph to represent each occurance of possible scores 22 | height = max(scores) 23 | 24 | # 1 Coord = 10px 25 | # each score bar height increse 10px too. 26 | win = GraphWin('Quiz Histogram', 640, 480) 27 | win.setCoords(0, 0, 35, height * 1.5) 28 | 29 | #show total students 30 | students = 'Total Students: '+str(students) 31 | 32 | totalStudent = Text(Point(8,.1 * height), students) 33 | totalStudent.draw(win) 34 | 35 | pos = 2 36 | hgt = .2 * height 37 | for i in range(11): 38 | bar = Rectangle(Point(pos, hgt),Point(pos + 2, scores[i] + hgt)) 39 | bar.setFill('red') 40 | bar.draw(win) 41 | 42 | pos = pos+3 43 | 44 | #bar number 0-10 45 | position = 3 46 | hgt = .1 * height + 1 47 | for i in range(11): 48 | Text(Point(position, hgt), i).draw(win) 49 | position = position + 3 50 | 51 | win.getMouse() 52 | win.close() 53 | 54 | 55 | infile.close() 56 | 57 | main() 58 | -------------------------------------------------------------------------------- /chap05/exercise_2.py: -------------------------------------------------------------------------------- 1 | def main(): 2 | #receive grade from teacher in number format 3 | n = eval(input("Enter a grade with no separation. ")) 4 | 5 | #create a list that associates numbers 5-0 with grades A-F 6 | grade = ["F", "F", "D", "C", "B", "A"] 7 | 8 | #print results using string formatting 9 | print(grade[n]) 10 | 11 | main() 12 | -------------------------------------------------------------------------------- /chap05/exercise_3.py: -------------------------------------------------------------------------------- 1 | def main(): 2 | for i in range (10): 3 | #receive grade from teacher in number format 4 | n = (eval(input("Enter a number grade: "))) 5 | 6 | #Use the append method to assign variables to values 7 | grade = [] 8 | for x in range(0, 60): 9 | grade.append("F") 10 | for x in range(60, 70): 11 | grade.append("D") 12 | for x in range(70, 80): 13 | grade.append("C") 14 | for x in range(80, 90): 15 | grade.append("B") 16 | for x in range(90, 300): 17 | grade.append("A") 18 | 19 | #print results 20 | print(grade[n]) 21 | 22 | main() 23 | -------------------------------------------------------------------------------- /chap05/exercise_4.py: -------------------------------------------------------------------------------- 1 | def main(): 2 | print("This program creates acronyms from user input.") 3 | 4 | #get input from user 5 | title = input("What would you like acronymized? \n") 6 | 7 | #initialize output list 8 | words = [] 9 | 10 | #loop for duration of input list split 11 | for string in title.split(): 12 | #create a temporary variable to store the first 13 | #letter of each word in upper case 14 | x = string[0].upper() 15 | words.append(x) 16 | 17 | #conjoin listed output strings and print 18 | acro = "".join(words) 19 | print(acro) 20 | 21 | main() 22 | -------------------------------------------------------------------------------- /chap05/exercise_5.py: -------------------------------------------------------------------------------- 1 | def main(): 2 | #Get name from user and store as a string 3 | name = input("What is your name? \n") 4 | 5 | #Convert to all lower 6 | name = name.lower() 7 | 8 | #Convert to numbers, subtract 96 from each, and accumulate 9 | x = 0 10 | for ch in name: 11 | x = int(ord(ch)) + x - 96 12 | 13 | print("The numeric value of your name is {0}.".format(x)) 14 | 15 | main() 16 | -------------------------------------------------------------------------------- /chap05/exercise_6.py: -------------------------------------------------------------------------------- 1 | def main(): 2 | #Get name from user and store as a string 3 | name = input("What is your name? \n") 4 | 5 | #Convert to all lower, and account for user input 6 | fullName = "".join(name) 7 | fullName = fullName.lower() 8 | fullName = fullName.lstrip() 9 | fullName = fullName.replace(" ", "`") 10 | fullName = fullName.replace("-", "`") 11 | 12 | #Convert to numbers, subtract 96 from each, and accumulate 13 | x = 0 14 | for ch in fullName: 15 | x = int(ord(ch)) + x - 96 16 | 17 | print("The numeric value of your name is {0}.".format(x)) 18 | 19 | main() 20 | -------------------------------------------------------------------------------- /chap05/exercise_7.py: -------------------------------------------------------------------------------- 1 | def main(): 2 | 3 | #Get plaintext(p_text) and key(x) from the user 4 | p_text = input("Enter the message you'd like encrypted.\n") 5 | key = eval(input("What's the key? : ")) 6 | 7 | #Create string from list 8 | #p_text = "".join(inputText) 9 | 10 | #Convert plaintext to ciphertext(c_text) using cipher loop 11 | c_text = "" 12 | for ch in p_text: 13 | c_text = c_text + (chr(ord(ch) + key)) 14 | 15 | print("Your encoded message is {0}.".format(c_text)) 16 | 17 | main() 18 | -------------------------------------------------------------------------------- /chap05/exercise_8.py: -------------------------------------------------------------------------------- 1 | def main(): 2 | 3 | #Get plaintext(p_text) and key(x) from the user 4 | p_text = input("Enter the message you'd like encrypted.\n") 5 | key = eval(input("What's the key? : ")) 6 | 7 | p_text = p_text.lower() 8 | 9 | #Create string of letters 10 | table = "abcdefghijklmnopqrstuvwxyz" 11 | 12 | #Convert plaintext to ciphertext(c_text) using cipher loop 13 | c_text = "" 14 | for ch in p_text: 15 | c_text = c_text + (table[((ord(ch)) - 97) + key % 52]) 16 | 17 | print("Your encoded message is {0}.".format(c_text)) 18 | 19 | main() 20 | -------------------------------------------------------------------------------- /chap05/exercise_8x.py: -------------------------------------------------------------------------------- 1 | #improved Caesar cipher 2 | def main(): 3 | 4 | #Get plaintext(p_text) and key(x) from the user 5 | p_text = input("Enter the message you'd like encrypted.\n") 6 | key = eval(input("What's the key? : ")) 7 | 8 | #Create string of letters 9 | table = "abcdefghijklmnopqrstuvwxyz" 10 | 11 | #initialize output list 12 | c_text = [] 13 | 14 | #loop for duration of input list split 15 | for c_string in p_text.split(" "): 16 | #create a temporary variable to store each c_text word (c_string) 17 | #Convert plaintext to ciphertext(c_text) using cipher loop 18 | x = c_string + (table[((ord(ch)) - 97) + key % 52]) 19 | #compile new list c_text 20 | c_text.append(c_string) 21 | print(c_text) 22 | #Convert plaintext to ciphertext(c_text) using cipher loop 23 | c_text = "" 24 | for ch in p_text: 25 | c_text = c_text + (table[((ord(ch)) - 97) + key % 52]) 26 | 27 | print("Your encoded message is {0}.".format(c_text)) 28 | 29 | main() 30 | -------------------------------------------------------------------------------- /chap05/exercise_9.py: -------------------------------------------------------------------------------- 1 | #word count 2 | def main(): 3 | text = input("Input: \n") 4 | 5 | #initialize output list 6 | word_len = [] 7 | 8 | #loop for duration of input list split 9 | for string in text.split(): 10 | #create a temporary variable to store the first 11 | #letter of each word 12 | x = string[0] 13 | word_len.append(x) 14 | 15 | #conjoin listed output strings and print 16 | print(len(word_len)) 17 | 18 | main() 19 | -------------------------------------------------------------------------------- /chap05/month.py: -------------------------------------------------------------------------------- 1 | def main(): 2 | #months is used as a lookup table 3 | months = "JanFebMarAprMayJunJulAugSepOctNovDec" 4 | 5 | n = eval(input("Enter a month number (1-12): ")) 6 | 7 | #compute starting position of month n in months 8 | pos = (n-1) * 3 9 | 10 | #Grab the appropriate slice from months 11 | monthAbbrev = months [pos:pos+3] 12 | 13 | #print the result 14 | print("The month abbreviation is", monthAbbrev + ".") 15 | 16 | main() 17 | -------------------------------------------------------------------------------- /chap05/month2.py: -------------------------------------------------------------------------------- 1 | def main(): 2 | #months is a list used as a lookup table 3 | months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", 4 | "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"] 5 | 6 | n = eval(input("Enter a month number (1-12): ")) 7 | 8 | print("The month abbreviation is", months[n-1] + ".") 9 | 10 | main() 11 | -------------------------------------------------------------------------------- /chap05/notes.py: -------------------------------------------------------------------------------- 1 | print("The total value of your change is ${0}.{1:0>2}".format(total//100, total%100)) 2 | 3 | #Strings variables can be split into smaller string variables 4 | #get the date 5 | dateStr = input("Enter a date (mm/dd/yyy): ") 6 | 7 | #split into components 8 | monthStr, dayStr, yearStr = dateStr.split("/") 9 | 10 | #accumulation loop for Unicode values 11 | x = 0 12 | 13 | for ch in "zelle": 14 | x = int(ord(ch)) + x -96 15 | print(x) 16 | 17 | #for separating a letter 18 | msg = "" 19 | for s in "secret".split("e"): 20 | msg = msg + s 21 | print(msg) 22 | 23 | #for Caesar cipher 24 | for ch in strExample: 25 | cipher = (chr(ord(ch)+x)) 26 | #Use the append method to assign variables to values 27 | grade = [] 28 | for x in range(0, 60): 29 | grade.append("F") 30 | for x in range(60, 70): 31 | grade.append("D") 32 | for x in range(70, 80): 33 | grade.append("C") 34 | for x in range(80, 90): 35 | grade.append("B") 36 | for x in range(90, 300): 37 | grade.append("A") 38 | # 39 | -------------------------------------------------------------------------------- /chap05/numbers2text.py: -------------------------------------------------------------------------------- 1 | def main(): 2 | print("This program converts a sequence of Unicode numbers into") 3 | print("the string of text that it represents. \n") 4 | 5 | #Get the message to encode 6 | inString = input("Please enter the Unicode-encoded message: ") 7 | 8 | #Loop through each substring and build Unicode message 9 | message = "" 10 | for numStr in inString.split(): 11 | codeNum = eval(numStr) #convert digits to a number 12 | message = message + chr(codeNum) #concatentate character to message 13 | 14 | print("\nThe decoded message is:", message) 15 | 16 | main() 17 | -------------------------------------------------------------------------------- /chap05/numbers2text2.py: -------------------------------------------------------------------------------- 1 | def main(): 2 | print("This program converts a sequence of Unicode numbers into") 3 | print("the string of text that it represents. \n") 4 | 5 | #Get the message to encode 6 | inString = input("Please enter the Unicode-encoded message: ") 7 | 8 | #Loop through each substring and build Unicode message 9 | chars = [] 10 | for numStr in inString.split(): 11 | codeNum = eval(numStr) #convert digits to a number 12 | chars.append(chr(codeNum)) #accumulate new character 13 | 14 | message = "".join(chars) 15 | print("\nThe decoded message is:", message) 16 | 17 | main() 18 | -------------------------------------------------------------------------------- /chap05/scores.txt: -------------------------------------------------------------------------------- 1 | 0 2 | 10 3 | 3 4 | 5 5 | 8 6 | 3 7 | 4 8 | 5 9 | 6 10 | 7 11 | 1 12 | 2 13 | 9 14 | 0 15 | 10 16 | 3 17 | 5 18 | 8 19 | 3 20 | 4 21 | 5 22 | 6 23 | 7 24 | 1 25 | 2 26 | 9 27 | 0 28 | 10 29 | 3 30 | 5 31 | 8 32 | 3 33 | 4 34 | 5 35 | 6 36 | 7 37 | 1 38 | 2 39 | 9 40 | -------------------------------------------------------------------------------- /chap05/sean_test.txt: -------------------------------------------------------------------------------- 1 | sean sean sean sean sean 2 | sean sean sean sean sean 3 | sean sean sean sean sean 4 | sean sean sean sean sean 5 | sean sean sean sean sean 6 | sean sean sean sean sean 7 | -------------------------------------------------------------------------------- /chap05/student_test.txt: -------------------------------------------------------------------------------- 1 | 11 2 | Kim: 85 3 | Jeffrey: 93 4 | Becca: 53 5 | Tina: 100 6 | Sean: 23 7 | Alex: 75 8 | Fred: 69 9 | Michael: 88 10 | Amanda: 93 11 | Maryann: 34 12 | John: 28 13 | -------------------------------------------------------------------------------- /chap05/test.py: -------------------------------------------------------------------------------- 1 | infile = open("sean_test.txt", "r") 2 | 3 | lines = [] 4 | for line in infile.readlines(): 5 | lines.append(line) 6 | print(len(lines)) 7 | -------------------------------------------------------------------------------- /chap05/text2numbers.py: -------------------------------------------------------------------------------- 1 | def main(): 2 | print("This program converts a textual message into a sequence") 3 | print("of numbers representing the Unicode encoding of the message.") 4 | 5 | message = input("Please enter the message to encode: ") 6 | 7 | print("\nHere are the Unicode codes:") 8 | 9 | for ch in message: 10 | print(ord(ch), end=" ") 11 | 12 | print() 13 | 14 | main() 15 | -------------------------------------------------------------------------------- /chap05/userfile.py: -------------------------------------------------------------------------------- 1 | #Program to create a file of usernames in batch mode 2 | 3 | def main(): 4 | print("This program creates a file of usernames from a") 5 | print("file of names.") 6 | 7 | #get the file names 8 | infileName = input("What file are the names in? ") 9 | outfileName = input("What file should the usernames go in? ") 10 | 11 | #open the files 12 | infile = open(infileName, "r") 13 | outfile = open(outfileName, "w") 14 | 15 | #process each line of the input files 16 | for line in infile: 17 | #get the first and last names from line 18 | first, last = line.split() 19 | #create usernames 20 | uname = (first[0]+last[:7]).lower() 21 | #write it to the output file 22 | print(uname, file=outfile) 23 | 24 | #close both files 25 | infile.close() 26 | outfile.close() 27 | 28 | print("Usernames have been written to", outfileName) 29 | 30 | main() 31 | -------------------------------------------------------------------------------- /chap05/username.py: -------------------------------------------------------------------------------- 1 | def main(): 2 | print("This program generates computer usernames. \n") 3 | 4 | #get user's first and last names 5 | first = input("Please enter your first name (all lowercase): ") 6 | last = input("Please enter your last name (all lowercase): ") 7 | 8 | #concatenate first initial with 7 chars of the last name. 9 | uname = first[0] + last[:7] 10 | 11 | #output the username 12 | print("Your username is:", uname) 13 | 14 | main() 15 | -------------------------------------------------------------------------------- /chap06/addinterest2.py: -------------------------------------------------------------------------------- 1 | def addInterest(balance, rate): 2 | newBalance = balance * (1 + .01 * rate) 3 | return newBalance 4 | 5 | def test(): 6 | amount = 1000 7 | rate = 5 8 | amount = addInterest(amount, rate) 9 | print(amount) 10 | 11 | test() 12 | -------------------------------------------------------------------------------- /chap06/addinterest3.py: -------------------------------------------------------------------------------- 1 | def addInterest(balances, rate): 2 | for i in range(len(balances)): 3 | balances[i] = balances[i] * (1 + rate) 4 | 5 | def test(): 6 | amounts = [1000, 2200, 800, 360] 7 | rate = 0.05 8 | addInterest(amounts, rate) 9 | print(amounts) 10 | 11 | test() 12 | -------------------------------------------------------------------------------- /chap06/drawBar.py: -------------------------------------------------------------------------------- 1 | from graphics import * 2 | 3 | def drawBar(window, year, height): 4 | #Draw a bar in window for given year with given height 5 | bar = Rectangle(Point(year, 0), Point(year+1, height)) 6 | bar.setFill("green") 7 | bar.setWidth(2) 8 | bar.draw(window) 9 | -------------------------------------------------------------------------------- /chap06/ex14test.txt: -------------------------------------------------------------------------------- 1 | 1 2 | 2 3 | 3 4 | 4 5 | 5 6 | -------------------------------------------------------------------------------- /chap06/exercise_1.py: -------------------------------------------------------------------------------- 1 | def oldMac(): 2 | print("Old MacDonald had a farm, Ee-igh, Ei-igh, Oh!") 3 | 4 | def animal(animal, sound): 5 | print("And on this farm he had a(n)", animal +", Ee-igh, Ee-igh, Oh!") 6 | print("With a(n)", sound + ",", sound, "here, and a(n)", sound+",", sound, "there.") 7 | print("Here a(n)", sound+",","there a(n)", sound + ",", "everywhere a(n)", sound+",", sound+".") 8 | 9 | def main(): 10 | oldMac() 11 | animal('pig', 'oink') 12 | oldMac() 13 | print() 14 | oldMac() 15 | animal('cow', 'moo') 16 | oldMac() 17 | print() 18 | oldMac() 19 | animal('chicken', 'cheep') 20 | oldMac() 21 | print() 22 | oldMac() 23 | animal('frog', 'ribbit') 24 | oldMac() 25 | print() 26 | oldMac() 27 | animal('goat', 'bah') 28 | oldMac() 29 | main() 30 | -------------------------------------------------------------------------------- /chap06/exercise_10.py: -------------------------------------------------------------------------------- 1 | def acronym(phrase): 2 | words = [] 3 | #loop for duration of input list split 4 | for string in phrase.split(): 5 | #create a temporary variable to store the first 6 | #letter of each word in upper case 7 | x = string[0].upper() 8 | words.append(x) 9 | 10 | #conjoin listed output strings and print 11 | acro = "".join(words) 12 | return acro 13 | def main(): 14 | phrase = input("What would you like acronymized? \n") 15 | x = acronym(phrase) 16 | print(x) 17 | main() 18 | -------------------------------------------------------------------------------- /chap06/exercise_11.py: -------------------------------------------------------------------------------- 1 | def squareEach(nums): 2 | for x in range (len(nums)): 3 | nums[x] = nums[x] ** 2 4 | return(nums) 5 | def test(): 6 | list = [1,2,3,4,5] 7 | y = squareEach(list) 8 | print(y) 9 | test() 10 | -------------------------------------------------------------------------------- /chap06/exercise_12.py: -------------------------------------------------------------------------------- 1 | def sumList(nums): 2 | y = 0 3 | for x in range (len(nums)): 4 | y = nums[x] + y 5 | return(y) 6 | def test(): 7 | list = [1,2,3,4,5] 8 | z = sumList(list) 9 | print(z) 10 | test() 11 | -------------------------------------------------------------------------------- /chap06/exercise_13.py: -------------------------------------------------------------------------------- 1 | def toNumbers(strList): 2 | for x in range (len(strList)): 3 | strList[x] = int(strList[x]) 4 | return(strList) 5 | def test(): 6 | list = ['1','2','3','4','5'] 7 | z = toNumbers(list) 8 | print(z) 9 | test() 10 | -------------------------------------------------------------------------------- /chap06/exercise_14.py: -------------------------------------------------------------------------------- 1 | def toNumbers(strList): 2 | for x in range (len(strList)): 3 | strList[x] = int(strList[x]) 4 | return(strList) 5 | 6 | def squareEach(nums): 7 | for x in range (len(nums)): 8 | nums[x] = nums[x] ** 2 9 | return(nums) 10 | 11 | 12 | def sumList(nums): 13 | y = 0 14 | for x in range (len(nums)): 15 | y = nums[x] + y 16 | return(y) 17 | 18 | def main(): 19 | fname = input("Enter filename: ") 20 | infile = open(fname, "r") 21 | 22 | lines = [] 23 | for line in infile.readlines(): 24 | lines.append(line) 25 | 26 | x = toNumbers(lines) 27 | y = squareEach(x) 28 | z = sumList(y) 29 | print(z) 30 | 31 | infile.close() 32 | main() 33 | -------------------------------------------------------------------------------- /chap06/exercise_17.py: -------------------------------------------------------------------------------- 1 | from graphics import * 2 | 3 | def moveTo(shape, newCenter, win): 4 | dx = oldCenter.getX() - newCenter.getX() 5 | dy = oldCenter.getY() - newCenter.getY() 6 | 7 | shape.move(dx, dy) 8 | #shape.draw(win) 9 | 10 | def main(): 11 | win = GraphWin("Move Shape", 400, 400) 12 | win.setCoords(0, 0, 100, 100) 13 | 14 | oldCenter = win.getMouse() 15 | shape = Circle(oldCenter, 3) 16 | shape.setOutline("red") 17 | shape.setFill("red") 18 | shape.draw(win) 19 | 20 | for i in range(10): 21 | newCenter = win.getMouse() 22 | moveTo(shape, newCenter, win) 23 | win.close() 24 | main() 25 | -------------------------------------------------------------------------------- /chap06/exercise_2.py: -------------------------------------------------------------------------------- 1 | 2 | def ants(): 3 | num = ['one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'ten'] 4 | rhyme = ['suck his thumb','tie his shoe','take a pee', 'shut the door','call the hive','pick up sticks', 'look to heaven','make a date', 'get outta line', 'sing it again'] 5 | for i in range (10): 6 | print("The ants go marching {0} by {0}, hurrah! hurrah!".format(str(num[i]))) 7 | print("The ants go marching {0} by {0}, hurrah! hurrah!".format(str(num[i]))) 8 | print("The ants go marching {0} by {0},".format(str(num[i]))) 9 | print("The little one stops to {0},".format(str(rhyme[i]))) 10 | print("And they all go marching down...") 11 | print("Into the ground...") 12 | print("To get out...") 13 | print("Of the rain.") 14 | print("Boom! Boom! Boom!") 15 | print() 16 | def main(): 17 | ants() 18 | main() 19 | -------------------------------------------------------------------------------- /chap06/exercise_3.py: -------------------------------------------------------------------------------- 1 | import math as m 2 | 3 | def sphereArea(radius): 4 | area = 4 * m.pi * (radius*radius) 5 | return area 6 | def sphereVolume(radius): 7 | volume = 4/3 * m.pi * (radius ** 3) 8 | return volume 9 | 10 | def main(): 11 | r = (eval(input("Input a value for the radius: "))) 12 | a = sphereArea(r) 13 | v = sphereVolume(r) 14 | print("A sphere with radius", r, "has volume", round(v, 3), "and surface area", round(a, 3),".") 15 | 16 | main() 17 | -------------------------------------------------------------------------------- /chap06/exercise_4.py: -------------------------------------------------------------------------------- 1 | def sumN(n): 2 | fact = 1 3 | for factor in range(n,1,-1): 4 | fact = fact + factor 5 | return fact 6 | def sumNCubes(n): 7 | cube = 1 8 | for factor in range(n,1,-1): 9 | cube = cube + factor ** 3 10 | return cube 11 | def main(): 12 | n = eval(input("Enter a value: ")) 13 | N = sumN(n) 14 | NCubes = sumNCubes(n) 15 | print("The sum of the first {0} natural numbers is {1}, and the sum of the\n" 16 | "sum of the first {0} cubes is {2}".format(n, N, NCubes)) 17 | 18 | main() 19 | -------------------------------------------------------------------------------- /chap06/exercise_5.py: -------------------------------------------------------------------------------- 1 | import math as m 2 | def pizzArea(diameter): 3 | area = m.pi * ((.5 * diameter) ** 2) 4 | return area 5 | def pizzPrice(cost, area): 6 | price_sqin = cost / area 7 | return price_sqin 8 | def main(): 9 | price, d = eval(input("Please enter the cost of the Pizza, and how big it was: ")) 10 | A = pizzArea(d) 11 | price_sqin = pizzPrice(price, A) 12 | print("The pizza has an area of {0} square inches".format(round(A, 2))) 13 | print("The price per square inch is about ${0}.".format(round(price_sqin, 2))) 14 | 15 | main() 16 | -------------------------------------------------------------------------------- /chap06/exercise_6.py: -------------------------------------------------------------------------------- 1 | import math as m 2 | def triangle(a, b, c): 3 | s = (a + b + c) / 2 4 | A = m.sqrt(s * (s-a) * (s-b) * (s-c)) 5 | return A 6 | 7 | def main(): 8 | a, b, c = eval(input("Input the 3 sides of the triangle, separated by commas: ")) 9 | A = triangle(a, b, c) 10 | print("The area of this triangle is: ", round(A, 2)) 11 | main() 12 | -------------------------------------------------------------------------------- /chap06/exercise_7.py: -------------------------------------------------------------------------------- 1 | import math as m 2 | def fibonnaci(n): 3 | x = 0 4 | y = 1 5 | z = 0 6 | 7 | for i in range (n+1): 8 | z = x + y 9 | x = y 10 | y = z 11 | return y 12 | 13 | def main(): 14 | n = eval(input("What number in the Fibonnaci sequence would you like to see?: ")) 15 | y = fibonnaci(n) 16 | print("The {0} Fibonnaci number is {1}.".format(n, y)) 17 | main() 18 | -------------------------------------------------------------------------------- /chap06/exercise_8.py: -------------------------------------------------------------------------------- 1 | import math as m 2 | 3 | def nextGuess(guess, x): 4 | g = (guess + x / guess) / 2 5 | return g 6 | 7 | def main(): 8 | x = eval(input("Find the square root of: ")) 9 | y = eval(input("How many iterations of Newton's formula would you like?: ")) 10 | g = x / 2 11 | for i in range (y): 12 | g = nextGuess(g, x) 13 | print(g) 14 | main() 15 | -------------------------------------------------------------------------------- /chap06/exercise_9.py: -------------------------------------------------------------------------------- 1 | def grade(score): 2 | grades = [] 3 | for x in range(0, 60): 4 | grades.append("F") 5 | for x in range(60, 70): 6 | grades.append("D") 7 | for x in range(70, 80): 8 | grades.append("C") 9 | for x in range(80, 90): 10 | grades.append("B") 11 | for x in range(90, 100): 12 | grades.append("A") 13 | return grades[score] 14 | def main(): 15 | n = (eval(input("Enter a number grade: "))) 16 | x = grade(n) 17 | print(x) 18 | main() 19 | -------------------------------------------------------------------------------- /chap06/futval_graph3*.py: -------------------------------------------------------------------------------- 1 | from graphics import * 2 | 3 | def drawBar(window, year, height): 4 | #Draw a bar in window for given year with given height 5 | bar = Rectangle(Point(year, 0), Point(year+1, height)) 6 | bar.setFill("green") 7 | bar.setWidth(2) 8 | bar.draw(window) 9 | 10 | def createLabeledWindow(): 11 | #Returns a GraphWin with title and labels drawn 12 | window = GraphWin("Investment Growth Chart", 320, 240) 13 | window.setBackground("white") 14 | window.setCoords(-1.75, -200, 11.5, 10400.0) 15 | Text(Point(-1, 0), ' 0.0K').draw(window) 16 | Text(Point(-1, 2500), ' 2.5K').draw(window) 17 | Text(Point(-1, 5000), ' 5.0K').draw(window) 18 | Text(Point(-1, 7500), ' 7.5K').draw(window) 19 | Text(Point(-1, 10000), '10.0K').draw(window) 20 | return window 21 | 22 | def main(): 23 | #Introduction 24 | print("This program plots the growth of a 10-year investment.") 25 | 26 | #Get principal and interest rate 27 | principal = eval(input("Enter the initial principal: ")) 28 | apr = eval(input("Enter the annual interest rate: ")) 29 | 30 | win = createLabeledWindow() 31 | 32 | #Draw bar for intial principal 33 | drawBar(win, 0, principal) 34 | for year in range(1,11): 35 | principal = principal * (1 + .01 * apr) 36 | drawBar(win, year, principal) 37 | 38 | input("Press to quit") 39 | win.close() 40 | 41 | main() 42 | -------------------------------------------------------------------------------- /chap06/happy.py: -------------------------------------------------------------------------------- 1 | def happy(): 2 | print("Happy Birthday to You!") 3 | 4 | def sing(person): 5 | happy() 6 | happy() 7 | print("Happy Birthday, dear", person + ".") 8 | happy() 9 | 10 | def main(): 11 | sing("Fred") 12 | print() 13 | sing("Lucy") 14 | print() 15 | sing("Elmer") 16 | 17 | main() 18 | -------------------------------------------------------------------------------- /chap06/test.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/drycode/zelle-python/ccd781784bf2a635d1f6e84ec2173d2ae7d50098/chap06/test.py -------------------------------------------------------------------------------- /chap06/test_img.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/drycode/zelle-python/ccd781784bf2a635d1f6e84ec2173d2ae7d50098/chap06/test_img.gif -------------------------------------------------------------------------------- /chap06/test_img.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/drycode/zelle-python/ccd781784bf2a635d1f6e84ec2173d2ae7d50098/chap06/test_img.jpg -------------------------------------------------------------------------------- /chap06/triangle2.py: -------------------------------------------------------------------------------- 1 | import math 2 | from graphics import * 3 | 4 | def square(x): 5 | return x * x 6 | 7 | def distance(p1, p2): 8 | dist = math.sqrt(square(p2.getX() - p1.getX()) 9 | + square(p2.getY() - p1.getY())) 10 | return dist 11 | import math as m 12 | def triArea(a, b, c): 13 | s = (a + b + c) / 2 14 | A = m.sqrt(s * (s-a) * (s-b) * (s-c)) 15 | return A 16 | 17 | def main(): 18 | win = GraphWin("Draw a Triangle") 19 | win.setCoords(0.0, 0.0, 10.0, 10.0) 20 | message = Text(Point(5, 0.5), "Click on three points") 21 | message.draw(win) 22 | 23 | #Get and draw three vertices of triangle 24 | p1 = win.getMouse() 25 | p1.draw(win) 26 | p2 = win.getMouse() 27 | p2.draw(win) 28 | p3 = win.getMouse() 29 | p3.draw(win) 30 | 31 | #Use Polygon object to draw the triangle 32 | triangle = Polygon(p1, p2, p3) 33 | triangle.setFill("peachpuff") 34 | triangle.setOutline("cyan") 35 | triangle.draw(win) 36 | 37 | #Calculate the perimeter of the Triangle 38 | perim = distance(p1, p2) + distance(p2, p3) + distance(p3, p1) 39 | message.setText("The perimeter is: {0:0.2f}".format(perim)) 40 | 41 | a = distance(p1, p2) 42 | b = distance(p2, p3) 43 | c = distance(p3, p1) 44 | 45 | A = triArea(a, b, c) 46 | message2 = Text(Point(5, 1.5), "The area is {0:0.2f}".format(A)) 47 | message2.draw(win) 48 | 49 | #Wait for another click to exit 50 | win.getMouse() 51 | win.close 52 | 53 | main() 54 | -------------------------------------------------------------------------------- /chap07/exercise_1.py: -------------------------------------------------------------------------------- 1 | def main(): 2 | x = 0 3 | while x <= 0: 4 | try: 5 | x, y = eval(input("How many hours worked, and how much per hour? ")) 6 | except NameError: 7 | print("Make sure to enter 2 numbers, separated by a comma") 8 | except TypeError: 9 | print("Make sure to enter 2 numbers, separated by a comma") 10 | except SyntaxError: 11 | print("Make sure to enter 2 numbers, separated by a comma") 12 | 13 | if x <= 40: 14 | pay = x * y 15 | else: 16 | pay = 40 * y 17 | pay = (x - 40) * 1.5 * y + pay 18 | print(pay) 19 | 20 | main() 21 | -------------------------------------------------------------------------------- /chap07/exercise_10.py: -------------------------------------------------------------------------------- 1 | def Easter(year): 2 | if 1900 <= year <= 2099: 3 | a = year % 19 4 | b = year % 4 5 | c = year % 7 6 | d = (19 * a + 24) % 30 7 | e = (2 * b + 4 * c + 6 * d + 5) % 7 8 | if (d + e) > 9: 9 | if year == 1954 or 1981 or 2049 or 2076: 10 | d = d - 7 11 | print("Easter falls on April {}.".format(d + e - 9)) 12 | else: 13 | print("Easter falls on April {}.".format(d + e - 9)) 14 | else: 15 | if year == 1954 or 1981 or 2049 or 2076: 16 | d = d - 7 17 | print("Easter falls on March {}.".format(22 + d + e)) 18 | else: 19 | print("Easter falls on March {}.".format(22 + d + e)) 20 | else: 21 | print("Year is out of range") 22 | 23 | 24 | def main(): 25 | #year = eval(input("Input a year: ")) 26 | year = 2049 27 | Easter(year) 28 | main() 29 | 30 | #1954, 1981, 2049, 2076 one week too late 31 | -------------------------------------------------------------------------------- /chap07/exercise_11.py: -------------------------------------------------------------------------------- 1 | #if year is divisible by 4, it's a leap years 2 | #unless it's a century year not divisible by 400 3 | #leap year yes or no 4 | 5 | def leapYear(year): 6 | if (year %4) != 0: 7 | print("{} is not a leap year.".format(year)) 8 | else: 9 | if (year % 100) == 0: 10 | if (year % 400) ==0: 11 | print("{} is a leap year.".format(year)) 12 | else: 13 | print("{} is not a leap year.".format(year)) 14 | else: 15 | print("{} is a leap year.".format(year)) 16 | 17 | 18 | def main(): 19 | year = 1900 20 | leapYear(year) 21 | main() 22 | -------------------------------------------------------------------------------- /chap07/exercise_12.py: -------------------------------------------------------------------------------- 1 | def leapYear(year): 2 | if (year % 4) != 0: 3 | return False 4 | else: 5 | if (year % 100) == 0: 6 | if (year % 400) ==0: 7 | return True 8 | else: 9 | return False 10 | else: 11 | return True 12 | 13 | def main(): 14 | dateStr = '6/29/1100' 15 | 16 | monthStr, dayStr, yearStr = dateStr.split("/") 17 | month = int(monthStr) 18 | day = int(dayStr) 19 | year = int(yearStr) 20 | 21 | if month > 12 or day > 31: 22 | print("This date is invalid.") 23 | else: 24 | if day <= 28: 25 | print("This date is valid.") 26 | elif month == 2 and day == 29: 27 | if leapYear(year) == False: 28 | print("This date is invalid.") 29 | else: 30 | print("This date is valid.") 31 | elif day == 31: 32 | if month == 2 or 4 or 6 or 11: 33 | print("This date is invalid") 34 | else: 35 | print("This date is valid") 36 | else: 37 | print("The date is valid.") 38 | main() 39 | -------------------------------------------------------------------------------- /chap07/exercise_14.py: -------------------------------------------------------------------------------- 1 | from graphics import * 2 | import math as m 3 | 4 | def main(): 5 | #Create a square window and set coordinates -10,-10 to 10,10 6 | win = GraphWin("Intersection of a line through a Circle", 500,500) 7 | win.setCoords(-10, -10, 10, 10) 8 | 9 | #Input: Radius of the circle and the y-intercept of the line 10 | r = eval(input("What is the radius of the circle? ")) 11 | y = eval(input("Where does the line cross the y axis? ")) 12 | 13 | #Draw a circle centered at 0,0 14 | c = Circle(Point(0,0), r) 15 | c.draw(win) 16 | 17 | #Draw a horizontal line across the window with teh given y-intercept 18 | line = Line(Point(-10, y), Point(10, y)) 19 | line.draw(win) 20 | 21 | if r < y: 22 | print("The line does not intersect.") 23 | else: 24 | #Compute x 25 | x = m.sqrt(r**2 - y**2) 26 | 27 | #Print the two x values of intersection textually 28 | print(-x, x) 29 | 30 | #Print the two x values graphically 31 | x1 = Text(Point(-x, y + 2),-x) 32 | x2 = Text(Point(x, y + 2), x) 33 | x1.draw(win) 34 | x2.draw(win) 35 | 36 | main() 37 | -------------------------------------------------------------------------------- /chap07/exercise_15.py: -------------------------------------------------------------------------------- 1 | import math as m 2 | from graphics import * 3 | 4 | def main(): 5 | win = GraphWin("Line Drawing Tool", 400, 400) 6 | win.setCoords(-10, -10, 10, 10) 7 | #Prompt the User for 2 mouse clicks 8 | message = Text(Point(-5, 8), "Click on 2 points to create a line") 9 | message.draw(win) 10 | #Store coordinates in variables x1, x2 etc 11 | point1 = win.getMouse() 12 | point2 = win.getMouse() 13 | x1 = point1.getX() 14 | x2 = point2.getX() 15 | y1 = point1.getY() 16 | y2 = point2.getY() 17 | 18 | #Create a Line w/ midpoint "cyan" 19 | line = Line(point1, point2) 20 | line.draw(win) 21 | mx, my = (x1+x2)/2, (y1+y2)/2 22 | win.plot(mx, my, "cyan") 23 | 24 | #Calculate the length and slope of the Line 25 | length = m.sqrt((x2 - x1)**2 + (y2 - y1)**2) 26 | if (x2 - x1) == 0: 27 | message3 = Text(Point(-5,6), ("The slope of the line is vertical.")) 28 | else: 29 | slope = (y2-y1)/(x2 -x1) 30 | message3 = Text(Point(-5, 6), ("The slope of the line is: ", round(slope, 2))) 31 | #Print length and slope of line 32 | message2 = Text(Point(-5, 7), ("The length of the line is: ", round(length, 2))) 33 | message2.draw(win) 34 | message3.draw(win) 35 | 36 | main() 37 | -------------------------------------------------------------------------------- /chap07/exercise_16.py: -------------------------------------------------------------------------------- 1 | from graphics import * 2 | import math as m 3 | 4 | def main(): 5 | win = GraphWin() 6 | win.setCoords(-5, -5, 5, 5) 7 | c = Circle(Point(0,0), 5) 8 | c.setOutline("green4") 9 | c.setFill("white") 10 | c.setWidth(1) 11 | c.draw(win) 12 | 13 | c2 = Circle(Point(0,0), 4) 14 | c2.setOutline("green4") 15 | c2.setFill("red") 16 | c2.setWidth(1) 17 | c2.draw(win) 18 | 19 | c3 = Circle(Point(0,0), 3) 20 | c3.setOutline("green4") 21 | c3.setFill("blue") 22 | c3.setWidth(1) 23 | c3.draw(win) 24 | 25 | c4 = Circle(Point(0,0), 2) 26 | c4.setOutline("green4") 27 | c4.setFill("black") 28 | c4.setWidth(1) 29 | c4.draw(win) 30 | 31 | c5 = Circle(Point(0,0), 1) 32 | c5.setOutline("green4") 33 | c5.setFill("white") 34 | c5.setWidth(1) 35 | c5.draw(win) 36 | 37 | sum = 0 38 | for x in range (5): 39 | arrow = win.getMouse() 40 | x = arrow.getX() 41 | y = arrow.getY() 42 | z = m.sqrt(x ** 2 + y ** 2) 43 | 44 | if 5 >= z > 4: 45 | y = 1 46 | sum = y + sum 47 | elif 4 >= z > 3: 48 | y = 3 49 | sum = y + sum 50 | elif 3 >= z > 2: 51 | y = 5 52 | sum = y + sum 53 | elif 2 >= z > 1: 54 | y = 7 55 | sum = y + sum 56 | elif 1 > z: 57 | y = 9 58 | sum = y + sum 59 | else: 60 | y = 0 61 | print("You missed!") 62 | print("Point: {0} Total: {1}".format(y, sum)) 63 | 64 | main() 65 | -------------------------------------------------------------------------------- /chap07/exercise_17.py: -------------------------------------------------------------------------------- 1 | from graphics import * 2 | from time import sleep 3 | import math as m 4 | 5 | def main(): 6 | win = GraphWin("Bouncing Ball", 500, 500) 7 | win.setCoords(-100, -100, 100, 100) 8 | 9 | shape = Circle(Point(0,-80),20) 10 | shape.setOutline("red") 11 | shape.setFill("red") 12 | shape.draw(win) 13 | 14 | dx = 1 15 | dy = 1 16 | 17 | for i in range(10000): 18 | c = shape.getCenter() 19 | 20 | if c.getX() > 80: 21 | dx = -1 22 | elif c.getX() < -80: 23 | dx = 1 24 | elif c.getY() > 80: 25 | dy = -1 26 | elif c.getY() < -80: 27 | dy = 1 28 | 29 | sleep(0.005) 30 | shape.move(dx,dy) 31 | main() 32 | -------------------------------------------------------------------------------- /chap07/exercise_18.py: -------------------------------------------------------------------------------- 1 | def leapYear(year): 2 | if (year % 4) != 0: 3 | return False 4 | else: 5 | if (year % 100) == 0: 6 | if (year % 400) ==0: 7 | return True 8 | else: 9 | return False 10 | else: 11 | return True 12 | 13 | def main(): 14 | try: 15 | dateStr = input("Please enter a date in form 00/00/0000: ") 16 | 17 | monthStr, dayStr, yearStr = dateStr.split("/") 18 | month = int(monthStr) 19 | day = int(dayStr) 20 | year = int(yearStr) 21 | 22 | 23 | if month > 12 or day > 31: 24 | print("This date is invalid.") 25 | else: 26 | if day <= 28: 27 | print("This date is valid.") 28 | elif month == 2 and day == 29: 29 | if leapYear(year) == False: 30 | print("This date is invalid.") 31 | else: 32 | print("This date is valid.") 33 | elif day == 31: 34 | if month == 2 or 4 or 6 or 11: 35 | print("This date is invalid") 36 | else: 37 | print("This date is valid") 38 | else: 39 | print("The date is valid.") 40 | 41 | except ValueError: 42 | print("Your input was not in the correct form.") 43 | except: 44 | print("Oops. Something went wrong!") 45 | main() 46 | -------------------------------------------------------------------------------- /chap07/exercise_2.py: -------------------------------------------------------------------------------- 1 | def main(): 2 | x = eval(input("What is the number grade? ")) 3 | if x == 5: 4 | print('A') 5 | elif x == 4: 6 | print('B') 7 | elif x == 3: 8 | print('C') 9 | elif x == 2: 10 | print('D') 11 | elif x == 1: 12 | print('F') 13 | elif x == 0: 14 | print('F') 15 | else: 16 | print('Please enter an integer between 0 and 5') 17 | main() 18 | -------------------------------------------------------------------------------- /chap07/exercise_3.py: -------------------------------------------------------------------------------- 1 | def main(): 2 | #x = eval(input("What is the number grade? ")) 3 | x = 84 4 | if x >= 90: 5 | print('A') 6 | elif 90 > x >= 80: 7 | print('B') 8 | elif 80 > x >= 70: 9 | print('C') 10 | elif 70 > x >= 60: 11 | print('D') 12 | elif 60 > x: 13 | print('F') 14 | else: 15 | print('Please enter an integer between 0 and 100') 16 | main() 17 | -------------------------------------------------------------------------------- /chap07/exercise_4.py: -------------------------------------------------------------------------------- 1 | def main(): 2 | x = eval(input("How many credits do you have? ")) 3 | 4 | if x < 7: 5 | print('Freshman') 6 | elif 7 <= x <16: 7 | print('Sophomore') 8 | elif 16 <= x <26: 9 | print('Junior') 10 | elif x >= 26: 11 | print('Senior') 12 | else: 13 | print("Please print a valid positive number ") 14 | main() 15 | -------------------------------------------------------------------------------- /chap07/exercise_5.py: -------------------------------------------------------------------------------- 1 | def BMI(weight, height): 2 | BMI = (weight * 720) / (height ** 2) 3 | return BMI 4 | def main(): 5 | x, y = eval(input("What is your weight (in pounds) and height (in inches)?")) 6 | bmi = BMI(x, y) 7 | 8 | if 19 <= bmi <= 25: 9 | print("You are within the arbitrary healthy range.") 10 | elif bmi < 19: 11 | print("You are below the arbitrary healthy range.") 12 | elif bmi > 25: 13 | print("You are above the arbitrary healthy range.") 14 | else: 15 | print("Please enter a valid height and weight") 16 | #try? 17 | main() 18 | -------------------------------------------------------------------------------- /chap07/exercise_6.py: -------------------------------------------------------------------------------- 1 | def main(): 2 | #x = input(eval("Please report speed: ")) 3 | #y = input(eval("What is the reported speed limit?")) 4 | x = -34 5 | y = 65 6 | t = x - y 7 | if t >= 0: 8 | fine = (t // 5) * 5 + 50 9 | if x >= 90: 10 | fine = fine + 200 11 | print("You owe ${0}.".format(fine)) 12 | elif t < 0: 13 | print("You have not committed a speed violation.") 14 | else: 15 | print("Check the speed limit or reported speed.") 16 | main() 17 | -------------------------------------------------------------------------------- /chap07/exercise_7.py: -------------------------------------------------------------------------------- 1 | def main(): 2 | #get time in hours and minutes and convert into float of hours 3 | #time = input("Please enter the time eg. (hh:mm): ") 4 | starTime = '9:15' 5 | endTime = '23:15' 6 | 7 | starMin = eval(starTime[-2:len(starTime)]) 8 | starHr = eval(starTime[:len(starTime)-3]) 9 | endMin = eval(endTime[-2:len(endTime)]) 10 | endHr = eval(endTime[:len(endTime)-3]) 11 | 12 | starTime = starHr + 1 / (60/starMin) 13 | endTime = endHr + 1 / (60/endMin) 14 | 15 | time = endTime - starTime 16 | if endTime < 21: 17 | bill = time * 2.50 18 | else: 19 | x = endTime - 21 20 | bill = (time - x) * 2.50 + (x * 1.75) 21 | print("${0}".format(round(bill, 2))) 22 | main() 23 | -------------------------------------------------------------------------------- /chap07/exercise_8.py: -------------------------------------------------------------------------------- 1 | def main(): 2 | cit = eval(input("How many years have you been a U.S. Citizen? ")) 3 | age = eval(input("How old are you? ")) 4 | if cit >= 9: 5 | if age >= 30: 6 | print("You are elibible to serve as a U.S. Senator, or a member of the House.") 7 | elif 30 > age >= 25: 8 | print("You are eligible to run for the House of Representatives.") 9 | else: 10 | print("Sorry, but you are not eligible to serve as a congressional representative.") 11 | else: 12 | print("Sorry, but you are not eligible to serve as a congressional representative.") 13 | main() 14 | -------------------------------------------------------------------------------- /chap07/exercise_9.py: -------------------------------------------------------------------------------- 1 | def Easter(year): 2 | if 1982 <= year <= 2018: 3 | a = year % 19 4 | b = year % 4 5 | c = year % 7 6 | d = (19 * a + 24) % 30 7 | e = (2 * b + 4 * c + 6 * d + 5) % 7 8 | if (d + e) > 9: 9 | print("Easter falls on April {}.".format(d + e - 9)) 10 | else: 11 | print("Easter falls on March {}.".format(22 + d + e)) 12 | else: 13 | print("Year is out of range") 14 | 15 | 16 | def main(): 17 | #year = eval(input("Input a year: ")) 18 | year = 2018 19 | Easter(year) 20 | main() 21 | -------------------------------------------------------------------------------- /chap07/test.py: -------------------------------------------------------------------------------- 1 | dateStr = '09/24/1956' 2 | 3 | monthStr, dayStr, yearStr = dateStr.split("/") 4 | month = int(monthStr) 5 | day = int(dayStr) 6 | year = int(yearStr) 7 | 8 | print(month, day, year) 9 | -------------------------------------------------------------------------------- /chap08/average1.py: -------------------------------------------------------------------------------- 1 | def main(): 2 | n = eval(input("How many numbers do you have? ")) 3 | num = 0.0 4 | for i in range(n): 5 | x = eval(input("Enter a number >> ")) 6 | sum = sum + x 7 | print("\nThe average of the numbers is", sum / n) 8 | 9 | main() 10 | -------------------------------------------------------------------------------- /chap08/average2.py: -------------------------------------------------------------------------------- 1 | #Interactive Loop 2 | def main(): 3 | sum = 0.0 4 | count = 0 5 | moredata = "yes" 6 | while moredata[0] == "y": 7 | x = eval(input("Enter a number >> ")) 8 | sum = sum + x 9 | moredata = input("Do you have more numbers (yes or no)? ") 10 | print("\nThe average of the numbers is", sum / count) 11 | 12 | main() 13 | -------------------------------------------------------------------------------- /chap08/average3.py: -------------------------------------------------------------------------------- 1 | #Sentinel Loop 2 | def main(): 3 | sum = 0.0 4 | count = 0 5 | x = eval(input("Enter a number (negative to quit) >> ")) 6 | while x >= 0: 7 | sum = sum + x 8 | count = count + 1 9 | x = eval(input("Enter a number (negative to quit) >> ")) 10 | print("\nThe average of the numbers is", sum / count) 11 | main() 12 | -------------------------------------------------------------------------------- /chap08/average4.py: -------------------------------------------------------------------------------- 1 | def main(): 2 | sum = 0.0 3 | count = 0 4 | xStr = input("Enter a number ( to quit) >> ") 5 | while xStr != "": 6 | x = eval(xStr) 7 | sum = sum + x 8 | count = count + 1 9 | xStr = input("Enter a number ( to quit) >> ") 10 | print("\nThe average of the numbers is", sum / count) 11 | main() 12 | -------------------------------------------------------------------------------- /chap08/average5.py: -------------------------------------------------------------------------------- 1 | def main(): 2 | fileName = input("What file are the numbers in? ") 3 | infile = open(fileName, 'r') 4 | sum = 0.0 5 | count = 0 6 | for line in infile: 7 | sum = sum + eval(line) 8 | count = count + 1 9 | print("\nThe average of the numbers is", sum / count) 10 | 11 | main() 12 | -------------------------------------------------------------------------------- /chap08/average6.py: -------------------------------------------------------------------------------- 1 | def main(): 2 | fileName = input("What file are the numbers in? ") 3 | infile = open(fileName, "r") 4 | sum = 0.0 5 | count = 0 6 | line = infile.readline() 7 | while line != "": 8 | sum = sum + eval(line) 9 | count = count + 1 10 | line = infile.readline() 11 | print("\nThe average of the numbers is", sum / count) 12 | 13 | main() 14 | -------------------------------------------------------------------------------- /chap08/average7.py: -------------------------------------------------------------------------------- 1 | def main(): 2 | fileName = input("What file are the numbers in? ") 3 | infile = open(fileName, "r") 4 | sum = 0.0 5 | count = 0 6 | line = infile.readline() 7 | while line != "": 8 | for xStr in line.split(","): 9 | sum = sum + eval(xStr) 10 | count = count + 1 11 | line = infile.readline() 12 | print("\nThe average of the numbers is", sum / count) 13 | 14 | main() 15 | -------------------------------------------------------------------------------- /chap08/discuss3.py: -------------------------------------------------------------------------------- 1 | def main(): 2 | sum = 0.0 3 | #n = input("Enter a number ( to quit) >> ") 4 | n = 5 5 | while n > 0: 6 | x = n 7 | sum = x + sum 8 | n = n - 1 9 | 10 | print("\nThe sum of the numbers is", sum ) 11 | main() 12 | -------------------------------------------------------------------------------- /chap08/exercise_1.py: -------------------------------------------------------------------------------- 1 | import math as m 2 | 3 | def main(): 4 | n = eval(input("What number in the Fibonnaci sequence would you like to see?: ")) 5 | count = 0 6 | x = 1 7 | y = 0 8 | 9 | while count < n: 10 | count = count + 1 11 | z = x + y 12 | x = y 13 | y = z 14 | print(z) 15 | 16 | main() 17 | -------------------------------------------------------------------------------- /chap08/exercise_10.txt: -------------------------------------------------------------------------------- 1 | 100 1 2 | 200 1 3 | 300 1 4 | 400 1 5 | 500 1 6 | 600 1 7 | 700 1 8 | 800 .75 9 | -------------------------------------------------------------------------------- /chap08/exercise_11.py: -------------------------------------------------------------------------------- 1 | #This program accepts a sequence of average daily temps and computes 2 | #the running total of cooling and heating degree days 3 | 4 | def main(): 5 | avgTemp = 0 6 | coolDeg = 0 7 | heatDeg = 0 8 | while True: 9 | #Accept input in degrees 10 | avgTemp = input("Enter average daily temperature (Type 'Exit' to quit)>> ") 11 | if avgTemp.lower() == "exit": 12 | break 13 | else: 14 | try: 15 | avgTemp = int(avgTemp) 16 | 17 | if avgTemp < 60: 18 | coolDeg = coolDeg + abs((avgTemp - 60)) 19 | elif avgTemp > 80: 20 | heatDeg = heatDeg + (avgTemp - 80) 21 | else: 22 | avgTemp = avgTemp 23 | except ValueError: 24 | print("Make sure your input is a number.") 25 | except IndexError: 26 | print("Make sure your input is a number.") 27 | 28 | 29 | 30 | print("The cooling degree-day is {0} and the heating degree-day is {1}".format(coolDeg, heatDeg)) 31 | 32 | main() 33 | -------------------------------------------------------------------------------- /chap08/exercise_12.py: -------------------------------------------------------------------------------- 1 | #This program accepts a sequence of average daily temps and computes 2 | #the running total of cooling and heating degree days 3 | 4 | def main(): 5 | fname = input("Enter filename: ") 6 | infile = open(fname, "r") 7 | 8 | coolDeg = 0 9 | heatDeg = 0 10 | avgTemp = 1 11 | 12 | while avgTemp != None: 13 | #Accept input in degrees 14 | for avgTemp in infile.readlines(): 15 | print(avgTemp) 16 | try: 17 | avgTemp = int(avgTemp[0:-1]) 18 | 19 | if avgTemp < 60: 20 | coolDeg = coolDeg + abs((avgTemp - 60)) 21 | elif avgTemp > 80: 22 | heatDeg = heatDeg + (avgTemp - 80) 23 | else: 24 | avgTemp = avgTemp 25 | except ValueError: 26 | if avgTemp[0:-1] == '': 27 | break 28 | else: 29 | return False 30 | finally: 31 | infile.close() 32 | break 33 | print("The cooling degree-day is {0} and the heating degree-day is {1}.".format(coolDeg, heatDeg)) 34 | 35 | 36 | main() 37 | -------------------------------------------------------------------------------- /chap08/exercise_12.txt: -------------------------------------------------------------------------------- 1 | 100 2 | 130 3 | 122 4 | 105 5 | 151 6 | 30 7 | 84 8 | 16 9 | 23 10 | 32 11 | 69 12 | 104 13 | 80 14 | 70 15 | 71 16 | 72 17 | 73 18 | 74 19 | -------------------------------------------------------------------------------- /chap08/exercise_14(gray).png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/drycode/zelle-python/ccd781784bf2a635d1f6e84ec2173d2ae7d50098/chap08/exercise_14(gray).png -------------------------------------------------------------------------------- /chap08/exercise_14.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/drycode/zelle-python/ccd781784bf2a635d1f6e84ec2173d2ae7d50098/chap08/exercise_14.png -------------------------------------------------------------------------------- /chap08/exercise_14.py: -------------------------------------------------------------------------------- 1 | #This program converts a color image to grayscale 2 | from graphics import * 3 | 4 | def fileWindow(infile, wWidth, wHeight): 5 | win = GraphWin("Original", wWidth, wHeight) 6 | #win.setCoords(-10, -10, 10, 10) 7 | infile.draw(win) 8 | #win.getMouse() 9 | 10 | height = 1 11 | while height < wHeight: 12 | for i in range (wWidth - 1): 13 | #r, g, b = get pixel info for current row and column 14 | r, g, b = infile.getPixel(i + 1, height) 15 | brightness = int(round(0.299 * r + 0.587 * g + 0.114 * b)) 16 | #set pixel to color_rgb(brightness, brightness, brightness) 17 | infile.setPixel((i + 1), (height), color_rgb(brightness, brightness, brightness)) 18 | #update the image # to see progress row by row 19 | 20 | win.update() 21 | height = height + 1 22 | 23 | return win 24 | 25 | 26 | #Get file from user 27 | def main(): 28 | fname = input("Enter a filename to be converted: ") 29 | infile = Image(Point(0,0), fname) 30 | 31 | wWidth = infile.getWidth() 32 | wHeight = infile.getHeight() 33 | infile = Image(Point(wWidth/2, wHeight/2), fname) 34 | win = fileWindow(infile, wWidth, wHeight) 35 | outfileName = input("Where should we save the updated file: ") 36 | infile.save(outfileName) 37 | 38 | 39 | 40 | #userfile.py chapt 5 41 | main() 42 | -------------------------------------------------------------------------------- /chap08/exercise_15(negative).png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/drycode/zelle-python/ccd781784bf2a635d1f6e84ec2173d2ae7d50098/chap08/exercise_15(negative).png -------------------------------------------------------------------------------- /chap08/exercise_15.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/drycode/zelle-python/ccd781784bf2a635d1f6e84ec2173d2ae7d50098/chap08/exercise_15.png -------------------------------------------------------------------------------- /chap08/exercise_15.py: -------------------------------------------------------------------------------- 1 | #This program converts a color image to grayscale 2 | from graphics import * 3 | 4 | def fileWindow(infile, wWidth, wHeight): 5 | win = GraphWin("Original", wWidth, wHeight) 6 | #win.setCoords(-10, -10, 10, 10) 7 | infile.draw(win) 8 | #win.getMouse() 9 | 10 | height = 1 11 | while height < wHeight: 12 | for i in range (wWidth - 1): 13 | #r, g, b = get pixel info for current row and column 14 | r, g, b = infile.getPixel(i+1, height) 15 | #brightness = int(round(0.299 * r + 0.587 * g + 0.114 * b)) 16 | #set pixel to color_rgb(brightness, brightness, brightness) 17 | infile.setPixel((i + 1), (height), color_rgb(255-r, 255-g, 255-b)) 18 | #update the image # to see progress row by row 19 | 20 | win.update() 21 | height = height + 1 22 | 23 | return win 24 | 25 | 26 | #Get file from user 27 | def main(): 28 | fname = input("Enter a filename to be converted: ") 29 | infile = Image(Point(0,0), fname) 30 | 31 | wWidth = infile.getWidth() 32 | wHeight = infile.getHeight() 33 | infile = Image(Point(wWidth/2, wHeight/2), fname) 34 | win = fileWindow(infile, wWidth, wHeight) 35 | outfileName = input("Where should we save the updated file: ") 36 | infile.save(outfileName) 37 | 38 | 39 | 40 | #userfile.py chapt 5 41 | main() 42 | -------------------------------------------------------------------------------- /chap08/exercise_2*.py: -------------------------------------------------------------------------------- 1 | # Get into the habit of using more descriptive variable names. 2 | # It will make the lives of whoever has to read this code easier (yourself included) 3 | def windchill(temperature, windspeed): 4 | if 50 >= windspeed >= 3: 5 | windchill = 35.74 + (0.6215 * temperature) - (35.75 * (windspeed ** 0.16)) + (0.4275 * temperature) * (windspeed ** 0.16) 6 | else: 7 | windchill = 0 8 | return windchill 9 | 10 | def generateWindchillTable(rows): 11 | # Extra credit - find a way to ensure the rows argument is a number, and not a string or a boolean (the for loop will fail if it isn't) 12 | try: 13 | if rows == True or rows == False or rows == None: 14 | print("Use a number not a boolean") 15 | else: 16 | for i in range (rows): 17 | print("{0:2} {1:>8.1f} {2:6.1f} {3:6.1f} {4:6.1f} {5:6.1f} {6:6.1f} {7:6.1f} {8:6.1f}".format(i*5,windchill(-20, i*5), windchill(-10, i*5), windchill(0, i*5), windchill(10, i*5), windchill(20, i*5), windchill(30, i*5), windchill(40, i*5), windchill(50, i*5))) 18 | except NameError as rows: 19 | print("rows must be a number!") 20 | except TypeError as rows: 21 | print("rows must be a number!") 22 | except SyntaxError: 23 | print("rows must be a number!") 24 | 25 | def main(): 26 | 27 | print("{0:>}".format("Table of Windchill Values")) 28 | print("{0:>11} {1:6} {2:6} {3:6} {4:>6} {5:6} {6:6} {7:6}".format(-20, -10, 0, 10, 20, 30, 40, 50)) 29 | print("") 30 | generateWindchillTable(11) 31 | 32 | main() 33 | -------------------------------------------------------------------------------- /chap08/exercise_2.py: -------------------------------------------------------------------------------- 1 | #Windchill Table 2 | 3 | 4 | def windchill(T, V): 5 | if 50 >= V >= 3: 6 | windchill = 35.74 + (0.6215 * T) - (35.75 * (V ** 0.16)) + (0.4275 * T) * (V ** 0.16) 7 | else: 8 | windchill = 0 9 | return windchill 10 | 11 | def main(): 12 | print("{0:>11} {1:6} {2:6} {3:6} {4:>6} {5:6} {6:6} {7:6}".format(-20, -10, 0, 10, 20, 30, 40, 50)) 13 | print("") 14 | for i in range (11): 15 | print("{0:2} {1:>8.1f} {2:6.1f} {3:6.1f} {4:6.1f} {5:6.1f} {6:6.1f} {7:6.1f} {8:6.1f}".format(i*5,windchill(-20, i*5), windchill(-10, i*5), windchill(0, i*5), windchill(10, i*5), windchill(20, i*5), windchill(30, i*5), windchill(40, i*5), windchill(50, i*5))) 16 | 17 | main() 18 | -------------------------------------------------------------------------------- /chap08/exercise_3.py: -------------------------------------------------------------------------------- 1 | #While loop to determine rule of 72 2 | 3 | def main(): 4 | apr = eval(input("What is the annualized interest rate? ")) 5 | apr = .01*apr 6 | principal = eval(input("What is the initial principal? ")) 7 | 8 | p = principal 9 | interest = 0 10 | years = 0 11 | 12 | while principal > .5 * p: 13 | years = years + 1 14 | interest = p * apr 15 | p = p + interest 16 | 17 | print(p) 18 | print(years) 19 | 20 | main() 21 | -------------------------------------------------------------------------------- /chap08/exercise_4.py: -------------------------------------------------------------------------------- 1 | #Syracuse sequence 2 | def syr(x): 3 | if x % 2 == 0: 4 | syrX = x/2 5 | elif x % 2 == 1: 6 | syrX = 3 * x + 1 7 | return syrX 8 | 9 | def main(): 10 | x = eval(input("Input a natural number: ")) 11 | print(x) 12 | while x > 1: 13 | syrX = syr(x) 14 | x = syrX 15 | print(syrX) 16 | main() 17 | -------------------------------------------------------------------------------- /chap08/exercise_5*.py: -------------------------------------------------------------------------------- 1 | #This program validates input n as a prime number. The program will close 2 | #if it finds n to be divisible by any number other than 1 and itself. 3 | 4 | import math as m 5 | #Validate n as a positive whole number 6 | def main(): 7 | n = eval(input("Input a positive whole number: ")) 8 | 9 | if n == 0: 10 | n = eval(input("Your number must be higher than 0: ")) 11 | elif (n % 1 != 0): 12 | n = eval(input("The number you entered was not whole: ")) 13 | elif (n < 1): 14 | n = eval(input("The number you entered was not positive: ")) 15 | else: 16 | #check if n is evenly divisible by values between 2 and int(m.sqrt(n)) 17 | x = m.sqrt(n) 18 | i = 2 19 | 20 | 21 | while i <= x: 22 | value = n % i 23 | #if any value is divisble, break and close program 24 | if value == 0: 25 | exit() 26 | #if no value is divisible evenly, print("The number is prime.") 27 | else: 28 | i = i + 1 29 | print("The number is prime.") 30 | 31 | main() 32 | -------------------------------------------------------------------------------- /chap08/exercise_5.py: -------------------------------------------------------------------------------- 1 | #Prime number validation 2 | #This program will close if the number is not prime, 3 | #and will report an error if the input is invalid 4 | 5 | import math as m 6 | 7 | def main(): 8 | #n = eval(input("Input a positive whole number: ")) 9 | n = 25 10 | while (n < 1) or (n % 1 != 0): 11 | n = eval(input("Try a positive whole number: ")) 12 | 13 | 14 | for i in range (int(m.sqrt(n))): 15 | i = 2 16 | if (n % (i)) != 0: 17 | i = i+1 18 | if i > m.sqrt(n): 19 | exit() 20 | else: 21 | break 22 | print("The number is prime.") 23 | main() 24 | -------------------------------------------------------------------------------- /chap08/exercise_5_refactor.py: -------------------------------------------------------------------------------- 1 | #This program determines if a value is prime. 2 | 3 | import math as m 4 | #Validate n as a positive whole number 5 | def main(): 6 | n = 0; 7 | 8 | while True: 9 | n = eval(input("Input a positive whole number: ")) 10 | 11 | if (n % 1 != 0): 12 | n = print("The number you entered was not whole!") 13 | elif (n < 1): 14 | n = print("The number you entered was not positive!") 15 | else: 16 | break 17 | 18 | #check if n is evenly divisible by values between 2 and int(m.sqrt(n)) 19 | x = m.sqrt(n) 20 | i = 2 21 | value = n % i 22 | 23 | while i <= x: 24 | #if any value is divisble, break and close program 25 | if value == 0: 26 | exit() 27 | #if no value is divisible evenly, print("The number is prime.") 28 | else: 29 | i = i + 1 30 | print("The number is prime.") 31 | 32 | main() 33 | -------------------------------------------------------------------------------- /chap08/exercise_6*.py: -------------------------------------------------------------------------------- 1 | #This program finds every prime number less than or equal to input n 2 | 3 | import math as m 4 | 5 | def primeNum(n): 6 | 7 | #check if n is evenly divisible by values between 2 and int(m.sqrt(n)) 8 | x = m.sqrt(n) 9 | i = 2 10 | 11 | while i <= x: 12 | value = n % i 13 | #if any value is divisble, break and close program 14 | if value == 0: 15 | return 16 | #if no value is divisible evenly, print("The number is prime.") 17 | else: 18 | i = i + 1 19 | print(n) 20 | 21 | def main(): 22 | x = 0 23 | #Validate x as a positive whole number 24 | while True: 25 | x = eval(input("Input a positive whole number: ")) 26 | 27 | if (x % 1 != 0): 28 | x = print("The number you entered was not whole!") 29 | elif (x < 1): 30 | x = print("The number you entered was not positive!") 31 | else: 32 | break 33 | for n in range(x): 34 | primeNum(n+1) 35 | 36 | main() 37 | -------------------------------------------------------------------------------- /chap08/exercise_6.py: -------------------------------------------------------------------------------- 1 | #This program finds every prime number less than or equal to input n 2 | 3 | import math as m 4 | 5 | def primeNum(n): 6 | 7 | #check if n is evenly divisible by values between 2 and int(m.sqrt(n)) 8 | x = m.sqrt(n) 9 | i = 2 10 | 11 | while i <= x: 12 | value = n % i 13 | #if any value is divisble, break and close program 14 | if value == 0: 15 | return 16 | #if no value is divisible evenly, print("The number is prime.") 17 | else: 18 | i = i + 1 19 | print(n) 20 | 21 | def main(): 22 | x = eval(input("Input a positive whole number: ")) 23 | #Validate x as a positive whole number 24 | if x == 0: 25 | x = eval(input("Your number must be higher than 0: ")) 26 | elif (x % 1 != 0): 27 | x = eval(input("The number you entered was not whole: ")) 28 | elif (x < 1): 29 | x = eval(input("The number you entered was not positive: ")) 30 | else: 31 | for n in range(x): 32 | primeNum(n+1) 33 | 34 | main() 35 | -------------------------------------------------------------------------------- /chap08/exercise_7*.py: -------------------------------------------------------------------------------- 1 | #Goldbach conjecture 2 | #Every even number is the sum of two prime numbers 3 | #This program gets a number from the user, validates it being even, 4 | #then finds two primes that add up to that number 5 | 6 | import math as m 7 | 8 | def primeNum(n): 9 | #check if n is evenly divisible by values between 2 and int(m.sqrt(n)) 10 | x = m.sqrt(n) 11 | i = 2 12 | while i <= x: 13 | value = n % i 14 | if value == 0: 15 | return None 16 | else: 17 | i = i + 1 18 | return n 19 | 20 | def main(): 21 | 22 | x = eval(input("Input a positive whole number: ")) 23 | while True: 24 | 25 | #Validate x as a positive whole number 26 | if x == 0: 27 | x = eval(input("Your number must be higher than 0: ")) 28 | elif (x % 1 != 0): 29 | x = eval(input("The number you entered was not whole: ")) 30 | elif (x < 1): 31 | x = eval(input("The number you entered was not positive: ")) 32 | elif (x % 2 != 0): 33 | x = eval(input("The number you entered was not even: ")) 34 | else: 35 | n = x 36 | break 37 | while n > 0: 38 | prime = primeNum(n) 39 | if prime != None: 40 | prime2 = x - prime 41 | test = primeNum(prime2) 42 | if test != None: 43 | print("{0} + {1} = {2}".format(prime, prime2, x)) 44 | n = n - 1 45 | 46 | main() 47 | -------------------------------------------------------------------------------- /chap08/exercise_7.py: -------------------------------------------------------------------------------- 1 | #Goldbach conjecture 2 | #Every even number is the sum of two prime numbers 3 | #This program gets a number from the user, validates it being even, 4 | #then finds two primes that add up to that number 5 | 6 | import math as m 7 | 8 | def primeNum(n): 9 | #check if n is evenly divisible by values between 2 and int(m.sqrt(n)) 10 | x = m.sqrt(n) 11 | i = 2 12 | while i <= x: 13 | value = n % i 14 | if value == 0: 15 | return None 16 | else: 17 | i = i + 1 18 | return n 19 | def main(): 20 | x = eval(input("Input a positive whole number: ")) 21 | #Validate x as a positive whole number 22 | if x == 0: 23 | x = eval(input("Your number must be higher than 0: ")) 24 | elif (x % 1 != 0): 25 | x = eval(input("The number you entered was not whole: ")) 26 | elif (x < 1): 27 | x = eval(input("The number you entered was not positive: ")) 28 | elif (x % 2 != 0): 29 | x = eval(input("The number you entered was not even: ")) 30 | else: 31 | n = x 32 | while n > 0: 33 | prime = primeNum(n+1) 34 | if prime != None: 35 | prime2 = x - prime 36 | test = primeNum(prime2) 37 | if test != None: 38 | print("{0} + {1} = {2}".format(prime, prime2, x)) 39 | n = n - 1 40 | 41 | main() 42 | -------------------------------------------------------------------------------- /chap08/exercise_8.py: -------------------------------------------------------------------------------- 1 | #Euclid's algorithm 2 | #User inputs 2 values, m and n 3 | #repeat formula n, m = m, n % m until m == 0 4 | #Output n as the GCD of two numbers 5 | def main(): 6 | m, n = eval(input("Please enter 2 numbers, separated by a comma: ")) 7 | 8 | try: 9 | if m < n: 10 | y = n 11 | n = m 12 | m = y 13 | 14 | while m != 0: 15 | y = m 16 | m = n % m 17 | n = y 18 | print("The GCD is {}".format(n)) 19 | 20 | except TypeError: 21 | print("The input must be numerical.") 22 | 23 | main() 24 | -------------------------------------------------------------------------------- /chap08/exercise_9.py: -------------------------------------------------------------------------------- 1 | #This program computes the fuel efficiency of a multi-leg journey 2 | def MPG(start_odom): 3 | count = 0 4 | 5 | #get information about a series of legs 6 | leg = 0 7 | totGas = 0 8 | while leg != "\n": 9 | #current odometer and amount of gas used separated by space 10 | leg = input("Enter the current odometer and amount of gas (gallons), \nseparated by a space ( to quit)>> ") 11 | try: 12 | newodom, gas = leg.split(" ") 13 | newodom = eval(newodom) 14 | gas = eval(gas) 15 | 16 | count = count + 1 17 | 18 | #distance traveled per leg 19 | distance = newodom - odom 20 | #compute MPG for leg 21 | legMPG = distance/gas 22 | 23 | #set new odometer reading 24 | odom = newodom 25 | 26 | print("On leg {0}, you got {1}/gal.".format(count, round(legMPG, 2))) 27 | 28 | #add values to trip total 29 | totGas = totGas / gas 30 | except ValueError: 31 | break 32 | return totGas, distance 33 | 34 | def main(): 35 | #Prompt the user for the starting odometer 36 | odom = int(input("What is your current odometer reading: ")) 37 | totGas, distance = MPG(odom) 38 | 39 | #print out miles/gal on each leg and the total MPG for the trip 40 | totMPG = distance + totGas 41 | print("On whole trip, you averaged {1}/gal.".format(count, round(totMPG, 2))) 42 | main() 43 | -------------------------------------------------------------------------------- /chap08/notes.py: -------------------------------------------------------------------------------- 1 | #Post-test loop 2 | while True: 3 | number = eval(input("Enter a positive number: ")) 4 | if number >=0: 5 | break #Exit loop if number is valid 6 | else: 7 | print("The number you entered is not valid. ") 8 | 9 | #Loop and a Half 10 | while True: 11 | number = eval(input("enter a positive number: ")) 12 | if number >= 0: break #Loop Exit 13 | print("The number you entered was not positive") 14 | 15 | -------------------------------------------------------------------------------- /chap09/exercise_11.py: -------------------------------------------------------------------------------- 1 | from random import randrange 2 | 3 | def main(): 4 | printIntro() 5 | n = eval(input("Simulations: ")) 6 | totFive = simNRolls(n) 7 | 8 | def printIntro(): 9 | print("This program is intended to simulate the rolling of five six-sided") 10 | print("dice to approximate the probability of rolling five-of-a-kind.") 11 | 12 | def simNRolls(n): 13 | totFive = 0 14 | for i in range (n): 15 | if not fiveOfAKind(): 16 | totFive = totFive 17 | else: 18 | totFive = totFive + 1 19 | return totFive 20 | 21 | def fiveOfAKind(): 22 | a, b, c, d, e = simOneRoll() 23 | if a == b == c == d == e: 24 | return True 25 | else: 26 | return False 27 | 28 | def simOneRoll(): 29 | dice = [] 30 | for i in range (5): 31 | x = randrange(1, 6) 32 | dice.append(x) 33 | return dice 34 | 35 | if __name__ == '__main__': main() 36 | -------------------------------------------------------------------------------- /chap09/exercise_12.py: -------------------------------------------------------------------------------- 1 | #One-dimensional random walk 2 | from random import random 3 | 4 | def main(): 5 | printIntro() 6 | n = eval(input("How many steps do you intend to take per trip? ")) 7 | avgTravel = avgSteps(n) 8 | print("The object will travel an average of", avgTravel, "based on the simulation.") 9 | 10 | def printIntro(): 11 | print("This program simulates a random walk in one dimension, where the") 12 | print("object will move either forward or backward at random. Varialble") 13 | print('"n" represents the number of random steps per trip. The program') 14 | print("will simulate 1000 trips by default, and will return the average") 15 | print("distance traveled per trip.") 16 | 17 | def avgSteps(n): 18 | totTravel = 0 19 | for i in range (1000): 20 | steps = simNSteps(n) 21 | totTravel = totTravel + steps 22 | if totTravel == 0: 23 | avgTravel = 0 24 | else: 25 | avgTravel = totTravel / 1000 26 | return avgTravel 27 | 28 | def simNSteps(n): 29 | steps = 0 30 | for i in range (n): 31 | x = 2 * random() - 1 32 | if x > 0: 33 | steps = steps + 1 34 | elif x < 0: 35 | steps = steps - 1 36 | else: 37 | steps = steps 38 | return steps 39 | 40 | if __name__ == '__main__': main() 41 | -------------------------------------------------------------------------------- /chap09/exercise_14.py: -------------------------------------------------------------------------------- 1 | #graphical program to trace random walk in 2 dimensions 2 | 3 | import math as m 4 | from random import random 5 | from graphics import * 6 | 7 | def main(): 8 | n = eval(input("How many steps do you intend to take through the simulation? ")) 9 | win = GraphWin("Random Walk", 1200, 1200) 10 | win.setCoords(-100, -100, 100, 100) 11 | for i in range (5): 12 | randWalk(n, win) 13 | 14 | 15 | def randWalk(n, win): 16 | point2 = Point(0,0) 17 | for i in range (n): 18 | x = point2.getX() 19 | y = point2.getY() 20 | 21 | point1 = simOneStep(x, y) 22 | point1.draw(win) 23 | line = Line(point2, point1) 24 | line.draw(win) 25 | point2 = point1 26 | 27 | def simOneStep(x, y): 28 | angle = random() * 2 * m.pi 29 | x = x + m.cos(angle) 30 | y = y + m.sin(angle) 31 | point = Point(x, y) 32 | return point 33 | 34 | if __name__ == '__main__': main() 35 | -------------------------------------------------------------------------------- /chap09/exercise_7.py: -------------------------------------------------------------------------------- 1 | #2, 3, or 12 the player loses 2 | #7 or 11 the player wins 3 | #Any other roll initiates roll for points 4 | #Roll for 7 (loss) or 11 (win) 5 | from random import randrange 6 | 7 | def main(): 8 | printIntro() 9 | n = eval(input("How many rolls should I simulate? >> ")) 10 | wins, losses = simNCraps(n) 11 | printSummary(wins, losses, n) 12 | 13 | def printIntro(): 14 | print("This program is designed to simulate (n) games of craps") 15 | print("and will return the probability of winning based on the") 16 | print("simulation.") 17 | 18 | def simNCraps(n): 19 | wins = 0 20 | losses = 0 21 | for i in range(n): 22 | if simOneCraps() is True: 23 | wins = wins + 1 24 | else: 25 | losses = losses + 1 26 | return wins, losses 27 | 28 | 29 | def simOneCraps(): 30 | x = randrange(2,12) 31 | if x == 2 or x == 3 or x == 12: 32 | return False 33 | elif x == 7 or x == 11: 34 | return True 35 | else: 36 | y = 0 37 | while x != y and x != 7: 38 | y = randrange(2, 12) 39 | if y == 7: 40 | return False 41 | elif y == x: 42 | return True 43 | 44 | def printSummary(wins, losses, n): 45 | print("\nGames simulated: ", n) 46 | print("Winning rolls: {0} ({1:0.1%})".format(wins, wins/n)) 47 | print("Losing rolls: {0} ({1:0.1%})".format(losses, losses/n)) 48 | 49 | 50 | if __name__ == '__main__': main() 51 | -------------------------------------------------------------------------------- /chap10/Playing_Card_Images/10C.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/drycode/zelle-python/ccd781784bf2a635d1f6e84ec2173d2ae7d50098/chap10/Playing_Card_Images/10C.png -------------------------------------------------------------------------------- /chap10/Playing_Card_Images/10D.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/drycode/zelle-python/ccd781784bf2a635d1f6e84ec2173d2ae7d50098/chap10/Playing_Card_Images/10D.png -------------------------------------------------------------------------------- /chap10/Playing_Card_Images/10H.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/drycode/zelle-python/ccd781784bf2a635d1f6e84ec2173d2ae7d50098/chap10/Playing_Card_Images/10H.png -------------------------------------------------------------------------------- /chap10/Playing_Card_Images/10S.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/drycode/zelle-python/ccd781784bf2a635d1f6e84ec2173d2ae7d50098/chap10/Playing_Card_Images/10S.png -------------------------------------------------------------------------------- /chap10/Playing_Card_Images/11C.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/drycode/zelle-python/ccd781784bf2a635d1f6e84ec2173d2ae7d50098/chap10/Playing_Card_Images/11C.png -------------------------------------------------------------------------------- /chap10/Playing_Card_Images/11D.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/drycode/zelle-python/ccd781784bf2a635d1f6e84ec2173d2ae7d50098/chap10/Playing_Card_Images/11D.png -------------------------------------------------------------------------------- /chap10/Playing_Card_Images/11H.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/drycode/zelle-python/ccd781784bf2a635d1f6e84ec2173d2ae7d50098/chap10/Playing_Card_Images/11H.png -------------------------------------------------------------------------------- /chap10/Playing_Card_Images/11S.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/drycode/zelle-python/ccd781784bf2a635d1f6e84ec2173d2ae7d50098/chap10/Playing_Card_Images/11S.png -------------------------------------------------------------------------------- /chap10/Playing_Card_Images/12C.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/drycode/zelle-python/ccd781784bf2a635d1f6e84ec2173d2ae7d50098/chap10/Playing_Card_Images/12C.png -------------------------------------------------------------------------------- /chap10/Playing_Card_Images/12D.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/drycode/zelle-python/ccd781784bf2a635d1f6e84ec2173d2ae7d50098/chap10/Playing_Card_Images/12D.png -------------------------------------------------------------------------------- /chap10/Playing_Card_Images/12H.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/drycode/zelle-python/ccd781784bf2a635d1f6e84ec2173d2ae7d50098/chap10/Playing_Card_Images/12H.png -------------------------------------------------------------------------------- /chap10/Playing_Card_Images/12S.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/drycode/zelle-python/ccd781784bf2a635d1f6e84ec2173d2ae7d50098/chap10/Playing_Card_Images/12S.png -------------------------------------------------------------------------------- /chap10/Playing_Card_Images/13C.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/drycode/zelle-python/ccd781784bf2a635d1f6e84ec2173d2ae7d50098/chap10/Playing_Card_Images/13C.png -------------------------------------------------------------------------------- /chap10/Playing_Card_Images/13D.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/drycode/zelle-python/ccd781784bf2a635d1f6e84ec2173d2ae7d50098/chap10/Playing_Card_Images/13D.png -------------------------------------------------------------------------------- /chap10/Playing_Card_Images/13H.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/drycode/zelle-python/ccd781784bf2a635d1f6e84ec2173d2ae7d50098/chap10/Playing_Card_Images/13H.png -------------------------------------------------------------------------------- /chap10/Playing_Card_Images/13S.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/drycode/zelle-python/ccd781784bf2a635d1f6e84ec2173d2ae7d50098/chap10/Playing_Card_Images/13S.png -------------------------------------------------------------------------------- /chap10/Playing_Card_Images/1C.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/drycode/zelle-python/ccd781784bf2a635d1f6e84ec2173d2ae7d50098/chap10/Playing_Card_Images/1C.png -------------------------------------------------------------------------------- /chap10/Playing_Card_Images/1D.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/drycode/zelle-python/ccd781784bf2a635d1f6e84ec2173d2ae7d50098/chap10/Playing_Card_Images/1D.png -------------------------------------------------------------------------------- /chap10/Playing_Card_Images/1H.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/drycode/zelle-python/ccd781784bf2a635d1f6e84ec2173d2ae7d50098/chap10/Playing_Card_Images/1H.png -------------------------------------------------------------------------------- /chap10/Playing_Card_Images/1S.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/drycode/zelle-python/ccd781784bf2a635d1f6e84ec2173d2ae7d50098/chap10/Playing_Card_Images/1S.png -------------------------------------------------------------------------------- /chap10/Playing_Card_Images/2C.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/drycode/zelle-python/ccd781784bf2a635d1f6e84ec2173d2ae7d50098/chap10/Playing_Card_Images/2C.png -------------------------------------------------------------------------------- /chap10/Playing_Card_Images/2D.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/drycode/zelle-python/ccd781784bf2a635d1f6e84ec2173d2ae7d50098/chap10/Playing_Card_Images/2D.png -------------------------------------------------------------------------------- /chap10/Playing_Card_Images/2H.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/drycode/zelle-python/ccd781784bf2a635d1f6e84ec2173d2ae7d50098/chap10/Playing_Card_Images/2H.png -------------------------------------------------------------------------------- /chap10/Playing_Card_Images/2S.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/drycode/zelle-python/ccd781784bf2a635d1f6e84ec2173d2ae7d50098/chap10/Playing_Card_Images/2S.png -------------------------------------------------------------------------------- /chap10/Playing_Card_Images/3C.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/drycode/zelle-python/ccd781784bf2a635d1f6e84ec2173d2ae7d50098/chap10/Playing_Card_Images/3C.png -------------------------------------------------------------------------------- /chap10/Playing_Card_Images/3D.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/drycode/zelle-python/ccd781784bf2a635d1f6e84ec2173d2ae7d50098/chap10/Playing_Card_Images/3D.png -------------------------------------------------------------------------------- /chap10/Playing_Card_Images/3H.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/drycode/zelle-python/ccd781784bf2a635d1f6e84ec2173d2ae7d50098/chap10/Playing_Card_Images/3H.png -------------------------------------------------------------------------------- /chap10/Playing_Card_Images/3S.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/drycode/zelle-python/ccd781784bf2a635d1f6e84ec2173d2ae7d50098/chap10/Playing_Card_Images/3S.png -------------------------------------------------------------------------------- /chap10/Playing_Card_Images/4C.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/drycode/zelle-python/ccd781784bf2a635d1f6e84ec2173d2ae7d50098/chap10/Playing_Card_Images/4C.png -------------------------------------------------------------------------------- /chap10/Playing_Card_Images/4D.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/drycode/zelle-python/ccd781784bf2a635d1f6e84ec2173d2ae7d50098/chap10/Playing_Card_Images/4D.png -------------------------------------------------------------------------------- /chap10/Playing_Card_Images/4H.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/drycode/zelle-python/ccd781784bf2a635d1f6e84ec2173d2ae7d50098/chap10/Playing_Card_Images/4H.png -------------------------------------------------------------------------------- /chap10/Playing_Card_Images/4S.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/drycode/zelle-python/ccd781784bf2a635d1f6e84ec2173d2ae7d50098/chap10/Playing_Card_Images/4S.png -------------------------------------------------------------------------------- /chap10/Playing_Card_Images/5C.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/drycode/zelle-python/ccd781784bf2a635d1f6e84ec2173d2ae7d50098/chap10/Playing_Card_Images/5C.png -------------------------------------------------------------------------------- /chap10/Playing_Card_Images/5D.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/drycode/zelle-python/ccd781784bf2a635d1f6e84ec2173d2ae7d50098/chap10/Playing_Card_Images/5D.png -------------------------------------------------------------------------------- /chap10/Playing_Card_Images/5H.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/drycode/zelle-python/ccd781784bf2a635d1f6e84ec2173d2ae7d50098/chap10/Playing_Card_Images/5H.png -------------------------------------------------------------------------------- /chap10/Playing_Card_Images/5S.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/drycode/zelle-python/ccd781784bf2a635d1f6e84ec2173d2ae7d50098/chap10/Playing_Card_Images/5S.png -------------------------------------------------------------------------------- /chap10/Playing_Card_Images/6C.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/drycode/zelle-python/ccd781784bf2a635d1f6e84ec2173d2ae7d50098/chap10/Playing_Card_Images/6C.png -------------------------------------------------------------------------------- /chap10/Playing_Card_Images/6D.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/drycode/zelle-python/ccd781784bf2a635d1f6e84ec2173d2ae7d50098/chap10/Playing_Card_Images/6D.png -------------------------------------------------------------------------------- /chap10/Playing_Card_Images/6H.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/drycode/zelle-python/ccd781784bf2a635d1f6e84ec2173d2ae7d50098/chap10/Playing_Card_Images/6H.png -------------------------------------------------------------------------------- /chap10/Playing_Card_Images/6S.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/drycode/zelle-python/ccd781784bf2a635d1f6e84ec2173d2ae7d50098/chap10/Playing_Card_Images/6S.png -------------------------------------------------------------------------------- /chap10/Playing_Card_Images/7C.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/drycode/zelle-python/ccd781784bf2a635d1f6e84ec2173d2ae7d50098/chap10/Playing_Card_Images/7C.png -------------------------------------------------------------------------------- /chap10/Playing_Card_Images/7D.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/drycode/zelle-python/ccd781784bf2a635d1f6e84ec2173d2ae7d50098/chap10/Playing_Card_Images/7D.png -------------------------------------------------------------------------------- /chap10/Playing_Card_Images/7H.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/drycode/zelle-python/ccd781784bf2a635d1f6e84ec2173d2ae7d50098/chap10/Playing_Card_Images/7H.png -------------------------------------------------------------------------------- /chap10/Playing_Card_Images/7S.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/drycode/zelle-python/ccd781784bf2a635d1f6e84ec2173d2ae7d50098/chap10/Playing_Card_Images/7S.png -------------------------------------------------------------------------------- /chap10/Playing_Card_Images/8C.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/drycode/zelle-python/ccd781784bf2a635d1f6e84ec2173d2ae7d50098/chap10/Playing_Card_Images/8C.png -------------------------------------------------------------------------------- /chap10/Playing_Card_Images/8D.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/drycode/zelle-python/ccd781784bf2a635d1f6e84ec2173d2ae7d50098/chap10/Playing_Card_Images/8D.png -------------------------------------------------------------------------------- /chap10/Playing_Card_Images/8H.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/drycode/zelle-python/ccd781784bf2a635d1f6e84ec2173d2ae7d50098/chap10/Playing_Card_Images/8H.png -------------------------------------------------------------------------------- /chap10/Playing_Card_Images/8S.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/drycode/zelle-python/ccd781784bf2a635d1f6e84ec2173d2ae7d50098/chap10/Playing_Card_Images/8S.png -------------------------------------------------------------------------------- /chap10/Playing_Card_Images/9C.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/drycode/zelle-python/ccd781784bf2a635d1f6e84ec2173d2ae7d50098/chap10/Playing_Card_Images/9C.png -------------------------------------------------------------------------------- /chap10/Playing_Card_Images/9D.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/drycode/zelle-python/ccd781784bf2a635d1f6e84ec2173d2ae7d50098/chap10/Playing_Card_Images/9D.png -------------------------------------------------------------------------------- /chap10/Playing_Card_Images/9H.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/drycode/zelle-python/ccd781784bf2a635d1f6e84ec2173d2ae7d50098/chap10/Playing_Card_Images/9H.png -------------------------------------------------------------------------------- /chap10/Playing_Card_Images/9S.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/drycode/zelle-python/ccd781784bf2a635d1f6e84ec2173d2ae7d50098/chap10/Playing_Card_Images/9S.png -------------------------------------------------------------------------------- /chap10/Playing_Card_Images/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/drycode/zelle-python/ccd781784bf2a635d1f6e84ec2173d2ae7d50098/chap10/Playing_Card_Images/__init__.py -------------------------------------------------------------------------------- /chap10/Playing_Card_Images/aces.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/drycode/zelle-python/ccd781784bf2a635d1f6e84ec2173d2ae7d50098/chap10/Playing_Card_Images/aces.png -------------------------------------------------------------------------------- /chap10/Playing_Card_Images/back_cards-07.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/drycode/zelle-python/ccd781784bf2a635d1f6e84ec2173d2ae7d50098/chap10/Playing_Card_Images/back_cards-07.png -------------------------------------------------------------------------------- /chap10/Playing_Card_Images/blue_back.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/drycode/zelle-python/ccd781784bf2a635d1f6e84ec2173d2ae7d50098/chap10/Playing_Card_Images/blue_back.png -------------------------------------------------------------------------------- /chap10/Playing_Card_Images/gray_back.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/drycode/zelle-python/ccd781784bf2a635d1f6e84ec2173d2ae7d50098/chap10/Playing_Card_Images/gray_back.png -------------------------------------------------------------------------------- /chap10/Playing_Card_Images/green_back.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/drycode/zelle-python/ccd781784bf2a635d1f6e84ec2173d2ae7d50098/chap10/Playing_Card_Images/green_back.png -------------------------------------------------------------------------------- /chap10/Playing_Card_Images/honor_clubs.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/drycode/zelle-python/ccd781784bf2a635d1f6e84ec2173d2ae7d50098/chap10/Playing_Card_Images/honor_clubs.png -------------------------------------------------------------------------------- /chap10/Playing_Card_Images/honor_diamond.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/drycode/zelle-python/ccd781784bf2a635d1f6e84ec2173d2ae7d50098/chap10/Playing_Card_Images/honor_diamond.png -------------------------------------------------------------------------------- /chap10/Playing_Card_Images/honor_heart-14.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/drycode/zelle-python/ccd781784bf2a635d1f6e84ec2173d2ae7d50098/chap10/Playing_Card_Images/honor_heart-14.png -------------------------------------------------------------------------------- /chap10/Playing_Card_Images/honors_spade-14.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/drycode/zelle-python/ccd781784bf2a635d1f6e84ec2173d2ae7d50098/chap10/Playing_Card_Images/honors_spade-14.png -------------------------------------------------------------------------------- /chap10/Playing_Card_Images/playingcard.py: -------------------------------------------------------------------------------- 1 | #playingcard.py 2 | from graphics import * 3 | import sys 4 | import os 5 | 6 | class PlayingCard: 7 | 8 | def __init__(self, rank, suit): 9 | self.rank = rank 10 | self.suit = suit 11 | 12 | def getRank(self): 13 | return self.rank 14 | 15 | def getSuit(self): 16 | return self.suit 17 | 18 | def BJValue(self): 19 | if 10 <= self.rank <= 13: 20 | self.rank = 10 21 | else: 22 | self.rank = self.rank 23 | return self.rank 24 | 25 | def __str__(self): 26 | n = self.rank 27 | if self.suit == 'd': 28 | s = "Diamonds" 29 | elif self.suit == 's': 30 | s = "Spades" 31 | elif self.suit == 'h': 32 | s = "Hearts" 33 | else: 34 | s = "Clubs" 35 | 36 | rank = ["Ace", "2", "3", "4", "5", "6", "7", "8", "9", "10", "Jack", "Queen", "King"] 37 | 38 | self.cardname = "{0} of {1}".format(rank[n - 1], s) 39 | return self.cardname 40 | 41 | def draw(self, win, center): 42 | filename = "{0}{1}".format(self.rank, self.suit.upper()) 43 | card = Image(center, filename) 44 | card.draw(win) 45 | -------------------------------------------------------------------------------- /chap10/Playing_Card_Images/purple_back.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/drycode/zelle-python/ccd781784bf2a635d1f6e84ec2173d2ae7d50098/chap10/Playing_Card_Images/purple_back.png -------------------------------------------------------------------------------- /chap10/Playing_Card_Images/red_back.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/drycode/zelle-python/ccd781784bf2a635d1f6e84ec2173d2ae7d50098/chap10/Playing_Card_Images/red_back.png -------------------------------------------------------------------------------- /chap10/Playing_Card_Images/yellow_back.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/drycode/zelle-python/ccd781784bf2a635d1f6e84ec2173d2ae7d50098/chap10/Playing_Card_Images/yellow_back.png -------------------------------------------------------------------------------- /chap10/cball3.py: -------------------------------------------------------------------------------- 1 | from math import radians, cos, sin 2 | 3 | class Projectile: 4 | 5 | def __init__(self, angle, velocity, height): 6 | self.xpos = 0.0 7 | self.ypos = height 8 | theta = radians(angle) 9 | self.xvel = velocity * cos(theta) 10 | self.yvel = velocity * sin(theta) 11 | 12 | def update(self, time): 13 | self.xpos = self.xpos + time * self.xvel 14 | yvel1 = self.yvel - 9.8 * time 15 | self.ypos = self.ypos + time * (self.yvel + yvel1) / 2.0 16 | self.yvel = yvel1 17 | 18 | def getX(self): 19 | return self.xpos 20 | 21 | def getY(self): 22 | return self.ypos 23 | 24 | def getInputs(): 25 | a = eval(input("Enter the launch angle (in degrees): ")) 26 | v = eval(input("Enter the initial velocity (in meters/sec): ")) 27 | h = eval(input("Enter the initial height (in meters): ")) 28 | t = eval(input( 29 | "Enter the time interval between position calculations: ")) 30 | return a, v, h, t 31 | 32 | def main(): 33 | angle, vel, h0, time = getInputs() 34 | cball = Projectile(angle, vel, h0) 35 | while cball.getY() >= 0: 36 | cball.update(time) 37 | print("\nDistance traveled: {0:0.1f} meters.".format(cball.getX())) 38 | 39 | main() 40 | -------------------------------------------------------------------------------- /chap10/cball4.py: -------------------------------------------------------------------------------- 1 | #cball4.py 2 | from projectile import Projectile 3 | 4 | def getInputs(): 5 | a = eval(input("Enter the launch angle (in degrees): ")) 6 | v = eval(input("Enter the initial velocity (in meters/sec): ")) 7 | h = eval(input("Enter the initial height (in meters): ")) 8 | t = eval(input( 9 | "Enter the time interval between position calculations: ")) 10 | return a, v, h, t 11 | 12 | def main(): 13 | angle, vel, h0, time = getInputs() 14 | cball = Projectile(angle, vel, h0) 15 | while cball.getY() >= 0: 16 | cball.update(time) 17 | print("\nDistance traveled: {0:0.1f} meters.".format(cball.getX())) 18 | 19 | main() 20 | -------------------------------------------------------------------------------- /chap10/cube.py: -------------------------------------------------------------------------------- 1 | #cube.py 2 | 3 | class Cube: 4 | """This class represents a geometric solid cube. 5 | It will return side length, surface area, and volume 6 | using getSideLength(), surfaceArea(), and volume().""" 7 | 8 | def __init__(self, side): 9 | self.side = side 10 | 11 | def getSideLength(self): 12 | return self.side 13 | 14 | def surfaceArea(self): 15 | self.surfaceArea = 6 * self.side ** 2 16 | return self.surfaceArea 17 | 18 | def volume(self): 19 | self.volume = self.side ** 3 20 | return self.volume 21 | -------------------------------------------------------------------------------- /chap10/discuss_3.py: -------------------------------------------------------------------------------- 1 | class Bozo: 2 | 3 | def __init__(self, value): 4 | print("Creating a Bozo from:", value) 5 | self.value = 2 * value 6 | 7 | def clown(self, x): 8 | print("Clowning:", x) 9 | print(x * self.value) 10 | return x + self.value 11 | 12 | def main(): 13 | print("Clowning around now.") 14 | c1 = Bozo(3) 15 | c2 = Bozo(4) 16 | print(c1.clown(3)) 17 | print(c2.clown(c1.clown(2))) 18 | 19 | main() 20 | -------------------------------------------------------------------------------- /chap10/exercise_1.py: -------------------------------------------------------------------------------- 1 | from projectile import Projectile 2 | 3 | def getInputs(): 4 | a = eval(input("Enter the launch angle (in degrees): ")) 5 | v = eval(input("Enter the initial velocity (in meters/sec): ")) 6 | h = eval(input("Enter the initial height (in meters): ")) 7 | t = eval(input( 8 | "Enter the time interval between position calculations: ")) 9 | return a, v, h, t 10 | 11 | def main(): 12 | angle, vel, h0, time = getInputs() 13 | cball = Projectile(angle, vel, h0) 14 | maxY = 0 15 | while cball.getY() >= 0: 16 | cball.update(time) 17 | if cball.getY() > maxY: 18 | maxY = cball.getY() 19 | print("\nDistance traveled: {0:0.1f} meters.".format(cball.getX())) 20 | print("Max height: {0:0.1f} meters.".format(maxY)) 21 | 22 | main() 23 | -------------------------------------------------------------------------------- /chap10/exercise_10.py: -------------------------------------------------------------------------------- 1 | from cube import Cube 2 | 3 | def main(): 4 | side = eval(input("What is the side length of your cube? ")) 5 | cube = Cube(side) 6 | A = cube.surfaceArea() 7 | V = cube.volume() 8 | print("The volume of your cube is {0:0.1f}.".format(V)) 9 | print("The area of your cube is {0:0.1f}.".format(A)) 10 | main() 11 | -------------------------------------------------------------------------------- /chap10/exercise_11.py: -------------------------------------------------------------------------------- 1 | from playingcard import PlayingCard 2 | from random import random 3 | 4 | def main(): 5 | n = 20 6 | for i in range (n): 7 | x = int(random() * 13) + 1 8 | y = int(random() * 4) 9 | suit = ['d', 's', 'h', 'c'] 10 | card = PlayingCard(x, suit[y]) 11 | print(card) 12 | print(card.BJValue()) 13 | print() 14 | main() 15 | -------------------------------------------------------------------------------- /chap10/exercise_12.py: -------------------------------------------------------------------------------- 1 | from playingcard import PlayingCard 2 | from graphics import * 3 | from random import random 4 | 5 | def main(): 6 | win = GraphWin("Playing Card", 700, 1100) 7 | win.setCoords(-10, -10, 10, 10) 8 | 9 | n = 5 10 | for i in range (n): 11 | x = int(random() * 13) + 1 12 | y = int(random() * 4) 13 | suit = ['d', 's', 'h', 'c'] 14 | card = PlayingCard(x, suit[y]) 15 | card.draw(win, Point(0,0)) 16 | win.getMouse() 17 | 18 | main() 19 | 20 | -------------------------------------------------------------------------------- /chap10/exercise_13.py: -------------------------------------------------------------------------------- 1 | from face import Face 2 | from graphics import * 3 | from cbutton import CButton 4 | 5 | def makeButtons(win): 6 | wink = CButton(win, Point(16, 17), 1, "Wink") 7 | meditate = CButton(win, Point(12, 17), 1, "Meditate") 8 | smile = CButton(win, Point(8, 17), 1, "Smile") 9 | endGame = CButton(win, Point(4, 17), 1, "Quit") 10 | wink.activate() 11 | meditate.activate() 12 | smile.activate() 13 | endGame.activate() 14 | 15 | return wink, meditate, smile, endGame 16 | 17 | def main(): 18 | win = GraphWin("Emoji Jawn", 800, 800) 19 | win.setCoords(20, 20, 0, 0) 20 | face = Face(win, Point(10,8), 7) 21 | wink, meditate, smile, endGame = makeButtons(win) 22 | 23 | pt = win.getMouse() 24 | while not endGame.clicked(pt): 25 | if wink.clicked(pt): 26 | face.wink() 27 | pt = win.getMouse() 28 | elif smile.clicked(pt): 29 | face.smile() 30 | pt = win.getMouse() 31 | elif meditate.clicked(pt): 32 | face.meditate() 33 | pt = win.getMouse() 34 | else: 35 | pt = win.getMouse() 36 | main() 37 | -------------------------------------------------------------------------------- /chap10/exercise_14.py: -------------------------------------------------------------------------------- 1 | from face import Face 2 | from graphics import * 3 | from time import sleep 4 | import math as m 5 | 6 | #Modify the face class from the previous problem to include a move 7 | #method similar to other grahpics objects. Using the move method, create a 8 | #program that makes a face bounce around in a window (see Programming Ex17 9 | #Chap7). Bonus: have the face change expression each time it "hits" the edge 10 | #of the window. 11 | 12 | #Bonus incomplete 13 | 14 | def main(): 15 | win = GraphWin("Bouncing Face", 500, 500) 16 | win.setCoords(100, 100, -100, -100) 17 | 18 | face = Face(win, Point(0,0), 15) 19 | 20 | dx = 5 21 | dy = 5 22 | 23 | for i in range(10000): 24 | c = face.getCenter() 25 | 26 | if c.getX() > 80: 27 | dx = -5 28 | elif c.getX() < -80: 29 | dx = 5 30 | elif c.getY() > 80: 31 | dy = -5 32 | elif c.getY() < -80: 33 | dy = 5 34 | sleep(0.005) 35 | face.move(dx,dy) 36 | main() 37 | -------------------------------------------------------------------------------- /chap10/exercise_15.py: -------------------------------------------------------------------------------- 1 | import math as m 2 | from tracker import Tracker 3 | from projectile import Projectile 4 | from graphics import * 5 | 6 | def main(): 7 | win = GraphWin("Projectile Tracker", 600, 600) 8 | win.setCoords(0, 0, 1400, 1400) 9 | missile = Projectile(45, 100, 0) 10 | tracker = Tracker(win, missile, 1400) 11 | while missile.getY() >= 0: 12 | missile.update(.05) 13 | dx = missile.getX() 14 | dy = missile.getY() 15 | tracker.move(dx, dy) 16 | print("{}:{}".format(missile.getX(), missile.getY())) 17 | 18 | 19 | main() -------------------------------------------------------------------------------- /chap10/exercise_16.py: -------------------------------------------------------------------------------- 1 | import math as m 2 | from tracker import Tracker 3 | from projectile import Projectile 4 | from graphics import * 5 | from button import Button 6 | 7 | def main(): 8 | win = GraphWin("Projectile Tracker", 600, 600) 9 | win.setCoords(0, 0, 1400, 1400) 10 | missile = Projectile(45, 100, 0) 11 | tracker = Tracker(win, missile, 1400) 12 | target = Button(win, Point(1021, 70), 140, 140, "x") 13 | target.activate() 14 | click = Point(missile.getX(), missile.getY()) 15 | while not target.clicked(click): 16 | missile.update(.05) 17 | dx = missile.getX() 18 | dy = missile.getY() 19 | tracker.move(dx, dy) 20 | click = tracker.getPosition() 21 | print(click.getX(), click.getY()) 22 | if dy <= 0: 23 | angle = eval(input("Angle: ")) 24 | velocity = eval(input("Velocity: ")) 25 | height = eval(input("Initial Height: ")) 26 | missile = Projectile(angle, velocity, height) 27 | 28 | main() -------------------------------------------------------------------------------- /chap10/exercise_17.py: -------------------------------------------------------------------------------- 1 | from zelle_modules.regression import Regression 2 | from graphics import * 3 | 4 | def graphWin(Title): 5 | #Create a graphics window with button in bottom left corner 6 | win = GraphWin(Title, 400, 400) 7 | win.setCoords(-10, -10, 10, 10) 8 | #Tell user to select multiple locations on the screen to designate points 9 | message = Text(Point(-5, 8), "Click to delineate points on the graph.") 10 | message.draw(win) 11 | 12 | axisX = Line(Point(-10,0), Point(10,0)) 13 | axisX.draw(win) 14 | 15 | axisY = Line(Point(0,10), Point(0,-10)) 16 | axisY.draw(win) 17 | 18 | r = Rectangle(Point(-9, -9), Point(-7,-8)) 19 | r.draw(win) 20 | rCenter = r.getCenter() 21 | stopMouse = Text(rCenter, "Done") 22 | stopMouse.draw(win) 23 | return win 24 | 25 | 26 | def main(): 27 | win = graphWin("Regression Line") 28 | allPoints = [] 29 | bestfit = Regression(win, allPoints, -10, 10) 30 | click = win.getMouse() 31 | click.draw(win) 32 | p1 = win.getMouse() 33 | p1.draw(win) 34 | bestfit.addPoint(p1) 35 | bestfit.addPoint(click) 36 | bestfit.drawRegressionLine(win) 37 | 38 | while True: 39 | click = win.getMouse() 40 | if ((-9 <= click.getX() <= -7) and (-9 <= click.getY() <= -8)): 41 | break 42 | else: 43 | #Store user points in an appended list 44 | bestfit.addPoint(click) 45 | click.draw(win) 46 | bestfit.unDraw() 47 | bestfit.drawRegressionLine(win) 48 | if __name__ == '__main__': main() -------------------------------------------------------------------------------- /chap10/exercise_2.py: -------------------------------------------------------------------------------- 1 | #graphical program to trace random walk in 2 dimensions 2 | 3 | import math as m 4 | from random import random 5 | from graphics import * 6 | from button import Button 7 | 8 | def main(): 9 | n = 100 10 | win = GraphWin("Random Walk", 1200, 1200) 11 | win.setCoords(-100, -100, 100, 100) 12 | 13 | newWalk = Button(win, Point(-80, -80), 30, 20, "Random Walk") 14 | quitButton = Button(win, Point(80, -80), 30, 20, "Quit") 15 | newWalk.activate() 16 | pt = win.getMouse() 17 | point = Point(0, 0) 18 | 19 | while not quitButton.clicked(pt): 20 | newWalk.deactivate() 21 | randWalk(n, win, point) 22 | newWalk.activate() 23 | quitButton.activate() 24 | pt = win.getMouse() 25 | while not (newWalk.clicked(pt) or quitButton.clicked(pt)): 26 | pt = win.getMouse() 27 | point = Point((2 * random() - 1) * 80, (2 * random() - 1) * 80) 28 | win.close() 29 | 30 | 31 | 32 | 33 | def randWalk(n, win, point): 34 | point2 = point 35 | for i in range (n): 36 | x = point2.getX() 37 | y = point2.getY() 38 | 39 | point1 = simOneStep(x, y) 40 | point1.draw(win) 41 | line = Line(point2, point1) 42 | line.draw(win) 43 | point2 = point1 44 | 45 | def simOneStep(x, y): 46 | angle = random() * 2 * m.pi 47 | x = x + m.cos(angle) 48 | y = y + m.sin(angle) 49 | point = Point(x, y) 50 | return point 51 | 52 | if __name__ == '__main__': main() 53 | -------------------------------------------------------------------------------- /chap10/exercise_5.py: -------------------------------------------------------------------------------- 1 | class Student: 2 | def __init__(self, name, hours, qpoints): 3 | self.name = name 4 | self.hours = float(hours) 5 | self.qpoints = float(qpoints) 6 | 7 | def getName(self): 8 | return self.name 9 | 10 | def getHours(self): 11 | return self.hours 12 | 13 | def getQPoints(self): 14 | return self.qpoints 15 | 16 | def gpa(self): 17 | return self.qpoints / self.hours 18 | 19 | def addGrade(self, gradePoint, credits): 20 | self.hours = float(self.hours) + float(credits) 21 | self.qpoints = self.qpoints + (gradePoint * credits) 22 | 23 | def makeStudent(infoStr): 24 | #inforStr is a tap-separated line: name hours getQPoints 25 | #returns a corresponding Student object 26 | name, hours, qpoints = infoStr.split("\t") 27 | return Student(name, hours, qpoints) 28 | 29 | def main(): 30 | new = makeStudent("Smith, Frank 0 0") 31 | x, y = eval(input("Input gradepoint and credits, separated by a comma: ")) 32 | new.addGrade(x, y) 33 | print(new.getHours(), new.getQPoints()) 34 | print(new.gpa()) 35 | 36 | main() 37 | -------------------------------------------------------------------------------- /chap10/exercise_7.py: -------------------------------------------------------------------------------- 1 | #roller1.py 2 | #Graphics program to roll a pair of dice. Uses custom widgets 3 | #Button and DieView 4 | 5 | from random import randrange 6 | from graphics import GraphWin, Point 7 | 8 | from cbutton import CButton 9 | from dieview import DieView 10 | 11 | def main(): 12 | #create the application window 13 | win = GraphWin("Dice Roller") 14 | win.setCoords(0, 0, 10, 10) 15 | win.setBackground("green2") 16 | 17 | #Draw the interface widgets 18 | die1 = DieView(win, Point(3, 7), 2) 19 | die2 = DieView(win, Point(7, 7), 2) 20 | rollButton = CButton(win, Point(2, 2.5), 1.5, "Roll Dice") 21 | rollButton.activate() 22 | quitButton = CButton(win, Point(8, 2.5), 1.5, "Quit") 23 | 24 | #Event loop 25 | pt = win.getMouse() 26 | while not quitButton.clicked(pt): 27 | if rollButton.clicked(pt): 28 | #value1 = randrange(1, 7) 29 | die1.roll() 30 | die2.roll() 31 | quitButton.activate() 32 | pt = win.getMouse() 33 | 34 | #close up shop 35 | win.close() 36 | 37 | main() 38 | -------------------------------------------------------------------------------- /chap10/exercise_8.py: -------------------------------------------------------------------------------- 1 | #roller.py 2 | #Graphics program to roll a pair of dice. uses custom widgets 3 | #Button and DieView 4 | 5 | from random import randrange 6 | from random import random 7 | from graphics import GraphWin, Point, color_rgb 8 | 9 | from button import Button 10 | from dieview import DieView 11 | 12 | def main(): 13 | #create the application window 14 | win = GraphWin("Dice Roller") 15 | win.setCoords(0, 0, 10, 10) 16 | win.setBackground("green2") 17 | 18 | #Draw the interface widgets 19 | die1 = DieView(win, Point(3, 7), 2) 20 | die2 = DieView(win, Point(7, 7), 2) 21 | rollButton = Button(win, Point(5, 4.5), 5, 1, "Roll Dice") 22 | rollButton.activate() 23 | quitButton = Button(win, Point(5, 1), 2, 1, "Quit") 24 | 25 | #Event loop 26 | pt = win.getMouse() 27 | while not quitButton.clicked(pt): 28 | r, g, b = int(random() * 255), int(random() * 255), int(random() * 255) 29 | if rollButton.clicked(pt): 30 | value1 = randrange(1, 7) 31 | die1.setColor(color_rgb(r,g,b)) 32 | die2.setColor(color_rgb(r,g,b)) 33 | die1.setValue(value1) 34 | value2 = randrange(1, 7) 35 | die2.setValue(value2) 36 | quitButton.activate() 37 | pt = win.getMouse() 38 | 39 | #close up shop 40 | win.close() 41 | 42 | main() 43 | -------------------------------------------------------------------------------- /chap10/exercise_9.py: -------------------------------------------------------------------------------- 1 | from sphere import Sphere 2 | 3 | def main(): 4 | r = eval(input("What is the radius of your sphere? ")) 5 | s = Sphere(r) 6 | A = s.surfaceArea() 7 | V = s.volume() 8 | print("The volume of your sphere is {0:0.1f}.".format(V)) 9 | print("The area of your sphere is {0:0.1f}.".format(A)) 10 | main() 11 | -------------------------------------------------------------------------------- /chap10/gpa.py: -------------------------------------------------------------------------------- 1 | #gpa.py 2 | # Program to find student with highest GPA 3 | 4 | class Student: 5 | def __init__(self, name, hours, qpoints): 6 | self.name = name 7 | self.hours = float(hours) 8 | self.qpoints = float(qpoints) 9 | 10 | def getName(self): 11 | return self.name 12 | 13 | def getHours(self): 14 | return self.hours 15 | 16 | def getQPoints(self): 17 | return self.qpoints 18 | 19 | def gpa(self): 20 | return self.qpoints / self.hours 21 | 22 | def makeStudent(infoStr): 23 | #inforStr is a tap-separated line: name hours getQPoints 24 | #returns a corresponding Student object 25 | name, hours, qpoints = infoStr.split("\t") 26 | return Student(name, hours, qpoints) 27 | 28 | def main(): 29 | #open the input file for reading 30 | filename = input("Enter the name of the grade file: ") 31 | infile = open(filename, 'r') 32 | 33 | #set best to the record for the first student in the file 34 | best = makeStudent(infile.readline()) 35 | 36 | #process subsequent lines of the file 37 | for line in infile: 38 | #turn the line into a student record 39 | s = makeStudent(line) 40 | #if this student is best so far, remember it. 41 | if s.gpa() > best.gpa(): 42 | best = s 43 | infile.close() 44 | 45 | #print information about the best student 46 | print("The best student is:", best.getName()) 47 | print("hours:", best.getHours()) 48 | print("GPA:", best.gpa()) 49 | 50 | if __name__ == '__main__': 51 | main() 52 | -------------------------------------------------------------------------------- /chap10/gpa.txt: -------------------------------------------------------------------------------- 1 | Adams, Henry 127 228 2 | Computewell, Susan 100 400 3 | DibbleBit, Denny 18 41.5 4 | Jones, Jim 48.5 155 5 | Smith, Frank 37 125.33 6 | -------------------------------------------------------------------------------- /chap10/msdie.py: -------------------------------------------------------------------------------- 1 | #msdie.py 2 | # Class definition for an n-sided die. 3 | from random import randrange 4 | 5 | class Person: 6 | def __init__(self, name, age): 7 | this.name = name 8 | this.age = age 9 | 10 | class MSDie: 11 | def __init__(self, sides): 12 | self.sides = sides 13 | self.value = 1 14 | 15 | def roll(self): 16 | self.value = randrange(1, self.sides + 1) 17 | 18 | def getValue(self): 19 | return self.value 20 | 21 | def setValue(self, value): 22 | self.value = value 23 | 24 | def main(): 25 | die1 = MSDie(12) 26 | die2 = MSDie(100) 27 | die1.roll() 28 | print(die1.getValue()) 29 | 30 | main() 31 | -------------------------------------------------------------------------------- /chap10/playingcard.py: -------------------------------------------------------------------------------- 1 | #playingcard.py 2 | from graphics import * 3 | import Playing_Card_Images 4 | 5 | class PlayingCard: 6 | 7 | def __init__(self, rank, suit): 8 | self.rank = rank 9 | self.suit = suit 10 | 11 | def getRank(self): 12 | return self.rank 13 | 14 | def getSuit(self): 15 | return self.suit 16 | 17 | def BJValue(self): 18 | if 10 <= self.rank <= 13: 19 | self.rank = 10 20 | else: 21 | self.rank = self.rank 22 | return self.rank 23 | 24 | def __str__(self): 25 | n = self.rank 26 | if self.suit == 'd': 27 | s = "Diamonds" 28 | elif self.suit == 's': 29 | s = "Spades" 30 | elif self.suit == 'h': 31 | s = "Hearts" 32 | else: 33 | s = "Clubs" 34 | 35 | rank = ["Ace", "2", "3", "4", "5", "6", "7", "8", "9", "10", "Jack", "Queen", "King"] 36 | 37 | self.cardname = "{0} of {1}".format(rank[n - 1], s) 38 | return self.cardname 39 | 40 | def draw(self, win, center): 41 | filename = "./Playing_Card_Images/{0}{1}.png".format(self.rank, self.suit.upper()) 42 | card = Image(center, filename) 43 | card.draw(win) -------------------------------------------------------------------------------- /chap10/projectile.py: -------------------------------------------------------------------------------- 1 | """projectile.py 2 | Provides a simple class for modeling the 3 | flight of projectiles.""" 4 | 5 | from math import radians, cos, sin 6 | 7 | class Projectile: 8 | 9 | """Simulates the flight of simple porjectiles near the earth's 10 | surface, ignoring wind resistance. Tracking is done in two 11 | dimensions, height (y) and distance (x).""" 12 | 13 | def __init__(self, angle, velocity, height): 14 | """Create a projectile with given launch angle, 15 | initial velocity and height.""" 16 | self.xpos = 0.0 17 | self.ypos = height 18 | theta = radians(angle) 19 | self.xvel = velocity * cos(theta) 20 | self.yvel = velocity * sin(theta) 21 | 22 | def update(self, time): 23 | """Update the state of this projectile to move it time seconds 24 | farther into its flight""" 25 | self.xpos = self.xpos + time * self.xvel 26 | yvel1 = self.yvel - 9.8 * time 27 | self.ypos = self.ypos + time * (self.yvel + yvel1) / 2.0 28 | self.yvel = yvel1 29 | 30 | def getX(self): 31 | """Returns the x position (distance) of this projectile.""" 32 | return self.xpos 33 | 34 | def getY(self): 35 | """Returns the y position (height) of this projectile.""" 36 | return self.ypos 37 | -------------------------------------------------------------------------------- /chap10/roller.py: -------------------------------------------------------------------------------- 1 | #roller.py 2 | #Graphics program to roll a pair of dice. uses custom widgets 3 | #Button and DieView 4 | 5 | from random import randrange 6 | from graphics import GraphWin, Point 7 | 8 | from button import Button 9 | from dieview import DieView 10 | 11 | def main(): 12 | #create the application window 13 | win = GraphWin("Dice Roller") 14 | win.setCoords(0, 0, 10, 10) 15 | win.setBackground("green2") 16 | 17 | #Draw the interface widgets 18 | die1 = DieView(win, Point(3, 7), 2) 19 | die2 = DieView(win, Point(7, 7), 2) 20 | rollButton = Button(win, Point(5, 4.5), 5, 1, "Roll Dice") 21 | rollButton.activate() 22 | quitButton = Button(win, Point(5, 1), 2, 1, "Quit") 23 | 24 | #Event loop 25 | pt = win.getMouse() 26 | while not quitButton.clicked(pt): 27 | if rollButton.clicked(pt): 28 | value1 = randrange(1, 7) 29 | die1.setValue(value1) 30 | value2 = randrange(1, 7) 31 | die2.setValue(value2) 32 | quitButton.activate() 33 | pt = win.getMouse() 34 | 35 | #close up shop 36 | win.close() 37 | 38 | main() 39 | -------------------------------------------------------------------------------- /chap10/sphere.py: -------------------------------------------------------------------------------- 1 | #sphere.py 2 | from math import pi 3 | 4 | class Sphere: 5 | """This class represents a geometric solid sphere. 6 | it will return radius, surface area, and volume 7 | using getRadius(), surfaceArea(), and volume().""" 8 | 9 | def __init__(self, radius): 10 | self.radius = radius 11 | 12 | def getRadius(self): 13 | return self.radius 14 | 15 | def surfaceArea(self): 16 | self.surfaceArea = 4 * pi * (self.radius * self.radius) 17 | return self.surfaceArea 18 | 19 | def volume(self): 20 | self.volume = 4/3 * pi * (self.radius ** 3) 21 | return self.volume 22 | -------------------------------------------------------------------------------- /chap10/tracker.py: -------------------------------------------------------------------------------- 1 | #tracker.py 2 | from graphics import * 3 | 4 | class Tracker: 5 | def __init__(self, window, objToTrack, max_min_X_coords): 6 | #window is a graphWin and objToTrack is an object whose 7 | #position is to be shown in the window. 8 | self.window = window 9 | # objToTrack is 10 | #an object that has getX() and getY() methods that 11 | #report its current position. 12 | self.objToTrack = objToTrack 13 | #Creates a Tracker object and draws a circle in window 14 | #at the current position of objToTrack 15 | xpos = objToTrack.getX() 16 | ypos = objToTrack.getY() 17 | self.center = Point(xpos, ypos) 18 | self.size = max_min_X_coords/100 19 | self.tracker = Circle(self.center, self.size) 20 | 21 | 22 | def initializeTracker(self): 23 | self.tracker = Circle(self.center, self.size) 24 | self.tracker.setFill("black") 25 | self.tracker.draw(self.window) 26 | 27 | def move(self, dx, dy): 28 | #Moves the circle in the window to the current position 29 | # of the object being tracked 30 | self.tracker.undraw() 31 | self.center = Point(dx, dy) 32 | self.initializeTracker() 33 | 34 | def getPosition(self): 35 | return self.center -------------------------------------------------------------------------------- /chap11/Playing_Card_Images/10C.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/drycode/zelle-python/ccd781784bf2a635d1f6e84ec2173d2ae7d50098/chap11/Playing_Card_Images/10C.png -------------------------------------------------------------------------------- /chap11/Playing_Card_Images/10D.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/drycode/zelle-python/ccd781784bf2a635d1f6e84ec2173d2ae7d50098/chap11/Playing_Card_Images/10D.png -------------------------------------------------------------------------------- /chap11/Playing_Card_Images/10H.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/drycode/zelle-python/ccd781784bf2a635d1f6e84ec2173d2ae7d50098/chap11/Playing_Card_Images/10H.png -------------------------------------------------------------------------------- /chap11/Playing_Card_Images/10S.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/drycode/zelle-python/ccd781784bf2a635d1f6e84ec2173d2ae7d50098/chap11/Playing_Card_Images/10S.png -------------------------------------------------------------------------------- /chap11/Playing_Card_Images/11C.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/drycode/zelle-python/ccd781784bf2a635d1f6e84ec2173d2ae7d50098/chap11/Playing_Card_Images/11C.png -------------------------------------------------------------------------------- /chap11/Playing_Card_Images/11D.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/drycode/zelle-python/ccd781784bf2a635d1f6e84ec2173d2ae7d50098/chap11/Playing_Card_Images/11D.png -------------------------------------------------------------------------------- /chap11/Playing_Card_Images/11H.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/drycode/zelle-python/ccd781784bf2a635d1f6e84ec2173d2ae7d50098/chap11/Playing_Card_Images/11H.png -------------------------------------------------------------------------------- /chap11/Playing_Card_Images/11S.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/drycode/zelle-python/ccd781784bf2a635d1f6e84ec2173d2ae7d50098/chap11/Playing_Card_Images/11S.png -------------------------------------------------------------------------------- /chap11/Playing_Card_Images/12C.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/drycode/zelle-python/ccd781784bf2a635d1f6e84ec2173d2ae7d50098/chap11/Playing_Card_Images/12C.png -------------------------------------------------------------------------------- /chap11/Playing_Card_Images/12D.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/drycode/zelle-python/ccd781784bf2a635d1f6e84ec2173d2ae7d50098/chap11/Playing_Card_Images/12D.png -------------------------------------------------------------------------------- /chap11/Playing_Card_Images/12H.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/drycode/zelle-python/ccd781784bf2a635d1f6e84ec2173d2ae7d50098/chap11/Playing_Card_Images/12H.png -------------------------------------------------------------------------------- /chap11/Playing_Card_Images/12S.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/drycode/zelle-python/ccd781784bf2a635d1f6e84ec2173d2ae7d50098/chap11/Playing_Card_Images/12S.png -------------------------------------------------------------------------------- /chap11/Playing_Card_Images/13C.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/drycode/zelle-python/ccd781784bf2a635d1f6e84ec2173d2ae7d50098/chap11/Playing_Card_Images/13C.png -------------------------------------------------------------------------------- /chap11/Playing_Card_Images/13D.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/drycode/zelle-python/ccd781784bf2a635d1f6e84ec2173d2ae7d50098/chap11/Playing_Card_Images/13D.png -------------------------------------------------------------------------------- /chap11/Playing_Card_Images/13H.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/drycode/zelle-python/ccd781784bf2a635d1f6e84ec2173d2ae7d50098/chap11/Playing_Card_Images/13H.png -------------------------------------------------------------------------------- /chap11/Playing_Card_Images/13S.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/drycode/zelle-python/ccd781784bf2a635d1f6e84ec2173d2ae7d50098/chap11/Playing_Card_Images/13S.png -------------------------------------------------------------------------------- /chap11/Playing_Card_Images/1C.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/drycode/zelle-python/ccd781784bf2a635d1f6e84ec2173d2ae7d50098/chap11/Playing_Card_Images/1C.png -------------------------------------------------------------------------------- /chap11/Playing_Card_Images/1D.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/drycode/zelle-python/ccd781784bf2a635d1f6e84ec2173d2ae7d50098/chap11/Playing_Card_Images/1D.png -------------------------------------------------------------------------------- /chap11/Playing_Card_Images/1H.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/drycode/zelle-python/ccd781784bf2a635d1f6e84ec2173d2ae7d50098/chap11/Playing_Card_Images/1H.png -------------------------------------------------------------------------------- /chap11/Playing_Card_Images/1S.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/drycode/zelle-python/ccd781784bf2a635d1f6e84ec2173d2ae7d50098/chap11/Playing_Card_Images/1S.png -------------------------------------------------------------------------------- /chap11/Playing_Card_Images/2C.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/drycode/zelle-python/ccd781784bf2a635d1f6e84ec2173d2ae7d50098/chap11/Playing_Card_Images/2C.png -------------------------------------------------------------------------------- /chap11/Playing_Card_Images/2D.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/drycode/zelle-python/ccd781784bf2a635d1f6e84ec2173d2ae7d50098/chap11/Playing_Card_Images/2D.png -------------------------------------------------------------------------------- /chap11/Playing_Card_Images/2H.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/drycode/zelle-python/ccd781784bf2a635d1f6e84ec2173d2ae7d50098/chap11/Playing_Card_Images/2H.png -------------------------------------------------------------------------------- /chap11/Playing_Card_Images/2S.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/drycode/zelle-python/ccd781784bf2a635d1f6e84ec2173d2ae7d50098/chap11/Playing_Card_Images/2S.png -------------------------------------------------------------------------------- /chap11/Playing_Card_Images/3C.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/drycode/zelle-python/ccd781784bf2a635d1f6e84ec2173d2ae7d50098/chap11/Playing_Card_Images/3C.png -------------------------------------------------------------------------------- /chap11/Playing_Card_Images/3D.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/drycode/zelle-python/ccd781784bf2a635d1f6e84ec2173d2ae7d50098/chap11/Playing_Card_Images/3D.png -------------------------------------------------------------------------------- /chap11/Playing_Card_Images/3H.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/drycode/zelle-python/ccd781784bf2a635d1f6e84ec2173d2ae7d50098/chap11/Playing_Card_Images/3H.png -------------------------------------------------------------------------------- /chap11/Playing_Card_Images/3S.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/drycode/zelle-python/ccd781784bf2a635d1f6e84ec2173d2ae7d50098/chap11/Playing_Card_Images/3S.png -------------------------------------------------------------------------------- /chap11/Playing_Card_Images/4C.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/drycode/zelle-python/ccd781784bf2a635d1f6e84ec2173d2ae7d50098/chap11/Playing_Card_Images/4C.png -------------------------------------------------------------------------------- /chap11/Playing_Card_Images/4D.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/drycode/zelle-python/ccd781784bf2a635d1f6e84ec2173d2ae7d50098/chap11/Playing_Card_Images/4D.png -------------------------------------------------------------------------------- /chap11/Playing_Card_Images/4H.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/drycode/zelle-python/ccd781784bf2a635d1f6e84ec2173d2ae7d50098/chap11/Playing_Card_Images/4H.png -------------------------------------------------------------------------------- /chap11/Playing_Card_Images/4S.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/drycode/zelle-python/ccd781784bf2a635d1f6e84ec2173d2ae7d50098/chap11/Playing_Card_Images/4S.png -------------------------------------------------------------------------------- /chap11/Playing_Card_Images/5C.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/drycode/zelle-python/ccd781784bf2a635d1f6e84ec2173d2ae7d50098/chap11/Playing_Card_Images/5C.png -------------------------------------------------------------------------------- /chap11/Playing_Card_Images/5D.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/drycode/zelle-python/ccd781784bf2a635d1f6e84ec2173d2ae7d50098/chap11/Playing_Card_Images/5D.png -------------------------------------------------------------------------------- /chap11/Playing_Card_Images/5H.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/drycode/zelle-python/ccd781784bf2a635d1f6e84ec2173d2ae7d50098/chap11/Playing_Card_Images/5H.png -------------------------------------------------------------------------------- /chap11/Playing_Card_Images/5S.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/drycode/zelle-python/ccd781784bf2a635d1f6e84ec2173d2ae7d50098/chap11/Playing_Card_Images/5S.png -------------------------------------------------------------------------------- /chap11/Playing_Card_Images/6C.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/drycode/zelle-python/ccd781784bf2a635d1f6e84ec2173d2ae7d50098/chap11/Playing_Card_Images/6C.png -------------------------------------------------------------------------------- /chap11/Playing_Card_Images/6D.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/drycode/zelle-python/ccd781784bf2a635d1f6e84ec2173d2ae7d50098/chap11/Playing_Card_Images/6D.png -------------------------------------------------------------------------------- /chap11/Playing_Card_Images/6H.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/drycode/zelle-python/ccd781784bf2a635d1f6e84ec2173d2ae7d50098/chap11/Playing_Card_Images/6H.png -------------------------------------------------------------------------------- /chap11/Playing_Card_Images/6S.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/drycode/zelle-python/ccd781784bf2a635d1f6e84ec2173d2ae7d50098/chap11/Playing_Card_Images/6S.png -------------------------------------------------------------------------------- /chap11/Playing_Card_Images/7C.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/drycode/zelle-python/ccd781784bf2a635d1f6e84ec2173d2ae7d50098/chap11/Playing_Card_Images/7C.png -------------------------------------------------------------------------------- /chap11/Playing_Card_Images/7D.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/drycode/zelle-python/ccd781784bf2a635d1f6e84ec2173d2ae7d50098/chap11/Playing_Card_Images/7D.png -------------------------------------------------------------------------------- /chap11/Playing_Card_Images/7H.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/drycode/zelle-python/ccd781784bf2a635d1f6e84ec2173d2ae7d50098/chap11/Playing_Card_Images/7H.png -------------------------------------------------------------------------------- /chap11/Playing_Card_Images/7S.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/drycode/zelle-python/ccd781784bf2a635d1f6e84ec2173d2ae7d50098/chap11/Playing_Card_Images/7S.png -------------------------------------------------------------------------------- /chap11/Playing_Card_Images/8C.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/drycode/zelle-python/ccd781784bf2a635d1f6e84ec2173d2ae7d50098/chap11/Playing_Card_Images/8C.png -------------------------------------------------------------------------------- /chap11/Playing_Card_Images/8D.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/drycode/zelle-python/ccd781784bf2a635d1f6e84ec2173d2ae7d50098/chap11/Playing_Card_Images/8D.png -------------------------------------------------------------------------------- /chap11/Playing_Card_Images/8H.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/drycode/zelle-python/ccd781784bf2a635d1f6e84ec2173d2ae7d50098/chap11/Playing_Card_Images/8H.png -------------------------------------------------------------------------------- /chap11/Playing_Card_Images/8S.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/drycode/zelle-python/ccd781784bf2a635d1f6e84ec2173d2ae7d50098/chap11/Playing_Card_Images/8S.png -------------------------------------------------------------------------------- /chap11/Playing_Card_Images/9C.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/drycode/zelle-python/ccd781784bf2a635d1f6e84ec2173d2ae7d50098/chap11/Playing_Card_Images/9C.png -------------------------------------------------------------------------------- /chap11/Playing_Card_Images/9D.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/drycode/zelle-python/ccd781784bf2a635d1f6e84ec2173d2ae7d50098/chap11/Playing_Card_Images/9D.png -------------------------------------------------------------------------------- /chap11/Playing_Card_Images/9H.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/drycode/zelle-python/ccd781784bf2a635d1f6e84ec2173d2ae7d50098/chap11/Playing_Card_Images/9H.png -------------------------------------------------------------------------------- /chap11/Playing_Card_Images/9S.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/drycode/zelle-python/ccd781784bf2a635d1f6e84ec2173d2ae7d50098/chap11/Playing_Card_Images/9S.png -------------------------------------------------------------------------------- /chap11/Playing_Card_Images/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/drycode/zelle-python/ccd781784bf2a635d1f6e84ec2173d2ae7d50098/chap11/Playing_Card_Images/__init__.py -------------------------------------------------------------------------------- /chap11/Playing_Card_Images/aces.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/drycode/zelle-python/ccd781784bf2a635d1f6e84ec2173d2ae7d50098/chap11/Playing_Card_Images/aces.png -------------------------------------------------------------------------------- /chap11/Playing_Card_Images/back_cards-07.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/drycode/zelle-python/ccd781784bf2a635d1f6e84ec2173d2ae7d50098/chap11/Playing_Card_Images/back_cards-07.png -------------------------------------------------------------------------------- /chap11/Playing_Card_Images/blue_back.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/drycode/zelle-python/ccd781784bf2a635d1f6e84ec2173d2ae7d50098/chap11/Playing_Card_Images/blue_back.png -------------------------------------------------------------------------------- /chap11/Playing_Card_Images/gray_back.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/drycode/zelle-python/ccd781784bf2a635d1f6e84ec2173d2ae7d50098/chap11/Playing_Card_Images/gray_back.png -------------------------------------------------------------------------------- /chap11/Playing_Card_Images/green_back.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/drycode/zelle-python/ccd781784bf2a635d1f6e84ec2173d2ae7d50098/chap11/Playing_Card_Images/green_back.png -------------------------------------------------------------------------------- /chap11/Playing_Card_Images/honor_clubs.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/drycode/zelle-python/ccd781784bf2a635d1f6e84ec2173d2ae7d50098/chap11/Playing_Card_Images/honor_clubs.png -------------------------------------------------------------------------------- /chap11/Playing_Card_Images/honor_diamond.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/drycode/zelle-python/ccd781784bf2a635d1f6e84ec2173d2ae7d50098/chap11/Playing_Card_Images/honor_diamond.png -------------------------------------------------------------------------------- /chap11/Playing_Card_Images/honor_heart-14.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/drycode/zelle-python/ccd781784bf2a635d1f6e84ec2173d2ae7d50098/chap11/Playing_Card_Images/honor_heart-14.png -------------------------------------------------------------------------------- /chap11/Playing_Card_Images/honors_spade-14.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/drycode/zelle-python/ccd781784bf2a635d1f6e84ec2173d2ae7d50098/chap11/Playing_Card_Images/honors_spade-14.png -------------------------------------------------------------------------------- /chap11/Playing_Card_Images/playingcard.py: -------------------------------------------------------------------------------- 1 | #playingcard.py 2 | from graphics import * 3 | import sys 4 | import os 5 | 6 | class PlayingCard: 7 | 8 | def __init__(self, rank, suit): 9 | self.rank = rank 10 | self.suit = suit 11 | 12 | def getRank(self): 13 | return self.rank 14 | 15 | def getSuit(self): 16 | return self.suit 17 | 18 | def BJValue(self): 19 | if 10 <= self.rank <= 13: 20 | self.rank = 10 21 | else: 22 | self.rank = self.rank 23 | return self.rank 24 | 25 | def __str__(self): 26 | n = self.rank 27 | if self.suit == 'd': 28 | s = "Diamonds" 29 | elif self.suit == 's': 30 | s = "Spades" 31 | elif self.suit == 'h': 32 | s = "Hearts" 33 | else: 34 | s = "Clubs" 35 | 36 | rank = ["Ace", "2", "3", "4", "5", "6", "7", "8", "9", "10", "Jack", "Queen", "King"] 37 | 38 | self.cardname = "{0} of {1}".format(rank[n - 1], s) 39 | return self.cardname 40 | 41 | def draw(self, win, center): 42 | filename = "{0}{1}".format(self.rank, self.suit.upper()) 43 | card = Image(center, filename) 44 | card.draw(win) 45 | -------------------------------------------------------------------------------- /chap11/Playing_Card_Images/purple_back.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/drycode/zelle-python/ccd781784bf2a635d1f6e84ec2173d2ae7d50098/chap11/Playing_Card_Images/purple_back.png -------------------------------------------------------------------------------- /chap11/Playing_Card_Images/red_back.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/drycode/zelle-python/ccd781784bf2a635d1f6e84ec2173d2ae7d50098/chap11/Playing_Card_Images/red_back.png -------------------------------------------------------------------------------- /chap11/Playing_Card_Images/yellow_back.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/drycode/zelle-python/ccd781784bf2a635d1f6e84ec2173d2ae7d50098/chap11/Playing_Card_Images/yellow_back.png -------------------------------------------------------------------------------- /chap11/discuss1.txt: -------------------------------------------------------------------------------- 1 | Christinas-iMac:zelle DanYoung$ import string 2 | bash: import: command not found 3 | Christinas-iMac:zelle DanYoung$ python import string 4 | (null): can't open file 'import': [Errno 2] No such file or directory 5 | Christinas-iMac:zelle DanYoung$ python 6 | Python 3.7.0 (v3.7.0:1bf9cc5093, Jun 26 2018, 23:26:24) 7 | [Clang 6.0 (clang-600.0.57)] on darwin 8 | Type "help", "copyright", "credits" or "license" for more information. 9 | >>> import string 10 | >>> s1 = [2,1,4,3] 11 | >>> s2 = ['c','a','b'] 12 | >>> s1 + s2 13 | [2, 1, 4, 3, 'c', 'a', 'b'] 14 | >>> 3 * s1 + 2 * s2 15 | [2, 1, 4, 3, 2, 1, 4, 3, 2, 1, 4, 3, 'c', 'a', 'b', 'c', 'a', 'b'] 16 | >>> s1[1] 17 | 1 18 | >>> s1[1:3] 19 | [1, 4] 20 | >>> s1 + s2[-1] 21 | Traceback (most recent call last): 22 | File "", line 1, in 23 | TypeError: can only concatenate list (not "str") to list 24 | >>> sl.append[s2[-1]] 25 | Traceback (most recent call last): 26 | File "", line 1, in 27 | NameError: name 'sl' is not defined 28 | >>> s1.append[s2[-1] 29 | ... } 30 | File "", line 2 31 | } 32 | ^ 33 | SyntaxError: invalid syntax 34 | >>> s1.append[s2[-1]] 35 | Traceback (most recent call last): 36 | File "", line 1, in 37 | TypeError: 'builtin_function_or_method' object is not subscriptable 38 | >>> s1.append(s2[-1]) 39 | >>> s1 40 | [2, 1, 4, 3, 'b'] 41 | >>> -------------------------------------------------------------------------------- /chap11/exercise_10.py: -------------------------------------------------------------------------------- 1 | #Sieve of Eratosthenes (finds prime numbers to range n) 2 | def sieve(list): 3 | newList = [] 4 | #take first item in list and announce as prime to initialize loop 5 | while len(list) != 0: 6 | #append newList with that number 7 | newList.append(list[0]) 8 | #remove multiples of that first number from the list 9 | #remove first number from the list 10 | try: 11 | for i in range(len(list)): 12 | if list[i] % list[0] == 0: 13 | list.remove(list[i]) 14 | except: 15 | newList 16 | return newList 17 | 18 | def main(): 19 | n = eval(input("Input value of n: ")) 20 | list = [] 21 | for i in range(n-1): 22 | list.append(i+2) 23 | list = sieve(list) 24 | #no idea why 4 remains after iterating through this logic....but this seems to be a nice workaround 25 | list.remove(4) 26 | print(list) 27 | 28 | main() -------------------------------------------------------------------------------- /chap11/exercise_11.py: -------------------------------------------------------------------------------- 1 | #censorship program 2 | 3 | def main(): 4 | filename = 'exercise_11.txt' 5 | infile = open(filename, 'r') 6 | outfile = open('exercise_11(1).txt', 'w') 7 | for line in infile: 8 | words = line.split() 9 | for i in range(len(words)): 10 | if len(words[i]) == 4: 11 | words[i] = '****' 12 | line = ' '.join(words) 13 | print((line), file = outfile) 14 | infile.close() 15 | outfile.close() 16 | 17 | main() 18 | 19 | -------------------------------------------------------------------------------- /chap11/exercise_12.py: -------------------------------------------------------------------------------- 1 | #censorship program 2 | def illegalWord(word): 3 | filename = 'exercise_12.txt' 4 | text = open(filename, 'r') 5 | censors = [] 6 | for x in text.readlines(): 7 | censors.append(x) 8 | for i in range(len(censors)): 9 | censors[i] = censors[i].strip('\n') 10 | for cen in censors: 11 | print(cen) 12 | if word == cen: 13 | return True 14 | def main(): 15 | filename = 'exercise_11.txt' 16 | infile = open(filename, 'r') 17 | outfile = open('exercise_11(1).txt', 'w') 18 | 19 | for line in infile: 20 | words = line.split() 21 | for i in range(len(words)): 22 | if illegalWord(words[i]): 23 | words[i] = '****' 24 | line = ' '.join(words) 25 | print((line), file = outfile) 26 | infile.close() 27 | outfile.close() 28 | 29 | main() 30 | 31 | -------------------------------------------------------------------------------- /chap11/exercise_12.txt: -------------------------------------------------------------------------------- 1 | Canada 2 | Japan 3 | Prime 4 | tariffs 5 | China 6 | want 7 | Mexico -------------------------------------------------------------------------------- /chap11/exercise_13.py: -------------------------------------------------------------------------------- 1 | from playingcard import PlayingCard 2 | from random import random 3 | from graphics import GraphWin, Point 4 | 5 | def main(): 6 | win = GraphWin("Playing Card", 700, 1100) 7 | win.setCoords(-10, -10, 10, 10) 8 | 9 | #create 52 card (13 per suit) parameters 10 | rank = ['C','D','H','S'] 11 | cardSpecs = [] 12 | for i in range(52): 13 | x = i % 13 + 1 14 | y = rank[i % 4] 15 | cardSpecs.append((x,y)) 16 | cards = [] 17 | for (x, y) in cardSpecs: 18 | cards.append(PlayingCard(x, y)) 19 | 20 | cards.sort(key=PlayingCard.getRank) 21 | cards.sort(key=PlayingCard.getSuit) 22 | for card in cards: 23 | card.draw(win, Point(0,0)) 24 | main() 25 | -------------------------------------------------------------------------------- /chap11/exercise_15.py: -------------------------------------------------------------------------------- 1 | from playingcard import PlayingCard 2 | from random import random 3 | 4 | class Deck: 5 | def __init__(self): 6 | rank = ['C','D','H','S'] 7 | cardSpecs = [] 8 | for i in range(52): 9 | x = i % 13 + 1 10 | y = rank[i % 4] 11 | cardSpecs.append((x,y)) 12 | self.cards = [] 13 | for (x, y) in cardSpecs: 14 | self.cards.append(PlayingCard(x, y)) 15 | 16 | def __shuffle(self): 17 | newList = [] 18 | for i in range (len(self.cards)): 19 | x = int(random() * len(self.cards)) - 1 20 | newList.append(self.cards[x]) 21 | self.cards.remove(self.cards[x]) 22 | return newList 23 | 24 | def shuffle(self): 25 | self.cards = self.__shuffle() 26 | 27 | def dealCard(self): 28 | return self.cards.pop(0) 29 | 30 | def cardsLeft(self): 31 | return len(self.cards) 32 | 33 | def main(): 34 | deck = Deck() 35 | deck.shuffle() 36 | for i in range(52): 37 | print(deck.dealCard()) 38 | main() 39 | 40 | 41 | -------------------------------------------------------------------------------- /chap11/exercise_16.py: -------------------------------------------------------------------------------- 1 | from math import sqrt 2 | 3 | class StatSet: 4 | def __init__(self): 5 | self.stats = [] 6 | 7 | def addNumber(self, x): 8 | self.stats.append(x) 9 | 10 | def mean(self): 11 | sum = 0.0 12 | for num in self.stats: 13 | sum = sum + num 14 | return sum / self.count() 15 | 16 | def median(self): 17 | self.stats.sort() 18 | size = len(self.stats) 19 | midPos = size // 2 20 | if size % 2 == 0: 21 | median = (self.stats[midPos] + self.stats[midPos - 1]) / 2 22 | else: 23 | median = self.stats[midPos] 24 | return median 25 | 26 | def stdDev(self): 27 | xbar = self.mean() 28 | sumDevSq = 0.0 29 | for num in self.stats: 30 | dev = xbar - num 31 | sumDevSq = sumDevSq + dev * dev 32 | return sqrt(sumDevSq/(len(self.stats) - 1)) 33 | 34 | def count(self): 35 | return len(self.stats) 36 | 37 | def min(self): 38 | self.stats.sort() 39 | return self.stats[0] 40 | 41 | def max(self): 42 | self.stats.sort(reverse=True) 43 | return self.stats[0] 44 | 45 | def main(): 46 | data = StatSet() 47 | for i in range(12): 48 | data.addNumber(i * 3/2) 49 | print(data.count()) 50 | print(data.mean()) 51 | print(data.median()) 52 | print(data.stdDev()) 53 | print(data.min()) 54 | print(data.max()) 55 | main() 56 | -------------------------------------------------------------------------------- /chap11/exercise_19.py: -------------------------------------------------------------------------------- 1 | """This set class represents a classical set.""" 2 | class Set: 3 | def __init__(self, elements): 4 | self.set = [] 5 | for i in elements: 6 | self.set.append(i) 7 | 8 | def addElement(self, x): 9 | self.set.append(x) 10 | 11 | def deleteElement(self, x): 12 | if self.member(x): 13 | self.set.remove(x) 14 | 15 | def member(self, x): 16 | if x in self.set: 17 | return True 18 | else: 19 | return False 20 | 21 | def intersection(self, set2): 22 | intersection = [] 23 | for x in set2: 24 | if x in (set2 and self.set): 25 | intersection.append(x) 26 | return intersection 27 | 28 | def union(self, set2): 29 | for x in set2: 30 | self.set.append(x) 31 | 32 | def subtract(self, set2): 33 | for x in set2: 34 | while x in self.set: 35 | self.set.remove(x) 36 | 37 | def getSet(self): 38 | return self.set 39 | 40 | def main(): 41 | list1 = ['cat', 'dog', 'fish', 'mouse', 'banana'] 42 | test = Set(list1) 43 | test.addElement('small') 44 | test.deleteElement('dog') 45 | 46 | list2 = ['flat', 'cat', 'rectangle', 'banana', 'dog', 'mouse', 'lemon'] 47 | list3 = ['cat', 'dog', 'mouse', 'fish'] 48 | intersect = test.intersection(list2) 49 | test.union(list2) 50 | test.subtract(list3) 51 | 52 | print(test.getSet()) 53 | print(intersect) 54 | 55 | 56 | main() -------------------------------------------------------------------------------- /chap11/exercise_5.py: -------------------------------------------------------------------------------- 1 | #(a) count(myList, x) (like myList.count(x)) 2 | def count(myList, x): 3 | tot = 0 4 | for i in myList: 5 | if i == x: 6 | tot = tot + 1 7 | return tot 8 | 9 | #(b) isin(myList, x) (like x in myList) 10 | def isin(myList, x): 11 | for i in myList: 12 | if i == x: 13 | return True 14 | 15 | #(c) index(myList, x) (like myList.index(x)) 16 | def index(myList, x): 17 | for i in range (len(myList)): 18 | if myList[i] == x: 19 | return i 20 | break 21 | 22 | #(d) reverse(myList) (like myList.revers()) 23 | def reverse(myList): 24 | newList = [] 25 | for i in range(len(myList)): 26 | x = myList[-1 * (i + 1)] 27 | newList.append(x) 28 | return newList 29 | 30 | #(e) sort(myList) (like myList.sort()) 31 | def sort(myList): 32 | newList = [] 33 | for i in range (len(myList)): 34 | x = min(myList) 35 | newList.append(x) 36 | myList.remove(x) 37 | return newList 38 | 39 | 40 | 41 | 42 | def main(): 43 | myList = [8, 6, 7, 5, 3, 0, 9] 44 | myList = myList * 3 45 | x = 3 46 | print("Count of x: ", count(myList, x)) 47 | print("X in myList: ", isin(myList, x)) 48 | print("Index of x: ", index(myList, x)) 49 | print("Reverse list: ", reverse(myList)) 50 | print("Sort List: ", sort(myList)) 51 | if __name__ == '__main__': main() -------------------------------------------------------------------------------- /chap11/exercise_6.py: -------------------------------------------------------------------------------- 1 | from random import random 2 | 3 | def shuffle(myList): 4 | newList = [] 5 | for i in range (len(myList)): 6 | x = int(random() * len(myList)) - 1 7 | newList.append(myList[x]) 8 | myList.remove(myList[x]) 9 | return newList 10 | 11 | def main(): 12 | myList = [8, 6, 7, 5, 3, 0, 9] 13 | myList = myList 14 | print("Shuffle List: ", shuffle(myList)) 15 | 16 | if __name__ == '__main__': main() -------------------------------------------------------------------------------- /chap11/exercise_7.py: -------------------------------------------------------------------------------- 1 | def main(): 2 | myList = [8,6,7,5,3,0,9] 3 | newList = [9,0,3,5,7,6,8] 4 | 5 | sum = 0 6 | for i in range(len(myList)): 7 | x = myList[i] * newList[i] 8 | sum = sum + x 9 | print(sum) 10 | main() -------------------------------------------------------------------------------- /chap11/exercise_8.py: -------------------------------------------------------------------------------- 1 | #can also use "x in myList" 2 | def isin(myList, x): 3 | for i in myList: 4 | if i == x: 5 | return True 6 | 7 | def removeDuplicates(myList): 8 | newList = [] 9 | for i in myList: 10 | if not isin(newList, i): 11 | newList.append(i) 12 | return newList 13 | 14 | def main(): 15 | myList = [8, 6, 7, 5, 3, 0, 9] 16 | myList = myList * 3 17 | print("Remove Duplicate: ", removeDuplicates(myList)) 18 | 19 | if __name__ == '__main__': main() -------------------------------------------------------------------------------- /chap11/exercise_9.py: -------------------------------------------------------------------------------- 1 | from gpa import Student 2 | 3 | def readStudents(filename): 4 | infile = open(filename, 'r') 5 | students = [] 6 | for line in infile: 7 | students.append(makeStudent(line)) 8 | infile.close() 9 | return students 10 | 11 | def makeStudent(infoStr): 12 | #inforStr is a tap-separated line: name hours getQPoints 13 | #returns a corresponding Student object 14 | name, hours, qpoints = infoStr.split("\t") 15 | return Student(name, hours, qpoints) 16 | 17 | def writeStudents(students, filename): 18 | #students is a list of Student object 19 | outfile = open(filename, 'w') 20 | for s in students: 21 | print("{0}\t{1}\t{2}".format(s[1], s[2], s[3]), file = outfile) 22 | outfile.close() 23 | 24 | def sort(students): 25 | newData = [] 26 | for i in range(len(students)): 27 | x = (students[i].gpa(), students[i].getName(), students[i].getHours(), students[i].getQPoints()) 28 | newData.append(x) 29 | newData.sort() 30 | newData.reverse() 31 | 32 | return newData 33 | 34 | def main(): 35 | print("This program sorts student grade information by GPA") 36 | #filename = input("Enter the name of the data file: ") 37 | filename = "gpa1.txt" 38 | data = readStudents(filename) 39 | data = sort(data) 40 | 41 | filename = "gpa_(sortfast).txt" 42 | writeStudents(data, filename) 43 | 44 | 45 | 46 | 47 | if __name__ == '__main__': main() 48 | 49 | 50 | 51 | -------------------------------------------------------------------------------- /chap11/gpa.py: -------------------------------------------------------------------------------- 1 | #gpa.py 2 | # Program to find student with highest GPA 3 | 4 | class Student: 5 | def __init__(self, name, hours, qpoints): 6 | self.name = name 7 | self.hours = float(hours) 8 | self.qpoints = float(qpoints) 9 | 10 | def getName(self): 11 | return self.name 12 | 13 | def getHours(self): 14 | return self.hours 15 | 16 | def getQPoints(self): 17 | return self.qpoints 18 | 19 | def gpa(self): 20 | return self.qpoints / self.hours 21 | 22 | def makeStudent(infoStr): 23 | #inforStr is a tap-separated line: name hours getQPoints 24 | #returns a corresponding Student object 25 | name, hours, qpoints = infoStr.split("\t") 26 | return Student(name, hours, qpoints) 27 | 28 | def main(): 29 | #open the input file for reading 30 | filename = input("Enter the name of the grade file: ") 31 | infile = open(filename, 'r') 32 | 33 | #set best to the record for the first student in the file 34 | best = makeStudent(infile.readline()) 35 | 36 | #process subsequent lines of the file 37 | for line in infile: 38 | #turn the line into a student record 39 | s = makeStudent(line) 40 | #if this student is best so far, remember it. 41 | if s.gpa() > best.gpa(): 42 | best = s 43 | infile.close() 44 | 45 | #print information about the best student 46 | print("The best student is:", best.getName()) 47 | print("hours:", best.getHours()) 48 | print("GPA:", best.gpa()) 49 | 50 | if __name__ == '__main__': 51 | main() 52 | -------------------------------------------------------------------------------- /chap11/gpa1.txt: -------------------------------------------------------------------------------- 1 | Adams, Henry 127 228 2 | Computewell, Susan 100 400 3 | DibbleBit, Denny 18 41.5 4 | Jones, Jim 48.5 155 5 | Smith, Frank 37 125.33 6 | -------------------------------------------------------------------------------- /chap11/gpa_(sortfast).txt: -------------------------------------------------------------------------------- 1 | Computewell, Susan 100.0 400.0 2 | Smith, Frank 37.0 125.33 3 | Jones, Jim 48.5 155.0 4 | DibbleBit, Denny 18.0 41.5 5 | Adams, Henry 127.0 228.0 6 | -------------------------------------------------------------------------------- /chap11/gpasort.py: -------------------------------------------------------------------------------- 1 | from gpa import Student 2 | 3 | def readStudents(filename): 4 | infile = open(filename, 'r') 5 | students = [] 6 | for line in infile: 7 | students.append(makeStudent(line)) 8 | infile.close() 9 | return students 10 | 11 | def writeStudents(students, filename): 12 | #students is a list of Student object 13 | outfile = open(filename, 'w') 14 | for s in students: 15 | print("{0}\t{1}\t{2}".format(s.getName(), s.getHours(), s.getQPoints()), file = outfile) 16 | outfile.close() 17 | 18 | def main(): 19 | print("This program sorts student grade information by GPA") 20 | filename = input("Enter the name of the data file: ") 21 | data = readStudents(filename) 22 | data.sort(key=Student.gpa) 23 | filename = input("enter a name for the outputfile: ") 24 | writeStudents(data, filename) 25 | print("the data has been written to", filename) 26 | 27 | if __name__ == '__main__': main() 28 | 29 | 30 | 31 | -------------------------------------------------------------------------------- /chap11/playingcard.py: -------------------------------------------------------------------------------- 1 | #playingcard.py 2 | from graphics import * 3 | import Playing_Card_Images 4 | 5 | class PlayingCard: 6 | 7 | def __init__(self, rank, suit): 8 | self.rank = rank 9 | self.suit = suit 10 | 11 | def getRank(self): 12 | return self.rank 13 | 14 | def getSuit(self): 15 | return self.suit 16 | 17 | def BJValue(self): 18 | if 10 <= self.rank <= 13: 19 | self.rank = 10 20 | else: 21 | self.rank = self.rank 22 | return self.rank 23 | 24 | def __str__(self): 25 | n = self.rank 26 | if self.suit == 'D': 27 | s = "Diamonds" 28 | elif self.suit == 'S': 29 | s = "Spades" 30 | elif self.suit == 'H': 31 | s = "Hearts" 32 | else: 33 | s = "Clubs" 34 | 35 | rank = ["Ace", "2", "3", "4", "5", "6", "7", "8", "9", "10", "Jack", "Queen", "King"] 36 | 37 | self.cardname = "{0} of {1}".format(rank[n - 1], s) 38 | return self.cardname 39 | 40 | def draw(self, win, center): 41 | filename = "./Playing_Card_Images/{0}{1}.png".format(self.rank, self.suit.upper()) 42 | card = Image(center, filename) 43 | card.draw(win) -------------------------------------------------------------------------------- /chap11/stats.py: -------------------------------------------------------------------------------- 1 | #stats.py 2 | from math import sqrt 3 | def getNumbers(): 4 | nums = [] 5 | 6 | #sentinel loop to get numbers 7 | xStr = input("Enter a number ( to Quit) >>") 8 | while xStr != "": 9 | x = eval(xStr) 10 | nums.append(x) 11 | xStr = input("Enter a number ( to quit) >> ") 12 | return nums 13 | 14 | def mean(nums): 15 | sum = 0.0 16 | for num in nums: 17 | sum = sum + num 18 | return sum / len(nums) 19 | 20 | def stdDev(nums, xbar): 21 | sumDevSq = 0.0 22 | for num in nums: 23 | dev = xbar - num 24 | sumDevSq = sumDevSq + dev * dev 25 | return sqrt(sumDevSq/(len(nums) - 1)) 26 | 27 | def median(nums): 28 | nums.sort() 29 | size = len(nums) 30 | midPos = size // 2 31 | if size % 2 == 0: 32 | median = (nums[midPos] + nums [midPos - 1]) / 2 33 | else: 34 | median = nums[midPos] 35 | return median 36 | 37 | def main(): 38 | print("This program computes mean, median, and standard deviation.") 39 | 40 | data = getNumbers() 41 | xbar = mean(data) 42 | std = stdDev(data, xbar) 43 | med = median(data) 44 | 45 | print('\nThe mean is', xbar) 46 | print("The standard deviation is", std) 47 | print("The median is", med) 48 | 49 | if __name__ == '__main__': main() 50 | -------------------------------------------------------------------------------- /chap11/wordfreq.py: -------------------------------------------------------------------------------- 1 | #wordfreq.py 2 | 3 | def byFreq(pair): 4 | return pair[1] 5 | 6 | def main(): 7 | print("This program analyzes word frequency in a file") 8 | print("and prints a report on the n most frequent words.\n") 9 | 10 | #get the sequence of words from the file 11 | fname = input("File to analyze: ") 12 | text = open(fname, 'r').read() 13 | text = text.lower() 14 | for chain '!"#$%()*+,-./:;<=>?@[\\]^_{|}~': 15 | text = text.replace(ch, ' ') 16 | words = text.split() 17 | 18 | #construct a dictionary of word counts 19 | counts = {} 20 | for w in words: 21 | counts[w] = counts.get(w,0) + 1 22 | 23 | #output analysis of n most frequent words 24 | n = eval(input("Output analysis of how many words? ")) 25 | items = list(counts.items()) 26 | items.sort() 27 | items.sort(key=byFreq, reverse=True) 28 | for i in range(n): 29 | word, count = items[i] 30 | print("{0:<15}{1:>5}".format(word, count)) 31 | 32 | if __name__ == '__main__': main() -------------------------------------------------------------------------------- /chap12/conferenceAttendees.json: -------------------------------------------------------------------------------- 1 | { 2 | "rorrun@gmail.com": { "name": "Chris", "company": "TMG", "state": "PA, USA"}, 3 | "mjt@gmail.com": {"name": "Matt", "company": "M&A", "state": "NJ, USA"}, 4 | "mccuskermusic@gmail": {"name": "Sean", "company": "PSD", "state": "PA, USA"}, 5 | "chrmgianc@gmail.com": {"name": "Christina", "company": "G&P", "state": "PA, USA"}, 6 | "brian@noidea.io": {"name": "Brian", "company": "Jordan Business Loans", "state": "Gaza Strip, Jordan"} 7 | 8 | } -------------------------------------------------------------------------------- /chap12/consolereader.py: -------------------------------------------------------------------------------- 1 | class ConsoleReader: 2 | @staticmethod 3 | def read_string(prefix): 4 | """ Read a string from console, with a prefix """ 5 | return input(prefix) 6 | 7 | @staticmethod 8 | def read_int(prefix, default = None): 9 | """ Read a (casted) int from console, with a prefix """ 10 | return ConsoleReader.__cast(ConsoleReader.read_string(prefix), int) or default 11 | 12 | @staticmethod 13 | def read_float(prefix, default = None): 14 | """ Read a (casted) float from console, with a prefix """ 15 | return ConsoleReader.__cast(ConsoleReader.read_string(prefix), float) or default 16 | 17 | @staticmethod 18 | def __cast(value, type): 19 | """ Safely cast a string to another type. """ 20 | parsed = False 21 | 22 | try: 23 | parsed = type(value) 24 | except ValueError: 25 | pass 26 | 27 | return parsed -------------------------------------------------------------------------------- /chap12/dice.py: -------------------------------------------------------------------------------- 1 | from random import randrange, random 2 | 3 | class Dice: 4 | def __init__(self): 5 | self.dice = [0]*5 6 | self.rollAll() 7 | 8 | def roll(self, which): 9 | for pos in which: 10 | self.dice[pos] = randrange(1,7) 11 | 12 | def rollAll(self): 13 | self.roll(range(5)) 14 | 15 | def values(self): 16 | return self.dice[:] 17 | 18 | def score(self): 19 | #Create the counts list 20 | counts = [0] * 7 21 | for value in self.dice: 22 | counts[value] = counts[value] + 1 23 | 24 | #score the hand 25 | if 5 in counts: 26 | return "Five of a Kind", 30 27 | elif 4 in counts: 28 | return "Four of a Kind", 15 29 | elif (3 in counts) and (2 in counts): 30 | return "Full House", 12 31 | elif (3 in counts): 32 | return "Three of a Kind", 8 33 | elif not (2 in counts) and (counts[1] == 0 or counts[6] == 0): 34 | return "Straight", 20 35 | elif counts.count(2) == 2: 36 | return "Two Pairs", 5 37 | else: 38 | return "Garbage", 0 -------------------------------------------------------------------------------- /chap12/exercise_4.py: -------------------------------------------------------------------------------- 1 | from atmmanager import ATMApp, User 2 | from textatm import TextInterface 3 | 4 | def main(): 5 | interface = TextInterface() 6 | app = ATMApp("new_atmusers.json", interface) 7 | main() 8 | -------------------------------------------------------------------------------- /chap12/exercise_6.py: -------------------------------------------------------------------------------- 1 | from playingcard import * 2 | 3 | class BridgeApp: 4 | def __init__(self): 5 | self.deck = Deck() 6 | self.players = [] 7 | for person in range(4): 8 | person = Player() 9 | self.players = person 10 | self.teamNS = [self.players[0], self.players[2]] 11 | self.teamEW = [self.players[1], self.players[3]] 12 | 13 | 14 | 15 | class Player: 16 | def __init__(self): 17 | self.name 18 | self.points 19 | self.currentbid 20 | self.hand = [] #fill with cards 21 | 22 | class Bid: 23 | #Spades, Hearts, Diamonds, Clubs 24 | #If 3 passes, bidding over / return bidder 25 | # first of team to bid wins bid, lest change of suit 26 | # 27 | def __init__(self): 28 | self.sequence_bids = 29 | self. 30 | -------------------------------------------------------------------------------- /chap12/exercise_7.py: -------------------------------------------------------------------------------- 1 | #Write an interactive program to play War -------------------------------------------------------------------------------- /chap12/exercise_8.py: -------------------------------------------------------------------------------- 1 | #Write an interactive program to play Connect Four or Battleship 2 | -------------------------------------------------------------------------------- /chap12/json_test.py: -------------------------------------------------------------------------------- 1 | import json 2 | from atmmanager import User 3 | 4 | with open("atmusers.json") as f: 5 | data = json.load(f) 6 | 7 | users = {} 8 | 9 | for key, value in data['users'].items(): 10 | print(value["userid"], value["pin"]) 11 | user = User(value["userid"], value["pin"],value["checking"],value["savings"], value["name"]) 12 | users['users'] = value['userid'] 13 | users['users'] 14 | print(users) 15 | 16 | # data = {} 17 | # data['users'] = {} 18 | # for user in users: 19 | # json_str = (vars(user)) 20 | # del json_str["user"] 21 | # userid = user.getID() 22 | # data['users'][userid] = json_str 23 | 24 | # with open('new_atmusers.json', 'w') as f: 25 | # json.dump(data, f, indent=4) 26 | 27 | -------------------------------------------------------------------------------- /chap12/new_atmusers.json: -------------------------------------------------------------------------------- 1 | { 2 | "users": { 3 | "christina_g": { 4 | "userid": "christina_g", 5 | "pin": "1111", 6 | "checking": 2000.0, 7 | "savings": 11000.0, 8 | "name": "Christina" 9 | }, 10 | "ricanontherun": { 11 | "userid": "ricanontherun", 12 | "pin": "1112", 13 | "checking": 8755.0, 14 | "savings": 7030.0, 15 | "name": "Christian" 16 | }, 17 | "theintimidator": { 18 | "userid": "theintimidator", 19 | "pin": "1113", 20 | "checking": 1845.0, 21 | "savings": 112.0, 22 | "name": "Sean" 23 | }, 24 | "jazzplusjazzequalsjazz": { 25 | "userid": "jazzplusjazzequalsjazz", 26 | "pin": "1114", 27 | "checking": 4489.0, 28 | "savings": 24000.0, 29 | "name": "Dan" 30 | } 31 | } 32 | } -------------------------------------------------------------------------------- /chap12/pokerapp.py: -------------------------------------------------------------------------------- 1 | from dice import Dice 2 | 3 | class PokerApp: 4 | def __init__(self, interface): 5 | self.dice = Dice() 6 | self.money = 100 7 | self.interface = interface 8 | 9 | def run(self): 10 | while self.money >= 10 and self.interface.wantToPlay(): 11 | self.playRound() 12 | self.interface.close() 13 | 14 | def playRound(self): 15 | self.money = self.money - 10 16 | self.interface.setMoney(self.money) 17 | self.doRolls() 18 | result, score = self.dice.score() 19 | self.interface.showResult(result, score) 20 | self.money = self.money + score 21 | self.interface.setMoney(self.money) 22 | 23 | def doRolls(self): 24 | self.dice.rollAll() 25 | roll = 1 26 | self.interface.setDice(self.dice.values()) 27 | toRoll = self.interface.chooseDice() 28 | while roll < 3 and toRoll != []: 29 | self.dice.roll(toRoll) 30 | roll = roll + 1 31 | self.interface.setDice(self.dice.values()) 32 | if roll < 3: 33 | toRoll = self.interface.chooseDice() 34 | 35 | -------------------------------------------------------------------------------- /chap12/textpoker.py: -------------------------------------------------------------------------------- 1 | class TextInterface: 2 | def __init__(self): 3 | print("Welcome to video poker.") 4 | 5 | def setMoney(self, amt): 6 | print("You currently have ${0}.".format(amt)) 7 | 8 | def setDice(self, values): 9 | print("Dice", values) 10 | 11 | def wantToPlay(self): 12 | ans = input("Do you wish to try your luck? ") 13 | return ans[0] in "yY" 14 | 15 | def close(self): 16 | print("\nThanks for playing!") 17 | 18 | def showResult(self, msg, score): 19 | print("{0}. You win ${1}.".format(msg, score)) 20 | 21 | def chooseDice(self): 22 | return eval(input("Enter list of which to change ([] to stop) ")) -------------------------------------------------------------------------------- /chap13/exercise_1.py: -------------------------------------------------------------------------------- 1 | def fib(n): 2 | print("Computing fib({})".format(n)) 3 | if n < 3: 4 | return 1 5 | else: 6 | print("Leaving fib({0}), returning {1}".format(n, fib(n-1) + fib(n-2))) 7 | return fib(n-1) + fib(n-2) 8 | 9 | 10 | 11 | fib(5) 12 | -------------------------------------------------------------------------------- /chap13/exercise_2.py: -------------------------------------------------------------------------------- 1 | class FibCounter: 2 | def __init__(self): 3 | self.fibcount = 0 4 | 5 | def getCount(self): 6 | return self.fibcount 7 | 8 | def fib(self, n): 9 | self.fibcount += 1 10 | if n < 3: 11 | return 1 12 | else: 13 | return self.fib(n-1) + self.fib(n-2) 14 | 15 | def resetCount(self): 16 | self.fibcount = 0 17 | 18 | 19 | count = FibCounter() 20 | 21 | count.fib(23) 22 | 23 | print(count.getCount()) 24 | -------------------------------------------------------------------------------- /chap13/exercise_3.py: -------------------------------------------------------------------------------- 1 | 2 | def palindrome(xStr, firstRun=True): 3 | if firstRun == True: 4 | for ch in '<}{ ][>.?/:;\|+=-_),(*&^%$#@!~`': 5 | xStr.replace(ch, "") 6 | xStr = xStr.lower() 7 | 8 | if len(xStr) < 2: 9 | return True 10 | elif xStr[0] == xStr[-1]: 11 | xStr = xStr[1:-1] 12 | palindrome(xStr, firstRun=False) 13 | return True 14 | else: 15 | return False 16 | 17 | def main(): 18 | xStr = input("Type a phrase to check for palindrome status....") 19 | if palindrome(xStr) is True: 20 | print("The phrase is a palindrome.") 21 | else: 22 | print("The phrase is not a palindrome.") 23 | main() 24 | 25 | 26 | -------------------------------------------------------------------------------- /chap13/exercise_5.py: -------------------------------------------------------------------------------- 1 | def baseConversion(num, base): 2 | digit = num % base 3 | print(num, digit) 4 | num = num // base 5 | 6 | if num == 0: 7 | return 1 8 | elif num < base: 9 | digit = num 10 | num = 0 11 | print(num, digit) 12 | else: 13 | baseConversion(num, base) 14 | 15 | baseConversion(153, 10) 16 | 17 | 18 | 19 | -------------------------------------------------------------------------------- /chap13/exercise_6.py: -------------------------------------------------------------------------------- 1 | class BaseConversion: 2 | def __init__(self, num, base): 3 | self.list = [] 4 | self.num = num 5 | self.base = base 6 | self.makeList() 7 | 8 | def makeList(self): 9 | digit = self.num % self.base 10 | self.list.append(digit) 11 | self.num = self.num // self.base 12 | 13 | if self.num < self.base: 14 | digit = self.num 15 | self.num = 0 16 | self.list.append(digit) 17 | else: 18 | self.makeList() 19 | 20 | def getDigits(self): 21 | self.list.reverse() 22 | digits = ["Zero", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine"] 23 | newlist = [] 24 | for num in self.list: 25 | num = digits[num] 26 | newlist.append(num) 27 | str1 = ' '.join(newlist) 28 | return str1 29 | 30 | list = BaseConversion(153, 10) 31 | newlist = list.getDigits() 32 | 33 | print(newlist) 34 | -------------------------------------------------------------------------------- /chap13/exercise_7.py: -------------------------------------------------------------------------------- 1 | import sys 2 | sys.setrecursionlimit(1000) 3 | def factorial(n): 4 | fact = 1 5 | for factor in range(n,1,-1): 6 | fact = fact * factor 7 | return fact 8 | 9 | def iterative_options(n, k): 10 | x = factorial(n) 11 | y = factorial(k) * factorial(n - k) 12 | return x / y 13 | 14 | 15 | def recursive_options(n, k): 16 | if k == 1: 17 | options = n 18 | elif n < k: 19 | options = 0 20 | else: 21 | options = recursive_options(n - 1, k - 1) + recursive_options(n-1, k) 22 | return options 23 | 24 | def main(): 25 | print(iterative_options(72, 5)) 26 | print(recursive_options(72, 5)) 27 | main() 28 | -------------------------------------------------------------------------------- /chap13/exercise_9.py: -------------------------------------------------------------------------------- 1 | from graphics import GraphWin, Point, Line 2 | from math import pi, cos, sin, sqrt 3 | 4 | def C_Curve(Turtle, length, degree): 5 | if degree == 0: 6 | Turtle.draw(length) 7 | else: 8 | length1 = length/(sqrt(2)) 9 | degree1 = degree - 1 10 | Turtle.turn(45) 11 | C_Curve(Turtle, length1, degree1) 12 | Turtle.turn(-90) 13 | C_Curve(Turtle, length1, degree1) 14 | Turtle.turn(45) 15 | 16 | class Turtle: 17 | def __init__(self, point, direction, window): 18 | self.location = point 19 | self.direction = direction 20 | self.win = window 21 | 22 | def moveTo(self, newpoint): 23 | self.location = newpoint 24 | 25 | def _moveTo(self, length): 26 | dx = length * cos(self.direction) 27 | dy = length * sin(self.direction) 28 | x = self.location.getX() 29 | y = self.location.getY() 30 | x += dx 31 | y += dy 32 | newpoint = Point(x, y) 33 | return self.moveTo(newpoint) 34 | 35 | def draw(self, length): 36 | oldLocation = self.location 37 | self._moveTo(length) 38 | path = Line(oldLocation, self.location) 39 | path.draw(self.win) 40 | 41 | def turn(self, direction): 42 | self.direction += direction * pi / 180 43 | 44 | 45 | def main(): 46 | length = 300 47 | degree = 15 48 | win = GraphWin("C_Curve Snowflake", 800, 800) 49 | dir = pi / 2 50 | turtle = Turtle(Point(475, 225), dir, win) 51 | C_Curve(turtle, length, degree) 52 | win.getMouse() 53 | main() -------------------------------------------------------------------------------- /chap13/testdoc.txt: -------------------------------------------------------------------------------- 1 | Before we move on to the analysis, we should note that this algorithm is a great 2 | example of a divide and conquer strategy. Divide and conquer means that we divide 3 | the problem into smaller pieces, solve the smaller pieces in some way, 4 | and then reassemble the whole problem to get the result. When 5 | we perform a binary search of a list, we first check the middle item. 6 | If the item we are searching for is less than the middle item, we can 7 | simply perform a binary search of the left half of the original list. 8 | Likewise, if the item is greater, we can perform a binary search of the right 9 | half. Either way, this is a recursive call to the binary search function 10 | passing a smaller list. CodeLens 4 shows this recursive version. --------------------------------------------------------------------------------