I need help with a simple program to print a table of numbers like this. It only has to work for when n is an odd number and not for even numbers. like n = 3, 5, 7, 27 I nearly finished it but can't figure it out to the end. A solution using for loop is preferred. My code only works for table(5) but not for table(9) for example.
def table(n: int):
for i in range(n // 2 1):
for j in range(n):
if j <= (n // 2):
print(n-i-j, end="")
else:
print(j-i 1, end="")
print()
for x in range(n // 2):
for y in range(n):
if y <= (n // 2):
print(n // 2 x 2 - y, end="")
else:
print(y // 2 x 2, end="")
print()
How it is supposed to be:
5 4 3 4 5
4 3 2 3 4
3 2 1 2 3
4 3 2 3 4
5 4 3 4 5
table(9)
my output(wrong):
9 8 7 6 5 6 7 8 9
8 7 6 5 4 5 6 7 8
7 6 5 4 3 4 5 6 7
6 5 4 3 2 3 4 5 6
5 4 3 2 1 2 3 4 5
6 5 4 3 2 4 5 5 6
7 6 5 4 3 5 6 6 7
8 7 6 5 4 6 7 7 8
9 8 7 6 5 7 8 8 9
what it should be:
9 8 7 6 5 6 7 8 9
8 7 6 5 4 5 6 7 8
7 6 5 4 3 4 5 6 7
6 5 4 3 2 3 4 5 6
5 4 3 2 1 2 3 4 5
6 5 4 3 2 3 4 5 6
7 6 5 4 3 4 5 6 7
8 7 6 5 4 5 6 7 8
9 8 7 6 5 6 7 8 9
CodePudding user response:
def table(n: int):
for i in range(n // 2 1):
for j in range(n):
if j <= (n // 2):
print(n-i-j, end="")
else:
print(j-i 1, end="")
print()
for x in range(n // 2):
for y in range(n):
if y <= (n // 2):
print(n // 2 x 2 - y, end="")
else:
# should be this instead of y//2
print(x 2 - n//2 y, end="")
print()
but actually you can do it in one line:
n = 9
[[1 abs(i-n//2) abs(j-n//2) for j in range(n)] for i in range(n)]
[[9, 8, 7, 6, 5, 6, 7, 8, 9],
[8, 7, 6, 5, 4, 5, 6, 7, 8],
[7, 6, 5, 4, 3, 4, 5, 6, 7],
[6, 5, 4, 3, 2, 3, 4, 5, 6],
[5, 4, 3, 2, 1, 2, 3, 4, 5],
[6, 5, 4, 3, 2, 3, 4, 5, 6],
[7, 6, 5, 4, 3, 4, 5, 6, 7],
[8, 7, 6, 5, 4, 5, 6, 7, 8],
[9, 8, 7, 6, 5, 6, 7, 8, 9]]