practiceProblems-2

pdf

School

Temple University *

*We aren’t endorsed by this school

Course

1051

Subject

Computer Science

Date

Jan 9, 2024

Type

pdf

Pages

15

Uploaded by ProfBook6768

Report
Practice Problems Intro to Programming and Problem Solving - Python Answer the questions in the spaces provided. Please note that there are no intentional errors in the code provided except in questions asking you to correct said code. Your written code does not have to be 100% syntactically correct. You are allowed a page of notes, front and back. Name: Page Points Score 3 10 4 10 5 10 6 20 7 20 11 10 12 10 15 10 Total: 100 1
Temple University Practice Problems CIS 1051 Useful notes: You are allowed to clarify any answer you give. You are allowed to ask for clarification. Things are never as complicated as they appear, especially the math. Never leave a question blank, even if you don’t know the answer. We can’t give partial credit to blanks. len(q) returns the size of q math.sqrt(x) returns the float x ”hello there”[2:7] returns ”llo t” ”hello”[1] returns ’e’ len(”hello”) returns 5 regex = re.compile(pattern) to make a regex object. regex.sub(thingsUsedToReplace,targetText) to replace the regex with thingsUsedToReplace in targetText \d Any numeral. \D Inverse of \D \w Any word character, which is an alphanumeric or an underscore. \W Inverse of \w . \s Any whitespace character. \S Any character that isn’t whitespace. \b Any word boundary character. It’s like \W , but will catch like beginnings and endings. open(filename,’r’).read() to read a file into a string. newFile = open(filename, ’w’) to create a new file to write to. newFile.write(text) to write some text to the file. If you want to overwrite a file you’re reading, you need to close() it first. Practice Problems Page 2 of 15 0 points
Temple University Practice Problems CIS 1051 1. (10 points) Write a function called makeUsername that generates a a username for a given name and suffix, as demonstrated by the examples below. You can assume that the format of the name is either “FIRSTNAME LASTNAME” or “FIRSTNAME MIDDLENAME LASTNAME” 1 # ’Andrew Rosen’,12 -> ar12 # ’Alan Turing’, 5 -> at5 # ’Andrew Benjamin Rosen’, 3 -> abr3 # ’Andrew Benjamin Rosen’, 104 -> abr104 def makeUsername(name,n): 1 Although this is not true for all cases in real life. https://www.kalzumeus.com/2010/06/17/ falsehoods-programmers-believe-about-names/ Practice Problems Page 3 of 15 10 points
Your preview ends here
Eager to read complete document? Join bartleby learn and gain access to the full version
  • Access to all documents
  • Unlimited textbook solutions
  • 24/7 expert homework help
Temple University Practice Problems CIS 1051 2. (10 points) From previous Final: Suppose you are playing a game which keeps track of each of the player’s scores and outputs it into a file. The files is made of multiple lines; each line contains a player’s name, followed by a comma, followed by that player’s score. Write a function that takes in a filename as an argument and returns or prints which player had the highest score and what it was. For this example file below, your function should report that Mario was the winner with a score of 97. Kamek,57 Toad,12 Peach,82 Mario,97 Luigi,80 Bowser,5 Yoshi,70 Cappy,92 Goomba,2 Donkey Kong,45 def whoWonWhy(filename): #your code goes here Practice Problems Page 4 of 15 10 points
Temple University Practice Problems CIS 1051 3. (10 points) belowAverage: Given a list of numbers, return a new list of all numbers from that list that are less than the average. def belowAverage(numbers): Practice Problems Page 5 of 15 10 points
Temple University Practice Problems CIS 1051 4. (10 points) XOR : Return true if only a is true or only b is true, but false if both are true or both are false. def XOR(a, b): 5. (10 points) sumOfThrees : Given a list that contains many lists of integers, return the sum of all the integers in the lists that are multiples of 3. Half credit is given if the answers works on a list of integers [[1,2,3,4,5,6,7,8,9,10]] -> 18 [[10,20], [5], [20,15,1,1,1]] -> 15 [[10,20,51], [10,20,30]] -> 30 def sumOfThrees(numbers): Practice Problems Page 6 of 15 20 points
Your preview ends here
Eager to read complete document? Join bartleby learn and gain access to the full version
  • Access to all documents
  • Unlimited textbook solutions
  • 24/7 expert homework help
