0

My goal is to get the most repeated letter in a sentence or a line of strings (including spaces)

Here's the code I have so far

input = (str(input("Please enter a sentence:"))).strip()
b = list()
b.append(input.split())

counts = dict()
for word in b:
    i = 0
    while i < len(word):
        counts[word[i]] = counts.get(word[i], 0) + 1
        i += 1

print(counts)

At this point, I expect each and every letter to be in the dictionary with its values. But the output I get is (The input is "I want to do that" :

{'I': 1, 'want': 1, 'to': 1, 'do': 1, 'that': 1}

Instead of having individual letters with their values, I am getting the entire words

Can you guys please tell me the mistakes I made and so on?

  • 1
    You've already identified the problem. Look closer at `b.append(input.split())`. Have you looked up the default split value in the documentation? Hint: you're getting a nested list at the end of that. You might want to think about how you want to split that string up (maybe `.split()` isn't what you want) – roganjosh Jan 17 '21 at 17:16
  • `b` is a list of lists which means you count words. Just change to `b = input.split()`... But you should also not use `input` as a name to a variable. And your whole code could be one line using a [`Counter`](https://docs.python.org/3/library/collections.html#collections.Counter)... – Tomerikoo Jan 17 '21 at 17:17
  • @Tomerikoo surely there is a better dupe target? :/ I'm not keen on what you've linked but I'm also not clear on what I think the target should be – roganjosh Jan 17 '21 at 17:18
  • You don't need to create `b`, you can just iterate over the output of `input.split()` [directly](https://repl.it/@ShashSinha/AccurateDismalSymbols#main.py) – Sash Sinha Jan 17 '21 at 17:19
  • @roganjosh I doubt there is a dupe to the exact problem in this case (`append`ing the split result to a list which creates two-level nesting), but that is a well-known problem with 13 answers there which will surely help the OP find the right way – Tomerikoo Jan 17 '21 at 17:21

0 Answers0