-3

I had written a simple pascal triangle code in python but I am getting a error

def factorial(n):
    c=1
    re=1
    for c in range(n):
        re = re * c;
    return(re)

print "Enter how many rows of pascal triangle u want to show \n"
n=input();
i=1
c=1
for i in range(n):
    for c in range(n-i-1):
        print ""
        for c in range(i):
            a = factorial(i);
            b = factorial(c);
            d = factorial(i-c);
            z = (a/(b*d));
            print "%d" % z
            print "\n"

ERROR:

Traceback (most recent call last):
  File "/home/tanmaya/workspace/abc/a.py", line 19, in <module>
    z = (a/(b*d));
ZeroDivisionError: integer division or modulo by zero
taesu
  • 4,482
  • 4
  • 23
  • 41
Tanu Tanmay
  • 31
  • 1
  • 1
  • 5

2 Answers2

4

ZeroDivisionError means that you were trying to divide or modulo, a number n with 0.
in your case, z = (a/(b*d)) resulted in z = (a/0)

Also, as @theB pointed out, your factorial function is incorrect.

Try fixing those.

Also, you don't really need ; in your code. It's usually the case we put ; when we want to make the code one liner.

taesu
  • 4,482
  • 4
  • 23
  • 41
4

Your factorial() function returns 0 for any input because of how you defined your range.

The range builtin starts at 0 unless otherwise defined so:

for c in range(n):
    re = re * c  # no semicolons in Python

is doing:

re = re * 0

on the first iteration so for all subsequent iterations:

re = 0 * c

will always be 0

Start your range at 1 like so

for c in range(1, n):
    re *= c  # The *= operator is short hand for a = a * b

you can see this more explicityly:

>>> print(list(range(5)))
[0, 1, 2, 3, 4]
>>> print(list(range(1,5)))
[1, 2, 3, 4]
>>> 

or instead of rolling your own function use the one that comes with Python:

>>> from math import factorial
>>> factorial(3)
6

Upon closer reading of your code it seems you tried to circumvent this by setting c = 1 outside your for loop. This is not going to work because the variables you declared outside the loop are being reassigned inside it.

kylieCatt
  • 10,672
  • 5
  • 43
  • 51
  • @TanuTanmay Well I'm not familiar with Pascal triangles so you'll have to open a new question and post your new problem there. – kylieCatt Sep 04 '15 at 03:01