Pascal Triangle in without loops?

Viewed 104

I am trying to implement a Pascal triangle whose 1st row is 0 without using import functions such as lists. While I think it is fairly easy to do in more common languages like Python, I can not seem to put into my mind how I can do it in Erlang. With that, any help on how I can solve this is appreciated.

-module(s).

-compile(export_all).

main()->
    pascal(3).


calc(X, Y) ->
    if
    Y == 0 -> 1;
    X == Y -> 1;
    true -> calc(X-1, Y-1) + calc(X-1, Y)
    end.

pascal(N) -> 
    Row = 0,
    Col = 0,
    pascal1(N, Row, Col).

pascal1(N, Row, Col) ->
    if
    Row =< N ->pascal2(N, Row, Col);
    true -> io:write("done")
    end.

pascal2(N, Row, Col) ->
    if 
    Col =< Row -> calc(Row, Col);
    true -> pascal1(N, Row+1, NewCol = 0)
    end.

What I get from this is: [100,111,110,101] What I need to get is: 1 11 121 1331

I decided to recreate this in python in such a way that it also does not use loops. I think it is possible with recursion, but I don't think I have done it right.

def calc (x, y):
    if (x == 0 & (y == 0 | y == x)):
        print (1)
    else:
        print (calc(x-1, y) + calc(x-1, y-1))

def pascal(n):
    row = 0
    col = 0
    pascal1(n, row, col)

def pascal1(n, row, col):
    if row <= n:
        pascal2(n, row, col)
    else:
        print("done")

def pascal2(n, row, col):
    if col <= row:
        calc(row, col)
        pascal2(n, row, col + 1)
    else:
        pascal1(n, row + 1, col = 0)

print(pascal(3))

print results to 1 1 1 and a bunch of errors

1 Answers

One problem here is that your functions don't return any values. In Erlang, functions implicitly return the value of the last expression, but in Python you need to explicitly use a return statement.

Something like:

def calc (x, y):
    if (x == 0 & (y == 0 | y == x)):
        result = 1
    else:
        result = calc(x-1, y) + calc(x-1, y-1)
    print(result)
    return result

And for the pascal function:

def pascal(n):
    row = 0
    col = 0
    return pascal1(n, row, col)

And so on.

Related