Here is my code, Could anyone please help me why the 'long_band' resulted in empty list?
Expected output: [[9,10],[0,1,2,3,4,5,6,7],[18],[12]]
Code begins here:
arr = [1, 9, 3, 0, 18, 5, 2, 4, 10, 7, 12, 6]
len1 = len(arr)
long_band = list()
chain = list()
def band(i):
chain.append(i)
j = i 1
if j in arr:
band(j)
else:
#print(chain)
#print(long_band)
long_band.append([chain])
#print(long_band)
del chain[:]
def isHead(n):
x = n-1
if x in arr:
None
else:
band(n)
for i in range(len1):
isHead(arr[i])
print(long_band)
CodePudding user response:
arr = [1, 9, 3, 0, 18, 5, 2, 4, 10, 7, 12, 6]
len1 = len(arr)
long_band = list()
chain = list()
def band(i):
chain.append(i)
j = i 1
if j in arr:
band(j)
else:
long_band.append(chain[:])
del chain[:]
def isHead(n):
x = n-1
if x in arr:
None
else:
band(n)
def FindMaxLen(long_band):
maxLength = max(len(x) for x in long_band)
print(maxLength)
for i in range(len1):
isHead(arr[i])
print(long_band)
FindMaxLen(long_band)
CodePudding user response:
The immediate problem is this:
long_band.append([chain])
del chain[:]
You're appending the chain object to the list, and then immediately clear it. This also clears the object in the list, because there's only one object. Appending it to a list doesn't create a copy of it.
The bigger problem is that your algorithm is way overcomplicated. Here's a much simpler approach:
>>> arr = [1, 9, 3, 0, 18, 5, 2, 4, 10, 7, 12, 6]
>>> arr.sort()
>>> res = [arr[0:1]]
>>> for i, j in zip(arr, arr[1:]):
... if i != j - 1:
... res.append([])
... res[-1].append(j)
...
>>> res
[[0, 1, 2, 3, 4, 5, 6, 7], [9, 10], [12], [18]]
