(Dec-01-2020, 05:56 PM)bowlofred Wrote:When i changed the target to 111, the program returned 140. Why if in that list there is a 100, which is smaller than 111, and 140 isn't.(Dec-01-2020, 05:45 PM)1234 Wrote: And what if my target is 100 and there is no 100 in the list, so I want to take the closest number to 100 that is smaller than 100?
The program didn't return 100 (because 100 isn't less than 100). It returned the largest number less than 100.
You can read more about the specifics of bisect (which allow you to quickly find things in a sorted list, and to append things in a way that keeps a list sorted) in the docs.
Find _ in a list
Find _ in a list
|
||
I've changed the target to 111, the program returned 140. Why if there is a 100, that is smaller, and 140 isn't?
Dec-01-2020, 07:05 PM
(This post was last modified: Dec-01-2020, 07:25 PM by deanhystad.)
I'm guessing you have a typo? I just ran with target = 111 and got
What are you using for data? I used
But the demo does warn to be on the lookout for index == -1.
Dec-01-2020, 07:13 PM
Yeah what I had was a typo, but 1 more thing, if for example there is a list(5,7,2,9,34) and I run the program with target = 7, the result will be 5, because it will only do lower that 7, instead of lower or equal, which will be 7. How would I change it from lower, to lower or equal?
Dec-01-2020, 07:53 PM
Change it from bisect_left to bisect_right. Now it will give you an insertion point to the right of your target. If you back up one spot (like the program does), that will return the largest number less than or equal to your target.
| ||
|
Users browsing this thread: 1 Guest(s)