counting number of occurrence in string - python

I'm trying to count the number of times "bob" has occurred in a given string. this is what I tried:
s = input("give me a string:")
count = 0
for i in s:
if i=="b":
for j in s:
x=0
if j!="b":
x+=1
else:
break
if s[x+1]=="o" and s[x+2]=="b":
count+=1
print(count)
if I give the string "bob", it gives back 2, and if I give something like "jbhxbobalih", it gives back 0. I don't know why this happens. any idea?

The easiest manual count would probably use indeces and slices. The main difference between this and the much simpler s.count("bob") is that it also counts overlapping occurrences:
# s = "aboboba" -> 2
count = 0
for i, c in enumerate(s):
if s[i:i+3] == "bob":
count += 1

You can try checking 3 consecutive characters, if they are 'bob', just add our counter up, and do nothing otherwise.
Your code should be like this:
s = input("give me a string:")
count = 0
for i in range(0, len(s) - 3):
if s[i] == 'b' and s[i + 1] == 'o' and s[i + 2] == 'b':
count += 1
print(count)

100 % working this will work for all string.
import re
def check(string, sub_str):
count = 0
val = re.findall(sub_str, string)
for i in val:
count+=1
print(count)
# driver code
string = "baadbobaaaabobsasddswqbobdwqdwqsbob"
sub_str = "bob"
check(string, sub_str)
This gives the correct output.

Related

how to get just one character form a string contained in a list

I'm trying to compare each character of the string num with each digit of the strings contained in computer_guesses.
I must use the numbers as strings.
I tried to run this code but the output was:
0
0
0
0
0
0
0
0
0
0
Process finished with exit code 0
Probably i'm just missing the syntax, i'm sure that it can be made without using the function split(word) .
def split(word):
return [char for char in word]
computer_guesses = ["12345", "67890"]
num = "23648"
correct = 0
for x in range(len(computer_guesses)):
for y in range(len(computer_guesses[x])):
if num[y] == split(computer_guesses[x]):
correct += 1
print(correct)
else:
print(correct)
You can use enumerate for iterating on iterable with index counting.
computer_guesses = ["12345", "67890"]
num = "23648"
correct = 0
for guess in computer_guesses:
for idx, digit in enumerate(guess):
if num[idx] == digit:
correct += 1
print(correct)
else:
print(correct)
This can be one approach for your problem:
def split(num,word):
num = num
default = [char for char in num]
wd = [char for char in word]
correct = 0
for m in range(len(wd)):
if default[m]==wd[m]:
correct += 1
return correct
computer_guesses = ["12345", "67890"]
num = "23648"
for x in range(len(computer_guesses)):
print(split(num, computer_guesses[x]))
from my vision the wrong part in code it's 'if condition' side
if num[y] == split(computer_guesses[x]):
i switch it to :
if num[y] == computer_guesses[x][y]:
and the code working , i hope that what you looking for

How do I count the number of capital letters using a while loop

s = input()
i = 0
while i < len(s) and (s[i]) < "A" or "Z" < s([i]):
print(i)
I keep getting this wrong and I'm not sure what to do. I Do not want to use a for loop just a while loop. Thank you
You can do it by many ways.
If I were you I will do it using isupper() and sum() generator,
s = input("Type something...")
print(sum(1 for c in s if c.isupper()))
Using while as you asked,
s = input("Type something...")
i = 0
capital = 0
while i < len(s):
if s[i].isupper():
capital+=1
i = i + 1
print(capital)
Your while loop is currently written such that it will terminate at the first lowercase letter. You need the loop to go over the entire string, but keep count of uppercase letters as it goes.
s = input()
i = 0
c = 0
while i < len(s):
if "A" <= s[i] <= "Z":
c = c + 1 # c only goes up on capital letters
i = i + 1 # i goes up on every letter
print(i, c)
print(f"Capital letters: {c}")
An easier method is to use the sum function along with isupper:
s = input()
print(f"Capital letters: {sum(c.isupper() for c in s)}")
You are using the while for both the limit and the counting which won't work.
You have to use the while for the limit and an if for the counting:
s = input()
i = 0
count = 0
while i < len(s):
print(i)
if "A" <= s[i] <= "Z":
count += 1
i = i + 1
print(f'Capitals in "{s}" = {count}')
However, this code is very complicated and better is the answer from #AlwaysSunny or the comment from #Samwise
def Capital(In):
return sum([l.isupper() for l in In])
print(Capital(input()))
Try use this:
text = input()
count=0
for letter in text:
if letter == letter.upper():
count+=1
print(letter, end=" ")
print(count-1)
I hope I have explained clearly)

