The general trick to doing something recursively is to take all the variables and turn them into parameters and change all assignments to function calls. You may need more than one function for more complex things, but usually you can easily flip each loop into a tail-recursive function :
function(){ int i=0; int x=0;
becomes
function(i,x){ //variables are now parameters if(condition){ return x; }else{ return function(i+1, x+i); //update } } main(){ function(0,0); //initialize
================
Here is the duplicate removal code, for example, for example (it does not do the same as yours)
removeDuplicates(str): i = str.length-1; out_str = ""; chars_used = [] while(i >= 0): c = str[i] if(c not in chars_used): chars_used.append(c) out_str += c i -= 1 return out_str
becomes
remove_duplicates(str, i, out_str, chars_used): if i < 0: return out_str else: c = str[i] if c in chars_used: return remove_duplicates(str, i-1, out_str, chars_used) else: return remove_duplicates(str, i-1, out_str+c, chars_used+[c])
source share