Advertisement
ludoo

Trick question

Oct 23rd, 2014
158
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.07 KB | None | 0 0
  1. """Given an array of numbers. Create another array that contains
  2. * the product of all the members in the array except the current
  3. * element. For example, if you have an array of 3 elements such as:
  4. *
  5. * A[0] = 2
  6. * A[1] = 4
  7. * A[2] = 6
  8. *
  9. * Then the resulting array will be
  10. * B[0] = 24
  11. * B[1] = 12
  12. * B[2] = 8"""
  13.  
  14. #
  15. # tempi per 100k ripetizioni con l = range(1, 10)
  16. #
  17. # ludo ~1.36s
  18. [reduce(lambda x, y: x*y, [el for j, el in enumerate(l) if j != i]) for i in range(len(l))]
  19. # andrea ~0.88s ma osserva Carlo che si pianta per numeri non interi
  20. [reduce(int.__mul__, l[:i]+l[i+1:], 1) for i in range(len(l))]
  21. # C8E ~0.43s ma osserva Andrea che salta se c'è uno 0 nella lista
  22. import operator; [reduce(operator.mul, l)/x for i, x in enumerate(l)]
  23. # MB #1 ~1.3s
  24. from operator import mul; [reduce(mul, (i for n,i in enumerate(l) if n!=m)) for m in range(len(l))]
  25. # MB #2 ~1.62s
  26. [reduce(lambda a,b: a*b, (i for n,i in enumerate(l) if n!=m)) for m in range(len(l))]
  27. # C8E+Andrea ~0.58s
  28. import operator; [reduce(operator.mul, l[:i] + l[i+1:]) for i, _ in enumerate(l)]
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement