Double exit when calling a function through another

count calls the find function to find out how many times a letter can be found in a word starting at a given index (see "code" below).

The confusing part: Using the "count" function, I get the following program output: program output

As you can see, some outputs are duplicated (marked in red). How can this be avoided without removing the fingerprint from the search? Is it possible, or am I forced to remove it (seal)? I understand that these two functions can be turned into simpler ones, but I want to understand how to call a function using the other.

I should also mention that the value of the variable counter is correct. The only problems are duplicated outputs.

Code:

 def find(word, letter, index): start_ind = index while index < (len(word)): if word[index] == letter: print "%s found at index %s" % (letter, index) return index index += 1 else: print "%s is not found in string '%s' when starting from index %s" % (letter, word, start_ind) return -1 def count(word, letter, index): count = 0 while index < len(word): if find(word, letter, index) != -1: count += 1 index = find(word, letter, index) + 1 print "%s is shown %s times in '%s'" % (letter, count, word) count("banana", "a", 0) 
+5
source share
2 answers

In the while there are two calls to find() for each iteration:

  if find(word, letter, index)!= -1: count += 1 index = find(word, letter, index) + 1 

Every time you type:

 print "%s found at index %s" % (letter,index) 

You must "memoize" by evaluating and storing the find() value once :

  found = find(word, letter, index) if found != -1: count += 1 index = found + 1 

This is a more elegant solution to the problem:

 word = 'banana' letter = 'a' occurences = [(index, value) for index, value in enumerate(word) if value == letter] for occurence in occurences: print "Letter ",letter," has been found at index ",index print "Letter ", letter, " has been found a total of ", len(occurences), " times." 
+5
source

Update the account function as follows:

 def count(word,letter,index): count = 0 while index < len(word): index = find(word,letter,index) + 1 if index != 0: count+=1 
0
source

Source: https://habr.com/ru/post/1235029/


All Articles