├── A_Practical_Introduction_to_Python_Programming_Heinold.pdf ├── Chapter 1 Exercise ├── Q_1.py ├── Q_2.py ├── Q_3.py ├── Q_4.py ├── Q_5.py ├── Q_6.py ├── Q_7.py ├── Q_8.py └── Q_9.py ├── Chapter 11 Exercise ├── Q_1.py ├── Q_10.py ├── Q_12.py ├── Q_14.py ├── Q_16.py ├── Q_2.py ├── Q_3.py ├── Q_4.py ├── Q_5.py ├── Q_6.py ├── Q_7.py ├── Q_8.py └── Q_9.py ├── Chapter 12 Exercise ├── Q_1 │ ├── Q_1.py │ ├── class_scores.txt │ ├── scores2.txt │ └── student2.txt ├── Q_10 │ ├── Q_10.py │ └── wordlist.txt ├── Q_11 │ ├── Q_11.py │ └── wordlist.txt ├── Q_12 │ ├── Q_12.py │ └── wordlist.txt ├── Q_13 │ ├── Q_13.py │ └── wordlist.txt ├── Q_14 │ ├── Q_14.py │ └── wordlist.txt ├── Q_15 │ ├── Q_15.py │ └── wordlist.txt ├── Q_2 │ ├── Q_2.py │ └── grades.txt ├── Q_3 │ ├── Q_3.py │ └── logfile.txt ├── Q_4 │ ├── Q_4.py │ ├── student.txt │ └── student2.txt ├── Q_5 │ ├── Q_5.py │ └── namelist.txt ├── Q_6 │ ├── Q_6.py │ └── namelist.txt ├── Q_7 │ ├── Q_7.py │ └── baseball.txt ├── Q_8 │ ├── Q_8.py │ └── scores.txt └── Q_9 │ ├── Q_9.py │ └── expenses.txt ├── Chapter 13 Exercise ├── Q_1.py ├── Q_10.py ├── Q_11.py ├── Q_12.py ├── Q_14.py ├── Q_15.py ├── Q_16.py ├── Q_17.py ├── Q_18.py ├── Q_19.py ├── Q_2.py ├── Q_20.py ├── Q_21.py ├── Q_3.py ├── Q_4.py ├── Q_5.py ├── Q_6.py ├── Q_7.py ├── Q_8.py └── Q_9.py ├── Chapter 14 Exercise ├── Q_1.py ├── Q_10.py ├── Q_11.py ├── Q_2.py ├── Q_3.py ├── Q_4.py ├── Q_5.py ├── Q_6.py └── Q_7.py ├── Chapter 2 Exercise ├── Q_1.py ├── Q_10.py ├── Q_11.py ├── Q_12.py ├── Q_13.py ├── Q_14.py ├── Q_2.py ├── Q_3.py ├── Q_4.py ├── Q_5.py ├── Q_6.py ├── Q_7.py ├── Q_8.py └── Q_9.py ├── Chapter 3 Exercise ├── Q_1.py ├── Q_10.py ├── Q_11.py ├── Q_12.py ├── Q_13.py ├── Q_14.py ├── Q_15.py ├── Q_16.py ├── Q_17.py ├── Q_18.py ├── Q_19.py ├── Q_2.py ├── Q_3.py ├── Q_4.py ├── Q_5.py ├── Q_6.py ├── Q_7.py ├── Q_8.py └── Q_9.py ├── Chapter 4 Exercise ├── Q_1.py ├── Q_10.py ├── Q_11.py ├── Q_12.py ├── Q_13.py ├── Q_2.py ├── Q_3.py ├── Q_4.py ├── Q_5.py ├── Q_6.py ├── Q_7.py ├── Q_8.py └── Q_9.py ├── Chapter 5 Exercise ├── Q_1.py ├── Q_10.py ├── Q_11.py ├── Q_12.py ├── Q_14.py ├── Q_2.py ├── Q_3.py ├── Q_4.py ├── Q_5.py ├── Q_6.py ├── Q_7.py ├── Q_8.py └── Q_9.py ├── Chapter 6 Exercise ├── Q_1.py ├── Q_10.py ├── Q_11.py ├── Q_12.py ├── Q_13.py ├── Q_14.py ├── Q_15.py ├── Q_16.py ├── Q_17.py ├── Q_18.py ├── Q_19.py ├── Q_2.py ├── Q_20.py ├── Q_21.py ├── Q_22.py ├── Q_3.py ├── Q_4.py ├── Q_5.py ├── Q_6.py ├── Q_7.py ├── Q_8.py └── Q_9.py ├── Chapter 7 Exercise ├── Q_1.py ├── Q_10.py ├── Q_11.py ├── Q_12.py ├── Q_13.py ├── Q_14.py ├── Q_15.py ├── Q_2.py ├── Q_3.py ├── Q_4.py ├── Q_5.py ├── Q_6.py ├── Q_7.py ├── Q_8.py └── Q_9.py ├── Chapter 8 Exercise ├── Q_1.py ├── Q_10.py ├── Q_12.py ├── Q_13.py ├── Q_14.py ├── Q_17.py ├── Q_18.py ├── Q_19.py ├── Q_2.py ├── Q_20.py ├── Q_22.py ├── Q_23.py ├── Q_3.py ├── Q_4.py ├── Q_5.py ├── Q_6.py ├── Q_7.py └── Q_9.py ├── Chapter 9 Exercise ├── Q_1.py ├── Q_10.py ├── Q_11.py ├── Q_12.py ├── Q_14.py ├── Q_15.py ├── Q_16.py ├── Q_17.py ├── Q_18.py ├── Q_2.py ├── Q_3.py ├── Q_4.py ├── Q_5.py ├── Q_6.py ├── Q_7.py ├── Q_8.py └── Q_9.py └── README.md /A_Practical_Introduction_to_Python_Programming_Heinold.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/henrytirla/Practical-Introduction-to-python/1e7cf5dc0268b24d984c2305d616091fd4e995a8/A_Practical_Introduction_to_Python_Programming_Heinold.pdf -------------------------------------------------------------------------------- /Chapter 1 Exercise/Q_1.py: -------------------------------------------------------------------------------- 1 | """"1. Print a box like the one below. 2 | ******************* 3 | ******************* 4 | ******************* 5 | *******************""" 6 | 7 | for rows in range(5): 8 | for columns in range(5): 9 | 10 | print(" *", end=" ") 11 | 12 | print() -------------------------------------------------------------------------------- /Chapter 1 Exercise/Q_2.py: -------------------------------------------------------------------------------- 1 | """Print a box like the one below. 2 | ******************* 3 | * * 4 | * * 5 | *******************""" 6 | 7 | 8 | for rows in range(5): 9 | for columns in range(5): 10 | if (rows == 0 or rows == 5-1 or columns == 0 or columns == 5-1): 11 | print("*" , end=" ") 12 | 13 | else: 14 | print(" ", end=" ") 15 | 16 | print() -------------------------------------------------------------------------------- /Chapter 1 Exercise/Q_3.py: -------------------------------------------------------------------------------- 1 | """ Print a triangle like the one below. 2 | * 3 | ** 4 | *** 5 | **** """ 6 | 7 | 8 | for rows in range (5): 9 | for colums in range(rows): 10 | print("*", end=" ") 11 | 12 | print() -------------------------------------------------------------------------------- /Chapter 1 Exercise/Q_4.py: -------------------------------------------------------------------------------- 1 | 2 | 3 | """ Write a program that computes and prints the result of 4 | 512 -282/47.48+5 5 | . It is roughly .1017. """ 6 | 7 | a = 512 8 | b = 282 9 | c = 47.48 10 | d = 5 11 | 12 | solve = ((a -b)/(c + d)) 13 | 14 | print(solve) -------------------------------------------------------------------------------- /Chapter 1 Exercise/Q_5.py: -------------------------------------------------------------------------------- 1 | """Ask the user to enter a number. Print out the square of the number, but use the sep optional 2 | argument to print it out in a full sentence that ends in a period. Sample output is shown 3 | below.""" 4 | 5 | num = eval(input("Enter a Number: ")) 6 | 7 | print("The square of",num,"is",num*num,".",sep=" ") 8 | -------------------------------------------------------------------------------- /Chapter 1 Exercise/Q_6.py: -------------------------------------------------------------------------------- 1 | """"Ask the user to enter a number x. Use the sep optional argument to print out x, 2x, 3x, 4x, 2 | and 5x, each separated by three dashes, like below.""" 3 | 4 | num = eval(input("Enter a number: ")) 5 | print(num ,2*num , 3*num ,4*num , 5*num , sep='--') -------------------------------------------------------------------------------- /Chapter 1 Exercise/Q_7.py: -------------------------------------------------------------------------------- 1 | """Write a program that asks the user for a weight in kilograms and converts it to pounds. There 2 | are 2.2 pounds in a kilogram.""" 3 | 4 | kg = eval(input("Enter a your Weight in Kg: ")) 5 | print("Your weight in pounds is",kg * 2.2) 6 | -------------------------------------------------------------------------------- /Chapter 1 Exercise/Q_8.py: -------------------------------------------------------------------------------- 1 | """Write a program that asks the user to enter three numbers (use three separate input statements). 2 | Create variables called total and average that hold the sum and average of the 3 | three numbers and print out the values of total and average.""" 4 | 5 | num1 ,num2 ,num3 =eval(input("Enter 3 Numbers: ")) 6 | 7 | total = num1 + num2 + num3 8 | average = total/3 9 | 10 | print("Total number is ",total) 11 | print("Average number is", average) -------------------------------------------------------------------------------- /Chapter 1 Exercise/Q_9.py: -------------------------------------------------------------------------------- 1 | """A lot of cell phones have tip calculators. Write one. Ask the user for the price of the meal and 2 | the percent tip they want to leave. Then print both the tip amount and the total bill with the 3 | tip included.""" 4 | 5 | meal_price = eval(input("Enter Price of your meal: ")) 6 | tip_percent = eval(input("Enter Tip Percentage")) 7 | 8 | print("Price of the meal is: ",meal_price,"Percentage of tip is",tip_percent) 9 | -------------------------------------------------------------------------------- /Chapter 11 Exercise/Q_1.py: -------------------------------------------------------------------------------- 1 | # Write a program that repeatedly asks the user to enter product names and prices. Store all 2 | # of these in a dictionary whose keys are the product names and whose values are the prices. 3 | # When the user is done entering products and prices, allow them to repeatedly enter a product 4 | # name and print the corresponding price or a message if the product is not in the dictionary. 5 | 6 | 7 | product_num = eval(input("Enter Number of products: ")) 8 | my_dict ={} 9 | for x in range(product_num): 10 | productName = input("Enter Product Name: ") 11 | productPrice = int(input("Enter Product Price")) 12 | my_dict[productName] = productPrice 13 | 14 | 15 | while True: 16 | productName = input("Enter Product name to get Price") 17 | if productName in my_dict: 18 | print("The price for your product is ", my_dict[productName]) 19 | 20 | else: 21 | print("This product is not found in dictionary") 22 | 23 | 24 | print(my_dict) 25 | 26 | -------------------------------------------------------------------------------- /Chapter 11 Exercise/Q_10.py: -------------------------------------------------------------------------------- 1 | """ 2 | Using the card dictionary from earlier in the chapter run a Monte Carlo simulation to estimate 3 | the probability of being dealt a flush in a five card hand. See Exercise 32 of Chapter 10 for 4 | more about Monte Carlo simulations. 5 | """ 6 | 7 | # Note, chances to get a flush in 5-card is about 1 out of 509 hands. 8 | 9 | from enum import Enum 10 | from random import sample 11 | 12 | class Cards(Enum): 13 | DECK = [{'value':i, 'suit':c} 14 | for c in ['spades', 'clubs', 'hearts', 'diamonds'] 15 | for i in range(2,15)] 16 | 17 | def validate_num(message): 18 | valid = False 19 | while not valid: 20 | try: 21 | user_input = int(input(message)) 22 | if user_input > 0: 23 | valid = True 24 | else: 25 | print('\nEnter a huge number for how many hands to play.') 26 | except ValueError: 27 | print('\nEnter a valid integer.') 28 | return user_input 29 | 30 | def flush(COUNT, num): 31 | for i in range(num): 32 | hand = get_cards() 33 | if hand[0]['suit'] == hand[1]['suit'] == hand[2]['suit'] == hand[3]['suit'] == hand[4]['suit']: 34 | COUNT += 1 35 | else: 36 | pass 37 | return COUNT 38 | 39 | def get_cards(): 40 | rand_cards = sample(Cards.DECK.value, 5) 41 | return rand_cards 42 | 43 | def main(): 44 | COUNT = 0 45 | message = 'Enter the number of hands to play: ' 46 | num = validate_num(message) 47 | prob = flush(COUNT, num) 48 | print(f'\n{prob} hand(s) had a flush.\n') 49 | print(f'The probability to get a flush from {num} hands is {round((prob/num)*100, 3)}%.') 50 | 51 | if __name__ == '__main__': 52 | main() 53 | -------------------------------------------------------------------------------- /Chapter 11 Exercise/Q_12.py: -------------------------------------------------------------------------------- 1 | """ 2 | Below are the notes used in music: 3 | C C# D D# E F F# G G# A A# B 4 | 5 | The notes for the C major chord are C, E, G. A mathematical way to get this is that E is 4 steps 6 | past C and G is 7 steps past C. This works for any base. For example, the notes for D major 7 | are D, F#, A. We can represent the major chord steps as a list with two elements: [4,7]. The 8 | corresponding lists for some other chord types are shown below: 9 | 10 | Minor [3,7] Dominant seventh [4,7,10] 11 | Augmented fifth [4,8] Minor seventh [3,7,10] 12 | Minor fifth [4,6] Major seventh [4,7,11] 13 | Major sixth [4,7,9] Diminished seventh [3,6,10] 14 | Minor sixth [3,7,9] 15 | 16 | Write a program that asks the user for the key and the chord type and prints out the notes of 17 | the chord. Use a dictionary whose keys are the (musical) keys and whose values are the lists 18 | of steps. 19 | """ 20 | 21 | from enum import Enum 22 | 23 | class Music(Enum): 24 | KEY = ['C', 'C#', 'D', 'D#', 'E', 'F', 'F#', 'G', 'G#', 'A', 'A#', 'B'] 25 | 26 | CHORD_STEPS = {1:[4,7], 2:[3,7], 3:[4,8], 4:[4,6], 5:[4,7,9], 6:[3,7,9], 27 | 7:[4,7,10], 8:[3,7,10], 9:[4,7,11], 10:[3,6,10]} 28 | 29 | def validate_key(message_key): 30 | valid = False 31 | while not valid: 32 | try: 33 | user_input = input(message_key).capitalize() 34 | if user_input in Music.KEY.value: 35 | valid = True 36 | else: 37 | print('\nPlease enter a valid key.') 38 | except: 39 | pass 40 | return user_input 41 | 42 | def validate_chord(message_chord): 43 | valid = False 44 | while not valid: 45 | try: 46 | user_input = int(input(message_chord)) 47 | if user_input in Music.CHORD_STEPS.value.keys(): 48 | valid = True 49 | else: 50 | print('\nEnter a number from the given options.') 51 | except ValueError: 52 | print('\nInvalid. Enter an integer.') 53 | return user_input 54 | 55 | def get_notes(user_key, user_chord): 56 | notes = [] 57 | key_list_transform = [] 58 | for i in range(len(Music.KEY.value)): 59 | if user_key == Music.KEY.value[i]: 60 | notes.append(Music.KEY.value[i]) 61 | key_list_transform = Music.KEY.value[i:] + Music.KEY.value[:i] 62 | for j in range(len(key_list_transform)): 63 | if j in Music.CHORD_STEPS.value[user_chord]: 64 | notes.append(key_list_transform[j]) 65 | return notes 66 | 67 | def main(): 68 | print('The following below are the musical keys:') 69 | print(Music.KEY.value) 70 | message_key = 'Enter a musical key: ' 71 | user_key = validate_key(message_key) 72 | print('\nEnter 1 for chord type Major.') 73 | print('Enter 2 for chord type Minor.') 74 | print('Enter 3 for chord type Augmented Fifth.') 75 | print('Enter 4 for chord type Minor Fifth.') 76 | print('Enter 5 for chord type Major Sixth.') 77 | print('Enter 6 for chord type Minor Sixth.') 78 | print('Enter 7 for chord type Dominant Seventh.') 79 | print('Enter 8 for chord type Minor Seventh.') 80 | print('Enter 9 for chord type Major Seventh.') 81 | print('Enter 10 for chord type Diminshed Seventh.') 82 | message_chord = 'Enter a chord type: ' 83 | user_chord = validate_chord(message_chord) 84 | chord_notes = get_notes(user_key, user_chord) 85 | print(f'\nThe following are the chord notes: {chord_notes}.') 86 | 87 | if __name__ == '__main__': 88 | main() 89 | -------------------------------------------------------------------------------- /Chapter 11 Exercise/Q_14.py: -------------------------------------------------------------------------------- 1 | """Dictionaries provide a convenient way to store structured data. Here is an example dictionary: 2 | d=[{'name':'Todd', 'phone':'555-1414', 'email':'todd@mail.net'}, 3 | {'name':'Helga', 'phone':'555-1618', 'email':'helga@mail.net'}, 4 | {'name':'Princess', 'phone':'555-3141', 'email':''}, 5 | {'name':'LJ', 'phone':'555-2718', 'email':'lj@mail.net'}] 6 | Write a program that reads through any dictionary like this and prints the following: 7 | (a) All the users whose phone number ends in an 8 8 | (b) All the users that don’t have an email address listed 9 | 10 | 11 | """ 12 | 13 | d=[{'name':'Todd', 'phone':'555-1414', 'email':'todd@mail.net'}, 14 | {'name':'Helga', 'phone':'555-1618', 'email':'helga@mail.net'}, 15 | {'name':'Princess', 'phone':'555-3141', 'email':''}, 16 | {'name':'LJ', 'phone':'555-2718', 'email':'lj@mail.net'}] 17 | 18 | 19 | for dict in range(len(d)): 20 | #print(d[dict]) 21 | dd =d[dict ] 22 | for keys,values in dd.items(): 23 | #print(keys,values) 24 | if keys == "phone" and values[-1] == "8": 25 | print(dd) 26 | if keys == "email" and values =='': 27 | print(dd) 28 | -------------------------------------------------------------------------------- /Chapter 11 Exercise/Q_16.py: -------------------------------------------------------------------------------- 1 | """(a) Write a program that converts Roman numerals into ordinary numbers. Here are the 2 | conversions: M=1000, D=500, C=100, L=50, X=10, V=5 I=1. Don’t forget about things 3 | like IV being 4 and XL being 40. 4 | (b) Write a program that converts ordinary numbers into Roman numerals""" 5 | 6 | roman_literal={1 :"I",2:"II",3:"III",4:"IV",5:"V",6:"VI",7:"VII",8:"VIII",9:"IX",10:"X",11:"XI",12:"XII",13:"XIII",14:"XIV",15:"XV", 7 | 16:"XVI",17:"XVII",18:"XVIII",19:"XIX",20:"XX",50:"L",100:"C",500:"D",1000:"M"} 8 | 9 | 10 | # def roman_Covert(x): 11 | # 12 | # num_string= str(x) 13 | # res = [int(x) for x in str(x)] 14 | # 15 | # for key ,val in roman_literal.items(): 16 | # if x == key: 17 | # print(roman_literal[key]) 18 | # if x > key and x < key: 19 | # print(key) 20 | # 21 | # 22 | # 23 | # print(roman_Covert(20)) 24 | 25 | #return roman_literal[key] 26 | 27 | 28 | def int_to_roman(input): 29 | """ Convert an integer to a Roman numeral. """ 30 | 31 | if not isinstance(input, type(1)): 32 | raise (TypeError,"expected integer, got %s" % type(input)) 33 | if not 0 < input < 4000: 34 | raise (ValueError, "Argument must be between 1 and 3999") 35 | ints = (1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1) 36 | nums = ('M', 'CM', 'D', 'CD','C', 'XC','L','XL','X','IX','V','IV','I') 37 | result = [] 38 | for i in range(len(ints)): 39 | count = int(input / ints[i]) 40 | result.append(nums[i] * count) 41 | input -= ints[i] * count 42 | #print(result,"result") 43 | #print(input,"Input") 44 | return ''.join(result) 45 | 46 | 47 | print(int_to_roman(22)) 48 | -------------------------------------------------------------------------------- /Chapter 11 Exercise/Q_2.py: -------------------------------------------------------------------------------- 1 | """Using the dictionary created in the previous problem, allow the user to enter a dollar amount 2 | and print out all the products whose price is less than that amount.""" 3 | 4 | 5 | 6 | 7 | my_dict ={'Mercedez': '100','Ferrari':'200','Bugatti':'300'} 8 | print(my_dict) 9 | 10 | amt =eval(input("Enter Amount: $$")) 11 | for key ,values in my_dict.items(): 12 | if int(values) < amt: 13 | print (key ,"->",values) 14 | 15 | 16 | -------------------------------------------------------------------------------- /Chapter 11 Exercise/Q_3.py: -------------------------------------------------------------------------------- 1 | """For this problem, use the dictionary from the beginning of this chapter whose keys are month 2 | names and whose values are the number of days in the corresponding months. 3 | (a) Ask the user to enter a month name and use the dictionary to tell them how many days 4 | are in the month. 5 | (b) Print out all of the keys in alphabetical order. 6 | (c) Print out all of the months with 31 days. 7 | (d) Print out the (key-value) pairs sorted by the number of days in each month 8 | (e) Modify the program from part (a) and the dictionary so that the user does not have to 9 | know how to spell the month name exactly. That is, all they have to do is spell the first 10 | three letters of the month name correctly. 11 | """ 12 | import operator 13 | 14 | year ={"January":"31","Febuary":"28","March":"30","April":"30","May":"31","June":"30"} 15 | 16 | #a 17 | user_input= input("Enter Name of a month: ") 18 | #user_input = "March" 19 | for key, values in year.items(): 20 | if user_input == key: #change equality sign to in to answer d 21 | print( values) 22 | #break 23 | 24 | 25 | #b 26 | sorted_year ={key:year[key] for key in sorted(year)} 27 | print(sorted_year.keys()) 28 | 29 | #c 30 | for keys,values in year.items(): 31 | if int(values) == 31: 32 | 33 | print(keys) 34 | 35 | #d 36 | ##can sort months by changing itemgetter 37 | # variable to 0 38 | sorted_bymonthdays = dict(sorted(year.items(),key= operator.itemgetter(1))) 39 | print(sorted_bymonthdays) 40 | -------------------------------------------------------------------------------- /Chapter 11 Exercise/Q_4.py: -------------------------------------------------------------------------------- 1 | """Write a program that uses a dictionary that contains ten user names and passwords. The 2 | program should ask the user to enter their username and password. If the username is not in 3 | the dictionary, the program should indicate that the person is not a valid user of the system. If 4 | the username is in the dictionary, but the user does not enter the right password, the program 5 | should say that the password is invalid. If the password is correct, then the program should 6 | tell the user that they are now logged in to the system.""" 7 | user_dict ={"Henry":"1234","Thomas":"Larissa","Monique":"Gaga"} 8 | def CheckUser_Pass(x,y): 9 | for keys ,values in user_dict.items(): 10 | if keys == x and y == user_dict[keys]: 11 | return ("you are succesfully logged in",keys,user_dict[keys]) 12 | else: 13 | return ("Please do check your login details") 14 | 15 | 16 | 17 | x = input("Enter Username: ") 18 | y = input("Enter Your Password ") 19 | print(CheckUser_Pass(x,y)) 20 | -------------------------------------------------------------------------------- /Chapter 11 Exercise/Q_5.py: -------------------------------------------------------------------------------- 1 | """Repeatedly ask the user to enter a team name and the how many games the team won and 2 | how many they lost. Store this information in a dictionary where the keys are the team names 3 | and the values are lists of the form [wins, losses]. 4 | (a) Using the dictionary created above, allow the user to enter a team name and print out 5 | the team’s winning percentage. 6 | (b) Using the dictionary, create a list whose entries are the number of wins of each team. 7 | (c) Using the dictionary, create a list of all those teams that have winning records.""" 8 | 9 | 10 | def teamWIn(): 11 | numberofTeams = int(input("Enter Number of Teams: ")) 12 | team_dict={} 13 | score_list =[] 14 | winning_record =[] 15 | percentage_score = 0 16 | for team in range(numberofTeams): 17 | team_name = input("Enter Team Name: ") 18 | team_winning_score = int(input("Team Winning game: ")) 19 | team_dict.update({team_name:team_winning_score}) 20 | score_list.append(team_winning_score) 21 | winning_record.append(team_name) 22 | 23 | userinput = input("Enter team to check % of wins: ") 24 | for keys,values in team_dict.items(): 25 | 26 | if userinput == keys: 27 | score = team_dict[keys] 28 | percentage_score = (score/100)* 100 29 | 30 | return "Your teams list is {},Percentage win of team {}%, All team with winning record {}".format(team_dict,percentage_score,winning_record) 31 | 32 | 33 | 34 | 35 | 36 | 37 | print(teamWIn()) -------------------------------------------------------------------------------- /Chapter 11 Exercise/Q_6.py: -------------------------------------------------------------------------------- 1 | """Repeatedly ask the user to enter game scores in a format like team1 score1 - team2 score2. Store 2 | this information in a dictionary where the keys are the team names and the values are lists of 3 | the form [wins, losses].""" 4 | 5 | 6 | 7 | def teamInfo(): 8 | num_team =int(input("Enter Number Of Teams: ")) 9 | team_dict={} 10 | for team in range(num_team): 11 | key = input("Enter Team name: ") 12 | value =[] 13 | wins = int(input("Enter Win: ")) 14 | losses = int(input("Enter Losses: ")) 15 | value.extend((wins,losses)) 16 | team_dict.update({key:value}) 17 | 18 | return team_dict 19 | 20 | print(teamInfo()) -------------------------------------------------------------------------------- /Chapter 11 Exercise/Q_7.py: -------------------------------------------------------------------------------- 1 | """Create a 5 X 5 list of numbers. Then write a program that creates a dictionary whose keys are 2 | the numbers and whose values are the how many times the number occurs. Then print the 3 | three most common numbers.""" 4 | 5 | matrix_5= [1,2,3,4,5, 6 | 5,6,7,4,5, 7 | 6,7,8,0,3, 8 | 4,2,1,5,6, 9 | 7,8,9,0,5] 10 | 11 | def creatList(): 12 | matrix_dict={} 13 | for num in range(len(matrix_5)): 14 | key = matrix_5[num] 15 | value = matrix_5.count(key) 16 | matrix_dict.update({key:value}) 17 | return matrix_dict 18 | 19 | 20 | 21 | print(creatList()) 22 | 23 | 24 | 25 | 26 | -------------------------------------------------------------------------------- /Chapter 11 Exercise/Q_8.py: -------------------------------------------------------------------------------- 1 | """"Using the card dictionary from earlier in this chapter, create a simple card game that deals 2 | two players three cards each. The player with the highest card wins. If there is a tie, then 3 | compare the second highest card and, if necessary, the third highest. If all three cards have 4 | the same value, then the game is a draw""" 5 | import random 6 | 7 | all_card ={"One":1,"Two":2,"Three":3,"Four":4,"Five":5,"Six":6,"Seven":7,"Eight":8,"Nine":9,"Ten":10} 8 | cards = 3 9 | player1Card =[] 10 | player2Card =[] 11 | for card in range(cards): 12 | c1 =random.choice(list(all_card.values())) 13 | c2= random.choice(list(all_card.values())) 14 | player1Card.append(c1) 15 | player2Card.append(c2) 16 | print(player1Card,player2Card) 17 | 18 | if sum(player1Card) > sum(player2Card): 19 | print("Player 1 wins with ",sum(player1Card)," Against Player 2 with",sum(player2Card)) 20 | elif sum(player2Card) > sum(player1Card): 21 | print("Player 2 wins with ",sum(player2Card)," Against Player 1 with",sum(player1Card)) 22 | 23 | 24 | 25 | 26 | 27 | 28 | -------------------------------------------------------------------------------- /Chapter 11 Exercise/Q_9.py: -------------------------------------------------------------------------------- 1 | """ 2 | Using the card dictionary from earlier in the chapter, deal out three cards. Determine the 3 | following: 4 | (a) If the three cards form a flush (all of the same suit) 5 | (b) If there is a three-of-a-kind (all of the same value) 6 | (c) If there is a pair, but not three-of-a-kind 7 | (d) If the three cards form a straight (all in a row, like (2, 3, 4) or (10, Jack, Queen)) 8 | """ 9 | 10 | from enum import Enum 11 | from random import sample 12 | 13 | class Cards(Enum): 14 | DECK = [{'value':i, 'suit':c} 15 | for c in ['spades', 'clubs', 'hearts', 'diamonds'] 16 | for i in range(2,15)] 17 | 18 | def get_cards(): 19 | rand_cards = sample(Cards.DECK.value, 3) 20 | return rand_cards 21 | 22 | def flush(hand): 23 | if hand[0]['suit'] == hand[1]['suit'] == hand[2]['suit']: 24 | print('\nYou have a flush.') 25 | else: 26 | print('\nYou don\'t have a flush.') 27 | 28 | def three_of_a_kind(hand): 29 | if hand[0]['value'] == hand[1]['value'] == hand[2]['value']: 30 | print('\nYou have a three-of-a-kind.') 31 | else: 32 | print('\nYou don\'t have a three-of-a-kind.') 33 | 34 | def pair(hand): 35 | try: 36 | for i in range(3): 37 | if hand[i]['value'] == hand[i+1]['value']: 38 | print('\nYou have a pair.') 39 | break 40 | else: 41 | pass 42 | except IndexError: 43 | print('\nYou don\'t have a pair.') 44 | 45 | def straight(hand): 46 | face_val = [] 47 | for i in range(3): 48 | face_val.append(hand[i]['value']) 49 | face_val.sort(reverse = True) 50 | try: 51 | for i in range(3): 52 | if (face_val[i] - face_val[i+1] == 1) and (face_val[i+1] - face_val[i+2] == 1): 53 | print('\nYou have a straight.') 54 | break 55 | else: 56 | pass 57 | except IndexError: 58 | print('\nYou don\'t have a straight.') 59 | 60 | def main(): 61 | hand = get_cards() 62 | print('The following below is your hand.\n') 63 | print(hand) 64 | flush(hand) 65 | three_of_a_kind(hand) 66 | pair(hand) 67 | straight(hand) 68 | 69 | if __name__ == '__main__': 70 | main() 71 | -------------------------------------------------------------------------------- /Chapter 12 Exercise/Q_1/Q_1.py: -------------------------------------------------------------------------------- 1 | """ 2 | You are given a file called class_scores.txt, where each line of the file contains a oneword 3 | username and a test score separated by spaces, like below:. 4 | GWashington 83 5 | JAdams 86 6 | Write code that scans through the file, adds 5 points to each test score, and outputs the usernames 7 | and new test scores to a new file, scores2.txt. 8 | 9 | 10 | """ 11 | 12 | lines = [line.strip() for line in open("class_scores.txt")] 13 | inside_lines = [line.split(' ') for line in lines] 14 | print("inside lines",inside_lines) 15 | for num in inside_lines: 16 | num[1]=str(int(num[1])+5) 17 | 18 | lines=[" ".join(line) for line in inside_lines] 19 | print("Lines",lines) 20 | 21 | 22 | f=open('scores2.txt','w') 23 | 24 | for line in lines: 25 | print(line,file=f) 26 | 27 | 28 | 29 | 30 | 31 | 32 | -------------------------------------------------------------------------------- /Chapter 12 Exercise/Q_1/class_scores.txt: -------------------------------------------------------------------------------- 1 | GWashington 83 2 | JAdams 86 -------------------------------------------------------------------------------- /Chapter 12 Exercise/Q_1/scores2.txt: -------------------------------------------------------------------------------- 1 | GWashington 88 2 | JAdams 91 3 | -------------------------------------------------------------------------------- /Chapter 12 Exercise/Q_1/student2.txt: -------------------------------------------------------------------------------- 1 | GWashington 88 2 | JAdams 91 3 | -------------------------------------------------------------------------------- /Chapter 12 Exercise/Q_10/Q_10.py: -------------------------------------------------------------------------------- 1 | """ 2 | 3 | Wordplay – Use the file wordlist.txt for this problem. Find the following: 4 | (a) All words ending in ime 5 | (b) All words whose second, third, and fourth letters are ave 6 | (c) How many words contain at least one of the letters r, s, t, l, n, e 7 | (d) The percentage of words that contain at least one of the letters r, s, t, l, n, e 8 | (e) All words with no vowels 9 | (f) All words that contain every vowel 10 | (g) Whether there are more ten-letter words or seven-letter words 11 | (h) The longest word in the list 12 | (i) All palindromes 13 | (j) All words that are words in reverse, like rat and tar. 14 | (k) Same as above, but only print one word out of each pair. 15 | (l) All words that contain double letters next each other like aardvark or book, excluding 16 | words that end in lly 17 | (m) All words that contain a q that isn’t followed by a u 18 | (n) All words that contain zu anywhere in the word 19 | (o) All words that contain ab in multiple places, like habitable 20 | (p) All words with four or more vowels in a row 21 | (q) All words that contain both a z and a w 22 | (r) All words whose first letter is a, third letter is e and fifth letter is i 23 | (s) All two-letter words 24 | (t) All four-letter words that start and end with the same letter 25 | (u) All words that contain at least nine vowels. 26 | (v) All words that contain each of the letters a, b, c, d, e, and f in any order. There may be 27 | other letters in the word. Two examples are backfield and feedback. 28 | (w) All words whose first four and last four letters are the same 29 | (x) All words of the form abcd*dcba, where * is arbitrarily long sequence of letters. 30 | (y) All groups of 5 words, like pat pet pit pot put, where each word is 3 letters, all words share 31 | the same first and last letters, and the middle letter runs through all 5 vowels. 32 | (z) The word that has the most i’s. 33 | """ 34 | 35 | file1= open('wordlist.txt','r') 36 | str_data =[line.strip('\n') for line in file1] 37 | #print(str_data) 38 | #a) 39 | answer_a =[] 40 | for i in range(0,len(str_data)): 41 | if len(str_data[i]) >3: 42 | if str_data[i][-3:] == "ime": 43 | answer_a.append(str_data[i]) 44 | #print(answer_a) 45 | 46 | #b) 47 | 48 | answer_b =[] 49 | for i in range(0,len(str_data)): 50 | if len(str_data[i]) >3: 51 | if str_data[i][1:2] == "a" and str_data[i][2:3] == "v" and str_data[i][3:4] == "e" : 52 | answer_b.append(str_data[i]) 53 | 54 | #print(answer_b) 55 | 56 | #c) 57 | # letters =["r", "s", "t", "l", "n", "e"] 58 | # answer_c =[] 59 | # for i in range(0,len(str_data)): 60 | # for text in letters: 61 | # if str_data[i] not in answer_c: 62 | # if text in str_data[i]: 63 | # answer_c.append(str_data[i]) 64 | #print(len(answer_c)) 65 | #d) 66 | #print(len(answer_c)/len(str_data) * 100) 67 | 68 | #e 69 | vowels =["a","e","i","o","u"] 70 | answer_e =[] 71 | for words in str_data: 72 | if "a" not in words and "e" not in words and "i" not in words and "o" not in words and "u" not in words: 73 | answer_e.append(words) 74 | 75 | #print(words) 76 | 77 | #f 78 | vowels =["a","e","i","o","u"] 79 | answer_f =[] 80 | for words in str_data: 81 | if "a" in words and "e" in words and "i" in words and "o" in words and "u" in words: 82 | answer_f.append(words) 83 | 84 | #print(answer_f) 85 | 86 | #g 87 | count_10 = 0 88 | count_7 =0 89 | for word in str_data: 90 | if len(word) == 10: 91 | count_10 = count_10 + 1 92 | if len(word) == 7: 93 | count_7 = count_7 + 1 94 | 95 | if count_10 > count_7: 96 | pass 97 | #print( "There are more 10 Letter Words") 98 | else: 99 | #print("There are more seven letter words",count_7) 100 | pass 101 | 102 | #h 103 | all_lenght =[] 104 | for words in str_data: 105 | length = len(words) 106 | all_lenght.append(length) 107 | #print(max(all_lenght)) 108 | if length == 23: 109 | pass 110 | #print(words) 111 | 112 | #j 113 | for word in str_data: 114 | words = list(reversed(word)) 115 | words = "".join(words) 116 | if word == words: 117 | pass 118 | # print(word) 119 | 120 | #k 121 | for word in str_data: 122 | words = list(reversed(word)) 123 | words = "".join(words) 124 | if words == "rat" or words == "tat": 125 | #print(word) 126 | pass 127 | 128 | #l 129 | alphabet =["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"] 130 | answer_l=[] 131 | for words in str_data: 132 | for letter in alphabet: 133 | if letter*2 in words and words[:-3] != "ily": 134 | answer_l.append(words) 135 | 136 | #print(answer_l) 137 | 138 | #m 139 | for words in str_data: 140 | for i in range(len(words)): 141 | if words[i]=="q" and words[i+1] !="u": 142 | # print(words) 143 | pass 144 | 145 | ##n 146 | for words in str_data: 147 | if "zu" in words: 148 | # print(words) 149 | pass 150 | #o 151 | count_o =0 152 | answer_xx =[] 153 | for wordz in str_data: 154 | if "ab" and "ab" in word: 155 | count_o = count_o + 1 156 | if count_o == 1: 157 | #print(word) 158 | pass 159 | 160 | #p 161 | 162 | for words in str_data: 163 | if "aeiou" in words: 164 | #print(words) 165 | pass 166 | 167 | #q 168 | for words in str_data: 169 | if "z" in words and "w" in words: 170 | #print(words) 171 | pass 172 | 173 | #r 174 | for words in str_data: 175 | if len(words) > 5: 176 | if words[:1] == "a" and words[2:3] == "e" and words[4:5] == "i": 177 | #print(words) 178 | pass 179 | 180 | #s 181 | for words in str_data: 182 | if len(words) == 2: 183 | #print(words) 184 | pass 185 | 186 | #t 187 | 188 | for words in str_data: 189 | if len(words) == 4: 190 | if words[:1] == words[-1:]: 191 | #print(words) 192 | pass 193 | 194 | #u 195 | vowel_u =["a","e","i","o","u"] 196 | count_u = 0 197 | for wordsi in str_data: 198 | count_u = 0 199 | for vowel in vowel_u: 200 | 201 | if vowel in wordsi: 202 | count_u = count_u + 1 203 | if count_u >= 9: 204 | #print(wordsi) 205 | pass 206 | #v 207 | 208 | 209 | 210 | for word in str_data: 211 | if "a" in word and "b" in word and "c" in word and "d" in word and "e" in word and "f" in word: 212 | #print(word) 213 | pass 214 | 215 | #w 216 | 217 | for word in str_data: 218 | if word[:4] == word[4:]: 219 | #print(word) 220 | pass 221 | 222 | 223 | 224 | 225 | 226 | 227 | -------------------------------------------------------------------------------- /Chapter 12 Exercise/Q_11/Q_11.py: -------------------------------------------------------------------------------- 1 | """Write a program to help with word games. The user enters a word and the program uses the 2 | wordlist to determine if the user’s word is a real word or not.""" 3 | 4 | file1 = open("wordlist.txt","r") 5 | str_data =[line.strip('\n') for line in file1] 6 | user_input = input("Enter a Word:") 7 | 8 | for words in str_data: 9 | if user_input == words: 10 | #print("User word is real") 11 | pass 12 | 13 | -------------------------------------------------------------------------------- /Chapter 12 Exercise/Q_12/Q_12.py: -------------------------------------------------------------------------------- 1 | """Suppose we write all the words in the wordlist backwards and then arrange these backwards 2 | words alphabetically. Write a program that prints the last word in this modified wordlist.""" 3 | 4 | 5 | file1 = open("wordlist.txt","r") 6 | str_data = [line.strip('\n') for line in file1] 7 | 8 | for words in str_data: 9 | rev =reversed(words) 10 | print(list(rev)) 11 | 12 | -------------------------------------------------------------------------------- /Chapter 12 Exercise/Q_13/Q_13.py: -------------------------------------------------------------------------------- 1 | """Print out all combinations of the string 'Python' plus a three letter English word. Capitalize 2 | the first letter of the three letter word. Example combinations are 'PythonCat', 3 | 'PythonDog', and 'PythonTag'. These are valid combinations because cat, dog, and tag 4 | are English words. On the other hand, 'PythonQqz' would not be a valid combination because 5 | qqz is not an English word. Use a wordlist to determine which three letter combinations 6 | are words.""" 7 | 8 | file1 = open("wordlist.txt","r") 9 | str_data = [line.strip("\n") for line in file1] 10 | str = "Python" 11 | for words in str_data: 12 | if len(words) ==3: 13 | c=words.title() 14 | print(str + c) 15 | -------------------------------------------------------------------------------- /Chapter 12 Exercise/Q_14/Q_14.py: -------------------------------------------------------------------------------- 1 | """Write a simple spell-checking program. The user should enter a string and the program 2 | should print out a list of all the words it thinks are misspelled. These would be all the words 3 | it cannot find in a wordlist.""" 4 | 5 | file1 = open("wordlist.txt","r") 6 | str_data = [line.strip("\n") for line in file1] 7 | 8 | count =0 9 | user_input = input("Enter a Word : ") 10 | for words in str_data: 11 | if user_input[:4] == words[:4] : 12 | if user_input not in words: 13 | print(words) 14 | -------------------------------------------------------------------------------- /Chapter 12 Exercise/Q_15/Q_15.py: -------------------------------------------------------------------------------- 1 | """Crossword cheater: When working on a crossword puzzle, often you will have a word where 2 | you know several of the letters, but not all of them. You can write a computer program to 3 | help you. For the program, the user should be able to input a word with the letters they 4 | know filled in and asterisks for those they don’t know. The program should print out a list 5 | of all words that fit that description. For example, the input th***ly should return all the 6 | words that could work, namely thickly and thirdly.""" 7 | 8 | file1 = open("wordlist.txt","r") 9 | str_data =[line.strip("\n") for line in file1] 10 | user_input = input("Enter Word You Know: ") 11 | 12 | for words in str_data: 13 | if user_input[:2] == words[:2] and user_input[-2:] == words[-2:] and len(user_input) == len(words): 14 | for i in user_input: 15 | if i in words: 16 | print(words) -------------------------------------------------------------------------------- /Chapter 12 Exercise/Q_2/Q_2.py: -------------------------------------------------------------------------------- 1 | """ 2 | You are given a file called grades.txt, where each line of the file contains a one-word student 3 | username and three test scores separated by spaces, like below:. 4 | GWashington 83 77 54 5 | JAdams 86 69 90 6 | Write code that scans through the file and determines how many students passed all three 7 | tests. 8 | """ 9 | 10 | passed_all3 =[] 11 | failed_atleast1 =[] 12 | with open("grades.txt") as f: 13 | s = f.readlines() 14 | lines = [line.strip() for line in s] 15 | structure_content = [line.split(" ") for line in lines ] 16 | 17 | for score in structure_content: 18 | c = 0 19 | for i in range(1, len(score)): 20 | 21 | if int(score[i]) > 50 : 22 | c +=1 23 | if c == 3: 24 | passed_all3.append(score[0]) 25 | if c !=3: 26 | failed_atleast1.append(score[0]) 27 | 28 | 29 | print("Student who passed all three Subjects:",passed_all3,"Their number is",len(passed_all3)) 30 | print("Student who Failed Atleast 1 Subject:",failed_atleast1,"Their number is",len(failed_atleast1)) 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | -------------------------------------------------------------------------------- /Chapter 12 Exercise/Q_2/grades.txt: -------------------------------------------------------------------------------- 1 | GWashington 83 77 52 2 | JAdams 86 69 90 3 | Henry 3 77 22 4 | Thomas 86 69 33 5 | Mark 3 00 44 -------------------------------------------------------------------------------- /Chapter 12 Exercise/Q_3/Q_3.py: -------------------------------------------------------------------------------- 1 | """ 2 | You are given a file called logfile.txt that lists log-on and log-off times for users of a 3 | system. A typical line of the file looks like this: 4 | Van Rossum, 14:22, 14:37 5 | 6 | Each line has three entries separated by commas: a username, a log-on time, and a log-off 7 | time. Times are given in 24-hour format. You may assume that all log-ons and log-offs occur 8 | within a single workday. 9 | Write a program that scans through the file and prints out all users who were online for at 10 | least an hour. 11 | """ 12 | file = open("logfile.txt") 13 | lines = [line.strip() for line in file ] 14 | structure_data = [line.split(" ") for line in lines] 15 | 16 | for line in structure_data: 17 | for time in range(1,len(line)): 18 | log_of = ((int(line[2][:2])) + (int(line[2][-2:])) / 60) 19 | log_in = ((int(line[1][:2])) + (int(line[1][3:-1])) / 60) 20 | time_onine = log_of - log_in 21 | #print(log_of) 22 | #print("log in",log_in) 23 | if time_onine >= 1: 24 | print(line[0]," Have Been Active For Over An Hour.",time_onine) 25 | 26 | 27 | 28 | 29 | 30 | -------------------------------------------------------------------------------- /Chapter 12 Exercise/Q_3/logfile.txt: -------------------------------------------------------------------------------- 1 | VanRossum, 14:22, 14:37 2 | HenryTirla, 13:22, 14:37 3 | ThomasTirnyuy, 12:22, 12:37 4 | NelsonKiwo, 11:22, 12:37 5 | 6 | -------------------------------------------------------------------------------- /Chapter 12 Exercise/Q_4/Q_4.py: -------------------------------------------------------------------------------- 1 | """ 2 | You are given a file called students.txt. A typical line in the file looks like: 3 | walter melon melon@email.msmary.edu 555-3141 4 | There is a name, an email address, and a phone number, each separated by tabs. Write a 5 | program that reads through the file line-by-line, and for each line, capitalizes the first letter 6 | of the first and last name and adds the area code 301 to the phone number. Your program 7 | should write this to a new file called students2.txt. Here is what the first line of the new 8 | file should look like: 9 | Walter Melon melon@email.msmary.edu 301-555-3141 10 | """ 11 | 12 | 13 | with open("student.txt") as student: 14 | s =student.readlines() 15 | 16 | lines= [line.strip() for line in s] 17 | #print(lines) 18 | structure_content = [line.split(" ") for line in lines] 19 | print("structured Content",structure_content) 20 | 21 | for data in structure_content: 22 | 23 | data[0] = data[0].title() 24 | data[1] = data[1].title() 25 | data[3] = "305-" + data[3] 26 | f= open("student2.txt","w") 27 | for lines in structure_content: 28 | print(lines,file=f) 29 | #print(structure_content) 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | -------------------------------------------------------------------------------- /Chapter 12 Exercise/Q_4/student.txt: -------------------------------------------------------------------------------- 1 | walter melon melon@email.msmary.edu 555-3141 2 | henry tirla antwerp@email.msmary.edu 444-3141 -------------------------------------------------------------------------------- /Chapter 12 Exercise/Q_4/student2.txt: -------------------------------------------------------------------------------- 1 | ['Walter', 'Melon', 'melon@email.msmary.edu', '305-555-3141'] 2 | ['Henry', 'Tirla', 'antwerp@email.msmary.edu', '305-444-3141'] 3 | -------------------------------------------------------------------------------- /Chapter 12 Exercise/Q_5/Q_5.py: -------------------------------------------------------------------------------- 1 | """You are given a file namelist.txt that contains a bunch of names. Some of the names are 2 | a first name and a last name separated by spaces, like George Washington, while others have 3 | a middle name, like John Quincy Adams. There are no names consisting of just one word or 4 | more than three words. Write a program that asks the user to enter initials, like GW or JQA, 5 | and prints all the names that match those initials. Note that initials like JA should match both 6 | John Adams and John Quincy Adams.""" 7 | 8 | with open("namelist.txt") as n: 9 | s = n.readlines() 10 | lines =[line.strip() for line in s] 11 | str_data = [line.split(" ") for line in lines] 12 | Init =(input("Enter User Initial: ")) 13 | initial= list(Init) ##Most crucial part for me 14 | 15 | for list in str_data: 16 | if len(initial) >=2: 17 | if initial[0] == list[0][:1] or initial[1] == list[1][:1]: 18 | print(list) 19 | else: 20 | print("Enter Two Initials Atleast") 21 | break 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | -------------------------------------------------------------------------------- /Chapter 12 Exercise/Q_5/namelist.txt: -------------------------------------------------------------------------------- 1 | Henry Tirla 2 | Thomas Tirnyuy Ndzenyuy 3 | Henry Kuvinyoh 4 | Nelson Kiwo 5 | Laurence Tatchom 6 | Monique Diboma 7 | John Quincy Adams 8 | John Adams -------------------------------------------------------------------------------- /Chapter 12 Exercise/Q_6/Q_6.py: -------------------------------------------------------------------------------- 1 | """You are given a file namelist.txt that contains a bunch of names. 2 | Print out all the names in the 3 | list in which the vowels a, e, i, o, and u appear in order 4 | (with repeats possible). 5 | The first vowel in the name must be a and after the first u, 6 | it is okay for there to be other vowels. An example is Ace Elvin Coulson.""" 7 | 8 | #structure each word 9 | #put each word to be tried against aeiou 10 | 11 | vowel =['A','E','I','O','U'] 12 | with open("namelist.txt") as n: 13 | s = n.readlines() 14 | lines= [line.strip() for line in s ] 15 | str_data =[line.split(' ') for line in lines] 16 | 17 | 18 | 19 | for names in str_data: 20 | for i in range(len(names)): 21 | if names[i][:1] == vowel[0] and names[i+1][:1] ==vowel[1] and names[i+2][:1] == vowel[2] and names[i+3][:1] == vowel[3] and names[i+4 ][:1] == vowel[4] : 22 | print(names) 23 | 24 | 25 | 26 | 27 | -------------------------------------------------------------------------------- /Chapter 12 Exercise/Q_6/namelist.txt: -------------------------------------------------------------------------------- 1 | Ace Elvin Ioulson Ognore Uron 2 | Apple Elvis Indica Orange Locko 3 | Adam Eveve Indica Ortage Uranium 4 | 5 | -------------------------------------------------------------------------------- /Chapter 12 Exercise/Q_7/Q_7.py: -------------------------------------------------------------------------------- 1 | """You are given a file called baseball.txt. A typical line of the file starts like below. 2 | Ichiro Suzuki SEA 162 680 74 ...[more stats] 3 | 4 | Each entry is separated by a tab, \t. The first entry is the player’s name and the second is 5 | their team. Following that are 16 statistics. Home runs are the seventh stat and stolen bases 6 | are the eleventh. Print out all the players who have at least 20 home runs and at least 20 stolen 7 | bases.""" 8 | 9 | file1 = open("baseball.txt","r") 10 | #print(file1.read()) 11 | str_data =[lines.split() for lines in file1] 12 | 13 | for player in str_data: 14 | if len(player) > 13: 15 | if int(player[9]) > 20 and int(player[13] )>= 20: 16 | print("Player Names: ", player[0:2]) -------------------------------------------------------------------------------- /Chapter 12 Exercise/Q_8/Q_8.py: -------------------------------------------------------------------------------- 1 | """ 2 | For this problem, use the file of NCAA basketball scores as described in Section 12.3. 3 | (a) Find the average of the points scored over all the games in the file. 4 | (b) Pick your favorite team and scan through the file to determine how many games they 5 | won and how many games they lost. 6 | (c) Find the team(s) that lost by 30 or more points the most times 7 | (d) Find all the teams that averaged at least 70 points a game. 8 | (e) Find all the teams that had winning records but were collectively outscored by their 9 | opponents. A team is collectively outscored by their opponents if the total number of 10 | points the team scored over all their games is less than the total number of points their 11 | opponents scored in their games against the team. 12 | """ 13 | 14 | file1 = open("scores.txt","r") 15 | str_data = [line.split() for line in file1] 16 | 17 | 18 | #print(str_data) 19 | #a) 20 | scorelist=[] 21 | for scores in str_data: 22 | scorelist.extend([scores[2],scores[4]]) 23 | for i in range(0,len(scorelist)): ##convert string to INT 24 | scorelist[i] = int(scorelist[i]) 25 | 26 | 27 | 28 | average = sum(scorelist)/len(scorelist) 29 | #print("Average",average) 30 | 31 | #b) 32 | 33 | myteam ="AlcornSt." 34 | team1=[] 35 | team2 =[] 36 | for teams in str_data: 37 | if teams[1] == myteam: 38 | team1.append(teams[1:]) 39 | if teams[3] == myteam: 40 | team2.append(teams[1:]) 41 | 42 | wins= 0 43 | loss =0 44 | for matches in team1: 45 | if int(matches[1]) > int(matches[3]): 46 | wins = wins + 1 47 | print("wins") 48 | else: 49 | loss = loss +1 50 | 51 | for matches in team2: 52 | if int(matches[3]) > int(matches[1]): 53 | wins = wins + 1 54 | 55 | else: 56 | loss = loss +1 57 | #print(myteam,"Won: ", wins,"Matches and Lost: ",loss,"Matches") 58 | 59 | #c) 60 | looser_team =[] 61 | for teams in str_data: 62 | if int(teams[2]) - int(teams[4]) >= 30: 63 | if teams[3] not in looser_team: 64 | looser_team.append(teams[3]) 65 | 66 | if int(teams[4]) - int(teams[2]) >= 30: 67 | if teams[1] not in looser_team: 68 | looser_team.append(teams[1]) 69 | 70 | #print("Teams who lost Match with Atleast 30 or more points",looser_team) 71 | 72 | 73 | #d) 74 | winner_teams=[] 75 | for teams in str_data: 76 | if int(teams[4]) - int(teams[2]) >= 70: 77 | #if teams[3] not in looser_team: 78 | winner_teams.append(teams[3]) 79 | #print(winner_teams) 80 | 81 | 82 | 83 | #e -------------------------------------------------------------------------------- /Chapter 12 Exercise/Q_9/Q_9.py: -------------------------------------------------------------------------------- 1 | """ 2 | Benford’s law states that in real data where the values are spread across several orders of 3 | magnitude, about 30% of the values will start with the number 1, whereas only about 4.6% 4 | of the values will start with the number 9. This is contrary to what we might expect, namely 5 | that values starting with 1 and 9 would be equally likely. Using the file expenses.txt which 6 | consists of a number of costs from an expense account, determine what percentage start with 7 | each of the digits 1 through 9. This technique is used by accountants to detect fraud. 8 | """ 9 | 10 | 11 | file1 = open("expenses.txt","r") 12 | str_data =[line.strip("\n") for line in file1] 13 | 14 | total = len(str_data) 15 | percentage_occurence =[] 16 | 17 | 18 | count = 0 19 | for benford_law in range(1,10): 20 | 21 | for number in range(0,len(str_data)): 22 | value = str_data[number][:1] 23 | if int(str_data[number][:1]) == benford_law: 24 | count = count + 1 25 | percentage = count/total * 100 26 | percentage_occurence.append([benford_law,"Occurence Percentage is ",percentage]) 27 | count = 0 28 | 29 | 30 | print(percentage_occurence) 31 | -------------------------------------------------------------------------------- /Chapter 12 Exercise/Q_9/expenses.txt: -------------------------------------------------------------------------------- 1 | 152 2 | 9 3 | 1 4 | 12 5 | 45 6 | 55 7 | 4 8 | 791 9 | 13 10 | 1429 11 | 11 12 | 31 13 | 34 14 | 9 15 | 412 16 | 41 17 | 2212 18 | 5 19 | 121 20 | 2 21 | 21 22 | 1 23 | 726 24 | 252 25 | 6375 26 | 89 27 | 41 28 | 1 29 | 89 30 | 28 31 | 3 32 | 6 33 | 3819 34 | 8 35 | 213 36 | 5131 37 | 5123 38 | 313 39 | 1721 40 | 65 41 | 8 42 | 162 43 | 6 44 | 6 45 | 2362 46 | 1 47 | 751 48 | 441 49 | 1646 50 | 2155 51 | 22 52 | 1 53 | 6 54 | 1821 55 | 5251 56 | 3411 57 | 1821 58 | 31 59 | 432 60 | 411 61 | 13 62 | 5924 63 | 2111 64 | 168 65 | 5 66 | 4211 67 | 5 68 | 56 69 | 51 70 | 158 71 | 541 72 | 4211 73 | 5672 74 | 9814 75 | 4611 76 | 4268 77 | 9 78 | 91 79 | 412 80 | 5421 81 | 724 82 | 89 83 | 19 84 | 21 85 | 5 86 | 2247 87 | 2 88 | 241 89 | 653 90 | 4 91 | 4271 92 | 4 93 | 2 94 | 186 95 | 63 96 | 34 97 | 34 98 | 5 99 | 18 100 | 1654 -------------------------------------------------------------------------------- /Chapter 13 Exercise/Q_1.py: -------------------------------------------------------------------------------- 1 | """ 2 | 3 | Write a function called rectangle that takes two integers m and n as arguments and prints 4 | out an mx n box consisting of asterisks. Shown below is the output of rectangle(2,4) 5 | **** 6 | **** 7 | 8 | """ 9 | 10 | def rectangle(m,n): 11 | for i in range(0,m): 12 | out = n * "*" 13 | print(out) 14 | 15 | 16 | 17 | 18 | rectangle(2,4) 19 | -------------------------------------------------------------------------------- /Chapter 13 Exercise/Q_10.py: -------------------------------------------------------------------------------- 1 | """Write a function called closest that takes a list of numbers L and a number n and returns 2 | the largest element in L that is not larger than n. For instance, if L=[1,6,3,9,11] and n=8, 3 | then the function should return 6, because 6 is the closest thing in L to 8 that is not larger than 4 | 8. Don’t worry about if all of the things in L are smaller than n.""" 5 | 6 | 7 | 8 | def closest(L,n): 9 | 10 | for i in range(len(L)): 11 | new_list=[] 12 | for number in L: 13 | if number < n: 14 | new_list.append(number) 15 | print(max(new_list)) 16 | 17 | 18 | closest([1,6,3,9,11],8) -------------------------------------------------------------------------------- /Chapter 13 Exercise/Q_11.py: -------------------------------------------------------------------------------- 1 | """Write a function called matches that takes two strings as arguments and returns how many 2 | matches there are between the strings. A match is where the two strings have the same character 3 | at the same index. For instance, 'python' and 'path' match in the first, third, and 4 | fourth characters, so the function should return 3.""" 5 | 6 | def matches(x,y): 7 | count = 0 8 | for i in range(len(x)): 9 | for j in range(len(y)): 10 | if x[i] == y[j]: 11 | count += 1 12 | print(count) 13 | 14 | 15 | matches("python","path") -------------------------------------------------------------------------------- /Chapter 13 Exercise/Q_12.py: -------------------------------------------------------------------------------- 1 | """Recall that if s is a string, then s.find('a') will find the location of the first a in s. The 2 | problem is that it does not find the location of every a. Write a function called find all that 3 | given a string and a single character, returns a list containing all of the locations of that character 4 | in the string. It should return an empty list if there are no occurrences of the character 5 | in the string.""" 6 | import re 7 | def find_all(a_str, sub): 8 | start = 0 9 | while True: 10 | start = a_str.find(sub, start) 11 | if start == -1: return 12 | yield start 13 | start += len(sub) # use start += 1 to find overlapping matches 14 | 15 | 16 | print(list(find_all("Henrye","e"))) -------------------------------------------------------------------------------- /Chapter 13 Exercise/Q_14.py: -------------------------------------------------------------------------------- 1 | """Write a function called is_sorted that is given a list and returns True if the list is sorted 2 | and False otherwise.""" 3 | # 4 | def is_sorted(l): 5 | if l ==sorted(l): 6 | print (True) 7 | else: 8 | print(False) 9 | 10 | 11 | 12 | is_sorted([1,4,2,5]) 13 | array = [3,5,-4,8,11,1,-1,6] 14 | 15 | 16 | 17 | 18 | -------------------------------------------------------------------------------- /Chapter 13 Exercise/Q_15.py: -------------------------------------------------------------------------------- 1 | """Write a function called root that is given a number x and an integer n and returns x1=n. In 2 | the function definition, set the default value of n to 2.""" 3 | 4 | def root(x,n=2): 5 | print(x**(1/n)) 6 | 7 | 8 | root(36) -------------------------------------------------------------------------------- /Chapter 13 Exercise/Q_16.py: -------------------------------------------------------------------------------- 1 | """Write a function called one_away that takes two strings and returns True if the strings are of 2 | the same length and differ in exactly one letter, like bike/hike or water/wafer.""" 3 | 4 | """ 5 | count = 0 6 | if len(a) == len(b) 7 | for i in a: 8 | for j in b: 9 | if i != j: 10 | count += 1 11 | if count == 1: 12 | print(true) 13 | 14 | 15 | """ 16 | 17 | def one_way(a,b): 18 | u = zip(a,b) 19 | count =0 20 | if len(a) == len(b): 21 | for i , j in u: 22 | if i != j: 23 | count += 1 24 | if count == 1: 25 | print(True) 26 | else: 27 | print("Not the same length") 28 | 29 | 30 | 31 | 32 | one_way("Henry","Henrxf") 33 | 34 | -------------------------------------------------------------------------------- /Chapter 13 Exercise/Q_17.py: -------------------------------------------------------------------------------- 1 | """(a) Write a function called primes that is given a number n and returns a list of the first n 2 | primes. Let the default value of n be 100. 3 | (b) Modify the function above so that there is an optional argument called start that allows 4 | the list to start at a value other than 2. The function should return the first n primes that 5 | are greater than or equal to start. The default value of start should be 2.""" 6 | 7 | 8 | def primes(n=10): 9 | 10 | primes_l=[] 11 | for number in range(1, 10): 12 | if number >1: 13 | for i in range(2, number): 14 | 15 | if (number % i) == 0: 16 | break 17 | else: 18 | primes_l.append(number) 19 | print(primes_l) 20 | 21 | 22 | primes(10) -------------------------------------------------------------------------------- /Chapter 13 Exercise/Q_18.py: -------------------------------------------------------------------------------- 1 | """Our number system is called base 10 because we have ten digits: 0, 1, . . . , 9. Some cultures, 2 | including the Mayans and Celts, used a base 20 system. In one version of this system, the 20 3 | digits are represented by the letters A through T. Here is a table showing a few conversions: 4 | 10 20 10 20 10 20 10 20 5 | 0 A 8 I 16 Q 39 BT 6 | 1 B 9 J 17 R 40 CA 7 | 2 C 10 K 18 S 41 CB 8 | 3 D 11 L 19 T 60 DA 9 | 4 E 12 M 20 BA 399 TT 10 | 5 F 13 N 21 BB 400 BAA 11 | 6 G 14 O 22 BC 401 BAB 12 | 7 H 15 P 23 BD 402 BAC 13 | Write a function called base20 that converts a base 10 number to base 20. It should return 14 | the result as a string of base 20 digits. One way to convert is to find the remainder when 15 | the number is divided by 20, then divide the number by 20, and repeat the process until the 16 | number is 0. The remainders are the base 20 digits in reverse order, though you have to 17 | convert them into their letter equivalents. 18 | 19 | """ 20 | 21 | def base20(): 22 | pass 23 | -------------------------------------------------------------------------------- /Chapter 13 Exercise/Q_19.py: -------------------------------------------------------------------------------- 1 | """Write a function called verbose that, given an integer less than 1015, returns the name of 2 | the integer in English. As an example, verbose(123456) should return one hundred 3 | twenty-three thousand, four hundred fifty-six.""" 4 | 5 | 6 | 7 | def verbose(num): 8 | d ={0:"zero",1:"one",2:"two",3:"three",4:"four",5:"five",6:"six",7:"seven",8:"eight",9:"nine",10:"ten", 9 | 11:"eleven",12:"twelve",13:"thirteen",14:"fourteen",15:"fiftheen",16:"sixteen",17:"seventeen",18:"eighteen", 10 | 19:"nineteen",20:"twenty",30:"30",40:"fourty",50:"fifthy",60:"sixty",70:"Seventy",80:"eighty",90:"Ninety"} 11 | 12 | if num <20: 13 | return d[num] 14 | 15 | if num <100 : 16 | if num % 10 == 0: 17 | return d[num] 18 | else: 19 | return d[num //10 * 10] + verbose(num % 10) 20 | 21 | if num < 10 **3: 22 | if num % 100 == 0: 23 | return d[num] + "hundred" 24 | else: 25 | return d[num//100] + "hundred and " + verbose(num % 100) 26 | 27 | if num < 10 **6: 28 | if num % 10**3 == 0: 29 | return verbose(num) + "Thousand" 30 | 31 | else: 32 | return verbose(num//10**3)+ "Thousand " + verbose(num % 10**3) 33 | 34 | if num < 10 ** 9: 35 | if num % 10 **6 == 0: 36 | return verbose(num//10**6) + "Million" 37 | else: 38 | return verbose(num // 10**6) + " Million " + verbose(num % 10**6) 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | print(verbose(123456)) -------------------------------------------------------------------------------- /Chapter 13 Exercise/Q_2.py: -------------------------------------------------------------------------------- 1 | """(a) Write a function called add_excitement that takes a list of strings and adds an exclamation 2 | point (!) to the end of each string in the list. The program should modify the 3 | original list and not return anything. 4 | (b) Write the same function except that it should not modify the original list and should 5 | instead return a new list.""" 6 | 7 | 8 | def add_exictement(x): 9 | 10 | x=[words + "!" for words in x] 11 | 12 | def add_exictement2(x): 13 | new_c =[] 14 | for words in x: 15 | new_word =words + "!" 16 | new_c.append(new_word) 17 | return new_c 18 | 19 | 20 | 21 | 22 | 23 | -------------------------------------------------------------------------------- /Chapter 13 Exercise/Q_20.py: -------------------------------------------------------------------------------- 1 | """Write a function called merge that takes two already sorted lists of possibly different lengths, 2 | and merges them into a single sorted list. 3 | (a) Do this using the sort method. 4 | (b) Do this without using the sort method.""" 5 | 6 | 7 | def merge_withsort(l1,l2): 8 | result = l1 + l2 9 | print((sorted(result))) 10 | 11 | 12 | merge_withsort([1,3,4,6],[2,4,5,6,7]) 13 | 14 | 15 | def merge_withoutsort(l1,l2): 16 | l3 =l1+l2 17 | 18 | for i in range(len(l3)): 19 | for j in range(1+i,len(l3)): 20 | if l3[i] > l3[j]: 21 | l3[i], l3[j] = l3[j], l3[i] 22 | 23 | print(l3) 24 | 25 | merge_withoutsort([2,5,4,6,1],[7,6,5,4,3,0]) 26 | 27 | 28 | -------------------------------------------------------------------------------- /Chapter 13 Exercise/Q_21.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/henrytirla/Practical-Introduction-to-python/1e7cf5dc0268b24d984c2305d616091fd4e995a8/Chapter 13 Exercise/Q_21.py -------------------------------------------------------------------------------- /Chapter 13 Exercise/Q_3.py: -------------------------------------------------------------------------------- 1 | """Write a function called sum_digits that is given an integer num and returns the sum of the 2 | digits of num.""" 3 | 4 | 5 | def sum_digits(num): 6 | num_list = [] 7 | for numbers in range(num): 8 | num_list.append(numbers) 9 | print(sum(num_list)) 10 | 11 | 12 | 13 | sum_digits(4) 14 | -------------------------------------------------------------------------------- /Chapter 13 Exercise/Q_4.py: -------------------------------------------------------------------------------- 1 | """The digital root of a number n is obtained as follows: Add up the digits n to get a new number. 2 | Add up the digits of that to get another new number. Keep doing this until you get a number 3 | that has only one digit. That number is the digital root. 4 | For example, if n = 45893, we add up the digits to get 4 + 5 + 8 + 9 + 3 = 29. We then add up 5 | the digits of 29 to get 2 + 9 = 11. We then add up the digits of 11 to get 1 + 1 = 2. Since 2 has 6 | only one digit, 2 is our digital root. 7 | Write a function that returns the digital root of an integer n. [Note: there is a shortcut, where 8 | the digital root is equal to n mod 9, but do not use that here.]""" 9 | 10 | def digital_root(num): 11 | num = str(num) 12 | sum=0 13 | for i in range(len(num)): 14 | sum = sum + int(num[i]) % 9 15 | 16 | if(sum == 0): 17 | return 9 18 | else: 19 | return sum % 9 20 | 21 | 22 | print(digital_root(45893)) 23 | 24 | -------------------------------------------------------------------------------- /Chapter 13 Exercise/Q_5.py: -------------------------------------------------------------------------------- 1 | """Write a function called first_diff that is given two strings and returns the first location in 2 | which the strings differ. If the strings are identical, it should return -1.""" 3 | 4 | def first_diff(x,y): 5 | if len(x) == len(y): 6 | for i in range(1,len(x) + 1): 7 | if x[:] == y[:]: 8 | print("-1") 9 | elif x[:i] != y[:i]: 10 | print("They differ at the ",i, "Character",x[:i],y[:i]) 11 | break 12 | else: 13 | print("These are non identical Strings") 14 | 15 | 16 | 17 | first_diff("h2nry","henry") -------------------------------------------------------------------------------- /Chapter 13 Exercise/Q_6.py: -------------------------------------------------------------------------------- 1 | """Write a function called binom that takes two integers n and k and returns the binomial coefficient 2 | n! 3 | k!(n􀀀k)! .""" 4 | 5 | 6 | def binomialCoeff(n, k): 7 | if k > n: 8 | return 0 9 | if k == 0 or k == n: 10 | return 1 11 | 12 | # Recursive Call 13 | return binomialCoeff(n - 1, k - 1) + binomialCoeff(n - 1, k) 14 | 15 | 16 | print(binomialCoeff(5,2)) 17 | 18 | #credit https://www.geeksforgeeks.org/binomial-coefficient-dp-9/ -------------------------------------------------------------------------------- /Chapter 13 Exercise/Q_7.py: -------------------------------------------------------------------------------- 1 | """Write a function that takes an integer n and returns a random integer with exactly n digits. For 2 | instance, if n is 3, then 125 and 593 would be valid return values, but 093 would not because 3 | that is really 93, which is a two-digit number.""" 4 | 5 | import random 6 | 7 | def generate_num(n): 8 | 9 | random_num =random.randint(0, 10 ** n - 1) 10 | if random_num >100: 11 | print("Valid",random_num) 12 | else: 13 | print("invalid",random_num) 14 | 15 | 16 | 17 | generate_num(3) -------------------------------------------------------------------------------- /Chapter 13 Exercise/Q_8.py: -------------------------------------------------------------------------------- 1 | """Write a function called number_of_factors that takes an integer and returns how many 2 | factors the number has.""" 3 | 4 | def factors_num(n): 5 | count = 0 6 | for num in range(1,n): 7 | if n % num ==0: 8 | count += 1 9 | print(count) 10 | 11 | 12 | factors_num(28) -------------------------------------------------------------------------------- /Chapter 13 Exercise/Q_9.py: -------------------------------------------------------------------------------- 1 | """Write a function called factors that takes an 2 | integer and returns a list of its factors.""" 3 | 4 | def factors(n): 5 | list_factors=[] 6 | for i in range(n): 7 | if i > 0 and n % i == 0 : 8 | list_factors.append(i) 9 | print(list_factors) 10 | 11 | 12 | factors(12) -------------------------------------------------------------------------------- /Chapter 14 Exercise/Q_1.py: -------------------------------------------------------------------------------- 1 | """Write a class called Investment with fields called principal and interest. The constructor 2 | should set the values of those fields. There should be a method called value_after that 3 | returns the value of the investment after n years. The formula for this is p(1 + i)n, where p is 4 | the principal, and i is the interest rate. It should also use the special method __str__ so that 5 | printing the object will result in something like below: 6 | Principal - $1000.00, Interest rate - 5.12%""" 7 | 8 | 9 | class Investment: 10 | def __init__(self,principal,interest,n): 11 | self.principal = principal 12 | self.interest = interest 13 | self.n = n 14 | 15 | def value_after(self): 16 | 17 | return_investment = self.principal*(1+self.interest)**self.n 18 | return return_investment 19 | 20 | def __str__(self): 21 | return ("Principal --$", self.principal,"Interest rate---", self.interest,"%","Interst $",a.value_after()) 22 | 23 | 24 | 25 | 26 | a = Investment(1000,5.12,3) 27 | print((a.__str__())) 28 | -------------------------------------------------------------------------------- /Chapter 14 Exercise/Q_10.py: -------------------------------------------------------------------------------- 1 | ''' 2 | (a) Write a class called Connect4 that implements the logic of a Connect4 game. Use the 3 | Tic_tac_toe class from this chapter as a starting point. 4 | (b) Use the Connect4 class to create a simple text-based version of the game. 5 | ''' 6 | 7 | import pprint as pp 8 | class ConnectFour: 9 | 10 | def __init__(self): 11 | 12 | self.Board = [[' ' for i in range(7)] for i in range(6)] 13 | 14 | def get_diag_and_row(self): 15 | ''' to get rows,columns and diagonals''' 16 | # To print the board from a negative axis 17 | x1 = [[i[j] for j in range(-1, -(len(i)+1), -1)]for i in self.Board] 18 | 19 | def diag(d): 20 | ''' To get diagonals for the positive and negative slope ''' 21 | 22 | neg = [[d[i][j] for i in range(k+1) for j in range(k, -1, -1) if i+j == k-1] 23 | for k in range(1, 7)] 24 | pos = [[d[i][j] for i in range(5, -1, -1) for j in range(-1, -8, -1) if i+j == k] 25 | for k in range(6, -2, -1)] 26 | c = [i for i in (neg+pos) if len(i) >= 4] 27 | 28 | return c 29 | 30 | check_list = (diag(x1) + diag(self.Board) + self.Board) 31 | 32 | return check_list 33 | 34 | def get_column(self, col_index): 35 | """ 36 | Returns a value at that index on every row 37 | 38 | """ 39 | return [i[col_index] for i in self.Board] 40 | 41 | def check_win(self): 42 | """ 43 | checks for four_in_a_row in the positive and Negative diagonals 44 | 45 | Returns 46 | ------- 47 | the True if there is four in a row 48 | 49 | """ 50 | #check diagonals and rows 51 | four_in_row = [['1' for i in range(4)], ['2' for i in range(4)]] 52 | 53 | for check in self.get_diag_and_row(): 54 | 55 | for j in range(len(check)): 56 | 57 | if check[j:j+4] in four_in_row and j < len(check) - 3: 58 | #print ('yes') 59 | return True 60 | #Check columns 61 | for i in range(7): 62 | for j in range(6 - 3): 63 | if self.get_column(i)[j:j + 4] in four_in_row: 64 | return True 65 | 66 | else: 67 | return False 68 | 69 | def make_move(self, col, player): 70 | """ 71 | Parameters 72 | ---------- 73 | col : int. 74 | player : player 1 and 2. 75 | 76 | Returns 77 | ------- 78 | The Board with the players move registered. 79 | """ 80 | u = -1 81 | while self.Board[u][col] != ' ' and u != -6: 82 | u -= 1 83 | 84 | self.Board[u][col] = player 85 | pp.pprint(self.Board) 86 | return self.Board 87 | 88 | def play(self): 89 | """ 90 | To play the Connect4 game 91 | ------- 92 | Returns 93 | The winner of the game after each player makes their moves. 94 | """ 95 | pp.pprint(self.Board) 96 | for i in range(42): 97 | #pp.pprint(self.Board) 98 | 99 | col = int(input('Enter column: '))-1 100 | self.make_move(col, '1') 101 | if self.check_win() is True: 102 | 103 | return 'Player 1 Wins\nTHANKS FOR PLAYING' 104 | 105 | break 106 | 107 | col = int(input('Enter column: '))-1 108 | self.make_move(col, '2') 109 | if self.check_win() is True: 110 | 111 | return 'Player 2 Wins\nTHANKS FOR PLAYING' 112 | 113 | break 114 | 115 | 116 | game = ConnectFour() 117 | print(game.play()) 118 | -------------------------------------------------------------------------------- /Chapter 14 Exercise/Q_11.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Write a class called Poker_hand that has a field that is a list of Card objects. There should be 3 | the following self-explanatory methods: has_royal_flush, has_straight_flush, has_four_of_a_kind, 4 | has_full_house, has_flush, has_straight, has_three_of_a_kind, has_two_pair, has_pair. 5 | There should also be a method called best that returns a string indicating what the best hand 6 | is that can be made from those cards. 7 | ''' 8 | 9 | import random 10 | class Card: 11 | def __init__(self, value, suit): 12 | self.value = value 13 | self.suit = suit 14 | 15 | def __str__(self): 16 | names = ['Jack', 'Queen', 'King', 'Ace'] 17 | if self.value <= 10: 18 | return '{} of {}'.format(self.value, self.suit) 19 | else: 20 | return '{} of {}'.format(names[self.value - 11], self.suit) 21 | 22 | 23 | class PokerHand: 24 | def __init__(self): 25 | self.deck = [{'value': i, 'suit': c}for c in ['spades', 'clubs', 26 | 'hearts', 'diamonds']for i in range(2, 15)] 27 | self.deals = random.sample(self.deck, 5) 28 | self.suits = [(self.deals[i])['suit'] for i in range(len(self.deals))] 29 | self.values = [((self.deals[i])['value']) 30 | for i in range(len(self.deals))] 31 | 32 | self.cards = [Card(self.values[i], self.suits[i]).__str__() 33 | for i in range(len(self.deals))] 34 | self.values.sort() 35 | 36 | self.deck_count = {i: self.values.count(i) for i in self.values} 37 | self.card_count = [self.deck_count[i] for i in self.deck_count] 38 | self.card_count.sort() 39 | 40 | def straigth(self): 41 | 42 | return self.values == [self.values[0]+i for i in range(5)] or self.values == [2, 3, 4, 5, 14] 43 | 44 | def flush(self): 45 | return self.suits.count(self.suits[0]) == 5 46 | 47 | def straigth_flush(self): 48 | return self.straigth() and self.flush() 49 | 50 | def four_of_a_kind(self): 51 | return self.card_count == [1, 4] 52 | 53 | def three_of_a_kind(self): 54 | return self.card_count == [1, 1, 3] 55 | 56 | def two_pairs(self): 57 | return self.card_count == [1, 2, 2] 58 | 59 | def full_house(self): 60 | return self.card_count == [2, 3] 61 | 62 | def royal_flush(self): 63 | return self.values == [10, 11, 12, 13, 14] and self.flush() 64 | 65 | def one_pair(self): 66 | return self.card_count == [1, 1, 1, 2] 67 | 68 | def best_hand(self): 69 | for i, card in enumerate(self.cards): 70 | print(f'card {i+1}.', card) 71 | 72 | if self.royal_flush(): 73 | 74 | return ("BEST HAND IS ROYAL FLUSH ") 75 | 76 | elif self.straigth_flush(): 77 | return("BEST HAND IS STRAIGHT FLUSH") 78 | 79 | elif self.four_of_a_kind(): 80 | return("BEST HAND IS FOUR OF A KIND ") 81 | 82 | elif self.full_house(): 83 | return("BEST HAND IS FULL HOUSE") 84 | 85 | elif self.flush(): 86 | return("BEST HAND IS FLUSH ") 87 | 88 | elif self.straigth(): 89 | return("BEST HAND IS STRAIGHT ") 90 | 91 | elif self.three_of_a_kind(): 92 | return("BEST HAND IS THREE OF A KIND") 93 | 94 | elif self.two_pairs(): 95 | return("BEST HAND IS TWO PAIRS") 96 | 97 | elif self.one_pair(): 98 | return("BEST HAND IS ONE PAIR") 99 | else: 100 | return "YOU HAVE HIGH CARDS" 101 | 102 | poker = PokerHand() 103 | print(poker.best_hand()) 104 | -------------------------------------------------------------------------------- /Chapter 14 Exercise/Q_2.py: -------------------------------------------------------------------------------- 1 | """Write a class called Product. The class should have fields called name, amount, and price, 2 | holding the product’s name, the number of items of that product in stock, and the regular 3 | price of the product. There should be a method get_price that receives the number of 4 | items to be bought and returns a the cost of buying that many items, where the regular price 5 | 6 | is charged for orders of less than 10 items, a 10% discount is applied for orders of between 7 | 10 and 99 items, and a 20% discount is applied for orders of 100 or more items. There should 8 | also be a method called make_purchase that receives the number of items to be bought and 9 | decreases amount by that much. 10 | 11 | """ 12 | 13 | class Product: 14 | def __init__(self,name,amount ,price): 15 | self.name =name 16 | self.amount =amount 17 | self.price = price 18 | 19 | def get_price(self): 20 | return self.price * self.amount 21 | 22 | def make_purchase(self): 23 | if self.amount < 10: 24 | return "Discount Price", self.amount * self.price 25 | elif self.amount in range(9,100): 26 | return "Discount Price",self.amount * self.price-(self.price * 0.01) 27 | elif self.amount >= 100: 28 | return "Discount Price",self.amount * self.price - (self.price * 0.02) 29 | 30 | 31 | 32 | shop =Product("Henry",15,99) 33 | 34 | print(shop.make_purchase()) -------------------------------------------------------------------------------- /Chapter 14 Exercise/Q_3.py: -------------------------------------------------------------------------------- 1 | """"Write a class called Password_manager. The class should have a list called old_passwords 2 | that holds all of the user’s past passwords. The last item of the list is the user’s current password. 3 | There should be a method called get_password that returns the current password 4 | and a method called set_password that sets the user’s password. The set_password 5 | method should only change the password if the attempted password is different from all 6 | the user’s past passwords. Finally, create a method called is_correct that receives a string 7 | and returns a boolean True or False depending on whether the string is equal to the current 8 | password or not.""" 9 | 10 | class Password_manager: 11 | def __init__(self, old_passwords): 12 | self.old_passwords = paswords 13 | 14 | 15 | 16 | def get_password(self): 17 | return paswords[-1] 18 | 19 | def set_password(self): 20 | new_pass =(input("Enter Your New Pass: " )) 21 | if new_pass in paswords: 22 | return "Password found in list,Choose new pass" 23 | else: 24 | paswords.append(new_pass) 25 | return "New Password is Set",paswords[-1] 26 | 27 | 28 | 29 | 30 | def is_correct(self,string): 31 | if string == self.old_passwords[-1]: 32 | return True 33 | else: 34 | return False 35 | 36 | 37 | paswords= ["Henry","Gaga","Nelson"] 38 | a = Password_manager(paswords) 39 | 40 | #print(a.get_password()) 41 | #print(a.set_password()) 42 | print(a.is_correct("Nelson")) 43 | 44 | 45 | 46 | 47 | 48 | 49 | -------------------------------------------------------------------------------- /Chapter 14 Exercise/Q_4.py: -------------------------------------------------------------------------------- 1 | """"Write a class called Time whose only field is a time in seconds. It should have a method called 2 | convert_to_minutes that returns a string of minutes and seconds formatted as in the following 3 | example: if seconds is 230, the method should return '5:50'. It should also have 4 | a method called convert_to_hours that returns a string of hours, minutes, and seconds 5 | formatted analogously to the previous method.""" 6 | 7 | #NoteThe question has a slight mistake the Input of 230s should give an output of 3:50s and not 5:50s 8 | 9 | class Time: 10 | 11 | def __init__(self,seconds): 12 | self.seconds = seconds 13 | 14 | def convert_to_minutes(self): 15 | if self.seconds < 60: 16 | return self.seconds 17 | else: 18 | minute = int(self.seconds/60) 19 | sec = self.seconds% 60 20 | return "{} minutes :{} seconds".format(minute,sec) 21 | 22 | def convert_to_hours(self): 23 | if self.seconds < 60: 24 | hour =0 25 | minute = 0 26 | sec = self.seconds 27 | return "{} Hour :{} minutes :{} seconds".format(hour,minute,sec) 28 | elif self.seconds > 60 and self.seconds< 3600: 29 | hour = 0 30 | minute = int(self.seconds/60) 31 | sec = self.seconds % 60 32 | return "{} Hour :{} minutes :{} seconds".format(hour, minute, sec) 33 | elif self.seconds >= 3600: 34 | hour = int(self.seconds/3600) 35 | if self.seconds - 3600 < 60: 36 | minute =0 37 | else: 38 | minute = int((self.seconds - 3600) / 60) 39 | sec = int(self.seconds-3600)%60 40 | return "{} Hour :{} minutes :{} seconds".format(hour, minute, sec) 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | a =Time(5000) 50 | print(a.convert_to_minutes()) 51 | print(a.convert_to_hours()) -------------------------------------------------------------------------------- /Chapter 14 Exercise/Q_5.py: -------------------------------------------------------------------------------- 1 | """"Write a class called Wordplay. It should have a 2 | field that holds a 3 | list of words. The user 4 | of the class should pass the list of words they want to use to the class. 5 | There should be the 6 | following methods: 7 | • words_with_length(length)— returns a list of all the words of length length 8 | • starts_with(s)— returns a list of all the words that start with s 9 | • ends_with(s)— returns a list of all the words that end with s 10 | • palindromes()— returns a list of all the palindromes in the list 11 | • only(L)— returns a list of the words that contain only those letters in L 12 | • avoids(L)— returns a list of the words that contain none of the letters in L""" 13 | 14 | 15 | class Wordplay: 16 | def __init__(self): 17 | self.words_list = [] 18 | 19 | 20 | def words_with_length(self,length): 21 | wordlist = [] 22 | for w in self.words_list: 23 | if len(w) == length: 24 | wordlist.append(w) 25 | return "Words with length {} {}".format(length,wordlist) 26 | 27 | def start_with(self, s): 28 | wordlist = [] 29 | for w in self.words_list: 30 | if (w[0] == s): 31 | wordlist.append(w) 32 | return "Words Start with letter {} {}".format(s,wordlist) 33 | 34 | def ends_with(self,s): 35 | wordlist =[] 36 | for w in self.words_list: 37 | if w[-1] == s: 38 | wordlist.append(w) 39 | return "Words Ending with letter {} {}".format(s,wordlist) 40 | 41 | def palindrome(self): 42 | wordlist =[] 43 | for w in self.words_list: 44 | if w[::1] == w[::-1]: 45 | wordlist.append(w) 46 | return "Palindromes {}".format(wordlist) 47 | 48 | def only_L(self): 49 | wordlist =[] 50 | for w in self.words_list: 51 | if "l" in w: 52 | wordlist.append(w) 53 | return "Words containing L {}".format(wordlist) 54 | 55 | 56 | def Not_L(self): 57 | wordlist = [] 58 | for w in self.words_list: 59 | if "l" not in w: 60 | wordlist.append(w) 61 | return "Words Not containing L {}".format(wordlist) 62 | 63 | 64 | a = Wordplay() 65 | 66 | a.words_list=["solos","Marcus","Aurelius","Henryi","tirla","samantha","pocahontas","kayak"] 67 | 68 | print(a.words_with_length(5)) 69 | print(a.start_with("M")) 70 | print(a.ends_with("s")) 71 | print(a.palindrome()) 72 | print(a.ends_with("s")) 73 | print(a.only_L()) 74 | print(a.Not_L()) 75 | -------------------------------------------------------------------------------- /Chapter 14 Exercise/Q_6.py: -------------------------------------------------------------------------------- 1 | """Write a class called Converter. The user will pass a length and a unit when declaring an 2 | object from the class—for example, c = Converter(9,'inches'). The possible units are 3 | inches, feet, yards, miles, kilometers, meters, centimeters, and millimeters. For each of these 4 | units there should be a method that returns the length converted into those units. For example, 5 | using the Converter object created above, the user could call c.feet() and should get 6 | 0.75 as the result.""" 7 | 8 | class Converter: 9 | def __init__(self, length, unit): 10 | self.length = length 11 | self.unit = unit 12 | 13 | def convert(self, unit_convert): 14 | unit_list = ["inches", "feet", 'yards', 'miles', 'kilometers', 'meters', 'centimeters'] 15 | value_on_foot = [12, 1, 1 / 3, 1 / 5280, 1 / 3281, 1 / 3, 30] 16 | if unit_convert in unit_list: 17 | length_convert = round( 18 | self.length * value_on_foot[unit_list.index(unit_convert)] / value_on_foot[unit_list.index(self.unit)], 19 | 9) 20 | return "{1} {0}".format(length_convert, unit_convert) 21 | 22 | def inches(self): 23 | return self.convert('inches') 24 | 25 | def feet(self): 26 | return self.convert('feet') 27 | 28 | def yards(self): 29 | return self.convert('yards') 30 | 31 | def miles(self): 32 | return self.convert('miles') 33 | 34 | def kilometers(self): 35 | return self.convert('kilometers') 36 | 37 | def meters(self): 38 | return self.convert('meters') 39 | 40 | def centimeters(self): 41 | return self.convert('centimeters') 42 | 43 | 44 | c = Converter(9, "inches") 45 | print(c.yards()) 46 | print(c.miles()) 47 | -------------------------------------------------------------------------------- /Chapter 14 Exercise/Q_7.py: -------------------------------------------------------------------------------- 1 | """Use the Standard_deck class of this section to create a simplified version of 2 | the game War. 3 | In this game, there are two players. 4 | Each starts with half of a deck. The players each deal 5 | the top card from their decks and 6 | whoever has the higher card wins the other player’s cards 7 | and adds them to the bottom of his deck. If there is a tie, the two cards are eliminated from 8 | play (this differs from the actual game, but is simpler to program). The game ends when one 9 | player runs out of cards.""" 10 | 11 | from random import randint 12 | 13 | 14 | class Card: 15 | def __init__(self, value, suit): 16 | self.value = value 17 | self.suit = suit 18 | 19 | def __str__(self): 20 | names = ['Jack', 'Queen', 'King', 'Ace'] 21 | if self.value <= 10: 22 | return '{} of {}'.format(self.value, self.suit) 23 | else: 24 | return '{} of {}'.format(names[self.value - 11], self.suit) 25 | 26 | 27 | import random 28 | 29 | 30 | class Card_group: 31 | def __init__(self, cards=[]): 32 | self.cards = cards 33 | 34 | def nextCard(self): 35 | return self.cards.pop(0) 36 | 37 | def hasCard(self): 38 | return len(self.cards) > 0 39 | 40 | def size(self): 41 | return len(self.cards) 42 | 43 | def shuffleCard(self): 44 | return random.shuffle(self.cards) 45 | 46 | 47 | class Standard_deck(Card_group): 48 | def __init__(self): 49 | self.cards = [] 50 | for s in ['Hearts', 'Diamonds', 'Clubs', 'Spades']: 51 | for v in range(2, 15): 52 | self.cards.append(Card(v, s)) # hỏi chỗ này 53 | 54 | 55 | class War(Standard_deck): 56 | def __init__(self): 57 | Standard_deck.__init__(self) 58 | self.shuffleCard() 59 | self.player1 = [] 60 | self.player2 = [] 61 | self.__splitCardToPlayer() 62 | 63 | def __splitCardToPlayer(self): 64 | cardLength = len(self.cards) 65 | for i in range(0, cardLength, 2): 66 | self.player1.append(self.nextCard()) 67 | self.player2.append(self.nextCard()) 68 | 69 | 70 | 71 | def __popCard(self, playerNumber): 72 | if playerNumber == 1: 73 | return self.player1.pop() 74 | if playerNumber == 2: 75 | return self.player2.pop() 76 | 77 | def play(self): 78 | print('Playing card') 79 | while len(self.player1) > 0 and len(self.player2) > 0: 80 | card1 = self.__popCard(1) 81 | card2 = self.__popCard(2) 82 | if card1.value > card2.value: 83 | self.player1.append(card1) 84 | elif card2.value > card1.value: 85 | self.player2.append(card2) 86 | 87 | if len(self.player1) > 0: 88 | print("player 1 wins") 89 | elif len(self.player2) > 0: 90 | print("player 2 wins") 91 | else: 92 | print("noone win") 93 | 94 | 95 | deck = War() 96 | deck.play() 97 | 98 | -------------------------------------------------------------------------------- /Chapter 2 Exercise/Q_1.py: -------------------------------------------------------------------------------- 1 | """Write a program that prints your name 100 times.""" 2 | 3 | for i in range(100): 4 | print("Dr. Henry Tirla ") 5 | -------------------------------------------------------------------------------- /Chapter 2 Exercise/Q_10.py: -------------------------------------------------------------------------------- 1 | """ Use a for loop to print a box like the one below. Allow the user to specify how wide and how 2 | high the box should be. [Hint: print('*'*10) prints ten asterisks.] """ 3 | 4 | n=eval(input("Enter a number to specify how high you want your box: ")) 5 | 6 | for i in range(10): 7 | print("*"*n) #Changing this parameter increases the size 8 | 9 | 10 | -------------------------------------------------------------------------------- /Chapter 2 Exercise/Q_11.py: -------------------------------------------------------------------------------- 1 | """Use a for loop to print a box like the one below. Allow the user to specify how wide and how 2 | high the box should be.""" 3 | n=eval(input("Enter a number to specify how high you want your box: ")) 4 | for rows in range(n): 5 | for column in range(n): 6 | if (rows == 0 or rows == n-1 or column == 0 or column == n-1): 7 | print("*", end=" ") 8 | 9 | else: 10 | print(" ", end=" ") 11 | 12 | print() -------------------------------------------------------------------------------- /Chapter 2 Exercise/Q_12.py: -------------------------------------------------------------------------------- 1 | """Use a for loop to print a triangle like the one below. Allow the user to specify how high the 2 | triangle should be.""" 3 | n=eval(input("Enter a number to specify how high you want your triangle: ")) 4 | for rows in range (n): 5 | for colums in range(rows): 6 | print("*", end=" ") 7 | 8 | print() -------------------------------------------------------------------------------- /Chapter 2 Exercise/Q_13.py: -------------------------------------------------------------------------------- 1 | """Use a for loop to print an upside down triangle like the one below. Allow the user to specify 2 | how high the triangle should be.""" 3 | n=eval(input("Enter a number to specify how high you want your triangle: ")) 4 | 5 | for rows in range (n,0,-1): 6 | for colums in range(rows): 7 | print("*", end=" ") 8 | 9 | print() 10 | 11 | 12 | 13 | -------------------------------------------------------------------------------- /Chapter 2 Exercise/Q_14.py: -------------------------------------------------------------------------------- 1 | """Use for loops to print a diamond like the one below. Allow the user to specify how high the 2 | diamond should be. 3 | 4 | * 5 | *** 6 | ***** 7 | ******* 8 | ***** 9 | *** 10 | * """ 11 | 12 | n = eval(input("Enter a number to specify how high you want your triangle: ")) 13 | for i in range(n): 14 | print(" "*(n-i)+" *"*(i+1)) 15 | 16 | for j in range(n-1): 17 | print(" "*(j+2)+" *"*(n-1-j)) 18 | 19 | 20 | 21 | 22 | -------------------------------------------------------------------------------- /Chapter 2 Exercise/Q_2.py: -------------------------------------------------------------------------------- 1 | """Write a program to fill the screen horizontally and vertically with your name. [Hint: add the 2 | option end='' into the print function to fill the screen horizontally.]""" 3 | 4 | for i in range(10): 5 | print("Henry Tirla " * 6) -------------------------------------------------------------------------------- /Chapter 2 Exercise/Q_3.py: -------------------------------------------------------------------------------- 1 | """Write a program that outputs 100 lines, numbered 1 to 100, each with your name on it. The 2 | output should look like the output below.""" 3 | 4 | for i in range(1,101): 5 | print(i ,"Henry Tirla") -------------------------------------------------------------------------------- /Chapter 2 Exercise/Q_4.py: -------------------------------------------------------------------------------- 1 | """Write a program that prints out a list of the integers from 1 to 20 and their squares. The output 2 | should look like this:""" 3 | for i in range(1,21): 4 | print(i, i*i, sep="---") -------------------------------------------------------------------------------- /Chapter 2 Exercise/Q_5.py: -------------------------------------------------------------------------------- 1 | """Write a program that uses a for loop to print the numbers 8, 11, 14, 17, 20, . . . , 83, 86, 89.""" 2 | 3 | 4 | for i in range(8,90,3): 5 | print(i) -------------------------------------------------------------------------------- /Chapter 2 Exercise/Q_6.py: -------------------------------------------------------------------------------- 1 | """Write a program that uses a for loop to print the numbers 100, 98, 96, . . . , 4, 2.""" 2 | 3 | for i in range(100,1,-2): 4 | print(i) -------------------------------------------------------------------------------- /Chapter 2 Exercise/Q_7.py: -------------------------------------------------------------------------------- 1 | """Write a program that uses exactly four for loops to print the sequence of letters below. 2 | AAAAAAAAAABBBBBBBCDCDCDCDEFFFFFFG""" 3 | 4 | for i in range(10): 5 | print("A",end="") 6 | for i in range(7): 7 | print("B", end="") 8 | for i in range(4): 9 | print("CD",end="") 10 | print("E", end="") #Take not of this it's not in the for loop Prints only once only E and G 11 | 12 | for i in range(5): 13 | print("F",end="") 14 | print("G", end="") 15 | 16 | 17 | 18 | 19 | -------------------------------------------------------------------------------- /Chapter 2 Exercise/Q_8.py: -------------------------------------------------------------------------------- 1 | """Write a program that asks the user for their name and how many times to print it. The program 2 | should print out the user’s name the specified number of times.""" 3 | 4 | ask_user = input("Please Enter Your Name: ") 5 | printing_times = eval(input("How many times do you want to print your ")) 6 | 7 | for i in range(printing_times): 8 | print(ask_user) -------------------------------------------------------------------------------- /Chapter 2 Exercise/Q_9.py: -------------------------------------------------------------------------------- 1 | """The Fibonacci numbers are the sequence below, where the first two numbers are 1, and each 2 | number thereafter is the sum of the two preceding numbers. Write a program that asks the 3 | user how many Fibonacci numbers to print and then prints that many. 4 | 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89 . . .""" 5 | 6 | num = eval(input("How many Fibonacci Numbers do you want to Print: ")) 7 | first_number = 0 8 | second_number = 1 9 | print(first_number) 10 | print(second_number) 11 | for i in range(2,num): 12 | 13 | next_number =first_number + second_number 14 | first_number = second_number 15 | second_number = next_number 16 | 17 | print(next_number) 18 | 19 | 20 | 21 | 22 | 23 | 24 | -------------------------------------------------------------------------------- /Chapter 3 Exercise/Q_1.py: -------------------------------------------------------------------------------- 1 | """Write a program that generates and prints 50 random integers, each between 3 and 6.""" 2 | 3 | from random import randint 4 | 5 | for i in range(50): 6 | x=randint(3,6) 7 | print(x) 8 | -------------------------------------------------------------------------------- /Chapter 3 Exercise/Q_10.py: -------------------------------------------------------------------------------- 1 | """(a) One way to find out the last digit of a number is to mod the number by 10. Write a 2 | program that asks the user to enter a power. Then find the last digit of 2 raised to that 3 | power.""" 4 | 5 | exponent_number = eval(input("Enter the Value of the Exponent: ")) 6 | 7 | find_a = 2**exponent_number%10 8 | print("The Last two digits of the " , find_a) 9 | 10 | 11 | 12 | ## (b) Solution of this problem is change the value of 10 above to 100 13 | 14 | ## (c) Solution Use and if \else statement to solve the problem. -------------------------------------------------------------------------------- /Chapter 3 Exercise/Q_11.py: -------------------------------------------------------------------------------- 1 | """Write a program that asks the user to enter a weight in kilograms. The program should 2 | convert it to pounds, printing the answer rounded to the nearest tenth of a pound.""" 3 | 4 | ## 1kg = 2.20462 Pounds 5 | ## 1/10 meaning pound is rounded to one decimal number 6 | 7 | weight_kg = eval(input("Enter Your Weights in Kg: ")) 8 | 9 | kg_to_pound = round(weight_kg * 2.20462,1) 10 | 11 | print("Your Weight in Pounds is :",kg_to_pound) -------------------------------------------------------------------------------- /Chapter 3 Exercise/Q_12.py: -------------------------------------------------------------------------------- 1 | """Write a program that asks the user for a number and prints out the factorial of that number.""" 2 | 3 | 4 | 5 | 6 | number=eval(input("Enter a number: ")) 7 | factorial =1 8 | 9 | 10 | if number == 0: 11 | print("Factorial of this number does not exist") 12 | 13 | elif number ==1: 14 | print("Factorial of 0 is 1") 15 | 16 | else: 17 | 18 | for number in range(1,number+1): 19 | factorial = factorial * number 20 | 21 | 22 | print(factorial) 23 | 24 | -------------------------------------------------------------------------------- /Chapter 3 Exercise/Q_13.py: -------------------------------------------------------------------------------- 1 | """ Write a program that asks the user for a number and then prints out the sine, cosine, and 2 | tangent of that number. """ 3 | 4 | from math import sin ,cos ,tan 5 | number = eval(input("Enter a number: ")) 6 | 7 | print("The Sine is: ", sin(number),"The cosine is: ",cos(number),"The Tangent is: ",tan(number)) 8 | 9 | -------------------------------------------------------------------------------- /Chapter 3 Exercise/Q_14.py: -------------------------------------------------------------------------------- 1 | """ Write a program that asks the user to enter an angle in degrees and prints out the sine of that 2 | angle. """ 3 | 4 | 5 | from math import* 6 | import math 7 | 8 | number = math.radians(eval(input("Enter Degree: "))) 9 | # number = math.degrees(number) 10 | print("The Sin of Number is : ", sin(number)) 11 | -------------------------------------------------------------------------------- /Chapter 3 Exercise/Q_15.py: -------------------------------------------------------------------------------- 1 | """ Write a program that prints out the sine and cosine of the angles ranging from 0 to 345 in 2 | 15 increments. Each result should be rounded to 4 decimal places. Sample output is shown 3 | below: 4 | 0 --- 0.0 1.0 5 | 15 --- 0.2588 0.9659 6 | 30 --- 0.5 0.866 7 | ... 8 | 345 --- -0.2588 0.9659 """ 9 | 10 | 11 | import math 12 | from math import * 13 | 14 | for i in range(0,346,15): 15 | j = math.radians(i) 16 | print(i,"---",sin(j),cos(j)) -------------------------------------------------------------------------------- /Chapter 3 Exercise/Q_16.py: -------------------------------------------------------------------------------- 1 | """"Below is described how to find the date of Easter in any year. Despite its intimidating appearance, 2 | this is not a hard problem. Note that bxc is the floor function, which for positive numbers 3 | just drops the decimal part of the number. For instance b3.14c = 3. The floor function is part 4 | of the math module. 5 | C = century (1900’s ! C = 19) 6 | Y = year (all four digits) 7 | m = (15 + C 􀀀 b C 8 | 4 9 | c 􀀀 b 8C+13 10 | 25 11 | c) mod 30 12 | n = (4 + C 􀀀 b C 13 | 4 14 | c) mod 7 15 | a = Y mod 4 16 | b = Y mod 7 17 | c = Y mod 19 18 | d = (19c + m) mod 30 19 | e = (2a + 4b + 6d + n) mod 7 20 | Easter is either March (22+d+e) or April (d+e􀀀9). There is an exception if d = 29 and e = 6. 21 | In this case, Easter falls one week earlier on April 19. There is another exception if d = 28, 22 | e = 6, and m = 2, 5, 10, 13, 16, 21, 24, or 39. In this case, Easter falls one week earlier on April 23 | 18. Write a program that asks the user to enter a year and prints out the date of Easter in that 24 | year. (See Tattersall, Elementary Number Theory in Nine Chapters, 2nd ed., page 167)""" 25 | 26 | 27 | ##TODO -------------------------------------------------------------------------------- /Chapter 3 Exercise/Q_17.py: -------------------------------------------------------------------------------- 1 | """" A year is a leap year if it is divisible by 4, except that years divisible by 100 are not leap years 2 | unless they are also divisible by 400. Ask the user to enter a year, and, using the // operator, 3 | determine how many leap years there have been between 1600 and that year. """ 4 | 5 | 6 | year = eval(input("Enter a Year: ")) 7 | # 8 | # if year < 2000: 9 | # print("Enter any year as from 2000") 10 | 11 | for years in range(1600,year): 12 | if years % 4 == 0 or years % 100 == 0 and years % 400 == 0: 13 | print( years) 14 | 15 | 16 | -------------------------------------------------------------------------------- /Chapter 3 Exercise/Q_18.py: -------------------------------------------------------------------------------- 1 | """"18. Write a program that given an amount of change less than $1.00 will print out exactly how 2 | many quarters, dimes, nickels, and pennies will be needed to efficiently make that change. 3 | [Hint: the // operator may be useful.]""" 4 | 5 | ##To fully understand this problem you have to understand what are the differences between quaters ,dimes ,nickels and pennies. 6 | import sys 7 | 8 | """ Quater = 25cents 9 | Dimes = 10cents 10 | Nickel = 5cents 11 | Penny = 1cent 12 | 13 | """ 14 | 15 | 16 | number = eval(input("Enter a number beween 0-99: ")) 17 | if number < 0 or number > 99: 18 | print("You entered a number in the wrong range!!!!!") 19 | sys.exit() 20 | 21 | else: 22 | Quater = number // 25 23 | Dimes = number // 10 24 | Nickel = number // 5 25 | Penny = number // 1 26 | 27 | print("Quater = ",Quater, "Dimes = ", Dimes, "Nickel = ", Nickel, "Penny = ", Penny) -------------------------------------------------------------------------------- /Chapter 3 Exercise/Q_19.py: -------------------------------------------------------------------------------- 1 | """"Write a program that draws “modular rectangles” like the ones below. The user specifies the 2 | width and height of the rectangle, and the entries start at 0 and increase typewriter fashion 3 | from left to right and top to bottom, but are all done mod 10. Below are examples of a 3  5 4 | rectangle and a 4  8. 5 | 0 1 2 3 4 6 | 5 6 7 8 9 7 | 0 1 2 3 4 8 | 9 | 0 1 2 3 4 5 6 7 10 | 8 9 0 1 2 3 4 5 11 | 6 7 8 9 0 1 2 3 12 | 4 5 6 7 8 9 0 1""" 13 | 14 | width = eval(input("Enter Width: ")) 15 | height = eval(input("Enter Height: ")) 16 | 17 | for i in range(0,width*height,1): 18 | print("") 19 | for j in range(0+i,width+i,1): 20 | print(j%10,end="") 21 | 22 | -------------------------------------------------------------------------------- /Chapter 3 Exercise/Q_2.py: -------------------------------------------------------------------------------- 1 | """Write a program that generates a random number, x, between 1 and 50, a random number y 2 | between 2 and 5, and computes x y .""" 3 | 4 | from random import randint 5 | 6 | x=randint(1,50) 7 | y= randint(2,5) 8 | compute = x**y 9 | print("The value of X is:",x,"The value of Y is:",y,"The value of X^Y is",compute) -------------------------------------------------------------------------------- /Chapter 3 Exercise/Q_3.py: -------------------------------------------------------------------------------- 1 | """Write a program that generates a random number between 1 and 10 and prints your name 2 | that many times.""" 3 | 4 | from random import randint 5 | x=input("Enter your Name:") 6 | n = randint(1,10) 7 | for i in range(n): 8 | print(x) 9 | -------------------------------------------------------------------------------- /Chapter 3 Exercise/Q_4.py: -------------------------------------------------------------------------------- 1 | """Write a program that generates a random decimal number between 1 and 10 with two decimal 2 | places of accuracy. Examples are 1.23, 3.45, 9.80, and 5.00.""" 3 | 4 | import random 5 | x = round(random.uniform(1,10),2) 6 | 7 | 8 | print(x) 9 | -------------------------------------------------------------------------------- /Chapter 3 Exercise/Q_5.py: -------------------------------------------------------------------------------- 1 | """ Write a program that generates 50 random numbers such that the first number is between 1 2 | and 2, the second is between 1 and 3, the third is between 1 and 4, . . . , and the last is between 3 | 1 and 51.""" 4 | # from random import randint 5 | # for n in range(2,52): 6 | # x=randint(1,n) 7 | # print(x) 8 | 9 | def factorial(num): 10 | if num == 1: 11 | return 1 12 | return num * factorial(num-1) 13 | 14 | print(factorial(4)) -------------------------------------------------------------------------------- /Chapter 3 Exercise/Q_6.py: -------------------------------------------------------------------------------- 1 | """Write a program that asks the user to enter two numbers, x and y, and computes jx􀀀yj 2 | x+y .""" 3 | 4 | x = eval(input("Enter the value of X: ")) 5 | y = eval(input("Enter the value of Y: ")) 6 | 7 | print((x-y)/(x+y)) -------------------------------------------------------------------------------- /Chapter 3 Exercise/Q_7.py: -------------------------------------------------------------------------------- 1 | x=eval(input("Enter size of angle between -180 and 180 degrees: ")) 2 | ## modulo gives the remainder, so the positive value, must return itself, which requires addition to 360, while the negative angle returns a value less than 360 3 | print("The equivalent of the angle on the range between 0 and 360 degrees is", (x+360)%360) 4 | -------------------------------------------------------------------------------- /Chapter 3 Exercise/Q_8.py: -------------------------------------------------------------------------------- 1 | """Write a program that asks the user for a number of seconds and prints out how many minutes 2 | and seconds that is. For instance, 200 seconds is 3 minutes and 20 seconds. [Hint: Use the // 3 | operator to get minutes and the % operator to get seconds.]""" 4 | 5 | seconds= eval(input("Enter the number of seconds: ")) 6 | 7 | 8 | time_in_minutes =int(seconds /60) 9 | time_in_seconds = seconds % 60 10 | 11 | print("The time is " , time_in_minutes,"minutes ", time_in_seconds,"seconds") 12 | -------------------------------------------------------------------------------- /Chapter 3 Exercise/Q_9.py: -------------------------------------------------------------------------------- 1 | """"Write a program that asks the user for an hour between 1 and 12 and for how many hours in 2 | the future they want to go. Print out what the hour will be that many hours into the future. 3 | 4 | An example is shown below. 5 | Enter hour: 8 6 | How many hours ahead? 5 7 | New hour: 1 o'clock 8 | """ 9 | 10 | hour = eval(input("Enter the the Current Hour between 1-12 : ")) 11 | projected_hour = eval(input("Enter Projected Hour: ")) 12 | 13 | current_hour = hour + projected_hour 14 | 15 | if current_hour > 12: 16 | current_hour = current_hour % 12 17 | 18 | 19 | print("New Hour :",current_hour," O'clock") 20 | -------------------------------------------------------------------------------- /Chapter 4 Exercise/Q_1.py: -------------------------------------------------------------------------------- 1 | """Write a program that asks the user to enter a length in centimeters. If the user enters a negative 2 | length, the program should tell the user that the entry is invalid. Otherwise, the program 3 | should convert the length to inches and print out the result. There are 2.54 centimeters in an 4 | inch.""" 5 | 6 | import sys 7 | length_cm = eval(input("Enter Lenth in Centimeters: ")) 8 | if length_cm < 0: 9 | print("You Have Entered an Invalid Number") 10 | sys.exit() 11 | 12 | else: 13 | length_inches = length_cm / 2.54 14 | print(length_inches," inches") -------------------------------------------------------------------------------- /Chapter 4 Exercise/Q_10.py: -------------------------------------------------------------------------------- 1 | """"Write a multiplication game program for kids. The program should give the player ten randomly 2 | generated multiplication questions to do. After each, the program should tell them 3 | whether they got it right or wrong and what the correct answer is. """ 4 | 5 | from random import randint 6 | 7 | 8 | questions = 0 9 | 10 | for questions in range(10): 11 | num_1 = randint(1, 10) 12 | num_2 = randint(1, 10) 13 | questions += 1 14 | 15 | print("Question :",questions ,num_1 ,"X",num_2) 16 | solution =eval(input("Enter Solution: ")) 17 | 18 | if(solution == num_1 * num_2): 19 | print("YaY you got it Right!!") 20 | 21 | else: 22 | print(solution,"Your Answer is Wrong") 23 | 24 | -------------------------------------------------------------------------------- /Chapter 4 Exercise/Q_11.py: -------------------------------------------------------------------------------- 1 | """Write a program that asks the user for an hour between 1 and 12, asks them to enter am or pm, 2 | and asks them how many hours into the future they want to go. Print out what the hour will 3 | be that many hours into the future, printing am or pm as appropriate. An example is shown 4 | below. 5 | Enter hour: 8 6 | am (1) or pm (2)? 1 7 | How many hours ahead? 5 8 | New hour: 1 pm """ 9 | 10 | 11 | hour = eval(input("Enter Hour Between 1 and 12: ")) 12 | 13 | enter_am_pm = input("Choose 1 for AM and 2 for pm") 14 | 15 | future_hour = eval(input("Enter Hours in the future: ")) 16 | 17 | if enter_am_pm == 1: 18 | print("Future Hours ", enter_am_pm + future_hour) 19 | 20 | 21 | 22 | -------------------------------------------------------------------------------- /Chapter 4 Exercise/Q_12.py: -------------------------------------------------------------------------------- 1 | """A jar of Halloween candy contains an unknown amount of candy and if you can guess exactly 2 | how much candy is in the bowl, then you win all the candy. You ask the person in charge the 3 | following: If the candy is divided evenly among 5 people, how many pieces would be left 4 | over? The answer is 2 pieces. You then ask about dividing the candy evenly among 6 people, 5 | and the amount left over is 3 pieces. Finally, you ask about dividing the candy evenly among 6 | 7 people, and the amount left over is 2 pieces. By looking at the bowl, you can tell that there 7 | are less than 200 pieces. Write a program to determine how many pieces are in the bowl.""" 8 | 9 | 10 | for candies in range(200): 11 | if (candies % 5 != 2): 12 | continue 13 | if (candies % 6 != 3): 14 | continue 15 | if (candies % 7 != 2): 16 | continue 17 | 18 | print(str(candies) + " is the answer!") 19 | break -------------------------------------------------------------------------------- /Chapter 4 Exercise/Q_13.py: -------------------------------------------------------------------------------- 1 | """Write a program that lets the user play Rock-Paper-Scissors against the computer. There 2 | should be five rounds, and after those five rounds, your program should print out who won 3 | and lost or that there is a tie.""" 4 | 5 | from random import randint 6 | game = 0 7 | 8 | rock = 1 9 | paper =2 10 | scissors =3 11 | wins =0 12 | loose =0 13 | 14 | 15 | for game in range(5): 16 | print("Game",game,"Start") 17 | 18 | my_hand = eval(input("Choose Rock , paper or scissors: ")) 19 | computer_hand = randint(1, 3) 20 | if my_hand == computer_hand : 21 | print ("You and Computer Played the same hand its a tie..") 22 | elif my_hand == rock and computer_hand == scissors: 23 | print("Yay I crushed the computer scissors") 24 | wins += 1 25 | elif my_hand == rock and computer_hand == paper: 26 | print("Oops Computer Cover my Rock") 27 | loose += 1 28 | elif my_hand == paper and computer_hand == rock: 29 | print("Yay!! I covered computer rock haha") 30 | wins += 1 31 | elif my_hand == paper and computer_hand == scissors: 32 | print("Oops Computer cut me up into piece") 33 | loose += 1 34 | elif my_hand == scissors and computer_hand == rock: 35 | print("Oops Computer Shattered My scissors") 36 | loose += 1 37 | elif my_hand == scissors and computer_hand == paper: 38 | print("Yay I cut up computer paper into pieces") 39 | wins += 1 40 | 41 | if wins > loose: 42 | print("You win ", "You Scored ",wins,"Computer Scored",loose) 43 | 44 | else: 45 | print("You loosed Try Again") 46 | 47 | -------------------------------------------------------------------------------- /Chapter 4 Exercise/Q_2.py: -------------------------------------------------------------------------------- 1 | """Ask the user for a temperature. Then ask them what units, Celsius or Fahrenheit, the temperature 2 | is in. Your program should convert the temperature to the other unit. The conversions 3 | are F = 95 4 | C + 32 and C = 59 5 | (F 􀀀 32).""" 6 | import sys 7 | temperature = int(input("Enter Temperateture: ")) 8 | degree = input("What Units C or F :") 9 | 10 | if degree == "F" : 11 | c = 5/9*(temperature-32) 12 | print("Your Temperature in Celcius is: ", c) 13 | 14 | elif degree =="C": 15 | f= 9/5*temperature + 32 16 | print("Your temperature in Fahrenheit is: ", f) 17 | 18 | 19 | elif degree != "C" and degree!= "F": 20 | print("You entered wrong Units") 21 | sys.exit() 22 | 23 | 24 | -------------------------------------------------------------------------------- /Chapter 4 Exercise/Q_3.py: -------------------------------------------------------------------------------- 1 | """Ask the user to enter a temperature in Celsius. The program should print a message based 2 | on the temperature: 3 | • If the temperature is less than -273.15, print that the temperature is invalid because it is 4 | below absolute zero. 5 | • If it is exactly -273.15, print that the temperature is absolute 0. 6 | • If the temperature is between -273.15 and 0, print that the temperature is below freezing. 7 | • If it is 0, print that the temperature is at the freezing point. 8 | • If it is between 0 and 100, print that the temperature is in the normal range. 9 | • If it is 100, print that the temperature is at the boiling point. 10 | • If it is above 100, print that the temperature is above the boiling point.""" 11 | 12 | 13 | temp_celcuis = eval(input("Enter temperature in Celcuis: ")) 14 | absolute_zero = -273.15 15 | if temp_celcuis < absolute_zero: 16 | print("Temperature is invalid and below freezing point") 17 | elif temp_celcuis == absolute_zero: 18 | print("The temperature is absolute zero") 19 | elif temp_celcuis <= 0 : 20 | print("Temperature is below freezing point") 21 | elif temp_celcuis == 0: 22 | print("Temperatur is at freezing point") 23 | elif temp_celcuis > 0 and temp_celcuis < 100: 24 | print("Temperature is in normal range") 25 | elif temp_celcuis == 100: 26 | print("The temperature is at boiling point") 27 | elif temp_celcuis > 100: 28 | print("The temperature is above boiling point") 29 | 30 | 31 | -------------------------------------------------------------------------------- /Chapter 4 Exercise/Q_4.py: -------------------------------------------------------------------------------- 1 | """Write a program that asks the user how many credits they have taken. If they have taken 23 2 | or less, print that the student is a freshman. If they have taken between 24 and 53, print that 3 | they are a sophomore. The range for juniors is 54 to 83, and for seniors it is 84 and over.""" 4 | 5 | credits_taken = eval(input("Emter the number of credit taken: ")) 6 | 7 | if credits_taken <= 23: 8 | print("You are a fresh man") 9 | elif credits_taken >= 24 and credits_taken <= 53: 10 | print("You are a sophormore") 11 | elif credits_taken >= 54 and credits_taken <= 83: 12 | print("You are a Junior") 13 | elif credits_taken >= 84: 14 | print("Congrats You are a Senior") -------------------------------------------------------------------------------- /Chapter 4 Exercise/Q_5.py: -------------------------------------------------------------------------------- 1 | """Generate a random number between 1 and 10. Ask the user to guess the number and print a 2 | message based on whether they get it right or not.""" 3 | 4 | ### This isn't the exact answer to this but it was fun to let the user guess again and again. 5 | from random import randint 6 | 7 | random_number = randint(1,10) 8 | 9 | 10 | game = 0 11 | while game < 6: 12 | guess = eval(input("Guess generated random number: ")) 13 | game =game + 1 14 | 15 | 16 | if guess == random_number: 17 | print("You Guessed right!") 18 | break 19 | elif guess > random_number: 20 | print("Input number is greater than Random number") 21 | 22 | elif guess < random_number: 23 | print("Input is less than random number") 24 | 25 | 26 | 27 | -------------------------------------------------------------------------------- /Chapter 4 Exercise/Q_6.py: -------------------------------------------------------------------------------- 1 | """A store charges $12 per item if you buy less than 10 items. If you buy between 10 and 99 2 | items, the cost is $10 per item. If you buy 100 or more items, the cost is $7 per item. Write a 3 | program that asks the user how many items they are buying and prints the total cost.""" 4 | 5 | item_tobuy = eval(input("How many items do you want to buy:")) 6 | 7 | if item_tobuy < 10: 8 | print("Total price is: ", item_tobuy*10) 9 | 10 | elif item_tobuy in range(10,100): 11 | print("Total price is:", item_tobuy*10) 12 | elif item_tobuy >= 100: 13 | print("Total price is: ",item_tobuy*7 ) 14 | -------------------------------------------------------------------------------- /Chapter 4 Exercise/Q_7.py: -------------------------------------------------------------------------------- 1 | """Write a program that asks the user for two numbers and prints Close if the numbers are 2 | within .001 of each other and Not close otherwise.""" 3 | 4 | num1 = eval(input("Enter First Number: ")) 5 | num2 = eval(input("Enter Second Number:")) 6 | 7 | if num1 + 0.001 == num2: 8 | 9 | print("close") 10 | 11 | elif num2 + 0.001 == num1: 12 | 13 | print("close") 14 | 15 | else: 16 | print("Not close") 17 | -------------------------------------------------------------------------------- /Chapter 4 Exercise/Q_8.py: -------------------------------------------------------------------------------- 1 | """A year is a leap year if it is divisible by 4, except that years divisible by 100 are not leap years 2 | unless they are also divisible by 400. Write a program that asks the user for a year and prints 3 | out whether it is a leap year or not.""" 4 | 5 | year = int(input("Enter Year To Check if its a leap year: ")) 6 | 7 | if year % 4 == 0 or year % 100 != 0 and year % 400 == 0: 8 | 9 | print(year," Is a leap year") 10 | 11 | else: 12 | print(year,"Is not a leap Year") 13 | 14 | -------------------------------------------------------------------------------- /Chapter 4 Exercise/Q_9.py: -------------------------------------------------------------------------------- 1 | """Write a program that asks the user to enter a number and prints out all the divisors of that 2 | number. [Hint: the % operator is used to tell if a number is divisible by something.""" 3 | 4 | 5 | number = eval(input("Enter a number: ")) 6 | 7 | for i in range(1,number): 8 | if number % i == 0: 9 | print( i) -------------------------------------------------------------------------------- /Chapter 5 Exercise/Q_1.py: -------------------------------------------------------------------------------- 1 | """Write a program that counts how many of the squares of the numbers from 1 to 100 end in a 2 | 1.""" 3 | 4 | count = 0 5 | 6 | 7 | for i in range(1,100): 8 | if (i**i % 10 == 1 or i**i % 10 == 9): 9 | count += 1 10 | #print(i) can be use to confirm numbers displayed squares actually end with one 11 | print(count) -------------------------------------------------------------------------------- /Chapter 5 Exercise/Q_10.py: -------------------------------------------------------------------------------- 1 | """ 2 | Ask the user to enter 10 test scores. Write a program to do the following: 3 | (a) Print out the highest and lowest scores. 4 | (b) Print out the average of the scores. 5 | (c) Print out the second largest score. 6 | (d) If any of the scores is greater than 100, then after all the scores have been entered, print 7 | a message warning the user that a value over 100 has been entered. 8 | (e) Drop the two lowest scores and print out the average of the rest of them. 9 | """ 10 | 11 | from statistics import mean 12 | 13 | mylist = [] 14 | 15 | for i in range(10): 16 | score = eval(input(f'Enter Test Score {i+1}: ')) 17 | while score < 0 or score > 100: 18 | score = eval(input(f'Invalid. Enter Test Score {i+1}: ')) 19 | continue 20 | mylist.append(score) 21 | 22 | mylist.sort(reverse = True) 23 | max_score = max(mylist) 24 | min_score = min(mylist) 25 | max2_score = mylist[1] 26 | ave_score = mean(mylist) 27 | ave2_score = mean(mylist[:-2]) 28 | 29 | print(f'The maximum score was {max_score} and the minimum score was {min_score}.') 30 | print(f'The 2nd largest score was {max2_score}.') 31 | print(f'The average was {ave_score}. The average score with the two lowaest scores dropped is {ave2_score}.') 32 | -------------------------------------------------------------------------------- /Chapter 5 Exercise/Q_11.py: -------------------------------------------------------------------------------- 1 | def factorial(x): 2 | for i in range(1, x): 3 | x *= i 4 | print(f'Factorial is {x}.') 5 | num = eval(input('Enter a number: ')) 6 | factorial(num) 7 | -------------------------------------------------------------------------------- /Chapter 5 Exercise/Q_12.py: -------------------------------------------------------------------------------- 1 | """ 2 | Write a program that asks the user to guess a random number between 1 and 10. If they guess 3 | right, they get 10 points added to their score, and they lose 1 point for an incorrect guess. Give 4 | the user five numbers to guess and print their score after all the guessing is done. 5 | """ 6 | 7 | from random import randint 8 | 9 | score = 0 10 | 11 | for i in range(5): 12 | comp_guess = randint(1, 10) 13 | user_guess = eval(input('Enter guess between 1 and 10: ')) 14 | while user_guess < 0 or user_guess > 10: 15 | user_guess = eval(input('Invalid. Enter guess between 1 and 10: ')) 16 | continue 17 | if user_guess == comp_guess: 18 | score += 10 19 | print(f'You guessed right! Your score is {score}.') 20 | else: 21 | score -= 1 22 | print(f'Wrong. Computer guessed {comp_guess}. You guessed {user_guess}.') 23 | print(f'\nAfter 5 rounds, your total score is {score}.') 24 | -------------------------------------------------------------------------------- /Chapter 5 Exercise/Q_14.py: -------------------------------------------------------------------------------- 1 | """ 2 | This exercise is about the well-known Monty Hall problem. In the problem, you are a contestant on a game show. The host, Monty Hall, shows you three doors. 3 | Behind one of those doors is a prize, and behind the other two doors are goats. You pick a door. Monty Hall, who knows behind which door the prize lies, 4 | then opens up one of the doors that doesn’t contain the prize. There are now two doors left, and Monty gives you the opportunity to change your 5 | choice. Should you keep the same door, change doors, or does it not matter? 6 | 7 | Write a program that simulates playing this game 10000 times and calculates what percentage of the time you would win if you switch and what percentage of the time you 8 | would win by not switching. 9 | """ 10 | 11 | from random import randint, choice 12 | 13 | count = 0 14 | 15 | for i in range(1000): 16 | user_guess = randint(1, 3) 17 | prize = randint(1, 3) 18 | if prize == 1: 19 | doors = [1, randint(2,3)] 20 | if user_guess not in doors: 21 | user_guess = choice(doors) 22 | if user_guess == prize: 23 | count += 1 24 | else: 25 | if user_guess == prize: 26 | count += 1 27 | if prize == 2: 28 | doors = [2, randint(1,3)] 29 | if user_guess not in doors: 30 | user_guess = choice(doors) 31 | if user_guess == prize: 32 | count += 1 33 | else: 34 | if user_guess == prize: 35 | count += 1 36 | if prize == 3: 37 | doors = [3, randint(2,3)] 38 | if user_guess not in doors: 39 | user_guess = choice(doors) 40 | if user_guess == prize: 41 | count += 1 42 | else: 43 | if user_guess == prize: 44 | count += 1 45 | percentage = round((count/1000) * 100, 2) 46 | print(f'User chose the correct door {count} amount of times out of 1000. The percentage is {percentage}%.') 47 | -------------------------------------------------------------------------------- /Chapter 5 Exercise/Q_2.py: -------------------------------------------------------------------------------- 1 | """Write a program that counts how many of the squares of the numbers from 1 to 100 end in a 2 | 4 and how many end in a 9.""" 3 | 4 | count = 0 5 | 6 | 7 | for i in range(1,100): 8 | if (i**i % 10 == 4 or i**i % 10 == 7 ): 9 | count += 1 10 | # print(i) 11 | print(count) -------------------------------------------------------------------------------- /Chapter 5 Exercise/Q_3.py: -------------------------------------------------------------------------------- 1 | """Write a program that asks the user to enter a value n, and then computes (1+ 1 2 | 2 + 1 3 | 3 +  + 1 4 | n )􀀀 5 | ln(n). The ln function is log in the math module.""" 6 | 7 | import math 8 | 9 | # n = eval(input("Enter value of n")) 10 | -------------------------------------------------------------------------------- /Chapter 5 Exercise/Q_4.py: -------------------------------------------------------------------------------- 1 | """Write a program to compute the sum 1 􀀀 2 + 3 􀀀 4 +    + 1999 􀀀 2000.""" 2 | 3 | 4 | import matplotlib 5 | num = 1 6 | for i in range(1,6): 7 | sol = num - (i+1) 8 | num += 1 9 | print(sol) 10 | 11 | 12 | 13 | -------------------------------------------------------------------------------- /Chapter 5 Exercise/Q_5.py: -------------------------------------------------------------------------------- 1 | """ Write a program that asks the user to enter a number and prints the sum of the divisors of 2 | that number. The sum of the divisors of a number is an important function in number theory.""" 3 | 4 | def sumDivisors(x): 5 | a = [] 6 | for i in range(1,x): 7 | if x % i == 0: 8 | a.append(i) 9 | return a,"With Sum",sum(a) 10 | 11 | 12 | x = int(input("Enter X:")) 13 | print(sumDivisors(x)) 14 | 15 | -------------------------------------------------------------------------------- /Chapter 5 Exercise/Q_6.py: -------------------------------------------------------------------------------- 1 | """A number is called a perfect number if it is equal to the sum of all of its divisors, not including 2 | the number itself. For instance, 6 is a perfect number because the divisors of 6 are 1, 2, 3, 6 3 | and 6 = 1 + 2 + 3. As another example, 28 is a perfect number because its divisors are 1, 2, 4, 4 | 7, 14, 28 and 28 = 1 + 2 + 4 + 7 + 14. However, 15 is not a perfect number because its divisors 5 | are 1, 3, 5, 15 and 15 6= 1 + 3 + 5. Write a program that finds all four of the perfect numbers 6 | that are less than 10000.""" 7 | 8 | 9 | 10 | def perfectNum(x): 11 | for num in range(1,x): 12 | divisors = [] 13 | results = 0 14 | perfect_num=[] 15 | not_prime=[] 16 | for i in range(1,num): 17 | if num % i == 0: 18 | divisors.append(i) 19 | results = sum(divisors) 20 | 21 | 22 | if results == num: 23 | perfect_num.append(results) 24 | print("divisors",divisors,"num",num,"SumDivisors",results,"Perfect NUm",perfect_num) 25 | 26 | print(perfectNum(10000)) 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | -------------------------------------------------------------------------------- /Chapter 5 Exercise/Q_7.py: -------------------------------------------------------------------------------- 1 | """An integer is called squarefree if it is not divisible by any perfect squares other than 1. For 2 | instance, 42 is squarefree because its divisors are 1, 2, 3, 6, 7, 21, and 42, and none of those 3 | numbers (except 1) is a perfect square. On the other hand, 45 is not squarefree because it is 4 | divisible by 9, which is a perfect square. Write a program that asks the user for an integer and 5 | tells them if it is squarefree or not.""" 6 | 7 | from math import sqrt 8 | def squareFree(num): 9 | #for num in range(1,n): 10 | divisors = [] 11 | results = 0 12 | square_num = [] 13 | 14 | for i in range(1, num): 15 | if num % i == 0: 16 | divisors.append(i) 17 | results = sum(divisors) 18 | for j in range(len(divisors)): 19 | while divisors[j] != 1 and divisors[j] % sqrt(divisors[j]) == 0 : 20 | #sq =num / divisors[j] != 0 21 | if num % divisors[j] == 0: 22 | square_num.append(divisors[j]) 23 | return(num,"SQUARES FOUND,Its Squares are",square_num,divisors) 24 | else : 25 | return (num,"Is not a square",divisors) 26 | 27 | ##When No ssquare is found none is returned .##This is a bug im still to fix 28 | 29 | print(squareFree(49)) -------------------------------------------------------------------------------- /Chapter 5 Exercise/Q_8.py: -------------------------------------------------------------------------------- 1 | """Write a program that swaps the values of three variables a, b, and c, so that a gets the value 2 | of b, b gets the value of c, and c gets the value of a.""" 3 | 4 | 5 | def swapThree(a, b, c): 6 | # Store sum of all in a 7 | a = a + b + c # (a = 6) 8 | 9 | # After this, b has value of a 10 | b = a - (b + c) # (b = 6 – (3+2) =1) 11 | 12 | # After this, c has value of b 13 | c = a - (b + c) # (c = 6 – (1 + 3) = 2) 14 | 15 | # After this, a has value of c 16 | a = a - (b + c) 17 | 18 | return ("After swapping a =", a, ", b =", b, ", c =", c) 19 | 20 | 21 | print(swapThree(1,2,3)) 22 | 23 | ##credit https://www.geeksforgeeks.org/swap-three-variables-without-using-temporary-variable/ -------------------------------------------------------------------------------- /Chapter 5 Exercise/Q_9.py: -------------------------------------------------------------------------------- 1 | from math import sqrt 2 | count = 0 3 | for num in range(1, 1001): 4 | if sqrt(num) % 1 != 0 and (num**(1/3)) % 1 != 0 and (num**(1/5)) % 1 != 0: 5 | count+=1 6 | print(f'There are {count} numbers that are not perfect squares, cubes, or fifths.') 7 | -------------------------------------------------------------------------------- /Chapter 6 Exercise/Q_1.py: -------------------------------------------------------------------------------- 1 | """Write a program that asks the user to enter a string. The program should then print the 2 | following: 3 | (a) The total number of characters in the string 4 | (b) The string repeated 10 times 5 | (c) The first character of the string (remember that string indices start at 0) 6 | (d) The first three characters of the string 7 | (e) The last three characters of the string 8 | (f) The string backwards 9 | (g) The seventh character of the string if the string is long enough and a message otherwise 10 | (h) The string with its first and last characters removed 11 | (i) The string in all caps 12 | (j) The string with every a replaced with an e 13 | (k) The string with every letter replaced by a space 14 | """ 15 | 16 | enter_string = input("Enter Your Full names: ") 17 | 18 | print("(a)" , len(enter_string)) 19 | print("(b)", enter_string * 10) 20 | print("(c)", enter_string[:1]) 21 | print("(d)",enter_string[:3]) 22 | print("(e)", enter_string[-3:]) 23 | print("(f)",enter_string[::-1]) 24 | 25 | if len(enter_string) > 7: 26 | print("(g)",enter_string[:7]) 27 | else: 28 | print("(g)","String not long enough") 29 | 30 | print("(h)", enter_string[1:-1]) 31 | 32 | print("(i)",enter_string.upper()) 33 | for a in range(len(enter_string)): 34 | if enter_string[a] == 'a': 35 | enter_string = enter_string.replace('a', "e") 36 | print("(j)",enter_string) 37 | 38 | 39 | 40 | 41 | for a in range(len(enter_string)): 42 | if enter_string.isalpha(): 43 | enter_string = enter_string.replace(enter_string, " ") 44 | print("(k)",enter_string,end="") 45 | 46 | 47 | 48 | 49 | -------------------------------------------------------------------------------- /Chapter 6 Exercise/Q_10.py: -------------------------------------------------------------------------------- 1 | """Write a program that asks the user to enter a string, then prints out each letter of the string 2 | doubled and on a separate line. For instance, if the user entered HEY, the output would be 3 | HH 4 | EE 5 | YY""" 6 | 7 | user_string = input("Enter String: ") 8 | 9 | for letter in user_string: 10 | print(letter * 2) -------------------------------------------------------------------------------- /Chapter 6 Exercise/Q_11.py: -------------------------------------------------------------------------------- 1 | 2 | """Write a program that asks the user to enter a word that contains the letter a. The program 3 | should then print the following two lines: On the first line should be the part of the string up 4 | to and including the the first a, and on the second line should be the rest of the string. Sample 5 | output is shown below: 6 | 7 | Enter a word: buffalo 8 | buffa 9 | lo""" 10 | 11 | input_string = input("Enter a String that contains the letter a: ") 12 | # 13 | for letters in range(len(input_string)): 14 | 15 | if input_string[letters] == "a": 16 | print(input_string[:letters+1]) 17 | print(input_string[letters+1:]) 18 | #eg Buffalo, binance 19 | 20 | 21 | -------------------------------------------------------------------------------- /Chapter 6 Exercise/Q_12.py: -------------------------------------------------------------------------------- 1 | """Write a program that asks the user to enter a word and then capitalizes every other letter of 2 | that word. So if the user enters rhinoceros, the program should print rHiNoCeRoS.""" 3 | 4 | 5 | user_input = input("Enter word: ") 6 | result = "" 7 | for letters in range(len(user_input)): 8 | if letters % 2 != 0: 9 | result = result + user_input[letters].upper() 10 | else: 11 | result = result + user_input[letters].lower() 12 | 13 | print(result) 14 | 15 | -------------------------------------------------------------------------------- /Chapter 6 Exercise/Q_13.py: -------------------------------------------------------------------------------- 1 | """Write a program that asks the user to enter two strings of the same length. The program 2 | should then check to see if the strings are of the same length. If they are not, the program 3 | should print an appropriate message and exit. If they are of the same length, the program 4 | should alternate the characters of the two strings. For example, if the user enters abcde and 5 | ABCDE the program should print out AaBbCcDdEe.""" 6 | 7 | first_string = input("Enter First String: ") 8 | second_string = input("Enter Second String: ") 9 | 10 | 11 | res = "" 12 | if len(first_string) != len(second_string): 13 | print("Both Strings Do not have the same length") 14 | exit() 15 | else: 16 | for i in range(len(first_string)): 17 | res = res + first_string[i] + second_string[i] 18 | 19 | print(res) 20 | -------------------------------------------------------------------------------- /Chapter 6 Exercise/Q_14.py: -------------------------------------------------------------------------------- 1 | """Write a program that asks the user to enter their name in lowercase and then capitalizes the 2 | first letter of each word of their name.""" 3 | 4 | user_input = input("Enter Your names in lower case :") 5 | 6 | print(user_input.title()) -------------------------------------------------------------------------------- /Chapter 6 Exercise/Q_15.py: -------------------------------------------------------------------------------- 1 | """When I was a kid, we used to play this game called Mad Libs. The way it worked was a friend 2 | would ask me for some words and then insert those words into a story at specific places 3 | and read the story. The story would often turn out to be pretty funny with the words I had 4 | given since I had no idea what the story was about. The words were usually from a specific 5 | category, like a place, an animal, etc. 6 | For this problem you will write a Mad Libs program. First, you should make up a story and 7 | leave out some words of the story. Your program should ask the user to enter some words 8 | and tell them what types of words to enter. Then print the full story along with the inserted 9 | words. Here is a small example, but you should use your own (longer) example: 10 | 11 | 12 | Enter a college class: CALCULUS 13 | Enter an adjective: HAPPY 14 | Enter an activity: PLAY BASKETBALL 15 | CALCULUS class was really HAPPY today. We learned how to 16 | PLAY BASKETBALL today in class. I can't wait for tomorrow's 17 | class! 18 | 19 | 20 | 21 | 22 | """ 23 | 24 | name = input(" What is your name: ") 25 | country= input("Where are you from: ") 26 | dream= input("What is your dream? ") 27 | user_story = "Dear {name} , you are a great programmer. Always remember practice makes progress, you are from {country} a beautiful country, Believe in yourself and your will achieve your dream to be a {dream}".format(name=name,country=country,dream=dream) 28 | 29 | 30 | print(user_story) -------------------------------------------------------------------------------- /Chapter 6 Exercise/Q_16.py: -------------------------------------------------------------------------------- 1 | """Companies often try to personalize their offers to make them more attractive. One simple 2 | way to do this is just to insert the person’s name at various places in the offer. Of course, 3 | companies don’t manually type in every person’s name; everything is computer-generated. 4 | Write a program that asks the user for their name and then generates an offer like the one 5 | below. For simplicity’s sake, you may assume that the person’s first and last names are one 6 | word each. 7 | """ 8 | 9 | first_name = input("Please Enter your First name: ") 10 | last_name = input("Please Enter your Last name: ") 11 | 12 | message = f"Dear {first_name} {last_name} I am pleased to offer you our new Platinum " \ 13 | f"Plus Rewards card at a special introductory APR of 47.99%. {first_name}, an offer" \ 14 | f"like this does not come along every day, so I urge you to call now toll-free at 1-800-314-1592. We cannot " \ 15 | f"offer such a lowrate for long, {first_name}, so call right away.".format(first_name=first_name,last_name=last_name) 16 | 17 | 18 | print(message) -------------------------------------------------------------------------------- /Chapter 6 Exercise/Q_17.py: -------------------------------------------------------------------------------- 1 | """ 2 | Write a program that generates the 26-line block of letters partially shown below. Use a loop 3 | containing one or two print statements. 4 | abcdefghijklmnopqrstuvwxyz 5 | bcdefghijklmnopqrstuvwxyza 6 | cdefghijklmnopqrstuvwxyzab 7 | ... 8 | yzabcdefghijklmnopqrstuvwx 9 | zabcdefghijklmnopqrstuvwxy 10 | """ 11 | 12 | alphabet="abcdefghijklmnopqrstuvwxyz" 13 | 14 | for m in range (26): 15 | for j in range (26): 16 | print(alphabet[(m+j)%26],end='') 17 | print() 18 | 19 | -------------------------------------------------------------------------------- /Chapter 6 Exercise/Q_18.py: -------------------------------------------------------------------------------- 1 | """ 2 | 3 | The goal of this exercise is to see if you can mimic the behavior of the in operator and the 4 | count and index methods using only variables, for loops, and if statements. 5 | 6 | (a) Without using the in operator, write a program that asks the user for a string and a letter 7 | and prints out whether or not the letter appears in the string. 8 | 9 | (b) Without using the count method, write a program that asks the user for a string and a 10 | letter and counts how many occurrences there are of the letter in the string. 11 | 12 | (c) Without using the index method, write a program that asks the user for a string and 13 | a letter and prints out the index of the first occurrence of the letter in the string. If the 14 | letter is not in the string, the program should say so 15 | """ 16 | 17 | 18 | #a 19 | # string = input("Enter String: ") 20 | # letter = input("Enter Letter: ") 21 | # index =0 22 | # found= False 23 | # 24 | # 25 | # while index < len(string): 26 | # if string[index] == letter: 27 | # found= True 28 | # #print("Letter Found") 29 | # break 30 | # else: 31 | # index+=1 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | #b 40 | 41 | string = input("Enter String: ") 42 | letter = input("Enter Letter: ") 43 | index =0 44 | found= False 45 | count= 0 46 | 47 | 48 | while index < len(string): 49 | 50 | if string[index] == letter: 51 | index+=1 52 | count +=1 53 | 54 | 55 | else: 56 | index += 1 57 | print(f"Number occures {count} number of times") 58 | 59 | #c edit solution a to have answer to c -------------------------------------------------------------------------------- /Chapter 6 Exercise/Q_19.py: -------------------------------------------------------------------------------- 1 | """Write a program that asks the user for a large integer and inserts commas into it according 2 | to the standard American convention for commas in large numbers. For instance, if the user 3 | enters 1000000, the output should be 1,000,000""" 4 | 5 | num_userenter = int(input("Enter number: ")) 6 | print('{:,}'.format(num_userenter)) -------------------------------------------------------------------------------- /Chapter 6 Exercise/Q_2.py: -------------------------------------------------------------------------------- 1 | """"A simple way to estimate the number of words in a string is to count the number of spaces 2 | in the string. Write a program that asks the user for a string and returns an estimate of how 3 | many words are in the string.""" 4 | 5 | 6 | word = input("Enter a text: ") 7 | print("Number of words in text is: ",word.count(' ') + 1) 8 | -------------------------------------------------------------------------------- /Chapter 6 Exercise/Q_20.py: -------------------------------------------------------------------------------- 1 | """Write a program that converts a time from one time zone to another. The user enters the time 2 | in the usual American way, such as 3:48pm or 11:26am. The first time zone the user enters 3 | is that of the original time and the second is the desired time zone. The possible time zones 4 | are Eastern, Central, Mountain, or Pacific. 5 | Time: 11:48pm 6 | Starting zone: Pacific 7 | Ending zone: Eastern 8 | 2:48am""" -------------------------------------------------------------------------------- /Chapter 6 Exercise/Q_21.py: -------------------------------------------------------------------------------- 1 | """An anagram of a word is a word that is created by rearranging the letters of the original. 2 | For instance, two anagrams of idle are deli and lied. Finding anagrams that are real words is 3 | beyond our reach until Chapter 12. 4 | 5 | Instead, write a program that asks the user for a string 6 | and returns a random anagram of the string—in other words, a random rearrangement of the 7 | letters of that string.""" 8 | 9 | from random import shuffle 10 | word = input('Enter a word: ') 11 | new_word = list(word) 12 | shuffle(new_word) 13 | new_word_2 = ''.join(new_word) 14 | print(new_word_2) 15 | -------------------------------------------------------------------------------- /Chapter 6 Exercise/Q_22.py: -------------------------------------------------------------------------------- 1 | """ 2 | A simple way of encrypting a message is to rearrange its characters. One way to rearrange the 3 | characters is to pick out the characters at even indices, put them first in the encrypted string, 4 | and follow them by the odd characters. For example, the string message would be encrypted 5 | as msaeesg because the even characters are m, s, a, e (at indices 0, 2, 4, and 6) and the odd 6 | characters are e, s, g (at indices 1, 3, and 5). 7 | 8 | (a) Write a program that asks the user for a string and uses this method to encrypt the string. 9 | (b) Write a program that decrypts a string that was encrypted with this method. 10 | """ 11 | 12 | from sys import exit 13 | from itertools import zip_longest 14 | 15 | def encryption(message): 16 | even_enc = '' 17 | odd_enc = '' 18 | for i in range(len(message)): 19 | if i % 2 == 0: 20 | even_enc += message[i] 21 | else: 22 | odd_enc += message[i] 23 | encrypt = even_enc + odd_enc 24 | decryption(encrypt) 25 | 26 | def decryption(encrypt): 27 | decrypt = '' 28 | str_len = len(encrypt) 29 | if str_len % 2 == 0: 30 | i = int(str_len / 2) 31 | even_dec = encrypt[:i] 32 | odd_dec = encrypt[i:] 33 | else: 34 | i = int(((str_len + 1) / 2)) 35 | even_dec = encrypt[:i] 36 | odd_dec = encrypt[i:] 37 | for (j, k) in zip_longest(even_dec, odd_dec): 38 | if j is not None: 39 | decrypt += j 40 | if k is not None: 41 | decrypt += k 42 | else: 43 | continue 44 | show(message, encrypt, decrypt) 45 | 46 | def show(message, encrypt, decrypt): 47 | print('') 48 | print(f'The original message was {message}.') 49 | print(f'The encrypted message is {encrypt}.') 50 | print(f'The decypted message is {decrypt}.') 51 | print('') 52 | print('') 53 | 54 | if __name__ == '__main__': 55 | choices = ['1', '2'] 56 | while True: 57 | print('Welcome to the Simple Encryption and Decryption Program.') 58 | print('') 59 | print('Enter "1" to type in a string to encrypt and decrypt.') 60 | print('Enter "2" to exit the program.') 61 | print('') 62 | choice = '' 63 | while choice not in choices: 64 | choice = input('Enter your choice (1 or 2): ') 65 | continue 66 | if choice == '1': 67 | message = input('Please input your message: ') 68 | encryption(message) 69 | else: 70 | exit() 71 | -------------------------------------------------------------------------------- /Chapter 6 Exercise/Q_3.py: -------------------------------------------------------------------------------- 1 | """People often forget closing parentheses when entering formulas. Write a program that asks 2 | the user to enter a formula and prints out whether the formula has the same number of opening 3 | and closing parentheses.""" -------------------------------------------------------------------------------- /Chapter 6 Exercise/Q_4.py: -------------------------------------------------------------------------------- 1 | """Write a program that asks the user to enter a word and prints out whether that word contains 2 | any vowels.""" 3 | # print(vowels[j], j) 4 | vowels =['a','e','i','o','u'] 5 | count =0 6 | word =input("Enter Word: ") 7 | for i in range(len(word)): 8 | for j in range(5): 9 | if vowels[j] in word[i]: 10 | count += 1 11 | 12 | 13 | 14 | print(count) 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | -------------------------------------------------------------------------------- /Chapter 6 Exercise/Q_5.py: -------------------------------------------------------------------------------- 1 | """Write a program that asks the user to enter a string. The program should create a new string 2 | called new_string from the user’s string such that the second character is changed to an 3 | asterisk and three exclamation points are attached to the end of the string. Finally, print 4 | new_string. Typical output is shown below: 5 | 6 | Enter your string: Qbert 7 | 8 | Q*ert!!!""" 9 | 10 | string = input("Enter a String: ") 11 | 12 | new_string = string[0]+"*"+string [2:] 13 | 14 | print(new_string + "!!!") 15 | -------------------------------------------------------------------------------- /Chapter 6 Exercise/Q_6.py: -------------------------------------------------------------------------------- 1 | 2 | """Write a program that asks the user to enter a string s and then converts s to lowercase, removes 3 | all the periods and commas from s, and prints the resulting string.""" 4 | 5 | 6 | input_string= input("Please Enter a String: ") 7 | input_string = input_string.lower() 8 | input_string = input_string.replace('.','') 9 | input_string = input_string.replace(',','') 10 | print(input_string) 11 | 12 | # Example This , is a beautiful , day. 13 | -------------------------------------------------------------------------------- /Chapter 6 Exercise/Q_7.py: -------------------------------------------------------------------------------- 1 | """Write a program that asks the user to enter a word and determines whether the word is a 2 | palindrome or not. A palindrome is a word that reads the same backwards as forwards.""" 3 | 4 | user_word = input("Enter a Word: ") 5 | #eg kayak 6 | 7 | if user_word == user_word[::-1]: 8 | print(user_word," Yay this is a palindrome") 9 | 10 | else: 11 | print(user_word ," Sorry this is not a Palindrome") 12 | 13 | -------------------------------------------------------------------------------- /Chapter 6 Exercise/Q_8.py: -------------------------------------------------------------------------------- 1 | """At a certain school, student email addresses end with @student.college.edu, while professor 2 | email addresses end with @prof.college.edu. Write a program that first asks the 3 | user how many email addresses they will be entering, and then has the user enter those addresses. 4 | After all the email addresses are entered, the program should print out a message 5 | indicating either that all the addresses are student addresses or that there were some professor 6 | addresses entered.""" 7 | 8 | 9 | num_of_email = int(input("Enter the number of emails: ")) 10 | n = 0 11 | student_count = 0 12 | teacher_count = 0 13 | 14 | while n < num_of_email: 15 | email = input("Enter Student or `Teacher Email: ") 16 | if "prof" in email: 17 | teacher_count += 1 18 | n +=1 19 | elif "student" in email: 20 | student_count += 1 21 | n +=1 22 | 23 | 24 | if teacher_count == num_of_email: 25 | print("All emails were that of teachers") 26 | if student_count == num_of_email: 27 | print("All emails were that of student") 28 | if student_count != num_of_email and teacher_count != 0: 29 | print("Email list contained both professors and student email") 30 | 31 | 32 | -------------------------------------------------------------------------------- /Chapter 6 Exercise/Q_9.py: -------------------------------------------------------------------------------- 1 | """Ask the user for a number and then print the following, where the pattern ends at the number 2 | that the user enters. 3 | 1 4 | 2 5 | 3 6 | 4""" 7 | 8 | 9 | user_num = int(input("Enter a Number: ")) 10 | n=0 11 | while n< user_num: 12 | n+=1 13 | print(n) 14 | -------------------------------------------------------------------------------- /Chapter 7 Exercise/Q_1.py: -------------------------------------------------------------------------------- 1 | # Write a program that asks the user to enter a list of integers. Do the following: 2 | # (a) Print the total number of items in the list. 3 | # (b) Print the last item in the list. 4 | # (c) Print the list in reverse order. 5 | # (d) Print Yes if the list contains a 5 and No otherwise. 6 | # (e) Print the number of fives in the list. 7 | # (f) Remove the first and last items from the list, sort the remaining items, and print the 8 | # result. 9 | 10 | count =0 11 | count_num =0 12 | # number_list =eval(input('Enter numberlist: ')) 13 | number_list =[1,24,3,2,4,5] 14 | print("Total number of items in list",len(number_list)) 15 | print("Last item in list" ,number_list[-1]) 16 | print("Reverse List",number_list[::-1]) 17 | 18 | for i in range(len(number_list)): 19 | if number_list[i] == 5: 20 | count +=1 21 | print("YES FOUND FIVE", count) 22 | 23 | number_list.pop(0) 24 | number_list.pop(-1) 25 | number_list.sort() 26 | print("After pop and sort",number_list) 27 | 28 | for i in range(len(number_list)): 29 | if number_list[i] < 5: 30 | count_num += 1 31 | print("Numbers of digits less than 5 ", count_num) 32 | 33 | 34 | 35 | 36 | -------------------------------------------------------------------------------- /Chapter 7 Exercise/Q_10.py: -------------------------------------------------------------------------------- 1 | # Write a program that rotates the elements of a list so that the element at the first index moves 2 | # to the second index, the element in the second index moves to the third index, etc., and the 3 | # element in the last index moves to the first index. 4 | 5 | num = [1,2,3,4,5] 6 | reverse_list = [] 7 | 8 | for i in range( len(num)): 9 | reverse_list.append(num[i-1]) 10 | 11 | print("Normal List",num,"Reversed list", reverse_list) 12 | 13 | 14 | -------------------------------------------------------------------------------- /Chapter 7 Exercise/Q_11.py: -------------------------------------------------------------------------------- 1 | # Using a for loop, create the list below, which consists of ones separated by increasingly many 2 | # zeroes. The last two ones in the list should be separated by ten zeroes. 3 | # [1,1,0,1,0,0,1,0,0,0,1,0,0,0,0,1,....] 4 | 5 | # Initialising for the sequence start 6 | 7 | num_list =[1] 8 | for i in range(11): 9 | num_list = num_list + (i * [0]) + [1] 10 | 11 | 12 | print(num_list) -------------------------------------------------------------------------------- /Chapter 7 Exercise/Q_12.py: -------------------------------------------------------------------------------- 1 | # Write a program that generates 100 random integers that are either 0 or 1. Then find the 2 | # longest run of zeros, the largest number of zeros in a row. For instance, the longest run of 3 | # zeros in [1,0,1,1,0,0,0,0,1,0,0] is 4. 4 | 5 | import random 6 | random_list = [] 7 | c=0 8 | max_count=0 9 | for i in range(100): 10 | n = random.randint(0,1) 11 | random_list.append(n) 12 | print(random_list) 13 | 14 | 15 | for j in random_list: 16 | c = c+1 if j == 0 else 0 17 | max_count = max(max_count,c) 18 | print(max_count) 19 | -------------------------------------------------------------------------------- /Chapter 7 Exercise/Q_13.py: -------------------------------------------------------------------------------- 1 | # Write a program that removes any repeated items from a list so that each item appears at most 2 | # once. For instance, the list [1,1,2,3,4,3,0,0] would become [1,2,3,4,0]. 3 | 4 | 5 | ls = [1,1,2,2,3,4,3,0,0] 6 | 7 | a = [] 8 | 9 | 10 | for i in ls: 11 | if i not in a: 12 | a.append(i) 13 | 14 | 15 | print(a) 16 | -------------------------------------------------------------------------------- /Chapter 7 Exercise/Q_14.py: -------------------------------------------------------------------------------- 1 | 2 | # 3 | # def number_length(num): 4 | # num =str(num) 5 | # count =0 6 | # if num == "": 7 | # 8 | # return 0 9 | # else: 10 | # for words in num: 11 | # count += 1 12 | # 13 | # return count 14 | 15 | # def shift_to_left(x, y): 16 | # return (x * (y ** 2)) 17 | # 18 | # print(shift_to_left(10,3)) 19 | 20 | 21 | def shift_to_left (y): 22 | return (2 ** y) 23 | 24 | print(shift_to_left(3)) -------------------------------------------------------------------------------- /Chapter 7 Exercise/Q_15.py: -------------------------------------------------------------------------------- 1 | """ 2 | There is a provably unbreakable cipher called a one-time pad. The way it works is you shift 3 | each character of the message by a random amount between 1 and 26 characters, wrapping 4 | around the alphabet if necessary. For instance, if the current character is y and the shift is 5, 5 | then the new character is d. Each character gets its own shift, so there needs to be as many 6 | random shifts as there are characters in the message. As an example, suppose the user enters 7 | secret. The program should generate a random shift between 1 and 26 for each character. 8 | Suppose the randomly generated shifts are 1, 3, 2, 10, 8, and 2. The encrypted message would 9 | be thebmv. 10 | (a) Write a program that asks the user for a message and encrypts the message using the 11 | one-time pad. First convert the string to lowercase. Any spaces and punctuation in the 12 | string should be left unchanged. For example, Secret!!! becomes thebmv!!! using 13 | the shifts above. 14 | (b) Write a program to decrypt a string encrypted as above. 15 | The reason it is called a one-time-pad is that the list of random shifts should only be used once. 16 | It becomes easily breakable if the same random shifts are used for more than one message. 17 | Moreover, it is only provably unbreakable if the random numbers are truly random, and the 18 | numbers generated by randint are not truly random. For this problem, just use randint, 19 | but for cryptographically safe random numbers, see Section 22.8. 20 | """ 21 | 22 | # TO DO -------------------------------------------------------------------------------- /Chapter 7 Exercise/Q_2.py: -------------------------------------------------------------------------------- 1 | # Write a program that generates a list of 20 random numbers between 1 and 100. 2 | # (a) Print the list. 3 | # (b) Print the average of the elements in the list. 4 | # (c) Print the largest and smallest values in the list. 5 | # (d) Print the second largest and second smallest entries in the list 6 | # (e) Print how many even numbers are in the list. 7 | import random 8 | from random import randint 9 | 10 | number_list =[] 11 | count =0 12 | 13 | for i in range(20): 14 | number_list.append(randint(1,100)) 15 | 16 | print(number_list) 17 | number_list.sort() 18 | print(number_list) 19 | average = sum(number_list)/len(number_list) 20 | print("Average of list",average) 21 | print("Maximum Number",max(number_list)) 22 | print("Second Maximum Number",number_list[-2]) 23 | print("Minimum Number",min(number_list)) 24 | print("Second Minimum Number",number_list[1]) 25 | 26 | for i in number_list: 27 | if i%2==0: 28 | count += 1 29 | print("Number of even Numbers in List",count) 30 | 31 | 32 | -------------------------------------------------------------------------------- /Chapter 7 Exercise/Q_3.py: -------------------------------------------------------------------------------- 1 | # Start with the list [8,9,10]. Do the following: 2 | # (a) Set the second entry (index 1) to 17 3 | # (b) Add 4, 5, and 6 to the end of the list 4 | # (c) Remove the first entry from the list 5 | # (d) Sort the list 6 | # (e) Double the list 7 | # (f) Insert 25 at index 3 8 | # The final list should equal [4,5,6,25,10,17,4,5,6,10,17] 9 | 10 | number_list =[8,9,10] 11 | 12 | number_list[1]=17 13 | number_list.append(4) 14 | number_list.append(5) 15 | number_list.append(6) 16 | number_list.pop(0) 17 | number_list.sort() 18 | 19 | ls =[] 20 | for i in number_list: 21 | ls.append(i) 22 | 23 | number_list.extend(ls) 24 | 25 | number_list.insert(3,25) 26 | 27 | 28 | print(number_list) 29 | 30 | -------------------------------------------------------------------------------- /Chapter 7 Exercise/Q_4.py: -------------------------------------------------------------------------------- 1 | # Ask the user to enter a list containing numbers between 1 and 12. Then replace all of the 2 | # entries in the list that are greater than 10 with 10. 3 | 4 | input_num = eval(input("Enter List of Nmber: ")) 5 | number_list =[] 6 | number_list.extend(input_num) 7 | print(number_list) 8 | for i in range(len(number_list)): 9 | if number_list[i] > 10: 10 | number_list[i] = 10 11 | 12 | 13 | print(number_list) -------------------------------------------------------------------------------- /Chapter 7 Exercise/Q_5.py: -------------------------------------------------------------------------------- 1 | # Ask the user to enter a list of strings. Create a new list that consists of those strings with their 2 | # first characters removed. 3 | 4 | 5 | input_string = input("Enter String for list: ").split(",") 6 | string_list = [] 7 | string_list.extend(input_string) 8 | print(string_list) 9 | 10 | 11 | for i in range(len(string_list)): 12 | string_list[i]=string_list[i][1:] 13 | 14 | print(string_list) -------------------------------------------------------------------------------- /Chapter 7 Exercise/Q_6.py: -------------------------------------------------------------------------------- 1 | # Create the following lists using a for loop. 2 | # (a) A list consisting of the integers 0 through 49 3 | # (b) A list containing the squares of the integers 1 through 50. 4 | # (c) The list ['a','bb','ccc','dddd', . . . ] that ends with 26 copies of the letter z. 5 | 6 | import random 7 | import math 8 | number_list = [] 9 | square_list =[] 10 | alpha_list =[] 11 | 12 | for i in range(0,49): 13 | number_list.append(i) 14 | print(number_list) 15 | 16 | for j in range(0,number_list[i]): 17 | square_list.append(j*j) 18 | 19 | print(square_list) 20 | 21 | alphabet=['','a','b','c','d','e','f','g','h','k','l','m','n','o','p','q','r','s','t'] 22 | 23 | for alpha in range(1,len(alphabet)): 24 | alpha_list.append(alphabet[alpha]*alpha) 25 | print(alpha_list) 26 | 27 | 28 | 29 | -------------------------------------------------------------------------------- /Chapter 7 Exercise/Q_7.py: -------------------------------------------------------------------------------- 1 | # Write a program that takes any two lists L and M of the same size and adds their elements 2 | # together to form a new list N whose elements are sums of the corresponding elements in L 3 | # and M. For instance, if L=[3,1,4] and M=[1,5,9], then N should equal [4,6,13]. 4 | 5 | 6 | L =[3,1,4] 7 | M =[1,5,9] 8 | sum_list =[] 9 | def combine(L,M): 10 | sum =map(lambda x,y: x+y,L,M) 11 | 12 | print(list(sum)) 13 | 14 | 15 | 16 | # sum_list.append(sum) 17 | # print(sum_list) 18 | 19 | 20 | 21 | 22 | combine(L,M) -------------------------------------------------------------------------------- /Chapter 7 Exercise/Q_8.py: -------------------------------------------------------------------------------- 1 | # Write a program that asks the user for an integer and creates a list that consists of the factors 2 | # of that integer. 3 | 4 | 5 | input_int=eval(input("Enter Interger: ")) 6 | number_list=[] 7 | 8 | 9 | for i in range(1,input_int+1): 10 | if input_int%i == 0: 11 | number_list.append(i) 12 | 13 | print(number_list) 14 | -------------------------------------------------------------------------------- /Chapter 7 Exercise/Q_9.py: -------------------------------------------------------------------------------- 1 | # When playing games where you have to roll two dice, it is nice to know the odds of each 2 | # roll. For instance, the odds of rolling a 12 are about 3%, and the odds of rolling a 7 are about 3 | # 17%. You can compute these mathematically, but if you don’t know the math, you can write 4 | # a program to do it. To do this, your program should simulate rolling two dice about 10,000 5 | # times and compute and print out the percentage of rolls that come out to be 2, 3, 4, . . . , 12. 6 | 7 | 8 | from random import randint 9 | dice_roll=[] 10 | outcome ={2:0,3:0,4:0,5:0,6:0,7:0,8:0,9:0,10:0,11:0,12:0} 11 | sim =10000 12 | 13 | for simulations in range(sim): 14 | first_dice_roll = randint(1,6) 15 | second_dice_roll = randint(1,6) 16 | 17 | sum_dice =(first_dice_roll + second_dice_roll) 18 | # print(sum_dice) 19 | outcome[sum_dice] += 1 20 | 21 | 22 | 23 | for key in outcome.keys(): 24 | # print("Percentage for rolling a sum of %s is:"%(key,outcome[key]/sim*100)) 25 | print("Percentage for rolling a sum of %s is: %s" % (key, outcome[key] / sim * 100)) 26 | 27 | -------------------------------------------------------------------------------- /Chapter 8 Exercise/Q_1.py: -------------------------------------------------------------------------------- 1 | """Write a program that asks the user to enter some text and then counts how many articles are 2 | in the text. Articles are the words 'a', 'an', and 'the'.""" 3 | 4 | user_input =input("Enter Text: ") #love is a beautiful and profound an angelic being 5 | articles =["a","an","and"] 6 | words =user_input.split() 7 | count =0 8 | 9 | for word in words: 10 | if word in articles: 11 | count +=1 12 | print(count) 13 | -------------------------------------------------------------------------------- /Chapter 8 Exercise/Q_10.py: -------------------------------------------------------------------------------- 1 | """ 2 | Write a censoring program. Allow the user to enter some text and your program should print 3 | out the text with all the curse words starred out. The number of stars should match the length 4 | of the curse word. For the purposes of this program, just use the“curse” words darn, dang, 5 | freakin, heck, and shoot. 6 | """ 7 | 8 | from enum import Enum 9 | 10 | class curses(Enum): 11 | CURSE_WORDS = ['darn', 'dang', 'freakin', 'heck', 'shoot'] 12 | 13 | def censor(message): 14 | user_input = input(message) 15 | user_input = user_input.lower() 16 | for i in curses.CURSE_WORDS.value: 17 | user_input = user_input.replace(i, '*') 18 | censor_input = user_input.capitalize() 19 | print('') 20 | print(censor_input) 21 | 22 | 23 | def main(): 24 | print('Welcome to the Censoring Progam.') 25 | print('\nThe following are curse words that will be censored: \n') 26 | print(' - '.join(curses.CURSE_WORDS.value)) 27 | message = 'Enter a statement that contains these words: \n' 28 | censor(message) 29 | 30 | if __name__ == '__main__': 31 | main() 32 | 33 | # Oh shoot, I thought I had the dang problem figured out. Darn it. Oh well, it was a heck of a freakin try. 34 | -------------------------------------------------------------------------------- /Chapter 8 Exercise/Q_12.py: -------------------------------------------------------------------------------- 1 | """ 2 | Write a program that gets a string from the user containing a potential telephone number. 3 | The program should print Valid if it decides the phone number is a real phone number, and 4 | Invalid otherwise. A phone number is considered valid as long as it is written in the form 5 | abc-def-hijk or 1-abc-def-hijk. The dashes must be included, the phone number should contain 6 | only numbers and dashes, and the number of digits in each group must be correct. 7 | """ 8 | 9 | def validate_input(message): 10 | valid = False 11 | while not valid: 12 | user_input = input(message) 13 | num = user_input.split('-') 14 | try: 15 | if (len(num[0]) == 1) and (len(num[1]) == 3) and (len(num[2]) == 3) and (len(num[3]) == 4): 16 | valid = True 17 | elif (len(num[0]) == 3) and (len(num[1]) == 3) and (len(num[2]) == 4): 18 | valid = True 19 | else: 20 | print('Your format is off. Please enter a valid phone number.') 21 | except IndexError: 22 | print('A phone number was not inputted.') 23 | return user_input 24 | 25 | def main(): 26 | print('Welcome to Phone Number Validation.\n') 27 | print('The phone number format is 1-ABC-DEF-GHIJ or ABC-DEF-GHIJ.') 28 | message = 'Enter a valid phone number: ' 29 | valid_num = validate_input(message) 30 | print(f'\nThe number, {valid_num}, is valid.') 31 | 32 | if __name__ == '__main__': 33 | main() 34 | -------------------------------------------------------------------------------- /Chapter 8 Exercise/Q_13.py: -------------------------------------------------------------------------------- 1 | """ 2 | Let L be a list of strings. Write list comprehensions that create new lists from L for each of the 3 | following. 4 | (a) A list that consists of the strings of s with their first characters removed 5 | (b) A list of the lengths of the strings of s 6 | (c) A list that consists of only those strings of s that are at least three characters long 7 | """ 8 | 9 | L = ['apple', 'car', 'tree', 'I', 'watch', 'internet'] 10 | print(L) 11 | M = [s[1:] for s in L] 12 | print(M) 13 | N = [len(s) for s in L] 14 | print(N) 15 | O = [s for s in L if len(s) >= 3] 16 | print(O) 17 | -------------------------------------------------------------------------------- /Chapter 8 Exercise/Q_14.py: -------------------------------------------------------------------------------- 1 | """ 2 | Use a list comprehension to produce a list that consists of all palindromic numbers between 3 | 100 and 1000. 4 | """ 5 | 6 | L = [num for num in range(100, 1001)] 7 | M = [] 8 | count = 0 9 | for i in L: 10 | i = str(i) 11 | if i == i[::-1]: 12 | count+=1 13 | M.append(int(i)) 14 | print(f'\nThere are {count} numbers that are a palindromic.\n') 15 | print(M) 16 | -------------------------------------------------------------------------------- /Chapter 8 Exercise/Q_17.py: -------------------------------------------------------------------------------- 1 | """ 2 | Write a program that finds the average of all of the entries in a 4 × 4 list of integers. 3 | """ 4 | 5 | from pprint import pprint 6 | import numpy as np 7 | 8 | array = np.random.randint(5, size=(4,4)) 9 | pprint(array) 10 | ave = array.mean() 11 | print(f'The average of the matrix is {ave}.') 12 | -------------------------------------------------------------------------------- /Chapter 8 Exercise/Q_18.py: -------------------------------------------------------------------------------- 1 | """ 2 | Write a program that creates a 10×10 list of random integers between 1 and 100. Then do the 3 | following: 4 | (a) Print the list. 5 | (b) Find the largest value in the third row. 6 | (c) Find the smallest value in the sixth column. 7 | """ 8 | 9 | import numpy as np 10 | from pprint import pprint 11 | 12 | array = np.random.randint(1, 101, size = (10, 10)) 13 | pprint(array) 14 | print('') 15 | 16 | # Grabbed 3rd row. 17 | third_row_max = array[2].max(axis = 0) # axis = 0 is row 18 | print(third_row_max) 19 | print('') 20 | 21 | # Grabbed 6th column. 22 | column = array[:,5].reshape(1,-1) 23 | sixth_column_min = column.min() 24 | print(sixth_column_min) 25 | 26 | print('\nProblem 19\n') 27 | from pprint import pprint 28 | from itertools import cycle 29 | iterator = cycle(range(2)) 30 | L = [[next(iterator) for column in range(8)] for row in range(8)] 31 | pprint(L) 32 | -------------------------------------------------------------------------------- /Chapter 8 Exercise/Q_19.py: -------------------------------------------------------------------------------- 1 | """ 2 | Write a program that creates and prints an 8 × 8 list whose entries alternate between 1 and 2 3 | in a checkerboard pattern, starting with 1 in the upper left corner. 4 | """ 5 | 6 | print('\nProblem 19\n') 7 | 8 | from pprint import pprint 9 | from itertools import cycle 10 | 11 | iterator = cycle(range(2)) 12 | L = [[next(iterator) for column in range(8)] for row in range(8)] 13 | pprint(L) 14 | 15 | 16 | 17 | print('\nProblem 19 - Alternate Solution\n') 18 | 19 | from pprint import pprint 20 | 21 | def alternate(): 22 | while True: 23 | yield 1 24 | yield 0 25 | 26 | alternator = alternate() 27 | L = [[next(alternator) for column in range(8)] for row in range(8)] 28 | pprint(L) 29 | -------------------------------------------------------------------------------- /Chapter 8 Exercise/Q_2.py: -------------------------------------------------------------------------------- 1 | """ Write a program that allows the user to enter five numbers (read as strings). Create a string 2 | that consists of the user’s numbers separated by plus signs. For instance, if the user enters 2, 3 | 5, 11, 33, and 55, then the string should be '2+5+11+33+55'.""" 4 | 5 | user_input = input("Enter 5 numbers :") #1 2 3 4 5 6 | 7 | sepr = user_input.replace(" ", "+") 8 | 9 | print(sepr) -------------------------------------------------------------------------------- /Chapter 8 Exercise/Q_20.py: -------------------------------------------------------------------------------- 1 | """ 2 | Write a program that checks to see if a 4 × 4 list is a magic square. In a magic square, every 3 | row, column, and the two diagonals add up to the same value. 4 | """ 5 | 6 | import numpy as np 7 | 8 | array = np.random.randint(1, 5, size = (4, 4)) 9 | row_sum = array.sum(axis = 1) 10 | column_sum = array.sum(axis = 0) 11 | print(array) 12 | print('') 13 | print(row_sum) 14 | print(column_sum) 15 | 16 | # I believe This is incorrect. 17 | -------------------------------------------------------------------------------- /Chapter 8 Exercise/Q_22.py: -------------------------------------------------------------------------------- 1 | """ 2 | The following is useful as part of a program to play Battleship. Suppose you have a 5 × 5 list 3 | that consists of zeroes and ones. Ask the user to enter a row and a column. If the entry in the 4 | list at that row and column is a one, the program should print Hit and otherwise it should 5 | print Miss. 6 | """ 7 | 8 | from random import randint 9 | from pprint import pprint 10 | 11 | MAP = [[randint(0,1) for column in range(5)] for row in range(5)] 12 | 13 | def validate_input(row_input, column_input, flag): 14 | valid = False 15 | while not valid: 16 | try: 17 | if flag == 0: 18 | user_input = int(input(row_input)) 19 | else: 20 | user_input = int(input(column_input)) 21 | if 0 <= user_input <= 4: 22 | valid = True 23 | else: 24 | print('\nSorry you did not enter a number from the choices.') 25 | except ValueError: 26 | print('\nYou did not enter a number.') 27 | return user_input 28 | 29 | def hit_miss(row, column): 30 | if MAP[row][column] == 1: 31 | print('Hit') 32 | else: 33 | print('Miss') 34 | 35 | def main(): 36 | print('Welcome to Battleship.') 37 | print('') 38 | print('The board is 5x5 (25 choices total).') 39 | print('You will first inout row and then column to indicate the point you want to target.') 40 | print('The choices for the row and column will be 1 through 5.') 41 | row_input = 'Enter 0, 1, 2, 3, or 4 for row: ' 42 | column_input = 'Enter 0, 1, 2, 3, or 4 for column: ' 43 | flag = 0 44 | row = validate_input(row_input, column_input, flag) 45 | flag = 1 46 | column = validate_input(row_input, column_input, flag) 47 | hit_miss(row, column) 48 | pprint(MAP) 49 | 50 | if __name__ == '__main__': 51 | main() 52 | -------------------------------------------------------------------------------- /Chapter 8 Exercise/Q_23.py: -------------------------------------------------------------------------------- 1 | """ 2 | This exercise is useful in creating a Memory game. Randomly generate a 6 × 6 list of assorted 3 | characters such that there are exactly two of each character. An example is shown below. 4 | 5 | @ 5 # A A ! 6 | 5 0 b @ $ z 7 | $ N x ! N z 8 | 0 - + # b : 9 | - : + c c x 10 | """ 11 | 12 | 13 | from string import ascii_letters, punctuation, digits 14 | from random import sample, shuffle 15 | from pprint import pprint 16 | import numpy as np 17 | 18 | # From string module, imported all corresponding characters and grouped them together in source variable. 19 | source = ascii_letters + punctuation + digits 20 | 21 | # Using sample function from random module, grabbed 18 random characters from source string. 22 | # After which, the random chars cloned to create pairs for memory game. 23 | # Note, sample returns a list. 24 | chars = sample(source, 18) * 2 25 | 26 | # Used shuffle function to randomize the list of characters 27 | shuffle(chars) 28 | 29 | # Used numpy instead of list comprehensions to create an array of the chars at a 6x6 size. 30 | # After which, the array was converted to a list using the .tolist() method. 31 | L = np.array(chars).reshape(6,6).tolist() 32 | pprint(L) 33 | -------------------------------------------------------------------------------- /Chapter 8 Exercise/Q_3.py: -------------------------------------------------------------------------------- 1 | """(a) Ask the user to enter a sentence and print out the third word of the sentence. 2 | (b) Ask the user to enter a sentence and print out every third word of the sentence.""" 3 | 4 | user_input = input("Enter a sentence: ") 5 | #eg I love you ethan tirla and I promise to give you the best life has to offer 6 | sentence_words = user_input.split() 7 | 8 | print("a",sentence_words[2]) 9 | 10 | for word in range(2,len(sentence_words),3): 11 | print("b",sentence_words[word]) 12 | -------------------------------------------------------------------------------- /Chapter 8 Exercise/Q_4.py: -------------------------------------------------------------------------------- 1 | """ 2 | 3 | Write a program that asks the user to enter a sentence and 4 | then randomly rearranges the words of the sentence. 5 | Don’t worry about getting punctuation or capitalization correct. 6 | 7 | b) Do the above problem, but now make sure that the sentence starts with a capital, that 8 | the original first word is not capitalized if it comes in the middle of the sentence, and 9 | that the period is in the right place. 10 | """ 11 | 12 | from random import shuffle 13 | from string import punctuation 14 | #user_sentence = input("Enter a sentence: ") 15 | user_sentence = "I am a crypto billionaire ." 16 | #eg I am a crypto billionaire . 17 | #a 18 | L =user_sentence.split() 19 | shuffle(L) 20 | 21 | print(L) 22 | 23 | 24 | #b 25 | 26 | punct ="" 27 | sentence2="" 28 | if user_sentence[-1] in punctuation: 29 | punct = user_sentence[-1] 30 | sentence2 = user_sentence[0].lower() + user_sentence[1:-1] 31 | 32 | 33 | 34 | #print(sentence2) 35 | l2= sentence2.split() 36 | 37 | shuffle(l2) 38 | sentence2 = ' '.join(l2) + punct 39 | sentence2 = sentence2[0].upper() + sentence2[1:] 40 | print(sentence2) 41 | 42 | #b credit to https://github.com/Yaachaka/ for the solution of b -------------------------------------------------------------------------------- /Chapter 8 Exercise/Q_5.py: -------------------------------------------------------------------------------- 1 | """Write a simple quote-of-the-day program. 2 | The program should contain a list of quotes, and 3 | when the user runs the program, 4 | a randomly selected quote should be printed.""" 5 | import random 6 | from random import randint 7 | Quotes_list = ["To double your income and success, tripple your investment in personal Developent and professional mastery -Robin Sharma","Simplicity is the soul efficiency - Austin Freeman", "A journey of a thousand miles begins with a single step -Lao Tzu","Everything happens for a reason. It's okay if you don't know what that reason is yet -Unknown"] 8 | 9 | len_list = len(Quotes_list) 10 | num =random.randint(0,len_list-1) 11 | 12 | print(Quotes_list[num]) 13 | 14 | 15 | 16 | 17 | -------------------------------------------------------------------------------- /Chapter 8 Exercise/Q_6.py: -------------------------------------------------------------------------------- 1 | """Write a simple lottery drawing program. The lottery drawing should consist of 2 | six different 3 | numbers between 1 and 48.""" 4 | import random 5 | from random import randint 6 | lottery_num = [] 7 | 8 | 9 | while len(lottery_num) < 6: 10 | 11 | random_num = random.randint(1,48) 12 | lottery_num.append(random_num) 13 | 14 | print(lottery_num) 15 | 16 | 17 | 18 | 19 | -------------------------------------------------------------------------------- /Chapter 8 Exercise/Q_7.py: -------------------------------------------------------------------------------- 1 | from enum import Enum 2 | from random import sample 3 | 4 | class lottery(Enum): 5 | LOTTERY_NUM = [i for i in range(1,11)] 6 | 7 | ITERATIONS = 1000 8 | 9 | def lottery_hand(): 10 | # Used sample function instead of calling the num of draws globally to practice with it. 11 | L = sample(lottery.LOTTERY_NUM.value, 6) 12 | return L 13 | 14 | def winning_hand(ITERATIONS): 15 | count = 0 16 | for i in range(ITERATIONS): 17 | user_hand = lottery_hand() 18 | comp_hand = lottery_hand() 19 | if user_hand == comp_hand: 20 | count += 1 21 | return count 22 | 23 | def main(): 24 | won = winning_hand(ITERATIONS) 25 | print((won/ITERATIONS) * 100) 26 | 27 | if __name__ == '__main__': 28 | main() 29 | -------------------------------------------------------------------------------- /Chapter 8 Exercise/Q_9.py: -------------------------------------------------------------------------------- 1 | """ 2 | Write a simple quiz game that has a list of ten questions and a list of answers to those questions. The game should give the player four randomly selected questions to answer. It should 3 | ask the questions one-by-one, and tell the player whether they got the question right or 4 | wrong. At the end it should print out how many out of four they got right. 5 | """ 6 | 7 | from enum import Enum 8 | from random import choice 9 | 10 | class q_a(Enum): 11 | QUES_ANS = {'Sky is blue: ':'T', 'Square has 3 sides: ':'F', '100 pennies equal 1 USD dollar: ':'T', 'Leaves can change colors: ':'T', 'Coding sucks: ':'F'} 12 | 13 | N = 3 # Number of rounds. 14 | VALID_CHOICE = ['T', 'F'] 15 | 16 | def quiz_game(N): 17 | score = 0 18 | for i in range(N): 19 | current_ques_ans = get_ques_ans() 20 | current_ques = unpack_ques(current_ques_ans) 21 | current_ans = unpack_ans(current_ques_ans) 22 | valid_user_input = validate_ans(current_ques, current_ans) 23 | score = check_ans_score(current_ans, valid_user_input, score) 24 | print(f'\nYour score is {score}.') 25 | 26 | # Will return a tuple since choosing both items in the dictionary. 27 | def get_ques_ans(): 28 | ques_ans = choice(list(q_a.QUES_ANS.value.items())) 29 | return ques_ans 30 | 31 | def unpack_ques(current_ques_ans): 32 | ques = current_ques_ans[0] 33 | return ques 34 | 35 | def unpack_ans(current_ques_ans): 36 | ans = current_ques_ans[1] 37 | return ans 38 | 39 | def validate_ans(current_ques, current_ans): 40 | valid = False 41 | while not valid: 42 | user_input = input(current_ques) 43 | user_input = user_input.upper() 44 | try: 45 | if user_input in VALID_CHOICE: 46 | valid = True 47 | else: 48 | print('\nYou did not indicate true or false. Please enter "T" or "F".') 49 | except: 50 | pass 51 | return user_input 52 | 53 | def check_ans_score(current_ans, valid_user_input, score): 54 | if current_ans == valid_user_input: 55 | score += 1 56 | else: 57 | pass 58 | return score 59 | 60 | def main(): 61 | print('Welcome to True and False Quiz!') 62 | print('') 63 | print('Enter "T" if it is true or "F" if it is false.\n') 64 | quiz_game(N) 65 | 66 | if __name__ == '__main__': 67 | main() 68 | -------------------------------------------------------------------------------- /Chapter 9 Exercise/Q_1.py: -------------------------------------------------------------------------------- 1 | """The code below prints the numbers from 1 to 50. Rewrite the code using a while loop to 2 | accomplish the same thing. 3 | for i in range(1,51): 4 | print(i)""" 5 | num =0 6 | while num < 51: 7 | print(num) 8 | num+=1 -------------------------------------------------------------------------------- /Chapter 9 Exercise/Q_10.py: -------------------------------------------------------------------------------- 1 | """Write a program that has a list of ten words, some of which have repeated letters and some 2 | which don’t. Write a program that picks a random word from the list that does not have any 3 | repeated letters.""" 4 | from random import randint 5 | word_list =["henry","laura","gaga","gagayas","monique","marina","thomas","leopold","jackson","abigail"] 6 | 7 | 8 | 9 | listofwords=[] 10 | for i in range(len(word_list)): 11 | #print(words) 12 | for j in range(len(word_list[i])): 13 | #print(word_list[i][j], "----j") #You can use this print statement to understand code 14 | for k in range(j+1,len(word_list[i])): 15 | # print(word_list[i][k],"---k") 16 | 17 | if word_list[i][j] == word_list[i][k]: 18 | if word_list[i] not in listofwords: 19 | listofwords.append(word_list[i]) 20 | 21 | ##Random Selection not implemented 22 | print(listofwords) 23 | 24 | 25 | 26 | 27 | 28 | -------------------------------------------------------------------------------- /Chapter 9 Exercise/Q_11.py: -------------------------------------------------------------------------------- 1 | """Write a program that starts with an 5 X 5 list of zeroes and randomly changes exactly ten of 2 | those zeroes to ones.""" 3 | from random import randint 4 | list_50 =[0,0,0,0,0, 5 | 0,0,0,0,0, 6 | 0,0,0,0,0, 7 | 0,0,0,0,0, 8 | 0,0,0,0,0,] 9 | i=0 10 | total_zeros = len(list_50) 11 | while (i <1): 12 | value = randint(0, total_zeros-1) 13 | list_50[value] = 1 14 | i = i+1 15 | print(list_50) 16 | 17 | 18 | 19 | 20 | 21 | -------------------------------------------------------------------------------- /Chapter 9 Exercise/Q_12.py: -------------------------------------------------------------------------------- 1 | """Write a program in which you have a list that contains seven integers that can be 0 or 1. Find 2 | the first nonzero entry in the list and change it to a 1. If there are no nonzero entries, print a 3 | message saying so.""" 4 | 5 | from random import randint 6 | 7 | L = [randint(0, 1) for i in range(7)] 8 | print('The initial list is the following: ') 9 | print(L) 10 | print('') 11 | valid = False 12 | while not valid: 13 | try: 14 | i = L.index(0) 15 | print(f'The first zero occurs at index {i}.') 16 | print('\nThe new list is the following: ') 17 | L[i] = 1 18 | print(L) 19 | valid = True 20 | except ValueError: 21 | print('There are no zero entries.') 22 | break 23 | -------------------------------------------------------------------------------- /Chapter 9 Exercise/Q_14.py: -------------------------------------------------------------------------------- 1 | """ 2 | Write a program to play the following simple game. The player starts with $100. On each 3 | turn a coin is flipped and the player has to guess heads or tails. The player wins $9 for each 4 | correct guess and loses $10 for each incorrect guess. The game ends either when the player 5 | runs out of money or gets to $200. 6 | """ 7 | 8 | from enum import Enum 9 | from random import choice 10 | 11 | class coin(Enum): 12 | FACE = {'h':'Heads', 't':'Tails'} 13 | 14 | MONEY = 100 15 | 16 | def heads_tails(MONEY): 17 | while 0 < MONEY < 200: 18 | rand_face = coin_face() 19 | message = 'Enter "h" for heads or "t" for tails: ' 20 | user_guess = validate_input(message) 21 | print(rand_face) 22 | if rand_face == user_guess: 23 | MONEY += 9 24 | print(f'You guessed right! You now have ${MONEY}.') 25 | else: 26 | MONEY -= 10 27 | print(f'You guessed wrong! You now have ${MONEY}.') 28 | if MONEY < 0: 29 | print('You do not have any more money to play.') 30 | else: 31 | print(f'You have ${MONEY}. Good job. Good-bye.') 32 | 33 | def coin_face(): 34 | rand_face = choice(list(coin.FACE.value.keys())) 35 | return rand_face 36 | 37 | def validate_input(message): 38 | valid = False 39 | while not valid: 40 | try: 41 | user_input = input(message) 42 | user_input = user_input.lower() 43 | if (user_input == 'h') or (user_input == 't'): 44 | valid = True 45 | else: 46 | print('\nPlease enter "h" or "t".') 47 | except: 48 | pass 49 | return user_input 50 | 51 | def main(): 52 | print('Welcome to Heads and Tails.') 53 | print('') 54 | print(f'You have ${MONEY} to start with.') 55 | print('') 56 | print('If you guess right, you get $9. If you guess wrong, you lose $10.') 57 | heads_tails(MONEY) 58 | 59 | if __name__ == '__main__': 60 | main() 61 | -------------------------------------------------------------------------------- /Chapter 9 Exercise/Q_15.py: -------------------------------------------------------------------------------- 1 | """ 2 | Write a program to play the following game. There is a list of several country names and the 3 | program randomly picks one. The player then has to guess letters in the word one at a time. 4 | Before each guess the country name is displayed with correctly guessed letters filled in and 5 | the rest of the letters represented with dashes. For instance, if the country is Canada and the 6 | player has correctly guessed a, d, and n, the program would display -ana-da. The program 7 | should continue until the player either guesses all of the letters of the word or gets five letters 8 | wrong. 9 | """ 10 | 11 | from random import choice 12 | from string import ascii_lowercase 13 | from re import finditer 14 | from sys import exit 15 | 16 | COUNTRY_LIST = ['canada', 'england', 'japan', 'china', 'germany', 'scotland', 17 | 'chad', 'ghana', 'mexico', 'ireland', 'korea', 'denmark'] 18 | 19 | def game_on(): 20 | num_guesses = 5 21 | country = get_country(COUNTRY_LIST) 22 | country_placeholder = country 23 | for i in country: 24 | country = country.replace(i, '*') 25 | while num_guesses > 0: 26 | print(country) 27 | message = 'Enter a letter to guess: ' 28 | guess = validate_letter(message) 29 | if guess in country_placeholder: 30 | valid_letter = [x.start() for x in finditer(guess, country_placeholder)] 31 | for j in valid_letter: 32 | country = country[:j] + country[j].replace('*', guess) + country[j+1:] 33 | else: 34 | num_guesses -= 1 35 | print(f'No "{guess}" in the country\'s name. You have {num_guesses} number of guesses left.\n') 36 | win_lose(num_guesses, country, country_placeholder) 37 | 38 | def get_country(COUNTRY_LIST): 39 | rand_country = choice(COUNTRY_LIST) 40 | return rand_country 41 | 42 | def validate_letter(message): 43 | valid = False 44 | while not valid: 45 | try: 46 | user_input = input(message) 47 | if (user_input in ascii_lowercase) and (len(user_input) == 1): 48 | valid = True 49 | else: 50 | print('\nPlease enter a valid letter as a guess: ') 51 | except: 52 | pass 53 | return user_input 54 | 55 | def win_lose(num_guesses, country, country_placeholder): 56 | if num_guesses == 0: 57 | print(f'You ran out of guesses. The country is {country_placeholder.capitalize()}. You lose.') 58 | elif country == country_placeholder: 59 | print(f'\nYes the country was {country.capitalize()}.') 60 | print('You Win!') 61 | exit() 62 | else: 63 | pass 64 | 65 | def main(): 66 | print('Welcome to the Country Guessing Game') 67 | print('You have 5 guesses.\n') 68 | game_on() 69 | 70 | if __name__ == '__main__': 71 | main() 72 | -------------------------------------------------------------------------------- /Chapter 9 Exercise/Q_16.py: -------------------------------------------------------------------------------- 1 | """ 2 | Write a text-based version of the game Memory. The game should generate a 5 × 5 board (see 3 | the exercise from Chapter 8). Initially the program should display the board as a 5 × 5 grid of 4 | asterisks. The user then enters the coordinates of a cell. The program should display the grid 5 | with the character at those coordinates now displayed. The user then enters coordinates of 6 | another cell. The program should now display the grid with the previous character and the 7 | new character displayed. If the two characters match, then they should permanently replace 8 | the asterisks in those locations. Otherwise, when the user enters the next set of coordinates, 9 | those characters should be replaced by asterisks. The game continues this way until the player 10 | matches everything or runs out of turns. You can decide how many turns they player gets. 11 | """ 12 | 13 | from string import ascii_lowercase 14 | from random import sample, shuffle 15 | from pprint import pprint 16 | import numpy as np 17 | from sys import exit 18 | 19 | COOR = [0,1,2,3] 20 | 21 | def create_board(): 22 | # From string module, imported all corresponding characters and grouped them together in source variable. 23 | source = ascii_lowercase 24 | 25 | # Using sample function from random module, grabbed 18 random characters from source string. 26 | # After which, the random chars cloned to create pairs for memory game. 27 | # Note, sample returns a list. 28 | chars = sample(source, 8) * 2 29 | 30 | # Used shuffle function to randomize the list of characters 31 | shuffle(chars) 32 | 33 | # Used numpy instead of list comprehensions to create an array of the chars at a 4x4 size. 34 | # After which, the array was converted to a list using the .tolist() method. 35 | L = np.array(chars).reshape(4,4).tolist() 36 | return L 37 | 38 | def create_asterisks_board(board): 39 | M = [['*' for coulmn in row] for row in board] 40 | return M 41 | 42 | def game_on(board, asterisks_board): 43 | pprint(asterisks_board) 44 | pprint(board) # DELETE LATER 45 | N = 10 46 | while N > 0: 47 | user_coor_1 = get_coor() 48 | print(f'\nFirst set of coordinates are {user_coor_1}.\n') 49 | print(board[user_coor_1[0]][user_coor_1[1]]) 50 | user_coor_2 = get_coor() 51 | print(f'\nSecond set of coordinates are {user_coor_2}.\n') 52 | print(board[user_coor_2[0]][user_coor_2[1]]) 53 | asterisks_board, N = check_coors(user_coor_1, user_coor_2, board, asterisks_board, N) 54 | win_lose_check(board, asterisks_board, N) 55 | pprint(asterisks_board) 56 | 57 | def get_coor(): 58 | message = 'Enter row: ' 59 | row = validate_coor(message, COOR) 60 | message = 'Enter column: ' 61 | column = validate_coor(message, COOR) 62 | return row, column 63 | 64 | def validate_coor(message, COOR): 65 | valid = False 66 | while not valid: 67 | try: 68 | user_input = int(input(message)) 69 | if user_input in COOR: 70 | valid = True 71 | else: 72 | print('\nEnter a valid coordinate number.') 73 | except ValueError: 74 | print('\nEnter a valid integer.') 75 | return user_input 76 | 77 | def check_coors(user_coor_1, user_coor_2, board, asterisks_board, N): 78 | if user_coor_1 == user_coor_2: 79 | N -= 1 80 | print(f'\nThose are the same coordinates...no. You have {N} chances left.') 81 | elif board[user_coor_1[0]][user_coor_1[1]] == board[user_coor_2[0]][user_coor_2[1]]: 82 | asterisks_board[user_coor_1[0]][user_coor_1[1]] = board[user_coor_1[0]][user_coor_1[1]] 83 | asterisks_board[user_coor_2[0]][user_coor_2[1]] = board[user_coor_2[0]][user_coor_2[1]] 84 | else: 85 | N -= 1 86 | print(f'\nNot a match. You have {N} chances left.') 87 | return asterisks_board, N 88 | 89 | def win_lose_check(board, asterisks_board, N): 90 | if board == asterisks_board: 91 | print('You win') 92 | exit() 93 | elif N == 0: 94 | print('You lose\n') 95 | pprint(board) 96 | exit() 97 | else: 98 | pass 99 | 100 | def main(): 101 | print('Welcome to the Memory Game') 102 | print('You have 10 chances to find all of the letter pairs.') 103 | print('You must input the coordinates from 0 to 3 for the position on the 4x4 board.\n') 104 | board = create_board() 105 | asterisks_board = create_asterisks_board(board) 106 | game_on(board, asterisks_board) 107 | 108 | if __name__ == '__main__': 109 | main() 110 | -------------------------------------------------------------------------------- /Chapter 9 Exercise/Q_17.py: -------------------------------------------------------------------------------- 1 | 2 | 3 | '''Ask the user to enter the numerator and denominator of a fraction, and the digit they want to 4 | know. For instance, if the user enters a numerator of 1 and a denominator of 7 and wants to 5 | know the 4th digit, your program should print out 8, because 17 6 | = .142856... and 8 is the 4th 7 | digit. One way to do this is to mimic the long division process you may have learned in grade 8 | school. It can be done in about five lines using the // operator at one point in the program 9 | ''' 10 | 11 | 12 | num = eval(input('Enter numerator: ')) 13 | denum = eval(input('Enter denumerator: ')) 14 | digit = int(input('Enter the digit you want to know: ')) 15 | i = 0 16 | l=[] 17 | while i < digit+1: 18 | result=num//denum 19 | mod=num%denum 20 | num=mod*10 21 | l.append(str(result)) 22 | i+=1 23 | u=l[-1] 24 | #l.insert(1,'.') 25 | #v = ''.join(l) 26 | #print(v) ''' to print out all the digits''' 27 | print(f'The digit is {u}' ) 28 | 29 | -------------------------------------------------------------------------------- /Chapter 9 Exercise/Q_18.py: -------------------------------------------------------------------------------- 1 | """ 2 | Randomly generate a 6 × 6 list that has exactly 12 ones placed in random locations in the list. 3 | The rest of the entries should be zeroes. 4 | """ 5 | 6 | from pprint import pprint 7 | from random import randint 8 | 9 | L = [[0 for column in range(6)]for row in range (6)] 10 | i = 0 11 | 12 | # Must use a while loop instead of for loop because can not repeat iterations. 13 | while i < 12: 14 | a, b = randint(0, 5), randint(0, 5) 15 | if L[a][b] == 1: 16 | pass 17 | else: 18 | L[a][b] = 1 19 | i += 1 20 | pprint(L) 21 | -------------------------------------------------------------------------------- /Chapter 9 Exercise/Q_2.py: -------------------------------------------------------------------------------- 1 | """(a) Write a program that uses a while loop (not a for loop) 2 | to read through a string and print 3 | the characters of the string one-by-one on separate lines. 4 | (b) Modify the program above to print out every second character of the string""" 5 | 6 | s = "Sorry" 7 | num =0 8 | while num < len(s): 9 | print(s[num]) 10 | #num += 1 ## a() 11 | num += 2 ## b -------------------------------------------------------------------------------- /Chapter 9 Exercise/Q_3.py: -------------------------------------------------------------------------------- 1 | """A good program will make sure that the data its users enter is valid. Write a program that 2 | asks the user for a weight and converts it from kilograms to pounds. Whenever the user 3 | enters a weight below 0, the program should tell them that their entry is invalid and then ask 4 | them again to enter a weight. 5 | 6 | [Hint: Use a while loop, not an if statement]. 7 | 8 | """ 9 | 10 | 11 | while True: 12 | weight =eval(input("Enter Weight in Kg: ")) 13 | if weight < 0: 14 | print("Illegal weight entered") 15 | else: 16 | pounds = weight * 2.2 17 | print("Your weight in Pounds is",pounds) -------------------------------------------------------------------------------- /Chapter 9 Exercise/Q_4.py: -------------------------------------------------------------------------------- 1 | """Write a program that asks the user to enter a password. If the user enters the right password, 2 | the program should tell them they are logged in to the system. Otherwise, the program 3 | should ask them to reenter the password. The user should only get five tries to enter the 4 | password, after which point the program should tell them that they are kicked off of the 5 | system.""" 6 | 7 | numberoftries = 0 8 | 9 | while numberoftries < 5: 10 | rightpass ="henry" 11 | askuserpass=input("Enter Password: ") 12 | 13 | if askuserpass == rightpass: 14 | print("User Access Granted") 15 | numberoftries += 1 16 | break 17 | else: 18 | numberoftries += 1 19 | print("Wrong Password","Number of tries left",5-numberoftries) 20 | 21 | 22 | -------------------------------------------------------------------------------- /Chapter 9 Exercise/Q_5.py: -------------------------------------------------------------------------------- 1 | """Write a program that allows the user to enter any number of test scores. The user indicates 2 | they are done by entering in a negative number. Print how many of the scores are A’s (90 or 3 | above). Also print out the average.""" 4 | scores=[] 5 | count=0 6 | while True: 7 | testscore =eval(input("Enter Test Cores: ")) 8 | scores.append(testscore) 9 | if testscore >= 90: 10 | count+=1 11 | 12 | if testscore == 0: 13 | print("Count Agrade",count) 14 | print("Average",sum(scores)/len(scores)) -------------------------------------------------------------------------------- /Chapter 9 Exercise/Q_6.py: -------------------------------------------------------------------------------- 1 | """Modify the higher/lower program so that when there is only one guess left, it says 1 guess, 2 | not 1 guesses.""" 3 | 4 | from random import randint 5 | secret_num = randint(1,100) 6 | num_guesses = 0 7 | guess = 0 8 | while guess != secret_num and num_guesses <= 4: 9 | guess = eval(input('Enter your guess (1-100): ')) 10 | num_guesses += 1 11 | if 5-num_guesses == 1 and guess > secret_num: 12 | print("LOWER.", 5 - num_guesses, "GUESS left") 13 | elif 5 - num_guesses == 1 and guess < secret_num: 14 | print("Higher.", 5 - num_guesses, "GUESS left") 15 | elif guess < secret_num and 5-num_guesses !=1: 16 | print("HIGHER.", 5-num_guesses, "guesses left") 17 | elif guess > secret_num and 5-num_guesses !=1: 18 | print("LOWER.", 5-num_guesses, "guesses left") 19 | 20 | else: 21 | print('You got it!') 22 | if num_guesses==5 and guess != secret_num: 23 | print('You lose. The correct number is', secret_num) -------------------------------------------------------------------------------- /Chapter 9 Exercise/Q_7.py: -------------------------------------------------------------------------------- 1 | """Recall that, given a string s, s.index('x') returns the index of the first x in s and an error 2 | if there is no x. 3 | (a) Write a program that asks the user for a string and a letter. Using a while loop, the 4 | program should print the index of the first occurrence of that letter and a message if the 5 | string does not contain the letter. 6 | (b) Write the above program using a for/break loop instead of a while loop.""" 7 | 8 | #a 9 | def Firstletter(): 10 | user_input =input("Input Word: ") 11 | letter = input("Choose Letter: ") 12 | count =0 13 | while count <1: 14 | count+=1 15 | if letter in user_input: 16 | print(user_input.index(letter)) 17 | else: 18 | print("Letter not found in word") 19 | 20 | 21 | 22 | #Firstletter() 23 | 24 | #b 25 | def Firstletter2(): 26 | user_input =input("Input Word: ") 27 | letter = input("Choose Letter: ") 28 | 29 | for character in user_input: 30 | if character == letter: 31 | print(user_input.index(character)) 32 | 33 | break 34 | 35 | 36 | 37 | Firstletter2() -------------------------------------------------------------------------------- /Chapter 9 Exercise/Q_8.py: -------------------------------------------------------------------------------- 1 | """The GCD (greatest common divisor) of two numbers is the largest number that both are divisible 2 | by. For instance, gcd(18, 42) is 6 because the largest number that both 18 and 42 are 3 | divisible by is 6. Write a program that asks the user for two numbers and computes their gcd. 4 | Shown below is a way to compute the GCD, called Euclid’s Algorithm. 5 | • First compute the remainder of dividing the larger number by the smaller number 6 | • Next, replace the larger number with the smaller number and the smaller number with 7 | the remainder. 8 | • Repeat this process until the smaller number is 0. The GCD is the last value of the larger 9 | number.""" 10 | 11 | def Gcd(): 12 | x=int(input("Enter First Number: ")) 13 | y = int(input("Enter Second Number: ")) 14 | while x or y != 0: 15 | if x>y : 16 | remainder = x % y 17 | if remainder== 0: 18 | return "The GCD is",y 19 | break 20 | 21 | else: 22 | x = remainder 23 | 24 | 25 | else: 26 | remainder = y % x 27 | if remainder ==0: 28 | return "The GCD is",x 29 | break 30 | else: 31 | y = remainder 32 | 33 | 34 | 35 | 36 | print(Gcd()) 37 | 38 | 39 | 40 | 41 | -------------------------------------------------------------------------------- /Chapter 9 Exercise/Q_9.py: -------------------------------------------------------------------------------- 1 | """ 2 | A 4000-year old method to compute the square root of 5 is as follows: Start with an initial 3 | guess, say 1. Then compute 4 | ((1 + (5/1)) / 2) = 3. 5 | Next, take that 3 and replace the 1’s in the previous formula with 3’s . This gives 6 | ((3 + (5/3)) / 2) = 7/3 ≈ 2.33. 7 | Next replace the 3 in the previous formula with 7/3. This gives 8 | ((7/3) + (5/(7/3)))/2 = 47/21 ≈ 2.24. 9 | 10 | If you keep doing this process of computing the formula, getting a result, and plugging it back 11 | in, the values will eventually get closer and closer to sqrt(5). This method works for numbers 12 | other than 5. Write a program that asks the user for a number and uses this method to estimate 13 | the square root of the number correct to within 10**−10. The estimate will be correct to within 14 | 10**−10 when the absolute value of the difference between consecutive values is less than 10**−10. 15 | """ 16 | 17 | def validate_input(message): 18 | valid = False 19 | while not valid: 20 | try: 21 | user_input = int(input(message)) 22 | if user_input > 0: 23 | valid = True 24 | else: 25 | print('\nPlease enter a positive number.') 26 | except: 27 | print('\nSorry, an integer was not inputted. Please enter an integer.') 28 | return user_input 29 | 30 | def limit_squ_rt(valid_num): 31 | x = 1 32 | root = 10 33 | while True: 34 | root = round((x + (valid_num / x)) / 2, 10) 35 | if abs(x - root) < 10**-10: 36 | return root 37 | x = root 38 | 39 | def main(): 40 | message = 'Enter a number to find the limit of the square root: ' 41 | valid_num = validate_input(message) 42 | squ_rt = limit_squ_rt(valid_num) 43 | print(f'\nThe limit of square root of {valid_num} is {squ_rt}.') 44 | 45 | if __name__ == '__main__': 46 | main() 47 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Practical-Introduction-to-python 2 | A Practical Introduction to Python Programming by Brian Heinold. This repository is a solution for most exercises in the book. 3 | 4 | 5 | --------------------------------------------------------------------------------