TickingClock的个人博客分享 http://blog.sciencenet.cn/u/TickingClock

博文

Rosalind 4 - Conditions and Loops

已有 3100 次阅读 2017-10-20 08:47 |个人分类:Python Learning|系统分类:科研笔记

Python Village - INI4: Conditions and Loops


  • Python中的条件语句if:

>>> a = 42

>>> if a < 10:
...       print 'the number is less than 10'
...      else:
...       print 'the number is greater or equal to 10'
...
the number is greater or equal to 10

>>>


如果a小于10,输出'the number is less than 10';否则,输出'the number is greater or equal to 10’。


注意,if这一行最后需要有冒号,下一行print要空一格;然后else后要有冒号,下一行print前要空一格。


  • Python中的循环语句while:

>>> greetings = 1
>>> while greetings <= 3:
...        print 'Hello! ' * greetings
...        greetings = greetings + 1
...
Hello!
Hello! Hello!
Hello! Hello! Hello!

>>>


初始值greetings为1,判断当greetings小于等于3时,执行print 'Hello! ' * greetings和greetings = greetings + 1,然后再判断greetings是否小于等于3决定是否再一次执行print 'Hello! ' * greetings和greetings = greetings + 1。一直到greetings等于4的时候就会终止循环,最终的输出结果就有了。


注意,不能创造一个无限循环,比如:


>>> greetings = 1
>>> while greetings <= 3:
...        print 'Hello! ' * greetings
...        greetings = greetings + 0 # Bug here
...
Hello!
Hello!
Hello!
.
.
.

因为greetings = greetings + 0导致greetings始终为1,循环终止不了,就会一直输出Hello!


  • Python中的遍历语句for:

>>> names = ['Alice', 'Bob', 'Charley']
>>> for name in names:
...        print 'Hello, ' + name
...
Hello, Alice
Hello, Bob
Hello, Charley

>>>


这个其实就是对某个list中所有的item都操作一遍。


  • Python中的range()函数:

>>> range(10)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

>>>


>>> range(2, 8)
[2, 3, 4, 5, 6, 7]

>>>


>>> range(2, 8, 1)
[2, 3, 4, 5, 6, 7]

>>>


>>> range(2, 8, 2)
[2, 4, 6]

>>>


Problem


Given: Two positive integers a and b (a<b<10000).


Return: The sum of all odd integers from a through b, inclusively.


Sample Dataset


100 200


Sample Output


7500


Solution


这个就是要计算从a到b之间所有奇整数的和(包括b)


>>> a = 100
>>> b = 200
>>> sum = 0
>>> for n in range(a|1, (b+1)|1, 2):
...        sum = sum + n
...
>>> print sum
7500

>>>


其中a|1代表当a为偶数时,返回a+1;当a为奇数时,返回a。range(a|1, (b+1)|1, 2)就是从a到b内的所有奇数,如果b是奇数也包括在内,比如:


>>> a = 1
>>> b = 5
>>> range(a|1, (b+1)|1, 2)
[1, 3, 5]

>>>


>>> a = 2
>>> b = 6
>>> range(a|1, (b+1)|1, 2)
[3, 5]

>>>


Over


Rosalind is a platform for learning bioinformatics and programming through problem solving. Take a tour to get the hang of how Rosalind works.


P.S. 欢迎关注微信公众号:微信号Plant_Frontiers




https://blog.sciencenet.cn/blog-3158122-1081666.html

上一篇:Nature Communications:稗草基因组分析揭示其广泛适应性机制
下一篇:Plant Cell:拮抗转录因子复合物调控水稻成花转变
收藏 IP: 221.181.145.*| 热度|

0

该博文允许注册用户评论 请点击登录 评论 (0 个评论)

数据加载中...
扫一扫,分享此博文

Archiver|手机版|科学网 ( 京ICP备07017567号-12 )

GMT+8, 2024-4-26 02:57

Powered by ScienceNet.cn

Copyright © 2007- 中国科学报社

返回顶部