Description
CPSC 231 Assignments 01 The Game of Pig
Pig is a very simple, but fun dice game invented by John Scarne in 1945. It is normally played by two
players, and has an interesting jeopardy decision component during each player’s turn.
The rules of Pig are very simple. Two players take turns trying to accumulate points, and the winner is
the first player to reach 100 points. At the beginning of a player’s turn, a separate turn score is started at
zero, and the turn proceeds as follows:
1. The player makes a decision whether to roll (going to step 2) or to hold (going to step 3).
2. If the player decided to roll, he or she rolls a single six-sided die.
1 – Pig out! The player scores nothing this turn, the turn ends, and the opponent’s turn begins.
2, 3, 4, 5, or 6 – The roll is added to the turn score, and the player continues his or her turn at
step 1.
3. If the player decided to hold, the current turn score is added to the player’s total score and his
or her turn ends.
Players can toss a coin to decide who goes first. The first player to end their turn at or above 100 total
points is the winner.
This assignment will be your first use of the Python programming language in this class to implement a
version of the game that can be played within the console window on your computer. Create and
submit a separate Python program for each problem.
Problem 1: Rolling a die (1 marks)
Write a Python program to simulate rolling a single six-sided die. Print the result of the roll to the
terminal.
Inputs: None.
Outputs: The result of your die roll.
Example Problem 1 output:
– rolled a 3
Problem 2: Expected Value (2 marks)
If you study probability theory, you may think of the outcome of a die roll as a random variable. The
expected value of the random variable long-term average or mathematical expectation of what the
outcome would be if you repeated the random process many times.
Write a Python program to compute the expected value of a six sided die roll by simulating many rolls
and calculating the average outcome. Use a command line argument to specify the number of simulated
trials to perform.
Inputs: The number of rolls to simulate as a command line argument.
Outputs: Your estimation of the expected value of a die roll, presented in a form similar to that shown
on the right.
Example Problem 2 invocation:
$ python my-p2.py 1000
Example Problem 2 output:
Rolling 1000 times…
Estimated expectation: 3.481
Problem 3: Expected Rolls (3 marks)
You might also wonder, on average, how many die rolls you can expect to make in a turn of Pig before
you “pig out”. Write a program to simulate rolling a die and counting the number of rolls before a 1
comes up. Then use the same simulation method from Problem 2 to estimate the expected number of
turns before pigging out.
Inputs: A command line argument specifying the number of turns to simulate.
Outputs: Your estimation of the expected number of rolls before pigging out.
Example Problem 3 invocation:
$ python3 my-p3.py 500
Example Problem 3 output:
Simulating 500 turns…
Estimated expectation: 6.432
Problem 4: The Computer’s Turn (3 marks)
First, we’d like to program the computer to be able to play a turn of pig. We wouldn’t want the
computer to keep rolling until it pigs out every turn of course, because it would never score any points!
A very simple and good strategy for Pig is to keep rolling until you accumulate 20 or more points in the
turn, then hold and keep that as your turn score.
Write a program that simulates a single turn of Pig with the computer using this strategy to play.
Inputs: None.
Outputs: Print the outcome of each die roll as it happens, then print the final score for the computer
player at the end of the turn.
Example Problem 4 output:
– rolled a 5
– rolled a 6
– rolled a 6
– rolled a 4
Turn score = 21
Another sample run:
– rolled a 3
– rolled a 2
– rolled a 1
Pigged out!
Turn score = 0
Problem 5: The Computer’s Strategy (3 marks)
We can make a little tweak to the strategy to make it do a lot better. For example, if we start the turn
with 98 total points, there’s really no reason to try to get 20 points because we only need 2 points to
win!
Write a program that plays a turn of pig where, given the initial score, it uses the strategy of holding at
20 points or after accumulating enough points to reach 100. This will be our final computer AI’s strategy.
Inputs: The current total score entered via a prompt.
Outputs: Print the outcome of each die roll as it happens, then print the turn score and total score for
the computer player.
Example Problem 5 output:
Enter current score: 90
– rolled a 2
– rolled a 6
– rolled a 6
Turn score = 14
New total score = 104
Problem 6: The Solitaire Pig (4 marks)
With the computer AI complete, we can test it out by having it play a full game of Pig by itself.
Write a program that simulates a full one player game, played by the just the computer, starting at a
total score of 0 and playing turn after turn until it reaches 100 points.
Inputs: None.
Outputs: A turn-by-turn transcript of the computer playing Pig by itself until it reaches the goal of 100
points.
Example Problem 6 output:
– rolled a 6
– rolled a 1
Pigged out!
Turn score = 0
New total score = 0
– rolled a 1
Pigged out!
Turn score = 0
New total score = 0
– rolled a 5
…
– rolled a 4
Turn score = 23
New total score = 90
– rolled a 4
– rolled a 5
– rolled a 5
Turn score = 14
New total score = 104
Problem 7: Computer vs. Computer (4 marks)
The game of Pig was really meant for two players, so we’ll make that happen now. First, we’ll have both
players controlled by the computer, and both using the same strategy as before.
Write a program that simulates two computer AIs playing Pig against each other. Name the players
“Player One” and “Player Two”, or other names of you choosing, to distinguish them.
Your program should randomly choose which player goes first. It should keep a total score for each
player, and alternate turns between the computer players until one player ends its turn with a score of
100 or higher. Print the outcomes of each roll that occurred during each turn, and at the end of each
turn, print a summary of the total scores to that point in the game.
Inputs: None.
Outputs: A turn-by-turn transcript of two computer players playing Pig against each other.
Example Problem 7 output:
Player One’s score: 0
Player Two’s score: 0
It’s Player One’s turn
– rolled a 1
Pigged out!
Total turn score = 0
Player One’s score: 0
Player Two’s score: 0
It’s Player Two’s turn
– rolled a 6
– rolled a 2
…
Player One’s score: 85
Player Two’s score: 88
It’s Player One’s turn
– rolled a 2
– rolled a 6
– rolled a 2
– rolled a 4
– rolled a 3
Total turn score = 17
Final score: 102 vs 88
Player One wins!
Problem 8: Player vs AI (5 marks)
Finally, it’s time to create the interactive game of Pig where you get to play a full game against the
computer. Replace one of the computer players from your previous program with an interactive prompt
for a human player’s input. After each roll during the human player’s turn, ask whether the player wants
to [r]oll or [h]old.
Print a full transcript of the game playing out, just as you did with the previous problem. Play a few
games against your computer AI when you’re done, just to make sure everything works.
Submission:
After you have completed this assignment, you should have written a total of eight Python programs,
saved as .py files.
Please ensure that your files are named descriptively, with the problem number included, so that your
TA can easily see which program is associated with each problem.
Use the University of Calgary Desire2Learn system (https://d2l.ucalgary.ca) to submit your assignment
work online. Log in using your UofC eID and password, then find our course, cpsc 231 l01 and l02, in the
list. Then navigate to Assessments -> Dropbox Folders, and find the folder for Assignment #1 here.
Collaboration
Discussing the assignment requirements with others is a reasonable thing to do, and an excellent way to
learn. However, the work you hand-in must ultimately be your work. This is essential for you to benefit
from the learning experience, and for the instructors and TAs to grade you fairly. Handing in work that is
not your original work, but is represented as such, is plagiarism and academic misconduct. Penalties for
academic misconduct are outlined in the university calendar.
Here are some tips to avoid plagiarism in your programming assignments.
1. Cite all sources of code that you hand-in that are not your original work. You can put the citation
into comments in your program. For example, if you find and use code found on a web site, include
a comment that says, for example:
# the following code is from
https://www.quackit.com/python/tutorial/python_hello_world.cfm.
Use the complete URL so that the marker can check the source.
2. Citing sources avoids accusations of plagiarism and penalties for academic misconduct. However,
you may still get a low grade if you submit code that is not primarily developed by yourself.
3. Discuss and share ideas with other programmers as much as you like, but make sure that when you
write your code that it is your own. A good rule of thumb is to wait 20 minutes after talking with
somebody before writing your code. If you find yourself exchanging code by electronic means,
writing code while sitting and discussing with a fellow student, typing what you see on another
person’s console, then you can be sure that “your” code is not substantially your own, and your
sources must then be cited to avoid plagiarism.
4. Collaborative coding is strictly prohibited. Your assignment submission must be strictly your code.
Discussing anything beyond assignment requirements and ideas is a strictly forbidden form of
collaboration. This includes sharing code, discussing code itself, or modeling code after another
student’s algorithm. You cannot use (even with citation) another student’s code.
5. We will be looking for plagiarism in all code submissions, possibly using automated software
designed for the task. For example, see Measures of Software Similarity (MOSS –
https://theory.stanford.edu/~aiken/moss/).
Remember, if you are having trouble with an assignment, it is always better to go to your TA and/or
instructor to get help, than it is to plagiarize.
Credits:
The game of Pig was originally invented by John Scarne [1]. To the best of our knowledge, the use of the
Pig dice game to teach computer science was pioneered at Gettysburg College. A few problems
appearing in this assignment are derived from originals posed by Todd Neller [2]. A few problems were
also derived from problems posted by Sonny Chen.
1. John Scarne. Scarne on Dice. Wilshire Book Co., 8th edition, 1992
2. Todd W. Neller, Clifton G. M. Presser, Ingrid Russell, and Zdravko Markov. Pedagogical
possibilities for the dice game Pig. Journal of Computing Sciences in Colleges, 21(6):149–161,
2006
Grading:
There are total 25 marks for this assignment. If you have completed all the problems, you would get 25
marks.
CPSC 231 Assignment 02 Statistics on Movie and it’s rating Database
In this assignment, you will perform different statistical operation on a movie database and extract
useful information. This movie database contains list of 30 movies and ratings for these movies.
There are two problems in this assignment. For the problem 1, a list of 30 movies and corresponding
ratings (or scores) are already provided in problem1.py file. The rating is based on the following scale:
0 Never seen it.
1 It was terrible!
2 Didn’t like it.
3 It was OK.
4 Liked it.
5 It was awesome!
For problem 2, same list of 30 movies is provided. In addition to movie list, rating from five friends about
every movie is also provided in problem2.py file. The problem2.py contains two lists:
A list of movies
Rating (or scored) of each movie from five friends
Problem 1: Personal Summary (1 + 2 + 2 = 5 marks)
For this problem, you should first download problem1.py from D2L. It contains a list of 30 movies and
corresponding ratings.
Write a program that does not take any input and prints the following to the screen:
1. The number of movies seen out of the total number of movies.
2. A list of favorite titles (with the highest possible rating).
3. A list of least favorite titles (with the lowest possible rating).
Sample Run:
Hello [YourName]!
It looks like you’ve seen 21 out of the 30 movies.
Your favorite movies were:
The Ring (2002)
Deadpool (2016)
Your least favorite movies were:
Wall-E (2008)
Million Dollar Baby (2004)
Ratatouille (2007)
Baywatch (2017)
The Matrix Revolutions (2003)
Problem 2: Friend’s rating statistics (1 + 3 + 2 + 3 + 2 = 11 marks)
For this problem, you should first download problem2.py from D2L. It contains a list of 30 movies and
rating from five friends about each movie as a single list.
Write a program that compute the following statistics:
1. Average number of movies seen: How many of our 30 movies, on average, has a friend seen?
Calculate the average number of non-zero ratings per individual in our data set.
2. Most popular movies: Which of our movies have been seen by the most? Find the movies that
have the most number of non-zero ratings from friends.
3. Least popular movies: Which movies have been seen by the least? Find the movies that have the
most number of zero ratings.
4. Highest rated movies. Which movies from the list are the “best” movies according to the
friends? Find the movies that have the highest average rating among friends. Do not include 0
ratings (never seen it) when calculating the average.
5. Lowest rated movies. Which are the worst movies? Find the movies that have the lowest
average rating. Again, do not include 0 ratings.
Sample Run:
On average, Each friend has seen 21.4 of the 30 movies.
The most popular movies were:
Wall-E (2008)
Minions (2015)
Ratatouille (2007)
Deadpool (2016)
The least popular movies were:
The Incredibles (2004)
The Strangers (2008)
Stalker (1979)
Up (2009)
Thor: Ragnarok (2017)
The highest rated movies were:
Wall-E (2008)
Deadpool (2016)
The lowest rated movies were:
Baywatch (2017)
The Matrix Revolutions (2003)
Submission:
After you have completed this assignment, you should have written a total of two Python programs,
saved as .py files.
Please ensure that your files are named descriptively, with the problem number included, so that your
TA can easily see which program is associated with each problem.
Use the University of Calgary Desire2Learn system (https://d2l.ucalgary.ca) to submit your assignment
work online. Log in using your UofC eID and password, then find our course, cpsc 231 l01 and l02, in the
list. Then navigate to Assessments -> Dropbox Folders, and find the folder for Assignment #2 here.
Collaboration
Discussing the assignment requirements with others is a reasonable thing to do, and an excellent way to
learn. However, the work you hand-in must ultimately be your work. This is essential for you to benefit
from the learning experience, and for the instructors and TAs to grade you fairly. Handing in work that is
not your original work, but is represented as such, is plagiarism and academic misconduct. Penalties for
academic misconduct are outlined in the university calendar.
Here are some tips to avoid plagiarism in your programming assignments.
1. Cite all sources of code that you hand-in that are not your original work. You can put the citation
into comments in your program. For example, if you find and use code found on a web site, include
a comment that says, for example:
# the following code is from
https://www.quackit.com/python/tutorial/python_hello_world.cfm.
Use the complete URL so that the marker can check the source.
2. Citing sources avoids accusations of plagiarism and penalties for academic misconduct. However,
you may still get a low grade if you submit code that is not primarily developed by yourself.
3. Discuss and share ideas with other programmers as much as you like, but make sure that when you
write your code that it is your own. A good rule of thumb is to wait 20 minutes after talking with
somebody before writing your code. If you find yourself exchanging code by electronic means,
writing code while sitting and discussing with a fellow student, typing what you see on another
person’s console, then you can be sure that “your” code is not substantially your own, and your
sources must then be cited to avoid plagiarism.
4. Collaborative coding is strictly prohibited. Your assignment submission must be strictly your code.
Discussing anything beyond assignment requirements and ideas is a strictly forbidden form of
collaboration. This includes sharing code, discussing code itself, or modeling code after another
student’s algorithm. You cannot use (even with citation) another student’s code.
5. We will be looking for plagiarism in all code submissions, possibly using automated software
designed for the task. For example, see Measures of Software Similarity (MOSS –
https://theory.stanford.edu/~aiken/moss/).
Remember, if you are having trouble with an assignment, it is always better to go to your TA and/or
instructor to get help, than it is to plagiarize.
Credits:
A few problems were derived from problems originally posted by Prof. Sonny Chen from University of
Calgary.
Grading:
There are total 16 marks for this assignment. If you have completed all the problems, you would get 16
marks.
CPSC 231 Assignments 03 Hangman
Hangman is a classic two-player guessing game, played on pencil and paper that most of us probably
learned in elementary school. One player thinks of a “secret” word, and the other player’s goal is to try
to determine the secret word by guessing its letters one at a time.
Your main objective in this assignment is to write a computer program that will play a game of Hangman
with you. Your program will come up with the secret word and keep track of your guesses, and you, or
anyone playing your game on the computer, will be the one guessing the word.
The rules for our game of Hangman are as follows. The computer will first choose a random secret word
that is at least four letters long from a lexicon (A lexicon is like a dictionary, but without definitions for
the words) of the 4000 most frequently used English words. It shows the word first as blanks
(underscores or dashes), with one blank for each letter of the word. Then play proceeds as follows:
1. The player chooses a letter of the alphabet and indicates it to the computer as his or her guess.
a. If the secret word contains the letter, all occurrences of the letter in the word are
revealed.
b. Otherwise, the letter is written in the list of incorrect guesses
2. If all letters of the secret word are revealed, the game is won. Otherwise, play continues with
step 1.
Our Hangman game will allow the human player a total of eight guesses to determine the secret word.
The game is lost once all the guesses are finished and word is not guessed.
Problem 1: Word LookUp (4 marks)
Write a Python program that will read the provided lexicon file and perform a lookup for a userspecified word in the lexicon. The lexicon file, cpsc231-lexicon.txt, is a text file that contains the 4000
most frequent words used in contemporary American English with one word written per line in order of
their frequency of use. All words are written lowercase except for the word “I”.
Your program should first indicate at what rank position the query word appears in the list, or that the
query word is not contained in the lexicon. Then it should output, in alphabetical order and without
duplicates, a list of all the letters that occur in the query word.
Inputs: A lexicon file name specified as the first command line argument, and a query word as the
second command line argument. For example, you might run your program with the following
invocation:
$ python3 UCID-p1.py cpsc231-lexicon.txt color
Outputs: An indication of what frequency rank the query word appears in the lexicon, or that it was not
found in the provided file. Then print a list of all letters contained within the query word, in alphabetical
order. For example, your program’s output may look like those shown below:
Example Problem 1 output:
According to our lexicon, “color” is the 633rd most common word in contemporary American English.
It contains the following letters: c l o r
Another sample run:
According to our lexicon, “colour” is not in the 4000 most common words of contemporary American
English.
It contains the following letters: c l o r u
Problem 2: Console Hangman (10 marks)
Your goal is to create an interactive game of Hangman that can be played entirely through the console
window. Your program will play the role of “executioner”, selecting the secret word, keeping track of
letter guesses, and detecting when the game is won or lost.
Since this is a console version of the game, so it will suffice to keep track of the number of guesses
remaining before the game is lost. At minimum, your program must be able to perform the following
functions:
1. Select a random secret word that contains at least four letters from the provided lexicon.
2. Display the number of guesses remaining. The player starts the game with 8 guesses left.
3. Prompt the human player for successive letter guesses through the terminal until the game is
over.
a. If a guess is correct, reveal all occurrences of that letter in the appropriate positions in
the secret word, keeping the other letters hidden as underscore (_) or dash (-)
characters.
b. If the secret word does not contain the letter guessed, add the letter to the list of
incorrect guesses and deduct one from the guesses remaining.
c. If the letter has been guessed before, inform the player and ask for a new guess
4. Detect when the game is either won or lost, display a message accordingly, and reveal the secret
word at the end.
It’s completely up to you to decide how you want to organize your program, but we suggest you try
using top-down design and stepwise refinement to break it up into sub-problems. Identify the tasks that
need to be completed and write functions for them if you can.
Inputs: The name of the lexicon file specified as a command line argument. For example, you may run
your program as follows:
$ python3 UCID-p2.py cpsc231-lexicon.txt
Outputs: A guess-by-guess transcript of the game unfolding as you play Console Hangman with your
computer program.
Example Problem 3 output:
Welcome to CPSC 231 Console Hangman!
The secret word looks like: _ _ _ _ _ _ _
You have 8 guesses remaining.
What’s your next guess? e
Nice guess!
The secret word looks like: _ _ _ _ _ _ e
You have 8 guesses remaining.
What’s your next guess? a
Sorry, there is no “a”.
The secret word looks like: _ _ _ _ _ _ e
Your bad guesses so far: a
You have 7 guesses remaining.
What’s your next guess? o
Nice guess!
The secret word looks like: _ o _ _ _ _ e
Your bad guesses so far: a
You have 7 guesses remaining.
What’s your next guess? t
Sorry, there is no “t”.
The secret word looks like: _ o _ _ _ _ e
Your bad guesses so far: a t
You have 6 guesses remaining.
What’s your next guess? u
Nice guess!
The secret word looks like: _o_ _ u _ e
Your bad guesses so far: a t
You have 6 guesses remaining.
What’s your next guess? n
Nice guess!
The secret word looks like: _on_u_e
Your bad guesses so far: a t
You have 6 guesses remaining.
What’s your next guess? f
Nice guess!
The secret word looks like: _onfu_e
Your bad guesses so far: a t
You have 6 guesses remaining.
What’s your next guess? s
Nice guess!
The secret word looks like: _onfuse
Your bad guesses so far: a t
You have 6 guesses remaining.
What’s your next guess? c
Nice guess! Congratulations!
You guessed the secret word: confuse
Submission:
After you have completed this assignment, you should have written a total of two Python programs,
saved as .py files.
Please ensure that your files are named descriptively (e.g. UCID-P1.py), so that your TA can easily see
which program is associated with each problem.
Use the University of Calgary Desire2Learn system (https://d2l.ucalgary.ca) to submit your assignment
work online. Log in using your UofC eID and password, then find our course, cpsc 231 l01 and l02, in the
list. Then navigate to Assessments -> Dropbox Folders, and find the folder for Assignment #3 here.
Collaboration
Discussing the assignment requirements with others is a reasonable thing to do, and an excellent way to
learn. However, the work you hand-in must ultimately be your work. This is essential for you to benefit
from the learning experience, and for the instructors and TAs to grade you fairly. Handing in work that is
not your original work, but is represented as such, is plagiarism and academic misconduct. Penalties for
academic misconduct are outlined in the university calendar.
Here are some tips to avoid plagiarism in your programming assignments.
1. Cite all sources of code that you hand-in that are not your original work. You can put the citation
into comments in your program. For example, if you find and use code found on a web site, include
a comment that says, for example:
# the following code is from
https://www.quackit.com/python/tutorial/python_hello_world.cfm.
Use the complete URL so that the marker can check the source.
2. Citing sources avoids accusations of plagiarism and penalties for academic misconduct. However,
you may still get a low grade if you submit code that is not primarily developed by yourself.
3. Discuss and share ideas with other programmers as much as you like, but make sure that when you
write your code that it is your own. A good rule of thumb is to wait 20 minutes after talking with
somebody before writing your code. If you find yourself exchanging code by electronic means,
writing code while sitting and discussing with a fellow student, typing what you see on another
person’s console, then you can be sure that “your” code is not substantially your own, and your
sources must then be cited to avoid plagiarism.
4. Collaborative coding is strictly prohibited. Your assignment submission must be strictly your code.
Discussing anything beyond assignment requirements and ideas is a strictly forbidden form of
collaboration. This includes sharing code, discussing code itself, or modeling code after another
student’s algorithm. You cannot use (even with citation) another student’s code.
5. We will be looking for plagiarism in all code submissions, possibly using automated software
designed for the task. For example, see Measures of Software Similarity (MOSS –
https://theory.stanford.edu/~aiken/moss/).
Remember, if you are having trouble with an assignment, it is always better to go to your TA and/or
instructor to get help, than it is to plagiarize.
Credits:
The idea of the Hangman game as an assignment was shamelessly borrowed from the CS 106a course
taught at Stanford University. It was likely Eric Roberts who introduced this assignment there. The
lexicon of most frequently used words in contemporary American English was obtained from
https://www.wordfrequency.info.
The assignment description is taken from a course offered by Dr. Sonny Chen.
Grading:
There are total 14 marks for this assignment. If you have completed all the problems, you would get 14
marks.
CPSC 231 Assignment 04 Analytical Geometry
This assignment has one part: Part I – Analytical geometry (14 marks) Part I – Analytical Geometry You will create a small graphical Python 3 program that draws a few shapes using the turtle library and information taken from the user. You will also use the Python math library to do calculations. Your TA will introduce you to these libraries and their intricate details during tutorials. You can start learning about turtle graphics here. You can also find documentation about Turtle graphics here. The assignment generally revises your concepts regarding constants, variables, expressions, as well as importing and using libraries, getting input from users, casting variables to different types, problemsolving. It will also help you to develop an interactive application using graphics and drawing in a coordinate system. Your program will present an 800×600 pixel window with (0,0) being the bottom left corner point and (800,600) being the top right corner point. Within this coordinate system, your program will draw an x and y axes that identify the centre of the window. Your program will prompt the user for values that define a circle and a line in this coordinate system and draw them. Finally, your program will perform calculations to determine whether the line and circle intersect. You can think of this assignment as a series of stages to complete. First, you import some libraries. Next, you define constants (all upper case). Some of these are obvious like the window size. You will likely identify more constants as you write the rest of the program. Then setup your window and carry out the rest of the assignment requirements. This code should get you started. With your window ready, draw your axis. This axis should cross through the middle point of the screen, i.e. (400,300). Remember to use your constants here and later on. Then prompt the user for input, cast it to the proper type, and store it in variables. Remember to use descriptive variable names. Draw your circle and your line. Calculate the number of intersection points between the circle and line. Then, produce a conditional statement that lets you display a message indicating the number of intersection points to the user. Drawing in Turtle: You can imagine the turtle drawing system as a turtle carrying a pen. The turtle starts at some default location within the window and has its pen pressed down and ready to draw. To draw a line from the turtle’s location to a new point, tell the turtle to move to the new location. It will drag the pen along as it moves to the new location effectively drawing a line. If you tell the turtle to lift up the pen then tell it to move to a new point, it will go to this new point without drawing the line. For this assignment, you must know how to position the turtle in a specific location (a point in the coordinate system, also known as pixel location), how to start and stop drawing, and how to change drawing colors. Draw the axis in black, the circle in red, the line in blue, and the intersect/text in green. You can use the circle command to draw the circle. The circle command, by default, draws circles from the middle of the bottom edge. Therefore, to draw a circle around a centre point, you must determine where the proper start location is (hint: adjust from the centre using the radius). Getting Input: Read the input from the user from command line (no command line argument). Display a prompt in the terminal window with a print statement, or by providing a parameter to the input function. Note that the user will enter their input in the terminal window, not in the graphics window. You will need to prompt for 7 and only 7 inputs. You will need an integer xc and integer yc for the centre (xc,yc) of the circle and a float r for the radius. You will need an integer x1 and integer y1 for the start (x1,y1) of the line and an integer x2 and integer y2 for the end (x2,y2) of the line. These are pixel locations in the window. A circle with middle (400,300) and radius 300 would be drawn in the middle of the window touching the top and bottom of the window. Analytical Geometry: We have 7 values that you should have stored as input: xc, yc, r, x1, y1, x2, y2. We will use these in our calculations. We will make use of 3 intermediate calculations to determine intersections. These fulfill the parameters of the quadratic We can solve this quadratic to determine intersections alpha ( ). However, we will not do this directly, but instead using the quadratic formula. Before we jump directly to using this to calculate alpha ( ) we can look at the value under the root to determine the number of intersections. Note that an alpha value greater than 1 or less than 0, indicates that the intersection occurs outside the end points of the line segment. These intersections should not be drawn. If then there are no intersections. We cannot use the imaginary number from square rooting a negative number in this situation. If then there is 1 intersection. The square root value is the root of 0. The result of adding and subtracting 0 is the same number. So there is only one result to the alpha. If then there are 2 intersections. Since the value is positive when add or subtract the result of rooting it, we will produce two different alphas; one for each intersection. After making a decision based on this value, we need to draw the result of the intersections. If there are no intersections, you should draw the words “No Intersect!” in the centre of the window. If there is one, or two intersections, you will should then calculate the alpha of the quadratic formula for each. With each alpha, we can calculate the coordinates of the intersection point using the following two formulas With this coordinate, you should draw a circle around this location. Using a radius of 5 (constant) is a good size. In effect the alpha is a ratio spot along the line between (x1,y1) and (x2,y2). An alpha of 0 is the point (y1,x1) and an alpha of one is the point (x2,y2). One final and very important point: although we may calculate an alpha that indicates that there is an intersection, this intersection may not be between the two points of the line. The calculation we have used so far also gives us intersections if line continue into infinity off either end. To ensure we only plot intersections between the two points we need to make sure that the alpha greater than or equal to zero and less than or equal to 1. Additional Specifications: Ensure that your program meets all the following requirements: You should have the class, your name, your tutorial, your student id, the date, and a description at the top of your code file in comments. Marks are given for these. The code file should be .py Import the necessary libraries Use constants appropriately. Use descriptive naming of variables. The use of variables that follow the math descriptions given are fine for those purposes. Draw your axis black, your circle red, your line blue, and your intersection circles/text green. Use descriptive prompts for input and cast input to the indicated types. Use in-line comments to indicate blocks of code and describe decisions or complex expressions. You do not have to worry about making sure input is of the correct type. Your program should crash if the values given cannot be cast from strings into the request types. So don’t worry about input validation. Example: Example input in the terminal window may looks as follow: Enter circle x coordinate: 400 Enter circle y coordinate:300 Enter radius of circle:200 Enter line start x coordinate:100 Enter line start y coordinate:200 Enter line end x coordinate:700 Enter line end y coordinate: 200 The output looks like: Submission: After you have completed this assignment, you should have written a total of one Python programs, saved as .py files. Use the University of Calgary Desire2Learn system (https://d2l.ucalgary.ca) to submit your assignment work online. Log in using your UofC eID and password and find our course, CPSC 231 L01 and L02, in the list. Then navigate to Assessments -> Dropbox Folders, and find the folder for Assignment #4 here. Collaboration Discussing the assignment requirements with others is a reasonable thing to do, and an excellent way to learn. However, the work you hand-in must ultimately be your work. This is essential for you to benefit from the learning experience, and for the instructors and TAs to grade you fairly. Handing in work that is not your original work, but is represented as such, is plagiarism and academic misconduct. Penalties for academic misconduct are outlined in the university calendar. Here are some tips to avoid plagiarism in your programming assignments. 1. Cite all sources of code that you hand-in that are not your original work. You can put the citation into comments in your program. For example, if you find and use code found on a web site, include a comment that says, for example: # the following code is from https://www.quackit.com/python/tutorial/python_hello_world.cfm. Use the complete URL so that the marker can check the source. 2. Citing sources avoids accusations of plagiarism and penalties for academic misconduct. However, you may still get a low grade if you submit code that is not primarily developed by yourself. 3. Discuss and share ideas with other programmers as much as you like, but make sure that when you write your code that it is your own. A good rule of thumb is to wait 20 minutes after talking with somebody before writing your code. If you find yourself exchanging code by electronic means, writing code while sitting and discussing with a fellow student, typing what you see on another person’s console, then you can be sure that “your” code is not substantially your own, and your sources must then be cited to avoid plagiarism. 4. Collaborative coding is strictly prohibited. Your assignment submission must be strictly your code. Discussing anything beyond assignment requirements and ideas is a strictly forbidden form of collaboration. This includes sharing code, discussing code itself, or modeling code after another student’s algorithm. You cannot use (even with citation) another student’s code. 5. We will be looking for plagiarism in all code submissions, possibly using automated software designed for the task. For example, see Measures of Software Similarity (MOSS – https://theory.stanford.edu/~aiken/moss/). Remember, if you are having trouble with an assignment, it is always better to go to your TA and/or instructor to get help, than it is to plagiarize. Grading for Part I: 14 – Fulfilled assignment specification and solved the problems completely 12 – Appears to fulfill assignment part 1 spec 9 – Code has part of intersection work done, but obvious errors/incomplete 6 – Code draws axis, gets input, draws circle/line 3 – Code draws axis and gets input 1 – 2 Syntax error or barely written any code. Credits: A few problems were derived from problems originally posted by Dr. Jonathan Hudson from University of Calgary.
CPSC 231 Assignments 05 Object Oriented Programming
Problem 1: Object Oriented Programming (Total Marks: 7)
For this problem, you will create a class. You can create any class (For example Fraction, Car, Complex
numbers). Once you have created class answer the following questions.
What are the attributes (or fields) of the class?
What is the constructor of the class?
What are the methods inside the class?
What is/are the variable that has class level scope?
What is/are the variables that have object level scope?
What is the name of the object?
You should create one class that answer each of the above questions. You can write your answer in the
submitted python file
Grading:
Class Created: (1 marks)
Answer questions: (1 * 6 = 6)
Problem 2: Recursion (Total Marks: 3)
Write a recursive function sumRecursive that takes a list of integers as an input, and calculates the sum
of all its values. For example: If the list has elements [1, 2, 3, 4], it will return 10.
You should use recursion to solve this. Do not use loops.
Submission:
After you have completed this assignment, you should have written a total of two Python programs,
saved as .py files. Write your answers of the questions asked in this assignment on the python files.
Please ensure that your files are named descriptively (e.g. UCID-P1.py), so that your TA can easily see
which program is associated with each problem.
Use the University of Calgary Desire2Learn system (https://d2l.ucalgary.ca) to submit your assignment
work online. Log in using your UofC eID and password, then find our course, cpsc 231 l01 and l02, in the
list. Then navigate to Assessments -> Dropbox Folders, and find the folder for Assignment #5 here.
Collaboration
Discussing the assignment requirements with others is a reasonable thing to do, and an excellent way to
learn. However, the work you hand-in must ultimately be your work. This is essential for you to benefit
from the learning experience, and for the instructors and TAs to grade you fairly. Handing in work that is
not your original work, but is represented as such, is plagiarism and academic misconduct. Penalties for
academic misconduct are outlined in the university calendar.
Here are some tips to avoid plagiarism in your programming assignments.
1. Cite all sources of code that you hand-in that are not your original work. You can put the citation
into comments in your program. For example, if you find and use code found on a web site, include
a comment that says, for example:
# the following code is from
https://www.quackit.com/python/tutorial/python_hello_world.cfm.
Use the complete URL so that the marker can check the source.
2. Citing sources avoids accusations of plagiarism and penalties for academic misconduct. However,
you may still get a low grade if you submit code that is not primarily developed by yourself.
3. Discuss and share ideas with other programmers as much as you like, but make sure that when you
write your code that it is your own. A good rule of thumb is to wait 20 minutes after talking with
somebody before writing your code. If you find yourself exchanging code by electronic means,
writing code while sitting and discussing with a fellow student, typing what you see on another
person’s console, then you can be sure that “your” code is not substantially your own, and your
sources must then be cited to avoid plagiarism.
4. Collaborative coding is strictly prohibited. Your assignment submission must be strictly your code.
Discussing anything beyond assignment requirements and ideas is a strictly forbidden form of
collaboration. This includes sharing code, discussing code itself, or modeling code after another
student’s algorithm. You cannot use (even with citation) another student’s code.
5. We will be looking for plagiarism in all code submissions, possibly using automated software
designed for the task. For example, see Measures of Software Similarity (MOSS –
https://theory.stanford.edu/~aiken/moss/).
Remember, if you are having trouble with an assignment, it is always better to go to your TA and/or
instructor to get help, than it is to plagiarize.
Grading:
There are total 10 marks for this assignment. If you have completed all the problems, you would get 10
marks.