Python_16_Udacity_Evans_Intro to CS_1_How to get started

<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]

太美的解法。
不過針對非大牛的人,實際編程中也不需要太注重美學,還是綜合效率第一。

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容

  • 我們認識快十年了,而關于我們一波三折的事情卻讓我現在都記憶猶新。 2007年我們認識的第一年,四川一個小縣城鎮上的...
    莫莫莫呀閱讀 1,126評論 2 4
  • 今天把合并搞完的話 就是好漢
    橘貓飯閱讀 319評論 0 0
  • 或許只能讓你像這樣,說出的每一個字都像匕首一樣,把你從我心里挖出來,就算再疼,我也要把你忘掉
    萍寶蘇蘇閱讀 267評論 0 0
  • 轉載:http://testerhome.com/topics/555 配好下面的環境之后,就可以利用程序做一些事...
    fka2004閱讀 1,461評論 0 0
  • 跑不完的漫長夜色中,對抗黑暗,忘我奔向光明的時間里, 直到汗流浹背,才是快意人生.
    愛妃給朕笑一個閱讀 125評論 0 0