浦発まとめ


bin(10)[2:]
'1010'

1、10進数から2進数に変換する個数を計算する
def count_1(num):
    count = 0
    while num > 0:
        count += 1
        num &= (num - 1)#                    1   。  x = 0b1100, x-1=0b1011, x&(x-1)=0b1000
    return count
print(count_1(1234))
print(count_1(9))
5
2

2、一時変数を使わずに、二つの数の値を交換する
def swap(a,b):
    print("        ,a:{0},  b{1}".format(bin(a), bin(b)))
    a = a^b
    b = a^b
    a = a^b
    print("        ,a:{0},  b{1}".format(bin(a), bin(b)))      
swap(4,7)
        ,a:0b100,  b0b111
        ,a:0b111,  b0b100
import numpy as np
import scipy.signal as signal
x = np.array([6,4,8,6,9,21,4,13,18,9])
x
array([ 6,  4,  8,  6,  9, 21,  4, 13, 18,  9])
signal.medfilt(x)
array([ 4.,  6.,  6.,  8.,  9.,  9., 13., 13., 13.,  9.])
a = [1,2,3]
b = [10,20,30]
for item in zip(a,b):
    print(item)
(1, 10)
(2, 20)
(3, 30)
z = zip(a,b)
list(z)
[(1, 10), (2, 20), (3, 30)]

2つの文字列の最大連続文字列を求めます
def func(str1, str2):
    L1 = len(str1)
    L2 = len(str2)
    record = [[0 for i in range(L2+1)] for j in range(L1+1)]
    #print(record)
    print(len(record))
    maxNum = 0
    p =0
    for i in range(L1):
        for j in range(L2):
            if str1[i] == str2[j]:
                record[i+1][j+1] = record[i][j] + 1
                if record[i+1][j+1] > maxNum:
                    maxNum = record[i+1][j+1]
                    p = i + 1
    return str1[p-maxNum:p],maxNum, record
str1 = 'abcfeh'
str2 = 'bcfhe'
func(str1, str2)
7





('bcf',
 3,
 [[0, 0, 0, 0, 0, 0],
  [0, 0, 0, 0, 0, 0],
  [0, 1, 0, 0, 0, 0],
  [0, 0, 2, 0, 0, 0],
  [0, 0, 0, 3, 0, 0],
  [0, 0, 0, 0, 0, 1],
  [0, 0, 0, 0, 1, 0]])
def FirstUnrepeat(s):
    '''Python    '''
    if len(s) == 0:
        return -1
    dict = {}
    for char in s:
        dict[char] = 1 if char not in dict else dict[char] + 1
    for i in range(len(s)):
        if dict[s[i]] == 1:
            return s[i]
    return 'False! all repeated'

if __name__ == "__main__":
    cases = ['abcd13faeb', 'adasdsfa', 'dadadasjfds','azzzzs','zzz']
    #     c, f,j, -1,a,  'False! all repeated'
    for case in cases:
        print(FirstUnrepeat(case))
c
f
j
a
False! all repeated

def is_legal_IP(Strs):  
    ''''' 
    python     
    '''  
    if '.' not in Strs:  
        return False  
    elif Strs.count('.') != 3:  
        return False  
    else:  
        flag = True  
        one_list = Strs.split('.')  
        for item in one_list:  
            try:  
                one_num=int(item)  
                if one_num >= 0 and one_num <= 255:  
                    pass  
                else:  
                    flag = False  
            except:  
                flag = False  
        return flag  


if __name__=='__main__':  
    ip_list=['', '12.31.127.251', '10.10.0.1000','11.1.1.1','122.23.13','aa.12.1.2','12345678','adad.ass.h','12.31.127.256''']  
    for ip in ip_list:  
        if is_legal_IP(ip):
            print ('{} is a legal ip address!'.format(ip))
        else:  
            print ('{} is not a legal ip address!'.format(ip))
 is not a legal ip address!
12.31.127.251 is a legal ip address!
10.10.0.1000 is not a legal ip address!
11.1.1.1 is a legal ip address!
122.23.13 is not a legal ip address!
aa.12.1.2 is not a legal ip address!
12345678 is not a legal ip address!
adad.ass.h is not a legal ip address!
12.31.127.256 is not a legal ip address!
a = 'asa'
type(a)==str
True
import sys
n, m = map(int, input().strip().split())
time_weights = []
for i in range(n):
    p = list(map(int, input().strip().split()))
    time_weights.append(p)
    
ds = []
for i in range(m):
    d = int(input().strip())
    ds.append(d)
    
print(n,m)
print(time_weights)
print(ds)
5 3
4 34
3 68
1 46
8 53
2 94
3
4
5
5 3
[[4, 34], [3, 68], [1, 46], [8, 53], [2, 94]]
[3, 4, 5]
result = []
for d in ds:
    max_weight =  0
    for item in time_weights:
        if item[0] >= d and item[1] >= max_weight:
            max_weight = item[1]
    result.append(max_weight)

for r in result:
    print(r)
68
53
53
print(result)
[68, 53, 53]


