码迷,mamicode.com
首页 > 其他好文 > 详细

第一天的作业题

时间:2016-02-27 20:41:15      阅读:330      评论:0      收藏:0      [点我收藏+]

标签:

   第一题 猜数字,超过3次退出。提示相应的结果:

   主要考察里面for 里面可以使用else的, _在这是不需要返回数值

技术分享
 1 NUMBER = 35
 2 
 3 for _ in range(3):
 4         cur = int (input(enter your number:))
 5         if cur == NUMBER:
 6                 print ("Your WIN!")
 7                 break
 8         elif cur < NUMBER:
 9                 print ("LESS")
10         else:
11                 print ("Bigger")
12 else:
13         print ("Your guess more than 3 time!")
14 ~                                              
View Code

 



第二题:找到列表里面的集合(不知道啥题目)

技术分享
1 (test_3.4.2) [root@Minion1 ~]# vim li1.py 
2 L = [1,3,2,4,3,3,2,5,7,7,2]
3 # [1,3,2,4,5,7]
4 
5 ret = list()
6 for item in L:
7         if item not in ret:
8                 ret.append(item)
9 print (ret)
View Code

 

10 (test_3.4.2) [root@Minion1 ~]# python li1.py 
11 [1, 3, 2, 4, 5, 7]

 

变化2:

技术分享
 1 (test_3.4.2) [root@Minion1 ~]# vim li2.py 
 2 L = [1,3,2,4,3,3,2,5,7,7,2]
 3 # [1,3,2,4,5,7]
 4 
 5 ret = list()
 6 tmp = set ()
 7 for item in L:
 8         if item not in ret:
 9                 ret.append(item)
10                 tmp.add(item)
11 print (ret)
12 
13 (test_3.4.2) [root@Minion1 ~]# python li2.py  
14 [1, 3, 2, 4, 5, 7]
View Code

 这个地方,例子1的执行效率没有例子2的高, 空间换时间,o(n) o(1),如果列表的数值太多,占用内存太多。

第三题:统计列表里面的素数的个数

 质数(prime number)又称素数,有无限个。除了1和它本身以外不再有其他的因数。根据算术基本定理,每一个比1大的整数,要么本身是一个质数,要么可以写成一系列质数的乘积,最小的质数是2。

(test_3.4.2) [root@Minion1 ~]# vim ma0.py    
L = [2,3,5,7,10,12,6,8]

count = 0

for item in L:
        for i in range(2,item):
                if item % i == 0:
                        break
        else:
                count += 1

print (count)
~                                                                                                                                                                      
(test_3.4.2) [root@Minion1 ~]# python ma0.py 
4

  

 变化:数字处理模块知识(math),

 1 (test_3.4.2) [root@Minion1 ~]# vim ma1.py    
 2 import math
 3 
 4 L = [2,3,5,7,10,12,6,8]
 5 
 6 count = 0
 7 
 8 for item in L:
 9         for i in range(2,math.ceil(math.sqrt(item))):
10                 if item % i == 0:
11                         break
12         else:
13                 count += 1
14 
15 print (count)
16 
17 ~                                                                                                                                                                      
18 (test_3.4.2) [root@Minion1 ~]# python ma1.py 
19 4



ceil(...)
ceil(x)

Return the ceiling of x as an int.
This is the smallest integral value >= x.


sqrt(...)
sqrt(x)

Return the square root of x.

 

 

 

 

第一天的作业题

标签:

原文地址:http://www.cnblogs.com/tom-li/p/5223477.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!