Skip to content

Instantly share code, notes, and snippets.

@mverleg
Created April 25, 2016 12:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mverleg/71dbbf755ed1cf96589236a69bc64027 to your computer and use it in GitHub Desktop.
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
@mverleg
Copy link
Author

mverleg commented Apr 25, 2016

@mverleg
Copy link
Author

mverleg commented Apr 25, 2016

The !f2py is important; without it the array will be copied and performance will drop to being similar to where.

@hech92
Copy link

hech92 commented May 31, 2020

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!

@mverleg
Copy link
Author

mverleg commented May 31, 2020

@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).

@hech92
Copy link

hech92 commented Jun 2, 2020

@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?

@mverleg
Copy link
Author

mverleg commented Jun 2, 2020

@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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment