python leetcode相关题目

来源:互联网 发布:java api1.6文档下载 编辑:程序博客网 时间:2024/05/17 23:31

Reshape the Matrix

class Solution(object):    def matrixReshape(self, nums, r, c):        """        :type nums: List[List[int]]        :type r: int        :type c: int        :rtype: List[List[int]]        """        l = []        for i in nums:            for j in range(len(i)):                l.append(i[j])        if len(l) != r*c:            return nums        else:            x = []            y = int(len(l)/c)            for i in range(y):                x.append(l[i*c:(i*c+c)])            return xif __name__ == '__main__':    a = [[2,3,4],[1,3]]    a = Solution()    print(a.matrixReshape([[1,2],[3,4]],1,4))


Hamming Distance

class Solution(object):    def hammingDistance(self, x, y):        """        :type x: int        :type y: int        :rtype: int        """        # def get_list(a):        #     a_list = list(bin(a))[2:]        #     return a_list        # a_str = ''.join(a_list)        x1 = list(bin(x))[2:]        y1 = list(bin(y))[2:]        if len(x1)>len(y1):            x_ins = len(x1)-len(y1)            for i in range(x_ins):                y1.insert(0,'0')        else:            y_ins = len(y1)-len(x1)            for i in range(y_ins):                x1.insert(0,'0')        print(x1)        print(y1)        i = 0        for n in range(len(x1)):            if x1[n] == y1[n]:                i += 1        count = len(x1)-i        return countif __name__ == '__main__':    a = Solution()    print(a.hammingDistance(34,4))
 


原创粉丝点击