A neat and tested python solution but got Compile Error, why?


  • 1
    Z

    This is my Solution:

    class Solution:
        # @return a string
        def longestCommonPrefix(self, strs):
            if len(strs) == 1:
                return len(strs[0])
            from itertools import count
            for i in count():
                try:
                    assert eval('=='.join([repr(s[:i+1]) for s in strs]))
                except AssertionError, IndexError:
                    break
            return i
    

    To test the solution, I wrote a unit test myself.

    import unittest
    
    class Solution:
        # @return a string
        def longestCommonPrefix(self, strs):
            if len(strs) == 1:
                return len(strs[0])
            from itertools import count
            for i in count():
                try:
                    assert eval('=='.join([repr(s[:i+1]) for s in strs]))
                except AssertionError, IndexError:
                    break
            return i
    
    class SolutionTest(unittest.TestCase):
        test_map = [
            ([''], 0),
            (['abc'], 3),
            (['ab', 'abc','abcd'], 2),
            (['', 'abc', 'ab'], 0),
            (['a', 'abc', 'abd', 'abe'], 1),
        ]
        def make_test(strs, num):
            def func(self):
                s = Solution()
                self.assertEquals(num, s.longestCommonPrefix(strs))
            return func
    
        for i, (j, k) in enumerate(test_map, 1):
            locals()['test_case_%d' % i] = make_test(j, k)
    
    if __name__ == '__main__':
        unittest.main()
    

    And all 5 test cases get pass. But when I submit, I got a compile error. Can anyone tell me why?

    .....
    ----------------------------------------------------------------------
    Ran 5 tests in 0.000s
    
    OK

  • 0
    C

    Probably because the from itertools import count, I think leetcode already imported all the core modules, you can just use it without import again.


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.