-1

Trying a solution for "Return the total count of string "Emma" appears in the given string: I wrote the following code which works fine:

string = 'Emma is a good developer. Emma is a writer'
x = string.count('Emma')
print (f'Emma appeared {x} times')

However, there is an alternative code (below) that also work but I don't seem to be able to understand how it works. Can you please explain how exactly is the code working: For example why do we need to take range at len(statement -1) what does the code count += statement[i: i + 4] == 'Emma' do exactly?:

def count_jhon(statement):
    print("Given String: ", statement)
    count = 0
    for i in range(len(statement) - 1):
        count += statement[i: i + 4] == 'Emma'
    return count

count = count_jhon("Emma is good developer. Emma is a writer")
print("Emma appeared ", count, "times")
martineau
  • 119,623
  • 25
  • 170
  • 301
Haseeb Haque
  • 25
  • 1
  • 1
  • 5
  • Please show your attempts to trace the operation of this code, and focus on the points you don't understand. I supplied a link to Python slicing (Stack Overflow avoids redundant tutorial information). For the loop limit, try moving that value by one in each direction; how do those change the program operation? How do the intermediate values change? Insert `print` statements and watch! :-) – Prune Apr 16 '20 at 23:40
  • were you going to include a link to Python slicing ? – Haseeb Haque Apr 17 '20 at 00:01
  • I already did: look at the top, in the blue closure box. – Prune Apr 17 '20 at 00:06

1 Answers1

2

statement[i:i+4] finds a substring from statement that starts at index i and ends at index 1 lower than i+4. So it contains characters at index i, i+1, i+2, and i+3, a total of 4 characters. If those 4 characters grouped equals Emma, then you have a match.

I will list some of the possible values statement[i:i+4] will produce that can then be compared with 'Emma'. Starting that first line, i = 0. For each progressive line, i = i + 1 (so the line with "mma " has i = 1). You will notice each line has 4 characters (a space counts as a character)

Emma #match
mma 
ma i
a is
 is 
is a
s a 
 a g
a go
 goo
good
ood 
od d
d de
 dev
deve
evel
velo
elop
lope
oper
per.
er. 
r. E
. Em
 Emm
Emma #match
mma 
ma i
... so on
Sri
  • 2,281
  • 2
  • 17
  • 24
  • thanks I understand - however will this not just group the first 4 character and then the next 4 characters and so on ? since the string starts with the work 'Emma' then it will return first instance of Emma but then the second instance of 'Emma' will only be returned if the total number of characters before it are divisible by 4. At least this is what I understand. However the code works regardless - what am I missing – Haseeb Haque Apr 17 '20 at 21:35
  • I am not sure what divisible by 4 means. But you give you a slightly better understanding, I will update my answer with several comparisons in the order the program will run – Sri Apr 17 '20 at 21:40