Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Double Output when calling a function through another one

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

The confusing part: By using the function "count", i get the following program output: program output

As it can be seen, some outputs are duplicated(marked in red). How can this be avoided without removing the print from find? Is it possible or am I forced to remove it(the print)? I understand that these two functions can be made into a more simple one, but i want to understand how to call a function using another one.

I must also mention that the value of the variable count is the correct one. The only problems are the duplicated outputs.

The 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)
like image 705
Sorin Soare Avatar asked Nov 02 '15 15:11

Sorin Soare


1 Answers

There are two find() calls per iteration in the while loop:

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

Each time you print:

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

You should "memoize" by computing and storing the value of find() once:

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

This is a more elegant solution of 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."
like image 196
Sebastian Wozny Avatar answered Oct 21 '22 13:10

Sebastian Wozny