├── Chapter1 ├── 1.1.py ├── 1.10.py ├── 1.11.py ├── 1.12.py ├── 1.13.py ├── 1.14.py ├── 1.15.py ├── 1.16.py ├── 1.17.py ├── 1.18.py ├── 1.19.py ├── 1.2.py ├── 1.20.py ├── 1.21.py ├── 1.3.py ├── 1.4.py ├── 1.5.py ├── 1.6.py ├── 1.7.py ├── 1.8.py └── 1.9.py ├── README.md ├── chapter10 ├── 10-33_char-hist.py ├── 15_CheckSorted.py ├── 16_BubbleSort.py ├── 18_EightQueens.py ├── 26_MergeTwoSortedList.py ├── 2_ReverseNumbers.py ├── 3_CountOccurence.py └── 9_ComputeDeviation.py ├── chapter11 ├── 11.10.py ├── 11.13.py ├── 11.2.py ├── 11.25.py ├── 11.5.py ├── 11.51.py └── 11.6.py ├── chapter12 ├── 12-02_locate-max.py ├── 12-04_bounded-rect.py ├── 1_TriangleClass.py ├── 2_LocationClass.py └── 3_ATMMachine.py ├── chapter13 ├── 13.1.py ├── 13.17.py ├── 13.2.py ├── 13.3.py ├── 13.6.py ├── 13.8.py └── 13.9.py ├── chapter14 └── 14.3.py ├── chapter15 ├── 15.1.py ├── 15.12.py ├── 15.21.py ├── 15.23.py ├── 15.24.py └── 15.3.py ├── chapter2 ├── 2.1.py ├── 2.10.py ├── 2.11.py ├── 2.12.py ├── 2.13.py ├── 2.14.py ├── 2.15.py ├── 2.16.py ├── 2.17.py ├── 2.18.py ├── 2.19.py ├── 2.2.py ├── 2.20.py ├── 2.21.py ├── 2.22.py ├── 2.23.py ├── 2.24.py ├── 2.25.py ├── 2.26.py ├── 2.3.py ├── 2.4.py ├── 2.5.py ├── 2.6.py ├── 2.7.py ├── 2.8.py ├── 2.9.py └── s.py ├── chapter3 ├── 3.1.py ├── 3.10.py ├── 3.11.py ├── 3.12.py ├── 3.13.py ├── 3.14.py ├── 3.15.py ├── 3.16.py ├── 3.17.py ├── 3.18.py ├── 3.2.py ├── 3.4.py ├── 3.5.py ├── 3.6.py ├── 3.7.py ├── 3.8.py └── 3.9.py ├── chapter4 ├── 4.1.py ├── 4.10.py ├── 4.11.py ├── 4.12.py ├── 4.13.py ├── 4.14.py ├── 4.15.py ├── 4.16.py ├── 4.17.py ├── 4.18.py ├── 4.19.py ├── 4.2.py ├── 4.20.py ├── 4.21.py ├── 4.22.py ├── 4.23.py ├── 4.24.py ├── 4.25.py ├── 4.26.py ├── 4.27.py ├── 4.28.py ├── 4.3.py ├── 4.30.py ├── 4.31.py ├── 4.32.py ├── 4.33.py ├── 4.34.py ├── 4.4.py ├── 4.5.py ├── 4.6.py ├── 4.7.py ├── 4.8.py ├── 4.9.py └── output.txt ├── chapter5 ├── 5.1.py ├── 5.10.py ├── 5.10Input.txt ├── 5.10output.txt ├── 5.11.py ├── 5.12.py ├── 5.13.py ├── 5.14.py ├── 5.15.py ├── 5.16.py ├── 5.17.py ├── 5.18.py ├── 5.19.py ├── 5.2.py ├── 5.20.py ├── 5.20A.py ├── 5.22.py ├── 5.23.py ├── 5.24.py ├── 5.25.py ├── 5.26.py ├── 5.27.py ├── 5.28.py ├── 5.3.py ├── 5.30.py ├── 5.36.py ├── 5.3output.txt ├── 5.4.py ├── 5.41.py ├── 5.4output.txt ├── 5.5.py ├── 5.5output.txt ├── 5.6.py ├── 5.6output.txt ├── 5.7.py ├── 5.7output.txt ├── 5.8.py ├── 5.8output.txt ├── 5.9.py ├── Trial.py └── time table.py ├── chapter6 ├── 6.1.py ├── 6.10.py ├── 6.18.py ├── 6.1n.py ├── 6.2.py ├── 6.21.py ├── 6.24.py ├── 6.29.py ├── 6.3.py ├── 6.34.py ├── 6.4.py ├── 6.5.py ├── 6.6.py ├── RandomCharacter.py ├── classTuto.py ├── trial.py └── trial2.py ├── chapter7 ├── 7.1.py ├── 7.10.py ├── 7.2.py ├── 7.5.py ├── 7.7.py ├── 7.8.py └── 7.9.py └── chapter8 ├── 8.1.py ├── 8.12.py ├── 8.13.py ├── 8.17.py ├── 8.19.py ├── 8.2.py ├── 8.3.py ├── 8.6.py ├── 8.7.py ├── 8.8.py └── 8.9.py /Chapter1/1.1.py: -------------------------------------------------------------------------------- 1 | print("Welcome to Python") 2 | print("Welcome to computer Science") 3 | print("Programming is Fun") 4 | -------------------------------------------------------------------------------- /Chapter1/1.10.py: -------------------------------------------------------------------------------- 1 | distance_in_kilometers = 45 2 | distance_in_miles = 45 * (1 / 1.6) 3 | time_in_minutes = 45 4 | time_in_sec = (60 * 45) + 30 5 | time_in_hours = time_in_sec / 3600 6 | print("Average speed =", distance_in_miles / time_in_hours, "miles per hours") 7 | -------------------------------------------------------------------------------- /Chapter1/1.11.py: -------------------------------------------------------------------------------- 1 | birth_in_7_sec = 1 2 | birth_per_hour = 3600 // 7 3 | birth_per_day = 24 * birth_per_hour 4 | 5 | immigrants_in_45_sec = 1 6 | immigrants_per_hour = 3600 // 45 7 | immigrants_per_day = 24 * immigrants_per_hour 8 | 9 | death_in_13_sec = 1 10 | deaths_per_hour = 3600 // 13 11 | deaths_per_day = 24 * deaths_per_hour 12 | 13 | total_pop_per_day = birth_per_day + immigrants_per_day - deaths_per_day 14 | total_pop =312032486 + 365 * total_pop_per_day 15 | 16 | years=1 17 | a = total_pop 18 | while years < 6: 19 | 20 | print("total population in year", years, "is =", a) 21 | years += 1 22 | a += total_pop 23 | -------------------------------------------------------------------------------- /Chapter1/1.12.py: -------------------------------------------------------------------------------- 1 | import turtle 2 | turtle.showturtle() 3 | 4 | turtle.forward(50) 5 | turtle.right(90) 6 | turtle.forward(50) 7 | turtle.right(90) 8 | turtle.forward(100) 9 | turtle.right(90) 10 | turtle.forward(100) 11 | turtle.right(90) 12 | turtle.forward(100) 13 | turtle.right(90) 14 | turtle.forward(50) 15 | turtle.right(90) 16 | turtle.forward(100) 17 | turtle.right(90) 18 | turtle.forward(50) 19 | turtle.right(90) 20 | turtle.forward(50) 21 | turtle.right(90) 22 | turtle.forward(100) 23 | -------------------------------------------------------------------------------- /Chapter1/1.13.py: -------------------------------------------------------------------------------- 1 | import turtle 2 | turtle.showturtle() 3 | 4 | turtle.forward(100) 5 | turtle.right(180) 6 | turtle.forward(200) 7 | turtle.right(180) 8 | turtle.forward(100) 9 | turtle.right(90) 10 | turtle.forward(100) 11 | turtle.right(180) 12 | turtle.forward(200) 13 | -------------------------------------------------------------------------------- /Chapter1/1.14.py: -------------------------------------------------------------------------------- 1 | import turtle 2 | turtle.showturtle() 3 | 4 | turtle.right(60) 5 | turtle.forward(100) 6 | turtle.right(120) 7 | turtle.forward(100) 8 | turtle.right(120) 9 | turtle.forward(100) 10 | -------------------------------------------------------------------------------- /Chapter1/1.15.py: -------------------------------------------------------------------------------- 1 | import turtle 2 | turtle.showturtle() 3 | 4 | turtle.right(60) 5 | turtle.forward(100) 6 | turtle.right(120) 7 | turtle.forward(100) 8 | turtle.right(120) 9 | turtle.forward(200) 10 | turtle.right(-120) 11 | turtle.forward(100) 12 | turtle.right(-120) 13 | turtle.forward(100) 14 | -------------------------------------------------------------------------------- /Chapter1/1.16.py: -------------------------------------------------------------------------------- 1 | import turtle 2 | turtle.showturtle() 3 | 4 | turtle.penup() 5 | turtle.goto(50, 50) 6 | turtle.pendown() 7 | turtle.circle(50) 8 | 9 | turtle.penup() 10 | turtle.goto(-50, -50) 11 | turtle.pendown() 12 | turtle.circle(50) 13 | 14 | turtle.penup() 15 | turtle.goto(50, -50) 16 | turtle.pendown() 17 | turtle.circle(50) 18 | 19 | turtle.penup() 20 | turtle.goto(-50, 50) 21 | turtle.pendown() 22 | turtle.circle(50) 23 | -------------------------------------------------------------------------------- /Chapter1/1.17.py: -------------------------------------------------------------------------------- 1 | import turtle 2 | turtle.showturtle() 3 | 4 | turtle.penup() 5 | turtle.goto(-39, 48) 6 | turtle.write("(-39, 48)") 7 | turtle.pendown() 8 | turtle.goto(50, -50) 9 | turtle.write("(50, -50)") 10 | -------------------------------------------------------------------------------- /Chapter1/1.18.py: -------------------------------------------------------------------------------- 1 | import turtle 2 | turtle.showturtle() 3 | 4 | turtle.penup() 5 | turtle.goto(0, 100) 6 | turtle.pendown() 7 | turtle.goto(45, 0) 8 | 9 | 10 | turtle.goto(-50, 60) 11 | 12 | turtle.goto(50, 60) 13 | 14 | turtle.goto(-45, 0) 15 | 16 | turtle.goto(0, 100) 17 | -------------------------------------------------------------------------------- /Chapter1/1.19.py: -------------------------------------------------------------------------------- 1 | import turtle 2 | turtle.showturtle() 3 | 4 | turtle.penup() 5 | 6 | turtle.goto(40, -69.28) 7 | 8 | turtle.pendown() 9 | 10 | turtle.goto(-40, -69.28) 11 | 12 | turtle.goto(-80, -9.8) 13 | 14 | turtle.goto(-40, 69) 15 | 16 | turtle.goto(40, 69) 17 | 18 | turtle.goto(80, 0) 19 | 20 | turtle.goto(40, -69.28) 21 | -------------------------------------------------------------------------------- /Chapter1/1.2.py: -------------------------------------------------------------------------------- 1 | print("Welcome to Python\n") 2 | print("Welcome to Python\n") 3 | print("Welcome to Python\n") 4 | print("Welcome to Python\n") 5 | print("Welcome to Python\n") 6 | -------------------------------------------------------------------------------- /Chapter1/1.20.py: -------------------------------------------------------------------------------- 1 | import turtle 2 | turtle.showturtle() 3 | 4 | turtle.penup() 5 | turtle.goto(-100, 0) 6 | turtle.pendown() 7 | turtle.forward(200) 8 | turtle.right(90) 9 | turtle.forward(100) 10 | turtle.right(90) 11 | turtle.forward(200) 12 | turtle.right(90) 13 | turtle.forward(100) 14 | turtle.right(90) 15 | turtle.forward(200) 16 | turtle.right(-45) 17 | turtle.forward(50) 18 | turtle.right(-135) 19 | turtle.forward(200) 20 | turtle.right(-90) 21 | turtle.forward(100) 22 | turtle.right(-90) 23 | turtle.forward(200) 24 | turtle.right(-90) 25 | turtle.forward(100) 26 | turtle.forward(-100) 27 | turtle.right(-135) 28 | turtle.forward(50) 29 | turtle.right(45) 30 | turtle.forward(200) 31 | turtle.right(135) 32 | turtle.forward(50) 33 | turtle.right(-45) 34 | turtle.forward(100) 35 | turtle.right(-135) 36 | turtle.forward(50) 37 | -------------------------------------------------------------------------------- /Chapter1/1.21.py: -------------------------------------------------------------------------------- 1 | import turtle 2 | turtle.showturtle() 3 | 4 | turtle.penup() 5 | turtle.goto(0, -100) 6 | turtle.pendown() 7 | turtle.circle(150) 8 | 9 | turtle.penup() 10 | turtle.goto(0, 50) 11 | turtle.pendown() 12 | 13 | turtle.forward(100) 14 | 15 | turtle.penup() 16 | turtle.goto(0, 50) 17 | turtle.pendown() 18 | 19 | turtle.right(-90) 20 | turtle.forward(125) 21 | 22 | turtle.penup() 23 | turtle.goto(135, 50) 24 | turtle.write("3") 25 | 26 | turtle.penup() 27 | turtle.goto(-1, 185) 28 | turtle.write("12") 29 | 30 | turtle.penup() 31 | turtle.goto(-135, 50) 32 | turtle.write("9") 33 | 34 | turtle.penup() 35 | turtle.goto(0, -100) 36 | turtle.write("6") 37 | 38 | turtle.penup() 39 | turtle.goto(-20, -125) 40 | turtle.write("9:15:00") 41 | -------------------------------------------------------------------------------- /Chapter1/1.3.py: -------------------------------------------------------------------------------- 1 | print("FFFFFFF\tU U\tNN NN") 2 | print("FF \tU U\tNNN NN") 3 | print("FFFFFFF\tU U\tNN N NN") 4 | print("FF \t U U \tNN N NN") 5 | print("FF \t UUU \tNN NNN") 6 | -------------------------------------------------------------------------------- /Chapter1/1.4.py: -------------------------------------------------------------------------------- 1 | a = 1 2 | 3 | print("a\ta^2\ta^3") 4 | while a < 5: 5 | b = a ** 2 6 | c = a ** 3 7 | print(int(a), "\t", int(b), "\t", int(c)) 8 | a += 1 9 | -------------------------------------------------------------------------------- /Chapter1/1.5.py: -------------------------------------------------------------------------------- 1 | print(((9.5 * 4.5) - (2.5 * 3)) / (45.5 - 3.5)) 2 | -------------------------------------------------------------------------------- /Chapter1/1.6.py: -------------------------------------------------------------------------------- 1 | print(1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9) 2 | -------------------------------------------------------------------------------- /Chapter1/1.7.py: -------------------------------------------------------------------------------- 1 | print(4 * ( 1 - (1 / 3) + (1 / 5) - (1 / 7) + (1 / 9) - (1 / 11)), "\n") 2 | print(4 * ( 1 - (1 / 3) + (1 / 5) - (1 / 7) + (1 / 9) - (1 / 11) + (1 / 13) - (1 / 15)), "\n") 3 | -------------------------------------------------------------------------------- /Chapter1/1.8.py: -------------------------------------------------------------------------------- 1 | PI = 3.14 2 | radius = 5.5 3 | area = radius * radius * PI 4 | perimeter = 2 * radius * PI 5 | print("Area of circle =", area, "\nPerimeter of circle =", perimeter) 6 | -------------------------------------------------------------------------------- /Chapter1/1.9.py: -------------------------------------------------------------------------------- 1 | width = 4.5 2 | height = 7.9 3 | area = width * height 4 | print("Area of rectangle", area) 5 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Solution_to_Daniel_Liang_python_exercises 2 | Answers and solutions to Daniel Liang Introduction to programming using python 3 | 4 | Solutions are arranged in per chapters. Each chapter contains solutions to its exersises 5 | 6 | #Content 7 | -Chapter1 8 | -Chapter2 9 | -Chapter3 10 | -Chapter4 11 | -------------------------------------------------------------------------------- /chapter10/10-33_char-hist.py: -------------------------------------------------------------------------------- 1 | # Liang 10.33 2 | from tkinter import * 3 | import random 4 | 5 | class CharHistogram: 6 | def __init__(self): 7 | NUMOFCHARS = 26 8 | self.width = 800 9 | self.height = 400 10 | self.canvasPadx = -40 11 | window = Tk() 12 | window.title('Histogram: Random Character Counts') 13 | 14 | # Canvas 15 | frame1 = Frame(window) 16 | frame1.pack() 17 | self.canvas = Canvas(frame1, width=self.width, height=self.height, 18 | bd=self.canvasPadx, bg='white') 19 | self.canvas.pack() 20 | 21 | # a-z Character Labels 22 | frame2 = Frame(window) 23 | frame2.pack() 24 | for i in range(NUMOFCHARS): 25 | Label(frame2, text=chr(ord('a')+i)).grid(row=1, column=i+1, padx=self.width//100) 26 | 27 | # Button 28 | frame3 = Frame(window) 29 | frame3.pack() 30 | Button(frame3, text='Display Histogram', command=self.displayHist).pack() 31 | window.mainloop() 32 | 33 | def displayHist(self): 34 | self.clearCanvas() 35 | WSIZE = self.width/27.8 36 | HSIZE = self.height/7 37 | barWidth = self.width/WSIZE 38 | counts = 26 * [0] 39 | chars = [] 40 | 41 | # Generate and count occurences of random generated chars 42 | for i in range(1000): 43 | chars.append(chr(97 + int(random.random() * (ord('z') - ord('`'))))) # '`' char before 'a' 44 | for j in range(len(chars)): 45 | counts[ord(chars[j]) - ord('a')] += 1 46 | 47 | # Draw histogram 48 | for k in range(len(counts)): 49 | self.canvas.create_line(barWidth*k, self.height, 50 | barWidth*k, self.height-self.height//HSIZE*counts[k], tags='line') 51 | self.canvas.create_line(barWidth*k, self.height-self.height//HSIZE*counts[k], 52 | barWidth*(k+1), self.height-self.height//HSIZE*counts[k], tags='line') 53 | self.canvas.create_line(barWidth*(k+1), self.height-self.height//HSIZE*counts[k], 54 | barWidth*(k+1), self.height, tags='line') 55 | 56 | def clearCanvas(self): 57 | self.canvas.delete('line') 58 | 59 | CharHistogram() 60 | 61 | 62 | -------------------------------------------------------------------------------- /chapter10/15_CheckSorted.py: -------------------------------------------------------------------------------- 1 | '''Program to check if the list is sorted''' 2 | 3 | def isSorted(lst): 4 | for i in range(len(lst)-1): 5 | if lst[i] > lst[i+1]: 6 | return False 7 | return True 8 | 9 | def main(): 10 | list1 = eval(input("Enter list: ")) 11 | check = isSorted(list1) 12 | if(check): 13 | print("The list is sorted") 14 | else: 15 | print("The list is not sorted") 16 | 17 | main() -------------------------------------------------------------------------------- /chapter10/16_BubbleSort.py: -------------------------------------------------------------------------------- 1 | ''' Program to sort a list using Bubble sort''' 2 | 3 | def BubbleSort(lst): 4 | for x in range(len(lst)): 5 | for y in range(len(lst)-1): 6 | if(lst[y] > lst[y+1]): 7 | temp = lst[y+1] 8 | temp1 = lst[y] 9 | lst[y+1] = temp1 10 | lst[y] = temp 11 | 12 | print("The sorted list is: ", lst) 13 | 14 | 15 | def main(): 16 | list1 = eval(input("Enter 10 numbers: ")) 17 | BubbleSort(list1) 18 | 19 | main() -------------------------------------------------------------------------------- /chapter10/18_EightQueens.py: -------------------------------------------------------------------------------- 1 | '''Program to solve the eight queen problem''' 2 | 3 | def isValid(k, j, queens): 4 | for i in range(k): 5 | if queens[i] == j: 6 | return False 7 | 8 | 9 | row = k - 1 10 | column = j - 1 11 | while row >= 0 and column >= 0: 12 | if queens[row] == column: 13 | return False 14 | 15 | row -= 1 16 | column -= 1 17 | 18 | 19 | row = k - 1 20 | column = j + 1 21 | while row >= 0 and column <= 7: 22 | if queens[row] == column: 23 | return False 24 | 25 | row -= 1 26 | column -= 1 27 | 28 | return True 29 | 30 | 31 | def findPosition(k, queens): 32 | start = 0 if queens[k] == -1 else (queens[k] + 1) 33 | for j in range(start, 8): 34 | if isValid(k, j, queens): 35 | return j 36 | 37 | return -1 38 | 39 | def printResult(queens): 40 | for i in range(8): 41 | print("("+ str(i) + ", " + str(queens[i]) + ")") 42 | print() 43 | 44 | 45 | for i in range(8): 46 | for j in range(queens[i]): 47 | print("| ", end = "") 48 | print("|Q|", end = "") 49 | 50 | for j in range(queens[i] + 1, 8): 51 | print(" |", end = "") 52 | print() 53 | 54 | def main(): 55 | queens = 8 * [-1] 56 | queens[0] = 0 57 | k = 1 58 | while k >= 0 and k <= 7: 59 | j = findPosition(k, queens) 60 | if j < 0: 61 | queens[k] = -1 62 | k -= 1 63 | else: 64 | queens[k] = j 65 | k += 1 66 | 67 | printResult(queens) 68 | 69 | main() -------------------------------------------------------------------------------- /chapter10/26_MergeTwoSortedList.py: -------------------------------------------------------------------------------- 1 | '''Program to merge two sorted lists''' 2 | 3 | def merge(list1, list2): 4 | list3 = [] 5 | i=0 6 | j=0 7 | 8 | while i < len(list1) and j < len(list2): 9 | if list1[i] < list2[j]: 10 | list3.append(list1[i]) 11 | i=i+1 12 | else: 13 | list3.append(list2[j]) 14 | j=j+1 15 | 16 | while i < len(list1): 17 | list3.append(list1[i]) 18 | i=i+1 19 | 20 | while j < len(list2): 21 | list3.append(list2[j]) 22 | j=j+1 23 | 24 | return list3 25 | 26 | def main(): 27 | list1 = eval(input("Enter the first sorted list: ")) 28 | list2 = eval(input("Enter the second sorted list: ")) 29 | list3 = merge(list1, list2) 30 | print("The merged sorted list is: ", list3) 31 | 32 | main() -------------------------------------------------------------------------------- /chapter10/2_ReverseNumbers.py: -------------------------------------------------------------------------------- 1 | '''Program to reverse a list of integers entered by user''' 2 | 3 | def reverse(list1): 4 | for i in range(len(list1)-1, -1, -1): 5 | print(list1[i], end = " ") 6 | 7 | 8 | def main(): 9 | list1 = eval(input("Enter list of numbers: ")) 10 | print("Reverse of the entered list is: ", end="") 11 | reverse(list1) 12 | 13 | main() -------------------------------------------------------------------------------- /chapter10/3_CountOccurence.py: -------------------------------------------------------------------------------- 1 | '''Program to count the occurrences of numbers in a list''' 2 | 3 | def CountOccur(list1): 4 | temp= [0]*100 5 | 6 | for num in list1: 7 | temp[num] +=1 8 | 9 | for i in range(len(temp)): 10 | if(temp[i]>1): 11 | print(i, "occurs", temp[i], "times") 12 | elif(temp[i]==1): 13 | print(i, "occurs", temp[i], "time") 14 | 15 | 16 | def main(): 17 | list1 = eval(input("Enter integers between 1 and 100: ")) 18 | CountOccur(list1) 19 | 20 | main() -------------------------------------------------------------------------------- /chapter10/9_ComputeDeviation.py: -------------------------------------------------------------------------------- 1 | '''Program to compute deviation''' 2 | 3 | def mean(x): 4 | sum1 = 0.0 5 | mean = 0.0 6 | for i in range(len(x)): 7 | sum1 += x[i] 8 | mean = (sum1/len(x)) 9 | return mean 10 | 11 | def deviation(x): 12 | sum1 = 0.0 13 | mean1 = mean(x) 14 | for i in range(len(x)): 15 | sum1 += (x[i] - mean1)**2 16 | stddev = (sum1/ (len(x) -1))**0.5 17 | return stddev 18 | 19 | 20 | def main(): 21 | list1 = eval(input("Enter numbers: ")) 22 | print("The mean is :", mean(list1)) 23 | print("The standard deviation is" , deviation(list1)) 24 | 25 | main() 26 | -------------------------------------------------------------------------------- /chapter11/11.10.py: -------------------------------------------------------------------------------- 1 | ''' To find the largest sum row and column in a matrix filled with binary numbers''' 2 | import random 3 | 4 | 5 | def printMatrix(m): 6 | for row in range(len(m)): 7 | for column in range(len(m[row])): 8 | print(m[row][column], end = " ") 9 | print() 10 | 11 | def sumofColumn(m, j):#access each column 12 | sum1 = 0 13 | for i in range(len(m)): 14 | sum1 += m[i][j] 15 | return sum1 16 | 17 | 18 | def main(): 19 | matrix = [] 20 | row, col = 4,4 21 | 22 | count = 0 23 | for row in range(row): 24 | matrix.append([]) # Add an empty new row 25 | for column in range(col): 26 | matrix[row].append(random.randint(0, 1)) 27 | count += 1 28 | 29 | printMatrix(matrix) 30 | 31 | # Check rows for largest index 32 | SumRow = sum(matrix[0]) 33 | ListRow = [0] 34 | for i in range(1, col): 35 | if SumRow < sum(matrix[i]): 36 | SumRow = sum(matrix[i]) 37 | ListRow = [i] 38 | elif SumRow == sum(matrix[i]): 39 | ListRow.append(i) 40 | 41 | print("The largest row index: ", end = "") 42 | 43 | for i in range(len(ListRow) - 1): 44 | print(ListRow[i], end = ", ") 45 | print(ListRow[len(ListRow) - 1]) 46 | 47 | # Largest Column Index 48 | SumCol = sumofColumn(matrix, 0) 49 | ListCol = [0] 50 | for j in range(1, col): 51 | if SumCol < sumofColumn(matrix, j): 52 | SumCol = sumofColumn(matrix, j) 53 | ListCol = [j] 54 | elif SumCol == sumofColumn(matrix, j): 55 | ListCol.append(j) 56 | 57 | print("The largest column index: ", end = "") 58 | for i in range(len(ListCol) - 1): 59 | print(ListCol[i], end = ", ") 60 | print(ListCol[len(ListCol) - 1]) 61 | 62 | main() 63 | -------------------------------------------------------------------------------- /chapter11/11.13.py: -------------------------------------------------------------------------------- 1 | '''Program to find the largest element in a 2D list''' 2 | 3 | 4 | def locateLargest(a): 5 | l = [0,0] 6 | maxValue = a[0][0] 7 | for i in range(len(a)): 8 | for j in range(len(a[i])): 9 | if float(maxValue) < float(a[i][j]): 10 | maxValue = a[i][j] 11 | l[0] = i 12 | l[1] = j 13 | return l 14 | 15 | def main(): 16 | row, col = eval(input("Enter the number of rows and columns in the list: ")) 17 | matrix2D = [] 18 | for i in range(row): 19 | matrix2D.append([]) 20 | print("Enter row ", i, " :", end = " ") 21 | input1 = input() 22 | eleCol = input1.split(" ") 23 | k = 0 24 | for j in range(col): 25 | matrix2D[i].append(eleCol[k]) 26 | k +=1 27 | 28 | largest = locateLargest(matrix2D) 29 | 30 | print("The location of largest element is at (", largest[0], ",",largest[1],")") 31 | 32 | main() -------------------------------------------------------------------------------- /chapter11/11.2.py: -------------------------------------------------------------------------------- 1 | '''Program to find the sum of major diagonal of a given matrix''' 2 | 3 | def sumMajorDiagonal(m): 4 | sumMajorDiag = 0 5 | for i in range(len(m)): 6 | for j in range(len(m)): 7 | if(i==j): 8 | sumMajorDiag += m[i][j] 9 | 10 | return sumMajorDiag 11 | 12 | def main(): 13 | matrix = [] # Create an empty list 14 | numberOfRows = eval(input("Enter the number of rows: ")) 15 | numberOfColumns = eval(input("Enter the number of columns: ")) 16 | 17 | for i in range(numberOfRows): 18 | matrix.append([]) 19 | print("Enter row ", i, " :", end = " ") 20 | input1 = input() 21 | eleCol = input1.split(" ") 22 | k = 0 23 | for j in range(numberOfColumns): 24 | matrix[i].append(int(eleCol[k])) 25 | k +=1 26 | 27 | 28 | for row in range(numberOfRows): 29 | for column in range(numberOfColumns): 30 | print(matrix[row][column], end = " ") 31 | print() 32 | 33 | print("The sum of major diagonal is :", sumMajorDiagonal(matrix)) 34 | 35 | main() 36 | -------------------------------------------------------------------------------- /chapter11/11.25.py: -------------------------------------------------------------------------------- 1 | '''Program to implement Markov matrix''' 2 | 3 | def checkPositive(matrix): 4 | check=False 5 | for i in range(len(matrix)): 6 | for j in range(len(matrix[i])): 7 | if(matrix[i][j]>=0): 8 | check=True 9 | else: 10 | check=False 11 | return check 12 | 13 | def checkSumOfElements(matrix): 14 | check=False 15 | 16 | for j in range(len(matrix[0])): 17 | sum1=0 18 | for i in range(len(matrix)): 19 | sum1=matrix[i][j]+sum1 20 | if(sum1==1): 21 | check=True 22 | else: 23 | check=False 24 | return check 25 | 26 | 27 | 28 | def main(): 29 | matrix = [] 30 | numberOfRows = eval(input("Enter the number of rows ")) 31 | numberOfColumns = eval(input("Enter the number of columns: ")) 32 | print("Enter a 3 by 3 matrix row by row :") 33 | 34 | for i in range(numberOfRows): 35 | matrix.append([]) 36 | input1 = input() 37 | eleCol = input1.split(" ") 38 | k = 0 39 | for j in range(numberOfColumns): 40 | matrix[i].append(float(eleCol[k])) 41 | k +=1 42 | 43 | if checkPositive(matrix) and checkSumOfElements(matrix): 44 | print("The matrix is Markov ") 45 | else: 46 | print("The matrix is not Markov") 47 | 48 | main() -------------------------------------------------------------------------------- /chapter11/11.5.py: -------------------------------------------------------------------------------- 1 | '''Program to add two 2D matrix''' 2 | 3 | def printMatrix(m): 4 | for row in range(len(m)): 5 | for column in range(len(m[row])): 6 | print(m[row][column], end = " ") 7 | print() 8 | 9 | 10 | def addMatrices(m1, m2): 11 | if(len(m1) == len(m2)): 12 | m3 = [] 13 | for i in range(len(m1)): 14 | m3.append([]) 15 | for j in range(len(m1)): 16 | m3[i].append(m1[i][j] + m2[i][j]) 17 | 18 | printMatrix(m3) 19 | 20 | else: 21 | print("Matrices of different length cannot be added") 22 | 23 | def main(): 24 | matrix1 = [] # Create an empty list 25 | matrix2 = [] 26 | numberOfRows = 3 #eval(input("Enter the number of rows: ")) 27 | numberOfColumns = 3 #eval(input("Enter the number of columns: ")) 28 | numbers = input("Enter the matrix1: ") 29 | value = numbers.split(" ") 30 | 31 | count = 0 32 | for row in range(numberOfRows): 33 | matrix1.append([]) # Add an empty new row 34 | for column in range(numberOfColumns): 35 | matrix1[row].append(int(value[count])) 36 | count += 1 37 | 38 | numbers2 = input("Enter the matrix2: ") 39 | value2 = numbers2.split(" ") 40 | 41 | count = 0 42 | for row in range(numberOfRows): 43 | matrix2.append([]) # Add an empty new row 44 | for column in range(numberOfColumns): 45 | matrix2[row].append(int(value2[count])) 46 | count += 1 47 | 48 | 49 | 50 | print("The sum of matrix 1 and 2 is:") 51 | addMatrices(matrix1,matrix2) 52 | 53 | main() -------------------------------------------------------------------------------- /chapter11/11.51.py: -------------------------------------------------------------------------------- 1 | '''Program to sort students ''' 2 | 3 | def main(): 4 | matrix = input("Enter students' names and scores: ").split() 5 | students = [] 6 | for i in range(0,len(matrix),2): 7 | temp = [] 8 | temp.append(float(matrix[i+1])) 9 | temp.append(matrix[i]) 10 | students.append(temp) 11 | students.sort() 12 | 13 | for i in range(0,int(len(matrix)/2)): 14 | print(students[i][1]+ " " +str(students[i][0])) 15 | 16 | main() -------------------------------------------------------------------------------- /chapter11/11.6.py: -------------------------------------------------------------------------------- 1 | '''Program to multiply two 2D matrix''' 2 | 3 | def printMatrix(m): 4 | for row in range(len(m)): 5 | for column in range(len(m[row])): 6 | print(m[row][column], end = " ") 7 | print() 8 | 9 | 10 | def MultiplyMatrices(m1, m2): 11 | list = len(m2[0]) * [0] 12 | result = [] 13 | for i in range(len(m1)): 14 | result.append([x for x in list]) 15 | 16 | for i in range(len(result)): 17 | for j in range(len(result[0])): 18 | for k in range(len(m2)): 19 | result[i][j] += m1[i][k] * m2[k][j] 20 | 21 | printMatrix(result) 22 | 23 | def main(): 24 | matrix1 = [] # Create an empty list 25 | matrix2 = [] 26 | numberOfRows = eval(input("Enter the number of rows: ")) 27 | numberOfColumns = eval(input("Enter the number of columns: ")) 28 | numbers = input("Enter the matrix1: ") 29 | value = numbers.split(" ") 30 | 31 | count = 0 32 | for row in range(numberOfRows): 33 | matrix1.append([]) # Add an empty new row 34 | for column in range(numberOfColumns): 35 | matrix1[row].append(int(value[count])) 36 | count += 1 37 | 38 | numbers2 = input("Enter the matrix2: ") 39 | value2 = numbers2.split(" ") 40 | 41 | count = 0 42 | for row in range(numberOfRows): 43 | matrix2.append([]) # Add an empty new row 44 | for column in range(numberOfColumns): 45 | matrix2[row].append(int(value2[count])) 46 | count += 1 47 | 48 | 49 | 50 | print("The multiplication of matrix 1 and 2 is:") 51 | MultiplyMatrices(matrix1,matrix2) 52 | 53 | main() -------------------------------------------------------------------------------- /chapter12/12-02_locate-max.py: -------------------------------------------------------------------------------- 1 | # Liang 12.2 2 | 3 | class Location: 4 | def __init__(self, row, column, maxValue): 5 | self.row = row 6 | self.column = column 7 | self.maxValue = maxValue 8 | 9 | def locateLargest(arr): 10 | maxValue = arr[0][0] 11 | row = col = 0 12 | 13 | for i in range(len(arr)): 14 | for j in range(len(arr[i])): 15 | if arr[i][j] > maxValue: 16 | maxValue = arr[i][j] 17 | row = i 18 | col = j 19 | return Location(row, col, maxValue) 20 | 21 | def main(): 22 | uInput = input('Enter the number of rows and columns in the list: ') 23 | arrDimn = [int(d) for d in uInput.split(',')] 24 | arr = [] 25 | nRow = 0 26 | 27 | while nRow < arrDimn[0]: 28 | cRow = [int(v) for v in input('Enter row %d: ' % nRow).split()] 29 | if len(cRow) > arrDimn[1]: 30 | raise RuntimeError('Out of Bound Exception: Row %d' % nRow) 31 | arr += [cRow] 32 | nRow += 1 33 | 34 | loc = locateLargest(arr) 35 | print ('The location of the largest element is %d at (%d, %d)' % (loc.maxValue, loc.row, loc.column)) 36 | 37 | if __name__ == '__main__': 38 | main() 39 | -------------------------------------------------------------------------------- /chapter12/12-04_bounded-rect.py: -------------------------------------------------------------------------------- 1 | # Liang 12.4 2 | from Rectangle2D import * 3 | 4 | def getRectangle(points): 5 | xVals = [float(points[x]) for x in range(len(points)) if x % 2 == 0] 6 | yVals = [float(points[y]) for y in range(len(points)) if y % 2 != 0] 7 | xMax, yMax, xMin, yMin = max(xVals), max(yVals), min(xVals), min(yVals) 8 | x = (xMax + xMin) / 2 9 | y = (yMax + yMin) / 2 10 | 11 | return Rectangle2D(x, y, abs(xMax - xMin), abs(yMax - yMin)) 12 | 13 | def main(): 14 | points = input('Enter the points: ') 15 | rect = getRectangle(points.split()) 16 | print ('The bounding rectangle is centered at (%0.2f, %0.2f) with width %0.2f and height %0.2f' \ 17 | % (rect.getX(), rect.getY(), rect.getWidth(), rect.getHeight())) 18 | 19 | if __name__ == '__main__': 20 | main() 21 | -------------------------------------------------------------------------------- /chapter12/1_TriangleClass.py: -------------------------------------------------------------------------------- 1 | '''Program to create rectangle class by inheriting Geometric object class''' 2 | 3 | from GeometricObject import GeometricObject 4 | 5 | class Rectangle(GeometricObject): 6 | def __init__(self, side1 = 1, side2 = 1, side3 = 1): 7 | super().__init__() 8 | self.__side1 = side1 9 | self.__side2 = side2 10 | self.__side3 = side3 11 | 12 | def getSide1(self): 13 | return self.__side1 14 | 15 | def setSide1(self, side1): 16 | self.__side1 = side1 17 | def getSide2(self): 18 | return self.__side2 19 | 20 | def setSide2(self, side2): 21 | self.__side2 = side2 22 | 23 | def getSide3(self): 24 | return self.__side3 25 | 26 | def setSide3(self, side3): 27 | self.__side3 = side3 28 | 29 | 30 | def getArea(self): 31 | p = self.getPerimeter() 32 | area = (p*(p-self.__side1)*(p-self.__side2)*(p-self.__side3))**0.5 33 | return area 34 | 35 | def getPerimeter(self): 36 | return (self.__side1 + self.__side2 + self.__side3) 37 | 38 | def __str__(self): 39 | return "Triangle: side1 = " + str(self.__side1) + " side2 = " + str(self.__side2) + " side3 = " + str(self.__side3) 40 | 41 | 42 | def main(): 43 | s1,s2,s3 = eval(input("Enter the three sides of a Triangle: ")) 44 | color = input("Enter the color of Triangle: ") 45 | isFilled = eval(input("Is Triangle filled(0/1): ")) 46 | R = Rectangle(s1,s2,s3) 47 | R.setColor(color) 48 | R.setFilled(isFilled) 49 | 50 | print("Area is: ", R.getArea()," Perimeter is: ", R.getPerimeter(), " Color is:", R.getColor(), " Filled: ", str(R.isFilled())) 51 | 52 | 53 | main() -------------------------------------------------------------------------------- /chapter12/2_LocationClass.py: -------------------------------------------------------------------------------- 1 | '''Program to create location class - to locate largest number''' 2 | 3 | class Location(): 4 | def __init__(self, row = 0, column = 0, maxValue = 0.0): 5 | self.row = row 6 | self.column = column 7 | self.maxValue = maxValue 8 | 9 | def getrow(self): 10 | return self.row 11 | 12 | def setrow(self, row): 13 | self.row = row 14 | 15 | def getcolumn(self): 16 | return self.column 17 | 18 | def setcolumn(self, column): 19 | self.column = column 20 | 21 | def getMaxValue(self): 22 | return self.maxValue 23 | 24 | 25 | def locateLargest(self, a): 26 | self.maxValue = a[0][0] 27 | for i in range(len(a)): 28 | for j in range(len(a[i])): 29 | if float(self.maxValue) < float(a[i][j]): 30 | self.maxValue = a[i][j] 31 | self.row = i 32 | self.column = j 33 | 34 | 35 | 36 | 37 | def printMatrix(a): 38 | for i in range(len(a)): 39 | for j in range(len(a[i])): 40 | print(a[i][j], end =" ") 41 | print() 42 | 43 | def Input2DMatrix(): 44 | row, col = eval(input("Enter the number of rows and columns in the list: ")) 45 | matrix2D = [] 46 | for i in range(row): 47 | matrix2D.append([]) 48 | print("Enter row ", i, " :", end = " ") 49 | input1 = input() 50 | eleCol = input1.split(" ") 51 | k = 0 52 | for j in range(col): 53 | matrix2D[i].append(eleCol[k]) 54 | k +=1 55 | 56 | return matrix2D 57 | 58 | def main(): 59 | inputmatrix = Input2DMatrix() 60 | printMatrix(inputmatrix) 61 | l = Location() 62 | l.locateLargest(inputmatrix) 63 | 64 | print("The Location of Largest element is", l.maxValue, "at (",l.getrow(),",",l.getcolumn(),")") 65 | 66 | main() -------------------------------------------------------------------------------- /chapter12/3_ATMMachine.py: -------------------------------------------------------------------------------- 1 | '''Program to create ATM class''' 2 | import sys 3 | 4 | class Account: 5 | def __init__(self): 6 | self.__balance = 100.0 7 | self.__id= 0 8 | self.__annualInterestRate = 0.0 9 | 10 | def getMonthlyInterestRate(self): 11 | return (self.annualInterestRate/100)/12 12 | 13 | def getMonthlyInterest(self): 14 | return self.__balance * self.getMonthlyInterestRate() 15 | 16 | def withdraw(self,amount): 17 | self.__balance=self.__balance-amount 18 | 19 | def deposit(self,amount): 20 | self.__balance=self.__balance+amount 21 | 22 | def getBalance(self): 23 | return self.__balance 24 | 25 | class ATMmachine(Account): 26 | def __init__(self, id): 27 | super().__init__() 28 | self.id = id 29 | def getMainMenu(self): 30 | return "Main menu \n1: Check balance \n2: Withdraw \n3: Deposit \n4: Exit \nEnter a choice: " 31 | 32 | 33 | def main(): 34 | account=[0,1,2,3,4,5,6,7,8,9] 35 | 36 | while True: 37 | id1 = eval(input("Enter an account id: ")) 38 | if id1 in account: 39 | atmMachine = ATMmachine(id1) 40 | while True: 41 | choiceInput = eval(input(atmMachine.getMainMenu())) 42 | if choiceInput == 1: 43 | 44 | print("The balance is: ", atmMachine.getBalance()) 45 | atmMachine.getMainMenu() 46 | elif choiceInput == 2: 47 | d = eval(input("Enter an amount to withdraw: ")) 48 | atmMachine.withdraw(d) 49 | atmMachine.getMainMenu() 50 | elif choiceInput == 3: 51 | d = eval(input("Enter an amount to Deposit: ")) 52 | atmMachine.deposit(d) 53 | atmMachine.getMainMenu() 54 | elif choiceInput == 4: 55 | sys.exit() 56 | break 57 | else: 58 | print("Incorrect account id!") 59 | continue 60 | 61 | main() 62 | 63 | 64 | 65 | 66 | 67 | -------------------------------------------------------------------------------- /chapter13/13.1.py: -------------------------------------------------------------------------------- 1 | '''Program to remove a string in the same file''' 2 | 3 | def removeWord(filename, word): 4 | readfile = open(filename,"r") 5 | read = readfile.read().split() 6 | 7 | newString = "" 8 | for i in read: 9 | if word.lower() in i.lower(): 10 | newString += "" 11 | else: 12 | newString += i 13 | 14 | writefile = open(filename,'w') 15 | writefile.write(str(newString)) 16 | 17 | writefile.close() 18 | readfile.close() 19 | print("The file has been updated !") 20 | 21 | def main(): 22 | filename = input("Enter the input path: ") 23 | word = input("Enter the word you want to remove: ") 24 | 25 | removeWord(filename,word) 26 | 27 | main() 28 | -------------------------------------------------------------------------------- /chapter13/13.17.py: -------------------------------------------------------------------------------- 1 | # L 13.17 2 | import urllib.request 3 | 4 | def computeSalary(infile): 5 | staffs = ['assistant', 'associate', 'full'] 6 | salary = [[0,0], [0,0], [0,0]] 7 | currStaff = infile.readline().decode().split() 8 | while currStaff != []: 9 | s = staffs.index(currStaff[2]) 10 | salary[s][0] += float(currStaff[3]) 11 | salary[s][1] += 1 12 | currStaff = infile.readline().decode().split() 13 | return salary 14 | 15 | def main(): 16 | # url = input('Etner the URL for a file: ') 17 | url = 'http://cs.armstrong.edu/liang/data/Salary.txt' 18 | infile = urllib.request.urlopen(url) 19 | 20 | tSals = computeSalary(infile) 21 | st1, st2, st3 = tSals[0][0], tSals[1][0], tSals[2][0] 22 | n1, n2, n3 = tSals[0][1], tSals[1][1], tSals[2][1] 23 | # computeAvgSalary(s) 24 | 25 | print ('Total Salary\n%s %15.2f \n%s %15.2f \n%s %20.2f \n%s %13.2f' % \ 26 | ('Assistant salary:', st1, 'Associate salary:', st2, 'Full salary:', st3, \ 27 | 'All Faculty salary:', st1+st2+st3)) 28 | 29 | print ('\nAverage Salary\n%s %15.2f \n%s %15.2f \n%s %20.2f \n%s %13.2f' % \ 30 | ('Assistant salary:', st1 / n1, 'Associate salary:', st2 / n2, 'Full salary:', st3 / n3, \ 31 | 'All Faculty salary:', (st1+st2+st3)/(n1+n2+n3))) 32 | 33 | 34 | if __name__ == '__main__': 35 | main() 36 | -------------------------------------------------------------------------------- /chapter13/13.2.py: -------------------------------------------------------------------------------- 1 | '''Program to count the characters lines and words''' 2 | 3 | def main(): 4 | file1 = input("Enter a filename: ").strip() 5 | readfile = open(file1, "r") 6 | 7 | stringFile = readfile.read() 8 | word=stringFile.split() 9 | sum1=0 10 | for i in word: 11 | sum1+=len(i) 12 | print(str(sum1) + " characters") 13 | print(str(len(stringFile.split())) + " words") 14 | print(str(len(stringFile.split('\n'))) + " lines") 15 | 16 | 17 | readfile.close() 18 | main() 19 | -------------------------------------------------------------------------------- /chapter13/13.3.py: -------------------------------------------------------------------------------- 1 | '''Program to process scores''' 2 | 3 | def main(): 4 | file1 = input("Enter a filename: ").strip() 5 | readfile = open(file1, "r") 6 | 7 | 8 | stringFile = readfile.read() 9 | word=stringFile.split() 10 | 11 | Scores=[eval(x) for x in word] 12 | total = len(Scores) 13 | sum1 = 0 14 | for i in Scores: 15 | sum1 += i 16 | 17 | average=sum1/total 18 | 19 | print("There are",total," Scores") 20 | print("The Total is",sum1) 21 | print("The Average is",average) 22 | 23 | readfile.close() 24 | 25 | main() 26 | -------------------------------------------------------------------------------- /chapter13/13.6.py: -------------------------------------------------------------------------------- 1 | '''Program that counts the number of words in 2 | President Abraham Lincoln’s Gettysburg Address given in the url''' 3 | 4 | import urllib.request 5 | 6 | def main(): 7 | readfile = urllib.request.urlopen("http://cs.armstrong.edu/liang/data/Lincoln.txt") 8 | stringFile = readfile.read() 9 | print("The number of words in the file is " + str(len(stringFile.split()))) 10 | 11 | main() -------------------------------------------------------------------------------- /chapter13/13.8.py: -------------------------------------------------------------------------------- 1 | # L 13.8 2 | import pickle 3 | 4 | def encrypt(ifile, ofile): 5 | infile = open(ifile, 'r') 6 | outfile = open(ofile, 'wb') 7 | for line in infile: 8 | for word in line: 9 | for char in word: 10 | pickle.dump(chr(ord(char)+5), outfile) 11 | infile.close() 12 | outfile.close() 13 | return 'Done' 14 | 15 | def main(): 16 | ifile, ofile = input('Enter name of input and output file: ').split(',') 17 | print (encrypt(ifile, ofile)) 18 | 19 | if __name__ == '__main__': 20 | main() 21 | 22 | -------------------------------------------------------------------------------- /chapter13/13.9.py: -------------------------------------------------------------------------------- 1 | # L 13.9 2 | import pickle 3 | 4 | def decrypt(ifile, ofile): 5 | infile = open(ifile, 'rb') 6 | outfile = open(ofile, 'w') 7 | s = pickle.load(infile) 8 | try: 9 | while s != '': 10 | outfile.write(chr(ord(s)-5)) 11 | s = pickle.load(infile) 12 | except EOFError: 13 | infile.close() 14 | outfile.close() 15 | return 'Done' 16 | 17 | def main(): 18 | ifile, ofile = input('Enter name of input and output file: ').split(',') 19 | print (decrypt(ifile, ofile)) 20 | 21 | if __name__ == '__main__': 22 | main() 23 | 24 | -------------------------------------------------------------------------------- /chapter14/14.3.py: -------------------------------------------------------------------------------- 1 | '''Program to check the keywords in a python file''' 2 | import os.path 3 | import sys 4 | 5 | def main(): 6 | keyWords = {"and", "as", "assert", "break", "class", 7 | "continue", "def", "del", "elif", "else", 8 | "except", "False", "finally", "for", "from", 9 | "global", "if", "import", "in", "is", "lambda", 10 | "None", "nonlocal", "not", "or", "pass", "raise", 11 | "return", "True", "try", "while", "with", "yield"} 12 | 13 | filename = input("Enter a Python filename: ").strip() 14 | 15 | if not os.path.isfile(filename): 16 | print("File", filename, "does not exist") 17 | sys.exit() 18 | 19 | readfile = open(filename, "r") 20 | words = readfile.read().split() 21 | count = 0 22 | countKeyword={} 23 | for word in words: 24 | if word in keyWords: 25 | count += 1 26 | countKeyword[word]=count 27 | 28 | for key in countKeyword: 29 | print(key + ":" + str(countKeyword[key])) 30 | 31 | readfile.close() 32 | 33 | main() -------------------------------------------------------------------------------- /chapter15/15.1.py: -------------------------------------------------------------------------------- 1 | '''Recursive method to do sum of digits''' 2 | 3 | def SumOfDigits(n): 4 | if(n==0): 5 | return n 6 | else: 7 | return n%10+ SumOfDigits(n//10) 8 | 9 | 10 | def main(): 11 | input1=eval(input("Enter the number: ")) 12 | print("Sum of digits is",SumOfDigits(input1)) 13 | 14 | 15 | main() -------------------------------------------------------------------------------- /chapter15/15.12.py: -------------------------------------------------------------------------------- 1 | # L 15.12 2 | 3 | def findLargest(l): 4 | if len(l) == 1: 5 | return l[0] 6 | else: 7 | return max(l[0], findLargest(l[1:])) 8 | 9 | def main(): 10 | nums = input('Enter a list of number: ').split(',') 11 | nList = [int(n) for n in nums] 12 | print (findLargest(nList)) 13 | 14 | if __name__ == '__main__': 15 | main() 16 | -------------------------------------------------------------------------------- /chapter15/15.21.py: -------------------------------------------------------------------------------- 1 | # (Binary to decimal) Write a recursive function that parses a binary number as a 2 | # string into a decimal integer. The function header is as follows: 3 | # def binaryToDecimal(binaryString): 4 | # Write a test program that prompts the user to enter a binary string and displays its 5 | # decimal equivalent. 6 | 7 | def binaryToDecimal(binaryString): 8 | if len(binaryString) == 0: 9 | return 0 10 | else: 11 | return 2**(len(binaryString) - 1) * (int(binaryString[0])) + binaryToDecimal(binaryString[1:len(binaryString)]) 12 | 13 | def test(): 14 | binaryString = input("Enter a binary number:") 15 | 16 | print("The decimal equivalent of the binary string is", binaryToDecimal(binaryString)) 17 | 18 | test() -------------------------------------------------------------------------------- /chapter15/15.23.py: -------------------------------------------------------------------------------- 1 | # (String permutation) Write a recursive function to print all the permutations of a 2 | # string. For example, for the string abc, the printout is: 3 | # abc 4 | # acb 5 | # bac 6 | # bca 7 | # cab 8 | # cba 9 | # (Hint: Define the following two functions. The second function is a helper function. 10 | # def displayPermuation(s): 11 | # def displayPermuationHelper(s1, s2): 12 | # The first function simply invokes displayPermuation(" ", s).The second function uses a 13 | # loop to move a character from s2 to s1 and recursively invokes it with a new s1 and s2. 14 | # The base case is that s2 is empty and prints s1 to the console.) Write a test program that 15 | # prompts the user to enter a string and displays all its permutations. 16 | 17 | def displayPermutation(s): 18 | displayPermutationHelper(" ", s) 19 | 20 | def displayPermutationHelper(s1, s2): 21 | if len(s2) == 0: 22 | print(s1) 23 | # else: 24 | for i in range(len(s2)): 25 | # print(s1) 26 | displayPermutationHelper(s1 + s2[i], s2[0:i] + s2[i+1:len(s2)]) 27 | 28 | displayPermutation("abc") 29 | 30 | # 31 | # def permutations(s,l,r): 32 | # 33 | # if l==r: 34 | # str1=tostring(s) 35 | # print(str1) 36 | # else: 37 | # for i in range(l,r+1): 38 | # 39 | # s[l],s[i]=s[i],s[l] 40 | # 41 | # permutations(s,l+1,r) 42 | # 43 | # s[l], s[i] = s[i], s[l] 44 | # 45 | # 46 | # def tostring(s): 47 | # str1 = ''.join(s) 48 | # return str1 49 | # 50 | # b="abc" 51 | # a=list(b) 52 | # permutations(a,0,len(b)-1) -------------------------------------------------------------------------------- /chapter15/15.24.py: -------------------------------------------------------------------------------- 1 | # (Number of files in a directory) Write a program that prompts the user to enter a 2 | # directory and displays the number of files in the directory. 3 | 4 | import os 5 | 6 | def getNumberOfFiles(path): 7 | count = 0 8 | if not os.path.isfile(path): 9 | lst = os.listdir(path) 10 | for subdirectory in lst: 11 | count += getNumberOfFiles(path + "\\" + subdirectory) 12 | else: 13 | count += 1 14 | return count 15 | 16 | def test(): 17 | inputDirectory = input("Enter a directory:") 18 | 19 | print("Total number of files inside the directory is", str(getNumberOfFiles(inputDirectory))) 20 | 21 | test() -------------------------------------------------------------------------------- /chapter15/15.3.py: -------------------------------------------------------------------------------- 1 | '''Program to do GCD recursive method''' 2 | 3 | def GCD(a,b): 4 | if a%b ==0: 5 | return b 6 | else: 7 | GCD(b,a%b) 8 | 9 | 10 | def main(): 11 | num1,num2=eval(input("Enter two numbers: ")) 12 | if(num1 < num2): 13 | num1,num2=num2,num1 14 | print("GCD :", GCD(num1, num2)) 15 | 16 | 17 | main() -------------------------------------------------------------------------------- /chapter2/2.1.py: -------------------------------------------------------------------------------- 1 | celsius = int(input("Enter a degree in celsius : ")) 2 | print(celsius, "Celsius is", (9 / 5) * celsius + 32, "Fahrenheit") 3 | -------------------------------------------------------------------------------- /chapter2/2.10.py: -------------------------------------------------------------------------------- 1 | v, a = eval(input("Enter speed and acceleration : ")) 2 | length = (v ** 2) / (2 * a) 3 | 4 | print("The minimum runaway length for this airplane is", length) 5 | -------------------------------------------------------------------------------- /chapter2/2.11.py: -------------------------------------------------------------------------------- 1 | final_account_value = eval(input("Enter the final account value : ")) 2 | annual_interest_rate = eval(input("Enter the annual interest rate in percent : ")) 3 | number_of_years = eval(input("Enter the number of years : ")) 4 | 5 | monthly_interest_rate = (annual_interest_rate / 52) / 100 6 | number_of_months = 52 * number_of_years 7 | 8 | initial_deposit_value = final_account_value / ((1 + monthly_interest_rate) ** number_of_months) 9 | 10 | amount_of_money_needed = 5000 - initial_deposit_value 11 | 12 | print("Initial deposit value", initial_deposit_value) 13 | 14 | print("The amount of money needed to deposit inorder to to have 5000 is", amount_of_money_needed) 15 | -------------------------------------------------------------------------------- /chapter2/2.12.py: -------------------------------------------------------------------------------- 1 | a = 0 2 | print("a b a ** b") 3 | while a < 6: 4 | b = a + 1 5 | c = a ** b 6 | a += 1 7 | print(a, b, c) 8 | -------------------------------------------------------------------------------- /chapter2/2.13.py: -------------------------------------------------------------------------------- 1 | integer = eval(input("Enter a 4 digit integer : ")) 2 | total = 0 3 | a = [] 4 | 5 | while integer > 0: 6 | 7 | digit = integer % 10 8 | 9 | integer = integer // 10 10 | 11 | a.append(digit) 12 | 13 | a[::-1] 14 | 15 | print(a[3]) 16 | print(a[2]) 17 | print(a[1]) 18 | print(a[0]) 19 | 20 | 21 | -------------------------------------------------------------------------------- /chapter2/2.14.py: -------------------------------------------------------------------------------- 1 | x1, y1, x2, y2, x3, y3 = eval(input("Enter three points of a triangle : ")) 2 | 3 | print(x1, y1) 4 | print(x2, y2) 5 | print(x3, y3) 6 | 7 | side1 = (((x1 - x2) ** 2) + ((y1 - y2) ** 2)) ** (1 / 2) 8 | side2 = (((x1 - x3) ** 2) + ((y1 - y3) ** 2)) ** (1 / 2) 9 | side3 = (((x3 - x2) ** 2) + ((y3 - y2) ** 2)) ** (1 / 2) 10 | 11 | s = (side1 + side2 + side3) / 2 12 | 13 | area = (s * ((s - side1) * (s - side2) * (s - side3))) ** (1 / 2) 14 | 15 | print("The area of the triangle is", area) 16 | -------------------------------------------------------------------------------- /chapter2/2.15.py: -------------------------------------------------------------------------------- 1 | side = eval(input("Enter the side : ")) 2 | s = side 3 | area = (((3 * (3 ** (1 / 2))) / 2) * (s ** (2))) 4 | 5 | print("The area of the hexagon is", area) 6 | -------------------------------------------------------------------------------- /chapter2/2.16.py: -------------------------------------------------------------------------------- 1 | v0, v1, t = eval(input("Enter v0 and v1 and t : ")) 2 | a = (v1 - v0) / t 3 | print("The average acceleration is", a) 4 | -------------------------------------------------------------------------------- /chapter2/2.17.py: -------------------------------------------------------------------------------- 1 | weight_pounds = eval(input("Enter weight in pounds : ")) 2 | height_inches = eval(input("Enter height in inches : ")) 3 | 4 | weight_kilo = 0.45359237 * weight_pounds 5 | height_meters = 0.0254 * height_inches 6 | 7 | BMI = weight_kilo / (height_meters ** 2) 8 | 9 | print('BMI =', BMI) 10 | -------------------------------------------------------------------------------- /chapter2/2.18.py: -------------------------------------------------------------------------------- 1 | GMT_offset = eval(input("Enter the time zone offset to GMT : ")) 2 | 3 | import time 4 | currentTime = time.time() 5 | 6 | totalSeconds = int(currentTime) 7 | currentSecond = totalSeconds % 60 8 | 9 | totalMinutes = totalSeconds // 60 10 | currentMinute = totalMinutes % 60 11 | 12 | totalHours = totalMinutes // 60 13 | currentHour = (totalHours % 24) + GMT_offset 14 | 15 | 16 | print("Current time is", currentHour, ":", currentMinute, ":", currentSecond, "GMT") 17 | -------------------------------------------------------------------------------- /chapter2/2.19.py: -------------------------------------------------------------------------------- 1 | investmentAmount = eval(input("Enter investment amount : ")) 2 | annualInterestRate = eval(input("Enter annual interest rate : ")) 3 | number_of_years = eval(input("Enter number of years : ")) 4 | 5 | monthlyInterestRate = (annualInterestRate) / 100 6 | number_of_months = number_of_years 7 | 8 | futureInvestmentAmount = investmentAmount * ((1 + monthlyInterestRate) ** number_of_months) 9 | 10 | print("Accumulated value is", futureInvestmentAmount) 11 | -------------------------------------------------------------------------------- /chapter2/2.2.py: -------------------------------------------------------------------------------- 1 | radius, length = eval(input("Enter the radius and length of a cylinder : ")) 2 | PI = 3.14 3 | area = radius * radius * PI 4 | volume = area * length 5 | print("The area is", area, "\n The volume is", volume) 6 | -------------------------------------------------------------------------------- /chapter2/2.20.py: -------------------------------------------------------------------------------- 1 | balance, interest_rate = eval(input("Enter balance and interest rate : ")) 2 | 3 | interest = balance * (interest_rate / 1200) 4 | 5 | print("The interest is", interest) 6 | -------------------------------------------------------------------------------- /chapter2/2.21.py: -------------------------------------------------------------------------------- 1 | annual_interest_rate = eval(input('Enter annual interest rate : ')) 2 | monthly_saving = eval(input("Enter monthly saving amount : ")) 3 | 4 | monthly_interest_rate = (annual_interest_rate / 100) / 12 5 | 6 | first_month = 100 * (1 + 0.00417) 7 | 8 | months = 0 9 | 10 | while months < 5: 11 | 12 | next_month = (100 + first_month) * (1 + 0.00417) 13 | 14 | first_month = next_month 15 | 16 | months += 1 17 | 18 | print("After the sixth month the account saving is", first_month) 19 | -------------------------------------------------------------------------------- /chapter2/2.22.py: -------------------------------------------------------------------------------- 1 | birth_in_7_sec = 1 2 | birth_per_hour = 3600 // 7 3 | birth_per_day = 24 * birth_per_hour 4 | 5 | immigrants_in_45_sec = 1 6 | immigrants_per_hour = 3600 // 45 7 | immigrants_per_day = 24 * immigrants_per_hour 8 | 9 | death_in_13_sec = 1 10 | deaths_per_hour = 3600 // 13 11 | deaths_per_day = 24 * deaths_per_hour 12 | 13 | total_pop_per_day = birth_per_day + immigrants_per_day - deaths_per_day 14 | total_pop =312032486 + 365 * total_pop_per_day 15 | years = eval(input("Enter the number of years : ")) 16 | b = 1 17 | a = total_pop 18 | while b < (years + 1): 19 | 20 | print("total population in year", years, "is =", a) 21 | b += 1 22 | a += total_pop 23 | -------------------------------------------------------------------------------- /chapter2/2.23.py: -------------------------------------------------------------------------------- 1 | import turtle 2 | turtle.showturtle() 3 | 4 | turtle.penup() 5 | turtle.goto(-50, 0) 6 | turtle.pendown() 7 | 8 | turtle.right(-45) 9 | turtle.forward(50) 10 | turtle.right(-45) 11 | turtle.forward(50) 12 | turtle.right(-45) 13 | turtle.forward(50) 14 | turtle.right(-90) 15 | turtle.forward(50) 16 | turtle.right(-45) 17 | turtle.forward(50) 18 | turtle.right(-45) 19 | turtle.forward(100) 20 | turtle.right(45) 21 | turtle.forward(50) 22 | turtle.right(45) 23 | turtle.forward(50) 24 | turtle.right(90) 25 | turtle.forward(50) 26 | turtle.right(45) 27 | turtle.forward(50) 28 | turtle.right(45) 29 | turtle.forward(50) 30 | turtle.right(45) 31 | 32 | turtle.penup() 33 | turtle.goto(50, 0) 34 | turtle.pendown() 35 | 36 | turtle.right(-45) 37 | turtle.forward(50) 38 | turtle.right(-45) 39 | turtle.forward(50) 40 | turtle.right(-45) 41 | turtle.forward(50) 42 | turtle.right(-90) 43 | turtle.forward(50) 44 | turtle.right(-45) 45 | turtle.forward(50) 46 | turtle.right(-45) 47 | turtle.forward(100) 48 | turtle.right(45) 49 | turtle.forward(50) 50 | turtle.right(45) 51 | turtle.forward(50) 52 | turtle.right(90) 53 | turtle.forward(50) 54 | turtle.right(45) 55 | turtle.forward(50) 56 | turtle.right(45) 57 | turtle.forward(50) 58 | -------------------------------------------------------------------------------- /chapter2/2.24.py: -------------------------------------------------------------------------------- 1 | import turtle 2 | turtle.showturtle() 3 | 4 | turtle.penup() 5 | turtle.goto(-50, 0) 6 | turtle.pendown() 7 | 8 | turtle.right(-45) 9 | turtle.forward(50) 10 | turtle.right(-45) 11 | turtle.forward(50) 12 | turtle.right(-45) 13 | turtle.forward(50) 14 | turtle.right(-90) 15 | turtle.forward(50) 16 | turtle.right(-45) 17 | turtle.forward(50) 18 | turtle.right(-45) 19 | turtle.forward(100) 20 | turtle.right(45) 21 | turtle.forward(50) 22 | turtle.right(45) 23 | turtle.forward(50) 24 | turtle.right(90) 25 | turtle.forward(50) 26 | turtle.right(45) 27 | turtle.forward(50) 28 | turtle.right(45) 29 | turtle.forward(50) 30 | turtle.right(45) 31 | 32 | turtle.penup() 33 | turtle.goto(50, 0) 34 | turtle.pendown() 35 | 36 | turtle.right(-45) 37 | turtle.forward(50) 38 | turtle.right(-45) 39 | turtle.forward(50) 40 | turtle.right(-45) 41 | turtle.forward(50) 42 | turtle.right(-90) 43 | turtle.forward(50) 44 | turtle.right(-45) 45 | turtle.forward(50) 46 | turtle.right(-45) 47 | turtle.forward(100) 48 | turtle.right(45) 49 | turtle.forward(50) 50 | turtle.right(45) 51 | turtle.forward(50) 52 | turtle.right(90) 53 | turtle.forward(50) 54 | turtle.right(45) 55 | turtle.forward(50) 56 | turtle.right(45) 57 | turtle.forward(50) 58 | -------------------------------------------------------------------------------- /chapter2/2.25.py: -------------------------------------------------------------------------------- 1 | x, y = eval(input("Enter the center of the rectangle : ")) 2 | w, h = eval(input("Enter the width and height")) 3 | 4 | import turtle 5 | turtle.showturtle() 6 | 7 | turtle.penup() 8 | turtle.goto(x, y) 9 | 10 | turtle.goto(-(x + (w /2)), (y + (h /2)) ) 11 | turtle.pendown() 12 | turtle.forward(w) 13 | turtle.right(90) 14 | 15 | turtle.forward(h) 16 | turtle.right(90) 17 | 18 | turtle.forward(w) 19 | turtle.right(90) 20 | 21 | turtle.forward(h) 22 | turtle.right(90) 23 | -------------------------------------------------------------------------------- /chapter2/2.26.py: -------------------------------------------------------------------------------- 1 | x, y = eval(input("Enter the x and y coordinates of the center of the circle : ")) 2 | r = eval(input("Enter the radius of the circle : ")) 3 | 4 | PI = 3.1428571429 5 | A = PI * r *r 6 | 7 | import turtle 8 | turtle.showturtle() 9 | 10 | turtle.penup() 11 | turtle.goto(x, y) 12 | turtle.pendown() 13 | 14 | turtle.circle(r) 15 | turtle.penup() 16 | turtle.goto(x, (y + r)) 17 | turtle.pendown() 18 | turtle.write(A) 19 | 20 | -------------------------------------------------------------------------------- /chapter2/2.3.py: -------------------------------------------------------------------------------- 1 | feet = eval(input("Enter a value for feet : ")) 2 | meters = feet * (0.305) 3 | print(feet, "feet is", meters, "meters") 4 | -------------------------------------------------------------------------------- /chapter2/2.4.py: -------------------------------------------------------------------------------- 1 | pounds = eval(input("Enter a value in pounds : ")) 2 | kilo = (0.454) * pounds 3 | print(pounds, "pounds is", kilo, "kilograms") 4 | -------------------------------------------------------------------------------- /chapter2/2.5.py: -------------------------------------------------------------------------------- 1 | subtotal, gratuity_rate = eval(input("Enter the subtotal and gratuity rate\n")) 2 | gratuity = (gratuity_rate / 100) * subtotal 3 | total = gratuity + subtotal 4 | print("The gratuity is", gratuity, "and the total is", total) 5 | -------------------------------------------------------------------------------- /chapter2/2.6.py: -------------------------------------------------------------------------------- 1 | integer = eval(input("Enter an integer between 0 and 1000 : ")) 2 | total = 0 3 | while integer > 0: 4 | 5 | digit = integer % 10 6 | 7 | integer = integer // 10 8 | 9 | total += digit 10 | 11 | print(total) 12 | -------------------------------------------------------------------------------- /chapter2/2.7.py: -------------------------------------------------------------------------------- 1 | minutes = eval(input("Enter the number of minutes : ")) 2 | hours = minutes // 60 3 | days = hours // 24 4 | years = days // 365 5 | 6 | print(minutes, "minutes is approximately", years, "and", days, "days") 7 | -------------------------------------------------------------------------------- /chapter2/2.8.py: -------------------------------------------------------------------------------- 1 | M = eval(input("Enter the amount of water in kilogramme : ")) 2 | initial_temperature = eval(input("Enter the initial temperature : ")) 3 | final_temperature = eval(input("Enter the final temperature : ")) 4 | 5 | Q = M * (final_temperature - initial_temperature) * 4182 6 | 7 | print("The energy needed is", Q) 8 | -------------------------------------------------------------------------------- /chapter2/2.9.py: -------------------------------------------------------------------------------- 1 | ta = eval(input("Enter the temperature in Fahrenheit between -58 and 41 : ")) 2 | v = eval(input("Enter the wind speed in miles per hour : ")) 3 | 4 | if v >= 2: 5 | 6 | twc = 35.74 + (0.6215 * ta) - (35.75 * (v ** 0.16)) + (0.4275 * ta * (v ** 0.16)) 7 | print("The wind chill is", twc) 8 | 9 | else : 10 | 11 | print("Sorry but the wind speed is too small to be evaluated") 12 | -------------------------------------------------------------------------------- /chapter2/s.py: -------------------------------------------------------------------------------- 1 | Python 3.7.0 (v3.7.0:1bf9cc5093, Jun 27 2018, 04:59:51) [MSC v.1914 64 bit (AMD64)] on win32 2 | Type "copyright", "credits" or "license()" for more information. 3 | >>> 4 | ========== RESTART: C:/Users/Xurror/Desktop/mywork/chapter4/4.32.py ========== 5 | Enter the x and Y coordinates of the points p0, p1 and p2 respectively: 1, 1, 2, 2, 3, 3 6 | -------------------------------------------------------------------------------- /chapter3/3.1.py: -------------------------------------------------------------------------------- 1 | import math 2 | x1, y1 = eval(input("Enter point 1 (latitude and longitude) in degrees: ")) 3 | x2, y2 = eval(input("Enter point 2 (latitude and longitude) in degrees: ")) 4 | radius = 6371.01 5 | 6 | d = (radius * math.acos(math.sin(math.radians(x1))) * math.sin(math.radians(x2))) + (math.cos(math.radians(x1))) * math.cos(math.radians(x2)) * math.cos(math.radians(y1 - y2)) 7 | print("The distance between the two points is", round(area, 2)) 8 | -------------------------------------------------------------------------------- /chapter3/3.10.py: -------------------------------------------------------------------------------- 1 | import turtle 2 | turtle.showturtle() 3 | 4 | turtle.write("\u03b1\u03b2\u03b3\u03b4\u03b5\u03b6\u03b7\u03b8") -------------------------------------------------------------------------------- /chapter3/3.11.py: -------------------------------------------------------------------------------- 1 | integer = input("Enter an integer: ") 2 | print("The reversed number is", integer[::-1]) 3 | -------------------------------------------------------------------------------- /chapter3/3.12.py: -------------------------------------------------------------------------------- 1 | l = eval(input("Enter the length of the star: ")) 2 | 3 | import turtle 4 | turtle.showturtle() 5 | 6 | turtle.penup() 7 | turtle.goto(0, 100) 8 | turtle.pendown() 9 | 10 | turtle.right(72) 11 | turtle.forward(l) 12 | 13 | turtle.penup() 14 | turtle.goto(0, 100) 15 | turtle.pendown() 16 | 17 | turtle.right(36) 18 | turtle.forward(l) 19 | 20 | turtle.right(-144) 21 | turtle.forward(l) 22 | 23 | turtle.right(-144) 24 | turtle.forward(l) 25 | 26 | turtle.right(-144) 27 | turtle.forward(l) 28 | -------------------------------------------------------------------------------- /chapter3/3.13.py: -------------------------------------------------------------------------------- 1 | 2 | import turtle 3 | turtle.showturtle() 4 | 5 | turtle.begin_fill() 6 | turtle.circle(100, steps = 6) 7 | turtle.end_fill() 8 | 9 | turtle.goto(-75, 75) 10 | turtle.color("white") 11 | turtle.write("STOP", font = ("Seriff", 40, "bold")) 12 | 13 | turtle.color("black") 14 | -------------------------------------------------------------------------------- /chapter3/3.14.py: -------------------------------------------------------------------------------- 1 | import turtle 2 | 3 | turtle.color("blue") 4 | turtle.penup() 5 | turtle.goto(-110, -25) 6 | turtle.pendown() 7 | turtle.circle(45) 8 | 9 | turtle.color("black") 10 | turtle.penup() 11 | turtle.goto(0, -25) 12 | turtle.pendown() 13 | turtle.circle(45) 14 | 15 | turtle.color("red") 16 | turtle.penup() 17 | turtle.goto(110, -25) 18 | turtle.pendown() 19 | turtle.circle(45) 20 | 21 | turtle.color("yellow") 22 | turtle.penup() 23 | turtle.goto(-55, -75) 24 | turtle.pendown() 25 | turtle.circle(45) 26 | 27 | turtle.color("green") 28 | turtle.penup() 29 | turtle.goto(55, -75) 30 | turtle.pendown() 31 | turtle.circle(45) 32 | -------------------------------------------------------------------------------- /chapter3/3.15.py: -------------------------------------------------------------------------------- 1 | import turtle 2 | turtle.showturtle() 3 | #head 4 | turtle.circle(100) 5 | #nose 6 | turtle.penup() 7 | turtle.goto(0, 110) 8 | turtle.pendown() 9 | 10 | turtle.right(72) 11 | turtle.forward(50) 12 | 13 | turtle.penup() 14 | turtle.goto(0, 110) 15 | turtle.pendown() 16 | 17 | turtle.right(36) 18 | turtle.forward(50) 19 | #mouth 20 | turtle.penup() 21 | turtle.forward(10) 22 | turtle.pendown() 23 | 24 | turtle.penup() 25 | turtle.right(72) 26 | turtle.forward(5) 27 | turtle.pendown() 28 | 29 | 30 | turtle.penup() 31 | turtle.right(-170) 32 | turtle.forward(5) 33 | turtle.pendown() 34 | turtle.forward(20) 35 | 36 | turtle.right(-20) 37 | turtle.forward(20) 38 | #eyes 39 | turtle.penup() 40 | turtle.goto(30, 125) 41 | turtle.pendown() 42 | turtle.begin_fill() 43 | turtle.circle(10) 44 | turtle.end_fill() 45 | 46 | turtle.penup() 47 | turtle.goto(-30, 125) 48 | turtle.pendown() 49 | turtle.begin_fill() 50 | turtle.circle(10) 51 | turtle.end_fill() 52 | -------------------------------------------------------------------------------- /chapter3/3.16.py: -------------------------------------------------------------------------------- 1 | import turtle 2 | turtle.showturtle() 3 | 4 | turtle.penup() 5 | turtle.goto(-200, 0) 6 | turtle.pendown() 7 | 8 | turtle.begin_fill() 9 | turtle.circle(25, steps = 3) 10 | turtle.end_fill() 11 | 12 | turtle.penup() 13 | turtle.goto(-120, 0) 14 | turtle.pendown() 15 | turtle.color("gray") 16 | turtle.begin_fill() 17 | turtle.circle(25, steps = 4) 18 | turtle.end_fill() 19 | 20 | turtle.penup() 21 | turtle.goto(-40, 0) 22 | turtle.pendown() 23 | turtle.color("green") 24 | turtle.begin_fill() 25 | turtle.circle(25, steps = 5) 26 | turtle.end_fill() 27 | 28 | turtle.penup() 29 | turtle.goto(40, 0) 30 | turtle.pendown() 31 | turtle.color("blue") 32 | turtle.begin_fill() 33 | turtle.circle(25, steps = 6) 34 | turtle.end_fill() 35 | 36 | turtle.penup() 37 | turtle.goto(120, 0) 38 | turtle.pendown() 39 | turtle.color("purple") 40 | turtle.begin_fill() 41 | turtle.circle(25, steps = 7) 42 | turtle.end_fill() 43 | 44 | -------------------------------------------------------------------------------- /chapter3/3.17.py: -------------------------------------------------------------------------------- 1 | 2 | x1, y1 = eval(input("Enter the point p1 of a triangle: ")) 3 | x2, y2 = eval(input("Enter the point p2 of a triangle: ")) 4 | x3, y3 = eval(input("Enter the point p3 of a triangle: ")) 5 | 6 | import turtle 7 | turtle.showturtle() 8 | 9 | import math 10 | 11 | turtle.penup() 12 | turtle.goto(x1, y1) 13 | turtle.pendown() 14 | #turtle.write("p1(", x1, y1, ")") 15 | 16 | turtle.goto(x2, y2) 17 | #turtle.write(x2, y2) 18 | 19 | turtle.goto(x3, y3) 20 | #turtle.write("p1(", x3, y3, ")") 21 | 22 | turtle.goto(x1, y1) 23 | 24 | d1 = math.sqrt(math.pow(x1 - x2, 2) + math.pow(y1 - y2, 2)) 25 | d2 = math.sqrt(math.pow(x1 - x3, 2) + math.pow(y1 - y3, 2)) 26 | d3 = math.sqrt(math.pow(x2 - x3, 2) + math.pow(y2 - y3, 2)) 27 | 28 | s = (d1 + d2 + d3) / 3 29 | 30 | area = (s * ((s - d1) * (s - d2) * (s - d3))) ** (1 / 2) 31 | 32 | turtle.penup() 33 | turtle.goto(-25 + s, -60 + s) 34 | turtle.pendown() 35 | 36 | turtle.write("The area of the triangle is" + area) 37 | -------------------------------------------------------------------------------- /chapter3/3.18.py: -------------------------------------------------------------------------------- 1 | 2 | x1, y1 = eval(input("Enter the point p1 of a triangle: ")) 3 | x2, y2 = eval(input("Enter the point p2 of a triangle: ")) 4 | x3, y3 = eval(input("Enter the point p3 of a triangle: ")) 5 | 6 | import turtle 7 | turtle.showturtle() 8 | 9 | import math 10 | 11 | turtle.penup() 12 | turtle.goto(x1, y1) 13 | turtle.pendown() 14 | #turtle.write("p1(", x1, y1, ")") 15 | 16 | turtle.goto(x2, y2) 17 | #turtle.write(x2, y2) 18 | 19 | turtle.goto(x3, y3) 20 | turtle.write("p3(" ) 21 | 22 | turtle.goto(x1, y1) 23 | 24 | #d1 = math.sqrt(math.pow(x1 - x2, 2) + math.pow(y1 - y2, 2)) 25 | #d2 = math.sqrt(math.pow(x1 - x3, 2) + math.pow(y1 - y3, 2)) 26 | #d3 = math.sqrt(math.pow(x2 - x3, 2) + math.pow(y2 - y3, 2)) 27 | 28 | #s = (d1 + d2 + d3) / 3 29 | 30 | #area = (s * ((s - d1) * (s - d2) * (s - d3))) ** (1 / 2) 31 | 32 | #turtle.penup() 33 | #turtle.goto(-25 + s, -60 + s) 34 | #turtle.pendown() 35 | 36 | #turtle.write("The area of the triangle is" + area) 37 | -------------------------------------------------------------------------------- /chapter3/3.2.py: -------------------------------------------------------------------------------- 1 | import math 2 | x1, y1 = eval(input("Enter point 1 (latitude and longitude) in degrees: ")) 3 | x2, y2 = eval(input("Enter point 2 (latitude and longitude) in degrees: ")) 4 | radius = 6371.01 5 | 6 | d = ((radius * math.acos(math.sin(math.radians(x1))) * math.sin(math.radians(x2))) + (math.cos(math.radians(x1)) * math.cos(math.radians(x2)) * math.cos(math.radians(y1 - y2)))) 7 | print("The distance between the two points is", d) -------------------------------------------------------------------------------- /chapter3/3.4.py: -------------------------------------------------------------------------------- 1 | import math 2 | 3 | 4 | s = eval(input("Enter the side: ")) 5 | 6 | area = (5 * math.pow(s, 2)) / (4 * math.tan(math.pi / 5)) 7 | print("The area of the pentagon is", area) -------------------------------------------------------------------------------- /chapter3/3.5.py: -------------------------------------------------------------------------------- 1 | import math 2 | 3 | n = eval(input("Enter the number side: ")) 4 | s = eval(input("Enter the side: ")) 5 | 6 | area = (n * math.pow(s, 2)) / (4 * math.tan(math.pi / n)) 7 | print("The area of the polygon is", area) -------------------------------------------------------------------------------- /chapter3/3.6.py: -------------------------------------------------------------------------------- 1 | import math 2 | 3 | code = eval(input("Enter an ASCII coded: ")) 4 | #character = ord(code) 5 | #area = (n * math.pow(s, 2)) / (4 * math.tan(math.pi / n)) 6 | 7 | # Print the equivalent character of the given ASCII code 8 | print("The character is", chr(code)) 9 | -------------------------------------------------------------------------------- /chapter3/3.7.py: -------------------------------------------------------------------------------- 1 | import time 2 | currentTime = time.time() 3 | totalSeconds = int(currentTime) 4 | currentSecond = totalSeconds % 60 5 | 6 | print(chr(currentSecond)) -------------------------------------------------------------------------------- /chapter3/3.8.py: -------------------------------------------------------------------------------- 1 | # Receive the amount 2 | amount = eval(input("Enter an amount, for example, 11.56: ")) 3 | 4 | realAmount = (int(amount % 100) / 100)+ int(amount // 100) 5 | # Convert the amount to cents 6 | remainingAmount = int(realAmount * 100) 7 | 8 | # Find the number of one dollars 9 | numberOfOneDollars = remainingAmount // 100 10 | remainingAmount = remainingAmount % 100 11 | 12 | # Find the number of quarters in the remaining amount 13 | numberOfQuarters = remainingAmount // 25 14 | remainingAmount = remainingAmount % 25 15 | 16 | # Find the number of dimes in the remaining amount 17 | numberOfDimes = remainingAmount // 10 18 | remainingAmount = remainingAmount % 10 19 | 20 | # Find the number of nickels in the remaining amount 21 | numberOfNickels = remainingAmount // 5 22 | remainingAmount = remainingAmount % 5 23 | 24 | # Find the number of pennies in the remaining amount 25 | numberOfPennies = remainingAmount 26 | 27 | # Display the results 28 | print("Your amount", abs(amount), "consists of\n", 29 | "\t", abs(numberOfOneDollars), "dollars\n", 30 | "\t", abs(numberOfQuarters), "quarters\n", 31 | "\t", abs(numberOfDimes), "dimes\n", 32 | "\t", abs(numberOfNickels), "nickels\n", 33 | "\t", abs(numberOfPennies), "pennies") 34 | #print(realAmount) -------------------------------------------------------------------------------- /chapter3/3.9.py: -------------------------------------------------------------------------------- 1 | name = input("Enter employee's name: ") 2 | hours = eval(input("Enter number of hours worked: ")) 3 | payRate = eval(input("Enter the hourly pay rate: ")) 4 | fedWithholdRate = eval(input('Enter federal tax withholding rate: ')) 5 | stateWithholdRate = eval(input('Enter state tax withholding rate: ')) 6 | 7 | print("Employee name:", name, '\n' 8 | "Hours Worked:", hours, '\n' 9 | "Pay Rate: $",payRate, "\n" 10 | "Gross Pay: $",hours * payRate, "\n" 11 | 'Deductions:\n' 12 | "\t Federal Withholding (20.0%): $",(fedWithholdRate) * (hours * payRate), '\n' 13 | "\t State Withholding (9.0%): $", stateWithholdRate * (hours * payRate), '\n' 14 | "\t Total Deduction: $",((fedWithholdRate) * (hours * payRate)) + (stateWithholdRate * (hours * payRate)), '\n' 15 | "Net pay: $",(hours * payRate) - (((fedWithholdRate) * (hours * payRate)) + (stateWithholdRate * (hours * payRate)))) -------------------------------------------------------------------------------- /chapter4/4.1.py: -------------------------------------------------------------------------------- 1 | import math 2 | 3 | a, b, c =eval(input("Enter a, b, and c the coefficients of a quadratic equation: ")) 4 | 5 | discriminant = math.pow(b, 2) - (4 * a * c) 6 | 7 | #r1 = (-b + math.sqrt(discriminant)) / (2 * a) 8 | #r2 = (-b - math.sqrt(discriminant)) / (2 * a) 9 | 10 | if discriminant == 0: 11 | 12 | r1 = (-b + math.sqrt(discriminant)) / (2 * a) 13 | r2 = (-b - math.sqrt(discriminant)) / (2 * a) 14 | r1 = r2 15 | 16 | print ("The root of the equation is", r1) 17 | 18 | elif discriminant > 0: 19 | 20 | r1 = (-b + math.sqrt(discriminant)) / (2 * a) 21 | r2 = (-b - math.sqrt(discriminant)) / (2 * a) 22 | 23 | print("The roots of the equation are", r1, "and", r2) 24 | 25 | else: 26 | 27 | print("The equation has no real roots") 28 | 29 | -------------------------------------------------------------------------------- /chapter4/4.10.py: -------------------------------------------------------------------------------- 1 | import random 2 | 3 | # 1. Generate two random single-digit integers 4 | number1 = random.randint(0, 99) 5 | number2 = random.randint(0, 99) 6 | 7 | '''if number1 < number2: 8 | number1, number2 = number2, number1 # Simultaneous assignment 9 | # 3. Prompt the student to answer "What is number1 - number2?"''' 10 | answer = eval(input("What is "+ str(number1) + " * " + str(number2) + "? ")) 11 | # 4. Check the answer and display the result 12 | 13 | if number1 * number2 == answer: 14 | print("You are correct!") 15 | 16 | else: 17 | print("Your answer is wrong.\n", number1, '-', number2, "is", number1 - number2, '.') 18 | -------------------------------------------------------------------------------- /chapter4/4.11.py: -------------------------------------------------------------------------------- 1 | actualYear = eval(input("Enter the actual year: ")) 2 | month, year = eval(input("Enter the numerical equivalent of a month and it's year: ")) 3 | 4 | January = 'January' 5 | February = 'February' 6 | March = 'March' 7 | April = 'April' 8 | May = 'May' 9 | June = 'June' 10 | July = 'July' 11 | August = 'August' 12 | September = 'September' 13 | October = 'October' 14 | November = 'November' 15 | December = 'December' 16 | 17 | #Check for leap year 18 | leapYear = year % 4 19 | 20 | if month == 1: 21 | month = January 22 | monthdays = 31 23 | elif month == 3: 24 | monthdays = 31 25 | month = March 26 | elif month == 4: 27 | monthdays = 30 28 | month = April 29 | elif month == 5: 30 | monthdays = 31 31 | month = May 32 | elif month == 6: 33 | monthdays = 30 34 | month = June 35 | elif month == 7: 36 | monthdays = 31 37 | month = July 38 | elif month == 8: 39 | monthdays = 31 40 | month = August 41 | elif month == 9: 42 | monthdays = 31 43 | month = September 44 | elif month == 10: 45 | monthdays = 31 46 | month = October 47 | elif month == 11: 48 | monthdays = 30 49 | month = November 50 | elif month == 12: 51 | monthdays = 31 52 | month = December 53 | 54 | if year == actualYear: 55 | if leapYear != 0: 56 | if month == 2: 57 | monthdays = 28 58 | month = February 59 | print(month, year, "has", monthdays, "days") 60 | 61 | else: 62 | if month == 2: 63 | month = February 64 | monthdays = 29 65 | print(month, year, "has", monthdays, "days") 66 | 67 | elif year > actualYear: 68 | if leapYear != 0: 69 | if month == 2: 70 | monthdays = 28 71 | month = February 72 | print(month, year, "will have", monthdays, "days") 73 | 74 | else: 75 | if month == 2: 76 | month = February 77 | monthdays = 29 78 | print(month, year, "will have", monthdays, "days") 79 | 80 | else: 81 | 82 | if leapYear != 0: 83 | if month == 2: 84 | monthdays = 28 85 | month = February 86 | print(month, year, "had", monthdays, "days") 87 | 88 | else: 89 | if month == 2: 90 | month = February 91 | monthdays = 29 92 | print(month, year, "had", monthdays, "days") 93 | 94 | -------------------------------------------------------------------------------- /chapter4/4.12.py: -------------------------------------------------------------------------------- 1 | integer = eval(input("Enter an integer: ")) 2 | 3 | mod5 = integer % 5 4 | mod6 = integer % 6 5 | 6 | ##if mod5 == 0 and mod6 == 0: 7 | print("Is", str(integer), "divisible by 5 and 6?", (mod5 == 0) and (mod6 == 0)) 8 | 9 | ##if mod5 == 0 or mod6 == 0: 10 | print("Is", str(integer), "divisible by 5 or 6?", (mod5 == 0) or (mod6 == 0)) 11 | 12 | ##if (mod5 == 0 or mod6 == 0) != (mod5 and mod6): 13 | print("Is", str(integer), "divisible by 5 or 6?", ((mod5 == 0) or (mod6 == 0)) != ((mod5 == 0) and (mod6 == 0))) 14 | -------------------------------------------------------------------------------- /chapter4/4.13.py: -------------------------------------------------------------------------------- 1 | import sys 2 | 2 3 | 3 4 | # Prompt the user to enter filing status 5 | 6 | status = eval(input( 7 | "(0-single filer, 1-married jointly,\n" + 8 | "2-married separately, 3-head of household)\n" + 9 | "Enter the filing status: ")) 10 | 11 | # Prompt the user to enter taxable income 12 | income = eval(input("Enter the taxable income: ")) 13 | 14 | # Compute tax 15 | tax = 0 16 | 17 | if status == 0: # Compute tax for single filers 18 | 19 | if income <= 8350: 20 | tax = income * 0.10 21 | elif income <= 33950: 22 | tax = 8350 * 0.10 + (income - 8350) * 0.15 23 | elif income <= 82250: 24 | tax = 8350 * 0.10 + (33950 - 8350) * 0.15 + \ 25 | (income - 33950) * 0.25 26 | elif income <= 171550: 27 | tax = 8350 * 0.10 + (33950 - 8350) * 0.15 + \ 28 | (82250 - 33950) * 0.25 + (income - 82250) * 0.28 29 | 30 | elif income <= 372950: 31 | tax = 8350 * 0.10 + (33950 - 8350) * 0.15 + \ 32 | (82250 - 33950) * 0.25 + (171550 - 82250) * 0.28 + \ 33 | (income - 171550) * 0.33 34 | else: 35 | tax = 8350 * 0.10 + (33950 - 8350) * 0.15 + \ 36 | (82250 - 33950) * 0.25 + (171550 - 82250) * 0.28 + \ 37 | (372950 - 171550) * 0.33 + (income - 372950) * 0.35; 38 | 39 | elif status == 1: # Compute tax for married file jointly 40 | print("Left as exercise") 41 | 42 | elif status == 2: # Compute tax for married separately 43 | print("Left as exercise") 44 | 45 | elif status == 3: # Compute tax for head of household 46 | print("Left as exercise") 47 | 48 | else: 49 | print("Error: invalid status") 50 | sys.exit() 51 | 52 | 53 | # Display the result 54 | 55 | print("Tax is", format(tax, ".2f")) 56 | -------------------------------------------------------------------------------- /chapter4/4.14.py: -------------------------------------------------------------------------------- 1 | import random 2 | x = random.randint(0, 1) 3 | 4 | guess = eval(input("Enter \"1\" for a \"HEAD\" and \"0\" for a \"TAIL\": ")) 5 | if guess == x: 6 | print("Correct, right pick") 7 | else: 8 | print("Oops, wrong") 9 | -------------------------------------------------------------------------------- /chapter4/4.15.py: -------------------------------------------------------------------------------- 1 | import random 2 | 3 | # Generate a lottery number 4 | lottery = random.randint(0, 999) 5 | 6 | # Prompt the user to enter a guess 7 | guess = eval(input("Enter your lottery pick (three digits): ")) 8 | 9 | # Get digits from lottery 10 | lotteryDigit1 = lottery // 100 11 | remainingDigits = lottery % 100 12 | lotteryDigit2 = remainingDigits // 10 13 | lotteryDigit3 = remainingDigits % 10 14 | 15 | # Get digits from guess 16 | guessDigit1 = guess // 100 17 | remainingGuessDigits = guess % 100 18 | guessDigit2 = remainingGuessDigits // 10 19 | guessDigit3 = remainingGuessDigits % 10 20 | print("The lottery number is", lottery) 21 | 22 | # Check the guess 23 | if guess == lottery: 24 | print("Exact match: you win $10,000") 25 | elif ((guessDigit1 == lotteryDigit1 26 | or guessDigit1 == lotteryDigit2 27 | or guessDigit1 == lotteryDigit2) 28 | and (guessDigit2 == lotteryDigit1 29 | or guessDigit2 == lotteryDigit2 30 | or guessDigit2 == lotteryDigit3) 31 | and(guessDigit3 == lotteryDigit1 32 | or guessDigit3 == lotteryDigit2 33 | or guessDigit3 == lotteryDigit3)): 34 | print("Match all digits: you win $3,000") 35 | elif (guessDigit1 == lotteryDigit1 36 | or guessDigit1 == lotteryDigit2 37 | or guessDigit1 == lotteryDigit3 38 | or guessDigit2 == lotteryDigit1 39 | or guessDigit2 == lotteryDigit2 40 | or guessDigit2 == lotteryDigit3 41 | or guessDigit2 == lotteryDigit1 42 | or guessDigit2 == lotteryDigit2 43 | or guessDigit2 == lotteryDigit3): 44 | print("Match one digit: you win $1,000") 45 | else: 46 | print("Sorry, no match") 47 | -------------------------------------------------------------------------------- /chapter4/4.16.py: -------------------------------------------------------------------------------- 1 | import random 2 | 3 | # Generate a number 4 | num = random.randint(1, 24) 5 | 6 | a, b, c, d, e, f, g, h, i, j = 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J' 7 | k, l, m, n, o, p, q, r, s, t = 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T' 8 | u, v, w, x, y, z = 'U', 'V', 'W', 'X', 'Y', 'Z' 9 | 10 | if num == 1: 11 | num = a 12 | elif num == 2: 13 | num = b 14 | elif num == 3: 15 | num = c 16 | elif num == 4: 17 | num = d 18 | elif num == 5: 19 | num = e 20 | elif num == 6: 21 | num = f 22 | elif num == 7: 23 | num = g 24 | elif num == 8: 25 | num = h 26 | elif num == 9: 27 | num = i 28 | elif num == 10: 29 | num = j 30 | elif num == 11: 31 | num = k 32 | elif num == 12: 33 | num = l 34 | elif num == 13: 35 | num = m 36 | elif num == 14: 37 | num = n 38 | elif num == 15: 39 | num = o 40 | elif num == 16: 41 | num = p 42 | elif num == 17: 43 | num = q 44 | elif num == 18: 45 | num = r 46 | elif num == 19: 47 | num = s 48 | elif num == 20: 49 | num = t 50 | elif num == 21: 51 | num = u 52 | elif num == 22: 53 | num = v 54 | elif num == 23: 55 | num = w 56 | elif num == 24: 57 | num = x 58 | elif num == 25: 59 | num = y 60 | elif num == 26: 61 | num = z 62 | 63 | print(num) 64 | -------------------------------------------------------------------------------- /chapter4/4.17.py: -------------------------------------------------------------------------------- 1 | import random 2 | 3 | # Generate a number 4 | num = random.randint(0, 2) 5 | scissor, rock, paper = 'scissor', 'rock', 'paper' 6 | player = eval(input("scissor (0), rock (1), paper (2): ")) 7 | if num == 0: 8 | num = scissor 9 | elif num == 1: 10 | num = rock 11 | elif num == 2: 12 | num = paper 13 | 14 | if player == 0: 15 | player = scissor 16 | elif player == 1: 17 | player = rock 18 | elif player == 2: 19 | player = paper 20 | 21 | if player == num: 22 | player = num 23 | print("The computer is " + 24 | str(num) + ". You are " + 25 | str(player) + 26 | " too. It is a draw") 27 | elif player == 0 and num == 1: 28 | print("The computer is " + 29 | str(num) + ". You are " + 30 | str(player) + 31 | ". You lose.") 32 | elif player == 0 and num == 2: 33 | print("The computer is " + 34 | str(num) + ". You are " + 35 | str(player) + 36 | ". You win.") 37 | elif player == 1 and num == 2: 38 | print("The computer is " + 39 | str(num) + ". You are " + 40 | str(player) + 41 | ". You lose.") 42 | elif player == 1 and num == 0: 43 | print("The computer is " + 44 | str(num) + ". You are " + 45 | str(player) + 46 | ". You win.") 47 | elif player == 2 and num == 0: 48 | print("The computer is " + 49 | str(num) + ". You are " + 50 | str(player) + 51 | ". You lose.") 52 | elif player == 2 and num == 1: 53 | print("The computer is " + 54 | str(num) + ". You are " + 55 | str(player) + 56 | ". You win.") 57 | 58 | 59 | 60 | 61 | 62 | -------------------------------------------------------------------------------- /chapter4/4.18.py: -------------------------------------------------------------------------------- 1 | conversion = eval(input("Enter \"0\" to convert dollars to RMB and \"1\" vice versa: ")) 2 | exchange_rate = eval(input("Enter the exchange rate from dollars to RMB: ")) 3 | 4 | 5 | if conversion == 0: 6 | USD = eval(input("Enter the dollar amount: ")) 7 | RMB = exchange_rate * USD 8 | print(USD, "is", RMB) 9 | elif conversion == 1: 10 | RMB = eval(input("Enter the Chinese Renminbi amount: ")) 11 | USD = RMB / exchange_rate 12 | print(RMB, "is", USD) 13 | -------------------------------------------------------------------------------- /chapter4/4.19.py: -------------------------------------------------------------------------------- 1 | e1, e2, e3 = eval(input("Enter three edges of a triangle: ")) 2 | 3 | if (e1 + e2 > e3) and (e1 + e3 > e2) and (e3 + e2 > e1): 4 | print("The perimeter is", (e1 + e2 + e3)) 5 | 6 | else : 7 | print("THe input is invalid") 8 | -------------------------------------------------------------------------------- /chapter4/4.2.py: -------------------------------------------------------------------------------- 1 | import random 2 | number1 = random.randint(0, 9) 3 | number2 = random.randint(0, 9) 4 | number3 = random.randint(0, 9) 5 | 6 | answer = eval(input("What is the sum of " + str(number1) + " and " + str(number2) + " and " + str(number3) + " is: ")) 7 | 8 | print("The sum", number1, "+", number2, "+", number3, "=", answer, "is", number1 + number2 + number3 == answer) 9 | -------------------------------------------------------------------------------- /chapter4/4.20.py: -------------------------------------------------------------------------------- 1 | ta = eval(input("Enter the temperature in Fahrenheit between -58 and 41 : ")) 2 | v = eval(input("Enter the wind speed in miles per hour : ")) 3 | 4 | if v >= 2 and (ta > -58 and ta < 41): 5 | 6 | twc = 35.74 + (0.6215 * ta) - (35.75 * (v ** 0.16)) + (0.4275 * ta * (v ** 0.16)) 7 | print("The wind chill is", twc) 8 | 9 | elif v < 2 and (ta < -58 or ta > 41): 10 | 11 | print("Sorry but the wind speed is too small to be evaluated and your temperature is out of range") 12 | 13 | elif v < 2: 14 | print("Sorry but the wind speed is too small") 15 | 16 | elif (ta < -58 or ta > 41): 17 | print("Sorry but the temperature is out of range") 18 | -------------------------------------------------------------------------------- /chapter4/4.21.py: -------------------------------------------------------------------------------- 1 | year = eval(input("Enter year: ")) 2 | m = eval(input("Enter month 1-12: ")) 3 | q = eval(input("Enter the day of the month 1-31: ")) 4 | 5 | Monday = 'Monday' 6 | Tuesday = 'Tuesday' 7 | Wednesday = 'Wednesday' 8 | Thursday = 'Thursday' 9 | Friday = 'Friday' 10 | Saturday = 'Saturday' 11 | Sunday = 'Sunday' 12 | 13 | #futureDay = today + elapsedDays 14 | 15 | k = year % 100 16 | j = year / 100 17 | 18 | h = (q + (((26 * (m + 1))) / 10) 19 | + k + (k // 4) 20 | + (j // 4) 21 | + (5 * j)) % 7 22 | h = round(h) 23 | if h == 1: 24 | h = Monday 25 | elif h == 2: 26 | h = Tuesday 27 | elif h == 3: 28 | h = Wednesday 29 | elif h == 4: 30 | h = Thursday 31 | elif h == 5: 32 | h = Friday 33 | elif h == 6: 34 | h = Saturday 35 | elif h == 0: 36 | h = Sunday 37 | 38 | 39 | print(h) 40 | -------------------------------------------------------------------------------- /chapter4/4.22.py: -------------------------------------------------------------------------------- 1 | import math 2 | x, y = eval(input("Enter a point with two coordinates: ")) 3 | 4 | d = math.sqrt(math.pow(x, 2) + math.pow(y, 2)) 5 | 6 | if d > 10: 7 | print("The point(" + str(format(x, "0.1f")) + ", " + str(format(y, "0.1f")) + ") is out of the circle") 8 | 9 | elif d <= 10: 10 | print("The point(" + str(format(x, "0.1f")) + ", " + str(format(y, "0.1f")) + ") is in the circle") 11 | -------------------------------------------------------------------------------- /chapter4/4.23.py: -------------------------------------------------------------------------------- 1 | x, y = eval(input("Enter a point with two coordinates: ")) 2 | 3 | if (x > 10 / 2) or (y > 5 / 2): 4 | print("The point(" + str(x) + ", " + str(y) + ") is out of the rectangle") 5 | 6 | elif (x <= 10 / 2) or (y <= 5 / 2): 7 | print("The point(" + str(x) + ", " + str(y) + ") is in the rectangle") 8 | -------------------------------------------------------------------------------- /chapter4/4.24.py: -------------------------------------------------------------------------------- 1 | import random 2 | card = random.randint(1, 4) 3 | rank = random.randint(1, 11) 4 | 5 | ##pick = eval(input("Enter a random number: ")) 6 | ## 7 | ##pick = card 8 | 9 | Ace = 'Ace' 10 | Jack = 'Jack' 11 | Queen = 'Queen' 12 | King = 'King' 13 | clubs = 'Clubs' 14 | Diamonds = 'Diamonds' 15 | Hearts = 'Hearts' 16 | Spades = 'Spades' 17 | 18 | if rank == 1: 19 | rank = Ace 20 | elif rank == 2: 21 | rank = 2 22 | elif rank == 3: 23 | rank = 3 24 | elif rank == 4: 25 | rank = 4 26 | elif rank == 5: 27 | rank = 5 28 | elif rank == 6: 29 | rank = 6 30 | elif rank == 7: 31 | rank = 7 32 | elif rank == 8: 33 | rank = 8 34 | elif rank == 9: 35 | rank = 9 36 | elif rank == 10: 37 | rank = 10 38 | elif rank == 11: 39 | rank = Jack 40 | elif rank == 12: 41 | rank = King 42 | elif rank == 13: 43 | rank = Queen 44 | 45 | if card == 1: 46 | card = Clubs 47 | elif card == 2: 48 | card = Diamonds 49 | elif card == 3: 50 | card = Hearts 51 | elif card == 4: 52 | card = Spades 53 | 54 | print("The card you picked is the", rank, "of", card) 55 | -------------------------------------------------------------------------------- /chapter4/4.25.py: -------------------------------------------------------------------------------- 1 | x1, y1, x2, y2, x3, y3, x4, y4 = eval(input("Enter the points x1, y1, x2, y2, x3, y3, x4, y4: ")) 2 | 3 | a, b, e = (y1 - y2), (x1 - x2), ((y1 - y2) * x1) - ((x1 - x2) * y1) 4 | c, d, f = (y3 - y4), (x3 - x4), ((y3 - y4) * x3) - ((x3 - x4) * y3) 5 | 6 | ##ax - by = c 7 | ##dx - ey = f 8 | 9 | D = ((a * -d) - (-b * c)) 10 | 11 | if D == 0: 12 | 13 | print("The two line are parallel") 14 | exit() 15 | 16 | x = ((e * -d) - (-b * f)) / D 17 | y = ((a * f) - (e * c)) / D 18 | 19 | print("The point of intersection is at (" + str(format(x, "0.5f")) + ", " + str(format(y, "0.5f")) + ")") 20 | 21 | exit() 22 | -------------------------------------------------------------------------------- /chapter4/4.26.py: -------------------------------------------------------------------------------- 1 | a, b, c = eval(input("Enter 3 positive integers: ")) 2 | 3 | if a == c: 4 | print(str(a) + str(b) + str(c) + " is a palindrome") 5 | else: 6 | print(str(a) + str(b) + str(c) + " is not a palindrome") 7 | -------------------------------------------------------------------------------- /chapter4/4.27.py: -------------------------------------------------------------------------------- 1 | x1, y1, x2, y2, x3, y3, x4, y4 = eval(input("Enter the points x1, y1, x2, y2, x3, y3, x4, y4: ")) 2 | 3 | a, b, e = (y1 - y2), (x1 - x2), ((y1 - y2) * x1) - ((x1 - x2) * y1) 4 | c, d, f = (y3 - y4), (x3 - x4), ((y3 - y4) * x3) - ((x3 - x4) * y3) 5 | 6 | ##ax - by = c 7 | ##dx - ey = f 8 | 9 | D = ((a * -d) - (-b * c)) 10 | 11 | if D == 0: 12 | 13 | print("The equation has no solution") 14 | exit() 15 | 16 | x = ((e * -d) - (-b * f)) / D 17 | y = ((a * f) - (e * c)) / D 18 | 19 | print("The point of intersection is at (" + str(format(x, "0.5f")) + ", " + str(format(y, "0.5f")) + ")") 20 | 21 | -------------------------------------------------------------------------------- /chapter4/4.28.py: -------------------------------------------------------------------------------- 1 | x1, y1, w1, h1 = eval(input("Enter r1's center x-, y-coordinate, width, and height: ")) 2 | x2, y2, w2, h2 = eval(input("Enter r2's center x-, y-coordinate, width, and height: ")) 3 | 4 | x = w1 - w2 5 | x = abs(x) 6 | y = h1 - h2 7 | y = abs(y) 8 | 9 | a1 = (w1 / 2) + abs(x1) 10 | a2 = (w2 / 2) + abs(x2) 11 | b1 = (h1 / 2) + abs(y1) 12 | b2 = (h2 / 2) + abs(y2) 13 | 14 | area1 = w1 * h1 15 | area2 = w2 * h2 16 | 17 | if (x1 and x2) >= 0: 18 | if abs(area1) > abs(area2): 19 | if (abs(a1) > abs(a2)) and (abs(b1) > abs(b2)): 20 | print("r2 is inside r1") 21 | 22 | elif area1 < area2: 23 | if abs(x2 - w2) > w1: 24 | if abs(y2 - h2) > h1: 25 | print("r1 is inside r2") 26 | elif abs(x2 - w2) < w1: 27 | if abs(y2 - h2) > h1: 28 | print("r1 overlaps on r2") 29 | elif abs(x2 - w2) > w1: 30 | if abs(y2 - h2) < h1: 31 | print("r1 overlaps on r2") 32 | elif abs(x2 - w2) < w1: 33 | if abs(y2 - h2) > h1: 34 | print("r1 overlaps on r2") 35 | -------------------------------------------------------------------------------- /chapter4/4.3.py: -------------------------------------------------------------------------------- 1 | a, b, c, d, e, f = eval(input("Enter values for a, b, c, d, e, f: ")) 2 | 3 | D = ((a * d) - (b * c)) 4 | 5 | if D == 0: 6 | 7 | print("The equation has no solution") 8 | exit() 9 | 10 | x = ((e * d) - (b * f)) / D 11 | y = ((a * f) - (e * c)) / D 12 | 13 | print("The solution to the equation is X =", x, "Y =", y) 14 | 15 | -------------------------------------------------------------------------------- /chapter4/4.30.py: -------------------------------------------------------------------------------- 1 | GMT_offset = eval(input("Enter the time zone offset to GMT : ")) 2 | 3 | import time 4 | currentTime = time.time() 5 | 6 | totalSeconds = int(currentTime) 7 | currentSecond = totalSeconds % 60 8 | 9 | totalMinutes = totalSeconds // 60 10 | currentMinute = totalMinutes % 60 11 | 12 | totalHours = totalMinutes // 60 13 | currentHour = (totalHours % 24) + GMT_offset 14 | currentHour = currentHour - 12 15 | 16 | print("Current time is", currentHour, ":", currentMinute, ":", currentSecond, "GMT") 17 | -------------------------------------------------------------------------------- /chapter4/4.31.py: -------------------------------------------------------------------------------- 1 | x0, y0, x1, y1, x2, y2 = eval(input("Enter the x and Y coordinates of the points p0, p1 and p2 respectively: ")) 2 | 3 | a = (x1 - x0) * (y2 - y0) 4 | b = (x2 - x0) * (y1 - y0) 5 | 6 | if (a - b) > 0: 7 | print("p2 is on the left side of the line") 8 | elif (a - b) < 0: 9 | print("p2 is on the right side of the line") 10 | elif (a - b) == 0: 11 | print("p2 is on thesame line from p0 to p1") 12 | -------------------------------------------------------------------------------- /chapter4/4.32.py: -------------------------------------------------------------------------------- 1 | x0, y0, x1, y1, x2, y2 = eval(input("Enter the x and Y coordinates of the points p0, p1 and p2 respectively: ")) 2 | 3 | a = (x1 - x0) * (y2 - y0) 4 | b = (x2 - x0) * (y1 - y0) 5 | 6 | if (a - b) == 0: 7 | print("(" 8 | + str(format(x2, ".1f")) 9 | + "," 10 | + str(format(y2, ".1f")) 11 | + ")is on the same line segment from (" 12 | + str(format(x0, ".1f")) 13 | + "," 14 | + str(format(y0, ".1f")) 15 | + ") to (" 16 | + str(format(x1, ".1f")) 17 | + "," 18 | + str(format(y1, ".1f")) 19 | +")") 20 | else: 21 | print("(" 22 | + str(format(x2, ".1f")) 23 | + "," 24 | + str(format(y2, ".1f")) 25 | + ")is not on the same line segment from (" 26 | + str(format(x0, ".1f")) 27 | + "," 28 | + str(format(y0, ".1f")) 29 | + ") to (" 30 | + str(format(x1, ".1f")) 31 | + "," 32 | + str(format(y1, ".1f")) 33 | + ")") 34 | -------------------------------------------------------------------------------- /chapter4/4.33.py: -------------------------------------------------------------------------------- 1 | decimal_number = eval(input("Enter a decimal value: ")) 2 | print("The hex value is", str(format(decimal_number, "X"))) 3 | -------------------------------------------------------------------------------- /chapter4/4.34.py: -------------------------------------------------------------------------------- 1 | hex_number = eval(input("Enter a hexadecimal value: ")) 2 | 3 | if hex_number == str: 4 | if hex_number == 'A' or 'a': 5 | print("hex_number = 10") 6 | elif hex_number == 'B' or' b': 7 | print("hex_number = 11") 8 | elif hex_number == 'C' or 'c': 9 | print("hex_number = 12") 10 | elif hex_number == 'D' or 'd': 11 | print("hex_number = 13") 12 | elif hex_number == 'E' or 'e': 13 | print("hex_number = 14") 14 | elif hex_number == 'F' or 'f': 15 | print("hex_number = 15") 16 | else: 17 | print("Invalid input") 18 | 19 | else: 20 | print("The hex number is ", hex_number) 21 | -------------------------------------------------------------------------------- /chapter4/4.4.py: -------------------------------------------------------------------------------- 1 | import random 2 | 3 | number1, number2 = random.randint(0, 99), random.randint(0, 99) 4 | answer = eval(input("What is the sum of " + str(number1) + " and " + str(number2) + " : ")) 5 | 6 | 7 | print("The sum", number1, "+", number2, "=", answer, "is", number1 + number2 == answer) 8 | -------------------------------------------------------------------------------- /chapter4/4.5.py: -------------------------------------------------------------------------------- 1 | today = eval(input("Enter today's day: ")) 2 | elapsedDays = eval(input("Enter the number of days elapsed since today: ")) 3 | 4 | Monday = 'Monday' 5 | Tuesday = 'Tuesday' 6 | Wednesday = 'Wednesday' 7 | Thursday = 'Thursday' 8 | Friday = 'Friday' 9 | Saturday = 'Saturday' 10 | Sunday = 'Sunday' 11 | 12 | 13 | futureDay = today + elapsedDays 14 | 15 | if today == 1: 16 | today = Monday 17 | elif today == 2: 18 | today = Tuesday 19 | elif today == 3: 20 | today = Wednesday 21 | elif today == 4: 22 | today = Thursday 23 | elif today == 5: 24 | today = Friday 25 | elif today == 6: 26 | today = Saturday 27 | elif today == 0: 28 | today = Sunday 29 | 30 | futureday = futureDay % 7 31 | 32 | if futureday == 1: 33 | futureDay = Monday 34 | elif futureday == 2: 35 | futureDay = Tuesday 36 | elif futureday == 3: 37 | futureDay = WWednesday 38 | elif futureday == 4: 39 | futureDay = Thursday 40 | elif futureday == 5: 41 | futureDay = Friday 42 | elif futureday == 6: 43 | futureDay = Saturday 44 | elif futureday == 0: 45 | futureDay = Sunday 46 | 47 | print("Today is", today, "and the future day is", futureDay) 48 | -------------------------------------------------------------------------------- /chapter4/4.6.py: -------------------------------------------------------------------------------- 1 | weight = eval(input("Enter the weight in pounds: ")) 2 | feet = eval(input("Enter height in feet: ")) 3 | inches = eval(input("Enter height in inches: ")) 4 | 5 | KILOGRAMS_PER_POUND = 0.45359237 6 | METERS_PER_INCH = 0.0254 7 | height = inches 8 | 9 | # Compute BMI 10 | weightInKilograms = weight * KILOGRAMS_PER_POUND 11 | heightInMeters = height * METERS_PER_INCH 12 | 13 | BMI = weightInKilograms / (heightInMeters * heightInMeters) 14 | 15 | print("BMI is", format(BMI, ".2f")) 16 | 17 | if BMI < 18.5: 18 | print("Underweight") 19 | elif BMI < 25: 20 | print("Normal") 21 | elif BMI < 30: 22 | print("Overweight") 23 | else: 24 | print("Obese") 25 | 26 | -------------------------------------------------------------------------------- /chapter4/4.7.py: -------------------------------------------------------------------------------- 1 | # Receive the amount 2 | amount = eval(input("Enter an amount, for example, 11.56: ")) 3 | # Convert the amount to cents 4 | remainingAmount = int(amount * 100) 5 | # Find the number of one dollars 6 | numberOfOneDollars = remainingAmount // 100 7 | remainingAmount = remainingAmount % 100 8 | # Find the number of quarters in the remaining amount 9 | numberOfQuarters = remainingAmount // 25 10 | remainingAmount = remainingAmount % 25 11 | # Find the number of dimes in the remaining amount 12 | numberOfDimes = remainingAmount // 10 13 | remainingAmount = remainingAmount % 10 14 | # Find the number of nickels in the remaining amount 15 | numberOfNickels = remainingAmount // 5 16 | remainingAmount = remainingAmount % 5 17 | # Find the number of pennies in the remaining amount 18 | numberOfPennies = remainingAmount 19 | #Display the results 20 | if numberOfOneDollars <= 1: 21 | print("Your amount", amount, "consists of", numberOfOneDollars, "dollar") 22 | else: 23 | print("Your amount", amount, "consists of", numberOfOneDollars, "dollars") 24 | 25 | if numberOfQuarters <= 1: 26 | print("Your amount", amount, "consists of", numberOfQuarters, "quarter") 27 | else: 28 | print("Your amount", amount, "consists of", numberOfQuarters, "quarters") 29 | 30 | if numberOfDimes <= 1: 31 | print("Your amount", amount, "consists of", numberOfDimes, "dime") 32 | else: 33 | print("Your amount", amount, "consists of", numberOfDimes, "dimes") 34 | 35 | if numberOfNickels <= 1: 36 | print("Your amount", amount, "consists of", numberOfNickels, "nickel") 37 | else: 38 | print("Your amount", amount, "consists of", numberOfNickels, "nickels") 39 | 40 | if numberOfPennies <= 1: 41 | print("Your amount", amount, "consists of", numberOfPennies, "penny") 42 | else: 43 | print("Your amount", amount, "consists of", numberOfPennies, "pennies") 44 | '''print("Your amount", amount, "consists of\n", 45 | "\t", numberOfOneDollars, "dollars\n", 46 | "\t", numberOfQuarters, "quarters\n", 47 | "\t", numberOfDimes, "dimes\n", 48 | "\t", numberOfNickels, "nickels\n", 49 | "\t", numberOfPennies, "pennies") 50 | ''' 51 | -------------------------------------------------------------------------------- /chapter4/4.8.py: -------------------------------------------------------------------------------- 1 | num1, num2, num3 = eval(input("Enter three integers: ")) 2 | 3 | if num1 < num2 and num2 < num3: 4 | print(str(num1) + "\n" + str(num2) + "\n" + str(num3)) 5 | elif num2 < num1 and num1 < num3: 6 | print(str(num2) + "\n" + str(num1) + "\n" + str(num3)) 7 | 8 | elif num3 < num1 and num1 < num2: 9 | print(str(num3) + "\n" + str(num1) + "\n" + str(num2)) 10 | elif num1 < num3 and num3 < num2: 11 | print(str(num1) + "\n" + str(num3) + "\n" + str(num2)) 12 | 13 | elif num3 < num2 and num2 < num1: 14 | print(str(num3) + "\n" + str(num2) + "\n" + str(num1)) 15 | elif num2 < num3 and num3 < num1: 16 | print(str(num2) + "\n" + str(num3) + "\n" + str(num1)) 17 | -------------------------------------------------------------------------------- /chapter4/4.9.py: -------------------------------------------------------------------------------- 1 | w1, p1 = eval(input("Enter the weight and price for package 1: ")) 2 | w2, p2 = eval(input("Enter the weight and price for package 2: ")) 3 | 4 | pricePerKilo1 = p1 / w1 5 | pricePerKilo2 = p2 / w2 6 | 7 | print(pricePerKilo1) 8 | print(pricePerKilo2) 9 | 10 | if pricePerKilo1 < pricePerKilo2: 11 | print("Package 2 has a better price") 12 | else: 13 | print("Package 1 has a better price") 14 | -------------------------------------------------------------------------------- /chapter4/output.txt: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /chapter5/5.1.py: -------------------------------------------------------------------------------- 1 | number = eval(input("Enter an integer," 2 | + "the input ends if it is 0: ")) 3 | counter = 1 4 | total = 0 5 | positive_numbers = 0 6 | negative_numbers = 0 7 | 8 | while number != 0: 9 | if number < 0: 10 | negative_numbers += 1 11 | elif number > 0: 12 | positive_numbers += 1 13 | counter += 1 14 | total = abs(number) + total 15 | number = eval(input("Enter an integer," 16 | + "the input ends if it is 0: ")) 17 | if number != 0: 18 | average = total / counter 19 | print("The number of positives is " 20 | + str(positive_numbers)) 21 | print("The number of negatives is " 22 | + str(negative_numbers)) 23 | print("The total is", str(total)) 24 | print("The average is", str(format(average, "0.2f"))) 25 | else: 26 | print("You did not enter any value") 27 | -------------------------------------------------------------------------------- /chapter5/5.10.py: -------------------------------------------------------------------------------- 1 | numberOfStudents = eval(input("Enter the number of students: ")) 2 | numberOfScores = 0 3 | scores = [] 4 | 5 | while numberOfScores < numberOfStudents: 6 | score = eval(input("\nEnter the student scores: ")) 7 | scores.append(score) 8 | numberOfScores += 1 9 | print("\nThe maximum score is " + str(max(scores))) 10 | 11 | -------------------------------------------------------------------------------- /chapter5/5.10Input.txt: -------------------------------------------------------------------------------- 1 | 5 2 | 2 3 | 3 4 | 7 5 | 45 6 | 423 -------------------------------------------------------------------------------- /chapter5/5.10output.txt: -------------------------------------------------------------------------------- 1 | Enter the number of students: Enter the student scores: Enter the student scores: Enter the student scores: Enter the student scores: Enter the student scores: The maximum score is 423 2 | -------------------------------------------------------------------------------- /chapter5/5.11.py: -------------------------------------------------------------------------------- 1 | numberOfStudents = eval(input("Enter the number of students: ")) 2 | numberOfScores = 0 3 | scores = [] 4 | 5 | while numberOfScores < numberOfStudents: 6 | score = eval(input("\nEnter the student scores: ")) 7 | scores.append(score) 8 | numberOfScores += 1 9 | print("\nThe maximum score is " + str(max(scores))) 10 | scores.pop(numberOfStudents - 1) 11 | print("\nThe second highest is " + str(max(scores))) 12 | 13 | -------------------------------------------------------------------------------- /chapter5/5.12.py: -------------------------------------------------------------------------------- 1 | number = 100 2 | numberList = [] 3 | 4 | for number in range(100, 201): 5 | if (number % 5 == 0) and (number % 6 == 0): 6 | numberList.append(number) 7 | 8 | while numberList != []: 9 | for i in range(0, 10): 10 | 11 | if numberList != []: 12 | print(min(numberList), end=" ") 13 | numberList.pop(0) 14 | 15 | 16 | 17 | 18 | -------------------------------------------------------------------------------- /chapter5/5.13.py: -------------------------------------------------------------------------------- 1 | number = 100 2 | numberList = [] 3 | 4 | for number in range(100, 201): 5 | if (number % 5 == 0) or (number % 6 == 0): 6 | if (number % 5 == 0) and (number % 6 == 0): 7 | continue 8 | else: 9 | numberList.append(number) 10 | 11 | while numberList != []: 12 | for i in range(0, 10): 13 | 14 | if numberList != []: 15 | print(min(numberList), end=" ") 16 | numberList.pop(0) 17 | print() 18 | 19 | 20 | 21 | 22 | -------------------------------------------------------------------------------- /chapter5/5.14.py: -------------------------------------------------------------------------------- 1 | n1, n2 = eval(input("Enter two numbers n1 and n2: ")) 2 | l = [] 3 | l.append(n1) 4 | l.append(n2) 5 | d = min(l) 6 | 7 | while d >= 1: 8 | if n1 % d == 0 and n2 % d == 0: 9 | break 10 | d -= 1 11 | 12 | print("The GCD is " + str(d)) 13 | -------------------------------------------------------------------------------- /chapter5/5.15.py: -------------------------------------------------------------------------------- 1 | Python 3.7.0 (v3.7.0:1bf9cc5093, Jun 27 2018, 04:59:51) [MSC v.1914 64 bit (AMD64)] on win32 2 | Type "copyright", "credits" or "license()" for more information. 3 | >>> 4 | ========== RESTART: C:/Users/Xurror/Desktop/mywork/chapter5/5.12.py ========== 5 | >>> 6 | ========== RESTART: C:/Users/Xurror/Desktop/mywork/chapter5/5.12.py ========== 7 | >>> 8 | ========== RESTART: C:/Users/Xurror/Desktop/mywork/chapter5/5.12.py ========== 9 | >>> 10 | ========== RESTART: C:/Users/Xurror/Desktop/mywork/chapter5/5.12.py ========== 11 | >>> 12 | ========== RESTART: C:/Users/Xurror/Desktop/mywork/chapter5/5.12.py ========== 13 | >>> 14 | ========== RESTART: C:/Users/Xurror/Desktop/mywork/chapter5/5.12.py ========== 15 | 120 150 180 210 240 270 300 330 360 390 420 450 480 510 540 570 600 630 660 690 720 750 780 810 840 870 900 930 960 990 16 | >>> 17 | ========== RESTART: C:/Users/Xurror/Desktop/mywork/chapter5/5.12.py ========== 18 | 100 102 105 108 110 114 115 120 125 126 130 132 135 138 140 144 145 150 155 156 160 162 165 168 170 174 175 180 185 186 190 192 195 198 200 204 205 210 215 216 220 222 225 228 230 234 235 240 245 246 250 252 255 258 260 264 265 270 275 276 280 282 285 288 290 294 295 300 305 306 310 312 315 318 320 324 325 330 335 336 340 342 345 348 350 354 355 360 365 366 370 372 375 378 380 384 385 390 395 396 400 402 405 408 410 414 415 420 425 426 430 432 435 438 440 444 445 450 455 456 460 462 465 468 470 474 475 480 485 486 490 492 495 498 500 504 505 510 515 516 520 522 525 528 530 534 535 540 545 546 550 552 555 558 560 564 565 570 575 576 580 582 585 588 590 594 595 600 605 606 610 612 615 618 620 624 625 630 635 636 640 642 645 648 650 654 655 660 665 666 670 672 675 678 680 684 685 690 695 696 700 702 705 708 710 714 715 720 725 726 730 732 735 738 740 744 745 750 755 756 760 762 765 768 770 774 775 780 785 786 790 792 795 798 800 804 805 810 815 816 820 822 825 828 830 834 835 840 845 846 850 852 855 858 860 864 865 870 875 876 880 882 885 888 890 894 895 900 905 906 910 912 915 918 920 924 925 930 935 936 940 942 945 948 950 954 955 960 965 966 970 972 975 978 980 984 985 990 995 996 19 | >>> 20 | ========== RESTART: C:/Users/Xurror/Desktop/mywork/chapter5/5.13.py ========== 21 | 100 102 105 108 110 114 115 120 125 126 130 132 135 138 140 144 145 150 155 156 160 162 165 168 170 174 175 180 185 186 190 192 195 198 200 22 | >>> 23 | ========== RESTART: C:/Users/Xurror/Desktop/mywork/chapter5/5.13.py ========== 24 | 100 100 100 100 100 100 100 100 100 100 25 | >>> 26 | ========== RESTART: C:/Users/Xurror/Desktop/mywork/chapter5/5.13.py ========== 27 | 100 102 105 108 110 114 115 120 125 126 130 132 135 138 140 144 145 150 155 156 160 162 165 168 170 174 175 180 185 186 190 192 195 198 200 28 | >>> 29 | ========== RESTART: C:/Users/Xurror/Desktop/mywork/chapter5/5.13.py ========== 30 | 100 102 105 108 110 114 115 125 126 130 132 135 138 140 144 145 155 156 160 162 165 168 170 174 175 185 186 190 192 195 198 200 31 | >>> 32 | ========== RESTART: C:/Users/Xurror/Desktop/mywork/chapter5/5.13.py ========== 33 | 100 102 105 108 110 114 115 125 126 130 132 135 138 140 144 145 155 156 160 162 165 168 170 174 175 185 186 190 192 195 198 200 34 | >>> 35 | ========== RESTART: C:/Users/Xurror/Desktop/mywork/chapter5/5.13.py ========== 36 | 100 37 | 38 | 102 39 | 40 | 41 | 105 42 | 43 | 44 | 108 45 | 46 | 110 47 | 48 | 49 | 50 | 114 51 | 115 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 125 61 | 126 62 | 63 | 64 | 65 | 130 66 | 67 | 132 68 | 69 | 70 | 135 71 | 72 | 73 | 138 74 | 75 | 140 76 | 77 | 78 | 79 | 144 80 | 145 81 | 82 | 83 | 84 | 85 | 86 | 87 | 88 | 89 | 155 90 | 156 91 | 92 | 93 | 94 | 160 95 | 96 | 162 97 | 98 | 99 | 165 100 | 101 | 102 | 168 103 | 104 | 170 105 | 106 | 107 | 108 | 174 109 | 175 110 | 111 | 112 | 113 | 114 | 115 | 116 | 117 | 118 | 185 119 | 186 120 | 121 | 122 | 123 | 190 124 | 125 | 192 126 | 127 | 128 | 195 129 | 130 | 131 | 198 132 | 133 | 200 134 | >>> 135 | ========== RESTART: C:/Users/Xurror/Desktop/mywork/chapter5/5.14.py ========== 136 | 111 137 | >>> 138 | ========== RESTART: C:/Users/Xurror/Desktop/mywork/chapter5/5.14.py ========== 139 | 110 140 | >>> 141 | ========== RESTART: C:/Users/Xurror/Desktop/mywork/chapter5/5.14.py ========== 142 | 22 143 | >>> 144 | -------------------------------------------------------------------------------- /chapter5/5.16.py: -------------------------------------------------------------------------------- 1 | n1, n2 = eval(input("Enter two numbers n1 and n2: ")) 2 | l = [] 3 | l.append(n1) 4 | l.append(n2) 5 | d = min(l) 6 | 7 | while d >= 1: 8 | if n1 % d == 0 and n2 % d == 0: 9 | break 10 | d -= 1 11 | 12 | print("The GCD is " + str(d)) 13 | -------------------------------------------------------------------------------- /chapter5/5.17.py: -------------------------------------------------------------------------------- 1 | num = 33 2 | codeList = [] 3 | 4 | for num in range(33, 127): 5 | codeList.append(chr(num)) 6 | 7 | while codeList != []: 8 | for i in range(0, 10): 9 | 10 | if codeList != []: 11 | print(min(codeList), end=" ") 12 | codeList.pop(0) 13 | print() 14 | -------------------------------------------------------------------------------- /chapter5/5.18.py: -------------------------------------------------------------------------------- 1 | num = eval(input("Enter an integer: ")) 2 | counter1 = 0 3 | counter2 = 0 4 | counter3 = 0 5 | counter4 = 0 6 | factors = [] 7 | 8 | while num != 1: 9 | if num % 2 == 0: 10 | num /= 2 11 | factors.append(2) 12 | counter1 += 1 13 | if num % 3 == 0: 14 | num /= 3 15 | factors.append(3) 16 | counter2 += 1 17 | if num % 5 == 0: 18 | num /= 5 19 | factors.append(5) 20 | counter3 += 1 21 | if num % 7 == 0: 22 | num /= 7 23 | factors.append(7) 24 | counter4 += 1 25 | while factors != []: 26 | 27 | print(min(factors), end=", ") 28 | factors.pop(0) 29 | -------------------------------------------------------------------------------- /chapter5/5.19.py: -------------------------------------------------------------------------------- 1 | n = eval(input("Enter an integer: ")) 2 | # number of spaces 3 | k = 2*n - 2 4 | left = 1 5 | right = 1 6 | 7 | # outer loop to handle number of rows 8 | for i in range(0, n): 9 | 10 | left = 1 11 | # inner loop to handle number spaces 12 | # values changing acc. to requirement 13 | #for j in range(0, k): 14 | # print(end=" ") 15 | 16 | #right = 2 17 | #num = 1 18 | 19 | # decrementing k after each loop 20 | #k = k - 1 21 | 22 | # inner loop to handle number of columns 23 | # values changing acc. to outer loop 24 | for j in range(0, i+1): 25 | 26 | 27 | # printing stars 28 | print(left, end=" ") 29 | left = n - 1 30 | #right = right + 1 31 | #right = num + 1 32 | # ending line after each row 33 | print("\r") 34 | 35 | # incrementing number at each column 36 | #num = num + 1 37 | 38 | # ending line after each row 39 | print("\r") 40 | -------------------------------------------------------------------------------- /chapter5/5.2.py: -------------------------------------------------------------------------------- 1 | import random 2 | additionQuestions = 0 3 | 4 | while additionQuestions < 10: 5 | int1 = random.randint(1, 15) 6 | int2 = random.randint(1, 15) 7 | 8 | total = eval(input("What is the sum of " 9 | + str(int1) + " + " + str(int2) + " = ")) 10 | print(str(int1) + " + " + str(int2) 11 | + " = " + str(total) + " is " 12 | + str((int1 + int2) == total)) 13 | additionQuestions += 1 14 | -------------------------------------------------------------------------------- /chapter5/5.20.py: -------------------------------------------------------------------------------- 1 | # Liang 5.20 (A and B) 2 | 3 | LIMIT = 7 4 | 5 | def displayPatternA(): 6 | for i in range(1, LIMIT): 7 | for j in range(1, i + 1): 8 | print (j, end=' ') 9 | print () 10 | 11 | def displayPatternB(): 12 | for i in range(1, LIMIT): 13 | for j in range(1, LIMIT - i + 1): 14 | print (j, end=' ') 15 | print () 16 | 17 | def main(): 18 | print ('Pattern A'); displayPatternA() 19 | print ('\n\nPattern B\n'); displayPatternB() 20 | 21 | main() 22 | -------------------------------------------------------------------------------- /chapter5/5.20A.py: -------------------------------------------------------------------------------- 1 | Python 3.7.0 (v3.7.0:1bf9cc5093, Jun 27 2018, 04:59:51) [MSC v.1914 64 bit (AMD64)] on win32 2 | Type "copyright", "credits" or "license()" for more information. 3 | >>> 4 | ========== RESTART: C:\Users\Xurror\Desktop\mywork\chapter5\5.19.py ==========5 5 | Enter an integer: 5 6 | 1 7 | 8 | 1 2 9 | 10 | 1 2 3 11 | 12 | 1 2 3 4 13 | 14 | 1 2 3 4 5 15 | 16 | 17 | 18 | >>> 19 | ========== RESTART: C:\Users\Xurror\Desktop\mywork\chapter5\5.19.py ========== 20 | Enter an integer: 5 21 | 1 22 | 23 | 1 2 24 | 25 | 1 2 3 26 | 27 | 1 2 3 4 28 | 29 | 1 2 3 4 5 30 | 31 | 32 | 33 | >>> 34 | ========== RESTART: C:\Users\Xurror\Desktop\mywork\chapter5\5.19.py ========== 35 | Enter an integer: 5 36 | 1 37 | 38 | 1 2 39 | 40 | 1 2 3 41 | 42 | 1 2 3 4 43 | 44 | 1 2 3 4 5 45 | 46 | 47 | 48 | >>> 49 | ========== RESTART: C:\Users\Xurror\Desktop\mywork\chapter5\5.19.py ========== 50 | Enter an integer: 5 51 | 1 52 | 53 | 1 2 54 | 55 | 1 2 3 56 | 57 | 1 2 3 4 58 | 59 | 1 2 3 4 5 60 | 61 | 62 | 63 | >>> 64 | -------------------------------------------------------------------------------- /chapter5/5.22.py: -------------------------------------------------------------------------------- 1 | #numberOfPrimes = 50 2 | numberOfPrimesPerLine = 8 3 | count = 0 4 | number = 2 5 | 6 | print("The prime numbers between 2 and 1000 are:") 7 | 8 | for numberOfPrimes in range(2, 1000): 9 | 10 | isPrime = True 11 | 12 | divisor = 2 13 | 14 | while divisor <= number / 2: 15 | if number % divisor == 0: 16 | 17 | isPrime = False 18 | break 19 | divisor += 1 20 | 21 | if isPrime: 22 | count += 1 23 | 24 | print(number, end= " ") 25 | 26 | if count % numberOfPrimesPerLine == 0: 27 | 28 | print('\r') 29 | 30 | number += 1 31 | -------------------------------------------------------------------------------- /chapter5/5.23.py: -------------------------------------------------------------------------------- 1 | Loan = eval(input("Loan Amount: ")) 2 | Years = eval(input("Number of Years: ")) 3 | rate = 5.00 4 | 5 | print("Interest Rate \t Monthly Payment \t Total Payment") 6 | 7 | while rate <= 8: 8 | 9 | monthlyPayment = Loan * rate / (1 - 1 / (1 + rate) ** (Years * 12)) 10 | totalPayment = monthlyPayment * Years * 12 11 | 12 | print(str(format(rate, ".3f")) + "%\t\t" 13 | + str(format(monthlyPayment, ".2f")) + "\t\t" 14 | + str(format(totalPayment, ".2f"))) 15 | rate += 1 / 8 16 | 17 | -------------------------------------------------------------------------------- /chapter5/5.24.py: -------------------------------------------------------------------------------- 1 | Loan = eval(input("Loan Amount: ")) 2 | Years = eval(input("Number of Years: ")) 3 | rate = 5.00 4 | 5 | print("Interest Rate \t Monthly Payment \t Total Payment") 6 | 7 | while rate <= 8: 8 | 9 | monthlyPayment = Loan * rate / (1 - 1 / (1 + rate) ** (Years * 12)) 10 | totalPayment = monthlyPayment * Years * 12 11 | 12 | print(str(format(rate, ".3f")) + "%\t\t" 13 | + str(format(monthlyPayment, ".2f")) + "\t\t" 14 | + str(format(totalPayment, ".2f"))) 15 | rate += 1 / 8 16 | 17 | -------------------------------------------------------------------------------- /chapter5/5.25.py: -------------------------------------------------------------------------------- 1 | n = 50000 2 | add = 0 3 | 4 | while n > 0: 5 | add += 1 / n 6 | n -= 1 7 | add += 1 8 | print(str(format(add,".1f"))) 9 | -------------------------------------------------------------------------------- /chapter5/5.26.py: -------------------------------------------------------------------------------- 1 | n = 1 2 | add = 1 / 3 3 | 4 | while n < 100: 5 | 6 | if n % 2 != 0: 7 | add += n / (n + 2) 8 | n += 1 9 | #add += 1 10 | print(str(format(add,".1f"))) 11 | -------------------------------------------------------------------------------- /chapter5/5.27.py: -------------------------------------------------------------------------------- 1 | 2 | n = 1000 3 | 4 | add = 1 / 3 5 | 6 | 7 | 8 | while n <= 10000: 9 | 10 | for i in range(n): 11 | 12 | pi = (((-1) ** (i + 1)) / (2*i - 1)) 13 | 14 | print("PI for", n, "is", pi) 15 | n += 1000 16 | 17 | #print(str(format(add,".1f"))) 18 | -------------------------------------------------------------------------------- /chapter5/5.28.py: -------------------------------------------------------------------------------- 1 | 2 | n = 1000 3 | 4 | add = 1 / 3 5 | 6 | 7 | 8 | while n <= 10000: 9 | 10 | for i in range(n): 11 | 12 | pi = 4*S(((-1) ** (i + 1)) / (2*i - 1)) 13 | 14 | print("PI for", n, "is", pi) 15 | n += 1000 16 | 17 | #print(str(format(add,".1f"))) 18 | -------------------------------------------------------------------------------- /chapter5/5.3.py: -------------------------------------------------------------------------------- 1 | kilogram = 1 2 | print("KILOGRAMS \t POUNDS") 3 | 4 | for kilogram in range(1, 200, 2): 5 | pounds = kilogram * 2.2 6 | print(str(format(kilogram, "<4.0f")) + str(format(pounds, "20.1f"))) 7 | 8 | -------------------------------------------------------------------------------- /chapter5/5.30.py: -------------------------------------------------------------------------------- 1 | #Program to find the first days of all months by the given year and January 1 of that year 2 | 3 | year = eval(input("Enter the year: ")) 4 | first = eval(input("Enter the first day of the year: ")) 5 | days = 0 6 | 7 | for m in range(1,12 + 1): 8 | if m == 1: 9 | print("January 1", year, "is ", end = "") 10 | days = 31 11 | elif m == 2: 12 | print("February 1",year, "is ", end = "") 13 | if (year % 400 == 0 or (year % 4 == 0 and year % 100 != 0)): 14 | days = 29 15 | else: 16 | days = 28 17 | elif m == 3: 18 | print("March 1,", year, "is ", end = "") 19 | days = 31 20 | elif m == 4: 21 | print("April 1,", year, "is ", end = "") 22 | days = 30 23 | elif m == 5: 24 | print("May 1,", year, "is ", end = "") 25 | days = 31 26 | elif m == 6: 27 | print("June 1,", year, "is ", end = "") 28 | days = 30 29 | elif m == 7: 30 | print("July 1,", year, "is ", end = "") 31 | days = 31 32 | elif m == 8: 33 | print("August 1,", year, "is ", end = "") 34 | days = 31 35 | elif m == 9: 36 | print("September 1,", year, "is ", end = "") 37 | days = 30 38 | elif m == 10: 39 | print("October 1,", year, "is ", end = "") 40 | days = 31 41 | elif m == 11: 42 | print("November 1,", year, "is ", end = "") 43 | days = 30 44 | elif (m == 12): 45 | print("December 1,", year, "is ", end = "") 46 | days = 31 47 | 48 | 49 | if first == 0: 50 | print("Sunday") 51 | elif first == 1: 52 | print("Monday") 53 | elif first == 2: 54 | print("Tuesday") 55 | elif first == 3: 56 | print("Wednesday") 57 | elif first == 4: 58 | print("Thursday") 59 | elif first == 5: 60 | print("Friday") 61 | elif first == 6: 62 | print("Saturday") 63 | 64 | first = (first + days) % 7 65 | -------------------------------------------------------------------------------- /chapter5/5.36.py: -------------------------------------------------------------------------------- 1 | #Program to implement 2 | import random 3 | count = 0 4 | 5 | print("Rules: scissor (0), rock (1), paper (2) ") 6 | while count <= 2 or count <= -2: 7 | num = random.randint(0, 2) 8 | user = eval(input("Enter your choice: ")) 9 | 10 | # Check the User Guess with Computer's Guess 11 | if num == 0: 12 | if user == 0: 13 | print("It is a draw") 14 | elif user == 1: 15 | print("You won!") 16 | count += 1 17 | elif user == 2: 18 | print("Computer won!") 19 | count -= 1 20 | elif num == 1: 21 | if user == 0: 22 | print("Computer won!") 23 | count -= 1 24 | elif user == 1: 25 | print("It is a draw") 26 | elif user == 2: 27 | print("You won!") 28 | count += 1 29 | elif num == 2: 30 | if user == 0: 31 | print("You won!") 32 | count += 1 33 | elif user == 1: 34 | print("Computer won!") 35 | count -= 1 36 | elif user == 2: 37 | print("It is a draw") 38 | 39 | if count > 2: 40 | print("You won more than two times continuously") 41 | else: 42 | print("The computer won more than two times continously") 43 | 44 | -------------------------------------------------------------------------------- /chapter5/5.3output.txt: -------------------------------------------------------------------------------- 1 | KILOGRAMS POUNDS 2 | 1 2.2 3 | 3 6.6 4 | 5 11.0 5 | 7 15.4 6 | 9 19.8 7 | 11 24.2 8 | 13 28.6 9 | 15 33.0 10 | 17 37.4 11 | 19 41.8 12 | 21 46.2 13 | 23 50.6 14 | 25 55.0 15 | 27 59.4 16 | 29 63.8 17 | 31 68.2 18 | 33 72.6 19 | 35 77.0 20 | 37 81.4 21 | 39 85.8 22 | 41 90.2 23 | 43 94.6 24 | 45 99.0 25 | 47 103.4 26 | 49 107.8 27 | 51 112.2 28 | 53 116.6 29 | 55 121.0 30 | 57 125.4 31 | 59 129.8 32 | 61 134.2 33 | 63 138.6 34 | 65 143.0 35 | 67 147.4 36 | 69 151.8 37 | 71 156.2 38 | 73 160.6 39 | 75 165.0 40 | 77 169.4 41 | 79 173.8 42 | 81 178.2 43 | 83 182.6 44 | 85 187.0 45 | 87 191.4 46 | 89 195.8 47 | 91 200.2 48 | 93 204.6 49 | 95 209.0 50 | 97 213.4 51 | 99 217.8 52 | 101 222.2 53 | 103 226.6 54 | 105 231.0 55 | 107 235.4 56 | 109 239.8 57 | 111 244.2 58 | 113 248.6 59 | 115 253.0 60 | 117 257.4 61 | 119 261.8 62 | 121 266.2 63 | 123 270.6 64 | 125 275.0 65 | 127 279.4 66 | 129 283.8 67 | 131 288.2 68 | 133 292.6 69 | 135 297.0 70 | 137 301.4 71 | 139 305.8 72 | 141 310.2 73 | 143 314.6 74 | 145 319.0 75 | 147 323.4 76 | 149 327.8 77 | 151 332.2 78 | 153 336.6 79 | 155 341.0 80 | 157 345.4 81 | 159 349.8 82 | 161 354.2 83 | 163 358.6 84 | 165 363.0 85 | 167 367.4 86 | 169 371.8 87 | 171 376.2 88 | 173 380.6 89 | 175 385.0 90 | 177 389.4 91 | 179 393.8 92 | 181 398.2 93 | 183 402.6 94 | 185 407.0 95 | 187 411.4 96 | 189 415.8 97 | 191 420.2 98 | 193 424.6 99 | 195 429.0 100 | 197 433.4 101 | 199 437.8 102 | -------------------------------------------------------------------------------- /chapter5/5.4.py: -------------------------------------------------------------------------------- 1 | miles = 1 2 | print("MILES \t KILOMETERS") 3 | 4 | for miles in range(1, 10): 5 | kilometers = miles * 1.609 6 | print(str(format(miles, "<10.0f")) + str(kilometers)) 7 | 8 | -------------------------------------------------------------------------------- /chapter5/5.41.py: -------------------------------------------------------------------------------- 1 | count = 1 2 | num = eval(input("Enter a number (0: for end of input): ")) 3 | num1 = num 4 | num1 = max 5 | 6 | while num != 0: 7 | num = eval(input("Enter a number (0: for end of input): ")) 8 | 9 | if num == num1: 10 | count += 1 11 | elif num > num1: 12 | num = max 13 | num1 = max 14 | count = 1 15 | print(num) 16 | print(max(num), count) 17 | -------------------------------------------------------------------------------- /chapter5/5.4output.txt: -------------------------------------------------------------------------------- 1 | MILES KILOMETERS 2 | 1 1.609 3 | 2 3.218 4 | 3 4.827 5 | 4 6.436 6 | 5 8.045 7 | 6 9.654 8 | 7 11.263 9 | 8 12.872 10 | 9 14.481 11 | -------------------------------------------------------------------------------- /chapter5/5.5.py: -------------------------------------------------------------------------------- 1 | kilogram = 1 2 | pound = 20 3 | print("KILOGRAMS \t POUNDS \t | \t POUNDS \t KILOGRAMS") 4 | 5 | while (kilogram in range(1, 200)) or (pound in range(20, 520)): 6 | pounds = kilogram * 2.2 7 | kilograms = pound / 2.2 8 | print(str(format(kilogram, "<4.0f")) + str(format(pounds, "20.1f")) 9 | + " \t |" 10 | + str(format(pound, "20.0f")) + str(format(kilograms, "20.2f"))) 11 | 12 | kilogram += 2 13 | pound += 5 14 | 15 | -------------------------------------------------------------------------------- /chapter5/5.5output.txt: -------------------------------------------------------------------------------- 1 | KILOGRAMS POUNDS | POUNDS KILOGRAMS 2 | 1 2.2 | 20 9.09 3 | 3 6.6 | 25 11.36 4 | 5 11.0 | 30 13.64 5 | 7 15.4 | 35 15.91 6 | 9 19.8 | 40 18.18 7 | 11 24.2 | 45 20.45 8 | 13 28.6 | 50 22.73 9 | 15 33.0 | 55 25.00 10 | 17 37.4 | 60 27.27 11 | 19 41.8 | 65 29.55 12 | 21 46.2 | 70 31.82 13 | 23 50.6 | 75 34.09 14 | 25 55.0 | 80 36.36 15 | 27 59.4 | 85 38.64 16 | 29 63.8 | 90 40.91 17 | 31 68.2 | 95 43.18 18 | 33 72.6 | 100 45.45 19 | 35 77.0 | 105 47.73 20 | 37 81.4 | 110 50.00 21 | 39 85.8 | 115 52.27 22 | 41 90.2 | 120 54.55 23 | 43 94.6 | 125 56.82 24 | 45 99.0 | 130 59.09 25 | 47 103.4 | 135 61.36 26 | 49 107.8 | 140 63.64 27 | 51 112.2 | 145 65.91 28 | 53 116.6 | 150 68.18 29 | 55 121.0 | 155 70.45 30 | 57 125.4 | 160 72.73 31 | 59 129.8 | 165 75.00 32 | 61 134.2 | 170 77.27 33 | 63 138.6 | 175 79.55 34 | 65 143.0 | 180 81.82 35 | 67 147.4 | 185 84.09 36 | 69 151.8 | 190 86.36 37 | 71 156.2 | 195 88.64 38 | 73 160.6 | 200 90.91 39 | 75 165.0 | 205 93.18 40 | 77 169.4 | 210 95.45 41 | 79 173.8 | 215 97.73 42 | 81 178.2 | 220 100.00 43 | 83 182.6 | 225 102.27 44 | 85 187.0 | 230 104.55 45 | 87 191.4 | 235 106.82 46 | 89 195.8 | 240 109.09 47 | 91 200.2 | 245 111.36 48 | 93 204.6 | 250 113.64 49 | 95 209.0 | 255 115.91 50 | 97 213.4 | 260 118.18 51 | 99 217.8 | 265 120.45 52 | 101 222.2 | 270 122.73 53 | 103 226.6 | 275 125.00 54 | 105 231.0 | 280 127.27 55 | 107 235.4 | 285 129.55 56 | 109 239.8 | 290 131.82 57 | 111 244.2 | 295 134.09 58 | 113 248.6 | 300 136.36 59 | 115 253.0 | 305 138.64 60 | 117 257.4 | 310 140.91 61 | 119 261.8 | 315 143.18 62 | 121 266.2 | 320 145.45 63 | 123 270.6 | 325 147.73 64 | 125 275.0 | 330 150.00 65 | 127 279.4 | 335 152.27 66 | 129 283.8 | 340 154.55 67 | 131 288.2 | 345 156.82 68 | 133 292.6 | 350 159.09 69 | 135 297.0 | 355 161.36 70 | 137 301.4 | 360 163.64 71 | 139 305.8 | 365 165.91 72 | 141 310.2 | 370 168.18 73 | 143 314.6 | 375 170.45 74 | 145 319.0 | 380 172.73 75 | 147 323.4 | 385 175.00 76 | 149 327.8 | 390 177.27 77 | 151 332.2 | 395 179.55 78 | 153 336.6 | 400 181.82 79 | 155 341.0 | 405 184.09 80 | 157 345.4 | 410 186.36 81 | 159 349.8 | 415 188.64 82 | 161 354.2 | 420 190.91 83 | 163 358.6 | 425 193.18 84 | 165 363.0 | 430 195.45 85 | 167 367.4 | 435 197.73 86 | 169 371.8 | 440 200.00 87 | 171 376.2 | 445 202.27 88 | 173 380.6 | 450 204.55 89 | 175 385.0 | 455 206.82 90 | 177 389.4 | 460 209.09 91 | 179 393.8 | 465 211.36 92 | 181 398.2 | 470 213.64 93 | 183 402.6 | 475 215.91 94 | 185 407.0 | 480 218.18 95 | 187 411.4 | 485 220.45 96 | 189 415.8 | 490 222.73 97 | 191 420.2 | 495 225.00 98 | 193 424.6 | 500 227.27 99 | 195 429.0 | 505 229.55 100 | 197 433.4 | 510 231.82 101 | 199 437.8 | 515 234.09 102 | -------------------------------------------------------------------------------- /chapter5/5.6.py: -------------------------------------------------------------------------------- 1 | kilometers = 20 2 | miles = 1 3 | print("MILES \t KILOMETERS \t | \t KILOMETERS \t MILES") 4 | 5 | while (miles in range(1, 11)) and (kilometers in range(20, 70)): 6 | kilometer = miles * 1.609 7 | mile = kilometers * 0.621 8 | print(str(format(miles, "<4.0f")) + str(format(kilometer, "15.3f")) 9 | + " \t |" 10 | + str(format(kilometers, "10.0f")) + str(format(mile, "15.3f"))) 11 | 12 | kilometers += 5 13 | miles += 1 14 | 15 | -------------------------------------------------------------------------------- /chapter5/5.6output.txt: -------------------------------------------------------------------------------- 1 | MILES KILOMETERS | KILOMETERS MILES 2 | 1 1.609 | 20 12.420 3 | 2 3.218 | 25 15.525 4 | 3 4.827 | 30 18.630 5 | 4 6.436 | 35 21.735 6 | 5 8.045 | 40 24.840 7 | 6 9.654 | 45 27.945 8 | 7 11.263 | 50 31.050 9 | 8 12.872 | 55 34.155 10 | 9 14.481 | 60 37.260 11 | 10 16.090 | 65 40.365 12 | -------------------------------------------------------------------------------- /chapter5/5.7.py: -------------------------------------------------------------------------------- 1 | import math 2 | 3 | print("degree \t sin \t\t cos") 4 | degree = 0 5 | 6 | for degree in range(0, 365, 10): 7 | 8 | sin = math.sin(degree) 9 | cos = math.cos(degree) 10 | 11 | print(str(degree) 12 | + str(format(sin, "15.4f")) 13 | + str(format(cos, "15.4f"))) 14 | -------------------------------------------------------------------------------- /chapter5/5.7output.txt: -------------------------------------------------------------------------------- 1 | degree sin cos 2 | 0 0.0000 1.0000 3 | 10 -0.5440 -0.8391 4 | 20 0.9129 0.4081 5 | 30 -0.9880 0.1543 6 | 40 0.7451 -0.6669 7 | 50 -0.2624 0.9650 8 | 60 -0.3048 -0.9524 9 | 70 0.7739 0.6333 10 | 80 -0.9939 -0.1104 11 | 90 0.8940 -0.4481 12 | 100 -0.5064 0.8623 13 | 110 -0.0442 -0.9990 14 | 120 0.5806 0.8142 15 | 130 -0.9301 -0.3673 16 | 140 0.9802 -0.1978 17 | 150 -0.7149 0.6993 18 | 160 0.2194 -0.9756 19 | 170 0.3466 0.9380 20 | 180 -0.8012 -0.5985 21 | 190 0.9978 0.0663 22 | 200 -0.8733 0.4872 23 | 210 0.4677 -0.8839 24 | 220 0.0884 0.9961 25 | 230 -0.6161 -0.7877 26 | 240 0.9454 0.3258 27 | 250 -0.9705 0.2410 28 | 260 0.6832 -0.7302 29 | 270 -0.1760 0.9844 30 | 280 -0.3878 -0.9217 31 | 290 0.8268 0.5624 32 | 300 -0.9998 -0.0221 33 | 310 0.8509 -0.5253 34 | 320 -0.4282 0.9037 35 | 330 -0.1324 -0.9912 36 | 340 0.6503 0.7597 37 | 350 -0.9589 -0.2836 38 | 360 0.9589 -0.2837 39 | -------------------------------------------------------------------------------- /chapter5/5.8.py: -------------------------------------------------------------------------------- 1 | import math 2 | 3 | print("number \t Square Root") 4 | number = 0 5 | 6 | for number in range(0, 21, 2): 7 | print(str(number) 8 | + str(format(math.sqrt(number), "15.4f"))) 9 | 10 | -------------------------------------------------------------------------------- /chapter5/5.8output.txt: -------------------------------------------------------------------------------- 1 | number Square Root 2 | 0 0.0000 3 | 2 1.4142 4 | 4 2.0000 5 | 6 2.4495 6 | 8 2.8284 7 | 10 3.1623 8 | 12 3.4641 9 | 14 3.7417 10 | 16 4.0000 11 | 18 4.2426 12 | 20 4.4721 13 | -------------------------------------------------------------------------------- /chapter5/5.9.py: -------------------------------------------------------------------------------- 1 | tuition = 10000 2 | years = 0 3 | total = 10000 4 | 5 | for years in range(0, 11): 6 | tuition = tuition * 1.05 7 | while years < 4: 8 | total += tuition 9 | years += 1 10 | print("Tuition at the tenth year will be ", str(format(tuition, ".2f"))) 11 | print("The total fees after 4 years is ", str(format(total, ".2f"))) 12 | -------------------------------------------------------------------------------- /chapter5/Trial.py: -------------------------------------------------------------------------------- 1 | n = eval(input("Enter a number: ")) 2 | l = [] 3 | z = 0 4 | e = n - 1 5 | for a in range(0, n): 6 | l.append(z + 1) 7 | z += 1 8 | 9 | z -= 1 10 | 11 | for i in range(0, n): 12 | 13 | 14 | 15 | for j in range(0, i+1): 16 | print(l[z], end= " ") 17 | z -= 1 18 | l.pop(e) 19 | e = e - 1 20 | z = max(l) 21 | print() 22 | z -= 1 23 | 24 | isPrime divisor 25 | -------------------------------------------------------------------------------- /chapter5/time table.py: -------------------------------------------------------------------------------- 1 | print(" Multiplication Table") 2 | # Display the number title 3 | print(" |", end = '') 4 | for j in range(1, 10): 5 | print(" ", j, end = '') 6 | print() # Jump to the new line 7 | print("——————————————————————————————————————————") 8 | 9 | # Display table body 10 | for i in range(1, 10): 11 | print(i, "|", end = '') 12 | for j in range(1, 10): 13 | # Display the product and align properly 14 | print(format(i * j, "4d"), end = '') 15 | print() # Jump to the new line 16 | -------------------------------------------------------------------------------- /chapter6/6.1.py: -------------------------------------------------------------------------------- 1 | def getPentagonalNumber(n): 2 | 3 | getPentagonalNumber = (n * (3*n - 1)) / 2 4 | 5 | return getPentagonalNumber 6 | 7 | def main(): 8 | n = eval(input("Enter a number: ")) 9 | print(getPentagonalNumber(n)) 10 | 11 | main() -------------------------------------------------------------------------------- /chapter6/6.10.py: -------------------------------------------------------------------------------- 1 | # Program to create a function to check if number is prime or not 2 | def isPrime(num): 3 | temp=2 4 | while temp<=num/2: 5 | if num%temp==0: 6 | return False 7 | temp+=1 8 | return True 9 | 10 | def main(): 11 | num=2 12 | 13 | while num<10000: 14 | if isPrime(num): 15 | print(num,end="\n") 16 | num = num + 1 17 | 18 | main() -------------------------------------------------------------------------------- /chapter6/6.18.py: -------------------------------------------------------------------------------- 1 | import random 2 | 3 | def printMatrix(n): 4 | 5 | for i in range(0, n): 6 | for j in range(0, n): 7 | rand = random.randint(0, 9) 8 | print(rand, end = " ") 9 | 10 | print() 11 | 12 | def main(): 13 | 14 | n = eval(input("Enter the order of the matrix: ")) 15 | printMatrix(n) 16 | 17 | main() -------------------------------------------------------------------------------- /chapter6/6.1n.py: -------------------------------------------------------------------------------- 1 | #def getPentagonalNumber(n): 2 | 3 | #getPentagonalNumber = (n * (3*n - 1)) / 2 4 | 5 | # return getPentagonalNumber 6 | 7 | #def main(): 8 | # n = eval(input("Enter a number: ")) 9 | # print(getPentagonalNumber(n)) 10 | 11 | #main() 12 | class Nasser: 13 | def __init__(self, name, age): 14 | self.name = name 15 | self.age = age 16 | user = Nasser() 17 | user.name = input("Enter your name: ") 18 | user.age = input("Enter your age: ") 19 | print(user.name()) -------------------------------------------------------------------------------- /chapter6/6.2.py: -------------------------------------------------------------------------------- 1 | #Program to write a function to display the sum of digits 2 | 3 | def SumOfDigits(num): 4 | count=0 5 | total=0 6 | 7 | while num!=0: 8 | count=num%10 9 | total+=count 10 | num=num//10 11 | return total 12 | 13 | 14 | def main(): 15 | InputNum = eval(input("Enter the number: ")) 16 | print("The sum of digits of ", InputNum, " is: ",SumOfDigits(InputNum)) 17 | 18 | main() -------------------------------------------------------------------------------- /chapter6/6.21.py: -------------------------------------------------------------------------------- 1 | def sqrt(n): 2 | 3 | lastGuess = 1 4 | nextGuess = (lastGuess + (n / lastGuess)) / 2 5 | 6 | if (nextGuess - lastGuess) > 0.0001: 7 | 8 | nextGuess = (lastGuess + (n / lastGuess)) / 2 9 | sqrt = nextGuess 10 | 11 | else: 12 | sqrt = nextGuess 13 | 14 | def main(): 15 | n = eval(input("Enter a number: ")) 16 | sqrt(n) 17 | main() -------------------------------------------------------------------------------- /chapter6/6.24.py: -------------------------------------------------------------------------------- 1 | #Find 100 Palindrome prime numbers 2 | 3 | def Reverse(N): 4 | count="" 5 | str1="" 6 | while N!=0: 7 | count=N%10 8 | str1=str(str1) 9 | count=str(count) 10 | str1=str1+count 11 | count=int(count) 12 | N=N//10 13 | 14 | str1=int(str1) 15 | return str1 16 | 17 | 18 | def isPrime(num): 19 | temp=2 20 | while temp<=num/2: 21 | if num%temp==0: 22 | return False 23 | temp+=1 24 | return True 25 | 26 | 27 | def isPalindromePrime(): 28 | cnt=0 29 | num=2 30 | while cnt<=100: 31 | if isPrime(num)==True and Reverse(num)==num: 32 | cnt+=1 33 | if cnt<=10: 34 | print(num,end=" ") 35 | elif cnt>10 and cnt<=20: 36 | print(num,end=" ") 37 | elif cnt>20 and cnt<=30: 38 | print(num,end=" ") 39 | elif cnt>30 and cnt<=40: 40 | print(num,end=" ") 41 | elif cnt>40 and cnt<=50: 42 | print(num,end=" ") 43 | elif cnt>50 and cnt<=60: 44 | print(num,end=" ") 45 | elif cnt>60 and cnt<=70: 46 | print(num,end=" ") 47 | elif cnt>70 and cnt<=80: 48 | print(num,end=" ") 49 | elif cnt>80 and cnt<=90: 50 | print(num,end=" ") 51 | elif cnt>90 and cnt<=100: 52 | print(num,end=" ") 53 | else: 54 | print(num,end=" ") 55 | 56 | if cnt%10==0: 57 | print() 58 | num+=1 59 | 60 | 61 | isPalindromePrime() 62 | -------------------------------------------------------------------------------- /chapter6/6.29.py: -------------------------------------------------------------------------------- 1 | #Program to check whether the Credit Card number is valid or not 2 | import math 3 | 4 | def isValid(num): 5 | if getSize(num)> 16 or getSize(num)<13: 6 | return False 7 | elif getPrefix(num,1)==4 or getPrefix(num,1)==5 or getPrefix(num,1)==6 or getPrefix(num,2)==37: 8 | pass 9 | else: 10 | return False 11 | sum1 = sumOfDoubleEvenPlace(num) + sumOfOddPlace(num) 12 | return sum1 % 10 == 0 13 | 14 | def sumOfDoubleEvenPlace(num): 15 | sum1=0 16 | while num>0: 17 | num=num//10 18 | digit=getDigit((num % 10) * 2) 19 | sum1+=digit 20 | num=num//10 21 | return sum1 22 | 23 | def getDigit(num): 24 | if num>9: 25 | num -= 9 26 | return num 27 | else: 28 | return num 29 | 30 | def sumOfOddPlace(num): 31 | sum1=0 32 | while num>0: 33 | digit=num%10 34 | digit=getDigit(digit) 35 | sum1+=digit 36 | num=num//100 37 | 38 | return sum1 39 | 40 | def prefixMatched(num,d): 41 | if d>num: 42 | return False 43 | diff=getSize(num)-getSize(d) 44 | d=num/math.pow(num,diff) 45 | return d 46 | 47 | def getSize(num): 48 | size = 0 49 | while num>0: 50 | size+=1 51 | num=num//10 52 | 53 | return size 54 | 55 | def getPrefix(num,k): 56 | if (prefixMatched(num,k)): 57 | return k,num 58 | 59 | def main(): 60 | ccnumber=eval(input("Enter the Credit Card Number: ")) 61 | if (isValid(ccnumber)): 62 | print("Credit Card number is Valid") 63 | else: 64 | print("Credit Card number is not Valid") 65 | 66 | main() 67 | 68 | 69 | 70 | -------------------------------------------------------------------------------- /chapter6/6.3.py: -------------------------------------------------------------------------------- 1 | #Program to find the palindrome of a number using functions 2 | 3 | def Reverse(N): 4 | count="" 5 | str1="" 6 | while N!=0: 7 | count=N%10 8 | str1=str(str1) 9 | count=str(count) 10 | str1=str1+count 11 | count=int(count) 12 | N=N//10 13 | 14 | str1=int(str1) 15 | return str1 16 | 17 | 18 | def isPalindrome(): 19 | inputNum = eval(input("Enter the number: ")) 20 | if Reverse(inputNum) == inputNum: 21 | print("The number", inputNum,"is a palindrome") 22 | else: 23 | print("The number", inputNum,"is not palindrome") 24 | 25 | isPalindrome() -------------------------------------------------------------------------------- /chapter6/6.34.py: -------------------------------------------------------------------------------- 1 | # Liang 6.34 2 | import math 3 | 4 | def area(n, side): 5 | return (n * (side * side)) / (4 * math.tan(math.pi / n)) 6 | 7 | def main(): 8 | n = int(input('Enter the number of sides (n > 2): ')) 9 | side = float(input('Enter the side length (length > 0): ')) 10 | print ('The area of the polygon is %f' % area(n, side)) 11 | 12 | if __name__ == '__main__': 13 | main() 14 | -------------------------------------------------------------------------------- /chapter6/6.4.py: -------------------------------------------------------------------------------- 1 | reversedNumber = [] 2 | 3 | def reverse(number): 4 | n = 0 5 | while number > 10: 6 | 7 | reverse = number % 10 8 | reversedNumber.append(reverse) 9 | number //= 10 10 | print(reverse, end= '') 11 | print(number) 12 | 13 | def main(): 14 | 15 | number = eval(input("Enter a number: ")) 16 | reverse(number) 17 | 18 | main() 19 | 20 | -------------------------------------------------------------------------------- /chapter6/6.5.py: -------------------------------------------------------------------------------- 1 | def displaySortedNumbers(num1, num2, num3): 2 | 3 | print(max(num1, num2, num3), end = ", ") 4 | 5 | if num1 != (max(num1, num2, num3) and min(num1, num2, num3)): 6 | print(num1, end = ", ") 7 | 8 | elif num2 != (max(num1, num2, num3) and min(num1, num2, num3)): 9 | print(num2, end = ", ") 10 | 11 | elif num3 != (max(num1, num2, num3) and min(num1, num2, num3)): 12 | print(num3, end = ", ") 13 | 14 | print(min(num1, num2, num3)) 15 | 16 | def main(): 17 | num1, num2, num3 = eval(input("Enter three numbers: ")) 18 | displaySortedNumbers(num1, num2, num3) 19 | 20 | main() -------------------------------------------------------------------------------- /chapter6/6.6.py: -------------------------------------------------------------------------------- 1 | def displayPattern(n): 2 | 3 | k = 1 4 | 5 | for i in range(0, n): 6 | 7 | print(k, end = "") 8 | 9 | for j in range(0, k): 10 | print() 11 | 12 | k += 1 13 | 14 | def main(): 15 | 16 | n = eval(input("Enter a number: ")) 17 | displayPattern(n) 18 | 19 | main() 20 | 21 | -------------------------------------------------------------------------------- /chapter6/RandomCharacter.py: -------------------------------------------------------------------------------- 1 | from random import randint # import randint 2 | 3 | # Generate a random character between ch1 and ch2 4 | def getRandomCharacter(ch1, ch2): 5 | return chr(randint(ord(ch1), ord(ch2))) 6 | 7 | # Generate a random lowercase letter 8 | def gerRandomLowerCaseLetter(): 9 | return getRandomCharacter('a', 'z') 10 | 11 | # Generate a random uppercase letter 12 | def getRandomUpperCaseLetter(): 13 | return getRandomCharacter('A', 'Z') 14 | 15 | # Generate a random digit character 16 | def getRandomDigitCharacter(): 17 | return getRandomCharacter('0', '9') 18 | 19 | # Generate a random character 20 | def getRandomASCIICharacter(): 21 | return chr(randint(0, 127)) 22 | -------------------------------------------------------------------------------- /chapter6/classTuto.py: -------------------------------------------------------------------------------- 1 | import datetime 2 | 3 | class User: 4 | """A member of FriendFace. 5 | For now we are only storing their name and birthday. 6 | But soon we will store an uncomfortable amount of of user infos""" 7 | 8 | def __init__(self, full_name, birthday): 9 | self.full_name = full_name 10 | self.birthday = birthday #yymmdd 11 | 12 | #Extract first and last names 13 | name_pieces = full_name.split(" ") 14 | self.first_name = name_pieces[0] 15 | self.last_name = name_pieces[-1] 16 | 17 | def age(self): 18 | """Return the age of the user in years.""" 19 | today = datetime.date(2001, 5, 12) 20 | yy = int(self.birthday[0:4]) 21 | mm = int(self.birthday[4:6]) 22 | dd = int(self.birthday[6:8]) 23 | dob = datetime.date(yy, mm, dd) #date of birth 24 | age_in_days = (today - dob).days 25 | age_in_years = age_in_days / 365 26 | return int(age_in_years) 27 | 28 | user = User("Dave Bowman", "19710315") 29 | #print(user.first_name) 30 | print(user.first_name) 31 | #print(user.last_name) 32 | #print(user.birthday) 33 | print(user.age()) 34 | 35 | -------------------------------------------------------------------------------- /chapter6/trial.py: -------------------------------------------------------------------------------- 1 | def sum(i1, i2): 2 | result = 0 3 | for i in range(i1, i2 + 1): 4 | result += i 5 | 6 | return result 7 | 8 | def main(): 9 | print("The sum from 1 to 10 is", sum(1, 10)) 10 | print("The sum from 20 to 37 is", + sum(20, 37)) 11 | print("The sum from 35 to 49 is", + sum(35, 49)) 12 | 13 | main() 14 | -------------------------------------------------------------------------------- /chapter6/trial2.py: -------------------------------------------------------------------------------- 1 | def main(): 2 | x = 1 3 | print("Before the call, x is", x) 4 | 5 | increment(x) 6 | 7 | print("After the call, x is", x) 8 | 9 | def increment(n): 10 | 11 | n += 1 12 | 13 | print("\tn inside the function is", n) 14 | 15 | main() # Call the main functi 16 | -------------------------------------------------------------------------------- /chapter7/7.1.py: -------------------------------------------------------------------------------- 1 | class rectangle: 2 | def __init__(self, width = 1, height = 2): 3 | self.width = width 4 | self.height = height 5 | 6 | #Method to compute area 7 | def getArea(self): 8 | return (self.width * self.height) 9 | #print(area) 10 | 11 | #Method to computr perimeter 12 | def getPerimeter(self): 13 | return ((self.width + self.height) * 2) 14 | 15 | 16 | Rectangle = rectangle(1, 2) 17 | #print(Rectangle.getArea()) 18 | -------------------------------------------------------------------------------- /chapter7/7.10.py: -------------------------------------------------------------------------------- 1 | import time 2 | 3 | class Time: 4 | def __init__(self): 5 | self.setTime(int(time.time())) 6 | 7 | def getHour(self): 8 | return self.__hour 9 | 10 | def getMinute(self): 11 | return self.__minute 12 | 13 | def getSecond(self): 14 | return self.__second 15 | 16 | def setTime(self, elapsedTime): 17 | self.__second = elapsedTime % 60 18 | totMins = elapsedTime // 60 19 | self.__minute = totMins % 60 20 | totHours = (totMins // 60)-5 21 | self.__hour = (totHours % 24) 22 | 23 | def main(): 24 | curTime = Time() 25 | print("Current time is " + str(curTime.getHour()) + ":" + str(curTime.getMinute()) + ":" + str(curTime.getSecond())) 26 | 27 | elapseTime = eval(input("Enter the elapsed time: ")) 28 | curTime.setTime(elapseTime) 29 | print("The hour:minute:second for elapsed time is " + str(curTime.getHour()) + ":" + str(curTime.getMinute()) + ":" + str(curTime.getSecond())) 30 | 31 | main() 32 | -------------------------------------------------------------------------------- /chapter7/7.2.py: -------------------------------------------------------------------------------- 1 | class stock: 2 | def __init__(self, symbol, name, previousClosingPrice, currentPrice): 3 | self.__symbol = symbol 4 | self.__name = name 5 | self.__previousClosingPrice = previousClosingPrice 6 | self.__currentPrice = currentPrice 7 | 8 | def getName(self): 9 | return self.__name 10 | 11 | def getSymbol(self): 12 | return self.__symbol 13 | 14 | def setPreviousClosingPrice(self, previousClosingPrice): 15 | previousClosingPrice = self.__previousClosingPrice 16 | return previousClosingPrice 17 | 18 | def setCurrentPrice(self, currentPrice): 19 | currentPrice = self.__currentPrice 20 | return currentPrice 21 | 22 | def getChangePercent(self): 23 | return (currentPrice - previousClosingPrice) / 100 24 | 25 | Stock = stock() 26 | Stock.name = input("Enter the stock name: ") 27 | Stock.symbol = input("Enter the symbol: ") 28 | Stock.previousClosingPrice = eval(input("Enter previousClosingPrice: ")) 29 | Stock.currentPrice = eval(input("Enter current price: ")) 30 | -------------------------------------------------------------------------------- /chapter7/7.5.py: -------------------------------------------------------------------------------- 1 | #Program to make a n sided regular Polygon using classes 2 | import math 3 | 4 | class RegularPolygon(): 5 | def __init__(self=1,n=3,side=1,x=0,y=0): 6 | self.n=n 7 | self.side=side 8 | self.x=x 9 | self.y=y 10 | 11 | def getPerimeter(self): 12 | return self.n*self.side 13 | 14 | def getArea(self): 15 | return ((self.n)*(self.side)**2)/(4*(math.tan(math.pi/self.n))) 16 | 17 | def main(): 18 | polygon1=RegularPolygon() 19 | polygon2=RegularPolygon(6,4) 20 | polygon3=RegularPolygon(10,4,5.6,7.8) 21 | 22 | 23 | print("Polygon1 perimeter is:",polygon1.getPerimeter(),"\n polygon1 Area is:",polygon1.getArea()) 24 | print("Polygon2 perimeter is:",polygon2.getPerimeter(),"\n polygon2 Area is:",polygon2.getArea()) 25 | print("polygon3 perimeter is:",polygon3.getPerimeter(),"\n polygon3 Area is:",polygon3.getArea()) 26 | 27 | main() -------------------------------------------------------------------------------- /chapter7/7.7.py: -------------------------------------------------------------------------------- 1 | #Program to solve linear equations 2 | import math 3 | 4 | class LinearEquation(): 5 | def __init__(self,a,b,c,d,e,f): 6 | self.a=a 7 | self.b=b 8 | self.c=c 9 | self.d=d 10 | self.e=e 11 | self.f=f 12 | 13 | def getA(self): 14 | return self.a 15 | def getB(self): 16 | return self.b 17 | def getC(self): 18 | return self.c 19 | def getD(self): 20 | return self.d 21 | def getE(self): 22 | return self.e 23 | def getF(self): 24 | return self.f 25 | 26 | def isSolvable(self): 27 | if (self.a*self.d)-(self.b*self.c)==0: 28 | return True 29 | 30 | def getX(self): 31 | return ((self.e*self.d)-(self.b*self.f))/((self.a*self.d)-(self.b*self.c)) 32 | 33 | def getY(self): 34 | return ((self.a*self.f)-(self.e*self.c))/((self.a*self.d)-(self.b*self.c)) 35 | 36 | 37 | def main(): 38 | a,b,c,d,e,f = eval(input("Enter Value for a,b,c,d,e,f: ")) 39 | 40 | equation=LinearEquation(a,b,c,d,e,f) 41 | 42 | if equation.isSolvable(): 43 | print("The Equation has no solution") 44 | else: 45 | print("The value for x:",equation.getX()) 46 | print("The value for y:",equation.getY()) 47 | 48 | 49 | main() -------------------------------------------------------------------------------- /chapter7/7.8.py: -------------------------------------------------------------------------------- 1 | # Liang 7.8 2 | import time 3 | 4 | class StopWatch: 5 | 6 | def __init__(self): 7 | self.__startTime = time.time() 8 | 9 | def getStartTime(self): 10 | return self.__startTime 11 | 12 | def getEndTime(self): 13 | return self.__endTime 14 | 15 | def start(self): 16 | self.__startTime = time.time() 17 | 18 | def stop(self): 19 | self.__endTime = time.time() 20 | 21 | def getElapsedTime(self): 22 | return round(self.__endTime - self.__startTime, 3) 23 | 24 | def main(): 25 | watch = StopWatch() 26 | nSum = 0 27 | LIMIT = int(1e6) 28 | 29 | watch.start() 30 | for i in range(LIMIT): 31 | nSum += 1 32 | 33 | watch.stop() 34 | print ('Execution time: %.3f' % watch.getElapsedTime()) 35 | 36 | if __name__ == '__main__': 37 | main() 38 | -------------------------------------------------------------------------------- /chapter7/7.9.py: -------------------------------------------------------------------------------- 1 | #Program to find the intersecting point of 2 lines 2 | import math 3 | 4 | class LinearEquation(): 5 | def __init__(self,a,b,c,d,e,f): 6 | self.a=a 7 | self.b=b 8 | self.c=c 9 | self.d=d 10 | self.e=e 11 | self.f=f 12 | 13 | def getA(self): 14 | return self.a 15 | def getB(self): 16 | return self.b 17 | def getC(self): 18 | return self.c 19 | def getD(self): 20 | return self.d 21 | def getE(self): 22 | return self.e 23 | def getF(self): 24 | return self.f 25 | 26 | def isSolvable(self): 27 | if (self.a*self.d)-(self.b*self.c)==0: 28 | return True 29 | 30 | def getX(self): 31 | return ((self.e*self.d)-(self.b*self.f))/((self.a*self.d)-(self.b*self.c)) 32 | 33 | def getY(self): 34 | return ((self.a*self.f)-(self.e*self.c))/((self.a*self.d)-(self.b*self.c)) 35 | 36 | 37 | def main(): 38 | x1,y1,x2,y2=eval(input("Enter the endpoints of the first line segment")) 39 | x3,y3,x4,y4=eval(input("Enter the endpoints of the second line segment")) 40 | a=y1-y2 41 | b=(-x1)+x2 42 | c=y3-y4 43 | d=(-x3)+x4 44 | e=-y1*(x1-x2)+(y1-y2)*x1 45 | f=-y3*(x3-x4)+(y3-y4)*x3 46 | 47 | temp=LinearEquation( a, b, c, d, e, f) 48 | 49 | if temp.isSolvable(): 50 | print("The two lines are parallel") 51 | else: 52 | print("The intersecting point is: (",temp.getX(),",",temp.getY(),")") 53 | 54 | main() 55 | -------------------------------------------------------------------------------- /chapter8/8.1.py: -------------------------------------------------------------------------------- 1 | # Liang 8.1 2 | 3 | def checkSSN(SSN): 4 | if len(SSN) == 3 and SSN[0]//1000 == 0 and SSN[1]//100 == 0 and SSN[2]//10000 == 0: 5 | return 'Valid SSN' 6 | else: 7 | return 'Invalid SSN' 8 | 9 | def main(): 10 | SSN = input('Enter a Social Security Number (ddd-dd-dddd): ').split('-') 11 | print (checkSSN([int(d) for d in SSN])) 12 | 13 | if __name__ == '__main__': 14 | main() 15 | -------------------------------------------------------------------------------- /chapter8/8.12.py: -------------------------------------------------------------------------------- 1 | # Liang 8.12 2 | 3 | def findGenes(genome): 4 | genes = '' 5 | itr = 0 6 | triplet = ['TAG', 'TAA', 'TGA'] 7 | genome = genome.replace('ATG', ' ATG').split() 8 | 9 | for gene in genome: 10 | if gene.startswith('ATG') and 'TAG' in gene or 'TAA' in gene or 'TGA' in gene: 11 | while gene.rfind(triplet[itr]) < 0: # Locate the triplet in gene 12 | itr += 1 13 | if len(gene[3:gene.rfind(triplet[itr])]) % 3 == 0: # Extract the gene from sub-genome 14 | genes += gene[3:gene.rfind(triplet[itr])] + ' ' 15 | itr = 0 16 | 17 | if len(genes) > 2: 18 | return genes 19 | else: 20 | return 'No gene found' 21 | 22 | def main(): 23 | genome = input('Enter a genome string: ') 24 | 25 | if findGenes(genome).startswith('No'): 26 | print (findGenes(genome)) 27 | else: 28 | for gene in findGenes(genome).split(): 29 | print (gene) 30 | 31 | if __name__ == '__main__': 32 | main() 33 | -------------------------------------------------------------------------------- /chapter8/8.13.py: -------------------------------------------------------------------------------- 1 | ''' Function to find the longest common prefix in two strings''' 2 | 3 | def prefix(s1, s2): 4 | preStr ="" 5 | if len(s1) <= len(s2): 6 | n = len(s1) 7 | else: 8 | n = len(s2) 9 | 10 | for i in range(0, n): 11 | if s1[i] == s2[i]: 12 | preStr = preStr + s1[i] 13 | else: 14 | break 15 | 16 | return preStr 17 | 18 | 19 | def main(): 20 | str1 = input("Enter the first string: ") 21 | str2 = input("Enter the second string: ") 22 | x = prefix(str1, str2) 23 | print("Longest prefix of String1: ", str1, "and String2: ", str2,"is :", x) 24 | 25 | main() -------------------------------------------------------------------------------- /chapter8/8.17.py: -------------------------------------------------------------------------------- 1 | ''' The Point Class ''' 2 | 3 | class Point(): 4 | def __init__(self,x = 0,y= 0): 5 | self.x=x 6 | self.y=y 7 | 8 | def __str__(self): 9 | s = "("+ self.x + "," + self.y +")" 10 | return s 11 | 12 | def getX(self): 13 | return self.x 14 | def getY(self): 15 | return self.y 16 | 17 | def distance(self, P1): 18 | x2 = P1.getX() 19 | y2 = P1.getY() 20 | D = ((self.x-x2)**2 + (self.y-y2)**2)**.5 21 | return D 22 | 23 | def isNearby(self, P1): 24 | if(self.distance(P1) <= 5): 25 | print("The points are near each other") 26 | else: 27 | print("The points are not near each other") 28 | 29 | 30 | def main(): 31 | x1,y1,x2,y2 = eval(input("Enter two points x1,y1,x2,y2: ")) 32 | P1 = Point(x1,y1) 33 | P2 = Point(x2,y2) 34 | 35 | print("The distance between the two points is", P1.distance(P2)) 36 | P1.isNearby(P2) 37 | 38 | main() 39 | -------------------------------------------------------------------------------- /chapter8/8.19.py: -------------------------------------------------------------------------------- 1 | # Liang 8.19 2 | 3 | class Rectangle2D: 4 | def __init__(self, x=0, y=0, width=0, height=0): 5 | self.x = x 6 | self.y = y 7 | self.width = width 8 | self.height = height 9 | 10 | def getX(self): 11 | return self.x 12 | 13 | def getY(self): 14 | return self.y 15 | 16 | def getWidth(self): 17 | return self.width 18 | 19 | def getHeight(self): 20 | return self.height 21 | 22 | def setX(self, x): 23 | self.x = x 24 | 25 | def setY(self, y): 26 | self.y = y 27 | 28 | def setWidth(self, width): 29 | self.width = width 30 | 31 | def setHeight(self, height): 32 | self.height = height 33 | 34 | def getArea(self): 35 | return self.width * self.height 36 | 37 | def getPerimeter(self): 38 | return 2 * (self.width + self.height) 39 | 40 | def containsPoint(self, x, y): 41 | return abs(x - self.x) <= self.width/2 and abs(y - self.y) <= self.height/2 42 | 43 | def contains(self, other): 44 | return ((self.x <= other.x ) and (self.x <= self.width)) \ 45 | and ((other.x + other.width) <= (self.x + self.width)) \ 46 | and ((other.y + other.height) <= (self.y + self.height)) 47 | 48 | def overlaps(self, other): 49 | return not(self.x <= other.x or self.x <= self.width \ 50 | or ((other.x + other.width) <= (self.x + self.width)) \ 51 | or ((other.y + other.height) <= (self.y + self.height))) 52 | 53 | def __contains__(self, other): 54 | return ((self.x >= other.x) and (self.y >= other.y)) \ 55 | and ((other.x + other.width) >= (self.x + self.width)) \ 56 | and ((other.y + other.height) >= (self.y + self.height)) 57 | 58 | def __cmp__(self, other): 59 | if self.getArea() > other.getArea(): 60 | return 1 61 | elif self.getArea() < other.getArea(): 62 | return -1 63 | else: 64 | return 0 65 | 66 | def __lt__(self, other): 67 | return self.__cmp__(other) < 0 68 | 69 | def __le__(self, other): 70 | return self.__cmp__(other) <= 0 71 | 72 | def __eq__(self, other): 73 | return self.__cmp__(other) == 0 74 | 75 | def __ne__(self, other): 76 | return self.__cmp__(other) != 0 77 | 78 | def __gt__(self, other): 79 | return self.__cmp__(other) > 0 80 | 81 | def __ge__(self, other): 82 | return self.__cmp__(other) >= 0 83 | 84 | 85 | def main(): 86 | r1 = input('Enter x, y, width, height: ') 87 | r2 = input('Enter x, y, width, height: ') 88 | r1 = [float(v) for v in r1.split(',')] 89 | r2 = [float(v) for v in r2.split(',')] 90 | 91 | r1 = Rectangle2D(r1[0], r1[1], r1[2], r1[3]) 92 | r2 = Rectangle2D(r2[0], r2[1], r2[2], r2[3]) 93 | 94 | print ('Area for %s is %0.1f' % ('r1', r1.getArea())) 95 | print ('Perimeter for %s is %0.1f' % ('r1', r1.getPerimeter())) 96 | print ('Area for %s is %0.1f' % ('r2', r2.getArea())) 97 | print ('Perimeter for %s is %0.1f' % ('r2', r2.getPerimeter())) 98 | print ('%s contains the center of %s? %r' % ('r1', 'r2', r1.containsPoint(r2.x, r2.y))) 99 | print ('%s contains %s? %r' % ('r1', 'r2', r1.contains(r2))) 100 | print ('%s overlaps %s %r' % ('r1', 'r2', r1.overlaps(r2))) 101 | 102 | 103 | if __name__ == '__main__': 104 | main() 105 | -------------------------------------------------------------------------------- /chapter8/8.2.py: -------------------------------------------------------------------------------- 1 | ''' Program to check whether a string is a substring of another string, without using inbuilt functions''' 2 | 3 | def find(str1, str2): 4 | for i in range(0, len(str2)): 5 | if str2[i] == str1[0]: 6 | k=i 7 | for j in range(0, len(str1)): 8 | if str2[k] == str1[j]: 9 | if j == len(str1)-1: 10 | return True 11 | k +=1 12 | else: 13 | break 14 | 15 | return False 16 | 17 | 18 | def main(): 19 | str1 = input("Enter the first string: ") 20 | str2 = input("Enter the second string: ") 21 | x = find(str1, str2) 22 | if (x): 23 | print("String ", str1, "is a substring of String ", str2) 24 | else: 25 | print("String ", str1, "is not a substring of String ", str2) 26 | 27 | main() -------------------------------------------------------------------------------- /chapter8/8.3.py: -------------------------------------------------------------------------------- 1 | ''' Write a program to check passwords based on following rules: 2 | A password must have at least eight characters. 3 | A password must consist of only letters and digits. 4 | A password must contain at least two digits. 5 | ''' 6 | 7 | def CheckPassword(str1): 8 | countChr = 0 9 | countNum = 0 10 | 11 | if(len(str1)>=8): 12 | for i in range(0, len(str1)): 13 | if (ord(str1[i].lower())>= 97 and ord(str1[i].lower()) <= 122): 14 | countChr +=1 15 | elif ord(str1[i]) >=48 and ord(str1[i])<=57: 16 | countNum +=1 17 | else: 18 | return False 19 | if(countNum >=2 and countChr> 0): 20 | return True 21 | else: 22 | return False 23 | else: 24 | return False 25 | 26 | 27 | def main(): 28 | pwd = input("Enter your password: ") 29 | if (CheckPassword(pwd)): 30 | print("Valid Password") 31 | else: 32 | print("Invalid Password") 33 | 34 | main() -------------------------------------------------------------------------------- /chapter8/8.6.py: -------------------------------------------------------------------------------- 1 | ''' Function to count the letters in a string ''' 2 | 3 | def countLetters(s): 4 | count = 0 5 | for i in range(0, len(s)): 6 | if (ord(s[i].lower())>= 97 and ord(s[i].lower()) <= 122): 7 | count +=1 8 | 9 | return count 10 | 11 | def main(): 12 | s = input("Enter a string: ") 13 | print("The number of letters in ",s,"is: ", countLetters(s)) 14 | 15 | main() -------------------------------------------------------------------------------- /chapter8/8.7.py: -------------------------------------------------------------------------------- 1 | # Liang 8.7 2 | 3 | def getNum(uppercaseLetter): 4 | numMap = (('A', 'B', 'C'), ('D', 'E', 'F'), ('G', 'H', 'I'), ('J', 'K', 'L'),\ 5 | ('M', 'N', 'O'), ('P', 'Q', 'R', 'S'), ('T', 'U', 'V'), ('W', 'X', 'Y', 'Z')) 6 | for num in numMap: 7 | for letter in num: 8 | if letter == uppercaseLetter: 9 | return numMap.index(num) + 2 10 | 11 | def letterToNum(word): 12 | pNum = '' 13 | for letter in word: 14 | pNum += str(getNum(letter.upper())) 15 | return pNum 16 | 17 | def main(): 18 | phoneNum = input('Enter a phone number with/without dashes: ').split('-') 19 | 20 | if len(phoneNum) == 3: 21 | print ('%s-%s-%s' % (phoneNum[0], phoneNum[1], letterToNum(phoneNum[2]))) 22 | else: 23 | print ('%s%s' % (phoneNum[0][:6], letterToNum(phoneNum[0][6:]))) 24 | 25 | if __name__ == '__main__': 26 | main() 27 | -------------------------------------------------------------------------------- /chapter8/8.8.py: -------------------------------------------------------------------------------- 1 | # Liang 8.8 2 | 3 | def binaryToDecimal(binaryString): 4 | i = len(binaryString) 5 | dec = 0 6 | while (i > 0): 7 | if (binaryString[i-1] == '1'): 8 | dec += 2**(len(binaryString) - i) 9 | i -= 1 10 | return dec 11 | 12 | def main(): 13 | binary = input('Enter a binary: ') 14 | print ('Decimal Value: %d' % binaryToDecimal(binary)) 15 | 16 | if __name__ == '__main__': 17 | main() 18 | -------------------------------------------------------------------------------- /chapter8/8.9.py: -------------------------------------------------------------------------------- 1 | ''' Function to convert a binary number to hexadecimal ''' 2 | 3 | def binaryToHex(binaryValue): 4 | bin1 = binaryValue 5 | base = 1 6 | dec = 0 7 | HexValue = "" 8 | # First convert binary to decimal 9 | while (bin1 > 0): 10 | rem = bin1 % 10 11 | dec = dec + rem * base; 12 | base = base * 2; 13 | bin1 = bin1 // 10; 14 | 15 | # Then convert decimal to hexadecimal 16 | while dec != 0 : 17 | temp = dec % 16 18 | if( temp < 10): 19 | temp = temp + 48 20 | else: 21 | temp = temp + 55; 22 | HexValue = chr(temp) + HexValue 23 | dec = dec // 16; 24 | 25 | 26 | return HexValue 27 | 28 | def main(): 29 | bin1 = eval(input("Enter the binary number: ")) 30 | print("The hexadecimal equivalent of ",bin1,"is: ", binaryToHex(bin1)) 31 | 32 | main() --------------------------------------------------------------------------------