pythontip 挑战python (6-10)

挑战python,6-10题,入门题的解答过程,有更好的方法请留言

题目(id:6):求解100以内的所有素数

输出100以内的所有素数,素数之间以一个空格区分

思路:筛选法求素数。另外,每行结果最后必须输出一个换行,所以最后又加了一个print

Python代码:

num = [0]*101
num[0] = num[1] = 1
for i in range(100):
    if num[i] == 0:
        j = i + i
        while(j <100):
            num [j] = 1
            j += i
for i in range(100):
    if num[i] == 0:
        print i,
print

题目(id:7):求矩形面积

已知矩形长a,宽b,输出其面积和周长,面积和周长以一个空格隔开

Python代码:

print a*b, 2*(a+b)

题目(id:8):求中位数

给你一个list L, 如 L=[0,1,2,3,4], 输出L的中位数(若结果为小数,则保留一位小数)。

思路:

这个题感觉给的输出要求不够充分。。。不过貌似测试用例比较简单

Python代码:

n = len(L) 
L.sort() 
if n&1: 
    print L[n/2] 
else: 
    if (L[n/2-1]+L[n/2])&1: 
        print round((L[n/2-1]+L[n/2])/2.0,1) 
    else: 
        print (L[n/2-1]+L[n/2])/2

题目(id:9):最大公约数

给你两个正整数a和b, 输出它们的最大公约数。

Python代码:

if a < b:
    a,b = b,a
while b:
    a,b=b,a%b
print a

题目(id:9):最小公倍数

给你两个正整数a和b, 输出它们的最小公倍数。

Python代码:

def gcd(a,b):
    if a < b:
        a,b = b,a
    while b:
        a,b=b,a%b
    return a
print a*b/gcd(a,b)
posted @ 2013-12-13 16:44  自加吧,少年  阅读(741)  评论(0编辑  收藏  举报