zoukankan      html  css  js  c++  java
  • Python元组与字符串操作(8)——三数排序多种实现

    练习

    依次接收用户输入的3个数,排序后打印

    1.转换int后,判断大小排序,使用分支结构完成

    num1 = []
    for i in range(3):
        num1.append(int(input('>>')))
    
    num1b = None
    if num1[0] > num1[1]:
        if num1[1] > num1[2]:
            num1b = [0,1,2]
        elif num1[0] > num1[2]:
            num1b = [0,2,1]
        else:
            num1b = [2,0,1]
    else:
        if num1[0] > num1[2]:
            num1b = [1,0,2]
        elif num1[2] > num1[1]:
            num1b = [2,1,0]
        else:
            num1b = [1,2,0]
    
    for i in num1b:
        print(num1[i])
    nums = []
    for i in range(3):
        nums.append(int(input('>>')))
    #num1 = []
    #while len(num1) < 3:
    #    num1.append(int(input('>>')))
    
    order = None
    if nums[0] > nums[1]:
        if nums[1] > nums[2]:
            order = [2,1,0]
        else:
            if nums[0] > nums[2]:
                order = [1,2,0]
            else:
                order = [1,0,2]
    else:
        if nums[2] > nums[1]:
            order = [0,1,2]
        else:
            if nums[0] > nums[2]:
                order = [2,0,1]
            else:
                order = [0,2,1]
    
    for i in order:
        print(nums[i])

    2.使用max函数

    num2 = []
    while len(num2) < 3:
        num2.append(int(input('>>')))
    
    num2b = []
    while len(num2) > 0:
        if len(num2) == 1:
            num2b.insert(0,num2[0])
            num2.clear()
        else:
            num2b.insert(0,max(num2))
            num2.remove(max(num2))
    
    print(num2b)
    nums = []
    while len(nums) < 3:
        nums.append(int(input('>>')))
    
    newlist = [None] * len(nums)
    #for i in range(len(nums)):
    index = -1
    while nums:
        m = max(nums)
        newlist[index] = m
        nums.remove(m)
        if len(nums) == 1:
            newlist[0] = nums[-1]
            break
        index -= 1
    
    print(newlist)

    3.使用列表的sort方法

    num3 = []
    while len(num3) < 3:
        num3.append(int(input('>>')))
    
    num3.sort()
    
    print(num3)
  • 相关阅读:
    防止人为误操作MySQL数据库技巧一例
    keepalived(nginx的高可用)安装文档
    Nginx安装手册
    每天学点Shiro-多realm
    每天学点Shiro-盐值加密
    每天学点Shiro-登录功能demo
    每天学点Shiro-集成spring
    每天学点Shiro-say hello
    每天学点SpringMVC-异常处理
    每天学点SpringMVC-拦截器
  • 原文地址:https://www.cnblogs.com/omgasw/p/11642804.html
Copyright © 2011-2022 走看看