Aug-14-2018, 08:05 AM
(This post was last modified: Aug-14-2018, 08:25 AM by vndywarhol.)
Hi! I decided to apply the functional programming in Python and apply it to the Collatz Conjecture. At first I wrote code for myself in the usual style.
Oh, I take it!
def collatz_steps(n, count=0):
if n == 1:
return count
if n < 1:
return "Enter numbers from one"
elif n % 2 == 0:
return collatz_steps(n / 2, count + 1)
else:
return collatz_steps(3 * n + 1, count + 1)
print(collatz_steps(12))Then I began to convert it line by line. But I ran into the problem already at the beginning. The exit condition from recursion in lambda does not work correctly even for a 1. What's wrong?def collatz_steps(n, count=0):
condition = lambda x=n: print("Enter numbers from one") if x == 1 else None
res = lambda x=n: print(count) if x == 1 else (
collatz_steps(x / 2, count + 1) if x % 2 == 0 else collatz_steps(3 * x + 1))
print(collatz_steps(12))Oh, I take it!
def collatz_steps(n, count=0):
condition = lambda x=n: print("Enter numbers from one") if x < 1 else None
condition(n)
res = lambda x=n: count if x == 1 else (
collatz_steps(x / 2, count + 1) if x % 2 == 0 else collatz_steps(3 * x + 1, count + 1))
return res(n)
print(collatz_steps(16))But I'm not sure that this is fully functional programming. Right?
