Dictionary task in Python: Elections - python

The first line gives the number of entries. Further, each entry contains the name of the candidate and the number of votes cast for him in one of the states. Summarize the results of the elections: for each candidate, determine the number of votes cast for him. Use dictionaries to complete the tasks.
Input:
Number of voting records (integer number), then pairs <> - <>
Output:
Print the solution of the problem.
Example:
Input:
5
McCain 10
McCain 5
Obama 9
Obama 8
McCain 1
Output:
McCain 16
Obama 17
My problem is at the step when I have to sum keys with same names but different values.
My code is:
cand_n = int(input())
count = 0
countd = 0
cand_list = []
cand_f = []
num = []
surname = []
edict = {}
while count < cand_n:
cand = input()
count += 1
cand_f = cand.split(' ')
cand_list.append(cand_f)
for k in cand_list:
for i in k:
if i.isdigit():
num.append(int(i))
else: surname.append(i)
while countd < cand_n:
edict[surname[countd]] = num[countd]
countd += 1
print(edict)

You can add the name and vote to the dictionary directly instead of using one more for() and while().
If the name does not exist in the dictionary, you add the name and vote. If the name exists in the dictionary, increase the vote.
cand_n = int(input())
count = 0
cand_list = []
cand_f = []
edict = {}
while count < cand_n:
cand = input()
count += 1
cand_f = cand.split(' ')
if cand_f[0] in edict:
edict[cand_f[0]] += int(cand_f[1])
else:
edict[cand_f[0]] = int(cand_f[1])
print(edict)

Related

How do I get the shortest repitition of something in an array?

