Reputation: 41
Is there a way to combine these two loops to make it more efficient?
for i in range(n):
for j in range(i + 1, n + 1):
print(i, j)
Thanks!
Upvotes: 2
Views: 96
Reputation: 1179
Your code is efficient enough with respect to fact that it is understandable and readable to others hence it is recommended.
However If you are looking for a one liner in python then you can use the following one but I strongly do not recommend it as it only makes the code more un-readable and only adds a headache to others
n = 10
print(' \n'.join('{} {}'.format(*item) for item in [ (i,j) for i in range(n) for j in range(i+1,n+1) ] ) )
This prints out the exact same output as the code that you have provided.
Upvotes: 1