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.178linux.com/87674

(1)
nolannolan
上一篇 2017-10-09 08:53
下一篇 2017-10-09 10:16

相关推荐

  • 内置数据结构

    list,tuple,str,bytes,bytearray,set,切片,分装解构,冒泡法

    2018-03-31
  • 函数

    函数、参数、参数解构
    返回值、作用域
    递归函数
    匿名函数、
    生成器

    2018-04-16
  • 类的继承

    Edit 类的继承 基本概念 面向对象三要素之一,继承Inheritance 举例: 人类和猫类都继承自动物类 个体继承自父母,继承了父母的一部分特征,但也可以有自己的个性 在面向对象的世界中,以父类继承,就可以直接拥有父类的属性和方法,这样可以减少代码、多复用。子类可以定义自己的属性和方法 class Animal: def shout(self): pr…

    2017-11-15
  • python summary(for previous 6 weeks)

    Meghan(haven’t been fullly organized)

    2018-04-19
  • python基础总结

    编程基础 一组能让计算机识别和执行的指令   电子计算机 能够执行程序的机器   现代计算机 英国数学家、逻辑学家,艾伦.麦席森.图灵被称为计算机科学之父,人工智能之父。图灵提出的著名的图灵模型为现代计算机的逻辑工作方式奠定了基础   图灵机,又称图灵计算机、图灵计算机,由图灵提出的一种抽象计算机模型,即将人们使用纸笔进行数学运…

    2017-09-17
  • 元组与字符串

    元组tuple 一个有序的元素组成的集合,不可变,用()表示,可进行索引,正索引:从左至右,从0开始;负索引:从右至左,从-1开始,正负索引不可超界,否则引发indexerror,tuple[index],index就是索引,使用中括号访问 元组是只读的,所以没有增,改,删的方法 冒泡法:属于交换排序,两两比较大小,交换位置,结果分为升序和降序排列 升序:n…

    Python笔记 2018-04-01