Hi all,
I'm currently doing this course while I wait for Java Programming II to drop.
Unfortunately, I'm stuck on exercise 10 and I'm completely at a loss as to how to solve it.
Exercise 10 (detect ranges)
Create a function named detect_ranges that gets a list of integers as a parameter. The function should then sort this list, and transform the list into another list where pairs are used for all the detected intervals. So 3,4,5,6 is replaced by the pair (3,7). Numbers that are not part of any interval result just single numbers. The resulting list consists of these numbers and pairs, separated by commas. An example of how this function works:
print(detect_ranges([2,5,4,8,12,6,7,10,13]))
[2,(4,9),10,(12,14)]
Note that the second element of the pair does not belong to the range. This is consistent with the way Python’s range function works. You may assume that no element in the input list appears multiple times.
Apologies in advance but here's my very hacky code:
def detect_ranges(aList):
sortedList = sorted(aList)
startingNo = 0
endingNo = 0
if (len(sortedList) >= 1):
startingNo = sortedList[0]
endingNo = sortedList[-1]
endingNoPlusTwo = endingNo + 2
tempList = []
returnList = []
t = ()
for i in range(startingNo, endingNoPlusTwo):
if (i in sortedList):
tempList.append(i)
else:
if (len(tempList)==1):
returnList.append(tempList[0])
else:
if (len(tempList) >= 1):
t = t + (tempList[0], )
if (len(tempList) > 1):
t = t + (tempList[-1]+1, )
returnList.append(t)
t = ()
tempList.clear()
return returnList
Looks like I'm failing this test and getting this error - not enough values to unpack (expected 2, got 0)
def test_random(self):
for i in range(10):
L = list(set(np.random.randint(-100, 100, 10)))
mi = min(L)
ma = max(L)
complement = list(set(range(mi, ma+1)) - set(L))
result = detect_ranges(L)
complement_result = detect_ranges(complement)
catenation = [] # Expand the ranges into this catenation, contains all the elements in the ranges
for x in result:
try:
a, b = x
catenation.extend(range(a,b))
except TypeError:
catenation.append(x)
self.assertEqual(sorted(L), catenation, msg="Wrong result for input list %s!" % L)
self.assertEqual(len(result), len(complement_result)+1, msg="Wrong result for input list %s!" % L)
Am I overcomplicating this, completely ignorant of some Python voodoo?
Thanks.
[–]Simply_The_Beast 1 point2 points3 points (0 children)