[Tutor] more newbie questions
Lloyd Kvam
pythontutor@venix.com
Tue, 30 Apr 2002 18:09:27 -0400
At the risk of totally beating this kind of subject to death, I had
written a short program to produce pascal triangles. I've used it
for up to 20 rows (actually 0 - 20). I used the new fractional
division so this won't work on an old version.
from __future__ import division
def fact(n,r=None):
if r is None: r = n
assert 0 <= r <= n, "r must be between 0 and n"
if r > 1:
return n * fact(n-1, r-1)
else:
return n or 1 # 0! == 1
def combo(n, r=None):
if r is None: r = int(n/2)
assert 0 <= r <= n, "r must be between 0 and n"
return int(fact(n,r)/fact(r))
def pascal(rows=5):
numlen = len(str(combo(rows)))
for i in range(rows+1):
indent = int( (numlen+1)*((rows - i)/2))
print " "*indent,
for r in range(i+1):
ptn = combo(i,r)
# attempt to center numbers in their slot
ptnlen = len(str(ptn))
ptnpad = int((numlen - ptnlen + 1) / 2)
ptnlen = numlen - ptnpad
print "%*s%s" % (ptnlen, ptn, " "*ptnpad),
print
pascal()
Danny Yoo wrote:
>
> On Tue, 30 Apr 2002, Lloyd Kvam wrote:
>
>
>> >>> for row in grid:
>>... print "%s%s%s" % tuple(row)
>>...
>>123
>>456
>>789
>>
>>Then I had a brain storm for when you don't know the size of the
>>row:
>> >>> for row in grid:
>>... fmt = "%s" * len(row)
>>... print fmt % tuple(row)
>>...
>>123
>>456
>>789
>>
>
>
> Here's an alternative way of doing it, but it needs a little more care:
>
> ###
>
>>>>def printgrid(grid):
>>>>
> ... for row in grid:
> ... stringed_row = map(str, row)
> ... print ''.join(stringed_row)
> ...
>
>>>>grid = [[1, 2, 3],
>>>>
> ... [4, 5, 6],
> ... [7, 8, 9]]
>
>>>>printgrid(grid)
>>>>
> 123
> 456
> 789
> ###
>
> One part of the printgrid() definition might seem a little weird, so it
> might be good to mention it. The reason why printGrid() does a
> 'map(str, row)' thing right before the joining is because string
> joining assumes that it's joining a list of strings:
>
> ###
>
>>>>print ''.join(['one', 'two', 'three'])
>>>>
> onetwothree
>
>>>>print ''.join([1, 2, 3])
>>>>
> Traceback (most recent call last):
> File "<stdin>", line 1, in ?
> TypeError: sequence item 0: expected string, int found
> ###
>
> and trying to string.join() a list of numbers will result in a TypeError,
> warning us that we're doing something potentially suspicious.
>
> The map() is there to apply the str()ing function on every element of row,
> and collects all those results into stringed_row, so that the
> string.join() can work.
>
>
>
--
Lloyd Kvam
Venix Corp.
1 Court Street, Suite 378
Lebanon, NH 03766-1358
voice:
603-443-6155
fax:
801-459-9582