问题
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.
回答1:
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:
L₁-X
: Subtract the value from everything in the list. Now, if this list contains a zero, it means our value was inL₁
.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 inL₁
. If the list is all zeroes, it was not.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 insideL₁
, so the maximum value will be zero. IfL₁
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
回答2:
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 for1 / 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.
来源:https://stackoverflow.com/questions/46517466/testing-if-value-is-in-list-array-ti-basic