Can anyone explain this code? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
3rd Nov 2018, 3:21 PM
Abhinav Singh
Abhinav Singh - avatar
5 Answers
+ 8
string.count(sub, i, i+len(sub)) is equivalent to string[i:i+len(sub)] == sub because slice length is never longer than sub length so it does somehing like this: find('abcabcd', 'abc') count += abc == abc count += bca == abc ... count += bcd == abc
3rd Nov 2018, 4:51 PM
Mert Yazıcı
Mert Yazıcı - avatar
+ 6
str.count(substr, start, end) returns non overlapping occurences of substr in str[start:end] this function returns all occurences including overlapping so 'aaa'.count('aa') returns 1 but this function returns 2
3rd Nov 2018, 4:28 PM
Mert Yazıcı
Mert Yazıcı - avatar
+ 1
The function basically counts the number of occurrences of another smaller string in a larger string: string = "this is a string" sub_string = "is" Number of occurrences = 2 # because there are two "is" in "this is a string" However I see no purpose of that implementation because str.count(substring) already returns the number of occurrences
3rd Nov 2018, 3:36 PM
jtrh
jtrh - avatar
0
Mert Yazıcı i know but how does the code do that can you please explain
3rd Nov 2018, 4:30 PM
Abhinav Singh
Abhinav Singh - avatar
0
thanks
3rd Nov 2018, 4:53 PM
Abhinav Singh
Abhinav Singh - avatar