Python For Loop Triangle [closed] - python

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
I'm trying to make a triangle that looks like this
10
11 12
13 14 15
16 17 18 19
20 21 22 23 24
25 26 27 28 29 30
31 32 33 34 35 36 37
38 39 40 41 42 43 44 45
46 47 48 49 50 51 52 53 54
I am trying to use two for loops with one nested. Here is as close as I have gotten so far.
for j in range(11):
print(end='\n')
for i in range(j+1):
print(i+j,'',end='')
print(end='\n')
I'm pretty sure I need to create a variable, but not really sure how to incorporate it into the loop.

Here you go:
>>> a=range(10, 55)
>>> for i in range(10):
... print(' '.join(repr(e) for e in a[:i+1]))
... a = a[i+1:]
...
10
11 12
13 14 15
16 17 18 19
20 21 22 23 24
25 26 27 28 29 30
31 32 33 34 35 36 37
38 39 40 41 42 43 44 45
46 47 48 49 50 51 52 53 54

How about short and simple like this:
k=10
for i in range(9):
for j in range(i+1):
print(k, end='')
k+=1
print('')

Here is another single for loop based solution:
number = 10
for line_length in range(9):
print(*range(number, number + line_length + 1))
number += line_length + 1
Giving:
10
11 12
13 14 15
16 17 18 19
20 21 22 23 24
25 26 27 28 29 30
31 32 33 34 35 36 37
38 39 40 41 42 43 44 45
46 47 48 49 50 51 52 53 54

I like Maelstrom's short and sweet answer, but if you want to look at it mathematically, you might do something like this instead:
>>> for i in range(1, 10):
... j = 10 + i * (i - 1) // 2
... print(*range(j, j + i)) # This line edited per lvc's comment
...
10
11 12
13 14 15
16 17 18 19
20 21 22 23 24
25 26 27 28 29 30
31 32 33 34 35 36 37
38 39 40 41 42 43 44 45
46 47 48 49 50 51 52 53 54

Use one variable to keep track of the current number and one to keep track of the tier you are on
num = 10;
tier = 1;
tiers = 10;
for i in range(tiers):
for j in range(tier):
print(num + " ");
num = num + 1;
print("\n");
tier = tier + 1

You can change the triangle height by adjusting the triangle_height variable and the starting element by changing print_number.
print_number = 10
triangle_height = 9
for level_element_count in range(triangle_height):
print('\n')
while level_element_count > -1:
print(print_number, '', end='')
print_number += 1
level_element_count -= 1
print('\n')

Just for fun.
This is related to a common pattern where you divide a given sequence (here, the numbers from 10 to 54, inclusive) into non-overlapping 'windows', to do some analysis on, say, 10 values at a time. The twist here is that each window is one element larger than the last.
This looks like a job for itertools!
import itertools as it
def increasing_windows(i, start=1, step=1):
'''yield non-overlapping windows from iterable `i`,
increasing in size from `start` by `step`.
'''
pos = 0
for size in it.count(start, step):
yield it.islice(i, pos, pos+size)
pos += size
for line in it.islice(increasing_windows(range(10, 55)), 9):
print(*line)

Try this
counter = 10
for i in range(10):
output = ""
for j in range(i):
output = output + " " + str(counter)
counter += 1
print(output)
Output:
10
11 12
13 14 15
16 17 18 19
20 21 22 23 24
25 26 27 28 29 30
31 32 33 34 35 36 37
38 39 40 41 42 43 44 45
46 47 48 49 50 51 52 53 54
Explanation:
First loop controls the width of the triangle and second loop controls the content and hence the height. We need to convert an integer to string and concatenate. We create proper output in a string variable in each iteration of second loop and then display it once it gets finished.The key thing is to iterate second loop according to the first one, i.e. loop it as much as first does

