<a href="http://www.lxweimin.com/p/54870e9541fc">總目錄</a>
課程頁面:https://www.udacity.com/course/intro-to-computer-science--cs101
授課教師:Dave Evans https://www.cs.virginia.edu/~evans/
如下內容包含課程筆記和自己的擴展折騰
課堂筆記
String index out of range?
s='cs'
- 如果
print s[3]
會出現error string index out of range - 但是如果是
print s[3:]
就不會,只會出來empty string - a tricky one: 如果s = "", 那么
print s[0]
結果是error!
Find strings in strings
- 格式1:
<search string>.find(target string)
- if target string is not found: returns
-1
- 例子
s = "Von Neumann was born Neumann János Lajos \
(in Hungarian the family name comes first), \
Hebrew name Yonah, in Budapest, Kingdom of Hungary, \
which was then part of the Austro-Hungarian Empire, \
to wealthy Jewish parents of the Haskalah."
#source: https://en.wikipedia.org/wiki/John_von_Neumann
s.find("in")
Input:
print s.find("Von")
print s[0:]
print s.find("in")
print s.find("of")
print s[126:]
Output:
0
Von Neumann was born Neumann János Lajos (in Hungarian the family name comes first), Hebrew name Yonah, in Budapest, Kingdom of Hungary, which was then part of the Austro-Hungarian Empire, to wealthy Jewish parents of the Haskalah.
43
126
of Hungary, which was then part of the Austro-Hungarian Empire, to wealthy Jewish parents of the Haskalah.
- 格式2:
<search string>.find(target string, number)
- 這個number就是相當于從
<search string>[number:]
的地方開始找 - 但是需要注意,輸出的結果還是count from the starting point of the original search string
Rounding numbers
這個練習真的很有意思
# Given a variable, x, that stores the
# value of any decimal number, write Python
# code that prints out the nearest whole
# number to x.
# If x is exactly half way between two
# whole numbers, round up, so
# 3.5 rounds to 4 and 2.5 rounds to 3.
# You may assume x is not negative.
# Hint: The str function can convert any number into a string.
# eg str(89) converts the number 89 to the string '89'
# Along with the str function, this problem can be solved
# using just the information introduced in unit 1.
# x = 3.14159
# >>> 3 (not 3.0)
# x = 27.63
# >>> 28 (not 28.0)
# x = 3.5
# >>> 4 (not 4.0)
下面是我的解答,太太太太太不美了:
x = 3.14159
#ENTER CODE BELOW HERE
xs = str(x)
point = xs.find(".")
integer_x = xs[:point]
if int(xs[point+1]) >= 5:
print int(integer_x)+1
else:
print int(integer_x)
正確的思路,不用round
, int
, if
, else
極簡的解法,借助數學:
x = 3.14159
x = str(x + 0.5)
point = x.find(".")
print x[:point]
太美的解法。
不過針對非大牛的人,實際編程中也不需要太注重美學,還是綜合效率第一。