欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Python的一道面试题

程序员文章站 2024-03-23 12:58:28
...

 

题目:
将下面的函数按照执行效率高低排序。它们都接受由0至1之间的数字构成的列表作为输入。这个列表可以很长。
一个输入列表的示例如下:[random.random() for i in range(100000)]。

def f1(lIn):
    l1 = sorted(lIn)
    l2 = [i for i in l1 if i<0.5]
    return [i*i for i in l2]

def f2(lIn):
    l1 = [i for i in lIn if i<0.5]
    l2 = sorted(l1)
    return [i*i for i in l2]

def f3(lIn):
    l1 = [i*i for i in lIn]
    l2 = sorted(l1)
    return [i for i in l1 if i<(0.5*0.5)]

你如何证明自己的答案是正确的。

可以通过python3自带的unittest来测试下

import unittest
import random

class PerfExp:
    case=[random.random() for i in range(100000)]
    @staticmethod
    def sort_by_list(self):
        self.case=sorted(PerfExp.case)
    @staticmethod
    def get_case(self):
        return PerfExp.case

class FuncPerfTests(unittest.TestCase):
    def test_f1(self):
     #   PerfExp.sort_by_list(self)
        l1 = sorted(PerfExp.case)
        l2 = [i for i in l1 if i < 0.5]
        return [i * i for i in l2]
    def test_f2(self):
        l1 = [i for i in PerfExp.get_case(self) if i < 0.5]
        l2 = sorted(l1)
        return [i * i for i in l2]
    def test_f3(self):
        l1 = [i * i for i in PerfExp.get_case(self)]
        l2 = sorted(l1)
        return [i for i in l1 if i < (0.5 * 0.5)]

if __name__ == '__main__':
    unittest.main()

 

结果:

Python的一道面试题

当然我们可以用timeit,改写下:


from timeit import timeit

f1 = """
import unittest
import random
class PerfExp:
    case=[random.random() for i in range(100000)]
    @staticmethod
    def sort_by_list(self):
        self.case=sorted(PerfExp.case)
    @staticmethod
    def get_case(self):
        return PerfExp.case
class FuncPerfTests():

    def test_f1(self):
     #   PerfExp.sort_by_list(self)
        l1 = sorted(PerfExp.case)
        l2 = [i for i in l1 if i < 0.5]
        return [i * i for i in l2]
"""
#### 静态方法不用再次声明
f2= """
import unittest
import random

class FuncPerfTests():

 def test_f2(self):
    l1 = [i for i in PerfExp.get_case(self) if i < 0.5]
    l2 = sorted(l1)
    return [i * i for i in l2]
    
"""


f3= """
import unittest
import random

class FuncPerfTests():
 def test_f3(self):
    l1 = [i * i for i in PerfExp.get_case(self)]
    l2 = sorted(l1)
    return [i for i in l1 if i < (0.5 * 0.5)]
"""

print("FuncPerfTests.test_f1: "+ str(timeit("FuncPerfTests.test_f1", f1)))
print("FuncPerfTests.test_f2: "+ str(timeit("FuncPerfTests.test_f2", f2)))
print("FuncPerfTests.test_f3: "+ str(timeit("FuncPerfTests.test_f3", f3)))

#if __name__ == '__main__':
    #unittest.main()

结果:

Python的一道面试题

相关标签: unittest python