# Recursive Funciton

Page 1 of 1

## 2 Replies - 3291 Views - Last Post: 19 January 2009 - 12:14 AMRate Topic: //<![CDATA[ rating = new ipb.rating( 'topic_rate_', { url: 'http://www.dreamincode.net/forums/index.php?app=forums&module=ajax&section=topics&do=rateTopic&t=81583&amp;s=49d23acedd61993cc51a0f6207b7ae75&md5check=' + ipb.vars['secure_hash'], cur_rating: 0, rated: 0, allow_rate: 0, multi_rate: 1, show_rate_text: true } ); //]]>

### #1 JairunCaloth

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

# Recursive Funciton

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

Reputation: 12
• 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

### #3 JairunCaloth

Reputation: 1
• 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.