Output each character of the string in turn by recursion and slicing, but my code doesn't have any output

Viewed 20

Here's my code

a = '94050'
i = 0
j = 1
b = []

def f(i,j):
    if j <= len(a) and i < len(a):
        b.append(a[i:j])
    else:
        print(b)
    i = i + 1
    j = j + 1
    f(i,j)

Just beginning to learn; Not to understand what went wrong.I hope I can get your help!

1 Answers

Below an approach using slicing and recursion:

a = '94050'
def f(a):
   if len(a)>1:
       print(a[0])
       f(a[1:])
   else:
       print(a[0])
f(a)

giving following output

9
4
0
5
0

The only problem with your own code is that you have forgot to return from the function if the printout is done continuing recursion until the script fails with an RecursionError. Adding return after the print solves the problem:


a = '94050'
i = 0
j = 1
b = []
def f(i,j):
    print(f'start f(i,j): {i=} {j=}')
    if j <= len(a) and i < len(a):
        print(f'next: b.append(a[{i}:{j}])')
        b.append(a[i:j])
    else:
        print('else: if j<= len(a)')
        print(b)
        print('b printed, RETURN')
        return # <<< print is done, RETURN
    i = i + 1
    j = j + 1
    f(i,j)

f(i,j)

giving:


start f(i,j): i=0 j=1
next: b.append(a[0:1])
start f(i,j): i=1 j=2
next: b.append(a[1:2])
start f(i,j): i=2 j=3
next: b.append(a[2:3])
start f(i,j): i=3 j=4
next: b.append(a[3:4])
start f(i,j): i=4 j=5
next: b.append(a[4:5])
start f(i,j): i=5 j=6
else: if j<= len(a)
['9', '4', '0', '5', '0']
b printed, RETURN

And if you have understood the pattern of the code I have given at the beginning the right version of your code would be to stop recursive calls when the else: statement is reached:

def f(i,j):
    if j <= len(a) and i < len(a):
        b.append(a[i:j])
        i = i + 1
        j = j + 1
        f(i,j)
    else:
        print(b)
f(i,j)
Related