Recursive Funciton

Python decimal to binary conversion excercise

Page 1 of 1

2 Replies - 2517 Views - Last Post: 19 January 2009 - 12:14 AM Rate Topic: -----

#1 JairunCaloth  Icon User is offline

  • New D.I.C Head

Reputation: 1
  • View blog
  • Posts: 12
  • Joined: 17-January 09

Recursive Funciton

Post icon  Posted 18 January 2009 - 10:58 PM

Hey guys, I'm teaching myself python and have been using some of the exercises from MIT's open courseware. One of the recent exercises I went through asked me to write a python program that uses a recursive function to convert a positive decimal integer into it's binary representative. I would like to get some feed back and constructive criticism on what I came up with.

The assignment : http://ocw.mit.edu/N...FDC/0/assn2.pdf

My code:
#!/usr/bin/python

import sys

def recurse(stuff):
		if stuff[0] > 0:
				stuff[1] = stuff[0] % 2
				stuff[0] = stuff[0] // 2
				stuff[2] = str(stuff[1]) + str(stuff[2])
				recurse(stuff)
				return stuff[2]
		else:
				return

def main():

		incoming = sys.argv[1]
		if int(incoming) > 0:
				incoming=[int(incoming),'','']
				binary = recurse(incoming)
				print binary
				return

		else:
				print str(sys.argv[1]) + " is not valid input"
				return
main()


Is This A Good Question/Topic? 0
  • +

Replies To: Recursive Funciton

#2 numerical_jerome  Icon User is offline

  • D.I.C Head

Reputation: 12
  • View blog
  • Posts: 167
  • Joined: 16-September 07

Re: Recursive Funciton

Posted 19 January 2009 - 12:00 AM

This is good, you have the idea of recursion down.

If you wished to improve performance, you don't really need to pass an array into function recurse, you could pass integers and return a string.

import sys

def recurse(stuff):
	if (stuff > 0):
		if(stuff % 2 == 1):
			 return(recurse(stuff / 2) + "1")
		else:
			 return(recurse(stuff / 2) + "0")
	else:
		 return ""

def main():
	print recurse(int(sys.argv[1]))

main()



Hope this was useful,

-Jerome
Was This Post Helpful? 1
  • +
  • -

#3 JairunCaloth  Icon User is offline

  • New D.I.C Head

Reputation: 1
  • View blog
  • Posts: 12
  • Joined: 17-January 09

Re: Recursive Funciton

Posted 19 January 2009 - 12:14 AM

That looks a lot easier to manage as well, thanks Jerome. I really like how you dealt with the problem of constructing the string that was the binary. I spent a lot of time trying to figure that one out hehe. :)
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1