Python基礎練習之set/dict練習

1.用戶輸入一個數字

  • 打印每一位數字及其重復的次數

(1)字符串練習2用的方法

while True:    
    num = input().strip().lstrip('0')
    if num.isdigit():
        break

count = [0] * 10
for j in num:
    x = int(j)
    if count[x] == 0:  
        count[x] = num.count(j)
        print('num is {}, count is {}'.format(j,count[x]))

(2)用dict做的,不建議用count

while True:    
    num = input().strip().lstrip('0')
    if num.isdigit():
        break

d = {}
count = 0
for i in num:
    if i not in d:
        #d.setdefault(i,num.count(i))
        d[i] = num.count(i)
        count += 1
print(count)

for k,v in d.items():
    print('num is {}, count is {}'.format(k,v))

(3)

while True:
    num = input('Please input a positive integer >>').strip().lstrip('0')
    if num.isdigit:
        break
    else:
        print('wrong number')

d = {}
for i in num:
    if i not in d:
        d[i] = 1
    else:
        d[i] += 1
print(d)

d = {}
for i in num:
    if not d.get(i):
        d[i] = 0
    d[i] += 1
print(d)
# if not d.get(i)等價于 if not None, 也就是說當d.get(i) = None(get取不到,默認None) 時進入,等于0 的時候也就是i不在d里

d = {}
for i in num:
    d[i] = d.get(i,0) + 1
print(d)
# (i,0) i沒有就取0,或者的關系

