Reputation: 228
I have to iterate from 0 to any Integer (call it x) that can be positive or negative (0 and x both included) (whether I iterate from x to 0 or from 0 to x does not matter)
I know I can use an if-else statement to first check if x is positive or negative and then use range(x+1)
if x>0 or range(x, 1)
if x<0 (both will work when x=0) like:
if x >= 0:
for i in range(x+1):
pass
else:
for i in range(x, 1):
pass
but I want a better way especially since I will actually be iterating over 2 Integers and this code is messy (and here also whether I iterate from y to 0 or from 0 to y does not matter)
if (x >= 0) and (y >= 0):
for i in range(x+1):
for j in range(y+1):
pass
elif (x >= 0) and (y < 0):
for i in range(x+1):
for j in range(y, 1):
pass
elif (x < 0) and (y >= 0):
for i in range(x, 1):
for j in range(y+1):
pass
else:
for i in range(x, 1):
for j in range(y, 1):
pass
Upvotes: 0
Views: 907
Reputation: 66
A simple solution that requires no functions
for i in range(min(x, 0), max(x, 0) + 1):
for j in range(min(y, 0), max(y, 0) + 1):
pass
Upvotes: 1
Reputation: 1380
You can simplify it by defining a function.
get_range_args = lambda x: (0, x+1) if x > 0 else (x, 1)
for i in range(*get_range_args(x)):
for j in range(*get_range_args(y)):
pass
Upvotes: 1
Reputation: 1218
Approach 1:
x = -9
y = 1
def getPosNeg(num):
if num >= 0:
return f"0, {num+1}"
return f"{num}, 1"
x_eval = eval(getPosNeg(x)) # use eval
y_eval = eval(getPosNeg(y)) # use eval
for i in range(*x_eval):
for j in range(*y_eval):
print(i, j)
Approach 2:
x = -9
y = 1
def getPosNeg(num):
if num >= 0:
return (0, num+1)
return (num, 1)
x_eval = getPosNeg(x)
y_eval = getPosNeg(y)
for i in range(*x_eval):
for j in range(*y_eval):
print(i, j)
If you only want positive integers in range, use abs()
:
x = -9
y = 1
for i in range(abs(x+1)):
for j in range(abs(y+1)):
print(i, j)
Docs:
eval()
Upvotes: 0