check if string is in abc order - python

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?

Related

Reverse only vowels in a string

Given a string, I want to reverse only the vowels and leave the remaining string as it is. If input is fisherman output should be fashermin. I tried the following code:
a=input()
l=[]
for i in a:
if i in 'aeiou':
l.append(i)
siz=len(l)-1
for j in range(siz,-1,-1):
for k in a:
if k in 'aeiou':
a.replace(k,'l')
print(a)
What changes should be made in this code to get the desired output?
It is a little easier to turn your word into a list of letters and back:
a=input('Enter word: ')
l=[]
for i in a:
if i in 'aeiou':
l.append(i)
letters = list(a)
for i in range(len(letters)):
if letters[i] in 'aeiou':
letters[i] = l.pop(-1)
print(''.join(letters))
You have few logical mistakes in the code.
You need to save the o/p of .replace function in another string
a= a.replace(k,'l')
'l' is a string. I am sure it was list access that you were going for, so the correct syntax is: a= a.replace(k,l[j])
When replacing if you use the same string(string 'a' in your case), it will lead to all vowels getting replaced by a same vowel.
Using the same variable names, you used, following is one of the correct ways to do it:
a=input()
l=""
for i in a:
if i in 'aeiouAEIOU':
l+=i
new_a = ""
for k in a:
if k in "aeiouAEIOU":
new_a += l[-1]
l = l[:-1]
else:
new_a += k
print(a)
print(new_a)
Here is a piece of code that I have worked on that is the same question.
Write a program to reverse only the vowels in the string.
Example:
Input:
India
Output:
andiI
def revv(word):
a = ''
b = ''
for x in word:
if x in 'aeiouAEIOU':
a = a+x
b = b+'-'
else:
b = b+x
c = ''
d = 0
a = a[::-1]
for x in b:
if x=='-':
c = c+a[d]
d = d+1
else:
c = c+x
print(c)
revv('India')
Output:
andiI
This must work. First found vowels and and indexes of the vowels also you need to store it in a variable. After that you can reverse it easly buy going backword.
a = "fisherman"
def isVowel(c):
if c == "a" or c == "e" or c == "u" or c == "i" or c == "o":
return True
return False
def reverseOnlyVowels(string):
indexes = []
chars = []
# get vowels and indexes
for index, i in enumerate(list(string)):
if isVowel(i):
indexes.append(index)
chars.append(i)
# reverse vowels
stringList = list(string)
index1 = 0
for i, index in zip(chars[::-1], indexes[::-1]):
stringList[index] = chars[index1]
index1 += 1
return "".join(stringList)
print(reverseOnlyVowels(a))

Check the most frequent letter(s) in a word. 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

How do I count if a string is within the substrings of a list?

For example:
list_strings = 'dietcoke', 'dietpepsi', 'sprite'
Here's what I did:
count = 0
list =
for ch in list_strings:
if ch == sub:
count += 1
print((list_strings, 'diet') == 2) is suppose to return True but it returns False.
I hope I understood you correctly.
Just use in to check if your substring is present in the mainstring.
list = ['dietcoke', 'dietpepsi', 'sprite']
Your function should look like this:
def myfuncname(list_strings, sub_string):
count = 0
for ch in list_strings:
if sub_string in ch:
count += 1
return count
If we call count now, we get count == 2
>>> print(myfuncname(list_strings, 'diet') == 2)
True
Hope that solved your problem.

Print count (word occurrence) from a random text (Print hackerearth)

I am trying to find the count of occurrence of fixed word from any given string.
Fixed word = 'hackerearth'
Random string may be s = 'aahkcreeatrhaaahkcreeatrha'
Now from string we can generate 2-times hackerearth.
I have written some code to find the count of (h,a,e,r,c,k,t) letters in string:
Code:
word = list(raw_input())
print word
h = word.count('h')
a = word.count('a')
c = word.count('c')
k = word.count('k')
e = word.count('e')
r = word.count('r')
t = word.count('t')
if (h >= 2 and a >= 2 and e >= 2 and r >=2) and (c >= 1 and k >= 1 and t >=1 ):
hc = h/2
ac = a/2
ec = e/2
rc = r/2
num_words = []
num_words.append(hc)
num_words.append(ac)
num_words.append(ec)
num_words.append(rc)
num_words.append(c)
num_words.append(k)
num_words.append(t)
print num_words
Output:
[2, 4, 2, 2, 2, 2, 2]
From above output list, I want to calculate the total occurrence of word.
How can I get total count of fixed word and any other way to make this code easier?
You could utilize Counter:
from collections import Counter
s = 'aahkcreeatrhaaahkcreeatrha'
word = 'hackerearth'
wd = Counter(word)
sd = Counter(s)
print(min((sd.get(c, 0) // wd[c] for c in wd), default=0))
Output:
2
Above code will create two dict like counters where letters are keys and their occurrence are values. Then it will use generator expression to iterate over the letters found in the word and for each letter generate the ratio. min will pick the lowest ratio and default value of 0 is used for case where word is empty string.
When looking for a substring, you need to account for the character order, and not just the counts
something like this should work:
def subword(lookup,whole):
if len(whole)<len(lookup):
return 0
if lookup==whole:
return 1
if lookup=='':
return 1
if lookup[0]==whole[0]:
return subword(lookup[1:],whole[1:])+subword(lookup,whole[1:])
return subword(lookup,whole[1:])
For example:
In [21]: subword('hello','hhhello')
Out[21]: 3
Because you can choose each of the 3 hs and construct the word hello with the remainder

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())

Categories

Resources