001 exercises

  • RANGE的實現

def myrange(start,stop,step):
    ret = list()
    cur = start
    ret.append(cur)
    while cur < stop:
        cur += step
    return ret
  • 猜數字

在程序中定義一個int常量,你有三次機會才數字的大小,如果猜中,輸出congratulations! you win!,如果機會用完,還未猜中,輸出Oops!you fail!

可以使用input函數獲取輸入

可以使用int函數把輸入轉化爲整型

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!")
  • 集合

給定一個列表,其中有一些元素是重複的,請移除重複的元素,只保留第一個,並且保持列表原來的次序

例如:

[1, 3, 2, 4, 2, 5, 5, 7]

輸出: [1, 3, 2, 4, 5, 7]

#第一種
 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)


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章