Skip to content

Commit 023f5e0

Browse files
nikolasvargaspoyea
authored andcommitted
fix empty list validation and code data structures (#826)
* fix empty list validation and code data structures * Update bucket_sort.py #826 (review)
1 parent b5667e5 commit 023f5e0

File tree

1 file changed

+13
-25
lines changed

1 file changed

+13
-25
lines changed

sorts/bucket_sort.py

+13-25
Original file line numberDiff line numberDiff line change
@@ -14,34 +14,22 @@
1414
# Best Case O(n); Average Case O(n); Worst Case O(n)
1515

1616
DEFAULT_BUCKET_SIZE=5
17-
def bucket_sort(my_list,bucket_size=DEFAULT_BUCKET_SIZE):
18-
if(my_list==0):
19-
print("you don't have any elements in array!")
2017

18+
def bucket_sort(my_list, bucket_size=DEFAULT_BUCKET_SIZE):
19+
if len(my_list) == 0:
20+
raise Exception("Please add some elements in the array.")
2121

22-
min_value=min(my_list)
23-
max_value=max(my_list)
22+
min_value, max_value = (min(my_list), max(my_list))
23+
bucket_count = ((max_value - min_value) // bucket_size + 1)
24+
buckets = [[] for _ in range(int(bucket_count))]
2425

25-
bucket_count=(max_value-min_value)//bucket_size+1
26-
buckets=[]
27-
for i in range(bucket_count):
28-
buckets.append([])
2926
for i in range(len(my_list)):
30-
buckets[(my_list[i]-min_value)//bucket_size].append(my_list[i])
27+
buckets[int((my_list[i] - min_value) // bucket_size)].append(my_list[i])
3128

29+
return sorted([buckets[i][j] for i in range(len(buckets))
30+
for j in range(len(buckets[i]))])
3231

33-
sorted_array=[]
34-
for i in range(len(buckets)):
35-
buckets[i].sort()
36-
for j in range(len(buckets[i])):
37-
sorted_array.append(buckets[i][j])
38-
return sorted_array
39-
40-
41-
42-
43-
#test
44-
#best on python 3.7.3
45-
user_input =input('Enter numbers separated by a comma:').strip()
46-
unsorted =[int(item) for item in user_input.split(',')]
47-
print(bucket_sort(unsorted))
32+
if __name__ == "__main__":
33+
user_input = input('Enter numbers separated by a comma:').strip()
34+
unsorted = [float(n) for n in user_input.split(',') if len(user_input) > 0]
35+
print(bucket_sort(unsorted))

0 commit comments

Comments
 (0)