• 参考代码:

    # 用装饰实现
    def singleton(cls):
        instances = {}
        def wrapper(*args, **kwargs):
            if cls not in instances:
                instances[cls] = cls(*args, **kwargs)
            return instances[cls]
        return wrapper
    
    
    @singleton
    class Foo(object):
        pass
    foo1 = Foo()
    foo2 = Foo()
    print(foo1 is foo2)
    
    # 用基类实现
    class Singleton(object):
        def __new__(cls, *args, **kwargs):
            if not hasattr(cls, '_instance'):
                cls._instance = super(Singleton, cls).__new__(cls, *args, **kwargs)
            return cls._instance
    
    class Foo(Singleton):
        pass
    foo1 = Foo()
    foo2 = Foo()
    print(foo1 is foo2)
    
    # 使用元类实现
    class Singleton(type):
        def __call__(cls, *args, **kwargs):
            if not hasattr(cls, '_instance'):
                cls._instance = super(Singleton, cls).__call__(*args, **kwargs)
            return cls._instance
    
    # Python2
    class Foo(object):
        __metaclass__ = Singleton
    # Python3
    class Foo(metaclass=Singleton):
        pass
    
    foo1 = Foo()
    foo2 = Foo()
    print(foo1 is foo2)
    
    
  • 参考代码:

    def sortport():
      for i in range(len(l)-1):
        for j in range(len(l)-1-i):
          if l[j] > l[j+1]:
            l[j],l[j+1] = l[j+1],l[j]
       return l
    
  • 参考代码:

    def binary_search(data, item):
        n = len(data)
        if n > 0:
            mid = n // 2
            if data[mid] == item:
                return True
            elif data[mid] > item:
                return binary_search(data[:mid], item)
            else:
                return binary_search(data[mid+1:], item)
        return False
    
  • 参考代码:

    class Solution:
        def secondMax(self, nums):
            maxValue = max(nums[0], nums[1])
            secValue = min(nums[0], nums[1])
            for i in range[2, len(nums)]:
                if nums[i] > maxValue:
                    secValue = maxValue
                    maxValue = nums[i]
                elif nums[i] > secValue:
                    secValue = nums[i]
            return secValue
    
  • 参考代码:

    raw=[]
    for i in range(3):
        x=int(input('int%d: '%(i)))
        raw.append(x)
    
    for i in range(len(raw)):
        for j in range(i,len(raw)):
            if raw[i]>raw[j]:
                raw[i],raw[j]=raw[j],raw[i]
    
  • 参考代码:

    import numpy as np
    
    #方法 1
    def fib_matrix(n):
        for i in range(n):
            res = pow((np.matrix([[1, 1], [1, 0]], dtype='int64')), i) * np.matrix([[1], [0]])
            print(int(res[0][0]))
    # 调用
    fib_matrix(50)
    
    #方法 2
    # 使用矩阵计算斐波那契数列
    def Fibonacci_Matrix_tool(n):
        Matrix = np.matrix("1 1;1 0", dtype='int64')
        # 返回是matrix类型
        return np.linalg.matrix_power(Matrix, n)
    
    def Fibonacci_Matrix(n):
        result_list = []
        for i in range(0, n):
            result_list.append(np.array(Fibonacci_Matrix_tool(i))[0][0])
        return result_list
    
  • 参考代码:

    class Solution:
        def rotateString(self, s, offset):
            if len(s) > 0:
                offset = offset % len(s)
            temp = (s + s)[len(s) - offset : 2 * len(s) - offset]
            for i in range(len(temp)):
                s[i] = temp[i]
    
  • 参考代码:

    class Solution:
        def reverseInteger(self, number):
            h = int(number/100)
            t = int(number%100/10)
            z = int(number%10)
            return (100*z + 10*t + h)
    
  • 参考代码:

    class Solution:
        def canGetString(self, s, t):
            pos = 0
            for x in t:
                while pos < len(s) and s[pos] != x:
                    pos += 1
                if pos == len(s):
                    return False
                pos += 1
            return True
    
  • 参考代码:

    # 方法1
    ip = input("请输入IP:")
    if len(ip.split(".")) !=4:
        print("NO")
        exit()
    elif " " in ip.split("."):
        print("NO")
        exit()
    else:
        new_list = [int(i) for i in ip.split(".")]
        for i in new_list:
            if not 0 <= i < 255:
                print("NO")
                break
        else:
            print("YES")
    
    # 方法2
    import IPy 
    def is_ip(address): 
      try: 
        IPy.IP(address) 
        return "YES"
      except Exception as e: 
        return "NO"
    address = input("请输入IP:")
    is_ip(address)
    
  • 参考代码:

    from math import ceil
    def divide_iter(lst, n):
        if n <= 0:
            yield lst
            return
        i, div = 0, ceil(len(lst) / n)
        while i < n:
            yield lst[i * div: (i + 1) * div]
            i += 1
    list(divide_iter([1, 2, 3, 4, 5], 2))
    
  • 参考代码:

    class Solution:
        def theTwoNumbers(self, a):
            ans = [0, 0]
            for i in a:
                ans[0] = ans[0] ^ i
            c = 1
            while c & ans[0] != c:
                c = c << 1
            for i in a:
                if i & c == c:
                    ans[1] = ans[1] ^ i
            ans[0] = ans[0] ^ ans[1]
            return ans
    
  • 参考代码:

    input_str = input()
    dimensions=[int(x) for x in input_str.split(',')]
    rowNum=dimensions[0]
    colNum=dimensions[1]
    multilist = [[0 for col in range(colNum)] for row in range(rowNum)]
    
    for row in range(rowNum):
        for col in range(colNum):
            multilist[row][col]= row*col
    
    print(multilist)
    
  • 参考代码:

    class Solution:
        def mergeSortedArray(self, A, B):
            i, j = 0, 0 
            C = []
            while i < len(A) and j < len(B):
                if A[i] < B[j]:
                    C.append(A[i])
                    i += 1
                else:
                    C.append(B[j])
                    j += 1
            while i < len(A):
                C.append(A[i])
                i += 1
            while j < len(B):
                C.append(B[j])
                j += 1
            return C
    
  • 可以尝试抽象一下。