设为首页 收藏本站
查看: 1768|回复: 0

[经验分享] 密歇根大学

[复制链接]

尚未签到

发表于 2015-11-30 14:54:36 | 显示全部楼层 |阅读模式
  人人都懂的编程课(Python)

Week03 Exercise
  Rewrite your pay program using try and except so
that your program handles non-numeric input gracefully.

Enter Hours: 20
Enter Rate: nine
Error, please enter numeric input


try:
inp = raw_input('Enter Hours: ')
hours = float(inp)
inp = raw_input('Enter Rate: ')
rate = float(inp)
except:
print "Error,please enter numeric input"
quit()
if hours <= 40:
pay = rate * hours
else:
pay = rate * 40 + ( hours - 40 ) * 1.5 * rate
print pay

Week03 Assignment
  Write a program to prompt for a score between 0.0 and 1.0.
If the score is out of range, print an error.
If the score is between 0.0 and 1.0, print a grade using the following table:
Score Grade

>= 0.9 A
>= 0.8 B
>= 0.7 C
>= 0.6 D
< 0.6 F

If the user enters a value out of range, print a suitable error message and exit. For the test, enter a score of 0.85.


try:
inp = raw_input('Please enter a score: ')
score = float(inp)
except:
print "Error, please enter a floated score"
quit()
if score > 0.9:
print 'A'
elif score > 0.8:
print 'B'
elif score > 0.7:
print 'C'
elif score > 0.6:
print 'D'
else:
print 'F'

Week04 Assignment
  Rewrite your pay computation with time-and-a-half
for overtime and create a function called computepay
which takes two parameters ( hours and rate).
Enter Hours: 45
Enter Rate: 10
Pay: 475.0


def computepay(h,r):
print "in computepay",h,r
if h <= 40:
p = r * h
else:
p = r * 40 + ( r * 1.5 * (h-40) )
print "Finished with computepay",p
return p
try:
inp = raw_input("Enter Hours: ")
hours = float(inp)
inp = raw_input("Enter Rate: ")
rate = float(inp)
except:
print "Error, please enter numeric input."
quit()
print "In the main code",rate,hours
pay = computepay(hours,rate)
print "We are back",pay

Week05 Assignment
  Write a program that repeatedly prompts a user for integer numbers until the user enters 'done'.
Once 'done' is entered, print out the largest and smallest of the numbers. If the user
enters anything other than a valid number catch it with a try/except and put out an
appropriate message and ignore the number. Enter the numbers from the book for problem 5.1
and Match the desired output as shown.


largest = None
smallest = None
num_list = []
while True:
num = raw_input("Enter a number: ")
if num == "done" : break
try:
num_list.append(int(num))
except:
print "Invalid input"
#find largest and smallest
for i in num_list:
if largest == None:
largest = i
else:
if largest < i:
largest = i
if smallest == None:
smallest = i
else:
if smallest > i:
smallest = i
print "Maximum is", largest
print "Minimum is", smallest

Week06 Assignment
  Parse the string: 'X-DSPAM-Confidence: 0.8475'

x = 'X-DSPAM-Confidence: 0.8475'
pos = x.find(':')
num = float(x[pos+1:].lstrip())
print num,type(num)

Week07 Assignment
  Write a program to read through a file and print contents of the file all in upper case. The file: http://www.py4inf.com/code/mbox-shrot.txt

fname = raw_input('Enter a file name:')
fhand = open(fname);
for line in fhand:
line = line.rstrip()
line = line.upper()
print line

Week07 Assignment2
  Write a program that prompts for a file name, then opens that file and reads through the file, looking for lines of the form:

X-DSPAM-Confidence:    0.8475
  Count these lines and extract the floating point values from each of the lines and compute the average of those values and produce an output as shown below. You can download the sample data at http://www.pythonlearn.com/code/mbox-short.txt when you are testing below enter mbox-short.txt as the file name.

# Use the file name mbox-short.txt as the file name
#fname = raw_input("Enter file name: ")
fh = open("d:/mbox-short.txt")
cnt = 0
sum = 0
for line in fh:
if not line.startswith("X-DSPAM-Confidence:") : continue
cnt = cnt + 1
sum = sum + float(line.split(':')[1].lstrip())
print "Average spam confidence:", sum / cnt

