Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/325.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 使用lambda而不使用变量或递归的pascal tringle_Python_Lambda_Pascals Triangle - Fatal编程技术网

Python 使用lambda而不使用变量或递归的pascal tringle

Python 使用lambda而不使用变量或递归的pascal tringle,python,lambda,pascals-triangle,Python,Lambda,Pascals Triangle,嗨,我有一个任务要用一个lambda打印一个pascal tringle。我遇到的问题是,我不能使用任何变量,也不能使用递归lambda。我需要以以下方式提交我的答案: lambda x : <code> 1: 0nCr0 2: 1nCr0, 1nCr1 3: 2nCr0, 2nCr1, 2nCr2 因为答案是以这种方式提交的,所以我不能使用任何变量,也不能使用递归 而tringle需要如下所示: 3: [[1], [1, 1], [1, 2, 1]] 因此,因为我不能使用任何

嗨,我有一个任务要用一个lambda打印一个pascal tringle。我遇到的问题是,我不能使用任何变量,也不能使用递归lambda。我需要以以下方式提交我的答案:

lambda x : <code>
1: 0nCr0
2: 1nCr0, 1nCr1
3: 2nCr0, 2nCr1, 2nCr2
因为答案是以这种方式提交的,所以我不能使用任何变量,也不能使用递归

而tringle需要如下所示:

3: [[1], [1, 1], [1, 2, 1]]
因此,因为我不能使用任何变量,所以我搜索了一种方法,在没有其他行的情况下打印tringle

我发现你可以用下面的方法计算一个帕斯卡弦:

lambda x : <code>
1: 0nCr0
2: 1nCr0, 1nCr1
3: 2nCr0, 2nCr1, 2nCr2
所以我试着用它来解决我的任务,我做到了:

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)]   )

唯一的问题是,如果不使用数学库,我无法使用导入,也不知道如何在lambda中使用阶乘。

如果没有Y组合器,我不知道如何做到这一点

您将不得不执行以下操作:

def F(n):
    return [1] if n == 0 else [a + b for a, b in zip([0] + F(n - 1), F(n - 1) + [0])]
然后使用递归函数将其转换为lambda。F(n)返回三角形的第n行,使用每个元素是其上两个元素的和这一事实


如果你不喜欢打两次F(n-1),那么

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))

使用可以使用lambda创建临时变量的事实。您仍然需要使用Y组合器来消除该函数。

您可以手动构建阶乘函数,然后将其与lambda一起使用:

def阶乘(n): 如果(n==0或n==1): 返回1 其他:
返回n*factorial(n-1)

由于您的部分解使用了
i
j
,我不知道“不能使用任何变量”是什么意思,除非您是指全局变量,在这种情况下,我提交:

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))
输出

> python3 test.py
[[1], [1, 1], [1, 2, 1], [1, 3, 3, 1], [1, 4, 6, 4, 1], [1, 5, 10, 10, 5, 1]]
>