mr_magoo

Untitled

Nov 14th, 2012
198
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.15 KB | None | 0 0
  1. '''
  2.  author:
  3.  date:
  4.  description: Slow and fast algorithms for this problem'''
  5.  
  6. import numpy as np
  7.  
  8. def slow_approach(x):
  9.   ''' A bad solution for finding the worst sequence of days.
  10.  Runs in O(N^3) time.'''
  11.  
  12.   def compute_profit(a,b):
  13.     '''Compute the profit starting on day 'a' and ending on day 'b',
  14.    day b included.'''
  15.     return sum(x[a:(b+1)])
  16.  
  17.   worst_profit = compute_profit(0,0) # Initialize it to anything reasonable.
  18.   worst_profit_indices = (0,0)
  19.   for i in xrange(0, N):
  20.     for j in xrange(i, N):
  21.       current_profit = compute_profit(i,j)
  22.       if (current_profit < worst_profit):
  23.         worst_profit = current_profit
  24.         worst_profit_indices=(i,j)
  25.  
  26.   return (worst_profit, worst_profit_indices)
  27.  
  28. def fast_approach(x):
  29.   '''Use dynamic programming. The basic idea
  30.  is that, rather than solving the problem directly,
  31.  find the worst sequence of days *beginning* on day 'i'
  32.  for the i different possibilities of i.
  33.  We can compute this easily for i=N, then use that
  34.  solution to compute for i=N-1, etc.
  35.  '''
  36.   sol_list = [0 for i in range(N)]
  37.  
  38.   # end_list[i] is the end point of the interval starting at i
  39.   end_list = [0 for i in range(N)]
  40.  
  41.   # Only one possible choice for i=N
  42.   sol_list[N-1] = x[N-1]
  43.   end_list[N-1] = N-1
  44.  
  45.   idx_list = range(N-1)
  46.   idx_list.reverse()
  47.  
  48.   for i in idx_list:
  49.     v1 =  sol_list[i+1]+x[i]
  50.     v2 = x[i]
  51.     if (v1 > v2):
  52.       '''Then best off making the list just (i)'''
  53.       sol_list[i] = v2
  54.       end_list[i] = i
  55.     else:
  56.       ''' Then we can extend the solution starting at i+1
  57.      with the index i'''
  58.       sol_list[i] = v1
  59.       end_list[i] = end_list[i+1]
  60.  
  61.   min_v = min(sol_list)
  62.   idx_min = sol_list.index(min_v)
  63.   return (min_v, (idx_min,end_list[idx_min]))
  64.  
  65. # List of N different numbers
  66. N=3
  67. trials=100
  68.  
  69. for i in range(trials):
  70.   x = np.random.randn(N)
  71.   result_slow = slow_approach(x)
  72.   result_fast = fast_approach(x)
  73.   print "Our worst profit using fast alg is: " + repr(result_fast)
  74.   print "Our worst profit using slow alg is: " + repr(result_slow)
  75.   if (result_slow[1] != result_fast[1]):
  76.     print "Fails on example: " + repr(x)
  77.     break
Advertisement
Add Comment
Please, Sign In to add comment