Finding a 'hello' word in a different string, which it has 'hello' in it
I should find a 'hello' word in a string, which I gave it from input too .I wrote this code by looking at the answer that someone gave to the below link's question.
firststring = input() #ahhellllloou
to_find = "hello"
def check_string(firststring, to_find):
c = 0
for i in firststring:
#print(i)
if i == to_find[c]:
c += 1
if c == len(to_find):
return "YES"
return "NO"
print(check_string(firststring, to_find))
but I don't want to use a def to solve the problem.
hello = "hello"
counter_hello = 0
bool_hello = False
for letter in string:
if letter == hello[counter_hello]:
counter_hello += 1
if counter_hello == len(hello):
bool_hello = True
if bool_hello == True:
print("YES")
else:
print("NO")
for hello string it works correct. also for pnnepelqomhhheollvlo.
but when I give it ahhellllloou it doesn't work.
I can't see where the bug is.
Your code is not the same. The return statement needs to be accounted for by breaking the loop
string = "ahhellllloou"
to_find = "hello"
match = False
c = 0
for i in string:
if i == to_find[c]:
c += 1
if c == len(to_find):
match = True
break
print("YES" if match else "NO")
Note that a loop isn't needed
>>> import re
>>> m = re.search('.*'.join('hello'), 'ahhellllloou')
>>> m is not None
True
>>> m = re.search('.*'.join('hello'), 'ahhellllliu')
>>> m is None
True
counter_hello = 0
bool_hello = False
for letter in 'ahhellllloou':
#print('letter: ', letter);
#print(hello[counter_hello])
if letter == hello[counter_hello] and counter_hello != len(hello) - 1:
counter_hello += 1
if counter_hello == len(hello) - 1:
bool_hello = True
if bool_hello == True:
print("YES")
else:
print("NO")
I want to count the number of times both a and b occur, in both strings together, using recursion in Python.
For example, if the input was ('aabb', 'bbba'), the output would be (3,5) because there are three a's and five b's total.
What I have tried:
def counting(string1, string2):
if not string1:
return 0
elif string1[0]=='a':
return 1+counting(string[1:],string2)
else:
return counting(string[1:],string2)
def counting(string1, string2):
def counting_recurse(string_total):
if not string_total:
return (0, 0)
elif string_total[0]=='a':
a_count, b_count = counting_recurse(string_total[1:])
return (1+a_count, b_count)
elif string_total[0]== 'b':
a_count, b_count = counting_recurse(string_total[1:])
return (a_count, b_count +1 )
else:
return counting_recurse(string_total[1:])
return counting_recurse(string1 + string2)
This works on your example. Does this solve your scenario?
You can recurse until both strings are empty.
def counting(string1, string2):
if string1 or string2:
a, b = counting(string1 and string1[1:], string2 and string2[1:])
count = lambda x: (string1 and string1[0] == x or 0) + (string2 and string2[0] == x or 0)
return (a + count('a'), b + count('b'))
return (0, 0)
print(counting('aabb', 'bbba'))
This seems like a simpler solution
Explanation
If you've reached end of string, then return (0,0) for a count and b count
Otherwise, you add 1 + a_count if first character is a otherwise you add 0 + a_count.
Similarly, you add 1 + b_count if first character is b otherwise you add 0 + b_count.
a_count is defined as the first value in tuple(), b_count is the second value()
def counting_recurse(combine_string):
if not combine_string:
return (0, 0)
return (int(combine_string[0]=='a') +counting_recurse(combine_string[1:])[0],
int(combine_string[0]=='b') +counting_recurse(combine_string[1:])[1])
string1 = 'aabb'
string2 = 'bbba'
counting_recurse(string1+string2)
Output
(3, 5)
def counting(stri, char):
if len(stri) == 0:
return 0
elif stri[0] == char:
return 1 + counting(stri[1:], char)
else:
return counting(stri[1:], char)
def count(str1, str2):
return (counting(str1,'a'),counting(str2,'b'))
print("aabb","bbba")
Looks like having two strings as arguments to the function is unnecessarily complicated, since you count across both strings anyway. So why not simply define the recursive function for a single string and call it on the concatenation of the two strings you're interested in, e.g.
def count_ab(s):
if not s:
return 0, 0
first_a = int(s[0] == 'a')
first_b = int(s[0] == 'b')
further_a, further_b = count_ab(s[1:])
return first_a + further_a, first_b + further_b
count_ab('aabb' + 'bbba')
(3, 5)
The following works:
def non_recursive_imp2(*args: str) -> tuple:
sargs = tuple(map(str, args))
a_count = 0
b_count = 0
for sarg in sargs:
for ch in sarg:
if ch == "a":
a_count += 1
elif ch == "b":
b_count += 1
return (a_count, b_count)
import operator
def recursive_count(inpuht:str, _:str):
inpuht += _
if len(inpuht) < 2:
if inpuht == "a":
return (1, 0)
elif inpuht == "b":
return (0, 1)
return (0, 0)
else:
left_str = inpuht[:len(inpuht)//2]
right_str = inpuht[len(inpuht)//2:]
left_count = recursive_count(left_str, "")
right_count = recursive_count(right_str, "")
return tuple(map(operator.add, left_count, right_count))
However, it is easier to write code for a non-recursive implementation:
NON-RECURSIVE IMPLEMENTATIONS:
def non_recursive_imp(x:str, y:str) -> tuple:
merged = x + y
a_count = 0
b_count = 0
for ch in merged:
if ch == "a":
a_count +=1
elif ch == "b":
b_count +=1
return (a_count, b_count)
I want to get the middle letter of a word, but I want the result to print as a string. How can I do so?
def get_middle(word):
a = int(len(word))
b = int(len(word)/2)
c = int(len(word)/2 - 1)
d = int(len(word)/2 - 0,5)
if a%2==0:
print(str(word[b] + word[c]))
elif a%2==1:
print(str(word[d]))
else:
print("That's not a sring!")
def get_middle(word):
if len(word)%2 == 1:
return word[:int((len(word)-1)/2)]+word[int((len(word)-1)/2)+1:]
I'm trying to create a function to evaluate if contains exactly one of each of the 5 vowels.
I've tried so far: (I don't know how can I limit now for only 1 of each vowel)
def isVowel(char): #=> Helper function
return len(char) == 1 and char.lower() in 'aeiou'
def fiveVowelsOneOfEach(word):
oneVowelOfEachCounter = 0
for char in word:
if isVowel(char):
if char == 'a':
oneVowelOfEachCounter += 1
if char == 'e':
oneVowelOfEachCounter += 1
if char == 'i':
oneVowelOfEachCounter += 1
if char == 'o':
oneVowelOfEachCounter += 1
if char == 'u':
oneVowelOfEachCounter += 1
if oneVowelOfEachCounter == 5:
return True
Just do:
s = 'aeiou'
s2 = 'aaeiou'
def checker(s):
return all(s.lower().count(i)==1 for i in 'aeiou')
print(checker(s))
print(checker(s2))
Output:
True
False
That's all needed, checking if the counts of each vowel is one
A simpler way of doing it
goodstr = 'aeiou'
badstr = 'aaeiou'
vowels = ['a','e','i','o','u'] # or a string "aeiou"
def fiveVowelsIsOneOfEach(word):
for vowel in vowels:
if word.count(vowel) != 1:
return False
return True
print(fiveVowelsIsOneOfEach(goodstr)) # returns True
print(fiveVowelsIsOneOfEach(badstr)) # returns False
def fiveVowelsOneOfEach(word):
oneVowelOfEachCounter = 0
vowels = list('aeiou')
dummy_vowels = list(chars)
for char in word:
if char in vowels:
vowels.remove(char)
continue
elif char in dummy_vowels:
return False
if len(vowels) == 0:
return True
return False
This should work. the trick is to use a list and a dummy list to make sure each vowel is only counted once.
Updated answer to address the issues in the question. Also added a version that does not use counter.
from collections import Counter
word = 'aaeiuo'
vowels = 'aeiuo'
c = Counter(word)
vowel_count = sum([1 if c[vowel] > 0 else 0 for vowel in vowels])
print(vowel_count) # 5
#without using counter
vowel_count = sum([1 if word.count(vowel) > 0 else 0 for vowel in vowels])
print(vowel_count) # 5
So what the task is, is that your supposed to write a recursion function that counts the amount of "double" letters in a string, So for example the string "hmmm" would return 1 and the string "hmmmm" would return 2 and that a string "abb" would return 1. My code is here:
def num_double_letters(astr):
if astr == "" or len(astr) == 1:
return 0
elif len(astr) == 2:
if astr[0] == astr[1]:
return 1 + num_double_letters(astr[1:])
else:
return 0 + num_double_letters(astr[1:])
elif astr[0] != astr[1]:
return 0 + num_double_letters(astr[1:])
elif astr[0] == astr[1] != astr[2]:
return 1 + num_double_letters(astr[1:])
elif astr[0] == astr[1] == astr[2]:
return 0 + num_double_letters(astr[1:])
My problem is that a string with 4 same letters = 1 when its supposed to = 2. And also is there a cleaner way to do this?
I think you've made it a bit complicated for yourself... there's no need to go deeper into the recursion once the length of your string is 2, and you want to advance by 2, not 1 when you find a double to count the way I think you do. Try this:
def num_double_letters(astr):
if astr == "" or len(astr) == 1:
return 0
elif len(astr) == 2:
if astr[0] == astr[1]:
return 1
else:
return 0
elif astr[0] != astr[1]:
return 0 + num_double_letters(astr[1:])
elif astr[0] == astr[1]:
return 1 + num_double_letters(astr[2:])
print(num_double_letters('hmm'))
print(num_double_letters('hmmm'))
print(num_double_letters('hmmmm'))
Output:
1
1
2
You might consider the following more Pythonic and concise:
def num_double_letters(astr):
if len(astr) < 2:
return 0
if astr[0] == astr[1]:
return 1 + num_double_letters(astr[2:])
return num_double_letters(astr[1:])