Great Deal! Get Instant $10 FREE in Account on First Order + 10% Cashback on Every Order Order Now

Microsoft Word - Decision Exercises.docx Decision Exercises #1 More BMI (10 points) If you completed the BMI exercise in the Basic applications, you could continue expanding that application here. The...

1 answer below »
Microsoft Word - Decision Exercises.docx
Decision Exercises

#1 More BMI (10 points)
If you completed the BMI exercise in the Basic applications, you could continue expanding that
application here. The video sequence added decisions to the logic to provide the user with an
indication of their BMI’s weight status. Again you need to merely follow along with the video
sequence and produce the exact results. The autograder will provide a basic indication if your
code produces the four categories, even if your logic is slightly different from mine.

https:
www.youtube.com/playlist?list=PLgvXUCQxGQrxU5_0KnzFWrAd3xgKx48uW

#2 Animal Classifier (20 points)
When algorithms include decisions, they naturally become more complex to code and also to
test. Part of successfully using decisions means analyzing the appropriate test cases required to
ensure the resulting code indeed works as planned. The following flowchart was proposed as
an algorithm for classifying most animals based on their traits.



Each result in this flowchart (e.g., Reptile, Mammal, Fish…) defines a new test case that needs
you to define the input values that would lead to that scenario.


1 -Test Planning
The flowchart above has many possible outcomes and sets of answer to the questions (i.e.,
inputs) that will result in each outcome. Testing decisions starts by identifying all possible
outcomes and ensuring an input dataset exists to reach each outcome. Use a table like the one
elow to plan out your tests. You can create this table electronically or on paper, you won’t
turn in step 1, but it is a good exercise to plan your testing.

Results Has
Skeleton
Has
Wings
Has
Feathers
Lays
Eggs
Drinks
Milk
Undergoes
Metamorphosis
Has Gills
Insect False False False False False False False



* The number of rows provided does not indicate the number of test cases expected

2 – Fill the data for automated testing
This step translates the inputs and expected results from the table above into your Python
code. At the top of the animalClassifier.py file is a list of variables that define the logic’s result
(e.g., AMPHIBIAN = “Amphibian”). Below these variables is a Python list (a data structure we
will practice using in a few weeks) that defines the test cases. Your data from above will drive
the testing!

The table contains each of the possible outputs from the diagram above. As the code stands
now, every input is set to False. Your table above should indicate which of the values should
instead be True to determine if the animal is an insect, bird, or whatnot. Very carefully modify
the appropriate values from False to True (it must be a capital T). If you accidentally delete a
comma (,) or square
acket ([]), the code will
eak.

3 – The poor miscategorized platypus
Sometimes on a software project, someone will provide you with exact rules they expect you to
code, like the flowchart above. The flowchart above, though, has at least one logical problem!
Think of the humble platypus. It has a skeleton, and its young drinks milk, yet it also lays eggs,
yet the logic does not accurately report the platypus as a mammal (Can you predict what it
would return?). You can help classify the platypus and earn some points by improving the logic.

You do not need to add the platypus test case to your table above, I have a separate test case
for that already!



#3 States of Matter (15 points)
In basic science, we learn that matter has three states – solid, liquid, and gas. One easy
example of this concept is how water transitions between ice, its fluid state, and steam as it
changes temperature, but there is some transition space between these temperatures in
physical testing (if you freeze or boil water, it does not suddenly solidify or evaporate). In this
exercise, I have written some code that
attempted to show the transitions
etween these states by having a
threshold in the logic. The hope was to
epresent the continuum between
states with a small temperature
threshold between each state.

In the na
ow band of 3 degrees above
and below each temperature (i.e., the
threshold), the app should report the
transition state rather than the ‘main
three’, but mine does not work
co
ectly.

1 – Fix my
oken code
Your task is to fix my code so that it passes each test case. The file comes with a built-in tester,
so your main goal is to make those failures turn into successes. Start by identifying the failing
test cases and their reason for failing, then modify the code to the desired outcome.

2 – Try your own version of the logic
A programmer can write code to realize a set of rules in many ways. To practice your skills at
writing decision logic, I provided a second method named determineStateAlternative().
For more points, write your version of this decision logic from scratch (i.e., don’t copy mine)
within this method such that it also passes the test cases.


#4 Rock, Paper, Scissors (30 points)
The game Rock, Paper, Scissors presents two players with a simple choice that could result in
either player winning or a tie. The rules of the game are easy to represent as a picture, but the
picture does not translate directly into an algorithm using decisions

I started a Rock, Paper, Scissors game (rps.py)
ut have not yet coded several critical decisions
that you must implement to finish the game.
Download the code and start by running it. The
provided code includes test cases followed by a
user interface. Work through the code (top-
down) and add one piece at a time. Remember
to “code small”, ensuring your code is always
unning without e
ors. Do not attempt to code
all steps before testing! You will need to add logic at the following places:
1. To play against the computer, we need to select a choice the computer player makes
andomly. The function getComputerMove() generates a random number (0, 1, or
2) into the variable move. Add logic here to return one of the constants ROCK, PAPER,
or SCISSORS as the computer’s move using a statement such as
return ROCK
2. To get the player’s move, we need to ensure their input is one of the valid moves. The
getPlayerMove() function defines the iteration logic for you and prompts the user for
their input, storing the value in a variable move. Add logic to this method to ensure the
user has typed in either “rock” (or “r”), “paper” (or “p”), or “scissors” (or “s”) and return
the appropriate constant value as described above. If the user does not enter one of
the three recognizable moves, print a line that tells them the valid options they can
enter.
3. Select the winner – your first task is to create a series of decisions within the function
winner(player1Move, player2Move)that realizes the game’s rules as dictated
in the picture above. Your logic must return the winning player number (1 or 2) or 0 if it
was a tie. The function parameters are set to one of the constant variables (ROCK,
PAPER, SCISSORS) to ensure your logic matches the valid input options. The
automated test cases will help you to know when you have completed this function
4. The player needs to know the result of the game, and we need a decision to tell them.
Modify the playGameWithUser() function to report the result and keep the score.
Update the variable reportResult to one of the three constant values
(RESULT_TIE, RESULT_P1, or RESULT_P2). Then update the three variables that
track each outcome’s count using the variables provided (player1Wins,
player2Wins, and ties).



#5 Coin Meter Classifier (30 points)
A toll booth system uses high-tech sensors to determine the diameter and weight of coins
dropped into a basket to pay for tolls. The file CoinMeter.py has started the code for determining
which type of coin was deposited by defining the known weights and diameters for pennies,
nickels, dimes, and quarters for the most common US cu
ency values. Since coins may not
conform exactly to these measures, the system allows for a threshold for the weight and
diameter, also provided as a constant in the code. Your code should check if an incoming coin is
within this threshold. If the weight threshold is 3%, a coin weighs between 97% and 103% of the
target weight of a penny, for example, to be considered a penny. A coin must be within the
thresholds of both the diameter and weight.

Individual determinination

The file coinMeter.py includes a constant value of each coin type and the expected weight and
diameter for each coin. You must complete the functions:
 isAPenny
 isANickel
 isADime
 isAQuarter

The caller to each function provides the weight and diameter of a candidate coin. Your code
should check if the values fall within the threshold of that coin’s values and return True if it does
or False if it does not.

You can also complete the classifyCoin function, which identifies which type of coin a caller
presented (PENNY, NICKEL, DIME, QUARTER, or UNKNOWN). The logic should checks if the
provided weight and height fall into any of the four mutually exclusive coin thresholds (e.g., you
Answered 2 days After Apr 21, 2021

Solution

Sandeep Kumar answered on Apr 23 2021
152 Votes
DT/.vscode/settings.json
{
"python.pythonPath": "C:\\Users\\nax\\AppData\\Local\\Programs\\Python\\Python39\\python.exe"
}
DT/animalclassifier-eurjlcjv.py
# From: https:
www.researchgate.net/publication/315146311_ANIMAL_CLASSIFICATION_IN_WILDLIFE_THROUGH_IMAGES_USING_STATISTICAL_METHODS_AND_DECISION_TREE
AMPHIBIAN = "Amphibian"
BIRD = "Bird"
FISH = "Fish"
INSECT = "Insect"
MAMMAL = "Mammal"
REPTILE = "Reptile"
#....................... 2 ..............................
# Modify the following data structure to match your defined test cases.
# The inputs to the test cases are next represented by Boolean values
# (must be True and False, case sensitive)
# that align to one of the input values in the following order:
# skeleton, wings, feathers, eggs, milk, meta, gills
TEST_CASES = [[INSECT , [False, False, False, False, False, False, False]],
[BIRD , [True, True, True, True, False, False, False]],
[MAMMAL , [True, True, False, True, True, False, False]],
[MAMMAL , [True, True, False, True, True, False, False]],
[AMPHIBIAN , [True, False, False, True, False, True, False]],
[REPTILE , [True, False, False, True, False, False, False]],
[FISH , [True, False, False, True, False, False, True]]]
# The following code, AnimalClassifier, is a class. It helps to group data
# and is a vital part of Object-Oriented programming. We won't do a lot with
# classes in this course, but they are important later. For now, it is just a way
# of grouping the various properties to classify an animal.
class AnimalClassifier:
hasSkeleton = False
hasWings = False
hasFeathers = False
laysEggs = False
drinksMilk = False
undergoesMetamorphasis = False
hasGills = False
#................... 3 ..........................................
def classify(self):
'''
Use the attributes of the Animal Classifier task to determine the animal
self - an grouping of the AnimalClassifier attributes
returns the class of the animal with those properties
'''
if self.hasSkeleton:
if self.hasWings:
if self.hasFeathers:
return BIRD
else:
return MAMMAL
else:
if not self.laysEggs:
if self.drinksMilk:
return MAMMAL
if self.undergoesMetamorphasis:
return AMPHIBIAN
else:
if self.hasGills:
return FISH
if self.drinksMilk:
return MAMMAL
else:
return REPTILE

else:
return INSECT
#==================================================================
# Everything below here is tester code DO NOT MODIFY
def __init__(self, skeleton, wings, feathers, eggs, milk, meta, gills):
'''
Initializes the class with the provided values
'''
self.hasSkeleton = skeleton
self.hasWings = wings
self.hasFeathers = feathers
self.laysEggs = eggs
self.drinksMilk = milk
self.hasGills = gills
self.undergoesMetamorphasis = meta
def getBoolean(prompt):
'''
Prompt the user a question that is answered true or false
prompt - the text to ask the use
returns True or False as specified by the use
'''
while True:
answer = input(prompt).lower()
if (answer == "true" or answer == 't'):
return True
elif (answer == "false" or answer == 'f'):
return False
else:
print("You must answer True (t) or False (f)")
def presentToUser():
'''
Ask the user a series of questions that help to classify the animal and
then show them the result
'''
hasSkeleton = getBoolean("Does your animal have a skeleton:")
hasWings = getBoolean("Does it have wings:")
hasFeathers = getBoolean("Does it have feathers:")
laysEggs = getBoolean("Does it lay eggs:")
drinksMilk = getBoolean("Does its young drink milk:")
undergoesMetamorphasis = getBoolean("Does it undergo a metamorphasis:")
hasGills = getBoolean("Does it have gills:")

classifier = AnimalClassifier(hasSkeleton, hasWings, hasFeathers, laysEggs,
drinksMilk, undergoesMetamorphasis, hasGills)
print("Your animal is a", classifier.classify())
def testClassifier():
'''
Test the classify logic using the test cases defined above
'''
success = True
for testCase in TEST_CASES:
answer = testCase[0]
parameters = testCase[1]
test = AnimalClassifier(parameters[0], parameters[1], parameters[2], parameters[3],
parameters[4], parameters[5], parameters[6])
result = test.classify()
if result != answer:
success = False
print ("Test case Failed: I expected", answer, "but got", result, "for the inputs", parameters)
return success
def testPlatypus():
success = True
answer = MAMMAL
parameters = [True, False, False, True, True, False, False]
test = AnimalClassifier(parameters[0], parameters[1], parameters[2], parameters[3],
parameters[4], parameters[5], parameters[6])
result = test.classify()
if result != answer:
success = False
print ("Platypus Test case Failed: I expected", answer, "but got", result, "for the inputs", parameters)
return success
if __name__ == '__main__':
if testClassifier() and testPlatypus():
print("All test cases passed!")
print(".................")
print("Classify your own animal now...")
presentToUser()
DT/coinmeter-qmgjurkp.py
PENNY = 0
NICKEL = 1
DIME = 2
QUARTER = 3
UNKNOWN = 4
    
PENNY_WEIGHT = 2.5
NICKEL_WEIGHT = 5.0
DIME_WEIGHT = 2.268
QUARTER_WEIGHT = 5.67
PENNY_DIAMETER = 0.75
NICKEL_DIAMETER = 0.835
DIME_DIAMETER = 0.705
QUARTER_DIAMETER = 0.955
WEIGHT_THRESHOLD = 0.03
DIAMETER_THRESHOLD = 0.01
def isAPenny(weight, diameter):
'''
Checks to see if the coin is a penny
weight - the weight of cu
ent coin to evaluate
diameter - the diameter of cu
ent coin to evaluate
returns True if coin is a penny
'''
if ((0.97*PENNY_WEIGHT <= weight and weight <= 1.03*PENNY_WEIGHT) and (0.97*PENNY_DIAMETER <= diameter and diameter <= 1.03*PENNY_DIAMETER)):
return True
else:
return False
def isANickel(weight, diameter):
'''
Checks to see if the coin is a nickel
weight - the weight of cu
ent coin to evaluate
diameter - the diameter of cu
ent coin to evaluate
returns True if coin is a nickel
'''
if ((0.97*NICKEL_WEIGHT <= weight and weight <= 1.03*NICKEL_WEIGHT) and (0.97*NICKEL_DIAMETER <= diameter and diameter <= 1.03*NICKEL_DIAMETER)):
return True
else:
return False
def isADime(weight, diameter):
'''
Checks to see if the coin is a dime
weight - the weight of cu
ent coin to evaluate
diameter - the diameter of cu
ent coin to evaluate
returns True if coin is a dime
'''
if ((0.97*DIME_WEIGHT <= weight and weight<= 1.03*DIME_WEIGHT ) and ( 0.97*DIME_DIAMETER <= diameter and diameter <= 1.03*DIME_DIAMETER)):
return True
else:
return False
def isAQuarter(weight, diameter):
'''
Checks to see if the coin is a quarte
weight - the weight of cu
ent coin to evaluate
diameter - the diameter of cu
ent coin to evaluate
returns True if coin is a quarte
'''
if ((0.97*QUARTER_WEIGHT <= weight and weight<= 1.03*QUARTER_WEIGHT ) and (0.97*QUARTER_DIAMETER <= diameter and diameter <= 1.03*QUARTER_DIAMETER)):
return True
else:
return False

def clasifyCoin(weight, diameter):
'''
Determine what type of coin was received based on the weight and diamete
weight - the weight of cu
ent coin to evaluate
diameter - the diameter of cu
ent coin to evaluate
returns One of the coin types listed above, or UNKNOWN
'''
if isAQuarter(weight, diameter)==True:
return 3
elif isADime(weight, diameter)==True:
return 2
elif isANickel(weight, diameter)==True:
return 1
elif isAPenny(weight, diameter)==True:
return 0
else:
return 4

#==================================================================
# Everything below here is tester code DO NOT MODIFY
TEST_DATA = [[2.5, 0.75, PENNY],
[5.0, 0.835, NICKEL],
[2.268, 0.705, DIME],
[5.67, 0.955, QUARTER],
[5.67, 0.75, UNKNOWN],
[5.1, 0.83, NICKEL],
[5.7, 0.95, QUARTER],
[2.4, 0.705, UNKNOWN]]
# Test the coin functions
def coinTester():
passed = True
#Penny Tests
weight = TEST_DATA[0][0]
diameter = TEST_DATA[0][1]
if not isAPenny(weight, diameter):
passed = False
print("isAPenny Fail: got False expected True",
"for the values weight =", weight, "and diameter =", diameter)
weight = TEST_DATA[1][0]
diameter = TEST_DATA[1][1]
if isAPenny(weight, diameter):
passed = False
print("isAPenny Fail: got True expected False",
"for the values weight =", weight, "and diameter =", diameter)
#Nickel Tests
weight = TEST_DATA[1][0]
diameter = TEST_DATA[1][1]
if not isANickel(weight, diameter):
passed = False
print("isANickel Fail: got False expected True",
"for the values weight =", weight, "and diameter =", diameter)
weight = TEST_DATA[2][0]
diameter = TEST_DATA[2][1]
if isANickel(weight, diameter):
passed = False
print("isANickel Fail: got True expected False",
"for the values weight =", weight, "and diameter =", diameter)

#Dime tests
weight = TEST_DATA[2][0]
diameter = TEST_DATA[2][1]
if not isADime(weight, diameter):
passed = False
print("isADime Fail: got False expected True",
"for the values weight =", weight, "and diameter =", diameter)
weight = TEST_DATA[3][0]
diameter = TEST_DATA[3][1]
if isADime(weight, diameter):
passed = False
print("isADime Fail: got True expected False",
"for the values weight =", weight, "and diameter =", diameter)
#Quarter Tests
weight = TEST_DATA[3][0]
diameter = TEST_DATA[3][1]
if not isAQuarter(weight, diameter):
passed = False
print("isAQuarter Fail: got False expected True",
"for the values weight =", weight, "and diameter =", diameter)
weight = TEST_DATA[4][0]
diameter = TEST_DATA[4][1]
if isAQuarter(weight, diameter):
passed = False
print("isAQuarter Fail: got True expected False",
"for the values weight =", weight, "and diameter =", diameter)

for testData in TEST_DATA:
weight = testData[0]
diameter = testData[1]
expected = testData[2]
answer = clasifyCoin(weight, diameter)
if answer != expected:
passed = False
print("Fail: got", answer, "expected", expected,
"for the values weight =", weight, "and diameter =", diameter)
if passed:
print("All coin tests passed")
# Only run this code below if this is called as the main, not imported
if __name__ == '__main__':
coinTester()
DT/graphics-ggngv2j4.py
# graphics.py
"""Simple object oriented graphics li
ary
The li
ary is designed to make it very easy for novice programmers to
experiment with computer graphics in an object oriented fashion. It is
written by John Zelle for use with the book "Python Programming: An
Introduction to Computer Science" (Franklin, Beedle & Associates).
LICENSE: This is open-source software released under the terms of the
GPL (http:
www.gnu.org/licenses/gpl.html).
PLATFORMS: The package is a wrapper around Tkinter and should run on
any platform where Tkinter is available.
INSTALLATION: Put this file somewhere where Python can see it.
OVERVIEW: There are two kinds of objects in the li
ary. The GraphWin
class implements a window where drawing can be done and various
GraphicsObjects are provided that can be drawn into a GraphWin. As a
simple example, here is a complete program to draw a circle of radius
10 centered in a 100x100 window:
--------------------------------------------------------------------
from graphics import *
def main():
win = GraphWin("My Circle", 100, 100)
c = Circle(Point(50,50), 10)
c.draw(win)
win.getMouse() # Pause to view result
win.close() # Close window when done
main()
--------------------------------------------------------------------
GraphWin objects support coordinate transformation through the
setCoords method and mouse and keyboard interaction methods.
The li
ary provides the following graphical objects:
Point
Line
Circle
Oval
Rectangle
Polygon
Text
Entry (for text-based input)
Image
Various attributes of graphical objects can be set such as
outline-color, fill-color and line-width. Graphical objects also
support moving and hiding for animation effects.
The li
ary also provides a very simple class for pixel-based image
manipulation, Pixmap. A pixmap can be loaded from a file and displayed
using an Image object. Both getPixel and setPixel methods are provided
for manipulating the image.
DOCUMENTATION: For complete documentation, see Chapter 4 of "Python
Programming: An Introduction to Computer Science" by John Zelle,
published by Franklin, Beedle & Associates. Also see
http:
mcsp.wartburg.edu/zelle/python for a quick reference"""
__version__ = "5.0"
# Version 5 8/26/2016
# * update at bottom to fix MacOS issue causing askopenfile() to hang
# * update takes an optional parameter specifying update rate
# * Entry objects get focus when drawn
# * __repr_ for all objects
# * fixed offset problem in window, made canvas borderless
# Version 4.3 4/25/2014
# * Fixed Image getPixel to work with Python 3.4, TK 8.6 (tuple type handling)
# * Added interactive keyboard input (getKey and checkKey) to GraphWin
# * Modified setCoords to cause redraw of cu
ent objects, thus
# changing the view. This supports scrolling around via setCoords.
#
# Version 4.2 5/26/2011
# * Modified Image to allow multiple undraws like other GraphicsObjects
# Version 4.1 12/29/2009
# * Merged Pixmap and Image class. Old Pixmap removed, use Image.
# Version 4.0.1 10/08/2009
# * Modified the autoflush on GraphWin to default to True
# * Autoflush check on close, setBackground
# * Fixed getMouse to flush pending clicks at entry
# Version 4.0 08/2009
# * Reverted to non-threaded version. The advantages (robustness,
# efficiency, ability to use with other Tk code, etc.)...
SOLUTION.PDF

Answer To This Question Is Available To Download

Related Questions & Answers

More Questions »

Submit New Assignment

Copy and Paste Your Assignment Here