Pygorithm – A Python module for learning major algorithms
github.com
github.com
mid = (left + right) // 2
It would be nice to have a discussion on why you used // instead of /. Depending on who reads your code, explaining this "obvious" choice might be interesting.
There are also other discussions topic : what happens if the array is empty ? what happens if the array is twice the size of the computer's RAM ? What happens if all the numbers in the array are equal ?
mid = left + (right - left)/2;
https://en.wikipedia.org/wiki/Binary_search_algorithm#Implem...
https://stackoverflow.com/questions/4581842/python-integer-r...
I'll add that the super cool thing about "simple" algorithms such as binary search is that their practical application is full of edge cases which are very interesting to study to properly understand what these algorithms "mean". There's an awful lot to be said about even the simplest things.
In fact, all of these seem to be ones that are actually built into Python already.
For example, if you have a very long (practically infinite) stream of mostly ordered items coming in and you want to semi-order a sliding window so downstream consumers have an easier time, what do you do?
You can't just call Array#sort.
Another example in the same vein: You get a large and mostly sorted dataset on an older 32 bit machine. It's about 500 million elements long, and loaded in memory on Python. Which sort algorithm do you use?
Sorry. ;)
def q(list): return [] if list==[] else q([x for x in list[1:] if x < list[0]]) + [list[0]] + q([x for x in list[1:] if x >= list[0]])
Not at a 135-characters length :)
And I'm not even accounting for the 1-char useless var/func names.
EDIT: To clarify, I don't think that the above "1 liner" has anything to offer. 1) It's not pythonic, 2) it's not 1-liner by any of python's standards and 3) it's a bad example of programming.
While on the other hand there are numerous other 1-liners that do not have these bad traits.
- One-char function names.
- You call a "list" a list. Shadows built-ins. At least use lst.
- if list==[] is non PEP8. Should be if not list.
- [list[0]] could be written as list[:1]It is sitting there alone... abandoned... Sorry poor repo that I never made something big from you. You deserve much more stars (p.s. don't tell him that the only one is from me) :(