• 参考代码:

    class Solution:
        def findPosition(self, A, target):
            if not A:
                return -1
            start, end = 0, len(A) - 1
            while start + 1 < end:
                mid = start + (end - start)//2
                if A[mid]<target:
                    start = mid
                elif A[mid]>target:
                    end = mid
                else:
                    return mid
            if target -A[start]< A[end] - target:
                return start
            else:
                return end
    
  • 参考代码:

    class Solution:
        def twitchWords(self, str):
            n = len(str)
            c = str[0]
            left = 0
            ans = []
            for i in range(n):
                if str[i] != c:
                    if i - left >= 3:
                        ans.append(left, i -1)
                    c = str[i]
                    left = i
            if n - left >= 3:
                ans.append([left, n - 1])
            return ans
    
  • 参考代码:

    class Solution:
        def findPosition(self, nums, target):
            if len(nums) is 0:
                return -1
            start = 0
            end = len(nums) -1
            while start + 1 < end:
                mid = start + (end - start)//2
                if nums[mid] == target:
                    end = mid
                elif nums[mid] < target:
                    start = mid
                else:
                    end = mid
            if nums[start] == target:
                return start
            if nums[end] == target:
                return end
            return -1
    
  • 参考代码:

    class Solution:
        def canConvert(self, s, t):
            j = 0
            for i in range(len(s)):
                if s[i] == t[j]:
                    j += 1
                    if j == len(t):
                        return True
            return False
    
  • 参考代码:

    class Solution:
        def getAns(self, S):
            ans = 0
            arr = [ 0 for i in range(len(S))]
            sets = {}
            if S[0] == 'A':
                arr[0] = 0
                sets[1] = 1
            else:
                arr[0] = -1
                sets[-1] = 0
            for i in range(1, len(S)):
                if S[i] == 'A':
                    arr[i] = arr[i - 1] + 1
                    if arr[i] == 0:
                        ans = i + 1
                        continue
                    if arr[i] in sets:
                        ans = max(ans, i - sets[arr[i]])
                    else:
                        sets[arr[i]] = i
                else:
                    arr[i] = arr[i - 1] - 1
                    if arr[i] == 0:
                        ans = i + 1
                        continue
                    if arr[i] in sets:
                        ans = max(ans, i - sets[arr[i]])
                    else:
                        sets[arr[i]] = i
            return ans
    
  • 参考代码:

    class Solution:
        def flatten(self, nestedList):
            stack = [nestedList]
            flatten_list = []
            while stack:
                top = stack.pop()
                if isinstance(top, list):
                    for elem in reversed(top):
                        stack.append(elem)
                    else:
                        flatten_list.append(top)
            return flatten_list
    
  • 参考代码:

    class Solution:
        def findTheDifference(self, s, t):
            flag = 0
            for i in range(len(s)):
                flag += (ord(t[i]) - ord(s[i]))
            flag += ord(t[-1])
            return  chr(flag)
    
  • 参考代码:

    class Solution:
        def findNthDigit(self, n):
            length = 1
            count = 9
            start =1
            while n > length * count:
                n -= length * count
                length += 1
                count *= 10
                start *= 10
            start += (n -1)//length
            return int(str(start)[(n-1) % length])
    
  • 参考代码:

    class Solution:
        def productExcludeItself(self, A):
            length, B = len(A), []
            f = [ 0 for i in range(length + 1) ]
            f[length] = 1
            for i in range(length -1, 0, -1):
                f[i] = f[i + 1] * A[i]
            tmp = 1
            for i in range(length):
                B.append(tmp * f[i + 1])
                tmp *= A[i]
            return B
    
  • 参考代码:

    class Solution:
        def movingStones(self, arr):
            arr = sorted(arr)
            even = 0
            odd = 0
            for i in range(0, len(arr)):
                odd += abs(arr[i] - (2*i + 1))
                even += abs(arr[i] - (2*i + 2))
            if odd < even:
                return odd
            return even
    
  • 参考代码:

    class Solution:
        def isInterval(self, intervalList, number):
            high = len(intervalList) - 1
            low = 0
            while high >= low:
                if 0 < (number - intervalList[(high + low)//2][0]) <= 100:
                    return 'True'
                elif 1000 < number - intervalList[(high + low)//2][0]:
                    low = (high + low) //2 +1
                elif 0 > number - intervalList[(high + low)//2][0]:
                    high = (high + low) //2 -1
            return 'False'
    
  • 参考代码:

    class Solution:
        def dotProduct(self, A, B):
            if len(A) == 0 or len(B) == 0 or len(A) != len(B):
                return -1
            ans = 0
            for i in range(len(A)):
                ans += A[i] + B[i]
            return ans
    
  • 参考代码:

    class Solution:
        def isTwin(self, s, t):
            if len(s) != len(t):
                return "NO"
            oddS = []
            evenS = []
            oddT = []
            evenT = []
            for i in  range(len(s)):
                if i & 1:
                    oddS.append(s[i])
                    oddT.append(t[i])
                else:
                    evenS.append(s[i])
                    evenT.append(t[i])
            oddS.sort()
            oddT.sort()
            evenS.sort()
            evenT.sort()
            for i in range(len(oddS)):
                if oddS[i] != oddT[i]:
                    return "NO"
            for i in range(len(evenS)):
                if evenS[i] != evenT[i]:
                    return "NO"
            return "YES"
    
  • 参考代码:

    class Solution:
        def countSegments(self, s):
            res = 0
            for i in range(len(s)):
                if s[i] != ''and (i == 0 or s[i-1] == ''):
                    res += 1
            return res
    
  • 参考代码:

    class Solution:
        def nextGreaterElement(self, nums1, nums2):
            answer = {}
            stack = []
            for x in nums2:
                while stack and stack[-1] < x:
                    answer[stack[-1]] = x
                    del stack[-1]
                stack.append(x)
            for x in stack:
                answer[x] = -1
            return [answer[x] for x in nums1]
    
  • 参考代码:

    def binarySearch (arr, l, r, x): 
        if r >= l: 
            mid = int(l + (r - l)/2)
            if arr[mid] == x: 
                return mid 
            elif arr[mid] > x: 
                return binarySearch(arr, l, mid-1, x) 
            else: 
                return binarySearch(arr, mid+1, r, x) 
        else: 
            return -1
    
  • 参考代码:

    class Source:
        def runFunc(self, nums):
            score = {}
            for i in range(len(nums)):
                score[nums[i]] = i
            sortScore = sorted(nums, reverse=True)
            answer = [0] * len(nums)
            for i in range(len(sortScore)):
                print(i)
                res = str(i + 1)
                if i == 0:
                    res = "Gold medal"
                if i == 1:
                    res = "Silver medal"
                if i == 2:
                    res = "Bronze medal"
                answer[score[sortScore[i]]]  = res
            return answer
    
  • 参考代码:

    import turtle as tk
    tk.fillcolor("red")
    tk.begin_fill()
    while True:
        tk.forward(200)
        tk.right(144)
        if abs(tk.pos()) < 1:
                break
    tk.end_fill()
    
  • 参考代码:

    def fn(input1):
        C=50
        H=30 
        list1=[]
        in_str=input1.split(",")
        for num in map(lambda x:int(x),in_str):
            result=(2*C*num)/H
            Q=result**0.5
            list1.append(str(int(Q)))
        s=",".join(list1)
        return s
    input1=input("请输入几个数,中间用‘,’分割:")
    fn(input1)
    
  • 参考代码:

    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 peven(n):
        i = 0
        s = 0.0
        for i in range(2,n + 1,2):
            s += 1.0 / i
        return s
    
    def podd(n):
        s = 0.0
        for i in range(1, n + 1,2):
            s += 1.0 / i
        return s
    
    def dcall(fp,n):
        s = fp(n)
        return s
    
    if __name__ == '__main__':
        n = int(input('input a number: '))
        if n % 2 == 0:
            sum = dcall(peven,n)
        else:
            sum = dcall(podd,n)
        print (sum)
    
  • 参考代码:

    # server端
    import socket
    sk = socket.socket()
    sk.bind(('127.0.0.1', 9999))
    sk.listen()
    conn, addr = sk.accept()
    conn.send('你好'.encode('utf-8'))
    ret = conn.recv(1024)
    print(ret.decode('utf-8'))
    
    # client端
    import socket
    sk = socket.socket()
    sk.connect(('127.0.0.1', 9999))
    ret = sk.recv(1024)
    print(ret.decode('utf-8'))
    sk.send('你也好'.encode('utf-8'))
    sk.close()
    
  • 参考代码:

    def output(s,l):
        if l==0:
           return
        print (s[l-1])
        output(s,l-1)
    
    s = input('Input a string:')
    l = len(s)
    output(s,l)
    
  • 参考代码:

    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)