Reputation: 241
I have an array whose elements I would like to increment when a new user votes.
For example if there are 10 options, from 1 to 10 and one user voted i=3
it would be easy to write:
A[i] = A[i] + 1;
In the case where the options are from 'A' to 'I', how can I do this? Because I can't use the letter to point to a specific array element.
For a few thousand users, I don't want to do an embedded loop where I search all elements of the array to see to which one the choice 'i' corresponds to each time.
Can I do this in O(n) time?
Upvotes: 0
Views: 61
Reputation: 4213
Is as simple as using dictionaries, a dictionary is like an array where instead of having index you have a key and for each key there is a value. For more information visit https://www.tutorialspoint.com/python/python_dictionary.htm
So in your example just define a dictionary like this:
data = {'A': 0, 'B': 0, 'C': 0 .....}
then find the letter that you want to upvote and increase it:
data['A'] += 1
print(data['A'])
>>> {'A': 1, 'B': 0, 'C': 0}
Even you can have dictionaries inside dictionaries, example:
data = {'A': {'Votes':0, 'Description': ''}, 'B': {'Votes':0, 'Description': ''}, 'C': {'Votes':0, 'Description': ''} .....}
data['A']['Votes'] += 1
Upvotes: 2