首页 > 解决方案 > 使用迭代和递归的代码简化

问题描述

我想 1)使用迭代简化下面的代码 2)使用递归实现它

这段代码具有一个类似于斐波那契数列的方程,差异是前面的答案乘以一个函数,在这种情况下,它只是 2 乘以索引。

该算法将输入不同的图像并计算总增量点,展平的最优矩阵将给出最高值。

请注意, list_c 应该给出最高值。

sum_list=[]
list_a= [1,0,1,0,1]
list_b= [1,0,0,1,1]
list_c= [1,1,1,0,0]

def increment(input_list):
    global i #i added it because i received an error

    """ returns

    Incrementing_answer = previous_answer + (list[i+1])
    for which previous_answer begins with list[0]

    if list[0] =0 then list[0]=-1

    for example, list_a should be evaluated as follows

    -   ans = 1+2*(1)
            = 3

    -   ans = 3+ 2*(0) --since since its 0 ,-1 is replaced
            = 3+ 2*(-1)
            = 1

    -  ans  = 1+2(1)
            =3
            and so on
        Incrementing_answers = sum_list=[3,1,3,1,3] =11





    """ 


    for i in range(0,len(input_list)):
        if input_list[i] == 0 :
            input_list[i] == -1
            ans = input_list[i]+2*input_list[i]

            sum_list.append(ans)


        else:
            ans = ans+input_list[i]
            sum_list.append(ans)

        return sum(sum_list)

以前的答案很有帮助,上面的代码不起作用 1)我想更正

2)是否可以使用递归解决相同的问题

3)我也刚刚意识到代码不适用于大型数组(preprocesed_images)

4)对于包含浮点数的列表或数组,我得到错误('ValueError:具有多个元素的数组的真值不明确。使用 a.any() 或 a.all()')

3)关于使用良好编程实践的反馈

4)欢迎提出任何关于如何解决问题的额外建议,输入的图像将使用 cv2 捕获,算法必须实时选择最佳图像,以解决难题。

首先十分感谢

标签: pythonlistrecursioniteration

解决方案


  1. 不鼓励将全局变量作为参数传递给函数

  2. 鼓励使用PEP 8命名约定(即命名函数增量而不是增量)

  3. 不鼓励使用单字母变量名称(即不知道 a、l、p 代表什么)(采用下面 Dan 的评论)。

代码

def increment(a, l, p):
  """
  Returns in an incrementing value ,using the formula a(n)=a(n)+l(i+1)
  were a(n) starts with the starts with l[0] and then l(i+1)
  """
  for i in range(len(l)):
    if l[i] == 0: # equation
      a += -2     # no change to l
    else:
      a += 2*l[i] 
    p.append(a)

  return sum(p)

用法

l = [1,0,1,0,1]
p=[]
a = 0
print(f'Increment: {increment(a, l, p)}')
print(f'l unchanged: {l}')
print(f'Updated p: {p}')
a = p[-1]  # a is last p
print(f'Updated a: {a}')

输出

Increment: 6
l unchanged: [1, 0, 1, 0, 1]
Updated p: [2, 0, 2, 0, 2]
Updated a: 2

推荐阅读