study Python 23day

def check_ip(s):
    for i in s:
        if i not in range(256):
            return False
        return True

def check_mask(s):
    if s in ([255,255,255,255],[0,0,0,0]):
        return False
    v=''
    for x in s[::-1]:
        for i in range(8):
            v+=str(x>>i&1)
    if '10' in v:
        return False
    Return True


res=[0,0,0,0,0,0,0]
while True:
    try:
        s=input().split('~')
        if len(s)!=2:
            break
    except:
        break
    try:
        ip=[int(x) for x in s[0].split('.')]
        mask=[int(x) for x in s[1].split('.')]
    except:
        res[5]+=1
        continue
    if check_ip(ip) and check_mask(mask):
        i,a=ip[0],ip[1]
        if i in range(1,127):
            res[0]+=1
        if i in range(128,192):
            res[1]+=1
        if i in range(192,224):
            res[2]+=1
        if i in range(224,240):
            res[3]+=1
        if i in range(240,256):
            res[4]++1
        if i==10 or (i==127 and (a in range(16,32)) or (i=192 and a==168)):
            res[6]+=1
print(' '.join(str(x)) for x in res)
from collections import Counter
while True:
    try:
        n=int(input())
        for i in range(n):
            c=Count(input())
            start=26
            rev=0
            for j in c.most_common():
                rev+=j[1]*start
                start-=1
            print(rev)
    except:
        break

while True:
    try:
        num=int(input())
        res=0
        for i in range(1,num+1):
            if i%7==0:
                res+=1
            elif '7'in str(i):
                res+=1
            else:
                continue
        print(res)
    except:
        break

print(eval(input()))

import sys
 
while True:
    try:
        string = sys.stdin.readline()
        line = int(string)
         
        if line == 1 or line == 2:
            print(-1)
        elif line == 3:
            print(2)
        elif line%4==1 or line%4==3:
            print(2)
        elif line%4==2:
            print(4)
        else:
            print(3)
         
    except:
        break


# -*- coding: utf-8 -*-
# !/usr/bin/python3
# 解题思路:动态规划dp[i][j]表示st1[0:j - 1]和st2[0:i - 1]的最小距离;
# 那么st1和st2的距离与dp[i][j], dp[i - 1][j]和dp[i][j - 1]有关;
# 如果st1[j] == st2[i], dp[i + 1][j + 1] = dp[i - 1][j - 1];
# 如果st1[j] != st2[i], dp[i + 1][j + 1] = min(dp[i - 1][j - 1], dp[i - 1][j] + 1, dp[i][j - 1] + 1);
# 边界条件:第0行和第0列表示空字符串分别于st1和st2的子字符串的距离,dp[i][0] = i, dp[0][j] = j
 
while True:
    try:
        st1 = input()
        st2 = input()
 
        if len(st1) < len(st2):
            st1, st2 = st2, st1
 
        m = len(st1)
        n = len(st2)
 
        res = [[0 for i in range(m + 1)] for i in range(n + 1)]
 
        for i in range(n + 1):
            res[i][0] = i
 
        for j in range(m + 1):
            res[0][j] = j
 
        for i in range(1, n + 1):
            for j in range(1, m + 1):
                if st1[j - 1] == st2[i - 1]:
                    res[i][j] = res[i - 1][j - 1]
                else:
                    res[i][j] = min(res[i - 1][j - 1] + 1, res[i - 1][j] + 1, res[i][j - 1] + 1)
 
        print(res[n][m])
 
    except:
        break

while True:
    try:
        a=input()
        b=input().split()
        c=int(input())
        print(b[-c] if c!=0 else 0)
    except:
        break

while True:
    try:
        print('ABCD'*int(input()))
    except:
        break

while True:
    try:
        a,b=input().split()
        
        print(a[:int(b)])
    except:
        break

from collections import Counter
while True:
    try:
        n=int(input())
        for i in range(n):
            c=Counter(input())
            start=26
            rev=0
            for j in c.most_common():
                rev+=j[1]*start
                start-=1
            print(rev)
    except:
        break

