Python代写 | COMP202 Assignment 2

ASSIGNMENT 2

COMP202, Winter 2021 Due: Friday, March 12th, 11:59pm

Part 1 (0 points): Warm-up

Do NOT submit this part, as it will not be graded. However, doing these exercises might help you to do the second part of the assignment, which will be graded. If you have difficulties with the questions of Part 1, then we suggest that you consult the TAs during their office hours; they can help you and work with you through the warm-up questions. You are responsible for knowing all of the material in these questions.

Warm-up Question 1 (0 points)
Write a function swap which takes as input two int values x and y. Your function should do 3 things:

1. Print the value of x and y
2. Swap the values of the variables x and y, so that whatever was in x is now in y and whatever was

iny isnowinx
3. Print the value of x and y again.

For example, if your function is called as follows: swap(3,4) the effect of calling your method should be the following printing

Warm-up Question 2 (0 points)
Consider the program you have just written. Create two global integer variables in the main body of your program. Call them x and y. Assign values to them and call the swap function you wrote in the previous part using x and y as input parameters.

After calling the swap() function —inside the main body— print the values of x and y. Are they different than before? Why or why not?

Warm-up Question 3 (0 points)
Create a function called counting that takes as input a positive integer and counts up to that number. For example:

Warm-up Question 4 (0 points)
Modify the last function by adding an additional input that represents the step size by which the function should be counting. For example:

Warm-up Question 5 (0 points)
Write a function replace_all which takes as input a string and two characters. If the second and third input string do not contain exactly one character the function should raise a ValueError. Oth- erwise, the function returns the string composed by the same characters of the given string where all occurrences of the first given character are replaced by the second given character. For exam- ple, replace_all(“squirrel”, “r” , “s”) returns the string “squissel”, while replace_all(“squirrel”, “t”, “a”) returns the string “squirrel”. Do not use the method replace to do this.

Warm-up Question 6 (0 points)
Write a module with the following global variables:

In this module write a function make_lower which takes a string as input and returns a string containing the same characters as the input string, but all in lower case. For example, make_lower(“AppLE”) returns the string “apple”. Do not use the method lower to do this. Hint: note that characters from the English alphabet appear in the same position in the two global variables.

Warm-up Question 7 (0 points)
Create a function called generate_random_list which takes an input an integer n and returns a list containing n random integers between 0 and 100 (both included). Use random to do this.

Warm-up Question 8 (0 points)
Write a function sum_numbers which takes as input a list of integers and returns the sum of the numbers in the list. Do not use the built-in function sum to do this.

The questions in this part of the assignment will be graded.

The main learning objectives for this assignment are:

Note that the assignment is designed for you to be practicing what you have learned in the videos up to and including Week 8.2. For this reason, you are NOT allowed to use anything seen after Week 8.2 or not seen in class at all. You will be heavily penalized if you do so.

For full marks on the following three questions, in addition to the points listed on page 1, make sure to add the appropriate documentation string (docstring) to all the functions you write. The docstring must contain the following:

Examples
For each question, we provide several examples of how your code should behave. All examples are given as

if you were to call the functions from the shell.

When you upload your code to codePost, some of these examples will be run automatically to check that your code outputs the same as given in the example. However, it is your responsibility to make sure your code/functions work for any inputs, not just the ones shown in the examples. When the time comes to grade your assignment, we will run additional, private tests that may use inputs not seen in the examples.

Furthermore, please note that your code files for this question and all others should not contain any function calls in the main body of the program (i.e., outside of any functions). Code that does not conform in this manner will automatically fail the tests on codePost and be heavily penalized. It is OK to place function calls in the main body of your code for testing purposes, but if you do so, make certain that you remove them before submitting. Please review what you have learned in video 5.2 if you’d like to add code to your modules which executes only when you run your files.

Safe Assumptions

For all questions in this assignment, you can safely assume that the type of the inputs (both to the functions and those provided to the program by the user) will always be correct. For example, if a function takes as input a list, you can assume that a list will always be provided. At times you will be required to do some

input validation, but this requirement will always be clearly stated. Otherwise, your functions should work with any possible input that respect the function’s description. For example, if the description says that the function takes as input a positive integer, then it should work with all integers greater than 0. If it mentions an integer, then it should work for any integer. Make sure to test your functions for edge cases!

