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

谁说胖子不能爱 提交于 2019-12-11 07:06:57

问题


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:

  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



回答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 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.


来源:https://stackoverflow.com/questions/46517466/testing-if-value-is-in-list-array-ti-basic

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!