Python 2.7 List Comprehension Number Pyramid
I am trying to create the following number pyramid using nested list comprehension and string formatting. 1 2 4 3 6 9 4 8 12 16 5 10 15 20 25 6 12 18 24 30 36 7 14
Solution 1:
You could use range
to build up each nested list, like so:
# Generation
result= [range(x, x**2+1, x) for x inrange(1, 8)]
# Formatting
print('\n'.join(''.join(str(x).ljust(4) for x inrow) forrowinresult))
Output:
1
2 4
3 6 9
4 8 12 16
5 10 15 20 25
6 12 18 24 30 36
7 14 21 28 35 42 49
Solution 2:
You can join
a list of lists (in this case, a generator of generators) by newlines
print('\n'.join(' '.join(str(i*j) for j inrange(1, i+1)) for i inrange(1, n+1)))
#1#2 4#3 6 9#4 8 12 16#5 10 15 20 25#6 12 18 24 30 36#7 14 21 28 35 42 49
and if you want to have the list that creates it just do:
rows= [[i*j for j inrange(1, i+1)] for i inrange(1, n+1)]
Post a Comment for "Python 2.7 List Comprehension Number Pyramid"