Code Repetition

One of the main principles of software development is DRY: Don’t Repeat Yourself. One of the main ways we can avoid repeating ourselves in code is by writing functions, then calling the functions when necessary, instead of repeating the code contained within them. Please pay careful attention in the questions of this assignment to not repeat yourself, and instead call previously-defined functions whenever appropriate. As always, you can also add your own helper functions if need be, with the intention of reducing code repetition as much as possible.

Question 1: Turtle Art (10 points)
This question asks you to write a function my_artwork() in a file called artwork.py. The function should draw a picture using the Turtle module. You are free to draw what you like, but your code/drawing must satisfy at least the following requirements:

Any submission meeting these requirements will obtain full marks, but you are encouraged to go beyond them. The most creative submissions (as judged by our TAs) will be shown in class. As St. Patrick’s Day is right around the due date of the assignment, you are encouraged to take inspiration from that holiday.

Note: Recall that you can import the speed function from turtle and then call speed(“fastest”) to speed up the drawing routines, so that you don’t waste time when testing your code.

Also, a reminder to please only use the functions from the Turtle module that we have seen in class, or you will lose marks. There is one exception: you can use the circle function from Turtle module. circle(r) takes a radius r as argument and draws a circle of the given radius. You can also specify a second integer argument for the extent of the circle to draw, e.g., circle(r, 90), which will draw only a quarter of a circle (90 degrees).

Some submissions from students of previous years (with their size scaled down to fit) can be found at the top of this page.

Question 2: Return of the COMP202COIN (35 points)
It is the year 3019 on the planet Orion. COMP202COIN has become the most popular currency on the planet. As much time has passed, the COMP202COIN that exist now are not like the ones you have seen previously. These COMP202COIN are represented in a special base known as ‘base 202’, which is similar to base 8 (octal). Base 8 uses the digits 0 through 7 to represent quantities. Base 202 is similar to base 8, as it uses only 8 characters, but instead of 0, 1, 2, 3, 4, 5, 6, and 7, it uses the following: 0, C, 2, O, M, P, I, andN.A0 (zero)anda2 (two)arethesameinbothbases,buta1, 3, 4, 5, 6, or 7 of a base 8 string do not exist in base 202 and are instead represented by a C, O, M, P, I, and N, respectively.

Another important note about amounts of COMP202COIN is that they are always represented using 10 characters. The first two characters are always 0c or 0C. The next eight characters represent the amount of COMP202COIN in base 202, with 0’s padding the amount in front if it does not need the full eight characters. For example, a solitary COMP202COIN would be represented as the string 0c0000000C (as a 1 in base 202 is C). Note that the letters are not case-sensitive, so a c or C, n or N, etc., can be used interchangeably.

You may assume for the purposes of this question that we will never deal with an amount greater than 8 characters in base 202 (i.e., the maximum value would be 0cNNNNNNNN).

Everything has been going great on the planet and major banks are now starting to use COMP202COIN as their main currency. But, bad news. Attack ships were spotted off the shoulder of Orion two days ago. Yesterday, they detonated an electromagnetic charge in the atmosphere, which has scrambled communications systems. Customers logging into their banks today have discovered their monthly statements of COMP202COIN transactions have been totally garbled. The banks are asking for help to get their customer transactions in order. Can you help restore order?

We will approach this problem by writing code in a file called coins.py. First, define two global variables at the top of your file:

• BASE8_CHARS: a string containing the characters of base 8: 0, 1, 2, 3, 4, 5, 6, and 7.

• BASE202_CHARS: a string containing the characters of base 202: 0, C, 2, O, M, P, I, and N. Use them as appropriate in your code.
Then, define the following functions:

When clients view their banking information on OrioNet, all their transactions are jumbled up into a single paragraph. We have to write some functions to identify particular transactions/amounts of money in the paragraph.

