Transcript MTsolution

Python for Bioinformatics
Midterm Solution
DO NOT PANIC
CONDENSED ELEMENTARY MATERIAL TO BE
COVERED IN CLASS AND AS OUTSIDE WORK
REPLACEMENT EXAM (FOR bio STUDENTS) BUT
NOT DURING REGULAR CLASS TIME
Problem 1
Write a Python program that prompts for and inputs two floating point values,
then prints their sum and their average value.
Always returns a string
x = float(input("Enter first floating point number: "))
y = float(input("Enter second floating point number: "))
sum = x + y
avg = sum/2
print("sum =",sum,", average =",avg)
Problem 2
Write a Python program that
(a) prompts for and inputs as a single line the users first and last names (in that
order) separated by a space
(b) prints a line containing the user's last name, a comma, a space and the
user's first name.
Example (user input underlined):
Enter your name (first, space, last):
Alexander, Jaydee
Jaydee Alexander
name = input("Enter your name (first, space, last):
first,last = name.split()
print(last,', ',first,sep='')
L = name.split()
L.reverse()
print(', '.join(L))
")
Problem 3
Write a Python program that inputs a sentence and then prints the words of the
sentence in reverse order. Words are separated by whitespace.
Example (user input underlined):
Enter a sentence: you can cage a swallow can't you
you can't swallow a cage can you
#
#
#
#
#
input the sentence
split the sentence into a list of words
reverse the list of words
join the words back together separated by spaces
print the modified sentence
Problem 3
Write a Python program that inputs a sentence and then prints the words of the
sentence in reverse order. Words are separated by whitespace.
Example (user input underlined):
Enter a sentence: you can cage a swallow can't you
you can't swallow a cage can you
sentence = input('Enter a sentence: ')
words = sentence.split()
words.reverse()
s = ' '.join(words)
print(s)
Problem 4
Write a Python function with one parameter, representing a test score, then returns
the corresponding letter grade using the standard scale: greater than equal to 90 -> A,
80 to 89 -> B, 70 to 79 -> C, 60 to 69 -> D, less than 60 -> F. Your code must use the elif
construct.
def grade(score):
if score >= 90:
return 'A'
elif score >= 80:
return 'B'
elif score >= 70:
return 'C'
elif score >= 60:
return 'D'
else:
return 'F'
Problem 5
Write a python program that creates a dictionary whose keys are names (strings)
and whose value for a key is a favorite food of the person with that name as
follows:
•
•
creates an empty dictionary;
prompts for a name, prompts for a favorite food and then creates a corresponding entry
in the dictionary.
The program should keep inputting names and favorite foods until the user enters
an empty string for the name.
After creating the dictionary, the program prints one line per dictionary entry
consisting of the name, the word "likes", and the value of the dictionary for that
name.
Example (user input underlined):
Enter a sequence of names followed by a favorite food,
terminating input by hitting enter for the name.
Name: John
Food: chocolate
Name: Karen
Food: dates
Name:
John likes chocolate
Karen likes dates
Problem 5
Write a python program that creates a dictionary whose keys are names (strings) and
whose value for a key is a favorite food of the person with that name as follows:
• creates an empty dictionary;
• prompts for a name, prompts for a favorite food and then creates a corresponding
entry in the dictionary.
The program should keep inputting names and favorite foods until the user enters an
empty string for the name.
After creating the dictionary, the program prints one line per dictionary entry consisting
of the name, the word "likes", and the value of the dictionary for that name.
# Create an empty dictionary
# Input a name
# while the name is not the empty string:
#
Input a food
#
Create a dictionary entry with key name and value food
#
Input a name
# for key in D:
#
print key, "likes", dictionary value for key
Problem 5
Write a python program that creates a dictionary whose keys are names (strings) and
whose value for a key is a favorite food of the person with that name as follows:
• creates an empty dictionary;
• prompts for a name, prompts for a favorite food and then creates a corresponding
entry in the dictionary.
The program should keep inputting names and favorite foods until the user enters an
empty string for the name.
After creating the dictionary, the program prints one line per dictionary entry consisting
of the name, the word "likes", and the value of the dictionary for that name.
# Create an empty dictionary
D = {}
name = input("Name: ")
while(name != ''):
# Guard against no names being entered
food = input("Food: ")
D[name] = food
# Dictionary entries created directly
name = input("Name: ")
for name in D:
print(name,"likes",D[name])
Problem 6
Write a Python function half_backwards(L) with parameter a list L that returns the
list consisting of the second half of L followed by the first half.
Hint: a//b is the integer quotient obtained by dividing a by b.
Examples :
L = [1,2,3,4]
K = half_backwards(L)
# Now K == [3,4,1,2]
L = [1,2,3,4,5]
K = half_backwards(L)
# Now K == [3,4,5,1,2]
def half_backwards(L):
# L = [1,2,3,4,5]
m = len(L)//2 + 1
# m = 5//2 + 1 = 2 + 1 = 3
first = L[:m]
# first = L[:3] = [1,2]
second = L[m:]
# second = L[3:] = [3,4,5]
return second+first
# second+first = [3,4,5,1,2]
Problem 7
Write a Python function that returns the number of lines of text in a file.
def line_count(path):
f = open(path,'r') #
L = f.readlines() #
#
f.close()
#
return len(L)
open the file for reading
input the file's lines into a list
close the file
return the length of the list
Problem 8
Write a Python program that inputs an integer n and prints the sum of the fourth
powers of the integers from 1 to n.
n = int(input("Enter an integer: "))
sum = 0
for i in range(1,n+1):
sum += i**4
print("The sum of the first",n,
"positive integers is",sum)
Problem 9
Write a Python program that replaces every four-letter word in a text file with '****'.
Assume words are separated by whitespace.
# get the filename (path) from the user
# open the file for reading
# get the file contents as string S and
# split into lines without '\n'
# for each line:
#
split line into list of words
#
#
#
#
for each word in the line's word list
if word length is 4
replace the list entry with string of four asterisks
rebuild the line (join using separator ' ')
# rebuild the file contents (join lines using separator '\n')
# open file for writing and
# write modified contents to file
Problem 9
Write a Python program that replaces every four-letter word in a text file with
'****'. Assume words are separated by whitespace.
fname = input("Enter an file name: ")
with open(fname,'r') as f: # open file for reading
S = f.read()
L = S.splitlines()
# get contents as string S and
# split into lines without '\n'
for i in range(len(L)):
K = L[i].split()
# for each line:
# split line into list of words
for j in len(K):
# for each word of the line
if len(K[j]) == 4: # if word length is 4
K[j] = '****'
#
replace with four asterisks
L[i] = ' '.join(K)
S = '\n'.join(L)
# rebuild the line
# rebuild the file contents
with open(fname,'w') as f: # open file for writing and
f.write(S)
# write modified contents to
Problem 9
Complete the code for the following Python function
def OneToOne(D):
""" returns True if no two keys of the dictionary D have
the same value in the dictionary"""
return len(D.values()) == len(D.keys())
Alternate Solution:
def OneToOne(D):
""" returns True if no two keys of the dictionary D have
the same value in the dictionary"""
return len(D.values()) == len(set(D.values()))