Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Convert numbers to a certain base
#1
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.
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
If you have any questions about how this works, feel free to ask. Blackhat
[Image: izsyo6.jpg]


Reply
#2
damn lol, more comments than actual code Tongue
[Image: nv70ad.png]
Terrorcore, unleash, extermination
Hyper real, cold blood, determination
fudge them, I like this sensation
Incredible, I from the annihilation
Reply
#3
(04-05-2010, 06:16 PM)Fallen Wrote: damn lol, more comments than actual code Tongue

Yeah the person I did it for(it was his homework) wanted it well documented so he can understand it. Come to think of it I should have used triple quotes for documentation.
[Image: izsyo6.jpg]


Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Generate Prime Numbers [Python] wchar_t 0 967 08-06-2010, 05:09 AM
Last Post: wchar_t

Forum Jump:


Users browsing this thread: 1 Guest(s)