Python lambda反向映射

2024-06-16 08:24:10 发布

您现在位置:Python中文网/ 问答频道 /正文

我的反向映射程序无法运行。有什么建议吗

实践案例:
reverseMap以一个函数(f)和两个数字(当前值和阈值)作为输入。它递归地创建一个字符串:在每个递归步骤中,它将函数f应用于数字“current”,结果与递归调用reverseMap的结果相结合(以相反顺序),其中current值增加(直到达到阈值,然后停止)。

f1将输入乘以5
f2将输入增加1
ProgramTest1:使用f1
ProgramTest2:使用f2
ProgramTest3:隐藏

def reverseMap(f, current, threshold):
  if___==___:
    return 'Result:'
  else:
  ___________________________
  ___________________________
  ___________________________

f1 = lambda ___  
f2 = lambda ___  
n = 10
res = reverseMap(f1, 1, n)
print()

在练习中,我可以看到结果是:
全局:
f1=ref_1
f2=参考2
n=10
res='结果:␣45␣40␣35␣30␣25␣20␣15␣10␣5'
反向映射=ref_0

因此,根据这些信息,我可以得出以下结论:

def reverseMap(f, current, threshold):
  if current == 0:
    return 'Result:'
  else:
  ___________________________
  ___________________________
  ___________________________

f1 = lambda x: x * 5  
f2 = lambda x: x + 1 
n = 10
res = reverseMap(f1, 1, n)
print()
我该怎么填空格呢?


Tags: lambda函数thresholdreturnifdefres阈值
1条回答
网友
1楼 · 发布于 2024-06-16 08:24:10

试试这个:

def reverseMap(f, current, threshold):
    if current == threshold:
        return 'Result:'
    new_result = reverseMap(f, f2(current), threshold)
    result =  new_result + ' ' + str(f(current))
    return result

f1 = lambda x: x*5
f2 = lambda x: x+1

n = 10
res = reverseMap(f1, 1, n)
print(res)
res = reverseMap(f2, 1, 7)
print(res)

相关问题 更多 >