• 参考代码:

    import os
    import time
    path_to_watch = "."
    before = dict ([(f, None) for f in os.listdir (path_to_watch)])
    while 1:
       time.sleep (10)
       after = dict ([(f, None) for f in os.listdir (path_to_watch)])
       added = [f for f in after if not f in before]
       removed = [f for f in before if not f in after]
       if added: print("Added: ", ", ".join (added))
       if removed: print("Removed: ", ", ".join (removed))
       before = after
    
  • 参考代码:

    import time
    pin = 0
    while True:
       ips = []
       fr = open('assce.log')
       fr.seek(pin)
       for line in fr:
           ip = line.split()[0]  
           ips.append(ip)
       new_ips = set(ips)
       for new_ip in new_ips:
           if ips.count(new_ip) > 200:
               print('加入黑名单的ip是:%s' % new_ip)
       pin = fr.tell()
       time.sleep(60)
    
  • 参考代码:

    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