Fall 20151 Week 7 CSCI141 Scott C Johnson Say we go to the bank to cash our paycheck We ask the teller for the fewest bills and coins as possible Moments later the teller gives us our money and we leave ID: 786168
Download The PPT/PDF document "Greedy Algorithms and Classes" is the property of its rightful owner. Permission is granted to download and print the materials on this web site for personal, non-commercial use only, and to display it on your personal computer provided you do not modify the materials and that you retain all copyright notices contained in the materials. By downloading content from our website, you accept the terms of this agreement.
Slide1
Greedy Algorithms and Classes
Fall 20151 Week
7
CSCI-141
Scott C. Johnson
Slide2Say we go to the bank to cash our paycheckWe ask the teller for the fewest bills and coins as possible
Moments later the teller gives us our money and we leave
In order to do this request the teller ran an algorithm
Greedy Algorithms
Slide3The teller’s algorithmStarts by choosing the highest bill/coin the teller can
Gets as many of these as possible
Repeats this for each smaller bill/coin until the amount is madeIn computer science we call this a greedy algorithm!
Due to the fact that it chooses what it perceives is the optimal at the time of the choice
Greedy Algorithms
Slide4In this lecture we will make a greedy algorithm that:
Will make change
Can use different regional currencyEach different kind of regional currency will be stored in a fileEach line of the file will represent a single coin denomination, containing a name and value
Greedy Algorithms
Slide5How the “Change Machine” will workPrompts the user for the currency region
Displays the coins for the region and their value
It will sort the coins by value in a listSmallest to largest
Prompt the user for the amount of change to make
If it is possible to make the change it will state it is possible
O
therwise it will state it is not possible
If possible it will next show the resulting coins
Greedy Algorithms
Slide6Show the running program687 using the currency for the United States (“us”)
We can make any amount because we have a penny!
Canada discontinued the pennyTherefore they cannot make 687
Greedy Algorithms
Slide7How can we represent coins in Python?Recall a coin has a name and a value
The solution above showed two different types of things:
A Coin
Name as a string
Value as an integerA C
oinRoll
Coin is an instance of some coin
Quantity of that coin as an integer
Greedy Algorithm
Slide8Can we use a list?
We could have the values of individual coins in a list
dollar = [“dollar-coin”, 100]
print(“Name: “, dollar[0])
Name: dollar-coin
p
rint(“Value: ”, dollar[1])
Value: 100
quarter
=
[“quarter”, 25]
Then in another list store the count for each roll
eightBucks
= [dollar, 8]
print(eightBucks)[[‘dollar-coin’, 100], 8]fiftyCents = [quarter, 2]print(fiftyCents)[[‘quarter’, 25], 2]
Greedy Algorithm
Slide9Then we can fill our sack
Sack = []
Sack.append(
eightBucks
)
Sack.append
(
fiftyCents
)
Sack
[[[‘dollar-coin’,100], 8], [[‘quarter’, 25], 2 ]]
Greedy Algorithm
Slide10Or we can use a new Python item called a tuple
A tuple is an immutable list
Dollar = ( “dollar-coin”, 100)p
rint(“Name: “, dollar[0])
Name: dollar-coin
print(“Value: “, dollar[1])
Value: 100
As you can see it is the same as a list, but it cannot be changed!
Greedy Algorithm
Slide11Can we use a tuple?
We could have the values of individual coins in a list
dollar = (“dollar-coin”, 100)
print(“Name: “, dollar[0])
Name: dollar-coin
p
rint(“Value: ”, dollar[1])
Value: 100
quarter
= (
“quarter”, 25)
Then in another list store the count for each roll
eightBucks
= (dollar, 8)
print(eightBucks)((‘dollar-coin’, 100), 8)fiftyCents = (quarter, 2)print(fiftyCents)((‘quarter’, 25), 2)
Greedy Algorithm
Slide12Then we can fill our sack
Sack = (
eightBucks,
fiftyCents
) p
rint(Sack)
[[[‘dollar-coin’,100], 8], [[‘quarter’, 25], 2 ]]
Sack[1] = ( dollar, 6)
Traceback
(most recent call last):
File ”<
stdin
>”, line 12, in <module>
TypeError
: ‘tuple’ object does not support item assignment.Greedy Algorithm
Slide13Another choice is a
NamedTuple
You must import collections to use itCoin =
collections.namedtuple
(“Coin”, [‘name’, ‘value’])
Coin(‘dime’, 10)
Coin(name=‘dime’, value=10)
tenCents
= Coin(‘dime’, 10)
tenCents.name
‘dime’
tenCents.name = ‘d’
Traceback
(most recent call last):
File ”<stdin>”, line 1, in <module>AttributeError: can’t set attribute.Coin(10, ‘dime’)Coin(name=10, value=‘dime’)Greedy Algorithm
Slide14Issues with lists, tuples, and
nametuples
Feels unnatural to use numeric indices when accessing the parts of an instance, what if you forget the number?
We cannot tell the difference between instances of different structures that have the same number
iof
parts
x
= [‘BMW’, 1972] can be mistaken for a y = [‘dollar’, 100]… how do we tell which is a car and which is a coin?
NamedTuple
does over come this issue, but it has its own issues
What is someone swaps the two named parts values when creating it?
Greedy Algorithms
Slide15Classes: A name slot approachWe can make our own unique types via classes
Lets us make our own, user defined types
Classes solve the issue of naming parts and distinguishing from other kinds of objects
A class declares a type, a new kind of structure
This allows us to specify names for parts rather than numbers
Greedy Algorithms
Slide16Example class:
Class Coin():
__slots__ = (‘name’, ‘value’)The slots hold the names of all the parts
They are make via a tuple of strings
To create a Coin
oneBuck
= Coin()
oneBuck.name = ‘dollar’
oneBuck.value
= 100
oneBuck.garbage
= 1
AttributeError: ‘Coin’ has no attribute ‘garbage’ Greedy Algorithms
Slide17Issues with classes
The slots of a class can hold any value
dime = Coin()
dime.value
= ‘dime’
amount =
dime.value
+ 4
TypeError
: unsupported operand type(s) for *: ‘
str
’ and ‘
int
’
No easy way to print an object using the default print statementdollar = Coin()dollar.name = ‘dollar’dollar.value = 100print(dollar)< main .Coin object at 0x10067a6c8>Greedy Algorithms
Slide18rit_lib
: typed, Named Slot Approach
Developed by the RIT CS deptAddresses the issues mentioned before
Use:
from
rit_lib
import *
class Coin(
struct
):
_slots = ( (
str
, ‘name’ ), (
int
, ‘value’ ) )Greedy Algorithms
Slide19Steps to use the rit_lib
approach:
Import the rit_lib module.
It is not part of the standard Python library
Add “from rit_lib import *”
Avoids having to write
rit_lib
over and over
Add
struct
inside the parentheses on the line that begins the class definition
This means that the class inherits from the
rit_lib
structA class that inherits will get the implementations of all the functions for displaying instances of the classSpecify the types and names of each of the slots using the _slots keywordNot the same as __slots__ for the new classGreedy Algorithms
Slide20Using the
rit_lib
method we can avoid lots of stepsWe can create and initialize the item in one stepCalled constructing an instance
We pass in the values in the order that the _slots items were added
Example
oneBuck
= Coin(‘dollar’, 100)
buck = Coin()
TypeError
: Constructor Coin() expected 2 arguments but got 0
print(
oneBuck
)
Coin( name: ‘dollar’, value: 100)print( oneBuck.value ) 100oneBuck.value = 99oneBuck.value = ‘dollar’
TypeError
: Type of quantity should be
int
, not
str
print(
oneBuck
)
Coin( name: ‘dollar’, value: 100)
Greedy Algorithms
Slide21We know we can represent a coin with
rit_lib
What about a CoinRoll?Recall a
CoinRoll
represents a number of coinsf
rom
rit_lib
import *
class
CoinRoll
(
struct
):
_slots = ( ( Coin, ‘Coin’), (
int, ‘qty’) )oneBuck = Coin( ‘;dollar’, 100)
sixBucks
=
CoinRoll
(
oneBuck
, 6)
print(
sixBucks
)
CoinRoll
( coin: Coin( name: ‘dollar’, value: 100),
qty
: 6 )
Greedy Algorithms
Slide22Now we know how to represent Coins and CoinRolls
using
rit_libWe will use that for our problem
Greedy Algorithms
Slide23High Level Pseudocode for the Algorithm:
Enter loop and print a banner
Prompt for a currency file
Tell the exchange to read the file
Tell the exchange to print the currency information
Enter an inner loop to:
Prompt user for an amount to change, break out if nothing or less than 1 was entered
Ask the exchange to handle the request’
Report the results of the request
Continue the loop
Thank the user and end the program
Greedy Algorithms
Slide24Implementationc
hange.py
The main module responsible for creating the exchange and interacting with the userexchange.pyThis is the “change machine”.
Creates the coins and
coinrolls
Reads the file to get the info
Makes the change from the coins and rolls if possible
Reports the results
To the code!
Greedy Algorithm
Slide25Time Complexity
What is the time complexity?
Since we use an insertion sort to sort the coins O(n2) for the sort
handleRequest
runs N times where N is the number of unique coin types, O(N)The cost of displaying the result is a loop thru all coins and rolls, O(n)
Therefore overall we have
O(n
2
) + O(n) + O(N) == O(n
2
)
Greedy Algorithm
Slide26Testing
We have seen cases where:
Change can be always made with fewest amount of coins (US)Change cannot always be made (Canada)
Is there a case where this machine will fail to make coins even though it is possible?
Lets look at the fictional country of Gormandy
Coins: grabby 9, glutton 11,
trieski
3
Lets try to make change for 18…
We can do this with 2 grabby…
Lets run our machine and see what happens…
Greedy Algorithm
Slide27The machine failed to make change!!!Why?????
Recall the algorithm is greedy…
If first takes glutton, gets one, leaving 7Next it tries grabby, and takes none, leaving 7
Next it tries
trieski, and takes 2, leaving 1
It fails because there are no ways to make 1
If the algorithm was not greedy and choose not to use the glutton it would have made change with the grabby.
Greedy Algorithms
Slide28There is another case to consider…It makes change but not the fewest number of coins
This can happen when making change in
madmax for 10!Coins: spark-plug 1, gasoline 7, battery 5
Recall it is greedy:
First takes 1 gasoline, leaving 3
Next it takes no battery, leaving 3
Finally it takes 3 spark-plug, leaving 0
It makes the change in 4 coins…
But could have done it in 2 if it took two battery
Greedy Algorithms
Slide29What you need to knowTakes largest first
, then works down
It is often simple and sometime optimalThere is no guarantee it will be able to produce and optimal result
or any result at all!
Greedy Algorithms