[Tutor] Help me with two dimensional arrays in Python

Luke Paireepinart rabidpoobear at gmail.com
Thu Oct 5 15:54:30 CEST 2006


Asrarahmed Kadri wrote:
> Its something very close.
> What I want is:
>  
> 1
> 1 1
> 1 2 1
> 1 3 3 1
> 1 4 6 4 1
>  
> This can be done using arrays, right or is there any other way??
They're not arrays, they're lists!
arrays imply contiguous memory blocks and single data types.
Lists are neither of these.
> My logic in C is:
>  
> int arr[5][5];
> for (i=0;i<5;i++)
> {
>    flag = 0;
>    for (j=0;j<=i;j++)
> {
>    if (flag == 0 || j == i)  // print 1 if the array element is the 
> first or the last number
>      {
>       arr[i][j] = 1;
>       flag = 1;
>     }
>   arr[i][j] = arr[i-1][j-1] + arr[i-1][j];
> }
Yes, you could do this in Python.
I'm guessing it'd be something like this:

lst = []
for x in range(5):
    tmp = []
    for y in range(x):
       if y == 0:
          tmp.append(1)
       else:
          tmp.append(tmp[y-1]) #this line would be different
    lst.append(tmp)

That's the best I can do.

HTH,
-Luke


More information about the Tutor mailing list