Temple University Practice Problems CIS 1051 6. (10 points) allDigitsProduct Given a list of numbers, return the product of all digits of all the numbers in the list. # [1,2,3,4,5] -> 120 # [10,20,5] -> 0 # [44, 12, 3112] -> 192 def allDigitsProduct(nums): 7. (10 points) has231 Given a list of numbers, return true if it follows the “231” pattern, namely that the list has a value x , followed by x + 1 , followed by x 1 . You don’t have to print out what the numbers were, but we listed them in the example outputs for extra clarity. # [1,2,3,4,5] -> False (doesn’t contain the pattern) # [74,3,4,2,74,75,2] -> True (3,4,2 satisfies the pattern) # [74,75,0,1,-1,100] -> True (0,1,-1 satisfies the pattern) def has231(arr) : Practice Problems Page 7 of 15 20 points
Temple University Practice Problems CIS 1051 The outcome of any fair coin toss has an equal chance of landing on heads or tails. If I were to toss a coin three times in a row, there are a total of 8 equally probable outcomes. HHH HHT HTH HTT THH THT TTH TTT where H is heads and T is tails. Thus, HHT represents two heads thrown in a row, followed by a tails. Suppose Professor Rosen challenges you to coin flipping game for $100. You will choose a sequence that occurs after three coin flips, such as HHT , and Professor Rosen will choose one, such as THH . One of you will keep flipping a coin until one of our three flip sequences occurs, and whoever’s sequence shows up first wins. So, for example, if we flip the coin until one of the chosen example sequences occurs, a few games might be: HTHTHTHH -> Rosen wins HHT -> You win TTHTHH -> Rosen win HHHHHT -> You win This seems like a fair bet; after all, all eight outcomes of flipping a coin three times are equally likely. Then you remember that Professor Rosen mentioned he was sorted into Slytherin and is a bit of a trickster; he probably wouldn’t be challenging you unless he was sure he was going to win. So let’s write a program on the next page to simulate this game and see if your professor is trying to scam you. 2 2 Once you finish the practice exam, you should learn more about the game by watching Numberphile’s video on Penney’s Game, found here: https://www.youtube.com/watch?v=Sa9jLWKrX0c Practice Problems Page 8 of 15 0 points
Temple University Practice Problems CIS 1051 8. (0 points) Write a program that simulates the game on the previous page with one player trying to get HHT and the other trying to get THH . 3 Have your program simulate the game 100000 times and print out the percentage of times the two players win. 3 Other games to simulate if you want to see more is TTT vs HTT and HHT vs HTH Practice Problems Page 9 of 15 0 points
Your preview ends here
Eager to read complete document? Join bartleby learn and gain access to the full version
  • Access to all documents
  • Unlimited textbook solutions
  • 24/7 expert homework help
Temple University Practice Problems CIS 1051 From Last Year’s Exam In the board game Monopoly, players move around the board by rolling a pair of six-sided dice. Rolling “doubles,” such as two 3’s or two 5’s, is especially fortunate, as this allows the player to roll again, essentially getting the player an extra turn. If the player rolls another set of doubles 4 , this allows the player yet another extra turn. However, rolling doubles a third time will immediately land the player in “jail,” ending their turn and trapping the player until they can roll a double. Write a program that will simulate 100000 Monopoly turns (extra rolls due to doubles count as the turn), where a turn is a single roll of the dice or more if the user rolls a double. Your program should print out: The percentage of rolls without a double. The percentage of rolls with 1 double. The percentage of rolls with 2 doubles. The percentage of rolls with 3 doubles. 0.1 Grading Points will be given as follows 10pts Simulating 100000 dice rolls. 5pts Handling doubles. 3pts Handling two and three doubles in a row. 2pts Presenting the data in percentages. 4 It can be the same pair as the first time Practice Problems Page 10 of 15 0 points
Temple University Practice Problems CIS 1051 9. (10 points) Put your program here: Practice Problems Page 11 of 15 10 points
Temple University Practice Problems CIS 1051 10. (10 points) Given a string, write a function which returns the most common letter in the string. Use a dictionary to do this. 11. (0 points) Given two strings, write a method that returns true if they are permutations of each other. Two strings are permutations of each other if they have the same numbers of each character. Use a pair of dictionaries to do this. This is a much harder problem than what would appear on the exam. def isPermutation(word1,word2): count1 = {} # keys are each character in word1 # value is the counts of each character in word2 count2 = {} # same, but word2 Practice Problems Page 12 of 15 10 points
Your preview ends here
Eager to read complete document? Join bartleby learn and gain access to the full version
  • Access to all documents
  • Unlimited textbook solutions
  • 24/7 expert homework help
