Problem when trying to solve a challenge

Asked

Viewed 60 times

0

Good night, you guys... I need your help to write a small code that is able to receive a number as well as its index and return the next element of the sequence... The problem is that I still can’t figure out the logic behind it

Enunciado do desafio

Testes do desafio

The code I wrote is as follows:...

def next(a,i):
  """
  1,0,2,−1,3,−2,4,-3,5,-4
  """
  if i%2 == 0:
    return 1 + 1*i//2
  else:
    return  1 + (-1)*i//2
print(next(17, 31))
  • 1

    lucasbbs, please edit your question by entering the code you tried to do and specifying your difficulties.

  • 1

    @Solkarped, okay... I already edited the code The problem is in the last test case

  • I don’t know if I understood the criteria, but finally, my guess: https://ideone.com/jG2qE9 - Changing the subject, I don’t know this platform, but I don’t like it anymore. It mixes 2 problems: one is programming itself, the other is trying to guess the crazy rule that generates the numbers. If one were to teach only programming, the correct - in my opinion - would be to explain the rule, because then one focuses only on writing the algorithm. But by turning it into a little guessing game, I think it hurts learning (but I don’t know, I’m not a teacher, I might be wrong...)

  • I agree with you @hkotsubo... Even more it is clear that my solution also satisfies the problem

1 answer

1


If your role receives ai and i as parameters, the least we can expect is that the expression that will define the next value depends on these two values.

By the examples it is clearer that the values of the parameters are directly linked to the result.

next(1, 1) = 0 ... 1 - 1 = 0
next(-1, 4) = 3 ... -1 + 4 = 3
next(-4, 10) = 6 ... -4 + 10 = 6
...

And by that connection we can see that i is odd, we subtract the two values to obtain the next term of the sequence; if i is par, just add them up.

Soon:

def next(ai, i):
  signal = 1 if i % 2 == 0 else -1
  return ai + signal * i

assert next(1, 1) == 0
assert next(-1, 4) == 3
assert next(-4, 10) == 6

If you’re not a fan of if to define the signal, you can make the equivalent expression using potentiation, because (-1)**i will be negative for i odd and positive for i par:

def next(ai, i):
  return ai + (-1)**i * i

Browser other questions tagged

You are not signed in. Login or sign up in order to post.