You could write a generator:
def number_triangle(start, nrows):
current = start
for length in range(1, nrows+1):
yield range(current, current+length)
current += length
>>> for row in number_triangle(10, 9):
... print(*row)
10
11 12
13 14 15
16 17 18 19
20 21 22 23 24
25 26 27 28 29 30
31 32 33 34 35 36 37
38 39 40 41 42 43 44 45
46 47 48 49 50 51 52 53 54
>>> for row in number_triangle(1, 12):
... print(*row)
1
2 3
4 5 6
7 8 9 10
11 12 13 14 15
16 17 18 19 20 21
22 23 24 25 26 27 28
29 30 31 32 33 34 35 36
37 38 39 40 41 42 43 44 45
46 47 48 49 50 51 52 53 54 55
56 57 58 59 60 61 62 63 64 65 66
67 68 69 70 71 72 73 74 75 76 77 78
Or you could have an infinite generator and leave it up to the caller to control how many rows to generate:
def number_triangle(start=0):
length = 1
while True:
yield range(start, start+length)
start += length
length += 1
>>> nt = number_triangle()
>>> for i in range(15):
... print(*next(nt))
0
1 2
3 4 5
6 7 8 9
10 11 12 13 14
15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30 31 32 33 34 35
36 37 38 39 40 41 42 43 44
45 46 47 48 49 50 51 52 53 54
55 56 57 58 59 60 61 62 63 64 65
66 67 68 69 70 71 72 73 74 75 76 77
78 79 80 81 82 83 84 85 86 87 88 89 90
91 92 93 94 95 96 97 98 99 100 101 102 103 104
105 106 107 108 109 110 111 112 113 114 115 116 117 118 119

No need for nested loop:
a = range(10, 55)
flag = 0
current = 0
for i, e in enumerate(a):
print e,
if flag == i:
current += 1
flag = i + 1 + current
print '\n',

Related

printing a number table of square

n: 8
0 1 2 3 4 5 6 7
8 9 10 11 12 13 14 15
16 17 18 19 20 21 22 23
24 25 26 27 28 29 30 31
32 33 34 35 36 37 38 39
40 41 42 43 44 45 46 47
48 49 50 51 52 53 54 55
56 57 58 59 60 61 62 63
How to print a number table like this in python with n that can be any number?
I am using a very stupid way to print it but the result is not the one expected:
n = int(input('n: '))
if n == 4:
print(' 0 1 2 3\n4 5 6 7\n8 9 10 11\n12 13 14 15')
if n == 5:
print(' 0 1 2 3 4\n5 6 7 8 9\n10 11 12 13 14\n15 16 17 18 19\n20 21 22 23 24')
if n == 6:
print(' 0 1 2 3 4 5\n6 7 8 9 10 11\n12 13 14 15 16 17\n18 19 20 21 22 23\n24 25 26 27 28 29\n30 31 32 33 34 35')
if n == 7:
print(' 0 1 2 3 4 5 6\n7 8 9 10 11 12 13\n14 15 16 17 18 19 20\n21 22 23 24 25 26 27\n28 29 30 31 32 33 34\n35 36 37 38 39 40 41\n42 43 44 45 46 47 48')
if n == 8:
print(' 0 1 2 3 4 5 6 7\n8 9 10 11 12 13 14 15\n16 17 18 19 20 21 22 23\n24 25 26 27 28 29 30 31\n32 33 34 35 36 37 38 39\n40 41 42 43 44 45 46 47\n48 49 50 51 52 53 54 55\n56 57 58 59 60 61 62 63')
if n == 9:
print(' 0 1 2 3 4 5 6 7 8\n9 10 11 12 13 14 15 16 17\n18 19 20 21 22 23 24 25 26\n27 28 29 30 31 32 33 34 35\n36 37 38 39 40 41 42 43 44\n45 46 47 48 49 50 51 52 53\n54 55 56 57 58 59 60 61 62\n63 64 65 66 67 68 69 70 71\n72 73 74 75 76 77 78 79 80')
if n == 10:
print(' 0 1 2 3 4 5 6 7 8 9\n10 11 12 13 14 15 16 17 18 19\n20 21 22 23 24 25 26 27 28 29\n30 31 32 33 34 35 36 37 38 39\n40 41 42 43 44 45 46 47 48 49\n50 51 52 53 54 55 56 57 58 59\n60 61 62 63 64 65 66 67 68 69\n70 71 72 73 74 75 76 77 78 79\n80 81 82 83 84 85 86 87 88 89\n90 91 92 93 94 95 96 97 98 99')
here is the result:
n: 8
0 1 2 3 4 5 6 7
8 9 10 11 12 13 14 15
16 17 18 19 20 21 22 23
24 25 26 27 28 29 30 31
32 33 34 35 36 37 38 39
40 41 42 43 44 45 46 47
48 49 50 51 52 53 54 55
56 57 58 59 60 61 62 63
I won't show you the code directly, here is some tips for you. Do you know % operator in python? And how to use it to break lines. As for the format, zfill function will help you. You may need to learn for or while statement to solve your problem
You can do this with a range loop and a list comprehension.
In order for the output to look right you need to figure out what the width of the largest value in the square will be. You then need to format each value to fit in that width (right-justified). Something like this:
def number_square(n):
w = len(str(n*n-1))
for r in range(n):
print(*[f'{c:>{w}}' for c in range(r*n, r*n+n)])
number_square(8)
Output:
0 1 2 3 4 5 6 7
8 9 10 11 12 13 14 15
16 17 18 19 20 21 22 23
24 25 26 27 28 29 30 31
32 33 34 35 36 37 38 39
40 41 42 43 44 45 46 47
48 49 50 51 52 53 54 55
56 57 58 59 60 61 62 63

