DEV Community

Discussion on: Daily Coding Problem #2

Collapse
 
edh_developer profile image
edh_developer

In python 2.7, no division, O(n) time. The tradeoff is using a bunch of memory, if the list is very long.

values = map(int,raw_input().split(' '))


def getLeftProducts(rawValues):
        leftProducts = []

        if len(rawValues) > 0:
                total = 1
                for val in rawValues:
                        total *= val
                        leftProducts.append(total)

        return leftProducts


def getRightProducts(rawValues):
        rightProducts = []

        if len(rawValues) > 0:
                total = 1
                index = len(rawValues) - 1

                while index >= 0:
                        total *= rawValues[index]
                        rightProducts.insert(0,total)
                        index -= 1

        return rightProducts


def processList(rawValues):
        if len(rawValues) < 2:
                return rawValues

        resultList = []
        leftList = getLeftProducts(rawValues)
        rightList = getRightProducts(rawValues)

        resultList.append(rightList[1])

        index = 1
        while index < (len(rawValues) - 1):
                resultList.append( leftList[index - 1] * rightList[index + 1] )
                index += 1

        resultList.append(leftList[index - 1])

        return resultList


print ' '.join(map(str,processList(values)))