• 参考代码:

    def dictf(number):
        dict2={}
        for i in range(1,number+1):
            key=str(i)
            value=i**2
            dict2[key]=value
        return dict2
    number=int(input("请输入一个数字:"))
    dictf(number)
    
  • 参考代码:

    import IPy 
    def is_ip(address): 
      try: 
        IPy.IP(address) 
        return "YES"
      except Exception as e: 
        return "NO"
    address = input("请输入IP:")
    is_ip(address)
    
  • 参考代码:

    def check_code():
        import random
        checkcode = ''
        for i in range(4):
            current = random.randrange(0, 4)
            if current != i:
                temp = chr(random.randint(65, 90))
            else:
                temp = random.randint(0, 9)
            checkcode += str(temp)
        return checkcode
    
    while True:
        code = check_code()
        print('验证码:'code)
        v = input('>>>')
        if v.lower() == code.lower():
            print('验证码正确')
            break
        else:
            print('验证码错误重新输入!')
    
  • 参考代码:

    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
    
  • 参考代码:

    def fn(x):
        return x ** 2
    List = [1,2,3,4,5]
    result_list = map(fn,List)
    result_list = [ i for i in result_list if i > 10]
    
  • 参考代码:

    from sys import stdout
    for i in range(1,1000):
         sum = 0
         for j in range(1,i):
             if i%j == 0:
                 sum += o
         if sum == i:
             print(i)
    
  • 参考代码:

    import itertools
    sum2=0
    a=[1,2,3,4]
    for i in itertools.permutations(a,3):
        print(i)
        sum2+=1
    print(sum2)
    
  • 参考代码:

    import math
    for i in range(100,200):
        for j in range(2,round(math.sqrt(i))+1):
            if i%j==0:
                break
        else:
            print(i)
    
  • 参考代码:

    def Quick_Sort(list):
        if len(list)<2:
            return list
        else:
            mid_pivot = list[0]
            less_before_midpivot = [i for i in list[1:] if i<=mid_pivot]
            bigger_after_pivot = [i for i in list[1:] if i > mid_pivot]
            finally_list = Quick_Sort(less_before_midpivot)+[mid_pivot] + Quick_Sort(bigger_after_pivot)
            return finally_list
    
  • 参考代码:

    import math
    for i in range(100,200):
        flag=0
        for j in range(2,round(math.sqrt(i))+1):
            if i%j==0:
                flag=1
                break
        if flag:
            continue
        print(i)
    
  • 参考代码:

    import math
    import random
    def shuffle(list):
        counter = len(list)
        # while there are elements in the list
        while counter > 0:
            # pick a random index
            index = math.floor(random.random()*counter)
            # Decrease counter by 1
            counter = counter -1
            # And swap the last element with it
            temp = list[counter]
            list[counter] = list[index]
            list[index] = temp
        return list
    
  • 参考代码:

    def spread(arg):
        ret = []
        for i in arg:
            if isinstance(i, list):
                ret.extend(i)
            else:
                ret.append(i)
        return ret
    def deep_flatten(lst):
        result = []
        result.extend(
            spread(list(map(lambda x: deep_flatten(x) if type(x) == list else x, lst))))
        return result
    
  • 参考代码:

    import re
    email_list= ["test01@163.com","test02@163.123", ".test03g@qq.com", "test04@gmail.com" ]
    for email in email_list:
      ret = re.match("[\w]{4,20}@(.*)\.com$",email)
      if ret:
        print("%s 是符合规定的邮件地址,匹配后结果是:%s" % (email,ret.group()))
      else
        print("%s 不符合要求" % email)
    
  • 参考代码:

    def reverse_int(x):
        if not isinstance(x, int):
            return False
        if -10 < x < 10:
            return x
        tmp = str(x)
        if tmp[0] != '-':
            tmp = tmp[::-1]
            return int(tmp)
        else:
            tmp = tmp[1:][::-1]
            x = int(tmp)
            return -x
    reverse_int(-23837)
    
  • 参考代码:

    def dedupe(items, key = None):
        seen = set()
        for item in items:
            val = item if key is None else key(item)
            if val not in seen:
                yield item
                seen.add(val)
    
  • 参考代码:

    from glob import iglob
    
    def func(fp, postfix):
        for i in iglob(f"{fp}/**/*{postfix}", recursive=True):
            print(i)
    
    if __name__ == "__main__":
        postfix = ".txt"
        func("F:\\", postfix)
    
  • 参考代码:

    class Node(object):
        def __init__(self, data=None, next=None):
            self.data = data
            self.next = next
    link = Node(1, Node(2, Node(3, Node(4, Node(5, Node(6, Node(7, Node(8, Node(9)))))))))
    def rev(link):
        pre = link
        cur = link.next
        pre.next = None
        while cur:
            tmp = cur.next
            cur.next = pre
            pre = cur
            cur = tmp
        return pre
    root = rev(link)
    while root:
        print root.data
        root = root.next
    
  • 参考代码:

    import time
    def wrapper(func):
        def inner():
            start_time = time.time()
            func()
            print("程序运行时间:",time.time() - start_time)
        return inner
    @wrapper
    def test():
        time.sleep(2)
    
  • 参考代码:

    from functools import wraps
    import logging
    def logged(level, name = None, message = None):
        def decorate(func):
            log_name = name if name else func.__module__
            log = logging.getLogger(log_name)
            log_msg = message if message else func.__name__
    
            @wraps(func)
            def wrapper(*args, **kwargs):
                log.log(level, log_msg)
                return func(*args, **kwargs)
            return wrapper
        return decorate
    
  • 参考代码:

    import heapq
    class PriorityQueue:
        def __init__(self):
            self._queue = []
            self._index = 0
    
        def push(self, item, priority):
            heapq.heappush(self._queue, (-priority,self._index, item))
            self._index += 1
    
        def pop(self):
            return heapq.heappop(self._queue)[-1]
    
    class Item:
        def __init__(self):
            self.name = name
    
        def __repr__(self):
            return 'Item({!r})'.format(self.name)
    
  • 参考代码:

    def fact(j):
        sum = 0
        if j == 0:
            sum = 1
        else:
            sum = j * fact(j - 1)
        return sum
    
  • 参考代码:

    # 首先定义一个抽象基类
    class CarStore(object):
        # 定义生产汽车的方法
        def createcar(self, name):
            pass
        # 根据类型去生产车
        def order(self, name):
            self.car = self.createcar(name)
            self.car.move()
    
    # 定义4s店  实现抽象类
    class AoDiCarStore(CarStore):
        def createcar(self, name):
            self.factory = CarFactory()
            return self.factory.createcar(name)
    
    # 创建一个车
    class AoDi():
        def move(self):
            print('移动')
    # 定义一个工厂
    class CarFactory():
        def createcar(self, name):
            self.name = name
            if self.name == 'AoDi':
                self.car = AoDi()
            return self.car
    aodi = AoDiCarStore()
    aodi.order('AoDi')
    
  • 参考代码:

    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 compareString(self, A, B):
            if len(B) == 0:
                return True
            if len(A) == 0:
                return True
            trackTable = [ 0 for _ in range(26) ]
            for i in A:
                trackTable[ord(i) - 65] += 1
            for i in B:
                if trackTable[ord(i) - 65] == 0:
                    return False
                else:
                    trackTable[ord(i) - 65] -= 1
            return True
    
  • 参考代码:

    tmp_list = [8, 5, 1, 3, 2, 10, 11, 4, 12, 20]
    def partition(arr,low,high): 
        i = ( low-1 )
        pivot = arr[high]     
        for j in range(low , high): 
            if   arr[j] <= pivot: 
                i = i+1 
                arr[i],arr[j] = arr[j],arr[i] 
    
        arr[i+1],arr[high] = arr[high],arr[i+1] 
        return ( i+1 )
    
    def quicksort(arr,low,high): 
        if low < high: 
            pi = partition(arr,low,high) 
            quicksort(arr, low, pi-1) 
            quicksort(arr, pi+1, high) 
    
    quicksort(tmp_list, 0, len(tmp_list)-1)
    print(tmp_list)