Note: A 10-character COMP202COIN substring cannot be part of another 10-character COMP202COIN substring. For example, `0c0cOIN0COIN’ contains only one 10-character COMP202COIN, starting
at index 0 and ending at index 9. Although there is another 10-character COMP202COIN from index 2 to 11, it should not be recognized by the function because indices 2 through 9 are already part of the first COMP202COIN string, and so cannot be ‘re-used.’

Examples:

The communication problem has caused a problem for the banks, who have lost the amounts of how much COMP202COIN they have to give out to clients. They are therefore imposing a maximum limit on the amount of COMP202COIN in any client’s holdings. If a client’s total holdings of COMP202COIN is greater than the limit, then the accounts of that client will all be reduced by a percentage such that the total of their holdings sums to the limit. We will write this task in the following function:

• reduce_amounts(text, limit): takes a string that could be of any length and contain any characters, and a non-negative integer limit. If the string contains any COMP202COIN amounts and their total dollar amount is less than or equal to the limit, then the function should return the same

string unchanged. Otherwise, it should calculate the difference between the total dollar amount and the limit, then find the percent decrease (by dividing the difference by the total dollar amount). It should then go through the string, and reduce each COMP202COIN amount by the given percentage (rounding down). Note that as the percentage relates to dollar amounts and not COMP202COIN amounts, each time a COMP202COIN amount is found in the string, it must first be converted to base 10, then reduced by the percentage and then converted back to base 202. The updated string should then be returned. Note that any characters not part of a COMP202COIN amount should remain unchanged in the returned string.

Examples:

Question 3: Farkle (55 points)
Farkle is a dice game. To play, all that is required is six 6-sided dice. Normally Farkle is played with 2 to 8 players. Each player in turn rolls all six dice and checks to see if they have rolled any scoring dice or combinations. (See Scoring below.) Any dice that score may be set aside and then the player may choose to roll all the remaining dice. The player must set aside at least one scoring die of their choice if possible but is not required to set aside all scoring dice.

For example, if a player rolled 1-2-2-5-5-6 on their turn, they could set aside the 1 and the two 5’s for scoring, or they could choose to set aside only the 1. Any scoring dice that are not set aside may be rerolled along with the non-scoring dice.

If all six dice have been set aside for scoring (known as having “hot dice”), the player can choose to roll all six dice again and continue adding to their accumulated score, or they can bank their points, end their turn, and pass the dice to the next player.

If a player scores no points on a roll, this is known as a Farkle. The player may continue to roll any dice that have not been previously set aside for scoring, but all of their points gained so far that turn are lost.

A player’s turn continues until either they decide to stop (at which point they then score their accumu- lated points) or until they have no more dice to throw. By deciding to keep re-rolling, the player may obtain a higher score, but they are also taking the risk to lose all their points so far if they Farkle.

At the end of a player’s turn, any points they have scored are recorded and the dice are passed to the next player.

The goal of this question is to write several modules to implement a multi-player game of Farkle.

This is the commonly used scoring rules for Farkle. Different variations are also used.

5 Three 1’s Three 2’s Three 3’s Three 4’s Three 5’s Three 6’s 1-2-3-4-5-6 3 Pairs

100 points 50 points 1,000 points 200 points 300 points 400 points 500 points 600 points 3000 points 1500 points

Note that scoring combinations only count when made with a single throw. (Example: If a player rolls a 1 and sets it aside and then rolls two 1’s on their next throw, they only score 300 points, not 1000.)

Sometimes a single roll will provide multiple ways to score. For example, a player rolling 1-2-4-5-5-5 could score one of the following:

• 100 points for the 1
• 150pointsforthe1anda5
• 500 points for the three 5’s
• 600 points for the 1 and the three 5’s

It is up to the player to decide which dice to set aside for scoring.

Farkle Utility Functions

Let’s start by creating a module named farkle_utils which contains several helper functions needed to implements the full program. Inside this module import the module random.

For full marks, all the following functions must be part of this module. Be careful!, functions that take lists as input should not modify them. To prevent this from happening you can create additional lists inside the function which are copies of the inputs and work with those instead.

For example:

For example:

For example:

For example:

• contains_all: given a list of integers, it returns True if the list contains all unique consecutive pos- itive integers starting from 1. The order in which the elements appear in the list is not important.

For example:

• count_num_of_pairs: given a list of integers, it returns the number of pairs in the list. Note that if a number appears 4 times in the list, this should count as two pairs, if it appears 6 times it should count as 3 pairs, and so on. The order in which the elements appear in the list is not important.

For example:

• is_included: given two lists of integers as input, it returns True if the second one is a subset of the first one, False otherwise. Note that once again, the order in which the elements appear in both list is not important.

For example:

• get_difference: given two lists of integers as input, it returns a list which, if added to the second one, would result in a list containing the same elements as the first one. If the second list is not a subset of the first one, then this function should return an empty list. Note that once again, the order in which the elements appear in both list is not important.

For example:

A game of Farkle

Let’s now create a module named farkle. This module will contain the functions that allow us to execute a game of Farkle between multiple players.

Inside this module, import random and farkle_utils, and add the following global variables:

Use the variables whenever appropriate in your code. For full marks, all the following functions must be part of this module:

• compute_score: given a list of integers between 1 and 6 (both included) as input representing the dice rolls selected by a player, it computes and returns the points scored. This function should use the global variables above and should refer to the scoring rules introduced at the beginning of this question. Please note that when scoring a triplet of 1’s, the score should be multiplied by 10 on top of using the TRIPLET_MULTIPLIER defined above. Note that if not all the rolls selected can be used when computing the score, then the total score should be 0. The function should output the highest possible score that can be made by using all rolls. For instance, assuming the global variables are initialized as indicated above [2, 2, 2, 2, 2, 2] would be con- sidered a three pairs scoring 1500 points, while [1, 1, 1, 1, 1, 1] would be considered two triplets of 1 scoring 2000 points. Note that, you can always assume that triplets score more than counting a single value three times. That is, it will never be the case that, for example, [1, 1, 1] scores more as three ones compare to a triplet.

For example:

• get_winners: given a list of positive integers representing the scores of the players, and a positive integer representing the score to reach in order to win the game, it returns a list of players with the highest score which reached or surpassed the winning score. Note that we represent a player with an integer. This integer is the position of the player’s score in the list when we start counting from 1. For instance, given the scores [500, 100, 5], we know that Player 1 scored 500 points, Player 2 100, and Player 3 only 5 points. If there are ties, the player numbers should appear in increasing order.

For example:

• play_one_turn: given a positive integer representing a player, it allows that player to play their turn. The function then returns the score of this player after they end their turn. For this function you do not need to write the examples in the docstring. You should still write the type contract and the description.

Here is how a turn of Farkle for one player works:

7. The function displays the current accumulated score as well as the remaining number of dice the player has. Assuming that the player has at least one dice to roll, the function asks them whether they’d like to roll or pass and the same process from step 3 is repeated.

Please note that the messages displayed by the function do not matter, and you are encouraged to personalize them. What matters is that all the information listed above appears, and is requested in the order specified. For example, the player should be asked whether they’d like to ‘roll’, a sequence of integers representing the rolls should be displayed, etc.

You can find below some examples of executing the function. Note that the inputs provided from the user appear in blue. The last number (the one that appears at the end of the execution) rep- resents the value returned (not displayed!!) by the function.

Example 1:

Example 2:

Example 3:

Example 4:

Example 5:

• play_farkle: given no inputs, this functions executes a game of Farkle. For this function you do not need to write the examples in the docstring. You should still write the type contract and the description.

Here is how a game of Farkle should work:

Please note that the messages displayed by the function do not matter, and you are encouraged to personalize them. What matters is that all the information listed above appear/are requested in the order specified. For example, the number of players should be asked (and settled on) before the winning score, etc.

You can find below a some examples of executing the function. Note that the inputs provided from the user appear in light blue.

Example 1:

Example 2:

Example 3:

What To Submit

You must submit all your files on codePost (https://codepost.io/). The file you should submit are listed below. Any deviation from these requirements may lead to lost marks.

artwork.py
coins.py
farkle_utils.py
farkle.py
README.txt In this file, you can tell the TA about any issues you ran into doing this assignment. If you point out an error that you know occurs in your program, it may lead the TA to give you more partial credit.

Remember that this assignment like all others is an individual assignment and must represent the entirety of your own work. You are permitted to verbally discuss it with your peers, as long as no written notes are taken. If you do discuss it with anyone, please make note of those people in this README.txt file. If you didn’t talk to anybody nor have anything you want to tell the TA, just say “nothing to report” in the file.