Python Forum
Learning functional programming
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Learning functional programming
#1
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.
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?
Reply


Messages In This Thread
Learning functional programming - by vndywarhol - Aug-14-2018, 08:05 AM
RE: Learning functional programming - by ichabod801 - Aug-14-2018, 12:46 PM
RE: Learning functional programming - by micseydel - Aug-15-2018, 02:17 AM

Possibly Related Threads…
Thread Author Replies Views Last Post
  functional LEDs in an array or list? // RPi user Doczu 5 1,852 Aug-23-2022, 05:37 PM
Last Post: Yoriz
  Stuck in functional proggaming haze hammer 2 1,504 Oct-27-2021, 02:07 PM
Last Post: hammer
  OOP vs functional - - elaborate turn based RPG game (Derek Banas Udemy course again) Drone4four 6 4,208 Mar-14-2021, 08:38 AM
Last Post: ndc85430
  Calculating surface area - - OOP or functional? Derek Banas Udemy course Drone4four 5 3,830 Mar-13-2021, 06:22 AM
Last Post: buran

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020