johndoe12345
johndoe12345

Reputation: 421

what is best method to index into array

Lets say I am trying to get the number of different peoples names. user inputs names until they enter a -1, once -1 is entered then loop will break

Once entered then i am trying to tabulate the output something likes this

names : John Max Joan

No of occurrences : 4 1 2

% of occurences : 20% 10% 30%

#!/usr/bin/python

names = ["John","Max","Joan"]

lst = []

while True:

    lst = raw_input("What is your name?")
    if lst == "-1":
        break
    input_list = lst.split()



print "Names" '[%s]' % ' '.join(map(str, names))

I have no idea on how to increment the values of the names with the number of times they are entered by the user - lets say the user enters john, john, max,joan joan joan then I would need to increment john twice, max once and joan 3 times.

I know I can reference different parts of names using [0] for example which is the first item but I don't know how to increment all the relevant parts .

Upvotes: 0

Views: 69

Answers (2)

Ozgur Vatansever
Ozgur Vatansever

Reputation: 52153

You can use collections.Counter to count and accumulate the occurrences of names in the given input:

counter = collections.Counter()
names = ["John", "Max", "Joan"]

while True:
    lst = raw_input("What is your name?")
    if lst == "-1":
        break

    lst = [name for name in lst.strip().split() if name in names]
    names.update(collections.Counter(lst))

print "names : {}".format(" ".join(names))
print "No of occurrences : {}".format(" ".join(map(str, names.values())))

Please note that, I presumed names are separated by whitespace in the input.

Upvotes: 1

decltype_auto
decltype_auto

Reputation: 1736

Counting word frequency in a multi-word string:

import sys
from collections import defaultdict

WORDS = """Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed 
do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim 
ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip 
ex ea commodo consequat."""


d = defaultdict(lambda: 0)
for word in WORDS.split():
    d[word] += 1 

for key in ['in', 'et', 'ut', 'sed']:
    print(key, ':\t', str(d[key]))

output:

in :     0
et :     1
ut :     2
sed :    1

Whether one normalizes the words to lowercase depends on the problem domain; in case the questioner wants to do that with the names he receives, that'd be data[word.lower()] += 1 in the loop, and then he may re-capitalize the first letter on output if he wishes to do that.

Upvotes: 0

Related Questions