Computer >> Computer tutorials >  >> Programming >> Python

Clumsy Factorial in Python


As we know that the factorial of a positive integer n is the product of all positive integers less than or equal to n. So factorial(10) = 10 * 9 * 8 * 7 * 6 * 5 * 4 * 3 * 2 * 1. We will try to find a clumsy factorial: using the integers in decreasing order, we swap out the multiply operations for a fixed rotation of operations: multiply (*), divide (/), add (+) and subtract (-) in this order.

The clumsy factorial is like clumsy(10) = 10 * 9 / 8 + 7 - 6 * 5 / 4 + 3 - 2 * 1. However, these operations are still applied using the usual order of operations of arithmetic: we perform all multiplication and division steps before any addition or subtraction steps, and multiplication and division steps are processed left to right. The division that we are using that is floor division such that 10 * 9 / 8 equals 11. This guarantees the result is an integer.

So for example, if the input is 10, then the result will be 12, as 12 = 10 * 9 / 8 + 7 – 6 * 5 / 4 + 3 – 2 * 1

To solve this, we will follow these steps −

  • define opeartions array, and store the operators [* / + -], create one empty stack, and push N into the stack.
  • index := 0
  • decrease N by 1
  • while N is not 0:
    • if operation[index] = *, then
      • if stack top element is >= 0, then update stack top element as top_element := N * top_element
      • otherwise stack top element := -1 * |N * stack top element|
    • else if operation[index] is /, then
      • if stack top element is >= 0, then update stack top element as top_element := top_element / N
      • otherwise stack top element := -1 * |stack top element / N|
    • else if operation[index] is +, then
      • insert N into stack
    • else insert (-1 * N) into stack
    • index := (index + 1) mod length of operations array
    • decrease N by 1
  • return sum of the stack elements.

Let us see the following implementation to get better understanding −

Example

class Solution(object):
   def clumsy(self, N):
      operations = ["*","/","+","-"]
      stack = []
      index = 0
      stack.append(N)
      N-=1
      while N:
         if operations[index] == "*":
            if stack[-1]>=0:
               stack[-1] *=N
            else:
               stack[-1] = -1*(abs(stack[-1])*N)
         elif operations[index] == "/":
            if stack[-1]>=0:
               stack[-1] //=N
            else:
               stack[-1] = -1*(abs(stack[-1])//N)
         elif operations[index] == "+":
            stack.append(N)
         else:
            stack.append(-1*N)
         index = (index+1) % len(operations)
         N-=1
      return sum(stack)
ob = Solution()
print(ob.clumsy(10))

Input

10

Output

12