Ex06 adicionado

This commit is contained in:
tiagorg 2022-11-11 11:47:51 +00:00
parent 96a28133dd
commit 642b88e74f
Signed by untrusted user who does not match committer: TiagoRG
GPG Key ID: DFCD48E3F420DB42
1 changed files with 37 additions and 12 deletions

View File

@ -6,34 +6,58 @@
# Face values of coins (in cents): # Face values of coins (in cents):
COINS = [200, 100, 50, 20, 10, 5, 2, 1] COINS = [200, 100, 50, 20, 10, 5, 2, 1]
def value(bag): def value(bag):
"""Return total amount in a bag.""" """Return total amount in a bag."""
... totalValue = 0
for coin in bag:
totalValue += bag[coin] * coin
return totalValue
def transfer1coin(bag1, c, bag2): def transfer1coin(bag1, c, bag2):
"""Try to transfer one coin of value c from bag1 to bag2. """Try to transfer one coin of value c from bag1 to bag2.
If possible, transfer coin and return True, otherwise return False.""" If possible, transfer coin and return True, otherwise return False."""
... if bag1[c] == 0:
return False
bag1[c] -= 1
bag2[c] = 1 if c not in bag2 else bag2[c] + 1
return True
def transfer(bag1, amount, bag2): def transfer(bag1, amount, bag2):
"""Try to transfer an amount from bag1 to bag2. """Try to transfer an amount from bag1 to bag2.
If possible, transfer coins and return True, If possible, transfer coins and return True,
otherwise, return False and leave bags with same values.""" otherwise, return False and leave bags with same values."""
# Creates a backup of the bags in case the transfer is not possible
bagBackup = (bag1.copy(), bag2.copy())
for coin in COINS:
while amount >= coin and transfer1coin(bag1, coin, bag2) and amount > 0:
amount -= coin
if amount == 0: if amount == 0:
return True return True
if value(bag1) < amount:
for coin in COINS:
bag1[coin] = bagBackup[0][coin] if coin in bagBackup[0] else 0
bag2[coin] = bagBackup[1][coin] if coin in bagBackup[1] else 0
return False return False
...
def strbag(bag): def strbag(bag):
"""Return a string representing the contents of a bag.""" """Return a string representing the contents of a bag."""
# You may want to change this to produce a more user-friendly # You may want to change this to produce a more user-friendly
# representation such as "4x200+3x50+1x5+3x1=958". # representation such as "4x200+3x50+1x5+3x1=958".
return str(bag) string = ""
... for coin in bag:
if bag[coin] != 0:
string = f"+{bag[coin]}x{coin}{string}"
string = f"{string[1:]}={value(bag)}"
return string
def main(): def main():
@ -74,6 +98,7 @@ def main():
return return
if __name__ == "__main__": if __name__ == "__main__":
main() main()