RANGE的實現python
def myrange(start,stop,step): ret = list() cur = start ret.append(cur) while cur < stop: cur += step return ret
猜數字app
在程序中定義一個int常量,你有三次機會才數字的大小,若是猜中,輸出congratulations! you win!,若是機會用完,還未猜中,輸出Oops!you fail!ide
可使用input函數獲取輸入函數
可使用int函數把輸入轉化爲整型input
NUM = 35 for _ in range(3): # 「_」表示忽略輸出 cur = int(input("Enter your number:")) if cur == NUM: print("You win!") break elif cur < NUM: print("Less!") else: print("Bigger!") else: print("You failed!")
集合it
給定一個列表,其中有一些元素是重複的,請移除重複的元素,只保留第一個,而且保持列表原來的次序io
例如:class
[1, 3, 2, 4, 2, 5, 5, 7]效率
輸出: [1, 3, 2, 4, 5, 7]import
#第一種 ret = list() for item in L: if item not in ret: #這種效率最低 ret.append(itme) print(ret) #第二種 ret = list() tmp = set() for item in L: if item not in tmp: #這種效率高 ret.append(item) tmp.add(item) print(ret)
求素數
給定一個列表,其中元素爲正整數,計算其中素數個數
例如:[2, 3, 4, 5, 6, 7] 輸出4
import math L = [2,3,5,7,10,12,6,8] count = 0 for item in L: for i in range(2,math.ceil(math.sqrt(item))): if item % i == 0: break else: count += 1 print(count)