Reputation:
What is a good way to add elements to a list that automatically adds elements depending on their string length?
For example.
class MyQueueSystem():
def __init__(self, myfunction):
self.myfucntion = myfunction
self.data = []
def add(self, item):
pass
For example,
def shorter(a, b):
return len(a) < len(b)
>>> me = MyQueueSystem(shorter)
>>> me.add('111')
>>> me.add('11')
>>> me.add('11111')
>>> print (me.data)
['11111','111','11']
item in the add function is an object.
My question is, how do you access a function as a parameter?
edit : I forgot to add a argument in the Init
Upvotes: 1
Views: 80
Reputation: 48090
You may use sorted
function within your add(..)
fucntion to sort the list based on the len
. Below is sample structure for your class:
class MyQueueSystem():
# v It should be passed as an argument to `__init__`
def __init__(self, data):
self.data = self._sort_on_length(data)
def add(self, item):
self.data = self._sort_on_length(self.data+[item])
def _sort_on_length(self, sort_list):
"""
Function to sort the argument `list` based on the length
in the descending order
"""
return sorted(sort_list, key=lambda x: -len(x))
Sample Run:
>>> my_object = MyQueueSystem(['111', '11', '11111'])
>>> my_object.data
['11111', '111', '11']
>>> my_object.add('1111')
>>> my_object.data
['11111', '1111', '111', '11']
Upvotes: 1