Let's say you have a list which only has two types of values and goes something like ['t','r','r','r','t','t','r','r','t'] and you want to find the length of the smallest sequence number of 'r's which have 't's at both ends.
In this case the smallest sequence of 'r' has a length of 2, because there is first t,r,r,r,t and then t,r,r,t, and the latter has the smallest number of 'r's in a row surrounded by 't' and the number of 'r's is 2.
How would I code for finding that number?
This is from a problem of trying of going to a play with your friend, and you want to sit as close as possible with your friend, so you are trying to find the smallest amount of taken seats in between two free seats at a play. "#" is a taken seat and a "." is a free seat. you are given the amount of seats, and the seating arrangement (free seats and taken seats), and they are all in one line.
An example of an input is:
5
#.##.
where there are two taken seats(##) in between two free seats.
Here is my code which is not working for inputs that I don't know, but working for inputs I throw at it.
import sys
seats = int(input())
configuration = input()
seatsArray = []
betweenSeats = 1
betweenSeatsMin = 1
checked = 0
theArray = []
dotCount = 0
for i in configuration:
seatsArray.append(i)
for i in range(len(seatsArray)):
if i == len(seatsArray) - 1:
break
if seatsArray[i] == "." and seatsArray[i+1] == ".":
print(0)
sys.exit()
for i in range(0,len(seatsArray)):
if i > 0:
if checked == seats:
break
checked += 1
if seatsArray[i] == "#":
if i > 0:
if seatsArray[i-1] == "#":
betweenSeats += 1
if seatsArray[i] == ".":
dotCount += 1
if dotCount > 1:
theArray.append(betweenSeats)
betweenSeats = 1
theArray = sorted(theArray)
if theArray.count(1) > 0:
theArray.remove(1)
theArray = list(dict.fromkeys(theArray))
print(theArray[0])
This is a noob and a !optimal approach to your problem using a counter for the minimum and maximum sequence where ew compare both and return the minimum.
''' create a funciton that
will find min sequence
of target char
in a list'''
def finder(a, target):
max_counter = 0
min_counter = 0
''' iterate through our list
and if the element is the target
increase our max counter by 1
'''
for i in x:
if i == target:
max_counter += 1
'''min here is 0
so it will always be less
so we overwrite it's value
with the value of max_counter'''
if min_counter < max_counter:
min_counter = max_counter
'''at last iteration max counter will be less than min counter
so we overwrite it'''
if max_counter < min_counter:
min_counter = max_counter
else:
max_counter = 0
return min_counter
x = ['t','r','r','r','t','t','r','r','t','t','t','r','t']
y = 'r'
print(finder(x,y))
Create a string from list and then search for pattern required and then count r in the found matches and then take min of it
Code:
import re
lst = ['t','r','r','r','t','t','r','r','t']
text = ''.join(lst)
pattern = '(?<=t)r+(?=t)'
smallest_r_seq = min(match.group().count('r') for match in re.finditer(pattern, text))
print(smallest_r_seq)
Output:
2

Trying to find same digits in a row [duplicate]

This question already has answers here:
Longest sequence of consecutive duplicates in a python list
(4 answers)
Closed 2 years ago.
Im trying to find the biggest series of digit in a row in a list which i can input. And im doing this way:
list = []
count_max_numbers = 0
while True:
x = int(input('число: '))
if x == 0:
break
list.append(int(x))
max_number = max(list)
for i in list:
if i != max_number:
pass
else:
count_max_numbers += 1
current_result = 0
max_result = 0
last_seen = list[0]
longest_digit = 0
for i in list:
if i == last_seen:
current_result += 1
else:
if current_result > max_result:
max_result = current_result
longest_digit = i
last_seen = i
current_result = 1
if current_result > max_result:
max_result = current_result
longest_digit = i
print(f'{list}')
print(f'max number: {max_number} reapeted{count_max_numbers} times')
print(f'the biggest series: {longest_digit} repeated {max_result} times')
this works only with first digit in a list. But i need to work it with whole list.
For example if input (1,2,3,3,3,3,5,55)
It need to get output: the biggest series: 3 repeated 4 times
I still have a problem with output of {longest_digit} it's incorrect
Try this:
mylist = [1,2,3,3,3,3,5,55]
val_holder = {}
for val in mylist:
if val not in val_holder.keys():
val_holder[val] = 1
else:
val_holder[val] += 1
max_key = max(val_holder, key=val_holder.get)
print(max_key)
My aproach to this will be using dictionary
lst = [1,2,3,3,3,3,5,55]
dict = {}
for val in lst:
if val not in dict.keys():
dict[val] = 1
else:
dict[val] = dict[val] + 1
Once we get the dictionary we sort this using the value
sorted_dict = sorted(dict.items(), key=lambda keyVal: keyVal[1], reverse=True)
print(dict[0][0])
Here's a simple algorithm:
Initialize longest = None, longest_digit = None, current = 0, previous_digit, and current_digit = None.
Then, for each item in the list:
If the item is equal to current_digit, increment current by one.
Otherwise:
(A) If current > longest, set longest = previous_digit and longest_digit = item
(B) Then, reset current to 1 and current_digit to item
Set previous_digit to item
At the end of the list, also do step (A) above.
Now you should have the answer in longest (4) and longest_digit (3)

Code Not Working Properly - Trying To Create A Simple Graph

I'm trying to create a simple program where my inputs about data relating to daily COVID-19 cases will then be tabulated and created into a small graph. For example, I'll first input (primary input) will be: 7 20200401 20200403, which represents the # of inputs after my primary input, and from what dates the cases are from. Then I'll go onto input which the hospital, the # of cases from that hospital, and the day of the report. The number of cases per day will be represented by a * . When I go to run my program, it just shows me what the last # of cases inputted was for all 7 days. Is there any way to fix it, and have the program properly display the correct amount of cases per day?
Just to help you understand, here is what a sample input and output should be for this program:
Input:
7 20200401 20200403
HP1 20200401 1
HP2 20200401 1
HP3 20200401 1
HP4 20200402 1
HP5 20200402 1
HP6 20200403 1
HP7 20200403 1
Output:
20200401:***
20200402:**
20200403:**
But instead, I get this:
20200401:*
20200402:*
20200403:*
Here is my code:
CoronaCaseNumber = input("")
CoronaList = CoronaCaseNumber.split(" ")
LuckyNumber = CoronaList[0]
Date = CoronaList[1]
Date2 = CoronaList[2]
LuckyNumero = int(LuckyNumber)
DateList = []
CaseNumberList = []
for case in range(LuckyNumero):
CoronaCaseData = input()
CoronaList2 = CoronaCaseData.split(" ")
InfoDate = CoronaList2[1]
DateList.append(InfoDate)
CaseNumber = CoronaList2[2]
CaseNumberList.append(CaseNumber)
EmptySet = []
for i in DateList:
if i >= Date and i <= Date2:
if i not in EmptySet:
EmptySet.append(i)
for i in range(0, len(CaseNumberList)):
CaseNumberList[i] = int(CaseNumberList[i])
EmptySet.sort()
for i in range(len(EmptySet)):
print("{}{}{}".format(EmptySet[i], ":", "*" * CaseNumberList[i]))
I'm way too lazy to type in all that data everytime I run your script, so I automated that part to make development and testing of it easier. Likewise, I think the easiest thing to do would be to use the collections module's defaultdict class to keep track of what dates have been seen and the total number of cases seen on each of them. Here's what I mean:
from collections import defaultdict
#CoronaCaseNumber = input("")
#CoronaList = CoronaCaseNumber.split(" ")
#LuckyNumber = CoronaList[0]
#Date = CoronaList[1]
#Date2 = CoronaList[2]
LuckyNumber, Date, Date2 = "8 20200401 20200404".split(" ")
data = """\
HP4 20200402 1
HP5 20200402 1
HP1 20200401 1
HP2 20200401 1
HP3 20200401 1
HP6 20200403 0
HP6 20200404 1
HP7 20200404 1
""".splitlines()
LuckyNumero = int(LuckyNumber)
DateList = []
CaseNumberList = []
for case in range(LuckyNumero):
CoronaCaseData = data[case]
CoronaList2 = CoronaCaseData.split(" ")
InfoDate = CoronaList2[1]
DateList.append(InfoDate)
CaseNumber = CoronaList2[2]
CaseNumberList.append(CaseNumber)
DailyCases = defaultdict(int)
for i, d in enumerate(DateList):
if Date <= d <= Date2: # Valid date?
DailyCases[d] += int(CaseNumberList[i])
# Print daily cases sorted by date (i.e. the dictionary's keys).
for date in sorted(DailyCases, key=lambda d: int(d)):
print("{}:{}".format(date, '*' * DailyCases[date]))
Output:
20200401:***
20200402:**
20200403:
20200404:**

Print pairs of values from two lists

Everything is working for me in this program except for one thing; I need my output to group the names and values together in the print(names, "\n" values) section.
For example: Pat : €99, Kev : €55, Dermot : €100.
My code is below:
salesperson = int(input("How many salesperson's do you wish to account
for:"))
names = []
values = []
counter = 0
total_sales = 0
total_value = 0
if salesperson > counter:
while salesperson != counter:
name = input("Please enter in the salesperson's name:")
value = float(input("Please enter in the value of sales for the
salesperson:"))
salesperson -= 1
names.append(name)
values.append(value)
total_value += value
from statistics import mean
average_values = mean(values)
minimum = min(values)
maximum = max(values)
print(names,"\n",values)
print(average_values)
print(total_value)
print(minimum)
print(maximum)
You can do this using zip(), and f-strings:
print([f"{x}: £{y}" for x, y in zip(names,values)])
Output:
['Pat: £1.0', 'Dermot: £2.0', 'Kev: £3.0', 'Boris: £4.0', 'Jeremy: £5.0']

Appending a dictionary value to a list in python

I'm having trouble appending the student dictionary value that coincides with key 'id' to a list. Any help is much appreciated!
students = list();
students.append( {'id':12345, 'first_name':'Alice',
'last_name':'Anderson','assignments':[('assignment_1',0),('assignment_2',2),
('assignment_3',3)]})
students.append({'id':22345, 'first_name':'John',
'last_name':'Sparks','assignments':[('assignment_1',2),('assignment_2',3),
('assignment_3',4)]})
students.append({'id':32345, 'first_name':'Taylor',
'last_name':'Mason','assignments':[('assignment_1',3),('assignment_2',2),
('assignment_3',3)]})
def return_passing(students):
grade_sum = 0
counter = 0
for s in students: #loop thru students
for assignment, grade in s['assignments']:
grade_sum += grade
counter += 1
average = grade_sum / counter
lst = list()
if average >= 2.0:
lst.append((s['id']))
return lst
return_passing(students)
print(return_passing(students))
You have several issues with initializing things at the wrong place, so they get reset. Explanations for those are in the comments:
def return_passing(students):
lst = [] # initialize lst here
for s in students: #loop thru students
grade_sum = 0 # reset these for each student
counter = 0
for assignment, grade in s['assignments']:
grade_sum += grade
counter += 1
# now that we have gone throug all assignments
# compute average
average = float(grade_sum) / counter # convert to float for precision
if average >= 2.0:
lst.append(s['id'])
return lst # return only after you've gone through all students

Categories

Resources