Week08 Assignment
  open the file romeo.txt and read it line by line.
For each line, split the line into a list of words using the split() function.
The program should build a list of words. For each word on each line check to see if the word is already in the list and if not append it to the list. When the program completes, sort and print the resulting words in alphabetical order.
You can download the sample data at http://www.pythonlearn.com/code/romeo.txt


fname = '/home/loongson/py4/romeo.txt'
fh = open(fname)
lst = list()
for line in fh:
line = line.rstrip()
words = line.split()
for word in words:
if word not in lst:
lst.append(word)
lst.sort()
print lst

Week08 Assignment02
  Open the file mbox-short.txt and read it line by line. When you find a line that starts with 'From ' like the following line:

From stephen.marquard@uct.ac.za Sat Jan  5 09:14:16 2008
  You will parse the From line using split() and print out the second word in the line (i.e. the entire address of the person who sent the message). Then print out a count at the end. Hint: make sure not to include the lines that start with 'From:'.
You can download the sample data at http://www.pythonlearn.com/code/mbox-short.txt


fname = '/home/loongson/py4/mbox-short.txt';
fh = open(fname)
count = 0
for line in fh:
line = line.strip()
words = line.split()
if len(words):
if words[0] == 'From:':
count = count + 1
print words[1]
print "There were",count,"lines in the file with From as the first word"

Week10 Assignment01
  统计一片文章出现频率最高的10个词

fhand = open('d:/romeo-full.txt');
counts = dict()
for line in fhand:
words = line.split()
for word in words:
counts[word] = counts.get(word,0) + 1
flipped = list()
for key,val in counts.items():
newtup = (val,key)
flipped.append(newtup)
flipped.sort(reverse=True)
for val,key in flipped[:10]:
print key,val

运维网声明 1、欢迎大家加入本站运维交流群:群②:261659950 群⑤:202807635 群⑦870801961 群⑧679858003
2、本站所有主题由该帖子作者发表,该帖子作者与运维网享有帖子相关版权
3、所有作品的著作权均归原作者享有,请您和我们一样尊重他人的著作权等合法权益。如果您对作品感到满意,请购买正版
4、禁止制作、复制、发布和传播具有反动、淫秽、色情、暴力、凶杀等内容的信息,一经发现立即删除。若您因此触犯法律,一切后果自负,我们对此不承担任何责任
5、所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其内容的准确性、可靠性、正当性、安全性、合法性等负责,亦不承担任何法律责任
6、所有作品仅供您个人学习、研究或欣赏,不得用于商业或者其他用途,否则,一切后果均由您自己承担,我们对此不承担任何法律责任
7、如涉及侵犯版权等问题,请您及时通知我们,我们将立即采取措施予以解决
8、联系人Email:admin@iyunv.com 网址:www.yunweiku.com

所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其承担任何法律责任,如涉及侵犯版权等问题,请您及时通知我们,我们将立即处理,联系人Email:kefu@iyunv.com,QQ:1061981298 本贴地址:https://www.yunweiku.com/thread-145484-1-1.html 上篇帖子: Python操作Word批量生成文章 下篇帖子: Python多进程(1)——subprocess与Popen()
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

扫码加入运维网微信交流群X

扫码加入运维网微信交流群

扫描二维码加入运维网微信交流群,最新一手资源尽在官方微信交流群!快快加入我们吧...

扫描微信二维码查看详情

客服E-mail:kefu@iyunv.com 客服QQ:1061981298


QQ群⑦:运维网交流群⑦ QQ群⑧:运维网交流群⑧ k8s群:运维网kubernetes交流群


提醒:禁止发布任何违反国家法律、法规的言论与图片等内容;本站内容均来自个人观点与网络等信息,非本站认同之观点.


本站大部分资源是网友从网上搜集分享而来,其版权均归原作者及其网站所有,我们尊重他人的合法权益,如有内容侵犯您的合法权益,请及时与我们联系进行核实删除!



合作伙伴: 青云cloud

快速回复 返回顶部 返回列表