美好的一天大家, 我需要排序和编写python排序功能的帮助。我正在尝试编写一个函数insert_in_order
,其中包含字符串项目和字符串项目的列表。我试图做到这一点假设项目已经排序的字母顺序,我必须在问候插入项目到正确的位置在项目在Python中排序项目
而且
同样的问题我是面对,我也想要一个功能remove
它需要一个列表项目和字符串项目。此功能应删除项目的第一个出现项目项目。此外,如果项目完全没有发生在项目中,则该功能应保留项目不变。
编辑:
我原来的功能集如下
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()
,我也有这应该测试这些功能的测试文件:
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')
我insert_in_order
和remove
功能应该被添加到功能,所以当我运行我的测试,他们通过。但我每次都会收到一个“失败的测试”。
我真的很困惑,任何帮助指出我在正确的方向将不胜感激。
为什么不使用'bisect.bisect_left'来查找项目的位置,然后使用'list.pop'来删除它。这会搜索'log(n)',而不是'O(n)'? – ovgolovin 2013-04-06 21:15:13
[从Python列表中删除项目是O(n)](http://wiki.python.org/moin/TimeComplexity),所以无论我们使用list.pop还是list.remove,我们仍然是O (N)。 – unutbu 2013-04-06 21:17:56
是的。但那为什么要使用'bisect'呢? – ovgolovin 2013-04-06 21:19:01