Python入门 第一周和第二周的练习

练习

回答下列粗体文字所描述的问题,如果需要,使用任何合适的方法,以掌握技能,完成自己想要的程序为目标,不用太在意实现的过程。

7 的四次方是多少?


In [1]:
pow(7, 4)


Out[1]:
2401

分割以下字符串

s = "Hi there Sam!"

到一个列表中


In [3]:
s = "Hi there Sam!"
s.split(' ')


Out[3]:
['Hi', 'there', 'Sam!']

In [3]:



Out[3]:
['Hi', 'there', 'dad!']

提供了一下两个变量

planet = "Earth"
diameter = 12742

使用format()函数输出一下字符串

The diameter of Earth is 12742 kilometers.

In [4]:
planet = "Earth"
diameter = 12742
"The diameter of {0} is {1} kilometers.".format(planet, diameter)


Out[4]:
'The diameter of Earth is 12742 kilometers.'

In [6]:



The diameter of Earth is 12742 kilometers.

提供了以下嵌套列表,使用索引的方法获取单词‘hello'


In [6]:
lst = [1,2,[3,4],[5,[100,200,['hello']],23,11],1,7]

In [9]:
lst[3][1][2][0]


Out[9]:
'hello'

提供以下嵌套字典,从中抓去单词 “hello”


In [10]:
d = {'k1':[1,2,3,{'tricky':['oh','man','inception',{'target':[1,2,3,'hello']}]}]}

In [13]:
d['k1'][3]['tricky'][3]['target'][3]


Out[13]:
'hello'

字典和列表之间的差别是什么??


In [23]:
# Just answer with text, no code necessary

编写一个函数,该函数能够获取类似于以下email地址的域名部分

user@domain.com

因此,对于这个示例,传入 "user@domain.com" 将返回: domain.com


In [14]:
'user@domain.com'.split('@')[-1]


Out[14]:
'domain.com'

In [15]:
def domain(email):
    return email.split('@')[-1]

创建一个函数,如果输入的字符串中包含‘dog’,(请忽略corn case)统计一下'dog'的个数


In [20]:
ss = 'This dog runs faster than the other dog dude!'

def countdog(s):
    return s.lower().split(' ').count('dog')

countdog(ss)


Out[20]:
2

In [21]:
def countDog(st):
    count = 0
    for word in st.lower().split():
        if word == 'dog':
            count += 1
    return count

创建一个函数,判断'dog' 是否包含在输入的字符串中(请同样忽略corn case)


In [18]:
s = 'I have a dog'

In [19]:
def judge_dog_in_str(s):
    return 'dog' in s.lower().split(' ')

judge_dog_in_str(s)


Out[19]:
True

如果你驾驶的过快,交警就会拦下你。编写一个函数来返回以下三种可能的情况之一:"No ticket", "Small ticket", 或者 "Big Ticket". 如果速度小于等于60, 结果为"No Ticket". 如果速度在61和80之间, 结果为"Small Ticket". 如果速度大于81,结果为"Big Ticket". 除非这是你的生日(传入一个boolean值),如果是生日当天,就允许超速5公里/小时。(同样,请忽略corn case)。


In [22]:
def caught_speeding(speed, is_birthday):
    
    if is_birthday:
        speeding = speed - 5
    else:
        speeding = speed
    
    if speeding > 80:
        return 'Big Ticket'
    elif speeding > 60:
        return 'Small Ticket'
    else:
        return 'No Ticket'

In [23]:
caught_speeding(81,True)


Out[23]:
'Small Ticket'

In [24]:
caught_speeding(81,False)


Out[24]:
'Big Ticket'

计算斐波那契数列,使用生成器实现


In [1]:
def fib_dyn(n):
    a,b = 1,1
    for i in range(n-1):
        a,b = b,a+b
    return a

In [3]:
fib_dyn(10)


Out[3]:
55

In [25]:
def fib_recur(n):
    if n == 0:
        return 0
    if n == 1:
        return 1
    else:
        return fib_recur(n-1) + fib_recur(n-2)
fib_recur(10)


Out[25]:
55

In [39]:
def fib(max): 
    n, a, b = 0, 0, 1 
    while n < max: 
        yield b 
        # print(b)
        a, b = b, a + b 
        n = n + 1 
print(list(fib(10))[-1])


55

Great job!