Advertisement
Guest User

Untitled

a guest
Oct 19th, 2019
93
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.29 KB | None | 0 0
  1. # coding: utf-8
  2. # Your code here!
  3.  
  4. #Good morning! Here's your coding interview problem for today.
  5.  
  6. #This problem was asked by Uber.
  7.  
  8. #Given an array of integers, return a new array such that each element at index i of the new array is the product of all the numbers in the original array except the one at i.
  9.  
  10. #For example, if our input was [1, 2, 3, 4, 5], the expected output would be [120, 60, 40, 30, 24]. If our input was [3, 2, 1], the expected output would be [2, 3, 6].
  11.  
  12. #Follow-up: what if you can't use division?
  13.  
  14.  
  15. def other_products(ls):
  16. leaf_cnt = len(ls)
  17. hp = [ 1 for x in range(0,leaf_cnt-1) ] + ls
  18.  
  19. def parent(i):
  20. return (i - 1) // 2
  21.  
  22. for r in range( len(hp) - 1, 0, -2 ):
  23. hp[parent(r)] = hp[r]*hp[r-1]
  24.  
  25. def sibling(i):
  26. if i % 2 == 0:
  27. return i - 1
  28. else:
  29. return i + 1
  30. def compute_product(i):
  31. result = 1
  32. while i != 0:
  33. result *= hp[sibling(i)]
  34. i = parent(i)
  35. return result
  36.  
  37. #return compute_product(len(ls))
  38. return [ compute_product( len(ls) - 1 + i ) for i in range(0,len(ls)) ]
  39.  
  40.  
  41.  
  42. #print( other_products( [1, 2, 3, 4, 5]) )
  43. assert( other_products( [1, 2, 3, 4, 5]) == [120, 60, 40, 30, 24] )
  44. assert( other_products( [3, 2, 1]) == [2, 3, 6] )
  45. print ( "OK" )
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement