Advertisement
gruntfutuk

slidingwindow

Apr 23rd, 2018
205
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 5.85 KB | None | 0 0
  1. ''' Beginner Exercise on sliding window array multiplication.
  2.  
  3.    NOTE < and > symbols in the below surround variable names to
  4.    indicate you can use your own name in place of what is used in
  5.    this text, they are not part of the Python syntax.
  6.  
  7.    Write a function that returns a list of results of some array
  8.    multiplications as described below.
  9.  
  10.    Your function must accept as parameters two numeric lists, we shall
  11.    call them <sliding> and <base>, and return one numeric list,
  12.    <answers>.
  13.  
  14.    Note that <sliding> will contain at least as many elements as <base>.
  15.  
  16.    Multiply each element in <base> by its corresponding element in
  17.    sliding: <base>[0] * <sliding>[0], <base>[1] * <sliding>[1],
  18.    <base>[2] * <sliding>[2]  and so on.
  19.  
  20.    Add up the results of the above. Store this as your first answer,
  21.    <answers>[0].
  22.    
  23.    Do it again, but start one element further along in the sliding list.
  24.    <base>[0] * <sliding>[1], <base>[1] * <sliding>[2], <base>[2] *
  25.    <sliding>[3], and so on.
  26.  
  27.    Add up the results of the above. Store this as your second answer,
  28.    <answers>[1].
  29.  
  30.    Repeat as many times as you can, storing each answer. You cannot go
  31.    past the point where <sliding> has fewer elements than <base>.
  32.    
  33.    Optionally, you can output to the console all of the answers. This
  34.    is not required for testing purposes.
  35.  
  36.    Return the answers list from your function. This is required for
  37.    testing.
  38.    
  39.    Use the test framework included below to test your function. Note
  40.    that the test framework may be changed from time to time, and
  41.    additional test values added, so check back. You should include
  42.    the name of your function, without the (), in the test call on
  43.    the last line.
  44.  
  45.    You are welcome to provide multiple solutions in the same file.
  46.  
  47.    You function name should start with your name, followed by a name for
  48.    the function, with _ between the names,
  49.    e.g. def Fred_Blogs_tricky(sliding, base):
  50.  
  51.    You can use common libraries as part of your solution, such as numpy,
  52.    if you wish.
  53.  
  54.    The image is designed to make the challenge more clear.
  55.    
  56.    See picture for more explanation: https://i.imgur.com/O2c3jdH.jpg
  57. '''
  58.  
  59. Stuart_Moore_lambda = lambda sliding, base: [sum(x*y for x, y in zip(sliding[counter:], base)) for counter in range(0, len(sliding)-len(base)+1)]
  60.  
  61. def Stuart_Moore_shorty(sliding, base):
  62.     return [sum(x*y for x, y in zip(sliding[counter:], base)) for counter in range(0, len(sliding)-len(base)+1)]
  63.  
  64. def Mark_Geyzer_mul_sliding(sliding, base):
  65.     import operator
  66.     def _mul_sliding_helper(slider, results):
  67.         if len(slider) < len(base):
  68.             return results
  69.         results.append(sum(operator.mul(*numbers) for numbers in zip(slider, base)))
  70.         return _mul_sliding_helper(slider[1:], results)
  71.     return _mul_sliding_helper(sliding, [])
  72.  
  73. def Stuart_Moore_rangy(sliding, base):
  74.     ''' using range, zip, and comprehension '''
  75.     totals = []
  76.     for counter in range(0, len(sliding)-len(base)+1):
  77.         totals.append(sum(x*y for x, y in zip(sliding[counter:], base)))
  78.     return totals
  79.  
  80.  
  81. def Stuart_Moore_zippy(sliding, base):
  82.     ''' using zip, pop and comprehension '''
  83.     slide = sliding[:]
  84.     totals = []
  85.     baselen = len(base) - 1
  86.     while slide[baselen:]:
  87.         totals.append(sum(x*y for x,y in zip(slide, base)))
  88.         slide.pop(0)
  89.     return totals
  90.  
  91.  
  92. def Stuart_Moore_windy(sliding, base):
  93.     ''' without zip, pop or comprehension '''
  94.     slide = sliding[:]
  95.     totals = []
  96.     baselen = len(base) - 1
  97.     while slide[baselen:]:
  98.         total = 0
  99.         slide_items = iter(slide)
  100.         for base_item in base:
  101.             slide_item = next(slide_items)
  102.             total += base_item * slide_item
  103.         totals.append(total)
  104.         slide = slide[1:]
  105.     return totals
  106.  
  107. def Stuart_Moore_slidy(sliding, base):
  108.     ''' using a sliding window '''
  109.    
  110.     def window(iterable, size=2):
  111.         itered = iter(iterable)
  112.         slit = []
  113.         for _ in range(0, size):
  114.             slit.append(next(itered))
  115.         yield slit
  116.         for element in itered:
  117.             slit = slit[1:] + [element]
  118.             yield slit
  119.            
  120.     slide = window(sliding, len(base))
  121.     totals = []
  122.     for slide_slice in slide:
  123.         totals.append(sum(x*y for x,y in zip(slide_slice, base)))
  124.     return totals
  125.    
  126. def Yap_Seng_Kuang_m(sliding,base):
  127.         return [sum([i*j for i,j in zip(sliding[k:k+len(base)],base ) ])  for k in range(0,len(sliding)-len(base)+1)]
  128.  
  129. ''' *******************************
  130.    **          TESTING          **
  131.    *******************************
  132. '''
  133.  
  134. def test_funcs(*funcs):
  135.     import traceback
  136.    
  137.     tests = [(  [-1, 2, -2, 3, 41, 38, 22, 10, -1, 3],
  138.                 [40, 30, 20, 10],
  139.                 [10, 490, 1210, 2330, 3320, 2370, 1190] ),
  140.              (  [56, -34, 20, -8, 15, 57,16, 13, 2, -5],
  141.                 [5, 10, 15, 20],
  142.                 [80, 210, 1385, 1285, 1145, 680, 140] )              
  143.             ]
  144.    
  145.     for func in funcs:
  146.         print(f'\n\nTesting function {func.__name__}:\n')
  147.         for sliding, base, answers in tests:
  148.             result = func(sliding, base)
  149.             try:
  150.                 assert result == answers
  151.             except AssertionError:
  152.                 print(f'function {func.__name__}: FAILED with {result}')
  153.                 print(f' for data, sliding: {sliding}')
  154.                 print(f' and base: base: {base}')
  155.                 print(f' expected: {answers}')
  156.             else:
  157.                 print(f'function {func.__name__}: {result}')
  158.  
  159.  
  160. ''' testing functions '''
  161. if __name__ == '__main__':
  162.     func_list = [func for name, func in globals().items()
  163.                 if callable(func) and name[0:2]
  164.                 not in ('__', 'te', 'ex', 'qu', 'ge')]
  165.     test_funcs(*func_list)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement