Check the most frequent letter(s) in a word. Python - python

My task is:
To write a function that gets a string as an argument and returns the letter(s) with the maximum appearance in it.
Example 1:
s = 'Astana'
Output:
a
Example 2:
s = 'Kaskelen'
Output:
ke
So far, I've got this code(click to run):
a = input()
def most_used(w):
a = list(w)
indexes = []
g_count_max = a.count(a[0])
for letter in a:
count = 0
i = int()
for index in range(len(a)):
if letter == a[index] or letter == a[index].upper():
count += 1
i = index
if g_count_max <= count: //here is the problem.
g_count_max = count
if i not in indexes:
indexes.append(i)
letters = str()
for i in indexes:
letters = letters + a[i].lower()
return letters
print(most_used(a))
The problem is that it automatically adds first letter to the array because the sum of appearance of the first element is actually equal to the starter point of appearance(which is basically the first element).
Example 1:
s = 'hheee'
Output:
he
Example 2:
s = 'malaysia'
Output:
ma

I think what you're trying to can be much simplified by using the standard library's Counter object
from collections import Counter
def most_used(word):
# this has the form [(letter, count), ...] ordered from most to least common
most_common = Counter(word.lower()).most_common()
result = []
for letter, count in most_common:
if count == most_common[0][1]:
result.append(letter) # if equal largest -- add to result
else:
break # otherwise don't bother looping over the whole thing
return result # or ''.join(result) to return a string

You can use a dictionary comprehension with a list comprehension and max():
s = 'Kaskelen'
s_lower = s.lower() #convert string to lowercase
counts = {i: s_lower.count(i) for i in s_lower}
max_counts = max(counts.values()) #maximum count
most_common = ''.join(k for k,v in counts.items() if v == max_counts)
Yields:
'ke'

try this code using list comprehensions:
word = input('word=').lower()
letters = set(list(word))
max_w = max([word.count(item) for item in letters])
out = ''.join([item for item in letters if word.count(item)==max_w])
print(out)

Also you can import Counter lib:
from collections import Counter
a = "dagsdvwdsbd"
print(Counter(a).most_common(3)[0][0])
Then it returns:
d

Related

I need combine indexs of a tuple how can i do this

I was trying a bigger letter to the index of word i did it but it is not in the same of index
k = 'kars'
k = k[0].upper(),k[1],k[2],k[3],k[4]
it is distributing the letters how can i combine them
Python has a title() method:
k = 'kars'
print(k.title())
# OR
print(k[0].upper() + k[1:])
# OR
def uppercaseAtIndex(k, i):
newK = list(k)
newK[i] = newK[i].upper()
return ''.join(newK)
print(uppercaseAtIndex(k, 1))
Out:
Kars
Kars
kArs
Use a generator expression and enumerate to capitalize a specific index. Join the letters with str.join().
index = 1
''.join(letter.upper() if i==index else letter for i,letter in enumerate('thestring'))

How to find the longest repeating sequence using python

I went through an interview, where they asked me to print the longest repeated character sequence.
I got stuck is there any way to get it?
But my code prints only the count of characters present in a string is there any approach to get the expected output
import pandas as pd
import collections
a = 'abcxyzaaaabbbbbbb'
lst = collections.Counter(a)
df = pd.Series(lst)
df
Expected output :
bbbbbbb
How to add logic to in above code?
A regex solution:
max(re.split(r'((.)\2*)', a), key=len)
Or without library help (but less efficient):
s = ''
max((s := s * (c in s) + c for c in a), key=len)
Both compute the string 'bbbbbbb'.
Without any modules, you could use a comprehension to go backward through possible sizes and get the first character multiplication that is present in the string:
next(c*s for s in range(len(a),0,-1) for c in a if c*s in a)
That's quite bad in terms of efficiency though
another approach would be to detect the positions of letter changes and take the longest subrange from those
chg = [i for i,(x,y) in enumerate(zip(a,a[1:]),1) if x!=y]
s,e = max(zip([0]+chg,chg+[len(a)]),key=lambda se:se[1]-se[0])
longest = a[s:e]
Of course a basic for-loop solution will also work:
si,sc = 0,"" # current streak (start, character)
ls,le = 0,0 # longest streak (start, end)
for i,c in enumerate(a+" "): # extra space to force out last char.
if i-si > le-ls: ls,le = si,i # new longest
if sc != c: si,sc = i,c # new streak
longest = a[ls:le]
print(longest) # bbbbbbb
A more long winded solution, picked wholesale from:
maximum-consecutive-repeating-character-string
def maxRepeating(str):
len_s = len(str)
count = 0
# Find the maximum repeating
# character starting from str[i]
res = str[0]
for i in range(len_s):
cur_count = 1
for j in range(i + 1, len_s):
if (str[i] != str[j]):
break
cur_count += 1
# Update result if required
if cur_count > count :
count = cur_count
res = str[i]
return res, count
# Driver code
if __name__ == "__main__":
str = "abcxyzaaaabbbbbbb"
print(maxRepeating(str))
Solution:
('b', 7)

using min with list properly

