Kiva
Kiva

Reputation: 43

Testing if value is in list/array (Ti-Basic)

Is there a way to test if a value is in a list? In Python, I think you can do something like 'if n in myList: print("Value N is in the list.")'

I don't want to use a for loop to check each value seperately, unless it's the only option. I'm using a Ti-84 Plus.

Upvotes: 2

Views: 1511

Answers (2)

glyvox
glyvox

Reputation: 58029

This idea for searching is from TI-Basic Developer, and is quite brilliant:

Let's suppose you have a value named x and a list named L.

:If max(1/(1+(abs(L-x))))=1
:Then
//value is in list
:Else
//value is not in list
:End

And that's it!

Here is how it works:

abs(L-x)

  • Firstly, it subtracts the searched number from every value of a list and gets its absolute value.

max(1/(1+(abs(L-x))))

  • After that, it searches for the largest element in it, adds it to 1 and divides 1 by it.

:If max(1/(1+(abs(L-x))))=1

  • If it's 1, than the value is in the list. Why? Because 1 / 1 + 0 is 1 (a number minus itself is always 0) and 0 is the maximum possible value for 1 / 1 + x (for positive numbers, of course). If the maximum is smaller than 1, it's certain that the searched value is not inside the list.

Upvotes: 2

tryashtar
tryashtar

Reputation: 278

This should work assuming I've thought through it correctly. It's very simple, where L₁ is the list to search and X is the value to look for.

max(not(L₁-X

Step-by-step analysis:

  1. L₁-X: Subtract the value from everything in the list. Now, if this list contains a zero, it means our value was in L₁.
  2. not(L₁-X: Invert everything in the list. This converts all zeroes to ones, and everything else to zeroes. Now, if this list contains a one, it means our value was in L₁. If the list is all zeroes, it was not.
  3. max(not(L₁-X: Get the maximum value in the list. As stated above, the list will be all zeroes if the value was not inside L₁, so the maximum value will be zero. If L₁ had the value inside, the maximum will be a one.

This makes a check as simple as this:

If max(not(L₁-X
Disp "The value was found:",X

Upvotes: 6

Related Questions