-
-
Save mverleg/71dbbf755ed1cf96589236a69bc64027 to your computer and use it in GitHub Desktop.
!! | |
!! f2py -c -m search search.f90 | |
!! | |
subroutine find_first(needle, haystack, haystack_length, index) | |
!! | |
!! Find the first index of `needle` in `haystack`. | |
!! | |
implicit none | |
integer, intent(in) :: needle | |
integer, intent(in) :: haystack_length | |
integer, intent(in), dimension(haystack_length) :: haystack | |
!f2py intent(inplace) haystack | |
integer, intent(out) :: index | |
integer :: k | |
index = -1 | |
do k = 1, haystack_length | |
if (haystack(k)==needle) then | |
index = k - 1 | |
exit | |
endif | |
enddo | |
end |
The !f2py
is important; without it the array will be copied and performance will drop to being similar to where
.
Hi,
can you tell me why haystack_length is an optional parameter in python? The docs which are printed in python (via print(search.find_first.doc) ) say that that parameter is optional and with default = len(haystack), but I don't know where or how that is defined.
I'm not a fortran programmer but would like to start tinkering with algorithms to speed up my python applications.
Thanks in advance!
@hech92 It means that you should leave it empty in Python, and then in Fortran it will have as value the number of elements in the array "haystack". In Fortran the number of elements needs to be passed separately, it's not part of the array (or lets say it's complicated).
@mverleg Yes, that's what is confusing me. I'm calling the function via search.find_first(needle, array) but nowhere am I giving the length as a parameter. Is this handled internally in the python-fortran interface?
@hech92 Yeah Python knows this information, just Fortran doesn't, so Python can fill it in automatically before calling Fortran. And because it's always the same logic, it can be in the wrapper code so you don't have to do it.
Python code: https://gist.github.com/mverleg/3b63d70c806ea4eb73168870297d0bcb