I want to print an array that results in the following (without using libraries):
1 2 3 4 5 6
6 5 4 3 2 1
1 2 3 4 5 6
6 5 4 3 2 1
1 2 3 4 5 6
6 5 4 3 2 1
I have solved it in two ways, but I feel both are redundant and I think there must be some more optimal way to do it, which I am overlooking.
This is the first:
for i in range(1,7):
if i % 2 != 0:
number = 1
else:
number = 6
for j in range(1,7):
if i % 2 != 0:
print(number, end=' ')
number += 1
else:
print(number, end=' ')
number = number -1
print(' ')
This is the second:
for i in range(1, 7):
if i % 2 == 0:
number = 6
for j in range(1,7):
print(number, end=' ')
number -= 1
else:
number = 1
for j in range(1,7):
print(number, end=' ')
number += 1
print('')
I don't know if this is more efficient or not, but surely it is more pythonic:
This returns an array of
max
xmax
of the following form:Correction Instead of adding the reference to the variable
fila
inside the array, we add a copy of it using the operator*
that unpacks an iterable into its component elements (popularly known as the splat operator ) and creates a "shallow" copy of the list. Since its elements are all primitive objects, the copy can be considered "deep" or complete.You can consult the documentation of
reversed()
and an example of use I hope it helps you to solve the problemA solution:
Explanation:
produces a list of numeric strings from 1 to the maximum value chosen:
Then we apply
[::valor]
to copy the string. Ifvalor
is1
, the copy is the same as the original; if we put-1
, then the copy is reversed.To determine whether to invert or not, we use modulo two (
% 2
), so the result will alternate between 0 and 1. We use this value to index the list[-1,1]
, which finally gives us the necessary step for the copy.Result