You have a problem with type comparison. You should compare it to int
, str
and list
types, not to "int", "str" and "list" strings.
Here's the quick fix for your issue:
class SortedList:
def __init__(self, element):
self.list = []
if type(element) == int or type(element) == str:
self.list = self.list + [element]
if type(element) == list:
self.list = self.list + element
self.list.sort()
a = SortedList(5)
b = SortedList([7, 5, 8])
print(a.list)
print(b.list)
Some things you could probably do better:
- Avoid using
list
as a variable name. You may accidentally override Python's built-in list
type.
- Use
isinstance
for type comparison instead of type(...) == ...
isinstance
can accept a tuple of classes to compare against
So here's the reformatted program:
class SortedList:
def __init__(self, element):
self.vals = []
if isinstance(element, (int, str)):
self.vals = self.vals + [element]
if isinstance(element, list):
self.vals = self.vals + element
self.vals.sort()
a = SortedList(5)
b = SortedList([7, 5, 8])
print(a.vals)
print(b.vals)
Going even further,
- You could simplify the code by converting it to a list, if it is not a list, and processing further.
Put a validation in place to ensure all data supplied as arguments are either integers or strings.
class SortedList:
def __init__(self, element):
self.vals = element if isinstance(element, list) else [element] # Convert to list if not a list
if not all(isinstance(item, (int, str)) for item in self.vals): # Ensure all items are either ints or strings
raise TypeError("Incorrect Item Datatypes")
self.vals.sort()
a = SortedList(5)
b = SortedList([7, 5, 8])
print(a.vals)
print(b.vals)
Now, assigning invalid data will throw an error:
c = SortedList([7.0, 5, 8])
Traceback (most recent call last):
File "tester.py", line 16, in <module>
c = SortedList([7.0, 5, 8])
File "tester.py", line 6, in __init__
raise TypeError("Incorrect Item Datatypes")
TypeError: Incorrect Item Datatypes