【python学习】简单的几个算法

一、闰年算法

闰年条件:满足年份模400为零,或者模4为0但模100不为0。

再通俗一点:能被4和400整除,不能被100整除。

import math
year=int(raw_input("Enter the year:"))
if(year%400==0):
    print("It's a leap year!")
elif(year%4==0 and not year%100==0):
    print("It's a leap year!")
else:
    print("It's not a leap year!")

二、python的一些运算符。

http://www.tsnc.edu.cn/tsnc_wgrj/doc/python/basic.htm#id2861602

尤其注意的是,当使用math函数的时候,必须的语法是先载入import math;使用的时候math.cos(xxx);

三、找出0~100所有素数

最基本的方法:

result1 = []
for num in range(2, N):
     f = True
     for snu in range(2, int(sqrt(num))+1):
         if num % snu == 0:
            f = False
            break
     if f:
         result1.append(num)
print result1

这种方法效率很低。更好的方法参见参考资料2——筛选法.

四、参考资料

1.http://www.phpweblog.net/sane/archive/2008/05/23/3739.html

2.http://blog.csdn.net/gavinming/article/details/7212980

3.http://wiki.woodpecker.org.cn/moin/ObpLovelyPython/LpyAttAnswerCdays

4.http://hi.baidu.com/ostech/blog/item/4ceef58242ec1cdb9023d917.html

原文地址:https://www.cnblogs.com/xweiwei/p/2498738.html