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)
  • 相关阅读:
    药方
    Git配置
    黄俊俊:做一个有想法的技术人
    刘铁猛:程序员:造阀门前,先蓄满‘情商池’
    Nginx + Tomcat 配置负载均衡集群简单实例
    mysql 用户权限管理详细
    mysql数据权限操作
    搭建分布式系统
    数据库 -- 悲观锁与乐观锁
    tomcat7以下线程控制
  • 原文地址:https://www.cnblogs.com/omgasw/p/11642804.html
Copyright © 2011-2022 走看看