#!usr/bin/env Python3.9# -*- coding:utf-8 -*-"""
The Fibonacci Sequence is computed based on the following formula:f(n)=0 if n=0 f(n)=1 if n=1 f(n)=f(n-1)+f(n-2) if n>1Please write a program to compute the value of f(n) with a given n input by console.Example: If the following n is given as input to the program:7Then, the output of the program should be:13
"""'''
Hints:
In case of input data being supplied to the question, it should be assumed to be a console input.
We can define recursive function in Python.
'''deffib(n):if n ==0:# 如果n=0,f(n)=0return0elif n ==1:# 如果n=1,f(n)=1return1else:return fib(n-1)+ fib(n-2)# 調用自身,進行遞歸,n>2,f(n)=f(n-1)+f(n-2)n =int(input('Please input the number:'))print(fib(n))#!usr/bin/env Python3.9# -*- coding:utf-8 -*-"""
The Fibonacci Sequence is computed based on the following formula:f(n)=0 if n=0 f(n)=1 if n=1 f(n)=f(n-1)+f(n-2) if n>1Please write a program using list comprehension to print the Fibonacci Sequence
in comma separated form with a given n input by console.Example: If the following n is given as input to the program:
7
Then, the output of the program should be:
0,1,1,2,3,5,8,13
"""'''
Hints:
We can define recursive function in Python.
Use list comprehension to generate a list from an existing list.
Use string.join() to join a list of strings.In case of input data being supplied to the question, it should be assumed to be a console input.
'''deffib(n):if n ==0:# 如果n=0,f(n)=0return0elif n ==1:# 如果n=1,f(n)=1return1else:return fib(n-1)+ fib(n-2)# 調用自身,進行遞歸,n>2,f(n)=f(n-1)+f(n-2)n =int(input('Please input the number:'))
l1 =[str(fib(x))for x inrange(0, n+1)]# 列表推導式,在range()范圍內逐個遞歸后存入列表l1中print(','.join(l1))# 在一行里打印出來,之間以逗號相隔#!usr/bin/env Python3.9# -*- coding:utf-8 -*-"""
Please write a program using generator to print the even numbers between 0 and n in comma separated form
while n is input by console.Example: If the following n is given as input to the program:
10
Then, the output of the program should be:
0,2,4,6,8,10
"""'''
Hints: Use yield to produce the next value in generator.
In case of input data being supplied to the question, it should be assumed to be a console input.
'''defeven_filter(t):i =0while i <= t:if i %2==0:yield i # 函數返回某個值時,會停留在某個位置,返回函數值后,會在前面停留的位置繼續執行i +=1t =int(input('Please input the number:'))
l1 =[]# 創建一個空列表for x in even_filter(t):# for循環迭代偶數l1.append(str(x))# 存入空列表中,列表里的元素需是str格式print(','.join(l1))# 示例程序解釋yield函數"""def foo():print("starting...")while True:res = yield 4print("res:", res)g = foo()
print(next(g))
print("*" * 20)
print(next(g))"""# 程序運行結果"""starting...4********************res: None4
""""""
直接解釋代碼運行順序,相當于代碼單步調試:1.程序開始執行以后,因為foo函數中有yield關鍵字,所以foo函數并不會真的執行,而是先得到一個生成器g(相當于一個對象)2.直到調用next方法,foo函數正式開始執行,先執行foo函數中的print方法,然后進入while循環3.程序遇到yield關鍵字,然后把yield想想成return,return了一個4之后,程序停止,并沒有執行賦值給res操作,此時next(g)語句執行完成,
所以輸出的前兩行(第一個是while上面的print的結果,第二個是return出的結果)是執行print(next(g))的結果,4.程序執行print("*"*20),輸出20個*5.又開始執行下面的print(next(g)),這個時候和上面那個差不多,不過不同的是,這個時候是從剛才那個next程序停止的地方開始執行的,
也就是要執行res的賦值操作,這時候要注意,這個時候賦值操作的右邊是沒有值的(因為剛才那個是return出去了,并沒有給賦值操作的左邊傳參數),
所以這個時候res賦值是None,所以接著下面的輸出就是res:None,6.程序會繼續在while里執行,又一次碰到yield,這個時候同樣return 出4,然后程序停止,print函數輸出的4就是這次return出的4.
"""#!usr/bin/env Python3.9# -*- coding:utf-8 -*-"""
Please write a program using generator to print the numbers
which can be divisible by 5 and 7 between 0 and n in comma separated form while n is input by console.Example: If the following n is given as input to the program:
100
Then, the output of the program should be:
0,35,70
"""'''Hints: Use yield to produce the next value in generator.'''defnum_filter(t):i =0# for i in range(0, t+1) # 循環語句可以不一樣while i <= t:if i %5==0and i %7==0:yield i # 函數返回某個值時,會停留在某個位置,返回函數值后,會在前面停留的位置繼續執行i +=1t =int(input('Please input the number:'))
l1 =[]# 創建一個空列表for x in num_filter(t):# for循環迭代偶數l1.append(str(x))# 存入空列表中,列表里的元素需是str格式print(','.join(l1))#!usr/bin/env Python3.9# -*- coding:utf-8 -*-"""
Please write assert statements to verify that every number in the list [2,4,6,8] is even.
"""'''
Hints: Use "assert expression" to make assertion.
'''even_nums =[2,4,6,8]for i in even_nums:assert i %2==0# 斷言函數是對表達式布爾值的判斷,要求表達式計算值必須為真。可用于自動調試。## 如果表達式為假,觸發異常;如果表達式為真,不執行任何操作。#!usr/bin/env Python3.9# -*- coding:utf-8 -*-"""
Please write a program which accepts basic mathematics expression from console and print the evaluation result.Example: If the following string is given as input to the program:35+3Then, the output of the program should be:38
"""'''
Hints: Use eval() to evaluate an expression.
'''simple_exp =input("Please input a simple expression:")print(eval(simple_exp))# eval()函數可進行簡單的計算#!usr/bin/env Python3.9# -*- coding:utf-8 -*-"""
Please write a binary search function which searches an item in a sorted list.
The function should return the index of element to be searched in the list.
請編寫一個二分搜索函數來搜索排序列表中的項目。該函數應返回要在列表中搜索的元素的索引。
"""'''Hints: Use if/elif to deal with conditions.'''import mathdefbinary_search(li, element):bottom =0top =len(li)-1index =-1# 如果未搜索到返回默認值-1while top >= bottom and index ==-1:# while循環直到搜索到給定值,跳出循環條件是top<bottom(說明已經將列表遍歷一遍)或者列表里沒有給定值mid =int(math.floor((top + bottom)/2.0))# 二分搜索法if li[mid]== element:index = elementelif li[mid]> element:# 如果mid值大于給定值,top = mid - 1,縮小搜索范圍top = mid -1else:# 如果mid值小于給定值,bottom = mid + 1, 縮小搜索范圍bottom = mid +1return indexli =[2,5,7,9,10,11,13,23,45,167]print(binary_search(li,13))print(binary_search(li,34))#!usr/bin/env Python3.9# -*- coding:utf-8 -*-"""
Please generate a random float where the value is between 10 and 100 using Python math module.
"""import random'''Hints: Use random.random() to generate a random float in [0,1].'''import randomprint(random.random()*100)# random方法用于產生0到1之間的隨機浮點數print(random.randint(10,100))# randint方法產生指定區間的隨機數# choice方法獲取序列中的一個隨機數# shuffle方法將序列打亂#!usr/bin/env Python3.9# -*- coding:utf-8 -*-"""Please generate a random float where the value is between 5 and 95 using Python math module."""'''Hints: Use random.random() to generate a random float in [0,1].'''import randomprint(random.random()*100-5)#!usr/bin/env Python3.9# -*- coding:utf-8 -*-"""Please write a program to output a random even number between 0 and 10 inclusive using random module
and list comprehension."""import random'''Hints: Use random.choice() to a random element from a list.'''l1 =[]# 創建一個空列表for i inrange(11):# 將范圍內的偶數存入列表l1if i %2==0:l1.append(i)print(random.choice(l1))# choice方法獲取序列中的一個隨機數# 源代碼,列表推導式更加簡潔"""
import random
print(random.choice([i for i in range(11) if i%2==0]))
"""