How to count specific substrings using slice notation

I want to count the number of occurrences of the substring "bob" within the string s. I do this exercise for an edX Course.
s = 'azcbobobegghakl'
counter = 0
numofiterations = len(s)
position = 0
#loop that goes through the string char by char
for iteration in range(numofiterations):
if s[position] == "b": # search pos. for starting point
if s[position+1:position+2] == "ob": # check if complete
counter += 1
position +=1
print("Number of times bob occurs is: " + str(counter))
However it seems that the s[position+1:position+2] statement is not working properly. How do i adress the two chars behind a "b"?
The second slice index isn't included. It means that s[position+1:position+2] is a single character at position position + 1, and this substring cannot be equal to ob. See a related answer. You need [:position + 3]:
s = 'azcbobobegghakl'
counter = 0
numofiterations = len(s)
position = 0
#loop that goes through the string char by char
for iteration in range(numofiterations - 2):
if s[position] == "b": # search pos. for starting point
if s[position+1:position+3] == "ob": # check if complete
counter += 1
position +=1
print("Number of times bob occurs is: " + str(counter))
# 2
You could use .find with an index:
s = 'azcbobobegghakl'
needle = 'bob'
idx = -1; cnt = 0
while True:
idx = s.find(needle, idx+1)
if idx >= 0:
cnt += 1
else:
break
print("{} was found {} times.".format(needle, cnt))
# bob was found 2 times.
Eric's answer explains perfectly why your approach didn't work (slicing in Python is end-exclusive), but let me propose another option:
s = 'azcbobobegghakl'
substrings = [s[i:] for i in range(0, len(s))]
filtered_s = filter(substrings, lambda s: s.startswith("bob"))
result = len(filtered_s)
or simply
s = 'azcbobobegghakl'
result = sum(1 for ss in [s[i:] for i in range(0, len(s))] if ss.startswith("bob"))

Counting e's in a string, using for loop [duplicate]