2.數字重復統計

  • 隨機產生100個整數
  • 數字范圍[-1000,1000]
  • 升序輸出所有不同的數字及其重復的次數
    import random
    
    nums = []
    for _ in range(100):
        nums.append(random.randint(-1000,1000))
    
    # 把數字弄進字典里,用 d[i] = nums.count(i)來計算重復
    # key為數字(d[i]),value為數字的重復次數(nums.count(i))
    d = {}
    for i in nums:
        if i not in d:
            d[i] = nums.count(i)
    #print(d)
    
    # 創建數字的排序列表
    sort = []
    for k in d.keys():
        sort.append(k)
    
    # 二元選擇排序來進行排序
    for  j in range(len(sort)//2):
        minindex = j
        maxindex = -j-1
        for u in range(j+1,len(sort)-j):
            if sort[u] < sort[minindex]:
                minindex = u
            if sort[-u-1] > sort[maxindex]:
                maxindex = -u-1
    
        if j != minindex:
            sort[j], sort[minindex] = sort[minindex], sort[j]
            if j == len(sort) + maxindex:
                maxindex = minindex
        if -j-1 != maxindex:
            sort[-j-1], sort[maxindex] = sort[maxindex], sort[-j-1]
    
    # 打印結果
    for q in range(len(sort)):
        if d.get(sort[q]) > 1:
            print('num is {}, count is {}'.format(sort[q],d.get(sort[q])))
    

  • sort法
    import random
    
    # 用隨機數創建數字列表
    # 把數字弄進字典,計算重復
    nums = []
    for _ in range(100):
        nums.append(random.randint(-1000,1000))
    d = {}
    for i in nums:
        if i not in d:
            d[i] = nums.count(i)
    #print(d)
    
    # 創建去重的數字列表,并排序
    num = []
    for k in d.keys():
        num.append(k)
        num.sort()
    
    # 打印結果    
    for j in num:
        if d.get(j) > 1:
            print('number is {}, count is {}'.format(j,d.get(j)))
    

  • 最終版
    from collections import OrderedDict
    import random
    
    # 創建數字列表,并排序
    nums = []
    for _ in range(100):
        nums.append(random.randint(-1000,1000))
    nums.sort()
    #print(nums)
    
    # 創建OrderedDict,并計算重復(因為前面已經排序了,用這個字典,會按照我們輸入的順序排列元素)
    od = OrderedDict()
    for i in nums:
        if i not in od:
            od[i] = 0
        od[i] += 1
    
    # 打印結果
    for k,v in od.items():
        if v > 1:
            print('number is {}, count is {}'.format(k,v))
    

59cd967b1eab013230000002


  • 3.字符串統計

    • 字符表’abcdefghijklmnopqrstuvwxyz’
    • 隨機挑選2個字母組成字符串,共挑選100個
    • 降序排出這100個字符串及重復的次數
      # 創建字母表
      #alphabet = 'abcdefghijklmnopqrstuvwxyz'
      alphabet = []
      for i in range(97,123):
          alphabet.append(chr(i))
      #print(alphabet)
      
      import random
      
      # 創建字母列表,并把符合條件的字符串添加到該列表
      alpha = []
      for p in range(100):
          a = []
          for q  in range(2):
              a.append(random.choice(alphabet))
          s = a[0] + a[1]
          alpha.append(s)
      #print(alpha)
      
      # 把字符串導入到字典,并計算重復
      d = {}
      for j in alpha:
          d[j] = alpha.count(j)
      #print(d)
      
      # 創建排序列表,并把去重的字符串添加到該列表
      sort = []
      for t in d.keys():
          sort.append(t)
      #print(sort)
      
      # 二元選擇排序
      for m in range(len(sort) // 2):
          maxindex = m
          minindex = -m-1
          for n in range(m+1, len(sort) - m):
              if sort[n] > sort[maxindex]:
                  maxindex = n
              if sort[-n-1] < sort[minindex]:
                  minindex = -n-1
      
          if m != maxindex:
              sort[m], sort[maxindex] = sort[maxindex], sort[m]
              if m == minindex + len(sort):
                  minindex = maxindex
          if -m-1 != minindex:
              sort[-m-1], sort[minindex] = sort[minindex], sort[-m-1]
      #print(sort)
      
      # 打印結果
      for r in sort:
          if d.get(r) > 1:
              print('string is {}, count is {}'.format(r,d.get(r)))
      

  • OrderedDict版
    # 創建字母表
    #alphabet = 'abcdefghijklmnopqrstuvwxyz'
    alphabet = []
    for i in range(97,123):
        alphabet.append(chr(i))
    #print(alphabet)
    
    import random
    from collections import OrderedDict
    
    # 創建字母列表,并把符合條件的字符串添加進去
    # 進行排序,然后反轉(因為降序,所以反轉)
    alpha = []
    for _ in range(100):
        #alpha.append(random.choice(alphabet)+random.choice(alphabet))
        #alpha.append(''.join(random.sample(alphabet,2)))  #隨機采樣
        alpha.append(''.join(random.choice(alphabet) for _ in range(2)))   #生成器
    
    alpha.sort()
    alpha.reverse()
    #print(alpha)
    
    # 創建OrderedDict,把字符串倒進去,并計算重復
    od = OrderedDict()
    for j in alpha:
        if j not in od:
            od[j] = 1
        od[j] += 1
    
    # 打印結果
    for k,v in od.items():
        if v > 1:
        print('alpha is {}, count is {}'.format(k,v))
    

  • sorted版

本文來自投稿,不代表Linux運維部落立場,如若轉載,請注明出處:http://www.www58058.com/87674

(1)
nolannolan
上一篇 2017-10-09
下一篇 2017-10-09

相關推薦

  • 滑動窗口

    數據載入 def load(path:str): with open(path) as f: for line in f: tmp = extract(line) if tmp: yield tmp else: # TODO 解析失敗就拋棄,或者打印日志 continue 時間窗口分析 概念 很多數據,例如日志,都和時間相關的,都是按照時間順序產生的。 產生…

    2017-11-04
  • DevOps 風向標!DevOps國際峰會6月29日正式啟航!

    DOIS 大會為您呈現互聯網公司與海外企業的實踐經驗與工具技術,聚焦 DevOps 在金融、電信、零售等行業的系統性實踐。在這里我們不空談、不務虛,實實在在的專注DevOps落地。

    2018-05-16
  • 異常、模塊、分發、插件化開發、插槽和反向等

    異常、模塊、分發、插件化開發、插槽和反向等

    Python筆記 2018-05-22
  • 遞歸函數

    遞歸函數 def foo(b,b1=3):print(“foo1 called “,b,b1)def foo2(c):foo3(c)print(“foo2 called”,c)def foo3(d):print(“foo3 called”)def mian():print(“…

    2018-04-16
  • Python數據結構

    數據結構個人總結,方便以后查找。

    Python筆記 2018-04-01
  • python函數與作用域

    ##函數– 函數— 數學定義:y=f(x),y是x的函數,x是自變量— python函數:由若干語句組成的語句塊、函數名稱、參數列表構成,它是組織代碼的最小單元;完成一定的功能 – 函數的作用— 結構化編程對代碼的最基本的封裝,一般按照功能組織一段代碼— 封裝的目的是為了復用,減少冗余代…

    2017-10-17
欧美性久久久久