Python Forum
Need an alternative to brute force optimization loop
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Need an alternative to brute force optimization loop
#4
Why so cagey?

Tell us what the functions and variables are!

As the guys said, np is faster than Python.

Quote:It is sometimes said that Python, compared to low-level languages such as C++, improves development time at the expense of runtime.

For this example, from realpython.com, numpy is nearly 100 times faster:

import numpy as np
from timeit import timeit

def profit(prices):
    max_px = 0
    min_px = prices[0]
    for px in prices[1:]:
        min_px = min(min_px, px)
        max_px = max(px - min_px, max_px)
    return max_px

def profit_with_numpy(prices):
    """Price minus cumulative minimum price, element-wise."""
    prices = np.asarray(prices)
    return np.max(prices - cummin(prices))

cummin = np.minimum.accumulate
# compare speeds
seq = np.random.randint(0, 100, size=100000)
setup = ('from __main__ import profit_with_numpy, profit, seq;' ' import numpy as np')
num = 250
pytime = timeit('profit(seq)', setup=setup, number=num)
nptime = timeit('profit_with_numpy(seq)', setup=setup, number=num)
print('Speed difference: {:0.1f}x'.format(pytime / nptime))
Output:
Speed difference: 93.5x
Reply


Messages In This Thread
RE: Need an alternative to brute force optimization loop - by Pedroski55 - Dec-01-2023, 09:13 AM

Possibly Related Threads…
Thread Author Replies Views Last Post
  Brute Forcing Anagrams Anorak 12 1,835 Jan-10-2025, 04:07 PM
Last Post: Anorak
  Solving an equation by brute force within a range alexfrol86 3 4,141 Aug-09-2022, 09:44 AM
Last Post: Gribouillis
  force a program to exit ? Armandito 3 4,773 May-12-2022, 04:03 PM
Last Post: Gribouillis
  How to use scipy.optimization.brute for multivariable function Shiladitya 9 8,744 Oct-28-2020, 10:40 PM
Last Post: scidam
  best way to force an exception Skaperen 2 2,787 Oct-21-2020, 05:59 AM
Last Post: Gribouillis
  I need advise with developing a brute forcing script fatjuicypython 11 8,276 Aug-21-2020, 09:20 PM
Last Post: Marbelous
  Force calculation result as decimal vercetty92 4 3,746 Mar-20-2019, 02:27 PM
Last Post: vercetty92
  Password Brute Force 2skywalkers 9 7,255 Oct-18-2018, 02:35 PM
Last Post: buran
  Brute Force Password Guesser 2skywalkers 1 3,892 Oct-05-2018, 08:04 PM
Last Post: ichabod801
  Brute Force Pad Lock Guesser RedSkeleton007 4 5,284 Mar-03-2018, 07:42 AM
Last Post: RedSkeleton007

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020