I am trying to write a program to count the occurrences of a specific letter in a string without the count function. I made the string into a list and set a loop to count but the count is never changing and i cant figure out why. This is what I have right now:
letter = 'a'
myString = 'aardvark'
myList = []
for i in myString:
myList.append(i)
count = 1
for i in myList:
if i == letter:
count == count + 1
else:
continue
print (count)
Any help is greatly appreciated.
Be careful, you are using count == count + 1, and you must use count = count + 1
The operator to attribute a new value is =, the operator == is for compare two values
Instead of
count == count + 1
you need to have
count = count + 1
Although someone else has solved your problem, the simplest solution to do what you want to do is to use the Counter data type:
>>> from collections import Counter
>>> letter = 'a'
>>> myString = 'aardvark'
>>> counts = Counter(myString)
>>> print(counts)
Counter({'a': 3, 'r': 2, 'v': 1, 'k': 1, 'd': 1})
>>> count = counts[letter]
>>> print(count)
3
Or, more succinctly (if you don't want to check multiple letters):
>>> from collections import Counter
>>> letter = 'a'
>>> myString = 'aardvark'
>>> count = Counter(myString)[letter]
>>> print(count)
3
The simplest way to do your implementation would be:
count = sum(i == letter for i in myString)
or:
count = sum(1 for i in myString if i == letter)
This works because strings can be iterated just like lists, and False is counted as a 0 and True is counted as a 1 for arithmetic.
Use filter function like this
len(filter(lambda x: x==letter, myString))
Your count is never changing because you are using == which is equality testing, where you should be using = to reassign count.
Even better, you can increment with
count += 1
Also note that else: continue doesn't really do anything as you will continue with the next iteration of the loop anyways. If I were to have to come up with an alternative way to count without using the count function, I would lean towards regex:
import re
stringy = "aardvark"
print(len(re.findall("a", stringy)))
Apart from the above methods, another easiest way is to solve the problem by using the python dictionary
word="purple"
dic={}
for letter in word:
if letter in dic:
dic[letter]+=1
else:
dic[letter]=1
print(dic)
{'p': 2, 'u': 1, 'r': 1, 'l': 1, 'e': 1}
In case if you want to count the occurences of a particular character in the word.we can get that it by following the below mentioned way,
dic['p']
2
Your code logic is right except for considering count == 1 while using count == 1 you are comparing if count == 1 and count = 1 is for assigning and count += 1 is for incrementing.
Probably you know this, you might have got confused
also, you have to initialize count = 0
letter = 'a'
myString = 'aardvark'
myList = []
for i in myString:
myList.append(i)
count = 0
for i in myList:
if i == letter:
count +=1
else:
continue
print(count)

Determining how many times a substring occurs in a string in Python

I am trying to figure out how many times a string occurs in a string. For example:
nStr = '000123000123'
Say the string I want to find is 123. Obviously it occurs twice in nStr but I am having trouble implementing this logic into Python. What I have got at the moment:
pattern = '123'
count = a = 0
while pattern in nStr[a:]:
a = nStr[a:].find(pattern)+1
count += 1
return count
The answer it should return is 2. I'm stuck in an infinite loop at the moment.
I was just made aware that count is a much better way to do it but out of curiosity, does anyone see a way to do it similar to what I have already got?
Use str.count:
>>> nStr = '000123000123'
>>> nStr.count('123')
2
A working version of your code:
nStr = '000123000123'
pattern = '123'
count = 0
flag = True
start = 0
while flag:
a = nStr.find(pattern, start) # find() returns -1 if the word is not found,
#start i the starting index from the search starts(default value is 0)
if a == -1: #if pattern not found set flag to False
flag = False
else: # if word is found increase count and set starting index to a+1
count += 1
start = a + 1
print(count)
The problem with count() and other methods shown here is in the case of overlapping substrings.
For example: "aaaaaa".count("aaa") returns 2
If you want it to return 4 [(aaa)aaa, a(aaa)aa, aa(aaa)a, aaa(aaa)] you might try something like this:
def count_substrings(string, substring):
string_size = len(string)
substring_size = len(substring)
count = 0
for i in xrange(0,string_size-substring_size+1):
if string[i:i+substring_size] == substring:
count+=1
return count
count_substrings("aaaaaa", "aaa")
# 4
Not sure if there's a more efficient way of doing it, but I hope this clarifies how count() works.
import re
pattern = '123'
n =re.findall(pattern, string)
We can say that the substring 'pattern' appears len(n) times in 'string'.
In case you are searching how to solve this problem for overlapping cases.
s = 'azcbobobegghaklbob'
str = 'bob'
results = 0
sub_len = len(str)
for i in range(len(s)):
if s[i:i+sub_len] == str:
results += 1
print (results)
Will result in 3 because: [azc(bob)obegghaklbob] [azcbo(bob)egghaklbob] [azcbobobegghakl(bob)]
I'm pretty new, but I think this is a good solution? maybe?
def count_substring(str, sub_str):
count = 0
for i, c in enumerate(str):
if sub_str == str[i:i+2]:
count += 1
return count
string.count(substring) is not useful in case of overlapping.
My approach:
def count_substring(string, sub_string):
length = len(string)
counter = 0
for i in range(length):
for j in range(length):
if string[i:j+1] == sub_string:
counter +=1
return counter
You are not changing a with each loop. You should put:
a += nStr[a:].find(pattern)+1
...instead of:
a = nStr[a:].find(pattern)+1
def count_substring(string, substring):
c=0
l=len(sub_string)
for i in range(len(string)):
if string [i:i+l]==sub_string:
c=c+1
return c
string=input().strip()
sub_string=input().strip()
count= count_substring(string,sub_string)
print(count)
As mentioned by #João Pesce and #gaurav, count() is not useful in the case of overlapping substrings, try this out...
def count_substring(string, sub_string):
c=0
for i in range(len(string)):
if(string[i:i+len(sub_string)]==sub_string):
c = c+1
return c
def countOccurance(str,pat):
count=0
wordList=str.split()
for word in wordList:
if pat in word:
count+=1
return count
Usually i'm using enumerate for this kind of problems:
def count_substring(string, sub_string):
count = 0
for i, j in enumerate(string):
if sub_string in string[i:i+3]:
count = count + 1
return count
def count(sub_string,string):
count = 0
ind = string.find(sub_string)
while True:
if ind > -1:
count += 1
ind = string.find(sub_string,ind + 1)
else:
break
return count
def count_substring(string, sub_string):
count = 0
len_sub = len(sub_string)
for i in range(0,len(string)):
if(string[i:i+len_sub] == sub_string):
count+=1
return count

Categories