1、輸入字符串,判斷是否為回文(例:abcdcba即為回文)
str = raw_input("請輸入一個字符串:")
step = len(str)/2
for i in range(0,step):
if str[i] != str[-(i+1)]:
print "不是回文"
break
else:
print "是回文"
2、有一分?jǐn)?shù)序列:2/1,3/2,5/3,8/5,13/8,21/13...求出這個數(shù)列的前20項之和
fenzi = 2
fenmu = 1
sum = 0
for i in range(1,21):
fenzi,fenmu = fenzi+fenmu,fenzi #分子和分母同時賦值,python語言特性,無需中間變量
sum = sum + float(fenzi)/fenmu
print sum
3、有1、2、3、4個數(shù)字,能組成多少個互不相同且無重復(fù)數(shù)字的三位數(shù)?都是多少?
count = 0
for m in range(1,5):
for n in range(1,5):
for k in range(1,5):
if m!=n and m!=k and n!=k:
print str(m)+str(n)+str(k)
count += 1
print count
4、下劃線風(fēng)格轉(zhuǎn)駝峰風(fēng)格 (下劃線風(fēng)格:abc_def_ghi,駝峰風(fēng)格:AbcDefGhi)
data = raw_input("請輸入字符串:")
data = data.split('_')
word = []
for d in data:
word.append(d.capitalize())
print ''.join(word)
5、寫一個腳本解析url
http://localhost:8080/test/data?abc=def&test=debug
6、列表元素去重
c = [1, 2, 3, 4, 5, 6, 3, 7, 8, 9, 5, 8]
r = []
for d in c:
if d not in r:
r.append(d)
print r
7、用字典表示學(xué)生與數(shù)學(xué),語文,英語成績, 并計算平均分
dict = {
"chinese":90,
"math":78,
"english":88,
}
print sum(dict.values())/len(dict)
8、打開文件,統(tǒng)計英文單詞出現(xiàn)的次數(shù)
file = open("this.txt")
lines = file.readlines()
file.close()
result = {}
for line in lines:
data = line.strip(".\n").split(" ") #.strip()去空格和換行
for d in data:
word = d.lower()
if not word in result:
result.setdefault(word,1)
else:
result[word] += 1
print result["is"] #輸出單詞is的出現(xiàn)次數(shù)
9、實現(xiàn)排序函數(shù)
data = [2, 4, 7, 9, 1, 6, 3, 5, 8]
def sort(data):
for _ in range(len(data)):
for d in range(0,len(data)-1):
if data[d]>data[d+1]:
data[d],data[d+1] = data[d+1],data[d]
return data
print sort(data)
10、利用遞歸方法求n!
def jiec(x):
if x==1:
return 1
return x * jiec(x-1)
print jiec(5)
11、輸入某年某月某日,判斷這一天是這一年的第幾天
year = int(raw_input("請輸入年份:"))
month = int(raw_input("請輸入月份:"))
day = int(raw_input("請輸入幾號:"))
list = [31,28,31,30,31,30,31,31,30,31,30,31]
if (year%400==0) or (year%4==0 and year%100!=0) :
list[1] = 29
print sum(list[0:month-1]) + day
else:
print sum(list[0:month-1]) + day
12、輸出9*9口訣表
from __future__ import print_function #python2中無print函數(shù)無end屬性,需導(dǎo)包
for i in range(1,10):
for j in range(1,i+1):
print ("%d×%d=%d" % (j,i,i*j),end=" ")
print () #換行作用