n, a, b, c, f0 = list(map(int, input().strip().split()))
10 0 0 0 100
n, a, b, c, f0 = list(map(int, input().strip().split()))
f1 = a * f0 + 32768
f2 = a * f1 + b * f0 + 32773
f_n = [f0, f1, f2]
if n < 3:
    print(f_n[n])
else:
    for year in range(n-2):
        money = a * f_n[year+2] + b * f_n[year+1] + c * f_n[year] + 2 * (year+3)**2 - (year+3) + 32767
        f_n.append(money)       
    print(f_n[-1])
10 0 0 0 100
32957
f_n
[100, 32768, 32773, 32782, 32795, 32812, 32833, 32858, 32887, 32920, 32957]
import sys
n, m = map(int, input().strip().split())
time_weights = []
for i in range(n):
    p = list(map(int, input().strip().split()))
    time_weights.append(p)
    
ds = []
for i in range(m):
    d = int(input().strip())
    ds.append(d)

result = []
for d in ds:
    max_weight =  0
    for item in time_weights:
        if item[0] >= d and item[1] >= max_weight:
            max_weight = item[1]
    if max_weight == 0:
        result.append(-1)
    else:
        result.append(max_weight)

for r in result:
    print(r)
n, a, b, c, f0 = list(map(int, input().strip().split()))
f1 = a * f0 + 32768
f2 = a * f1 + b * f0 + 32773

if n == 0:
    print(f0)
if n == 1:
    print(f1)
if n == 0:
    print(f2)
    
F0, F1, F2 = f0, f1, f2
for year in range(n-2):
    Next = a * F2  + b * F1 + c * F2 + 2 * (year+3)**2 - (year+3) + 32767
    F0, F1, F2 = F1, F2, Next       
print(F2)
3 0 0 0 100
32782

1、素数かどうかを判断する
def isPrime(number):
    for num in range(number-1, 1, -1):
        if number % num == 0:
            return False
    return True
for num in [1,2,3,4,5,10,19,44,97]:
    print(isPrime(num), end=' ')
True True True False True False True False True 

2、出力文字列の頭文字大文字
def Simple(strings):
    res = ''
    Strs = strings.split()
    for s in Strs:
        res += s[0].upper()
    print(res)
Simple('end of file')
Simple('Hello world')
EOF
HW

3、1つの配列を与えて、その中の0要素を配列の最も右側に移動して、0要素以外は元の順序を維持します
def func(L):
    lenth = len(L)
    for index in range(lenth):
        if L[index] == 0:
            L.pop(index)
            L.insert(0,0)
    return L
a = [0,1,5,10,2,0,0,3,4,0]
func(a)
[0, 0, 0, 0, 1, 5, 10, 2, 3, 4]

4、数字xは1000<=x<=9999かつx%a=0、(x+1)%b=0、(x+2)%c=0を満たし、abcの値を与え、xを求める
def func(a,b,c):
    res = []
    for num in range(1000, 10000):
        if num % a == 0 and (num+1) % b == 0 and (num+2) % c == 0:
            res.append(num)
    if res == []:
        print("No such number")
    else:
        print(res)
func(10,3,8)
[1070, 1190, 1310, 1430, 1550, 1670, 1790, 1910, 2030, 2150, 2270, 2390, 2510, 2630, 2750, 2870, 2990, 3110, 3230, 3350, 3470, 3590, 3710, 3830, 3950, 4070, 4190, 4310, 4430, 4550, 4670, 4790, 4910, 5030, 5150, 5270, 5390, 5510, 5630, 5750, 5870, 5990, 6110, 6230, 6350, 6470, 6590, 6710, 6830, 6950, 7070, 7190, 7310, 7430, 7550, 7670, 7790, 7910, 8030, 8150, 8270, 8390, 8510, 8630, 8750, 8870, 8990, 9110, 9230, 9350, 9470, 9590, 9710, 9830, 9950]

5、nの階乗
def JC(n):
    res = 1
    for i in range(1, n+1):
        res *= i
    return res
JC(4)
24

6、10個の数を入力し、最大数と最後の数を交換し、最小数と最初の数を交換する
def func():
    print("please input 10 nums")
    nums = list(map(int, input().strip().split()))
    Max = max(nums)
    Min = min(nums)
    Max_index = nums.index(Max)
    Min_index = nums.index(Min)
    nums[Max_index] = nums[-1]
    nums[-1] = Max
    nums[Min_index] = nums[0]
    nums[0] = Min
    return nums
func()
please input 10 nums
12 2 45 2 18 9 13 9 11 19





[2, 12, 19, 2, 18, 9, 13, 9, 11, 45]

7、最大値と最小値の検索
def find_max_min(L):
    Min = L[0]
    Max = L[0]
    for item in L:
        if item >= Max:
            Max  = item
        if item <= Min:
            Min = item
    return Max, Min
find_max_min([1,2,20,4,2,4,43,56,44,23])
(56, 1)

8、猿が桃を食べる問題
def func():
    result = [1]
    for i in range(9):
        temp = (result[i]+1) * 2
        result.append(temp)
    return result[-1], result
