Character Count HW | Need suggestions for optimization - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: General (https://python-forum.io/forum-1.html) +--- Forum: Code Review (https://python-forum.io/forum-46.html) +--- Thread: Character Count HW | Need suggestions for optimization (/thread-31146.html) |
Character Count HW | Need suggestions for optimization - NectDz - Nov-25-2020 Hello, my homework asked to make a program that accepts a string as a parameter and that returns the letters that appeared the most without any duplicates. I would just like to know if there is any way I could of used any list comprehensions or optimized it in any way? Thanks! # Gets the max number in the list def maxNumber(L): i = 0 maxNum = L[0] while i < len(L): if L[i] >= maxNum: maxNum = L[i] i += 1 return maxNum # Returns a index list on the letters who appeared the most def indexes(maxNum,S): index = [] j = 0 for i in S: if S.count(i) == maxNum: index.append(j) j += 1 return index # Returns the letters that appeared the most def maxLetters(index,S): maxLetters = '' for i in index: if S[i] not in maxLetters: maxLetters += S[i] return maxLetters # Main Function def CharacterCount(S): # Removes Spaces S = S.replace(' ','') # Max Number - List Comprehension returns how many time times a letter appears maxNumbers = maxNumber([S.count(i) for i in S]) # Returns a index list on the letters who appeared the most index = indexes(maxNumbers,S) # Returns the letters that appeared the most maxLetter = maxLetters(index,S) print(maxLetter) CharacterCount('Python is great fun') CharacterCount('Good Times') RE: Character Count HW | Need suggestions for optimization - Larz60+ - Nov-25-2020 to get character count: from collections import Counter def CharacterCount(S): S = S.strip().replace(' ','') return Counter(S) print(f"\nCounts 'Python is great fun': {CharacterCount('Python is great fun')}") print(f"Counts 'Good Times': {CharacterCount('Good Times')}\n")
|