if --- Sort Three Numbers
来源:互联网 发布:汪涵的胡子 知乎 编辑:程序博客网 时间:2024/06/07 01:14
今天做练习遇到如下题目,只用if 对3个数排序,又把很久没用的排序给忘了,只记得sort了。用if写了下从大到小排列,自测没问题,int条件下。
This is an exercise in constructingif-statements. Using only simple variables and if statements, youshould be able to get this to work; a loop is not needed.
Given 3 numbers (X, Y,Z),assign variablesx,y,z so that andx ,y,and z are fromX,Y, andZ. Use only a series of if-statements and assignment statements.
Hint. You must define the conditions under which you choose between x← X, x ← Y or x ←Z. You will do a similar analysis for assigningvalues toy andz. Note that your analysisfor settingy will depend on the value set forx;similarly, your analysis for settingz will depend onvalues set forx andy.
#!/usr/bin/python# Filename: sort_three.pya = input("a = ")b = input("b = ")c = input("c = ")if a < b : max = b b = a a = max print a,bif b < c : max = c c = b b = max print b,cif a < b : max = b b = a a = max print a,bprint a,b,c
python 还有另一种交换数值的方法 a,b = b,a ,这样就不用再设置中间变量了,如下:
>>> a6>>> b3>>> a,b = b,a>>> a3>>> b6>>>
上面的3行用一行就可以解决。
if 的格式书写如下:
if expression : suite
或者:if expression : suiteelif expression : suite
expression 可以是:条件一 or 条件二:条件一 and 条件二:
if expression : suiteelif expression : suiteelse: suiteif expression : suiteelse: suite以上if也可以缩减为一句话:suite 表达式1 or/and 表达式2 等eg:average = sum/count if count != 0 else Noneaverage = count != 0 and float(sum)/count
- if --- Sort Three Numbers
- Sort Three Distinct Keys
- CareerCup Median of three numbers
- Maximum Product of Three Numbers
- Maximum Product of Three Numbers
- Maximum Product of Three Numbers
- The maximum of three numbers code
- leetcode628. Maximum Product of Three Numbers
- leetcode 628:Maximum Product of Three Numbers
- [leetcode]628. Maximum Product of Three Numbers
- Leetcode 628 Maximum Product of Three Numbers
- leetcode#628. Maximum Product of Three Numbers
- 628. Maximum Product of Three Numbers
- 628. Maximum Product of Three Numbers
- leetcode628: Maximum Product of Three Numbers
- leetcode: 628. Maximum Product of Three Numbers
- leetcode-- Maximmum Product of Three Numbers
- leetcode 628. Maximum Product of Three Numbers
- 优酷视频提取声音 王睿卓 带我到山顶 MP3
- 浅谈Qt中多线程编程
- 开源的C#项目
- Java笔记之:String(一)
- java 断点续传网络下载
- if --- Sort Three Numbers
- Rob Hess关于Sift的说明文档
- linux 文件类型和安装
- 解析 QT 多线程程序
- Web.Config:ConfigurationSection 使用示例
- OpenCV函数cvApproxPoly
- IDA反汇编/反编译静态分析iOS模拟器程序(九)block
- HTML5视频支持检测
- Struts2、Spring、Hibernate 高效开发的最佳实践