Python课程第二章控制流习题详解
1.使用尽可能多的方法实现list去重
方法一:
>>> a=[1,2,34,5,6,7,7,8,8,9]
>>> set(a)
set([1, 2, 5, 6, 7, 8, 9, 34])
方法二:
>>> a=[2,2,3,3,4,4]
>>> b=[2,4]
>>> for i in a:
... if i not in b:
... b.append(i)
...
>>> b
[2, 4, 3]
>>>
方法三:
>>> d={}
>>> a=[1,2,1,1,2,2,3,3,4,4]
>>> for i in a:
... d[i]=None
...
>>> print d
{1: None, 2: None, 3: None, 4: None}
>>> for i in a:
... d[i]=None
...
>>> print d.keys()
[1, 2, 3, 4]
方法四:
a={}
b=[1,2,3,2,1,2,3,5,6]
print list(a.fromkeys(b))
>>>
>>> a=[1,1,2,2,2,2,3,3]
>>> for i in a:
... for j in range(a.count(i)-1):
... a.remove(i)
...
>>> print a
[1, 2, 3]
方法五:
>>> a=[1,1,2,2,2,2,3,3]
>>> for i in a:
... for j in range(a.count(i)-1):
... a.remove(i)
...
>>>
>>> print a
[1, 2, 3]
方法六:
list_a=[1,1,1,3,5,6,8]
func=lambda x,y:x if y in x else x + [y]
print reduce(func,[[],]+list_a)
2.成绩等级判断
利用条件运算符的嵌套来完成此题:学习成绩>=90分的同学用A表示,
60-89分之间的用B表示,60分以下的用C表示
3.实现数学中多项式求和公式的打印
比如:a6x^6 + a5x^5 + a4x^4 + a3x^3 + a2x^2 + a1x^1 + a0
>>> result=[]
>>> for i in range(6,-1,-1):
... if i==0:
... result.append("a0")
... break
... result.append("a%sx^%s" %(i,i))
...
>>> print "+".join(result)
a6x^6+a5x^5+a4x^4+a3x^3+a2x^2+a1x^1+a0
4.统计名字列表中,各名字的首字母在名字列表中出现的次数
>>> s=['dick','david','foster']
>>> for i in s:
... i.count(i[0
...
1
2
1
>>> name_list=['foster','janet','jesus','david']
>>> count_dict={}
>>> for i in name_list:
... count_dict[i]="".join(name_list).count(i[0])
...
>>> print count_dict
{'david': 2, 'foster': 1, 'janet': 2, 'jesus': 2}
5.输入三个数,判断是否能构成三角形
能构成三角形三边关系:
三边都大于零
两边之和大于第三边,两边之差小于第三边
>>> import math
>>> a,b,c=input("please input three number a,b,c:")
please input three number a,b,c:4,5,7
>>> d=min(a,b,c)
>>> e=max(a,b,c)
>>> if d<=0:
... print "error"
... elif (a+b+c)>2*e:
... print u"能组成三角形"
... else:
... print u"不能组成三角形"
...
能组成三角形
>>> import math
>>> a,b,c=input("please input three number a,b,c:")
>>> for line in a,b,c:
... if line<=0:
... print "error"
...
>>> if (a+b-c)*(a+c-b)*(b+c-a)>0:
... print u"能构成三角形"
... else:
... print u"不能构成三角形"
...
能构成三角形
>>>
>>> def sj(a,b,c):
... m=max(a,b,c)
... if (a+b+c)>2*m:
... return u"能构成三角形"
... else:
... return u"不能构成三角形"
...
>>> print sj(3,4,5)
能构成三角形
>>> print sj(8,5,7)
能构成三角形
>>> def sj(a,b,c):
... m=max(a,b,c)
... if (a+b+c)>2*m:
... return u"能构成三角形"
... else:
... return u"不能构成三角形"
...
>>> print sj(3,4,5)
能构成三角形
>>> print sj(8,5,7)
能构成三角形
>>> def Judge(a,b,c):
... if a+b>c and b+c>a and a+c>b:
... print("是三角形")
... else:
... print("不是三角形")
... return;
...
>>> a,b,c=[float(items) for items in raw_input("please input three number").spli
t(',')]chen
please input three number3,4,5
>>> Judege(a,b,c)
>>> def isTriangle(a,b,c):
... if a+b>c and a+c>b and b+c>a:
... return 1
... else:
... return 0
...
>>> if(isTriangle(3,4,5)==1):
... print ("是三角形")
... else:
... print ("不是三角形")
...
是三角形
>>>
>> def is_triangle(a,b,
.. if a+b>c and a+c
.. print (
.. else:
.. print("
..
>> import random
>>
>> for i in range(10):
.. a=random.randin
.. b=random.randin
.. c=random.randin
.. print a,b,c
.. is_triangel(a,b
..
1 2
raceback (most recent c
File "<stdin>", line 6
ameError: name 'is_tria
>> import random
>> for i in range(10):
.. a=random.randin
.. b=random.randin
.. c=random.randin
.. print a,b,c
.. is_triangle(a,b
..
0 4
不是三角形
8 5
不是三角形
0 2 5
不是三角形
0 -2
不是三角形
1 3 6
不是三角形
4 7
不是三角形
2 0 9
不是三角形
0 1 5
不是三角形
10 5
三角形
1 10
不是三角形
>>
6.实现字典的fromkeys方法
例如:
seq = ('name', 'age', 'sex')
dict = dict.fromkeys(seq, 10)
print "New Dictionary : %s" % str(dict)
结果:New Dictionary : {'age': 10, 'name': 10, 'sex': 10}
>>> dict=dict.fromkeys(seq)
>>> print "New dictionary :%s" %str(dict)
New dictionary :{'age': None, 'name': None, 'sex': None}
>>> dict=dict.fromkeys(seq,10)
>>> print "New dictionary :%s" %str(dict)
New dictionary :{'age': 10, 'name': 10, 'sex': 10}
7.键盘读入一字符串,逆序输出
>> strA='ascvfdghjk'
>> strA[::-1]
kjhgdfvcsa'
>>> a=raw_input("please input some characters and reversed output:")
please input some characters and reversed output:afepeeripw123475850kljhuk
>>> order=[]
>>> for i in a:
... order.append(i)
...
>>> order.reverse()
>>> print ''.join(order)
kuhjlk058574321wpireepefa
>>> print ','.join(order)
k,u,h,j,l,k,0,5,8,5,7,4,3,2,1,w,p,i,r,e,e,p,e,f,a
8.读入一个整数n,输出n的阶乘
第一种方法:
>>> def fac(n):
... if n==1:
... return 1
... return n*fac(n-1)
...
>>> print fac(10)
3628800
第二种方法:
>>> def fac(n):
... result=n;
... for i in range(1,n):
... result*=i
... return result
...
>>> print fac(10)
3628800
第三种方法:
>>> reduce(lambda x,y:x*y,range(1,6))
120
9.打印1/2, 1/3, 1/4,….1/10
>>> print ["%s" %i for i in range(2,11)]
['2', '3', '4', '5', '6', '7', '8', '9', '10']
>>> print ["1/%s" %i for i in range(2,11)]
['1/2', '1/3', '1/4', '1/5', '1/6', '1/7', '1/8', '1/9', '
>>> "".join( ["1/%s" %i for i in range(2,11)])
'1/21/31/41/51/61/71/81/91/10'
>>> "".join( ["1/%s," %i for i in range(2,11)])
>>> "".join( ["1/%s," %i for i in range(2,11)])
'1/2,1/3,1/4,1/5,1/6,1/7,1/8,1/9,1/10,'
>>> from fractions import Fraction
>>> for i in range(2,11):
... x=Fraction(1,i)
... print x
...
1/2
1/3
1/4
1/5
1/6
1/7
1/8
1/9
1/10
>>>
11.输入数字a,n,如a,4,则打印a+aa+aaa+aaaa之和
>>> n=int(raw_input("please input a number:"))
please input a number:12
>>> "+".join(["%s" %'a'*i for i in range(1,n)])
'a+aa+aaa+aaaa+aaaaa+aaaaaa+aaaaaaa+aaaaaaaa+aaaaaaaaa+aaaaaaaaaa+aaaaaaaaaaa'
>>> a=int(raw_input('a='))
a=2
>>> sn=[]
>>> tn=0
>>> for i in range(1,11):
... tn=tn+a
... a=a*10
... sn.append(tn)
... print tn
...
2
22
222
2222
22222
222222
2222222
22222222
222222222
2222222222
>>> sn=reduce(lambda x,y:x+y,sn)
>>> print sn
2469135800
>>>
>>> def sum(a,n):
... sn=[]
... tn=0
... for i in range(1,n+1):
... tn+=a
... a=a*10
... sn.append(tn)
... return sn
...
>>> print sum(2,10)
[2, 22, 222, 2222, 22222, 222222, 2222222, 22222222, 222222222, 2222222222L]
>>> s=reduce(lambda x,y:x+y,sum(2,10))
>>> print s
2469135800
12.求100个随机数之和,随机数要求为0—9的整数
>>> sum=0
>>> sum+=random.randint(0,100)
>>> print sum
50
13.要求在屏幕上分别显求1到100之间奇数之和与偶数之和
>>> sumeven=0
>>> sumodd=0
>>> for i in range(0,101)[::2]:
... sumodd+=i
...
>>> for i in range(0,101)[::2]:
... sumodd+=i
...
>>> print sumodd
2550
>>> for i in range(1,100)[::2]:
... sumeven+=i
...
>>> print sumeven
2500
>>> print sumodd+sumeven
5050
14.输入10个数,并显示最大的数与最小的数
>>> s=[10,23,56,78,45,678,654,34,54,12]
>>> min(s)
10
>>> max(s)
678
15.给一个不多于5位的正整数,要求:一、它是几位数,二、逆序打印出
各位数字。
>>> a=raw_input("please input number(less than 5 digit:")
please input number(less than 5 digit:89075
>>> b=[]
>>> if len(n)<=5:
... for i in range(len(n)):
... b.append(a[i])
...
>>> print b
['8', '9', '0', '7', '5']
>>> b.reverse()
>>> print b
['5', '7', '0', '9', '8']
>>> "".join(b)
'57098'
>>>
16.求1000以内的所有水仙花数
水仙花是指:abc = a**3 +b**3 +c**3,如:153 = 1**3 +5**3 +3**3
方法一:
>>> for i in range(100,999):
... a=i/100
... b=(i%100)//10
... c=i%10
... if i==a**3+b**3+c**3:
... print(i)
...
153
370
371
407
>>>
方法二:
>>> for i in range(1,10):
... for j in range(1,10):
... for k in range(1,10):
... if i*100+j*10+k==i*i*i+j*j*j+k*k*k:
... print (i*100+j*10+k)
...
153
371
方法三:
>>> for i in range(100,1000):
... sum=0
... temp=i
... while temp:
... sum=sum+(temp%10)**3
... temp//=10
... if sum==i:
... print(i)
...
153
370
371
407
方法四:
>>> for i in range(100,999):
... x=int(str(i)[0])
... y=int(str(i)[1])
... z=int(str(i)[2])
... if i==(x**3+y**3+z**3):
... print (i)
...
153
370
371
407
>>>
>>> def tt(temp):
... global sum
... if temp:
... sum=sum+(temp%10)**3
... return tt(temp//10)
... else:
... return sum
...
>>> for i in range(100,1000):
... sum=0
... temp=i
... if tt(temp)==i:
... print(i)
...
153
370
371
407
def Narcissus():
1. for each in range(100,1000):
2. temp = each
3. sum = 0
4. while temp:
5. sum = sum +(temp%10) **3
6. temp =temp // 10
7.
8. if sum == each:
9. print(each,end='\t')
10.print('所有的水仙花数分别是:',end='')
11.Narcissus()
17.编程求s=1!+2!+3!+…..+n!
>>> def facsum(n):
... b=[]
... for i in range(1,n+1):
... t=reduce(lambda x,y:x*y,range(1,i+1))
... b.append(t)
... return b
...
>>> print facsum(10)
[1, 2, 6, 24, 120, 720, 5040, 40320, 362880, 3628800]
>>> print reduce(lambda x,y:x+y,facsum(10))
4037913
18.钞票换硬币
把一元钞票换成一分、二分、五分硬币(每种至少一枚),有多种换法,分
别有哪些?
19.自己实现在一句话中查找某个单词的算法,存在返回索引号,否则返回
False
20.读入一个十进制整数,实现十进制转二进制算法将其转成二进制数
要求:不能使用现成进制转换函数,自己写代码实现
浙公网安备 33010602011771号