2

In the following the code (from udacity course CS-101), I am trying to create a huge index on the same lines as done in the course lecture. Here, the input to the make_big_index - size limits the number of entries in the list - index. However, whenever I run the code, the while loop seems to run infinitely, without termination. The termination condition- len(index) < size, seems to pass every time, even though len(index) > size.

I have tried the pdb.settrace() option and step by step debugging shows that even though input size = 3, the loop continues and never exits.

import pdb, sys

def add_to_index(index, keyword, url):
    for entry in index:
        if entry[0]== keyword:
            entry[1].append(url)
            return
    index.append([keyword, [url]])
    return

def make_string(p):
    s=""
    for e in p:
        s=s+e
    return s


def make_big_index(size):
    index=[]
    letters = ['a','a','a','a','a','a','a','a']
    pdb.set_trace()
    while len(index) < size:
        word = make_string(letters)
        add_to_index(index, word, 'fake')
        print index
        for i in range(len(letters)-1, 0, -1):
            if letters[i] < 'z':
                letters[i] = chr(ord(letters[i])+1)
                break
            else:
                letters[i]='a'

##    return index

def main():
    size=raw_input('>size: ')
    make_big_index(size)

if __name__ == '__main__':
    main()

1 Answer 1

3

size is a string, since you are taking its input as -

size=raw_input('>size: ')
make_big_index(size)

In Python 2.x, strings are always greater than int (any int) , and hence that is why the loop never ends. Example to show this -

>>> '1' > 9999999999999999999999999999999
True

Convert it to a int when taking the input , Example -

size=int(raw_input('>size: '))
make_big_index(size)
Sign up to request clarification or add additional context in comments.

1 Comment

I had been stuck on this for quite a while and tried to debug all possible flaws. Thank You!!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.