2013-04-06 101 views
3

美好的一天大家, 我需要排序和编写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_orderremove功能应该被添加到功能,所以当我运行我的测试,他们通过。但我每次都会收到一个“失败的测试”。

我真的很困惑,任何帮助指出我在正确的方向将不胜感激。

回答

3

使用bisect.insort_left插入项目x到列表a,并保持排序,假设a排序。

使用list.remove可从列表中删除第一次出现的值。如果该值不在列表中,此函数会引发ValueError。所以您需要将呼叫打包到try..except以处理异常 - 请参阅下面的示例。


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'] 
+0

为什么不使用'bisect.bisect_left'来查找项目的位置,然后使用'list.pop'来删除它。这会搜索'log(n)',而不是'O(n)'? – ovgolovin 2013-04-06 21:15:13

+0

[从Python列表中删除项目是O(n)](http://wiki.python.org/moin/TimeComplexity),所以无论我们使用list.pop还是list.remove,我们仍然是O (N)。 – unutbu 2013-04-06 21:17:56

+0

是的。但那为什么要使用'bisect'呢? – ovgolovin 2013-04-06 21:19:01

0

bisect模块,其发现在排序列表插入或缺失的位置。

此外,请注意,list中的插入和删除为O(n),因为它们需要将所有项目移到插入或删除位置的右侧。您可以查看blist模块来代替list,它可以在O(log(n))中执行这些操作。

1

关于你的排序问题,一个快速的解决方案,它不需要额外的模块(这可能不是计算最优的,但在许多情况下不够好):

>>> your_list = ['a', 'b', 'c'] 
>>> your_list.append('baa') 
>>> your_list.sort() 
>>> print your_list 
['a', 'b', 'baa', 'c'] 

对于删除项目,仅使用列表的remove方法使用异常处理程序,如@unutbu's解决方案中所述。

+0

我试图在函数格式中实现它。请看我的编辑(在我原来的帖子中) – Kuma 2013-04-06 22:54:03

+0

所以写一个函数。我觉得也许你应该回去阅读一些教程,如果你不能自己写一个函数;这是非常基本的东西。 – 2013-04-07 08:06:56