-3

I would like to 1)simplify the code below using iteration 2)implement it using recursion

This code features an equation similar to the Fibonacci series the difference being the previous answer is multiplied by a function in this case just 2 by index.

The algorithm will input different images and calculate the total incremented points, the flattened optimal matrix will give the highest value.

Note that list_c should give the highest value.

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)

Previous answers have been helpful, the code above does not work 1)I would like corrections

2)Is it possible to solve the same problem using recursion

3) I also just realised the code does not work well for large arrays(preprocesed_images)

4) for lists or arrays that include floating points I get the error (' ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()')

3)Feedback on using good programming practices

4) Any additional advice on how to tackle the problem is Welcome, the inputted images will be captured using cv2 and the algorithm has to pick optimal images in real-time, to solve the puzzle.

Thanks very much in advance

quadhd
  • 71
  • 1
  • 8
  • Can you please narrow down your question? The code replaces all ``0`` with ``-1`` because you explicitly tell it to: ``if l[i]==0: l[i]=-1``. Are you looking for simplification of the existing (wrong) code, for improvements, or for new code using recursion? Are you aware how to pass arguments to functions? In your definition "a(n)=a(n)+l(i+1)", what is ``i``? – MisterMiyagi Jun 11 '20 at 11:04
  • The code is similar to the minimax algorithm, inputs will be images, Matrices with only 1s and 0s. – quadhd Jun 12 '20 at 16:52
  • The code is similar to the minimax algorithm, inputs will be images, Matrices with only 1s and 0s. If in a matrix 1s and 0s are consecutive, the probability or points of using that matrix should be less than that were 1s are consecutive, example A=[1,0,1,0,1] , B=[1,1,1,0,0] in this case B is selected. So I thought in order to Select B, the equation Total_Points = initial_value+ Matrix(index+1) can be used. but by replacing 0s with -1s, the difference is amplified. – quadhd Jun 12 '20 at 17:02

2 Answers2

1
  1. Global variables are discouraged over passing arguments as parameters to function

  2. Use of PEP 8 naming conventions is encouraged (i.e. name function increment rather than Increment)

  3. Single letter variable names are discouraged (i.e. no idea of what a, l, p represents) (adopting Dan's comment below).

Code

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)

Usage

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

Output

Increment: 6
l unchanged: [1, 0, 1, 0, 1]
Updated p: [2, 0, 2, 0, 2]
Updated a: 2
DarrylG
  • 16,732
  • 2
  • 17
  • 23
  • single letter variable names are also discouraged – Dan Jun 11 '20 at 11:00
  • @dan--True. But, I overlooked since he seems to be implementing a formula from some context. Would you say there are exceptions such as implementing a mathematical formula in some context such as in Physics we could have: `E = m*c**2`? Also is the discouragement a Pylint rather than PEP 8 issue [Why does pylint object to single character variable names?](https://stackoverflow.com/questions/21833872/why-does-pylint-object-to-single-character-variable-names)? – DarrylG Jun 11 '20 at 11:21
  • 1
    @dan--good point though, so updated my answer with your comment. – DarrylG Jun 11 '20 at 11:30
  • @DarrylG Your code works perfectly but is there a way of further simplifying it, as follows for example `def increment(input_list[0], input_list): sum_list =[] for i in range(len(l)): if input_list[i] == 0: # equation input_list[i] += -2 # no change to l else: input_list[i] += 2*input_list[i] sum_list.append(input_list[i]) return sum(sum_list) ` – quadhd Jun 12 '20 at 21:30
  • @DarrylG i have also updated the question, the code does not work well with large arrays and floating points – quadhd Jun 12 '20 at 21:50
  • @quadhd--in your previous comment about redefining the function--you cannot have `def increment(input_list[0], input_list):` The def is for the name of the two function parameters. Also, why is the loop `for i in range(len(l))`? What is l? You say it does not work well if large arrays? What's the issue? Is it too slow? Is it inaccurate? – DarrylG Jun 12 '20 at 22:53
0

a doesn't need to be a global and p & l should be passed as argumets -in your version you tied your implementation of your function to the implementation of the calling code - a better implementation would be :

I don't fully understand why you need a at all, but I think this code does what you need :

def Increment( initial, results ):
    """
    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)
   ,if l[i]= 0,-1 is calculated instead.

   """
    last = results[-1] if results else 0
    for index, value in enumerate(initial):
        term = -1 if value == 0 else value

        last += 2* term
        results.append(last)

    return sum(results)

l = [1,0,1,0,1]
p=[]
r = Increment(initial=l, results=p)
print(r) 

If you do need the a value outside the function it will just be p[-1]

I think the above code replicates the functionality, without changing your l list (which you indicated you didn't need.

Tony Suffolk 66
  • 9,358
  • 3
  • 30
  • 33
  • 1
    ``term = -1 if value == 0 else term`` does not work if the first ``value`` is anything but ``0``. Did you mean ``-1 if value == 0 else value``? – MisterMiyagi Jun 11 '20 at 11:06
  • @TonySuffolk66 Thanks for your answer, I have updated the question, please be sure to have a look. – quadhd Jun 12 '20 at 21:49