Good day everyone,
I need help with sorting and writing a sorting function in python. I am trying to write a function insert_in_order which takes a list of strings items and a string item. I'm trying to do this assuming that items is already sorted in alphabetical order and i must insert item into the correct position in items
Also
in regards to the same problem i am facing, i also want to right a function remove which takes a list items and a string item. This function should remove the first occurrence of item in items. Also, if item does not occur at all in items, the function should leave items unchanged.
Edit:
my original set of functions is as follows
def read_list(fname):
items = []
with open(fname, 'r') as fin:
for line in fin:
items = insert_in_order(items, line[:-1])
return items
def write_list(items, fname):
fout = open(fname, 'w')
for item in items:
fout.write(item + '\n')
fout.close()
and i also have a test file which is supposed to test those functions:
class TestLabThre(unittest.TestCase):
def test_read_list(self):
self.assertEqual(
read_list('lab06ReadTest.txt'),
['a', 'b', 'c', 'd', 'e'])
def test_write_list(self):
write_list(['a', 'b', 'c', 'd', 'e'], 'lab06WriteTest.txt')
in_file = open('lab06WriteTest.txt', 'r')
self.assertEqual(in_file.read(), 'a\nb\nc\nd\ne\n')
my insert_in_order and remove functions are supposed to be added to the functions so that when i run my tests, they pass. But i get a "failed test" every time.
I'm really confused and any help pointing me in the right direction will be appreciated.
Use bisect.insort_left to insert an item x into a list a, and keep it sorted assuming a is sorted.
Use list.remove to remove the first occurence of value from a list. This function raises a ValueError if the value is not in the list. So you'll need to wrap the call in a try..except to handle the exception -- see below for an example.
import bisect
cheese = sorted('manchego stilton brie gouda'.split())
print(cheese)
# ['brie', 'gouda', 'manchego', 'stilton']
item = 'gorgonzola'
bisect.insort_left(cheese, item)
print(cheese)
# ['brie', 'gorgonzola', 'gouda', 'manchego', 'stilton']
try:
cheese.remove('manchego')
except ValueError:
pass
print(cheese)
# ['brie', 'gorgonzola', 'gouda', 'stilton']
Regarding your sorting problem, a quick solution which requires no additional modules (which may not be computationally optimal, but good enough in many cases):
>>> your_list = ['a', 'b', 'c']
>>> your_list.append('baa')
>>> your_list.sort()
>>> print your_list
['a', 'b', 'baa', 'c']
For removing items, just use the list's remove method with an exception handler, as described in @unutbu's solution.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With