def solver(board, rows, cols, squs, i, j):
    if i>=9: return True
 
    if board[i][j]!='0':
        return solver(board, rows, cols, squs, (i*9+j+1)//9, (i*9+j+1)%9)
 
    for n in {'1','2','3','4','5','6','7','8','9'}-(rows[i]|cols[j]|squs[i//3*3+j//3]):
        board[i][j] = n
        rows[i].add(n)
        cols[j].add(n)
        squs[i//3*3+j//3].add(n)
 
        if not solver(board, rows, cols, squs, (i*9+j+1)//9, (i*9+j+1)%9):
            board[i][j] = '0'
            rows[i].remove(n)
            cols[j].remove(n)
            squs[i//3*3+j//3].remove(n)
        else:
            return True
    return False
 
while True:
    try:
        board = []
        for i in range(9):
            board.append(input().split())
         
        rows, cols, squs = [set() for i in range(9)], [set() for i in range(9)], [set() for i in range(9)]
        for i, row in enumerate(board):
            for j, num in enumerate(row):
                if num!='0':
                    rows[i].add(num)
                    cols[j].add(num)
                    squs[i//3*3+j//3].add(num)
        solver(board, rows, cols, squs, 0, 0)
        for i in range(9):
            print(' '.join(board[i]))
    except:
        break

try:
    while True:
        row,col = map(int,input().split())
        maze = []
        for i in range(row):
            maze.append(list(map(lambda x:-x,map(int,input().split()))))
        queue = [[0,0]]
        maze[0][0] = 1
        while queue:
            x,y = queue.pop(0)
            if x == row-1 and y == col-1:
                break
            if x+1 < row and maze[x+1][y] == 0:
                maze[x+1][y] = maze[x][y]+1
                queue.append([x+1,y])
            if y+1 < col and maze[x][y+1] == 0:
                maze[x][y+1] = maze[x][y]+1
                queue.append([x,y+1])
            if x-1 >= 0 and maze[x-1][y] == 0:
                maze[x-1][y] = maze[x][y]+1
                queue.append([x-1,y])
            if y-1 >= 0 and maze[x][y-1] == 0:
                maze[x][y-1] = maze[x][y]+1
                queue.append([x,y-1])
        result = [[row-1,col-1]]
        for i in range(maze[-1][-1]-1,0,-1):
            tempRow = result[0][0]
            tempCol = result[0][1]
            if tempRow-1>=0 and maze[tempRow-1][tempCol] == i:
                result.insert(0,[tempRow-1,tempCol])
            elif tempCol-1>=0 and maze[tempRow][tempCol-1] == i:
                result.insert(0,[tempRow,tempCol-1])
            elif tempRow+1<row and maze[tempRow+1][tempCol] == i:
                result.insert(0,[tempRow+1,tempCol])
            elif tempCol+1<col and maze[tempRow][tempCol+1] == i:
                result.insert(0,[tempRow,tempCol+1])
        for i in result:
            print('(%d,%d)'%(i[0],i[1]))
except Exception:
    pass
def numberToWords(num):
    to19='one two three four five six seven eight nine ten eleven twelve thirteen fourteen fifteen seventeen eighteen nineteen'.split()
    tens="twenty thirty forty fifty sixty seventy eighty ninety".split()
    def words(n):
        if n<20:return to19[n-1:n]
        if n<100:return [tens[n//10-2]]+words(n%10)
        if n<1000:
            return [to19[n//100-1]]+["hundred"]+["and"]+words(n%100)
        for p,w in enumerate(('thousand',"million","billion"),1):
            if n<1000**(p+1):
                return words(n//1000**p)+[w]+words(n%1000**p)
    return " ".join(words(num)) or "Zero"
while True:
    try:
        print(numberToWords(int(input())))
    except:break

while True:
    try:
        n=int(input())
        m=list(map(int,input().split()))#python3这块没有python2来的直接,需要用list转换一下
        x=list(map(int,input().split()))
        diff={0}
        for i in range(n):
            d=diff.copy()
            for j in range(x[i]):
                for k in d:
                    temp=k+m[i]*(j+1)
                    if temp not in d:
                        diff.add(temp)
        print(len(diff))
    except:
        break

while True:
    try:
        a=input()
        char,space,number,other=0,0,0,0
        for i in a:
            if i==" ":space+=1
            elif i.isnumeric():
                number+=1
            elif i.isalpha():char+=1
            else:other+=1
        print(char)
        print(space)
        print(number)
        print(other)
    except:
        break


import sys
while True:
    try:
        num=int(input())
        print(int(2.875*num))
        print(int(0.03125*num))
    except:
        break
#按比例缩放就好了。

while True:
    try:
        a=int(input())-1
        arr=[1,2]
        while len(arr)<a:
            arr.append(arr[-1]+arr[-2])
        print(arr[-1])
    except:
        break

while True:
    try:
        #key,string分别代表输入的key的加要密的字符串
        #chars是密钥对应的字母表,res是要返回的结果。
        key, string, chars, res = input(), input(), [], ""
        #经过下面的循环,chars前面几个是密匙的字母
        for i in key:
            if i not in chars:
                chars.append(i)
        #如果输入的key中有小写字母,转为大写字母。
        chars = list(map(lambda c: c.upper(), chars))
        #剩下的字母,填充到chars里面。
        for i in range(65, 91):
            if chr(i) not in chars:
                chars.append(chr(i))
        # 将输入加密。
        for i in string:
            if i.isupper():
                res += chars[ord(i) - 65]
            elif i.islower():
                res += chars[ord(i) - 97].lower()
            else:
                res += i
        print(res)
 
    except:
        break

while True:
    try:
        n, curNum = int(input()), 1  
        res = [[0 for i in range(n)] for j in range(n)]
        for i in range(n):
            for j in range(i + 1):
                res[i - j][j] = curNum
                curNum += 1
        for i in res:
            print(" ".join(map(str, (filter(lambda i: i != 0, i)))))
    except:
        break
        
while True:
    try:
        n,num=int(input()),1
        res=[[0 for i in range(n)] for j in range(n)]
        for i in range(n):
            for j in range(i+1):
                res[i-j][j]=num
                num+=1
        for i in res:
            print(" ".join(map(str,(filter(lambda i :i!=0,i)))))

while True:
    try:
        print(''.join(sorted(input())))
    except:
        break

while True:
    try:
        # ip to int_address
        # 按 '.'拆开 => map => 每节转二进制,去'ob',填充'0' => 合并 =》 转十进制
        a=input()
        b=input()
        s=a.split('.')
        print(int(''.join(map(lambda n:bin(int(n)).replace('0b','').rjust(8,'0'),s)),2))
        strbin=bin(int(b)).replace('0b','').rjust(32,'0')
        # int_address to bin
        ip=[]
        for i in range(4):
            ip.append(strbin[i*8:(i+1)*8])
        print('.'.join(map(lambda n:str(int(n,2)),ip)))
        # bin to ip
        # 将32位二进制地址每八个拆开 => map => 每节转十进制 =》 合并 
        
    except:
        break
        

def longestPalindrome(s):
    if s==s[::-1]:return len(s)
    maxLen=0
    for i in range(len(s)):
        if i-maxLen>=1 and s[i-maxLen-1:i+1]==s[i-maxLen-1:i+1][::-1]:
            maxLen+=2
            continue
        if i-maxLen>=0 and s[i-maxLen:i+1]==s[i-maxLen:i+1][::-1]:
            maxLen+=1
    return maxLen
while True:
    try:
        a=input()
        if a:
            print(longestPalindrome(a))
 
    except:
        break

import re
while True:
    try:
        s_list=re.split('[^a-zA-Z]+',input().strip())
        print(' '.join(s_list[::-1]).strip())
    except:
        break


while True:
    try:
 
        dic = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F"]
        s = input().replace(" ", "")  #s是输入的合并后的字符串
        ss = ""  #ss为最终返回的字符串
        odd, even = "", ""  # 字符串的奇数子串和偶数子串
        # 经过下面的循环,提取奇数与偶数的子串。
        for i, v in enumerate(s):
            if i % 2 == 0:
                even += v
            else:
                odd += v
        # 奇数与偶数部分排序       
        odd = "".join(sorted(odd))
        even = "".join(sorted(even))
 
        # 如果字符串在0123456789abcdefABCDEF范围内,对其做变换,否则不做任何处理。
        for i in range(len(even)):
            if even[i] in "0123456789abcdefABCDEF":
                ss += dic[int(bin(dic.index(even[i].upper())).replace("0b", "").rjust(4, "0")[::-1], 2)]
            else:
                ss += even[i]
            if len(odd) != i:   #注意偶数串可能比奇数串长一个字符,所以要做一下判断。
                if odd[i] in "0123456789abcdefABCDEF":
                    ss += dic[int(bin(dic.index(odd[i].upper())).replace("0b", "").rjust(4, "0")[::-1], 2)]
                else:
                    ss += odd[i]
        print(ss)
    except:
        break

while True:
    try:
        a, b = input(), input()
        resA, resB = "", ""
        for i in a:
            if i.isupper():
                if i != "Z":
                    resA += chr(ord(i) + 1).lower()
                else:
                    resA += "a"
            elif i.islower():
                if i != "z":
                    resA += chr(ord(i) + 1).upper()
                else:
                    resA += "A"
            elif i.isdigit():
                if i != "9":
                    resA += chr(ord(i) + 1)
                else:
                    resA += "0"
        for i in b:
            if i.isupper():
                if i != "A":
                    resB += chr(ord(i) - 1).lower()
                else:
                    resB += "z"
            elif i.islower():
                if i != "a":
                    resB += chr(ord(i) - 1).upper()
                else:
                    resB += "Z"
            elif i.isdigit():
                if i != "0":
                    resB += chr(ord(i) - 1)
                else:
                    resB += "9"
        print(resA)
        print(resB)
    except:
        break

def issu(x):
    tem = 2
    while tem**2<=x:
        if x%tem==0:
            return False
        tem+=1
    return True
def find(a,l1,l2,l3):
    for i in range(0,len(l3)):
        if issu(a+l3[i]) and l1[i]==0:
            l1[i]=1
            if l2[i]==0 or find(l2[i],l1,l2,l3):
                l2[i] = a
                return True
    return False
 
try:
    while True:
        n = input()
        n = int(n)
        l = list(map(int,input().split()))
        ji,ou = [],[]
        for i in range(n):
            if l[i]%2==0:
                ou.append(l[i])
            else:
                ji.append(l[i])
        result = 0
        match = [0]*len(ou)
        for i in range(0,len(ji)):
            used = [0]*len(ou)
            if find(ji[i],used,match,ou):
                result+=1
        print(result)
except:
    pass

from collections import defaultdict
 
while True:
    try:
        dd = defaultdict(list)
        a = input().split()
        # words是输入的单词,lookup是要查找的单词,num是要查找兄弟单词的索引,brothers是找到的兄弟单词列表
        words, lookup, num, brothers = a[1:1 + int(a[0])], a[-2], int(a[-1]), []
        for i in words:
            dd["".join(sorted(i))].append(i)
        for i in dd["".join(sorted(lookup))]:
            if i != lookup: brothers.append(i)
        # 下面这两行坑的老子调了半个小时。
        print(len(brothers))
        if brothers and num <= len(brothers):
            print(sorted(brothers)[num - 1])
    except:
        break

while True:
    try:
        a=input()
        res=[False]*len(a)
        s=[]
        for i,v in enumerate(a):
            if v.isalpha():
                s.append(v)
            else:
                res[i]=v
        s.sort(key=lambda c:c.lower())
        for j,v in enumerate(res):
            if not v:
                res[j]=s[0]
                s.pop(0)
        print(''.join(res))
    except:
        break


while True:
    try:
        a=input().split()[1:]
        b=map(str,sorted(map(int,set(input().split()[1:]))))
        totalNum=0
        res=""
        for num in b:
            singleRes,count="",0
            for i,v in enumerate(a):
                if num in v:
                    singleRes+=str(i)+" "+v+" "
                    totalNum+=2
                    count+=1
            if count:
                singleRes=num+" "+str(count)+" "+singleRes
                totalNum+=2
            res+=singleRes
        print((str(totalNum)+" "+res).rstrip())
 
 
 
    except:
        break

def get_index(nums,target):
    low,high=0,len(nums)-1
    pos=len(nums)
    while low<high:
        mid=(low+high)//2
        if nums[mid]<target:
            low=mid+1
        else:
            high=mid
            pos=mid
    return pos
def increase_lis(l,res):
    n=len(l)
    temp=[10**10]*n
    temp[0]=l[0]
    res+=[1]
    for i in range(1,n):
        pos=get_index(temp,l[i])
        res+=[pos+1]
        temp[pos]=l[i]
    return res
while True:
    try:
        n=int(input())
        a=list(map(int,input().strip().split()))
        dp_1,dp_2=[],[]
        dp_1=increase_lis(a,dp_1)
        new_list=a[::-1]
        dp_2=increase_lis(new_list,dp_2)
        maxValue=max([dp_1[i]+dp_2[n-i-1] for i in range(n)])
        print(n-maxValue+1)
    except:
        break

from collections import defaultdict
while True:
    try:
        a=input()
        b=defaultdict(int)
        for i in a:
            b[i]+=1
        for i in b.keys():
            if b[i]==min(b.values()):
                a=a.replace(i,'')
        print(a)
                
    except:
        break

while True:
    try:
        n=int(input())
        print(n//2)
    except:
        break

d={
    "abc":2,
    "def":3,
    "ghi":4,
    "jkl":5,
    "mno":6,
    "pqrs":7,
    "tuv":8,
    "wxyz":9,
 
}
while True:
    try:
        s=str(input())
        res=''
        for i in s:
            if i.isupper:
                if i=='Z':
                    res+='a'
                else:
                    res+=chr(ord(i.lower())+1)
            elif i.islower:
                for j in d.keys():
                    if i in j:
                        res+=str(d[j])
                        break
            else:
                res+=i
        print(res)
    except:
        break

import re 
while True:
    try:
        s=input()
        #1
        if len(s)<=8:
            print('NG')
            continue
        #2
        count=0
        if re.search('[0-9]',s):count+=1
        if re.search('[a-z]',s):count+=1
        if re.search('[A-Z]',s):count+=1
        if re.search('[^0-9a-zA-Z]',s):count+=1
        if count<3:
            print('NG')
            continue
        #3
        if re.search(r'.*(...)(.*/1)',s):
            print('NG')
            continue
        print('OK')
    except:
        break

error = dict()
filelist = []
while True:
    try:
        record = ' '.join(''.join(input().split('\\')[-1]).split())
        filename = record.split()
        if len(filename[0]) >= 16:
            filename[0] = filename[0][-16:]
        record = ' '.join(filename)
        if record not in error.keys():
            error[record] = 1
            filelist.append(record)
        else:
            error[record] += 1        
    except:
        break
key = filelist[-8:]
for each in key:
    print(' '.join(each.split()),error[each])

def check_ip(s):
    for i in s:
        if i not in range(256):
            return False
    return True

def check_mask(s):
    if s in ([255,255,255,255],[0,0,0,0]):
        return False
    v=''
    for x in s[::-1]:
        for i in range(8):
            v+=str(x>>i&1)
    if '10' in v:
        return False
    return True
res=[0,0,0,0,0,0,0]
while True:
    try:
        s=input().split('~')
        if len(s)!=2:
            break
    except:
        break
    try:
        ip=[int(x) for x in s[0].split('.')]
        mask=[int(x) for x in s[1].split('.')]
    except:
        res[5]+=1
        continue
    if check_ip(ip) and check_mask(mask):
        i,a=ip[0],ip[1]
        if i in range(1,127):
            res[0]+=1
        if i in range(128,192):
            res[1]+=1
        if i in range(192,224):
            res[2]+=1
        if i in range(224,240):
            res[3]+=1
        if i in range(240,256):
            res[4]+=1
        if i==10 or (i==127 and(a in range(16,32)) or (i==192 and a==168)):
            res[6]+=1
    else:
        res[5]+=1
print(' '.join(str(x) for x in res))

while True:
    try:
        dx=[-1,0,1,0]
        dy=[0,-1,0,1]
        x=0
        y=0
        s=input()
        for i in s.split(';'):
            if i and i[0] in 'ASDW':
                num=int(i[1:])
                x+=num*dx['ASDW'.find(i[0])]
                y+=num*dy['ASDW'.find(i[0])]
        print('%d,%d'%(x,y))
    except:
        break

s=str(bin(int(input())))
count=0
for i in s:
    if i=='1':
        count+=1
print(count)


n=int(input())
ls=[]
for i in range(n):
    ls.append(input())
for i in sorted(ls):
    print(i)

s=input()
print(' '.join(s.split()[::-1]))

print(input()[::-1])

s=str(input())
print(s[::-1])

s=str(input())
s1=set()
for i in s:
    if 0<ord(i)<128:
        s1.add(i)
print(len(s1))

while True:
    try:
        s=str(input())
        s1=''
        for i in s[::-1]:
            if i not in s1:
                s1+=i
        print(s1)
    except:
        break

#用defaultdict,每一个值都有默认值
from collections import defaultdict
while True:
    try:
        n=int(input())
        df=defaultdict(int)
        for i in range(n):
            key,value=map(int,input().split())
            df[key]+=value
        for i in sorted(df.keys()):
            print(str(i)+' '+str(df[i]))
    except:
        break

print(round(float(input())+0.001))

n=int(input())
ls=[]
for i in range(2,n//2+1):
    while n%i==0:
        ls.append(i)
        n/=i
print(' '.join(map(str,ls))+' ' if ls else str(n)+' ')

while True:
    try:
        print(int(input(),16))
    except:
        break

a=input()
b=input()
def sprint_str(s):
    if len(s)<=8:
        print(s+'0'*(8-len(s)))
    else:
        while len(s)>8:
            print(s[:8])
            s=s[8:]
        print(s+'0'*(8-len(s)))
sprint_str(a)
sprint_str(b)

while True:
    try:
        a=int(input())
        s=set()
        for i in range(a):
            s.add(int(input()))
        for j in sorted(s):
            print(j)
    except:
        break

a=input().lower()
b=input().lower()
print(a.count(b))

print(len(input().split()[-1]))
发布了65 篇原创文章 · 获赞 0 · 访问量 550

猜你喜欢

转载自blog.csdn.net/u011624267/article/details/103923585