-
Notifications
You must be signed in to change notification settings - Fork 5
/
vote_counter.py
92 lines (76 loc) · 3 KB
/
vote_counter.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
"""VoteCounter class to count votes from a json file or a string."""
import json
CANDIDATE_INDEXES = [
{"NICOLAS MADURO": 13},
{"LUIS MARTINEZ": 6},
{"JAVIER BERTUCCI": 1},
{"JOSE BRITO": 4},
{"ANTONIO ECARRI": 6},
{"CLAUDIO FERMIN": 1},
{"DANIEL CEBALLOS": 2},
{"EDMUNDO GONZALES": 3},
{"ENRIQUE MARQUEZ": 1},
{"BENJAMIN RAUSSEO": 1},
]
class VoteCounter:
"""VoteCounter class to count votes from a json file or a string"""
def count(self, json_data_file_path: str) -> dict:
"""Count votes from a json file
Args:
json_data_file_path: Path to the json file with the votes data
Returns:
A dictionary with the votes for each candidate
"""
with open(json_data_file_path, encoding="UTF-8") as json_data_file:
data = json.load(json_data_file)
return self._count_votes(data)
def count_from_string(self, data_string: str) -> dict:
"""Count votes from a string
Args:
data_string: String with the votes data
Returns:
A dictionary with the votes for each candidate
"""
vote_data = data_string.split("!")[1]
vote_numbers = list(map(int, vote_data.split(",")))
votes = {candidate: 0 for candidate in self.get_candidates()}
index = 0
for candidate_dict in CANDIDATE_INDEXES:
for candidate, count in candidate_dict.items():
votes[candidate] += sum(vote_numbers[index : index + count])
index += count
return votes
def _count_votes(self, data) -> dict:
"""Count votes from a list of votes data
Args:
data: List of votes data
Returns:
A dictionary with the votes for each candidate
"""
votes = {candidate: 0 for candidate in self.get_candidates()}
for vote in data:
vote_data = vote["data"].split("!")[1]
vote_numbers = list(map(int, vote_data.split(",")))
index = 0
for candidate_dict in CANDIDATE_INDEXES:
for candidate, count in candidate_dict.items():
votes[candidate] += sum(vote_numbers[index : index + count])
index += count
return votes
@staticmethod
def get_candidates() -> list:
"""Get the list of candidates"""
return [list(candidate_dict.keys())[0] for candidate_dict in CANDIDATE_INDEXES]
if __name__ == "__main__":
# Example usage
vote_counter = VoteCounter()
votes = vote_counter.count("outputs/qr_data.json")
print(votes)
total_votes = sum(votes.values())
print(total_votes)
# Example usage for the new method
data_string = "150702005.02.1.0001!105,7,2,0,4,1,0,1,1,1,0,2,44,2,1,0,0,1,0,1,0,0,0,1,0,0,0,0,1,0,1,0,0,7,13,350,0,2!0!0"
votes_from_string = vote_counter.count_from_string(data_string)
print(votes_from_string)
total_votes_from_string = sum(votes_from_string.values())
print(total_votes_from_string)