美文网首页
测试驱动的重要性

测试驱动的重要性

作者: codejoy | 来源:发表于2016-09-05 15:11 被阅读0次

    测试驱动,怎么强调都不过分

    测试驱动开发,从排斥到接受,到现在已经无法离开.
    今天一道貌似很简单算法题目,却用了自己超出想象的时间,确实也出乎意料了,细节是魔鬼.

    题目:

    You are playing the following Bulls and Cows game with your friend: You write down a number and ask your friend to guess what the number is. Each time your friend makes a guess, you provide a hint that indicates how many digits in said guess match your secret number exactly in both digit and position (called "bulls") and how many digits match the secret number but locate in the wrong position (called "cows"). Your friend will use successive guesses and hints to eventually derive the secret number.

    For example:

    Secret number: "1807"
    Friend's guess: "7810"
    Hint: 1 bull and 3 cows. (The bull is 8, the cows are 0, 1 and 7.)
    Write a function to return a hint according to the secret number and friend's guess, use A to indicate the bulls and B to indicate the cows. In the above example, your function should return "1A3B".

    Please note that both secret number and friend's guess may contain duplicate digits, for example:

    Secret number: "1123"
    Friend's guess: "0111"
    In this case, the 1st 1 in friend's guess is a bull, the 2nd or 3rd 1 is a cow, and your function should return "1A1B".
    You may assume that the secret number and your friend's guess only contain digits, and their lengths are always equal.

    最终代码如下:

    class Solution(object):
    
        def getHint(self, secret, guess):
            """
            :type secret: str
            :type guess: str
            :rtype: str
            """
            right = 0
            wrong = 0
            rewrite_secret = [ v for v in secret]
            rewrite_guess = [ v for v in guess]
            if len(secret) != len(guess):
                return None
            for index, v in enumerate(secret):
                if guess[index] == v:
                    right += 1
                    rewrite_secret[index] = '*'
                    rewrite_guess[index] = '*'
                    continue
    
            for index, v in enumerate(rewrite_guess):
                if rewrite_guess[index] == "*":
                    continue
                try:
                    j = rewrite_secret.index(v)
                    rewrite_secret[j]="*"
                    wrong += 1
                except:
                    continue
            return '%sA%sB'%(right, wrong)
    
    def main():
        a = Solution()
        print a.getHint("1807","7810")
        print a.getHint("11","11")
        print a.getHint("1234","0111")
    

    总结:

    如果一开始,就把case想全,就不会在三个case上面,停下来改代码,也可以一气呵成.联想实际的代码开发,平时经常会迫不及待的开发业务代码,业务还未全面建模,测试用例未覆盖全面,就开始了自己的开发,发现一个bug就一个个的修改,其实项目花费的开发时间,也比想象中多.

    1. 代码开动前,业务逻辑梳理清楚
    2. 代码开动之前,测试用例先行

    相关文章

      网友评论

          本文标题:测试驱动的重要性

          本文链接:https://www.haomeiwen.com/subject/peprettx.html