graph_tool: how to avoid that all_circuits function block my script

I'm learning python and I'm doing some experiment with the module graph_tool.
Since the function all_circuits could take a long time to calculate all the cycles, is there a way to stop the function (for example after "X" seconds or after the iterator reaches a certain size) and continue the execution of the script?
Thanks
This is quite simple, actually. The function all_circuits() returns an iterator over all circuits. Therefore, if you want to stop early, all you need is to break the iterations:
g = collection.ns["football"]
for i, c in enumerate(all_circuits(g)):
if i > 10:
print(c)
break
which prints
[ 0 1 25 24 11 10 5 4 9 8 7 6 2 3 26 12 13 15
14 38 18 19 29 30 35 34 31 32 21 20 17 16 23 22 47 46
49 48 44 45 33 37 36 43 42 57 56 27 62 61 54 39 60 59
58 63 64 100 99 89 88 83 53 52 40 41 67 68 50 28 69 70
65 66 75 76 95 87 86 80 79 55 94 82 81 72 74 73 110 114
104 93]
and stops.

Place data from a Pandas DF into a Grid or Template

I have process where the end product is a Pandas DF where the output, which is variable in terms of data and length, is structured like this example of the output.
9 80340796
10 80340797
11 80340798
12 80340799
13 80340800
14 80340801
15 80340802
16 80340803
17 80340804
18 80340805
19 80340806
20 80340807
21 80340808
22 80340809
23 80340810
24 80340811
25 80340812
26 80340813
27 80340814
28 80340815
29 80340816
30 80340817
31 80340818
32 80340819
33 80340820
34 80340821
35 80340822
36 80340823
37 80340824
38 80340825
39 80340826
40 80340827
41 80340828
42 80340829
43 80340830
44 80340831
45 80340832
46 80340833
I need to get the numbers in the second column above, into the following grid format based on the numbers in the first column above.
1 2 3 4 5 6 7 8 9 10 11 12
A 1 9 17 25 33 41 49 57 65 73 81 89
B 2 10 18 26 34 42 50 58 66 74 82 90
C 3 11 19 27 35 43 51 59 67 75 83 91
D 4 12 20 28 36 44 52 60 68 76 84 92
E 5 13 21 29 37 45 53 61 69 77 85 93
F 6 14 22 30 38 46 54 62 70 78 86 94
G 7 15 23 31 39 47 55 63 71 79 87 95
H 8 16 24 32 40 48 56 64 72 80 88 96
So the end result in this example would be
Any advice on how to go about this would be much appreciated. I've been asked for this by a colleague, so the data is easy to read for their team (as it matches the layout of a physical test) but I have no idea how to produce it.
pandas pivot table, can do what you want in your question, but first you have to create 2 auxillary columns, 1 determing which column the value has to go in, another which row it is. You can get that as shown in the following example:
import numpy as np
import pandas as pd
df = pd.DataFrame({'num': list(range(9, 28)), 'val': list(range(80001, 80020))})
max_rows = 8
df['row'] = (df['num']-1)%8
df['col'] = np.ceil(df['num']/8).astype(int)
df.pivot_table(values=['val'], columns=['col'], index=['row'])
val
col 2 3 4
row
0 80001.0 80009.0 80017.0
1 80002.0 80010.0 80018.0
2 80003.0 80011.0 80019.0
3 80004.0 80012.0 NaN
4 80005.0 80013.0 NaN
5 80006.0 80014.0 NaN
6 80007.0 80015.0 NaN
7 80008.0 80016.0 NaN

