La formattazione triangolo di Pascal
-
30-09-2019 - |
Domanda
Attualmente sto lavorando su un compito a casa per generare ciò che è noto come di Pascal triangolo in Python .
Finora, questo è quello che ho:
def mytri(myrange):
trianglevar = [[1]]
for i in range(1, myrange):
tempvar = [1]
for n in range(0, i-1):
tempvar.append(trianglevar[i-1][n]+trianglevar[i-1][n+1])
tempvar.append(1)
trianglevar.append(tempvar)
return trianglevar
def mymenu():
for i in mytri(int(raw_input("Please enter the height of the triangle: "))):
print i
print '\n'
choicevar = raw_input("Would you like to create another triangle? (y/n): ")
if choicevar == "y":
mymenu()
else:
print "Goodbye."
mymenu()
Che cosa fa il programma fino a questo punto è eseguire il calcolo per il triangolo. Calcola i numeri in ogni riga (iniziando con 1), e si ferma dopo aver raggiunto il numero di righe specificato dall'utilizzatore.
Comunque, io non sono sicuro di come formattare il mio triangolo. Attualmente stampa come:
[1]
[1, 1]
[1, 2, 1]
[1, 3, 3, 1]
[1, 4, 6, 4, 1]
...etc.
L'output che voglio è:
[1]
[1, 1]
[1, 2, 1]
[1, 3, 3, 1]
[1, 4, 6, 4, 1]
...etc.
(E 'un po' fuori a causa delle staffe / virgole, ma sto solo cercando di ottenere il formato generale verso il basso al momento.)
Grazie per tutto l'aiuto che potete offrire!
Soluzione
h = int(raw_input("Please enter the height of the triangle: "))
for i in mytri(h):
print " " * (h * 2), i
h -= 1
Così qui si stampa 2 spazi per ogni livello della piramide. Prima linea viene rientrato dal doppio del numero altezza degli spazi. Come, scendendo di un livello, si riduce il rientro per 2.
Altri suggerimenti
Una volta che avete le righe, si avrebbe probabilmente l'ultima riga come il più lungo.
Dal momento che semplicemente stampare, è possibile prendere la l = len(str(rows[-1]))
e poi, che si combinano con un str(rows[i]).center(l)
per ogni riga.
Modifica non era a conoscenza che dobbiamo dare tutte le risposte ai compiti a casa ... Se è così:
def mytri(myrange):
rows = list()
lr = None # Last row
for i in xrange(myrange+1):
try:
lr = [1] + [lr[i] + lr[i+1] for i in range(len(lr) - 1)] + [1]
except TypeError:
lr = [1]
#rows.append(str(lr))
rows.append(' '.join(str(v) for v in lr))
return rows
rows = mytri(10)
l = len(rows[-1])
print '\n'.join(v.center(l) for v in rows)
output sarebbe
1 1 1 1 2 1 1 3 3 1 1 4 6 4 1 1 5 10 10 5 1 1 6 15 20 15 6 1 1 7 21 35 35 21 7 1 1 8 28 56 70 56 28 8 1 1 9 36 84 126 126 84 36 9 1 1 10 45 120 210 252 210 120 45 10 1
Invece di rigenerazione delle righe precedenti ad ogni iterazione, è possibile produrre ogni riga come averlo generato:
def mytri(height):
start = [1]
for _ in xrange(height): # "_" for an unused variable
yield start # loop written "backwards" for simplicity,
# though this does generate one unused row
next_row = [1]
for a, b in zip(start, start[1:]): # slicing creates a new list, not a
next_row.append(a + b) # concern for this problem, but in
next_row.append(1) # others you could use itertools.islice
start = next_row # to avoid that
Ora enumerare le all'indietro altezza con ogni riga:
height = int(raw_input("Height: "))
for n, row in zip(xrange(height - 1, -1, -1), mytri(height)):
print " " * n, " ".join("%5d" % x for x in row)
Questa rapidamente è allineata con molto più righe, ma dovrebbe arrivare andando nella giusta direzione.
È necessario pad tutti i numeri in modo che siano la stessa larghezza
È inoltre necessario aggiungere un po 'imbottitura sul lato sinistro
def mymenu():
res = mytri(int(raw_input("Please enter the height of the triangle: ")))
width = len(str(res[-1][len(res[-1])/2]))
for i, row in enumerate(res):
print " "*(width*(len(res)-i)/2)+" ".join(str(x).rjust(width) for x in row)
print '\n'
choicevar = raw_input("Would you like to create another triangle? (y/n): ")
if choicevar == "y":
mymenu()
else:
print "Goodbye."
uscita:
Please enter the height of the triangle: 10
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1
1 6 15 20 15 6 1
1 7 21 35 35 21 7 1
1 8 28 56 70 56 28 8 1
1 9 36 84 126 126 84 36 9 1
n=input('enter n:')
z=0
d=' '
while z<n:
d=d+' '
z=z+1
print d,1
l1=[1]
l2=[1,1]
def space(n,a):
s=''
while a<n:
s=s+' '
a=a+1
return s
def digit(n):
r=1
k=0
while r!=0:
r=n/10**k
k=k+1
return k-1
def print_l(l1,b):
d=''
d='\n'+space(b-1,0)*3
i=0
while i<len(l1):
d=d+' '*(6-digit(l1[i]))+str(l1[i])
i=i+1
print d
b=n-1
k=1
while k<n:
l2=l1
l1=[1]
i=1
while len(l1)<len(l2):
if i>len(l2)/2:
l1.append(l1[len(l2)-i])
else:
l1.append(l2[i-1]+l2[i])
i=i+1
k=k+1
l1.append(1)
print_l(l1,b)
b=b-1