Temple University Practice Problems CIS 1051 Here’s a final monte carlo problem from a few years ago: Dungeons and Dragons (DnD for short) is one of the most popular tabletop Role-Playing Games currently on the market, if not the most popular, and I happen to be a pretty big fan of it. In DnD, players take on the roll of adventurers, going on quests and slaying monsters. For your exam, we will be running a simulation to answer the following question: what are the odds a level 1 fighter can slay a goblin in one hit. So what do we need to know to answer this question? Dice First, Dungeons and Dragons uses dice to determine the outcome of any action that has an element of chance. These dice range in sizes, but for our exam we only need to concern ourselves with two types of dice: the 20-sided die with the range 1 to 20 (a d20 for short), and the standard 6 sided die (a d6 for short). I will be using standard die notation: 1d20+5 -> take a 20-sided die, roll it, add 5 to the result, giving the range [6,26] 3d4+4 -> take three 4-sided dice, roll them, sum them up and add 4 to the result, giving the range [7,16] 8d6 -> take eight 6-sided dice, roll them, sum them up without adding anything, giving the range [8,48] Combat Second, the way combat works is in two parts: The attack roll and the damage roll. The Attack Roll The attack roll is made to see if an attack hits the target. This is done by rolling a d20 and adding a number, called the attack bonus. The total needs to be greater than or equal to the Armor Class (AC, for short) of the target, which is the number that indicates how tough the monster is to hit. If an attack hits the target by meeting or beating the AC,then we make a damage roll to see how strong the attack was. If an attack misses, which happens if the attack roll is lower than the AC, we don’t make a damage roll, meaning 0 damage is dealt. Here is an example: Example My wizard is trying to blast a zombie with fire. Zombies can’t really dodge, so they have an AC of 8. Assuming my wizard’s attack bonus is +4, I roll 1d20+4. If my total is greater than or equal to 8, the AC in this example, that is a hit, and my wizard can roll for damage. If my roll is lower, my blast of fire misses and does 0 damage. The Damage Roll When our attack hits, we roll for damage, which is much simpler. We simply roll the dice and add the bonus defined for the attack. For example, a cleric who hit a ghoul with his mace might do 1d6+2 damage, which has a range of [3,8], while the wizard from the above example might do 1d10 points of damage. This damage is subtracted from the targets Hit Points, or HP. If we reduce a monster’s hit points (HP) to 0 or less, we have slain it. Practice Problems Page 13 of 15 0 points
Temple University Practice Problems CIS 1051 The Simulation We are going to simulate a level 1 fighter (eg a player who just started the game) attacking a goblin and calculate the odds of slaying a goblin in a single strike. A fighter’s attack roll is 1d20+5 and the Goblin’s AC is 15, as they are quick and wear armor. If the attack roll hits, the fighter’s damage roll is 2d6+3. A goblin has 7 hit points. Calculate the odds of a fighter slaying a goblin in a single blow by simulating 100,000 attack rolls and their respective damage. A missed attack does 0 points of damage. 1 Rubric 1 points - A function for rolling a d20 1 points - A function for rolling a d6 1 points - Code or function to make an attack roll 1 points - Code or function to see if an attack roll hits. 1 points - Code or function to calculate damage 1 points - Code or function to see if goblin is slain 1 points - Code or function simulating attack roll / damage trial 1 points - Simulating 100000 trials 1 points - Collecting data 1 points - Presenting/printing results Practice Problems Page 14 of 15 0 points
Temple University Practice Problems CIS 1051 12. (10 points) Calculate the odds of a fighter slaying a goblin in a single blow by simulating 100,000 attack rolls and their respective damage. A missed attack does 0 points of damage. Practice Problems Page 15 of 15 10 points
Your preview ends here
Eager to read complete document? Join bartleby learn and gain access to the full version
  • Access to all documents
  • Unlimited textbook solutions
  • 24/7 expert homework help