-1

Hi I have a task to use a lambda that print's a pascal tringle. The problem I'm having is that I can't use any variables nor can I use a recursive lambda. I need to submit my answer in the following way:

lambda x : <code>

because the answer is submitted in this way I can't use any variables nor can I use recursion.

and the tringle need to look like this:

3: [[1], [1, 1], [1, 2, 1]]

so because I can't use any variables I searched for a way to print the tringle without the other lines.

and I found that you can calculate a pascal tringle in the following way:

1: 0nCr0
2: 1nCr0, 1nCr1
3: 2nCr0, 2nCr1, 2nCr2

so I tried using it to solve my task and I reached this thing:

lambda x : (   [([(int)( ( __import__("math").factorial(i) ) / (__import__("math").factorial(j) * ( __import__("math").factorial(i - j) ) ) ) for j in range(i + 1)]) for i in range(x)]   )

the only problem is that I can't use import and I don't know how to use factorial inside a lambda without using the math library.

Golden
  • 93
  • 9

3 Answers3

1

Since your partial solution uses i and j, I don't know what you mean by "can't use any variables" unless you mean global variables, in which case I submit:

pascal = lambda n: [(lambda s: [s] + [s := s * (r - t) // (t + 1) for t in range(r)])(1) for r in range(n)]

print(pascal(6))

OUTPUT

> python3 test.py
[[1], [1, 1], [1, 2, 1], [1, 3, 3, 1], [1, 4, 6, 4, 1], [1, 5, 10, 10, 5, 1]]
>
cdlane
  • 40,441
  • 5
  • 32
  • 81
0

I have no idea how to do this without the Y combinator.

You're going to have to do something like:

def F(n):
    return [1] if n == 0 else [a + b for a, b in zip([0] + F(n - 1), F(n - 1) + [0])]

and then use the Y combinator to the recursive function into a lambda. F(n) returns the nth row of the triangle by using the fact that each element is the sum of the two above it.


If you're unhappy with calling F(n-1) twice, then

def F(n):
    return [1] if n == 0 else \
        (lambda v: [a + b for a, b in zip([0] + v, v + [0])])(F(n - 1))

Using the fact that you can use lambda to create temporary variables. You'll still need to use the Y combinator to eliminate the function.

Frank Yellin
  • 9,127
  • 1
  • 12
  • 22
0

You can manually build your factorial function and then use it with lambda:

def factorial(n): if (n==0 or n==1): return 1 else: return n*factorial(n-1)