Python-クラシックプログラムの例


  • リストソート
  • def que6():
        # 6.      x, y, z,      ,   n        。
        #     :   sort  ,           。
        li = np.random.randint(-100, 100, size=10)
        #     
        li = li.tolist()
        #  sort()  
        li_sort = sorted(li, reverse = False)
        print(' sort  ,      :{}'.format(li_sort))
    
        #   sort  ,        ,
    
        #     
        def bubbleSort(m):
            m = m.copy()
            for time in range(1, len(m)):
                for index in range(len(m) - time):
                    if m[index] > m[index+1]:
                        m[index], m[index+1] = m[index+1] , m[index]
            return  m
    
        #     
        def selectSort(m):
            m = m.copy()
            for seat_L in range(len(m)-1):
                for seat_R in range(seat_L+1, len(m)):
                    if m[seat_L] > m[seat_R]:
                        m[seat_L], m[seat_R] = m[seat_R], m[seat_L]
            return m
    
        #     1(      ):
        def insertSort_1(m):
            result = []
    
            #     k    li
            def to_insert(li, k):
                #    
                tab = False
    
                #       
                #               +1,None    (   ),             ‘  ’
                for i in range(len(li) + 1):
                    #      ,  ‘          ’,   ‘  ’  
                    if i == (len(li)):
                        tab = True
    
                    #     li[-1]    (  )  ,      ,            
                    if not tab and k < li[i]:
                        li.insert(i, k)
                        break
                #       ,     ,  ‘  ’     ,       ‘  ’
                if tab:
                    li.append(k)
                return li
            #     
            # result = result[:1]
            for length in range(len(m)):
                result = to_insert(result, m[length])
    
                # print(result,m[length])
            return result
    
        #     2(      ):
        def insertSort2(m):
            m = m.copy()
            result = m[:1]
            for index_choose in range(1, len(m)):
                #      index_choose  ,   index_choose+1   append
                #         ,        ,     
                for index_insert in range(len(result) + 1):
                    print(result, index_insert,'
    ',m, index_choose,'

    ') if index_insert != index_choose and m[index_choose] < result[index_insert] : result.insert(index_insert, m[index_choose]) break if index_insert == index_choose: result.append(m[index_choose]) # print(result, m[index_choose]) return result # print(li) print(' :',insertSort3(li)) print(' :',selectSort(li)) print(' :',bubbleSort(li)) que6()
  • 辞書キー値
  • を置き換える.
    # 1.     .\
    def que1():
        d={1:"one",2:"two"}
    
        #   1 ---     
        def method1(d):
            d = d.copy()
            result = {}
            for k,v in d.items():
                result[v] = k
            return result
    
        #   2 ---    
        def method2(d):
            d = d.copy()
            result = {v:k for k,v in d.items()}
            return result
    
        #   3 ---      
        def method3(d):
            d = d.copy()
            #      
            def match(dic, b):
                return [k for k,v in dic.items() if v == b]
            #    key-None,   
            result = {}
            result = result.fromkeys(d.values())
            for k in result.keys():
                result[k] = match(d, k)[0]
            return result
    
        #   4 ---       <     /     >
        def method4(d):
            d = d.copy()
            key = d.keys()
            val = d.values()
            data = list(zip(key, val))
    
            #   4-1
            result1 = {}
            for i in range(len(data)):
                result1[data[i][1]] = data[i][0]
    
            #   4-2
            result2 = dict(zip(val, key))
    
            return result1, result2
    
        print('         :{}'.format(method1(d)))
        print('     :{}'.format(method2(d)))
        print('      :{}'.format(method3(d)))
        print('           :{}'.format(method4(d)[0]))
        print('         :{}'.format(method4(d)[1]))
    # que1()
  • リストから重複する要素を削除する
  • # 3.       list =[1,2,5,4,1,5,6,8,0,2,5]
    a = np.random.randint(-100, 100, size=10)
    a = a.tolist()
    
    def method1(a):
        a = a.copy()
        a = set(a)
        return a
    def method2(a):
        b = a.copy()
        c = 0
        for i in range(len(a)-1):
            if b[i+c] in b[:i+c]+b[i+c+1:]:
                b.pop(i+c)
                c -= 1
        return b
    print('   :',method1(a))
    print('   :',method2(a))
  • 出力素数
  • def prime(end):
    
        prime_list = []
        if end <= 1:
            print('    1')
        else:
            # prime_list.append(2)
            for i in range(2, end+1, 1):
                count = 0
                if i == 2:
                    if i%2 != 0:
                        prime_list.append(2)
                else:
                    for m in range(2, i):
                        #     ,     
                        if (i % m) == 0:
                            # print(i, m)
                            break
                        #     +1
                        else:
                            count += 1
                        #         (0/n)
                        if count == i - 2:
                            prime_list.append(i)
    
                        print(count, i, m)
    
        return (prime_list)
    
    num = int(input('   2   ?'))
    print(prime(num))
  • 印刷九九乗算表
  • #        
    
    for i in range(1,10):
        for j in range(1, i+1):
            print('{}×{}={}'.format(i, j, i*j),end="\t")
        print('
    ')
  • 塗りつぶしと中空の星
  • を印刷
    # 4.     
    def que4():
        #      
        def triangle_solid(num):
            for i in range(num):
                tab = False
                for j in range(i+1):
                    print('*',end='')
                    if j == i:
                        tab = True
                if tab:
                    print('
    ' ,end = '') # def hollow_solid(num): for i in range(num): tab = False for j in range(i + 1): # if i != num-1: # , if j == i : tab = True # * if (i == j or j == 0): print('*',end='') else : print(' ',end='') # , else: print('*', end='') if tab: print('
    ', end='') def hollow_solid_new(num): for i in range(num): for j in range(i + 1): # if i != num-1: # * if (i == j or j == 0): print('*',end='') else : print(' ',end='') # , else: print('*', end='') print('
    ') num = int(input(' ?
    ')) triangle_solid1(num) print('
    ') hollow_solid(num) return '
    ' # que4()
  • 判断は1年中何日目
  • def que3():
        # 3.        ,             ?:
        #       
        def judge_leap(num):
            date = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
            # (     and not  ) or     
            if (num % 4 == 0 and num % 100 != 0) or num % 400 ==0:
                date[1] =29
            return date
    
        #     
        date = (input('       ,   :“2018.02.12”:'))
        date_list = (list(map(int, (date.split('.')))))
        #       
        day = date_list[2]
        for i in range(date_list[1]):
            day += judge_leap(date_list[0])[i]
        print('{} {}  {}   {} 
    '.format(date_list[1], date_list[2], date_list[0], day)) # que3()
  • 推数
  • #      
    import random
    
    def judge_num(num, num_random):
        if num > num_random:
            print('It\'s too big')
            return 1
        elif num < num_random:
            print('It\'s too small')
            return 1
        else:
            print("Congratulation!! That\' right!")
            return 0
    
    #      
    num_start = int(input('Digital lower limit of guess number:
    ')) num_end = int(input('Digital upper limit of guess number:
    ')) num_random = random.randint(num_start, num_end) # result = 1 # i = 0 # frequency = 3 # # 、 print('WARNING: You have【{}】 chances you guess '.format(frequency), end = '--&&>>--') print('【{}】 chances left now:
    '.format(frequency - i +1)) while result and i != frequency: # num = int(input('Please guess a int_number:
    ')) result = judge_num(num, num_random) i += 1
  • 進数変換
  • #         
    def other_to_decimal(hex, num):
        #        ,
        num_str = str(num)
        # map() List      (list  )     (set)  
        num_list = list(map(int, num_str))
        #     
        num_list = num_list[::-1]
        print(list(map(int, num_str)))
    
        #       
        digit = len(num_list)
        num_decimal = 0
    
        #   
        for i in range(digit):
            numi = num_list[i]
            # print(numi, hex**i)
            num_decimal += numi*(hex**i)   #            
    
        return num_decimal
    
    #         
    def decimal_to_other(hex, num):
        #       
        digit = len(str(num))
    
        num_hex = []
        quotient = 1
    
        #   ,      num_hex
        while quotient:
            #      
            quotient = num // hex
            remainder = num % hex
            # print(quotient, remainder)
            #       
            num_hex.append(remainder)
            #        
            num = quotient
    
        #     ,     sort()      
        num_hex = num_hex[::-1]
        # num_hex.sort(reverse=True)
    
        #        , ASCII      
        for i in range(len(num_hex)):
            if num_hex[i] > 9:
                num_hex[i] = chr(int(num_hex[i])+87)
        # print(num_hex)
    
        #         
        result = (''.join('%s' %m for m in num_hex))
        return result
    
    
    Type = bool(input("           1,           0
    ")) if Type: hex = int(input(" ?
    ")) num = int(input(" :")) print(" :", decimal_to_other(hex, num)) else: hex = int(input(" ?
    ")) num = int(input(" :")) print(" :", other_to_decimal(hex, num))