03-03-2010, 06:50 PM
I posted this to help someone out over at HF. He had an assignment to be able to convert numbers to a certain base, but without using loops. The only thing he could use were recursions. I had no clue about recursions before I created this for him, so it was a learning experience for me, path math wise and programming wise ;). Basically, recursions are when you call a function inside the function itself, basically has the same principles as a loop, just different methods of coding.(you still need to provide and escape to escape the loop, etc.)
Anyway here is the code.
If you have any questions about how this works, feel free to ask.
Anyway here is the code.
Code:
import sys
sys.setrecursionlimit(1500) #Windows has a recursion limit
def start(): # define our main function, asks for input, etc.
num = int(raw_input('Please enter a non-negative integer between 2 and 9:')) #prompt for the number to convert
if num < 2 or num >= 10 or str(num)[0] == "-": #makes sure it isnt below 2, above 9.9, and isn't negative
print "You have entered an incorrect number"
start() #recall our start function so they get returned to the beginning
basenum = int(raw_input('What base shall I convert %i to?' %num)) #find the base to convert this number to
findbase(basenum, num) #call the findbase function using the input provided
result = [] #we need to use a global list so our function doesn't keep redefining it as empty
def findbase(base, num): #this function will print the result
global result #tell the program we are dealing with the global result variable, defined above
if num == 0: #if our number is equal to 0, stop dividing it, print the result
result.reverse #reverse the list first
print result #self explanatory
else:# if it isn't equal to 0
result.append(num % base) #append the remainder of the number divided by the base to our list
num /= base #divide the number by the base
findbase(base, num) #recursion, call the function again except using the new num, after divided by the base
start() #call our main function, starting the program