Reputation: 1383
I have a question about list
. My list needs to be around a midpoint with minimum of 1, and it needs 6 integer steps (+/-) evenly around the midpoint, with step of 1. There will be 7 digits (midpoint + 6 steps) in the list.
e.g.,if mid = 10
, then the list = [7,8,9,**10**,11,12,13]
. 3 steps above 10 and 3 steps below 10.
But if mid = 3
, the digits then can't distribute evenly with 3 steps above and under the midpoint, because the minimum is 1. To ensure 7 items in the list, 4 steps above 3 and 2 steps under 3. Thus, [1,2,**3**,4,5,6,7]
. If the mid=2
, 5 steps above 2 and 1 step under 2. The list is still [1,**2**,3,4,5,6,7]
.
Here is my code:
def gain_range(mid):
gainLower_list = list(range(1, mid)) #items under the midpoint
gainUpper_list = list(range(mid, n)) #items above the midpoint, hence I can combine the two lists later
if mid >= 4:
n = mid + 3
elif mid >= 3:
n = mid + 4
elif mid >= 2:
n = mid + 5
elif mid >= 1:
n = mid + 6
gain_range(3)
but this codes gives an error:
UnboundLocalError: local variable 'n' referenced before assignment
How should I fix this? And is there more elegant way to create this list with fixed steps, rather than fixed limits?
Upvotes: 0
Views: 208
Reputation: 1416
Just addressing the error here: you use the variable n
in your code before you have declared it.
def gain_range(mid):
gainLower_list = list(range(1, mid))
gainUpper_list = list(range(mid, n)) # use n here but is hasnt been declared and assigned a value
if mid >= 4:
n = mid + 3
elif mid >= 3:
n = mid + 4
elif mid >= 2:
n = mid + 5
elif mid >= 1:
n = mid + 6
You need to assign a value to n
before then...
However, if you just want 6 evenly distributed, consecutive digits surrounding mid
with a minimum of 1 then the answer above mine (Steven Rausch) should do the trick
Upvotes: 0
Reputation: 49774
The only decision needed is for the starting value which must be >= 1, so calculate that first, then just return a list
from range
:
Code:
def gain_range(mid):
start = max(1, mid - 3)
return list(range(start, start+7))
Test Code:
print(gain_range(3))
print(gain_range(4))
print(gain_range(5))
Results:
[1, 2, 3, 4, 5, 6, 7]
[1, 2, 3, 4, 5, 6, 7]
[2, 3, 4, 5, 6, 7, 8]
Upvotes: 1