text = input("enter string:")
text.lower()
counta = text.count ("a")
counte = text.count ("e")
counti = text.count ("i")
counto = text.count ("o")
countu = text.count ("u")
if counta > 0:
print ("'a'",counta)
if counte > 0:
print ("'e'",counte)
if counti> 0:
print ("'i'",counti)
if counto > 0:
print ("'o'",counto)
if countu > 0:
print ("'u':",countu)
leastFreq = [counta,counte,counti,counto,countu]
leastFreq.sort()
while 0 in leastFreq: leastFreq.remove(0)
print (leastFreq)
task = count vowels in word, print least frequent vowels that occur. in this case, "potato" would print:
'a' = 1
'0' = 2
how do I make it so that it prints just 'a'? I could use min(leastFreq) but that would only return the value "1". how do I do it so that it prints using the format 'a' = 1 or if there is more than one vowel with the same number of occurences.
You could use min with an additional filter condition, testing whether the element is > 0:
>>> leastFreq = [4, 2, 1, 0, 3, 0]
>>> min(x for x in leastFreq if x > 0)
1
But this way, you lose the information what character this count belongs to. Instead of your five different variables, you could create a dictionary, mapping vowels to their respective counts:
>>> text = "potato"
>>> counts = {c: text.count(c) for c in "aeiou"}
>>> counts
{'a': 1, 'i': 0, 'e': 0, 'u': 0, 'o': 2}
>>> counts["o"]
2
And then again use min with a generator expression and a specific key function (to sort by the count, not by the vowel itself).
>>> min((c for c in counts if counts[c] > 0), key=counts.get)
'a'
If you are interested in the counts of all the letters, you could also use collections.Counter.
To minimally change your code:
leastFreq = [(counta, 'a'),(counte, 'e'),(counti, 'i'),(counto, 'o'),(countu, 'u')]
leastvowel = min(leastFreq)[1]
But you should use collections.Counter instead
from collections import Counter
text = input("Enter text: ")
c = Counter(character for character in text if character in 'aeiou') #get counts of vowels
least_frequent = c.most_common()[-1]
least_frequent will then be a tuple like ('a', 1)
EDIT: If you want all of the most frequent items you can use itertools.groupby
lestfreq=list(next(itertools.groupby(c.most_common()[::-1], key=lambda x:x[1]))[1])
This looks complicated, but all it's saying is take a list in sorted order and take all the tuples with the same second value and put them in a list.
A combination of Counter and operator might do the trick:
from collections import Counter
import operator
text = raw_input("enter string:")
freq = Counter(i for i in text if i in 'aeiou')
items = sorted(freq.items(),key=operator.itemgetter(1))
min = items[0][1]
for character,frequency in items:
if frequency == min:
print character,frequency

Comparing occurrences of characters in strings

code
def jottoScore(s1,s2):
n = len(s1)
score = 0
sorteds1 = ''.join(sorted(s1))
sorteds2 = ''.join(sorted(s2))
if sorteds1 == sorteds2:
return n
if(sorteds1[0] == sorteds2[0]):
score = 1
if(sorteds2[1] == sorteds2[1]):
score = 2
if(sorteds2[2] == sorteds2[2]):
score = 3
if(sorteds2[3] == sorteds2[3]):
score = 4
if(sorteds2[4] == sorteds2[4]):
score = 5
return score
print jottoScore('cat', 'mattress')
I am trying to write a jottoScore function that will take in two strings and return how many character occurrences are shared between two strings.
I.E jottoScore('maat','caat') should return 3, because there are two As being shared and one T being shared.
I feel like this is a simple enough independent practice problem, but I can't figure out how to iterate over the strings and compare each character(I already sorted the strings alphabetically).
If you are on Python2.7+ then this is the approach I would take:
from collections import Counter
def jotto_score(str1, str2):
count1 = Counter(str1)
count2 = Counter(str2)
return sum(min(v, count2.get(k, 0)) for k, v in count1.items())
print jotto_score("caat", "maat")
print jotto_score("bigzeewig", "ringzbuz")
OUTPUT
3
4
in case they are sorted and the order matters:
>>> a = "maat"
>>> b = "caat"
>>> sum(1 for c1,c2 in zip(a,b) if c1==c2)
3
def chars_occur(string_a, string_b):
list_a, list_b = list(string_a), list(string_b) #makes a list of all the chars
count = 0
for c in list_a:
if c in list_b:
count += 1
list_b.remove(c)
return count
EDIT: this solution doesn't take into account if the chars are at the same index in the string or that the strings are of the same length.
A streamlined version of #sberry answer.
from collections import Counter
def jotto_score(str1, str2):
return sum((Counter(str1) & Counter(str2)).values())

check if string is in abc order

So the function should count the number of times the letters in uppercase are out of abc order.
>>> abc('ABBZHDL')
2
Above, z and d are out of order.
>>> abc('ABCD')
0
>>> abc('DCBA')
4
My code:
def abc(check):
order=ABCDEFGHIJKLMNOPQRSTUVWXYZ
for c in check:
if check != order:
#then I get stuck here
Pointers?
The question is ill-defined. One solution to a nearby question would be using the builtin sorted():
def abc(s):
count = 0
s = ''.join(i for i in s if i.isupper())
l = sorted(s)
for i,c in enumerate(s):
if l[i] != c:
count += 1
return count
It counts all of the places where the alphabetized string does not match the original.
def abc(check):
last = ''
count = 0
for letter in check:
if not letter.isupper():
continue
if letter < last:
count += 1
last = letter
return count
import string
a = 'acbdefr'
b = 'abdcfe'
assert ''.join(sorted(b)) in string.ascii_letters
assert ''.join(sorted(a)) in string.ascii_letters #should fail
Its really simple everyone seems to be overcomplicating it somewhat?

Categories

Resources