001_exercises

yum install python-setuptools
sudo easy_install pip

作业1---猜数字

在程序中定义一个int常量,你有三次机会才数字的大小,如果猜中,输出congratulations! you win!,如果机会用完,还未猜中,输出Oops!you fail!
可以使用input函数获取输入
可以使用int函数把输入转化为整型

NUMBER = 12

for _ in range(3):
    cur = int(input("enter a number"))
    if cur == NUMBER:
        print("you win!")
        break
    elif cur < NUMBER:
        print("less")
    else:
        print("bigger")
else:
    print("you failed!")

作业2---集合

给定一个列表,其中有一些元素是重复的,请移除重复的元素,只保留第一个,并且保持列表原来的次序
例如:
[1, 3, 2, 4, 2, 5, 5, 7]
输出: 1, 3, 2, 4, 5, 7

L = [1, 3, 2, 4, 3, 2, 5, 7, 7, 2]
ret = list()
tmp = set()
for item in L:
    if item not in tmp:
        ret.append(item)
        tmp.add(item)
print(ret)

作业3---求素数:

给定一个列表,其中元素为正整数,计算其中素数个数
例如:[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)
#coding:utf8
import sys
def sieve(n):
    #compute primes using sieve eratosthenes
    x = [1] * n
    x[1] = 0
    for i in range(2,n/2):
        j = 2 * i
        while j < n:
            x[j] = 0
            j = j + i
    return x
def prime(n,x):
    #Find nth prime
    i = 1
    j = 1
    while j <= n:
        if x[i] == 1:
            j = j + 1
        i = i + 1
    return i-1
x = sieve(10000)
code = [1206,301,384,5]
key = [1,1,2,2]
sys.stdout.write("".join(chr(i) for i in [73,83,66,78,32,61,22]))
for i in range(0,4):
    sys.stdout.write(str(prime(code[i],x)-key[i]))

你可能感兴趣的:(001_exercises)