学习python之路---python小算法总结(二)
2013-03-18 16:22
381 查看
题目6:输出101-201之间的素数
import math
result = []
for i in range(101,201):
mark = True
for j in range(2,int(math.sqrt(i))+1):
if i % j == 0:
mark = False
break
if mark == True:
result.append(i)
print result
输出结果:[101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163,167, 173, 179, 181, 191, 193, 197, 199]
题目7:辗转相除法---求输入两个正整数m和n的最大公约数
m = int(raw_input('Please input the firstpositive integer: '))
n = int(raw_input('Please input the secondpositive integer: '))
if m < n:
m,n = n,m
while n!=0: # 直到“余数”和“商”的商为0
r= m % n # 得到m和n相除的余数
m= n
n= r
print m
题目8:输入一行字符,分别统计出其中英文字母、空格、数字和其它字符的个数。
s=raw_input('please enter a string:')
letters=0
space=0
digit=0
others=0
for c in s:
ifc.isalpha():
letters+=1
elifc.isdigit():
digit+=1
elifc.isspace():
space+=1
else:
others+=1
print "letters:%d,Digit:%d,Space:%d,Others:%d"%(letters,digit,space,others)
题目9:递归运算
>>> def fact(j):
sum=0
ifj==0:
sum=1
else:
sum=j*fact(j-1)
returnsum
>>> fact(5)
120
题目10:回文数判断
x=int(raw_input("input a number:"))
x=str(x)
for i in range(len(x)/2):
if x[i]!=x[-i-1]:
print 'this numberis not a huiwenshu'
break
print 'this number is a huiwenshu'
import math
result = []
for i in range(101,201):
mark = True
for j in range(2,int(math.sqrt(i))+1):
if i % j == 0:
mark = False
break
if mark == True:
result.append(i)
print result
输出结果:[101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163,167, 173, 179, 181, 191, 193, 197, 199]
题目7:辗转相除法---求输入两个正整数m和n的最大公约数
m = int(raw_input('Please input the firstpositive integer: '))
n = int(raw_input('Please input the secondpositive integer: '))
if m < n:
m,n = n,m
while n!=0: # 直到“余数”和“商”的商为0
r= m % n # 得到m和n相除的余数
m= n
n= r
print m
题目8:输入一行字符,分别统计出其中英文字母、空格、数字和其它字符的个数。
s=raw_input('please enter a string:')
letters=0
space=0
digit=0
others=0
for c in s:
ifc.isalpha():
letters+=1
elifc.isdigit():
digit+=1
elifc.isspace():
space+=1
else:
others+=1
print "letters:%d,Digit:%d,Space:%d,Others:%d"%(letters,digit,space,others)
题目9:递归运算
>>> def fact(j):
sum=0
ifj==0:
sum=1
else:
sum=j*fact(j-1)
returnsum
>>> fact(5)
120
题目10:回文数判断
x=int(raw_input("input a number:"))
x=str(x)
for i in range(len(x)/2):
if x[i]!=x[-i-1]:
print 'this numberis not a huiwenshu'
break
print 'this number is a huiwenshu'
相关文章推荐
- 学习python之路---python小算法总结(一)
- 学习python之路---python小算法总结(三)
- 学习python之路---python小算法总结(四)
- 学习python之路---python小算法总结(六)
- 学习python之路---python小算法总结(七)
- Python 学习 (Leetcode 算法题解【easy部分 技巧总结】)
- Python之路,Day21 - 常用算法学习
- 编程学习总结python之路之字符编码(改进版1)(图)
- VERYIMPORTANT我的python学习之路-13知识总结
- Python算法之快排学习总结
- SVM学习总结(二)SVM算法流程图
- python学习之路一
- Python第二周学习总结
- 王亟亟的Python学习之路(七)-date,continue,迭代对象,生成器
- 开始Python的学习之路
- python学习总结----一些常用函数
- Openev3 python基础学习4——基础滤波算法
- Python学习之路--Flask+MongoDB搭建Restful Server
- python学习问题总结
- Python MySQLdb 学习总结