Skip to content

Commit 1447b36

Browse files
authored
Now patience_sort.py receives integers, floats, and strings and the sort them.
The code receives integers, strings, and floats. After that it sort them in this order: 1. Numbers are sorted first, followed by alphabets. 2. Integers and floats are sorted according to their magnitude. 3. Strings are sorted in alphabetical order.
1 parent 21c228c commit 1447b36

1 file changed

Lines changed: 28 additions & 3 deletions

File tree

‎sorts/patience_sort.py‎

Lines changed: 28 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,6 @@ def __lt__(self, other):
2525
def __eq__(self, other):
2626
return self[-1] == other[-1]
2727

28-
2928
def patience_sort(collection: list) -> list:
3029
"""A pure implementation of patience sort algorithm in Python
3130
@@ -52,10 +51,36 @@ def patience_sort(collection: list) -> list:
5251
stacks[i].append(element)
5352
else:
5453
stacks.append(new_stacks)
55-
54+
5655
# use a heap-based merge to merge stack efficiently
5756
collection[:] = merge(*(reversed(stack) for stack in stacks))
5857
return collection
58+
59+
def mixed_patience_sort(collection: list) -> list:
60+
"""
61+
With this block of code, numbers are sorted according to their
62+
magnitude, the strings are arranged in alphbetical order. And the numbers
63+
are arranged before the alphabets.
64+
"""
65+
66+
number_items = []
67+
string_items = []
68+
69+
for element in collection:
70+
if isinstance(element, (int, float)):
71+
number_items.append(element)
72+
elif isinstance(element, str):
73+
string_items.append(element)
74+
else:
75+
print("Only integers, floats, and strings are allowed.")
76+
77+
# The user input is sort by using the patience sort algorithm
78+
sorted_numbers = patience_sort(number_items)
79+
sorted_strings = patience_sort(string_items)
80+
81+
# use a heap-based merge to merge stack efficiently
82+
collection[:] = sorted_numbers + sorted_strings
83+
return collection
5984

6085
def convert_item(item):
6186
item = item.strip()
@@ -70,4 +95,4 @@ def convert_item(item):
7095
if __name__ == "__main__":
7196
user_input = input("Enter numbers separated by a comma:\n").strip()
7297
unsorted = [convert_item(item) for item in user_input.split(",")]
73-
print(unsorted)
98+
print(mixed_patience_sort(unsorted))

0 commit comments

Comments
 (0)