Reputation: 13
I require to create a program that provides the solution:
1
3 2
6 5 4
10 9 8 7
using python.
I've been trying out different ideas for over three weeks, and I can't find a solution. All of the code functions/commands that I am permitted to use have been used in the following attempts.
Various attempts include:
The first piece of code shows some promise, but it keeps getting duplicate items in the x list.
#Attempt 1
n=4
l = [0, 1, 2, 3, 4]
x = [0]
for i in range (0, n+1):
k = 0
j = i
while k <= i and j != x[j-1]:
j += l[k]
print (j, end = " ")
x.append(j)
while j != i and j != x[j-1]:
j -= 1
if j > i:
print (j, end = " ")
x.append(j)
print (x)
k+=1
#Attempt 2
n = 4
print (1)
for a in range (2, n):
for i in range (2, n*2, a):
j = i
j+=i-1
print (j, end =" ")
while j>i:
j-=1
print (j, end= " ")
print ()
#Attempt 3
n = 4
l = [1, 2, 3, 4]
for i in range (0, n):
for j in range (0, n*3, l[i]):
while j >= i:
print (j, end = " ")
j-=1
print ()
The output ought to be
1
3 2
6 5 4
10 9 8 7
in some form or the other, but I never get it.
Upvotes: 1
Views: 73
Reputation: 1016
Answer given by cdlane is more pythonic. This is simplified (school project) version.
n = 4
for i in range(1, n+1):
max_num_in_line = i * (i+1)// 2 # this gives max number to be printed in line i
for j in range(i): # here i is the total numbers to be printed in a line.
print(max_num_in_line, end=' ')
max_num_in_line -= 1
print()
Upvotes: 1
Reputation: 41905
If you're just looking to get that particular output, knowing only the value of n
, then you can do:
n = 8
numbers = range(1, n * (n + 1) // 2 + 1)
for i in range(1, n + 1):
head, numbers = numbers[:i], numbers[i:]
print(*reversed(head))
OUTPUT
> python3 test.py
1
3 2
6 5 4
10 9 8 7
15 14 13 12 11
21 20 19 18 17 16
28 27 26 25 24 23 22
36 35 34 33 32 31 30 29
>
Or is there more to this problem that I'm not getting?
Upvotes: 3
Reputation: 21
If you don't want duplicated values you should use set()
instead of list()
on the x
variable.
Upvotes: 0