-2

What would be the simplest way to get the next value based on a sorted list?

Sorted list with unique numbers:

If the number n is not found in the list, return n+1, if is found, find in the last number that does not breaks an incremental sequence, return num+1.

  • num=1, for the list [1,2,3,6] would return 4.
  • num=10, for the list [1,2,3,6] would return 11.
  • num=5, for the list [1,2,3,6] would return 7.

I tough about a recursive call, something like:

def nextn(num,listnums):
    if(num not in listnums): return num+1
    return nextn(num+1,listnums)

listnums=[1,2,3,6]
n=1
nn = nextn(n,listnums)
print("n=%d nn=%d" %(n,nn))
Alg_D
  • 2,242
  • 6
  • 31
  • 63

1 Answers1

1

Your if-statement is wrong, it is according to your text but not according to your examples.

I found, reversing the if is easier to understand:

def nextn(num,listnums):
    if (num+1 in listnums): 
        return nextn(num+1,listnums)
    else:
        return num+1

listnums=[1,2,4]
for n in range(10):
    print("n=%d nn=%d" %(n, nextn(n, listnums)))
Ilja
  • 2,024
  • 12
  • 28
  • you think this is not a solution either? :) but it is, just try – Ilja Mar 13 '16 at 15:00
  • I think you could improve the answer, adding some explanations. – poke Mar 13 '16 at 15:01
  • thank you, you are right (I commented to the question, but here it's better of course) – Ilja Mar 13 '16 at 15:07
  • sorry, poke, I see that you edited this, but I saw only after I have overridden it... it's the same, but I don't know how to get the version 3 back... – Ilja Mar 13 '16 at 15:17
  • No, it’s fine, I didn’t know you were still working on the answer, so I wanted to add the final code, but now that you did it yourself, it’s totally fine :) – poke Mar 13 '16 at 15:22