func()
(1534, [1, 4, 10, 22, 46, 94, 190, 382, 766, 1534])
def func():
    p = 1
    for i in range(9,0,-1):
        p = (p+1)*2
        print("  {}     {}    ".format(i,p))
    print("    {}   ".format(p))
func()
  9     4    
  8     10    
  7     22    
  6     46    
  5     94    
  4     190    
  3     382    
  2     766    
  1     1534    
    1534   

9、1つの数targetと1つの配列numを求めて、numの中の要素の加算がtargetの要素の下付き文字に等しいことを求めます.
def func(target, L):
    for i in range(len(L)):
        for j in range(i, len(L)):
            if i != j and L[i] + L[j] == target:
                print(i,j)
target = 10
L = [1,2,3,4,5,10,4,4,3,7,6]
func(target,L)
2 9
3 10
6 10
7 10
8 9

10、文字列間を-で接続する
def func(strs):
    r = '-'    
    print(r.join(strs))
func('adsfadsf')
a-d-s-f-a-d-s-f

11、百元百鶏
  • テーマは简単です:雄鶏5文銭1羽、雌鶏3文銭1羽、ニワトリ3羽1文銭、100文銭で100羽のニワトリを买って、その中の雄鶏、雌鶏、ニワトリはすべて必ずあって、雄鶏に闻いて、雌鶏、ニワトリはいくら买ってちょうど100文銭を足します.
  • def func():
        for i in range(1,20):
            #     20 
            for j in range(1,33):
                #     33 
                z = 100 - i - j #     
                if 5*i + 3*j + z/3 == 100:
                    print("  :{},  :{},  :{}".format(i,j,z))
    
    func()
    
      :4,  :18,  :78
      :8,  :11,  :81
      :12,  :4,  :84
    
    def func():
        for i in range(4, 16,4):
            #      4   
            j = 25 - 7/4  * i #      
            z = 100 -i -j
            if 5*i + 3*j + z/3 == 100:
                print(i,int(j),int(z))
    
    func()
    
    4 18 78
    8 11 81
    12 4 84
    

    12、文字列の反転
    def func(strs):
        s =  strs[::-1]
        print(s)
    
    s = 'abcd'
    func(s)
    
    dcba
    
    s
    
    'abcd'
    

    13、最大公約数と最小公倍数
    def func(m,n):
        m,n = (m,n) if m < n else (n,m)
        print(m,n)
        for i in range(m, 0, -1):
            if n%i == 0 and m%i == 0:
                print("     :{},     :{}".format(i, m*n//i))#                 
                break
        
    
    func(7,21)
    
    7 21
         :7,     :21
    

    14、0~7のみで、1桁で構成できる奇数個数、2桁で構成できる奇数個数、…9桁で構成できる奇数の個数を出力する.
    def func():
        '''        ,      1,3,5,7,     ;
              0,   7   ,             0,8   。    
        '''
        for i in range(1,10):
            if i == 1:
                print('{}        :{}'.format(i, 4))
            else:
                nums = 7*8**(i-2)*4
                print('{}        :{}'.format(i, nums))
    
    func()
    
    1        :4
    2        :28
    3        :224
    4        :1792
    5        :14336
    6        :114688
    7        :917504
    8        :7340032
    9        :58720256
    

    15、文字列ABAaacに文字数を統計させてA:2,B:1,a:2,c:1を出力させる
    def func(strs):
        result = {}
        for char in strs:
            if char not in result.keys():
                result[char] = 1
            else:
                result[char] += 1
        for item in result.items():
            print(item[0], ':', item[1])
    
    func("ABAACdaada")
    
    C : 1
    B : 1
    A : 3
    d : 2
    a : 3
    
  • 上記の出力順序は不定であり、先に出現した文字に従って先に出力すべきである
  • def func(strs):
        chars = []
        counts = []
        for char in strs:
            if char not in chars:
                chars.append(char)
                counts.append(1)
            else:
                index = chars.index(char)
                counts[index] += 1
        
        for item in zip(chars, counts):
            print(item[0], ':', item[1], end=',')
    
    func("ABAEEFACdaada")
    
    A : 3,B : 1,E : 2,F : 1,C : 1,d : 2,a : 3,
    

    16、統計の2つの数をバイナリに変換した後、各ビット数の異なる個数
    def func(num1, num2):
        str1 = bin(num1)[2:][::-1]
        str2 = bin(num2)[2:][::-1]
        count = 0
        print(str1, str2)
        L = min(len(str1), len(str2))
        for i in range(L):
            if str1[i] == str2[i]:
                count += 1            
        print(count)
    
    func(1999,2999)
    
    11110011111 111011011101
    6
    
    8^0
    
    8
    
    while True:
        try:
            a, b = map(int, input().strip().split())
            print("%.2f"%(a + b))
        except EOFError:
            break
    
    2 3
    5.00
    45 25
    70.00
    c
    
    print("{:.2f}".format(144.3))
    
    
    144.30