Reputation: 311
Return the number of times that the string "hi"
appears anywhere in the given string.
count_hi('abc hi ho') # → 1
count_hi('ABChi hi') # → 2
count_hi('hihi') # → 2
I have this solution with me;
def count_hi(str):
return str.count("hi")
But I am looking for a solution using a given hint: Use the for i in range(len(str)-1):
loop to look at each index in the string, except the last. For each i
, extract the string starting at i
and up to but not including i+2
. Check if that string is "hi"
, and count how many times that happens.
I even tried this solution, but doesn't pass all the test cases:
def count_hi(str):
count = 0
for char in str:
if char == 'hi':
count += 1
return count
Upvotes: 1
Views: 11253
Reputation: 1195
def count_hi(str):
my_list = []
for each in range(len(str) - 1):
if str[each] == "h":
next_item = str[each + 1]
my_list.append(str[each] + next_item)
total = my_list.count("hi")
return total
Upvotes: 0
Reputation: 1
def count_hi(str1):
#use the replace method to replace all spaces
str1 = list(str1.replace(' ',''))
print(str1)
'''define a counter variable that increments by one everytime the if cond
is met'''
count = 0
for i in range(len(str1)-1):
if str1[i] == "h" and str1[i+1] == "i":
count += 1
return count
Upvotes: 0
Reputation: 11
def count_hi(str):
len_w = len(str)
txt = str.replace("hi", "")
len_wo = len(txt)
return (len_w- len_wo)/2
Upvotes: 0
Reputation: 9
public int countHi(String str) {
int count = 0;
for( int i = 0 ; i < str.length()-1 ; i++){
if ( str.substring(i , i+2).equals("hi"))
count = count + 1;
}
return count;
}
Upvotes: -1
Reputation: 4155
You can split the string:
string = 'hire test foo hi bar high'
split_string = [[item]+['hi'] for item in string.split('hi') if item != ""]
split_string = sum(split_string, [])
And use a for
loop to count the matching strings:
string_count = 0
for item in range(len(split_string)):
if split_string[item] == 'hi':
string_count += 1
Or, you can skip the for
loop and directly count the list:
split_string.count('hi') # returns 3
Upvotes: 1
Reputation: 113864
Here is one version:
def count_hi(s):
count = 0
for i in range(len(s)-1):
count += s[i]=='h' and s[i+1]=='i'
return count
Here is another:
def count_hi2(s):
count = 0
for i in range(len(s)-1):
count += s[i:i+2] == 'hi'
return count
Consider this code fragment:
for char in str:
if char == 'hi':
This loops through the individual characters in the string str
. Thus, in this loop, char
is always one single character. Consequently, it will never be equal to two characters.
Also, it best practice to use a different name for strings: str
is a builtin. Python will let you freely overwrite builtins but a consequence is that you will lose easy access them.
Upvotes: 4