How to create 1-100 in 10 rows? [duplicate]

This question already has answers here:
How to right-align numeric data?
(5 answers)
Closed 5 years ago.
I'm trying to get the following exercise:
"Write a program containing a pair of neste while loops that displays the integer values 1-100, ten numbers per row, with the columns alignes as below.
1 2 3 4 5 6 7 8 9 10
11 12 13 14 15 16 17 18 19 20
So far I've come up with this:
lijst = list(range(1, 101))
i = 0
while i < 100:
print(lijst[i],"\t", end=" ".format(">"))
i = i+1
if i % 10 == 0:
print("")
Although it produces the things I need, the tabs aren't working. whenever I try to add spaces instead of a tab, things move way too much on the second and further rows.
Furthermore I can't seem to find out why the .format(">") doesn't work. I've tried to apply .format(">3") but that didn't do anything at all.
You can use the {:>5d} format style to right align integers 5 spaces
lijst = list(range(1, 101))
i = 0
while i < 100:
print("{:>5d}".format(lijst[i]), end=" ")
i = i+1
if i % 10 == 0:
print("")
Output:
1 2 3 4 5 6 7 8 9 10
11 12 13 14 15 16 17 18 19 20
21 22 23 24 25 26 27 28 29 30
31 32 33 34 35 36 37 38 39 40
41 42 43 44 45 46 47 48 49 50
51 52 53 54 55 56 57 58 59 60
61 62 63 64 65 66 67 68 69 70
71 72 73 74 75 76 77 78 79 80
81 82 83 84 85 86 87 88 89 90
91 92 93 94 95 96 97 98 99 100

Doing columns with a for loop on a nested list

I'm trying to get:
1 2 3 4 5 6 7 8 9 10
11 12 13 14 15 16 17 18 19 20
21 22 23 24 25 26 27 28 29 30
31 32 33 34 35 36 37 38 39 40
41 42 43 44 45 46 47 48 49 50
51 52 53 54 55 56 57 58 59 60
61 62 63 64 65 66 67 68 69 70
71 72 73 74 75 76 77 78 79 80
81 82 83 84 85 86 87 88 89 90
91 92 93 94 95 96 97 98 99 100
from this:
# nums is a range object
nums = list(range(1, 101))
chunks = []
print(nums)
print()
for i in range(0, len(nums), 10):
chunks.append(nums[i:i+10])
in Python.... I can't for the life of me solve it.
You can just use nested loops to print chunks out like that. Here's an example:
for i in chunks:
for j in i:
print(j, end=" ")
print()
This should produce exactly the same output as in the question:
for chunk in chunks:
print(''.join(str(x).rjust(5 if i else 2) for i, x in enumerate(chunk)))
Update: For every chunk it will first convert numbers to strings with str and then right justify them with rjust that uses space as default fill char. Since the first number on the row has width of 2 and rest of them have width of 5 enumerate is used to track the index so that correct argument can be passed to rjust. Enumerate returns tuples in form (index, item) and the index is then used in 5 if i else 2 to determine if number is first or not so width of 2 or 5 can be used respectively. Finally all the substrings are joined together for a row which is printed to screen.

Categories

Resources