Home > front end >  How can I use a dictionary to add and subtract numbers when required to do so?
How can I use a dictionary to add and subtract numbers when required to do so?

Time:11-19

So I'm trying to write a code that will return the total of points each person has. Everyone starts with 0 and the input will assign ' ' or '--' behind each person directly just like "Jim ", "John--" which means that Jim gains one point while John loses one point.

Every ' ' equals to one point added

Every '--' equals to one point deducted.

So if my input looks like this

["Jim ", "John--", "Jeff ", "Jim ", "John--", "Jeff--", "June "]

this is what my output should look like

["Jim": "2", "John":"-2", "Jeff":"0", "June":"1"]

I'm trying to keep it simple without using stuff like key = lamda, import, or collections.iter since I'm new to this and I would prefer to keep things simply for now.

Here is what I have, which apparently doesn't work at all..

def keepTabs(actions: list[str]):
    d = {'  ' :  1, '--': -1}
    return d[actions]

print(keepTabs(actions=["Jim  ", "John--", "Jeff  ", "Jim  ", "John--", "Jeff--", "June  "]))

What changes to my code should I make to make sure this works??

I was informed about the usage of dictionaries, so I was just wondering if that could be used to solve this problem

CodePudding user response:

Hello from your questions example i assume that you start with a dictionary like:

currentTabs = {"Jim":1, "John": -1 , "Jeff":-1, "June" : 0}

a dictionary with ALL the keys/names you want initialised with a value

you could then have an input function which will return you a new dictionary

def KeepTabs(currentTabs, actions):
    for combined in actions:
        key = combined[:-2] # get the name IE [Jeff]--
        action = combined[-2:] # get the action ie Jeff[--]
        # decide what the action means
        if action == "  ":
            value = 1
        elif action == "--":
            value = -1
        else:
            value = 0
        # modify the key in the dictionary by the value
        currentTabs[key] =  currentTabs[key]   value
    return currentTabs

this function breaks the input action into its key and value pair, which is what we use to find the current value in the dictionary.

you could replace the if/else statements with a dictionary similar to how you have done.

def KeepTabs(currentTabs, actions):
    for combined in actions:
        key = combined[:-2] # get the name IE [Jeff]--
        action = combined[-2:] # get the action ie Jeff[--]
        # decide what the action means
        d = {'  ' :  1, '--': -1}
        # modify the key in the dictionary by the value
        currentTabs[key] =  currentTabs[key]   dict[action]
    return currentTabs

but this will crash if you pass an invalid key like "- ", this could be solved in other ways like a default dict.

CodePudding user response:

Solution to add to the points to the dict entry by checking the string

input_list = ["Jim  ", "John--", "Jeff  ", "Jim  ", "John--", "Jeff--", "June  "]

You just want the dict to keep a count of points they have and a function to get the name from the list entry.

def get_name(string): # format to get the name by removing the   and - characters
    return string.replace(" ", "").replace("-", "")

output = {}
for entry in input_list:
    name = get_name(entry)
    if name not in output:
        output[name] = 0  # add the initial entry and start at 0
    if "  " in entry:
        output[name]  = 1  # add points
    if "--" in entry:
        output[name] -= 1  # subtract points

print(output)
>> {'Jim': 2, 'John': -2, 'Jeff': 0, 'June': 1}

CodePudding user response:

This is what you want:

def get_name_from_action(name: str):
    d = {'  ': 1, '--': -1}
    name_action = [name, 0]
    for key, value in d.items():
        if name.__contains__(key):
            name_action[0] = name.replace(key, '')
            name_action[1] = value
    return {'name': name_action[0], 'action': name_action[1]}


def keep_tabs(names_actions_list):
    names_dic = {}
    for name_action in names_actions_list:
        name_increment = get_name_from_action(name_action)
        name = name_increment['name']
        action = name_increment['action']
        if name not in names_dic:
            names_dic[name] = 0
        names_dic[name] = names_dic[name]   action

    return names_dic


print(keep_tabs(names_actions_list=['Jim  ', 'John--', 'Jeff  ', 'Jim  ', 'John--', 'Jeff--', 'June  ']))

CodePudding user response:

This solution should be fairly extensible.

from collections import defaultdict
data = ["Jim  ", "John--", "Jeff  ", "Jim  ", "John--", "Jeff--", "June  "]
operators = {'  ': lambda x: x   1, '--': lambda x: x - 1}
result = defaultdict(int)

for name_op in data:
    name, op = name_op[:-2], name_op[-2:]
    result[name] = operators[op](result[name])
  • Related