Skip to content

Instantly share code, notes, and snippets.

@lvsl-deactivated
Created August 12, 2012 10:45
Show Gist options
  • Save lvsl-deactivated/3331194 to your computer and use it in GitHub Desktop.
Save lvsl-deactivated/3331194 to your computer and use it in GitHub Desktop.
evernote contest
# coding: utf-8
'''
Given a list of integers, your task is to write a program to output an integer-valued list of equal length such that the output element at index 'i' is the product of all input elements except for the input element at 'i'.
In other words, let inputArray by an integer array of length 'n'. The solution,computed into outputArray, would be:
for each j from 1 to n-2:
outputArr[ j ] = inputArray[0] * inputArray[1] * inputArray[2] * ... * inputArray[j-1] * inputArray[j+1] * inputArray[j+2] *...* inputArray[n-1]
for j = 0
outputArray[0] = inputArray[1] * outputArray[2] * ... * outputArray[n-1]
for j = n-1
outputArray[n-1] = outputArray[0] * outputArray[1] * outputArray[2] * ... * outputArray[n-2]
As an example, if inputArray = { 1, 2, 3, 4 }, then
outputArray = { 2*3*4, 1*3*4, 1*2*4, 1*2*3 }.
Your program should run in O(n) time and should be space efficient.
Input format :
First line of input contains N , number of elements in list.
Next N lines will each contain an element (a signed integer)
Output format :
Print the output list of numbers.
Sample input :
4
5
2
2
3
Sample ouput :
12
30
30
20
Constraint :
You may assume that:
- The input array size will always have at least two elements in it, that is, n >= 2.
- The product of any subset of the input will never exceed the value of a 64 bit integer.
- The maximum length of input array is 1000.
'''
def mult_except_self(l):
zero_count = l.count(0)
if zero_count > 1:
return [0 for i in xrange(len(l))]
elif zero_count == 1:
zero_index = l.index(0)
mult1 = reduce(lambda x,y: x*y, l[:zero_index])
mult2 = reduce(lambda x,y: x*y, l[zero_index+1:])
return ([0 for i in xrange(zero_index)] +
[mult1 * mult2] +
[0 for i in xrange(zero_index+1, len(l))])
else:
mult = reduce(lambda x,y: x*y, l)
res = []
for e in l:
res.append(mult/e)
return res
def main():
n = int(raw_input())
l = []
for i in xrange(n):
l.append(int(raw_input()))
for r in mult_except_self(l):
print r
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment