conting of input names - python-3.x

I have a python homework which I need to take n from input to know how many names I have to take from input, save them to a dictionary then count how many each name was inputed, something like voting system.
so far I couldn't save my input into a dic.
Because I stored all inputs in a list after I assign my list with a dict, it turns to str.
for example:
how many vote u want to input : 4
take your votes:
jack
jasmin
jack
sara
result:
jack 2
jasmin 1
sara 1
My code:
vorodi=[]
n=int(input())
counter={}
for i in range(0,n):
vorodi.append(input())
for letter in vorodi:
if letter not in counter:
counter[letter]+=1
else:
counter[letter]=1
print(counter)

This is a classic case where you will want to use defaultdict. With defaultdict you specify the type of new keys and so if the key is not present it will be initialized to the default of the type specified. So you could do:
from collections import defaultdict
n = int(input())
counter = defaultdict(int)
for i in range(n):
counter[input()] += 1
print(counter.items())
OR:
with regular dict using the get method with the default argument:
n = int(input())
counter = {}
for i in range(n):
name = input()
count = counter.get(name, 0)
counter[name] = count + 1
OR:
with regular dict using the setdefault method with the default argument:
n = int(input())
counter = {}
for i in range(n):
name = input()
counter.setdefault(name, 0)
counter[name] += 1
To print it as you showed you can simply iterate the dict afterwards:
for k,v in counter.items():
print(k, v)

Related

Create a empty list. Populate the list with couple of numbers until the input is -1

Example for above question:
Explanation:
User is giving some random input(negative and positive). i am storing all in a list and I want only positive number should be present. remove all the negative number
What i have tried:
input_1st = []
var = int(input())
for j in range (0, var):
ele = int(input())
input_1st.append(ele)
for i in input_1st:
if (i>0):
lst.append(i)
print(lst)
the error I have got:
thankyou
Just read all input and check the value.
result = []
while True:
try:
value = int(input())
if value > 0:
result.append(value)
except EOFError:
break
print(result)

I was supposed to count the unique digits in a number but getting this int object not iterable on 4th line and not sure how to fix it

x = int(input("Enter the number: "))
count = 0
for elements in range(0,10):
for i in (x):
if elements == i:
count += 1
break
print()
That error raise because an integer is not an iterate object unlike strings, list, etc. So what you can do it's just work with a string, then use set (which get the unique values) and then get the length of it and you won't need to traverse with a for loop as below:
x = input("Enter the number: ")
unique_digits = set(x)
print(len(unique_digits))
Hope it will help you :)
x = input("Enter number: ")
count = 0
for elements in range(10):
for t in x:
if (int(t)==elements):
count += 1
break
print(count)

The output of the code is in different order than expected

n = int(input())
a_name = []
a_score = []
for _ in range(n):
name = input()
score = float(input())
a_name.append(name)
a_score.append(score)
a_score1 = set(a_score)
a_score1.remove(min(a_score1))
x = min(a_score1)
for i in range(n):
if a_score[i]==x:
print(a_name[i])
For the following code input is:
5
Harry
37.21
Berry
37.21
Tina
37.2
Akriti
41
Harsh
39
My Output:
Harry
Berry
Expected Output:
Berry
Harry
I am a newbie in the programming world and would appreciate help to solve this.
This is a hacker rank problem and the problem is to find the names with a second minimum score. I was able to pass 8/10 test cases but 2 test cases are failing with this solution. I am able to find the correct names(i.e. names with second-lowest score) however it is printed in wrong order)
you can find first the second minim and then find the names that have the second minim using a list comprehension and the built-in function zip:
second_minim = sorted(a_score)[1]
[n for n, s in zip(a_name, a_score) if s == second_minim]
output:
['Harry', 'Berry']
related to why should be ['Berry', 'Harry'] instead of ['Harry', 'Berry'] according to the requirements that you pointed:
If there are multiple students with the same grade, order their names alphabetically and print each name on a new line
so you should use:
result = sorted(n for n, s in zip(a_name, a_score) if s == second_minim)
print(*result, sep='\n')
output:
Berry
Harry
So instead of using two lists, you can map the scores to a name with a dict. Like so:
scores_dict = {'Harry': 37.21,
'Berry': 37.21,
'Tina': 37.2,
'Akriti': 41,
'Harsh': 39
}
Next remove all matching keys to the starting min value so that we can get the second min
x = min(scores_dict, key=scores_dict.get)
filtered_scores = {k:v for k,v in scores_dict.items() if v != scores_dict[x]}
Then we grab all the keys of any of the new min value.
x = min(filtered_scores, key=scores_dict.get)
res = [key for key in filtered_scores if filtered_scores[key] == filtered_scores[x]]
Full Code
n = int(input)
scores_dict = {}
for _ in range(n):
name = input()
score = int(input())
scores_dict[name] = score
# The loop will produce this dict
'''
scores_dict = {'Harry': 37.21,
'Berry': 37.21,
'Tina': 37.2,
'Akriti': 41,
'Harsh': 39
}
'''
x = min(scores_dict, key=scores_dict.get)
filtered_scores = {k:v for k,v in scores_dict.items() if v != scores_dict[x]}
x = min(filtered_scores, key=scores_dict.get)
res = [key for key in filtered_scores if filtered_scores[key] == filtered_scores[x]]
print(res)
If you really want to use two lists, it can be done, but it adds potential for bugs by adding unneeded complexity.
Dictionaries are just associative (named) arrays (lists).
n = int(input())
a_name = []
a_score = []
for _ in range(n):
name = input()
score = float(input())
a_name.append(name)
a_score.append(score)
a_score1 = set(a_score)
a_score1.remove(min(a_score1))
x = min(a_score1)
y =[]
for i in range(n):
if a_score[i]==x:
y.append(a_name[i])
y.sort()
for j in range(len(y)):
print(y[j])
I got the output with this code. Thank you everyone for the help!

