前不久在知乎上看到CS61A 和CS61B spring18 開課的消息。上去看了一眼,發現真的不錯,所有proj hw都可以本地測試!也就是說除了沒有課程成績和官方討論區和TA解答外,這個課完全可以上!(還需要翻牆看油管)簡直棒啊。於是打算寒假刷一波61A 61B 在此也立下flag
61A hw01
Q1: A Plus Abs B
Fill in the blanks in the following function definition for adding a
to the absolute value of b
, without calling abs
.
from operator import add, sub def a_plus_abs_b(a, b): """Return a+abs(b), but without calling abs. >>> a_plus_abs_b(2, 3) 5 >>> a_plus_abs_b(2, -3) 5 """ if b < 0: f = _____ else: f = _____ return f(a, b)
Use Ok to test your code:
python3 ok -q a_plus_abs_b
第一題就出問題簡直好氣。實際上python很靈活,我學了C以為賦值只能是值賦值,要么就函數指針,結果這個居然可以f = add 和 f = sub!驚呆了
Q4: If Function vs Statement
def if_function(condition, true_result, false_result): """Return true_result if condition is a true value, and false_result otherwise. >>> if_function(True, 2, 3) 2 >>> if_function(False, 2, 3) 3 >>> if_function(3==2, 3+2, 3-2) 1 >>> if_function(3>2, 3+2, 3-2) 5 """ if condition: return true_result else: return false_result
def with_if_statement(): """ >>> with_if_statement() 1 """ if c(): return t() else: return f() def with_if_function(): return if_function(c(), t(), f()) def c(): "*** YOUR CODE HERE ***" def t(): "*** YOUR CODE HERE ***" def f(): "*** YOUR CODE HERE ***"
在上面填寫代碼,讓with_if_statement return 1但是with_if_function return 不是1;
這里主要考察兩個知識點:1.if-else語句有一句后面不會執行 2.函數調用值傳遞必須在外面算完值才會傳遞進去
有了這兩條,大家也知道該怎么做了吧