I have a list like
words = ["test", "secondTest", "thirdTest"]
and I have a function to find for every position, the most occurring element through the list, e.g. the most occurring element in first position is 't', in second is 'e' and so on. The problem is that it takes very long time, especially for very long lists. Here's my function:
def mostFrequent(lst: list[str]) -> str:
dic = {}
count, itm = 0, ''
for item in reversed(sorted(lst)):
dic[item] = dic.get(item, 0) + 1
if dic[item] >= count:
count, itm = dic[item], item
return (itm)
def most_frequent_chars() -> str:
words = ["test", "secondTest", "thirdTest"]
maxOccurs = ""
listOfChars = []
for i in range(len(max(words, key=len))):
for item in words:
try:
listOfChars.append(item[i])
except IndexError:
pass
maxOccurs += mostFrequent(listOfChars)
listOfChars.clear()
return maxOccurs
I'm using another function because before I was just using a one-liner max() but it'd take a lot longer than this, so I swapped with a dictionary method, and I'm looking for making this a lot more efficient, I cannot use any import.