0

I am working on a radix sort implementation that will sort a list of strings. It first compares the last character, then second to last, and so on using recursion. It returns the sorted list when it is done sorting off of the first character of the longest item.

if c == maxlength:
     print("returning")
     print(Out)
     return Out

The sorted list is stored in the Out list. The above code prints out the sorted list exactly how it should using Print(Out), but the function still returns None

Full code is below:

def grc(s, c):
    x = bytes(s, 'ascii')
    if c < len(s):
        temp = len(s) - (1 + c)
        return x[temp]
    elif c >= len(s):
        return x[0]

def radix(I, c = 0):
        Count = [0] * 128
        Out = [0] * len(I)

        for x in I:     #iterates over each item in the input array
            i = grc(x, c)
            Count[i] = Count[i] + 1

        for x in range(1, 128):
            Count[x] += Count[x-1]

        x = len(I) - 1
        while x >= 0:
            temp = I[x]
            tempbyte = grc(temp, c)
            Count[tempbyte] -= 1
            Out[Count[tempbyte]] = temp
            x -= 1
        
        maxlength = len(max(I, key=len)) - 1
        print("c: " + str(c) + ' Maxlen: ' + str(maxlength))
        if c == maxlength:
            print("returning")
            print(Out)
            return Out
        else:
            print("Recurring - current c: " + str(c))
            c += 1
            radix(Out, c)



def main():
    z = ['az', 'va', 'dc', 'zb', 'jb']
    result = radix(z)
    print(result)

if __name__ == '__main__':
    main()

  • 3
    When `if c == maxlength` evaluates to `False`, nothing is returned. That must be what's happening. Have you stepped through the program in a debugger to check why that's happening? – Random Davis Sep 14 '21 at 18:34
  • I know for a fact that isn't happening because the `print(Out)` still occurs . Also the `c` value is incremented from 0 so it will always eventually equal `maxlength` – Jack Hammer Sep 14 '21 at 18:36
  • 3
    `radix(Out, c)` should be `return radix(Out, c)`. Recursive function calls must `return` their value. – Axe319 Sep 14 '21 at 18:37
  • That did it Axe319. Thank you! – Jack Hammer Sep 14 '21 at 18:39
  • 1
    Random Davis has the correct assessment. Also, your other function can also exit without returning a value. I searched on Stack Overflow for 'Check whether all control flow paths return a value' and saw only non-Python posts, so that may be a worthwhile follow up post. – kcsquared Sep 14 '21 at 18:39

0 Answers0