i'm struggling with this seemingly simple python problem.
i need 90 values in the list that increase by 6 (from 120) until it reaches 240, once it reaches 240 it should decrease by 6 back to 120. this loop would continue until 90 values are reached.
x = [30, 36, 42, 48, 54, 60]
e = [120]
for row in range(90):
if e[row] >= 120 and e[row] != 240:
e.append(e[row] 6)
print(e[row], "1")
elif e[row] <= 240 and e[row] != 120:
e.append(e[row] - 6)
print(e[row])
the code i have so far doesn't work well. after it reaches 240, it goes down to 236. 236 satisfies the >= 120
and != 240
condition so it just goes back up to 240.
any guidance would be appreciated!
CodePudding user response:
I guess you want something like this:
x = [30, 36, 42, 48, 54, 60]
e = [120]
dir = 1
for row in range(90):
if dir == 1:
if e[row] >= 240:
dir = -1
else:
if e[row] <= 120:
dir = 1
e.append(e[row] (dir * 6))
print(e[row])
print(f' LENGTH: {len(e)}')
CodePudding user response:
A one-line way to do this by just gluing range
s together would be:
>>> ((list(range(120, 240, 6)) list(range(240, 120, -6))) * 3)[:90]
[120, 126, 132, 138, 144, 150, 156, 162, 168, 174, 180, 186, 192, 198, 204, 210, 216, 222, 228, 234, 240, 234, 228, 222, 216, 210, 204, 198, 192, 186, 180, 174, 168, 162, 156, 150, 144, 138, 132, 126, 120, 126, 132, 138, 144, 150, 156, 162, 168, 174, 180, 186, 192, 198, 204, 210, 216, 222, 228, 234, 240, 234, 228, 222, 216, 210, 204, 198, 192, 186, 180, 174, 168, 162, 156, 150, 144, 138, 132, 126, 120, 126, 132, 138, 144, 150, 156, 162, 168, 174]
To build it in a loop the way you're trying to do, I'd have the delta in another variable and only flip it when you hit one of the edges, like this:
>>> e = [120]
>>> d = 6
>>> for _ in range(89):
... n = e[-1] d
... if n >= 240 or n <= 120:
... d *= -1
... e.append(n)
...
>>> e
[120, 126, 132, 138, 144, 150, 156, 162, 168, 174, 180, 186, 192, 198, 204, 210, 216, 222, 228, 234, 240, 234, 228, 222, 216, 210, 204, 198, 192, 186, 180, 174, 168, 162, 156, 150, 144, 138, 132, 126, 120, 126, 132, 138, 144, 150, 156, 162, 168, 174, 180, 186, 192, 198, 204, 210, 216, 222, 228, 234, 240, 234, 228, 222, 216, 210, 204, 198, 192, 186, 180, 174, 168, 162, 156, 150, 144, 138, 132, 126, 120, 126, 132, 138, 144, 150, 156, 162, 168, 174]
CodePudding user response:
You can use a variable to hold the amount that you're adding, and switch it between 6
and -6
. Test whether it's positive or negative to know which end to check for.
e = [120]
increment = 6
for _ in range(90):
e.append(e[-1] increment)
if increment > 0 and e[-1] == 240:
increment = -6
elif increment < 0 and e[-1] == 120:
increment = 6