0

I am making a voting system with python 3 and I get the candidates for each position based on user input through tkinter. For the sake of this example I won't be using tkinter as it is unnecessary.

I have my candidates stored inside of lists when they are created. Since the user can create as many candidates as they want there is no way of knowing how many variables I need for the counting process. That is why I believe I need to use a for loop to create variables. How can I do that?

posOne = []
f = [x.strip() for x in candidates.split(',')]
for x in f1:
    posOne.append(x)

for z in posOne:
    #code to create a new variable

Then I'll need a way to target the created variables so when they receive a vote I can count +1

If you know of a better way to handle this please let me know, because this doesn't seem optimized

2 Answers 2

3

Why not use a dictionary:

votes = {candidate.strip(): 0 for candidate in candidates.split(',')}

This is a dictionary comprehension that is equivalent to:

votes = {}
for candidate in candidates.split(','):
    votes[candidate.strip()] = 0

The when you get a vote for a candidate:

votes[candidate] += 1

To determine the winner:

winner = max(votes, key=votes.get)

e.g.:

>>> candidates = 'me, you'
>>> votes = {candidate.strip(): 0 for candidate in candidates.split(',')}
>>> votes
{'me': 0, 'you':0}
>>> votes[you] += 1
>>> winner = max(votes, key=votes.get)
>>> winner
'you'
Sign up to request clarification or add additional context in comments.

2 Comments

I've never used dicts or maps yet, how would I determine the winner using this?
if you don't mind could you break down what each section of the code does, since I haven't used dicts or maps before it would greatly help me understand how to edit your answer for my actual program
1

You could use collections.Counter which is dict like object where values are counts:

>>> from collections import Counter
>>> candidates = 'Jack, Joe, Ben'
>>> votes = Counter({x.strip(): 0 for x in candidates.split(',')})

Voting would be done like this:

>>> votes['Jack'] += 1
>>> votes['Jack'] += 1
>>> votes['Ben'] += 1

And most_common can be used to determine winner:

>>> votes.most_common(1)
[('Jack', 2)]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.