Home > database >  Getting an empty output when calculating two same numbers and unable to change key name in dict w/ R
Getting an empty output when calculating two same numbers and unable to change key name in dict w/ R

Time:02-13

Edit: I was able to figure out the first part of this question by adding a condition that if the cost and paid are the same and matches a key value in money then it adds it to the dict.

I'm sorry if the title is confusing. Basically, I am writing a function that takes in a number as the item cost and the second as the amount you paid with. Then it tells you your change in bills and coins.

  def right_change(cost, paid):

  money = {
    "$20 bill" : 20,
    "$10 bill" : 10,
    "$5 bill" : 5,
    "$1 bill": 1,
    "quarter": 0.25,
    "dime" : 0.10,
    "nickel": 0.05,
    "penny": 0.01
  }

  amount = paid - cost
  change = {}
  
  for item in money:
    while amount >= money[item]:
      amount -= money[item]
      amount = float(f'{amount:.2f}')
      if item not in change:
          change[item] = 1
      else:
          change[item]  = 1

I get the expected output when I use floats such as (5.40, 20) --> {$10 bill: 1, $1 bill: 4, quarter: 2, dime: 1} But if I use exact numbers like (20, 20) it will return an empty object when I want {$20 bill: 1}

I am also trying to change the names to plurals if their quantity is more than 1. In order to be less redundant and typing out conditions for each word, I tried using Regex:

def plurals(dict):
  new_dict = {}
  for item in dict:
    if dict[item] > 1 and re.match('/[^y]$/gm', item):
      new_dict[item "s"] = dict[item]
      if re.match('p', item):
          new_dict['pennies'] = dict[item]
    else:
        new_dict[item] = dict[item]

  return new_dict

It will still output the change but it won't change anything. Any help is appreciated! I've been spending hours trying to figure this out.

CodePudding user response:

For the name change issue:

def set_to_plural_if_more_than_one(old_dict):
    new_dict = {}
    for item in old_dict:
        if old_dict[item] > 1:
            if item[-1] == "y":
                new_dict[item[:-1]   "ies"] = old_dict[item]
            else:
                new_dict[item   "s"] = old_dict[item]
        else:
            new_dict[item] = old_dict[item]
    return new_dict

You can use regex but I feel like in this case it's an overkill since you are simply distinguishing between some basic strings you know and not searching for any advanced patterns.

Also just in general I would avoid overwriting names of pythons builtins such as dict as variable or argument names in your code since they can cause weird and sometimes hard to debug behaviour.

  • Related