-3

I need help creating a program that searches a list and prints out the letter that repeats the most in position 0. For now I have the following:

lst=['Bill','Kev','Bard','Mike']
lst2=list()
for word in lst:
  lst3.append(word[0])
print(lst3)

For know this creates a list ['B','K','B','M'] How can I make it so it prints out the most repeated letter in position 0?

Nothing too complex plz I'm still new

Paul Rooney
  • 20,879
  • 9
  • 40
  • 61
  • 1
    Possible duplicate of [How to find most common elements of a list?](https://stackoverflow.com/questions/3594514/how-to-find-most-common-elements-of-a-list) – Brad Solomon Nov 07 '18 at 01:11
  • In the linked dupe look at [this](https://stackoverflow.com/a/44481414/1540468) answer. – Paul Rooney Nov 07 '18 at 01:16

3 Answers3

4
from collections import Counter

# Inside the Counter I use list comprehenshion to get the first letter from each word
counter = Counter([word[0] for word in lst]) 
counter.most_common(1) # --> [('B', 2)]
Dani G
  • 1,202
  • 9
  • 16
1

You can use a Counter and a bunch of anonymous functions:

from collections import Counter
from functools import reduce

lst = ['Bill','Kev','Bard','Mike']

max_value = max(
  reduce(
    lambda p, x: p.update([x]) or p,
    map(lambda x:x[0], lst),
  Counter()).items(),
  key=lambda x:x[1])[0]
print(max_value)
Bi Rico
  • 25,283
  • 3
  • 52
  • 75
1

I did not need a library to solve this, but I have to say that previous responses are very elegant, this a raw alternative if you are not that knowledgeable in python libraries:

1 - lets say that you have the following array:

a = ['a','b','c','d','a','b','c','d','a']

2 - then I recommend to sort it:

a.sort()
out[]: [a,a,a,b,b,c,c,d,d]

3 - once you have the array sorted you only need to identify when it changes from one letter to another, as is shown in the following code:

a = ['a','b','c','d','a','b','c','d','a']
a.sort()
counter = 0
for i in range(len(a)):
    counter += 1
    try:
        if(a[i] != a[i+1]):
            print(a[i] + ' is ' + str(counter) + ' times' )
            counter = 0
    except:
        print(a[i] + ' is ' + str(counter) + ' times' )

I use try-except to handle the end of the array, anyway the code is built in a simple way without applying any library, as I mention before previous responses are very elegant and have better performance, but maybe this will help you to improve your understanding on how to build an algorithm. Best wishes keep coding :)

Jose Reyes
  • 41
  • 1
  • 3