Python_16_Udacity_Evans_Intro to CS_1_How to get started

<a href="http://www.jianshu.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,125评论 2 4
  • 今天把合并搞完的话 就是好汉
    橘猫饭阅读 319评论 0 0
  • 或许只能让你像这样,说出的每一个字都像匕首一样,把你从我心里挖出来,就算再疼,我也要把你忘掉
    萍宝苏苏阅读 267评论 0 0
  • 转载:http://testerhome.com/topics/555 配好下面的环境之后,就可以利用程序做一些事...
    fka2004阅读 1,460评论 0 0
  • 跑不完的漫长夜色中,对抗黑暗,忘我奔向光明的时间里, 直到汗流浃背,才是快意人生.
    爱妃给朕笑一个阅读 125评论 0 0