I currently have a populated list full of nodes in a path from one node to another. I need to stylize the printing of the path as such:
JavaScript
x
3
1
node -> node -> node -> node ->
2
node -> node
3
I currently have this code to do so:
JavaScript
1
45
45
1
if len(path) %4 == 0:
2
for i in range(0, len(path)):
3
if i+1 % 4 == 0:
4
print(print_queue[0]+' -> '+print_queue[1]+' -> '+print_queue[2]+' -> '+print_queue[3]+' -> ')
5
print_queue = []
6
else:
7
print_queue.append(path[i])
8
if len(path) %4 == 1:
9
path.append(' ')
10
for i in range(0, len(path)):
11
if path[i] == ' ':
12
break
13
if i+1 % 4 == 0:
14
print(print_queue[0]+' -> '+print_queue[1]+' -> '+print_queue[2]+' -> '+print_queue[3]+' -> ')
15
print_queue = []
16
else:
17
print_queue.append(path[i])
18
if len(path) %4 == 2:
19
path.append(' ')
20
for i in range(0, len(path)):
21
if path[i] == ' ':
22
break
23
if i+1 % 4 == 0:
24
print(print_queue[0]+' -> '+print_queue[1]+' -> '+print_queue[2]+' -> '+print_queue[3]+' -> ')
25
print_queue = []
26
else:
27
print_queue.append(path[i])
28
if len(path) %4 == 3:
29
path.append(' ')
30
for i in range(0, len(path)):
31
if path[i] == ' ':
32
break
33
if i+1 % 4 == 0:
34
print(print_queue[0]+' -> '+print_queue[1]+' -> '+print_queue[2]+' -> '+print_queue[3]+' -> ')
35
print_queue = []
36
else:
37
print_queue.append(path[i])
38
if print_queue != []:
39
if len(print_queue) == 1:
40
print(print_queue[0])
41
if len(print_queue) == 2:
42
print(print_queue[0]+' -> '+print_queue[1])
43
if len(print_queue) == 3:
44
print(print_queue[0]+' -> '+print_queue[1]+' -> '+print_queue[2])
45
But the path is not being printed. The path list is populated, but the program does not give any output.
What do I need to change in order for this path to print?
Advertisement
Answer
It looks like you want to print each element in the path with ” -> ” between them.
JavaScript
1
2
1
print(" -> ".join(path))
2
should print them that way.
If you want a ” -> ” on the end too, just add one on the end in the print statement
JavaScript
1
2
1
print(" -> ".join(path) + " -> ")
2
so a path of ["a", "b", "c"]
will print a -> b -> c ->
If you want it to break on multiples of 4 nodes you can break the array into chunks of 4 first
JavaScript
1
3
1
path = ["a", "b", "c", "d", "e"]
2
print(" -> n".join([" -> ".join(path[i:i+4]) for i in range(0, len(path), 4)]))
3
which will print
JavaScript
1
3
1
a -> b -> c -> d ->
2
e
3