0

I am trying to write a recursion function in python and after certain call it throws index out of bound. However, I am no able to undestand why?

Could someone help me understand ?

def find_combinations(str, remaining_char=""):
    print("find_combinations(%s, %s)" % (str, remaining_char))

    if len(str) == 0:
        print(remaining_char)
    else:

        for i in range(len(str)):
            chr = str[i] # at this line it shows index out of bound 
            remaining_char = remaining_char+chr
            str = str[1:]

            find_combinations(str, remaining_char)

find_combinations("ABCD")

Error:

find_combinations(BCD, A)
find_combinations(CD, AB)
find_combinations(D, ABC)
find_combinations(, ABCD)
ABCD
...
...
    chr = str[i]
IndexError: string index out of range
4
  • If you shorten str but keep iterating up to the length of the original str of course you'll go out of bounds. Commented Apr 18, 2019 at 23:14
  • Do you want permutations or combinations? Commented Apr 19, 2019 at 0:11
  • @DeveshKumarSingh Permutation. Sorry for wrong method name. Commented Apr 19, 2019 at 1:07
  • In that case, it is a one liner, check my answer below! Commented Apr 19, 2019 at 1:10

4 Answers 4

2

First of all, rename your string and char. Right now you're overloading str() and chr()

Your error comes from the fact that once you have removed things from the string, indexes matching the latter values in its old length will no longer be availible

def find_combinations(strz, remaining_char=""):
    print("find_combinations(%s, %s)" % (strz, remaining_char))

    if not strz:
        print(remaining_char)
    else:

        for i in range(len(strz)):
            print(i)
            print(strz)
            chrz = strz[i] # at this line it shows index out of bound
            remaining_char = remaining_char+chrz
            strz = strz[1:]

            find_combinations(strz, remaining_char)

find_combinations("ABCD")

outputs

find_combinations(ABCD, )
0
find_combinations(BCD, A)
0
find_combinations(CD, AB)
0
find_combinations(D, ABC)
0
find_combinations(, ABCD)
ABCD
1

As you can see, list index 1 is out of range

Sign up to request clarification or add additional context in comments.

Comments

0

Look at what you're doing: consider a string of 4 chars.

    for i in range(len(str)):
        chr = str[i] 
        str = str[1:]

i str


0 ABCD 1 ABC 2 AB ... and the next time you try to access str[i], the string is too short.

Keep the original string intact; send just the truncated one into the recursion:

    for i in range(len(s)):
        chr = s[i] 
        remaining_char += chr
        find_combinations(s[1:], remaining_char)

You still have logic problems in your program, but this will get you through the next step. I strongly recommend that you do three things:

  1. See this lovely debug blog for help.
  2. Use incremental programming -- write just 2-4 lines at a time, one small chunk of code. Make sure that they work before continuing. Part of the reason that you're needing so many SO questions is that you've introduced multiple errors into your function before testing. You can't easily isolate the cause of trouble when you have several causes waiting to bite you
  3. Research on line the ways that others have solved this problem; their guidance will likely be helpful in smoothing the remaining problems in your code.

Comments

0

You don't need the for line. You can remove it.

Just replace the chr = str[i] with chr = str[0], and rename your variables as said in previous posts (chr and str).

It will do what you want.

Comments

0

You can always use itertools.permutations which is a python provided function. The example below generates permutations taking all 4 characters in account

import itertools as it
words = list('ABCD')
print(list(it.permutations(words, 4)))
'''[('A', 'B', 'C', 'D'), ('A', 'B', 'D', 'C'), ('A', 'C', 'B', 'D'), 
('A', 'C', 'D', 'B'), ('A', 'D', 'B', 'C'), ('A', 'D', 'C', 'B'), 
('B', 'A', 'C', 'D'), ('B', 'A', 'D', 'C'), ('B', 'C', 'A', 'D'), 
('B', 'C', 'D', 'A'), ('B', 'D', 'A', 'C'), ('B', 'D', 'C', 'A'),
('C', 'A', 'B', 'D'), ('C', 'A', 'D', 'B'), ('C', 'B', 'A', 'D'),
 ('C', 'B', 'D', 'A'), ('C', 'D', 'A', 'B'), ('C', 'D', 'B', 'A'), 
('D', 'A', 'B', 'C'), ('D', 'A', 'C', 'B'), ('D', 'B', 'A', 'C'), 
('D', 'B', 'C', 'A'), ('D', 'C', 'A', 'B'), ('D', 'C', 'B', 'A')]'''

print(list(it.permutations(words, 2)))
#[('A', 'B'), ('A', 'C'), ('A', 'D'), ('B', 'A'), ('B', 'C'), 
#('B', 'D'), ('C', 'A'), ('C', 'B'), ('C', 'D'), ('D', 'A'), ('D', 'B'), ('D', 'C')]

Comments

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.