Making a matrix in python 3 without numpy using inputs

I want to have two inputs : a,b or x,y whatever...
When the user inputs say,
3 5
Then the shell should print a matrix with 3 rows and 5 columns also it should fill the matrix with natural numbers( number sequence starting with 1 and not 0).
Example::
IN :2 2
OUT:[1,2]
[3,4]
If your objective is only to get the output in that format
n,m=map(int,input().split())
count=0
for _ in range(0,n):
list=[]
while len(list) > 0 : list.pop()
for i in range(count,count+m):
list.append(i)
count+=1
print(list)
I am going to give a try without using numpy library.
row= int(input("Enter number of rows"))
col= int(input("Enter number of columns"))
count= 1
final_matrix= []
for i in range(row):
sub_matrix= []
for j in range(col):
sub_matrix.append(count)
count += 1
final_matrix.append(sub_matrix)
Numpy library provides reshape() function that does exactly what you're looking for.
from numpy import * #import numpy, you can install it with pip
n = int(input("Enter number of rows: ")) #Ask for your input, edit this as desired.
m = int(input("Enter number of columns: "))
x = range(1, n*m+1) #You want the range to start from 1, so you pass that as first argument.
x = reshape(x,(n,m)) #call reshape function from numpy
print(x) #finally show it on screen
EDIT
If you don't want to use numpy as you pointed out in the comments, here's another way to solve the problem without any libraries.
n = int(input("Enter number of rows: ")) #Ask for your input, edit this as desired.
m = int(input("Enter number of columns: "))
x = 1 #You want the range to start from 1
list_of_lists = [] #create a lists to store your columns
for row in range(n):
inner_list = [] #create the column
for col in range(m):
inner_list.append(x) #add the x element and increase its value
x=x+1
list_of_lists.append(inner_list) #add it
for internalList in list_of_lists: #this is just formatting.
print(str(internalList)+"\n")

acount total number of letter ONLY alphabet

I have a txt about a English story. My work is counting the total number of letters in this story(alphabet only from "a" to "z" and "A"to "Z" ) . this is what I have wrote:
def count():
file=open("xxx.txt","r")
for line in file:
I dont know how to type next, cuz I only need letter but not 'space",not"!",how can I improve it?
Easy way is to just count them all, then add up the ones you care about (ascii_letters in this case)
from collections import Counter
from string import ascii_letters
def count():
c = Counter()
with open("xxx.txt","r") as file:
for line in file:
c.update(line)
return sum(v for k, v in c.items() if k in ascii_letters)
Another terse approach is to use regex
def count():
with open("xxx.txt","r") as file:
return len(re.findall('[a-zA-Z]', file.read()))
Apparently this is homework and the teacher has imposed some arbitrary restrictions. Still not really any point using ord or chr here
def count():
c = 0
with open("xxx.txt","r") as file:
for line in file:
for ch in line:
if 'a' <= ch <= 'z' or 'A' <= ch <= 'Z':
c += 1
return c

Resources