Coursera: Python Data-Structures University of Michigan -all assignments solutions
assignment 2.2
name = input("Enter your name") print("Hello " + name)
assignment 2.3
hrs = input("Enter Hours:") rate = input("Enter rate:") pay = float(hrs) * float(rate) print(pay)
assignment 3.1
hrs = input("Enter Hours:") h = float(hrs) rate = input("Enter rate: ") r = float(rate) if h <= 40: pay = h * r else: pay = r * 40 + (r * 1.5) * (h - 40) print(pay)
assignment 5.2
largest = None smallest = None while True: num = input("Enter a number: ") if num == "done" : break n = int(num) elif largest < n : largest = n elif smallest == None or smallest > n : smallest = n else: print("Invalid input") print("Maximum is",largest) print ("Minimum is",smallest)
assignment 6.5
text = "X-DSPAM-Confidence: 0.8475"; pos=text.find(':') value=text[pos+1:] print(float(value))
assignment 7.1
# Use words.txt as the file name fname = input("Enter file name: ") fh = open(fname) for line in fh.readlines(): print(line.upper().strip())
assignment 7.2
# Use the file name mbox-short.txt as the file name total=0 count=0 fname = input("Enter file name: ") fh = open(fname) for line in fh: if not line.startswith("X-DSPAM-Confidence:") : continue count=count+1 pos=line.find(':') value=line[pos+1:] total=total+float(value) avg=total/count print("Average spam confidence:",avg) #Output: #Average spam confidence: 0.750718518519
assignment 8.4
#file used is romeo.txt
fname = input("Enter file name: ")
fh = open(fname)
lst = list()
for line in fh:
for i in line.split():
if not i in lst:
lst.append(i)
lst.sort()
print(lst)
#Output
#['Arise', 'But', 'It', 'Juliet', 'Who', 'already', 'and', 'breaks', 'east', 'envious', 'fair', 'grief', 'is', 'kill', 'light', 'moon', 'pale', 'sick', 'soft', 'sun', 'the', 'through', 'what', 'window', 'with', 'yonder']
assignment 8.5
fname = input("Enter file name: ") if len(fname) < 1 : fname = "mbox-short.txt" fhand = open(fname) count = 0 for line in fhand: line.rstrip() if line.startswith("From "): words = line.split() print(words[1]) count += 1 print("There were",count, "lines in the file with From as the first word")
assignment 9.4
name = input("Enter file:") if len(name) < 1 : name = "mbox-short.txt" handle = open(name) count = dict() for line in handle: if not line.startswith("From "):continue line = line.split() line = line[1] count[line] = count.get(line, 0) +1 bigcount = None bigword = None for k,v in count.items(): if bigcount == None or v > bigcount: bigword = k bigcount = v print(bigword, bigcount)
assignment 10.2
name = input("Enter file:") if len(name) < 1 : name = "mbox-short.txt" handle = open(name) lst=list() di=dict() for line in handle: if line.startswith("From "): pos=line.find(":") lst.append(line[pos-2:pos]) for word in lst: di[word]=di.get(word,0)+1 newlst=list() for key,val in di.items(): newtup=(key,val) newlst.append(newtup) newlst=sorted(newlst) for key,val in newlst: print(key,val)
No comments