for i in range(1, 11):
print(str(i).rjust(2), str(i**2).rjust(3), str(i**3).rjust(4))
1 1 1 2 4 8 3 9 27 4 16 64 5 25 125 6 36 216 7 49 343 8 64 512 9 81 729 10 100 1000
"text".rjust(50)
' text'
"text".ljust(50)
'text '
"text".center(50)
' text '
def make_triangle(n):
return ["*"*row for row in range(1, n+1)]
make_triangle(5)
['*', '**', '***', '****', '*****']
for row in make_triangle(5):
print(row)
* ** *** **** *****
def prety_print(triangle):
width = len(triangle[-1])
for row in triangle:
print(row.center(width))
prety_print(make_triangle(10))
*
**
***
****
*****
******
*******
********
*********
**********
def format_row(row):
return " ".join(list(row))
def prety_print(triangle):
base = len(triangle[-1])
width = base + base -1
for row in triangle:
row_ = format_row(row)
print(row_.center(width))
prety_print(make_triangle(10))
*
* *
* * *
* * * *
* * * * *
* * * * * *
* * * * * * *
* * * * * * * *
* * * * * * * * *
* * * * * * * * * *
Pascal Triangle
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1
def pascal(n):
"""
>>> pascal(1)
[[1]]
>>> pascal(5)
[[1], [1,1], [1, 2, 1], [1, 3, 3, 1], [1, 4, 6, 4, 1]]
"""
pass
11*11
121
111*111
12321
[1 , 4 , 6 , 4 , 1 ]
[1, 1+4, 4+6, 6+4, 4+1, 1]
1 4 6 4 1
---
---
---
---
1 4 6 4 1 0
0 1 4 6 4 1
------------------
1 5 10 10 5 1
def find_runing_sum(items):
r_s = []
for i, item in enumerate(items[:-1]):
r_s.append(item + items[i+1])
return r_s
def find_next_row(row):
runing_sum = find_runing_sum(row)
return [1] + runing_sum + [1]
def sum_shifted_rows(row):
first = row + [0]
second = [0] + row
return [a+b for a,b in zip(first, second)]
find_runing_sum([1,3, 3, 1])
[4, 6, 4]
find_next_row([1, 3, 3, 1])
[1, 4, 6, 4, 1]
sum_shifted_rows([1, 3, 3, 1])
[1, 4, 6, 4, 1]
def pascal(n):
tr = [[1]]
for i in range(n-1):
tr.append(find_next_row(tr[-1]))
return tr
pascal(5)
[[1], [1, 1], [1, 2, 1], [1, 3, 3, 1], [1, 4, 6, 4, 1]]
def pascal(n):
tr = [[1]]
for i in range(n-1):
tr.append(sum_shifted_rows(tr[-1]))
return tr
pascal(6)
[[1], [1, 1], [1, 2, 1], [1, 3, 3, 1], [1, 4, 6, 4, 1], [1, 5, 10, 10, 5, 1]]
[1, 2, 3] + [2, 3, 4]
[1, 2, 3, 2, 3, 4]
[1] + [3, 3] + [1]
[1, 3, 3, 1]
[1]
[1]
words = "hello how are you and whats your task".split()
words
['hello', 'how', 'are', 'you', 'and', 'whats', 'your', 'task']
for item in words:
print(item)
hello how are you and whats your task
for i, item in enumerate(words):
print(i, item)
0 hello 1 how 2 are 3 you 4 and 5 whats 6 your 7 task