I have a list of numbers. I want to group the numbers which lie within a distance of 4 from each other. For example if I have a list [1,34,45,34,66,35,14,3,5,12,4,62,31,4,13,12]
. I want to group the elements in the fashion "1 3 5 4 4 ;34 34 35 31 ;45 ;66 62 ;14 12 13 12 ;"
.To make it clear:
Input >> [1,34,45,34,66,35,14,3,5,12,4,62,31,4,13,12]
Output >> 1 3 5 4 4 ;34 34 35 31 ;45 ;66 62 ;14 12 13 12 ;
For this, I have written the following code:
arr = [1,34,45,34,66,35,14,3,5,12,4,62,31,4,13,12]
bucket = ''
while arr != []:
element = arr.pop(0)
bucket += (str(element) + ' ')
for term in arr:
if abs(element-term)<= 4:
bucket += (str(term) + ' ')
arr.remove(term)
print(bucket)
print(arr)
else:
bucket += ';'
print(arr)
print(bucket)
I expected the final output to be as follows:
1 3 5 4 4 ;34 34 35 31 ;45 ;66 62 ;14 12 13 12 ;
But what I got in the final output was:
1 3 4 4 ;34 34 35 31 ;45 ;66 62 ;14 12 12 ;5 ;13 ;
here the element '5' should have been in the first bucket but in the output it is not in the bucket where it's supposed to be. Similarly '13' is out of its place
Any help in identifying the problem in the code will be greatly appreciated.