Mark - 1 year ago 64
Python Question

# A python non finished function

So I have to make a function with returns a list from n to 1 where n will be divided by 2 and added to a list, then the number with was divided by 2 will be multiplied by 3 and will be summed up by 1. This will naturally go on until it reaches the number 1.
The code I have so far:

``````def Gaus(n):
list = []
if n%2 == 0:
list.append(n/2)
else:
list.append((n*3)+1)
return list
``````

So Gaus(30) should return:
[15,46,23,70....,2]

I'm new here at stack overflow, so sorry if my way of asking things is not clear enough. Thank you!

If I understand your question correctly ... this is a recursive implementation:

``````def gaus(n, ls = list()):
if n == 1:
return ls
else:
ls.append(n / 2.)           # Step 1:  n / 2
ls.append(ls[-1] * 3 + 1)   # Step 2: (n / 2) * 3 + 1
return gaus(n - 1, ls)

print gaus(30)
``````

The result is this list:

``````[15.0, 46.0, 14.5, 44.5, 14.0, 43.0, 13.5, 41.5, 13.0, 40.0, 12.5, 38.5, 12.0, 37.0, 11.5, 35.5, 11.0, 34.0, 10.5, 32.5, 10.0, 31.0, 9.5, 29.5, 9.0, 28.0, 8.5, 26.5, 8.0, 25.0, 7.5, 23.5, 7.0, 22.0, 6.5, 20.5, 6.0, 19.0, 5.5, 17.5, 5.0, 16.0, 4.5, 14.5, 4.0, 13.0, 3.5, 11.5, 3.0, 10.0, 2.5, 8.5, 2.0, 7.0, 1.5, 5.5, 1.0, 4.0]
``````

Edit:

``````def print_gaus(n):
if n == 1:
return
else:
if n % 2 == 0:
print (n / 2),
print (n / 2 * 3 + 1),
print_gaus(n / 2 * 3 + 1)
print_gaus(n - 1)

print print_gaus(30)
``````

But notice, it will break because of the maximum recursion depth of your environment.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download