《python 高级程序设计 》
课程目录
- Page hierarchy
- 一、Inclass exercises
- 二、Outclass exercises
- 总结
Page hierarchy
Main page->Courses->Problem sets
提示:以下是本篇文章正文内容,下面题目答案可供参考
一、Inclass exercises
1.Week7_InClass
1.expressions_number2
Description:
Trace the evaluation of the following expressions, and give their resulting values. Make sure to give a value of the appropriate type (such as including a .0 at the end of a float).
Answer:
2.expressions_exam1
Description:
Trace the evaluation of the following expressions, and give their resulting values. Make sure to give a value of the appropriate type (such as including “” quotes around a string or a .0 at the end of a float).
Answer:
3.expressions_exam2
Description:
Trace the evaluation of the following expressions, and give their resulting values. Make sure to give a value of the appropriate type (such as including “” quotes around a string or a .0 at the end of a float).
Answer:
4.expressions_exam5
Description: Trace the evaluation of the following expressions, and give their resulting values. Make sure to give a value of the appropriate type (such as including “” quotes around a string or a .0 at the end of a float).
Answer:
5.compute_pay
Description:
The following program redundantly repeats the same expressions many times. Modify the program to remove all redundant expressions using variables.
Answer:
def main():
# Calculate pay at work based on hours worked each day
print("My total hours worked:")
a=4 + 5 + 8 + 4
print(a)
print("My hourly salary:")
b=8.75
print(b)
print("My total pay:")
c=(4 + 5 + 8 + 4) * 8.75
print(c)
print("My taxes owed:") # 20% tax
d=(4 + 5 + 8 + 4) * 8.75 * 0.20
print(d)
main()
6.define_grade_variable
Description: Which of the following choices is the correct syntax for defining a real number variable named grade and initializing its value to 4.0?
Answer:
7.first_second
Description: What are the values of first and second at the end of the following code?
Answer:
8.first_second2
Description: What are the values of first and second at the end of the following code?
9.four_mistakes
Description: Rewrite the code from the previous exercise first_second to be shorter, by defining the variables on the same line and by using the special assignment operators (e.g., +=, -=, *=, and /=) as appropriate.
Answer:
first,second=8,19
first+=second
second=first-second
first-=second
10.last_digit
Description: Suppose you have an variable named number that stores an integer. What Python expression produces the last digit of the number (the 1s place)?
Answer:
11.max_min
Description: What is the output from the following code?
Answer:
12.random_integer_0_to_10r
**Description: ** Write an expression that generates a random integer between 0 and 10 inclusive.
n = ___
Answer:
13.roundoff_error
Description:
The expression (0.2 + 1.2 + 2.2 + 3.2) should equal 6.8, but in Python it does not. Why not?
Answer:
14.second_to_last_digit
Description: Suppose you have an variable named number that stores an integer. What Python expression produces the second-to-last digit of the number (the 10s place)? What expression produces the third-to-last digit of the number (the 100s place)?
Answer:
15.values_of_abc
Description: What are the values of a, b, and c after the following code statements?
Answer:
16.values_of_ijk
Description: What are the values of i, j, and k after the following code statements?
Answer:
2.Week8_InClass(None)
Description:
Answer:
3.Week9_InClass
1.area
Description:
Write a function named area that accepts the radius of a circle as a parameter and returns the area of a circle with that radius. For example, the call of area(2.0) should return 12.566370614359172. You may assume that the radius is non-negative.
Answer:
import math
def area(r):
s=math.pi*r*r
return s
2.get_first_digit
Description:
Write a function named get_first_digit that returns the first digit of an integer. For example, get_first_digit(3572) should return 3.
Answer:
def get_first_digit(num):
abs_num=abs(num)
a=len(str(abs_num))
num_first=abs_num//10**(a-1)
return num_first
3.average_of_2
Description:
Write a function named average_of_2 that takes two integers as parameters and returns the average of the two integers. For example, the call of average_of_2(2, 9) should return 5.5.
Answer:
def average_of_2(num_a,num_b):
average_num=1/2*(num_b+num_a)
return average_num
4.carbonated
Description:
What output is produced by the following program?
Answer:
5.days_in_month
Description:
Write a function named days_in_month that accepts a month (an integer between 1 and 12) as a parameter and returns the number of days in that month. For example, the call of days_in_month(9) returns 30 because September has 30 days. You may assume that the month value passed is between 1 and 12 inclusive. Ignore leap years assume that February always has 28 days.
Recall the following table of the number of days in each month:
Month | 1 Jan | 2 Feb | 3 Mar | 4 Apr | 5 May | 6 Jun | 7 Jul | 8 Aug | 9 Sep | 10 Oct | 11 Nov | 12 Dec |
---|---|---|---|---|---|---|---|---|---|---|---|---|
Days | 31 | 28 | 31 | 30 | 31 | 30 | 31 | 31 | 30 | 31 | 30 | 31 |
Answer:
def days_in_month(month):
if month==4 or month==6 or month==9 or month==11:
return 30
elif month==2:
return 28
else:
return 31
6.digit_sum
Description:
Write a recursive function named digit_sum that accepts an integer as a parameter and returns the sum of its digits. For example, calling digit_sum(1729) should return 1 + 7 + 2 + 9, which is 19. If the number is negative, return the negation of the value. For example, calling digit_sum(-1729) should return -19.
Constraints: Do not declare any global variables. Do not use any loops you must use recursion. Do not use any auxiliary data structures like list, dict, set, etc. Also do not solve this problem using a string. You can declare as many primitive variables like ints as you like. You are allowed to define other “helper” functions if you like they are subject to these same constraints.
Answer:
def digit_sum(num):
if abs(num)<10:
return num
elif num>0:
return digit_sum(num//10)+num%10
else:
n=abs(num)
return -(digit_sum(n//10)+n%10)
7.factorial
Description:
Write a recursive function named factorial that accepts an integer n as a parameter and returns the factorial of n, or n!. A factorial of an integer is defined as the product of all integers from 1 through that integer inclusive. For example, the call of factorial(4) should return 1 * 2 * 3 * 4, or 24. The factorial of 0 and 1 are defined to be 1. You may assume that the value passed is non-negative and that its factorial can fit in the range of type int.
Do not use loops or auxiliary data structures; solve the problem recursively.
Answer:
def factorial(n):
if n==1 or n==0:
return 1
return n*factorial(n-1)
8.fractal_concepts
Description:
Answer the following questions about fractals:
Answer:
9.hash_string
Description:
Write a recursive function named hash_string that accepts an integer parameter k and returns a string of # (hash symbols) that is 2k characters long (i.e., 2 to the kth power). For example, the call of hash_string(3) returns “########”. Throw an IllegalArgumentException if k is less than 0. Do not use loops you must use recursion.
Answer:
def hash_string(k):
num=0
if k<0:
raise ValueError()
num=2**k
return int(num)*"#"
10.double_digits
Description:
Write a recursive function named double_digits that accepts an integer as a parameter and returns the integer obtained by replacing every digit with two of that digit. For example, double_digits(348) should return 334488. The call double_digits(0) should return 0. Calling your function on a negative number should return the negation of calling it on the corresponding positive number; for example, double_digits(-789) should return -778899.
Answer:
def double_digits(num):
if num<10 and num>0 :
return 2*str(num)
elif num<0 and num>-10:
return int(2*str(abs(num)))*-1
elif num==0:
return 0
elif num>0:
return int(str(double_digits(num//10))+2*str(num%10))
else:
n=abs(num)
return int(str(double_digits(n//10))+2*str(n%10))*-1
4.Week10_InClass
1.data_list
Description:
Write code that creates a list of integers named data of size 5 containing the values 27, 51, 33, -1, and 101.
Answer:
data=[27,51,33,-1,101]
2.all_less
Description:
Write a function named all_less that accepts two lists of integers and returns True if each element in the first list is less than the element at the same index in the second list. Your function should return false if the lists are not the same length. For example, if the two lists passed are [45, 20, 300] and [50, 41, 600], your function should return True. If the lists are not the same length, you should always return False.
Answer:
def all_less(a,b):
if len(a)!=len(b):
return False
for i in range(len(a)):
if a[i]>b[i]:
return False
return True
3.average
Description:
Write a function named average that accepts a list of integers as its parameter and returns the average (arithmetic mean) of all elements in the list as a float. For example, if the list passed contains the values [1, -2, 4, -4, 9, -6, 16, -8, 25, -10], the calculated average should be 2.5. You may assume that the list contains at least one element. Your function should not modify the elements of the list.
Answer:
def average(a):
sum=0
for x in a:
sum+=x
average_num=1/len(a)*sum
return average_num
4.compute_average
Description:
Write a function named compute_average that computes and returns the mean of all elements in a list of integers. For example, if a list named a contains [1, -2, 4, -4, 9, -6, 16, -8, 25, -10], then the call of compute_average(a) should return 2.5.
Constraints: You may assume that the list contains at least one element. Your function should not modify the elements of the list.
Answer:
def compute_average (a):
sum=0
for x in a:
sum+=x
average_num=1/len(a)*sum
return average_num
5.list_mystery1
Description:
What are the values of the elements in list a1 after the following code executes?
Answer:
6.list_mystery2_xy
Description:
Consider the following function, mystery.
What are the values of the elements in list numbers after the following code executes?
Answer:
7.get_percent_even
Description:
Write a function named get_percent_even that accepts a list of integers as a parameter and returns the percentage of the integers in the list that are even numbers. For example, if a list a stores [6, 4, 9, 11, 5], then your function should return 40.0 representing 40% even numbers. If the list contains no even elements or is empty, return 0.0. Do not modify the list passed in.
Answer:
def get_percent_even(a):
count=0
per_num=0.0
for x in a:
if x%2==0:
count+=1
if count==0:
return 0.0
else:
per_num=1/len(a)*count*100
return per_num
8.collapse
Description:
Write a function named collapse that accepts a list of integers as a parameter and returns a new list where each pair of integers from the original list has been replaced by the sum of that pair. For example, if a list called a stores [7, 2, 8, 9, 4, 13, 7, 1, 9, 10], then the call of collapse(a) should return a new list containing [9, 17, 17, 8, 19]. The first pair from the original list is collapsed into 9 (7 + 2), the second pair is collapsed into 17 (8 + 9), and so on.
If the list stores an odd number of elements, the element is not collapsed. For example, if the list had been [1, 2, 3, 4, 5], then the call would return [3, 7, 5]. Your function should not change the list that is passed as a parameter.
Answer:
def collapse(a):
b=[]
for i in range(0,len(a),2):
if i==len(a)-1:
b.append(a[i])
else:
b.append(a[i]+a[i+1])
print(b)
return b
9.collapse_pairs
Description:
Write a function named collapse_pairs that accepts a list of integers as a parameter and modifies the list so that each of its pairs of neighboring integers (such as the pair at indexes 0-1, and the pair at indexes 2-3, etc.) are combined into a single sum of that pair. The sum will be stored at the even index (0,2,4, etc.) if the sum is even and at the odd index (1,3,5, etc.) if the sum is odd. The other index of the pair will change to 0.
For example, if a list named a stores the values [7, 2, 8, 9, 4, 22, 7, 1, 9, 10], then the call of collapse_pairs(a) should modify the list to contain the values [0, 9, 0, 17, 26, 0, 8, 0, 0, 19]. The first pair from the original list is collapsed into 9 (7 + 2), which is stored at the odd index 1 because 9 is odd. The second pair is collapsed into 17 (8 + 9), stored at the odd index 3 the third pair is collapsed into 26 (4 + 22), stored at the even index 4 and so on. The figure below summarizes the process for this example list:
Answer:
通过的标准答案:
def collapse_pairs(a):
for i in range(0,len(a)-1,2):
sum=a[i]+a[i+1]
if sum%2==0:
a[i]=sum
a[i+1]=0
else:
a[i]=0
a[i+1]=sum
结果正确,但输出不通过。
def collapse_pairs(a):
b=[]
label=0
for i in range(0,len(a),2):
if i==len(a)-1:
b.append(a[i])
label=1
else:
b.append(a[i]+a[i+1])
c=[0 for x in range(2*len(b))]
for j in range(len(b)):
if b[j]%2==1:
c[2*j+1]=b[j]
else:
c[2*j]=b[j]
if label==1 and c[-1]==0:
del c[-1]
elif label==1 and c[-2]==0:
del c[-2]
print(c)
10.average_length
Description:
Write a function named average_length of code that computes and returns the average string length of the elements of a list of strings. For example, if the list contains [“belt”, “hat”, “jelly”, “bubble gum”], the average length returned should be 5.5. Assume that the list has at least one element.
Answer:
def average_length(a):
sum=0
for x in a:
sum+=len(x)
return 1/len(a)*sum
5.Week11_InClass
自从Week10_Inclass开始,课堂练习难度大于课后练习难度
1.collection_mystery5
Description:
Write the output that is printed when the given function below is passed each of the following maps and lists as its parameters. Recall that maps prin a {key1=value1, key2=value2, …, keyN=valueN} format.
Though hash maps usually have unpredictable ordering, for this problem, you should assume that when looping over the map or printing a map, it visits the keys in the order that they were added to the map or the order they are declared below. If a map calls put() on a key that already exists, it retains its current position in the ordering (as would be the case for an OrderedDict).
Answer:
2.count_names
Description:
Write a complete console program that asks the user for a list of names (one per line) until the user enters a blank line (i.e., just presses Enter when asked for a name). At that point, the program should print out how many times each name in the list was entered. A sample run of this program is shown below.
Answer:
b={}
count=1
while True:
a=input("Enter name: ")
if a=='':
break
elif not a in b:
b[a]=count
else:
b[a]+=1
for key,value in b.items():
print("Entry [{}] has count {}".format(key,int(value)))
3.deans_list
Description:
Write a function named deans_list that accepts as a parameter a dictionary of student names mapped to GPAs (A decimal number between 0.0 and 4.0 inclusive) and returns a set of all students who have GPAs of 3.5 or above. For example, if a dictionary grades contains the following:
Then the call of deans_list(grades) should return the following set:
If the passed in dictionary is empty, your function should return an empty set.
Answer:
def deans_list(grades):
grades_name=[]
for key,values in grades.items():
if values>=3.5:
grades_name.append(key)
return {v for v in grades_name}
4.reverse
Description:
Write a function named reverse that accepts a dictionary from integers to strings as a parameter and returns a new dictionary of strings to integers that is the original’s “reverse”. The reverse of a dictionary is defined here to be a new dictionary that uses the values from the original as its keys and the keys from the original as its values. Since a dictionary’s values need not be unique but its keys must be, it is acceptable to have any of the original keys as the value in the result. In other words, if the original dictionary has pairs (k1, v) and (k2, v), the new dictionary must contain either the pair (v, k1) or (v, k2).
For example, for the following dictionary:
{42: ‘Marty’, 81: ‘Sue’, 17: ‘Ed’, 31: ‘Dave’, 56: ‘Ed’, 3: ‘Marty’, 29: ‘Ed’}
Your function could return the following new dictionary (the order of the key/value pairs does not matter):
{‘Marty’: 3, ‘Sue’: 81, ‘Ed’: 29, ‘Dave’: 31}
Do not modify the dictionary passed in as the parameter.
Answer:
def reverse(grades):
return {values:key for key,values in grades.items() }
5.has_duplicate_value
Description:
Write a function named has_duplicate_value that accepts a dictionary from strings to strings as a parameter and returns True if any two keys map to the same value. For example, if a dictionary named m stores {‘Marty’: ‘Stepp’, ‘Stuart’: ‘Reges’, ‘Jessica’: ‘Miller’, ‘Amanda’: ‘Camp’, ‘Meghan’: ‘Miller’, ‘Hal’: ‘Perkins’}, the call of has_duplicate_value(m) would return True because both ‘Jessica’ and ‘Meghan’ map to the value ‘Miller’. Return False if passed an empty or one-element dictionary. Do not modify the dictionary passed in.
Answer:
def has_duplicate_value(m):
m_size=len(m)
a=set(values for key,values in m.items())
if len(a)!=m_size and len(a)!="":
return True
else:
return False
6.intersect(♥♥)
Description:
Write a function named intersect that accepts two dicts of strings to integers as parameters and that returns a new dictionary whose contents are the intersection of the two. The intersection of two dictionaries is defined here as the set of keys and values that exist in both dictionaries. So if some value K maps to value V in both the first and second dictionary, include it in your result. If K does not exist as a key in both dictionaries, or if K does not map to the same value V in both dictionaries, exclude that pair from your result. For example, consider the following two dictionaries:
{‘Janet’: 87, ‘Logan’: 62, ‘Whitaker’: 46, ‘Alyssa’: 100, ‘Stefanie’: 80, ‘Jeff’: 88, ‘Kim’: 52, ‘Sylvia’: 95},
{‘Logan’: 62, ‘Kim’: 52, ‘Whitaker’: 52, ‘Jeff’: 88, ‘Stefanie’: 80, ‘Brian’: 60, ‘Lisa’: 83, ‘Sylvia’: 87}
Calling your function on the preceding dictionaries would return the following new dictionary:
{‘Logan’:62, ‘Stefanie’=80, ‘Jeff’=88, ‘Kim’=52}
Do not modify the dictionaries passed in as parameters.
Answer:
def intersect(k,v):
b={}
for key,values in k.items():
if not key in v.keys():
continue
elif k[key]!=v[key]:
continue
else:
b[key]=values
return b
7.lambda_tracing2
Description:
What is the output of the following code?
Answer:
8.count_negatives
Description:
Write a function named count_negatives that takes a list of integers as a parameter and returns how many numbers in the list are negative. For example, if the list is
[5, -1, -3, 20, 47, -10, -8, -4, 0, -6, -6], you should return 7.
Use Python’s functional programming constructs, such as list comprehensions, map, filter, reduce, to implement your function. Do not use any loops or recursion in your solution.
Answer:
def count_negatives(a):
b=filter(lambda x:x<0,a)
return len(list(b))
9. count_vowels
Description:
Write a function called count_vowels that counts the number of vowels in a given string. A vowel is an A, E, I, O, or U, case-insensitive. For example, if the string is “SOO beautiful”, there are 7 vowels.
Use Python’s functional programming constructs, such as list comprehensions, map, filter, reduce, to implement your function. Do not use any loops or recursion in your solution.
Answer:
def count_vowels(num):
a=filter(lambda x:x in "aeiouAEIOU",num)
return len(list(a))
10.double_list
Description:
Write a function named double_list that takes a list as a parameter and returns a list of integers that contains double the elements in the initial list. For example, if the initial list is [2, -1, 4, 16], you should return [4, -2, 8, 32].
Use Python’s functional programming constructs, such as list comprehensions, map, filter, reduce, to implement your function. Do not use any loops or recursion in your solution.
Answer:
def double_list(num_list):
a=map(lambda x:2*x,num_list)
return list(a)
11.generate_odds
Description:
Write a function named generate_odds that returns a generator expression that will generate all the odd numbers between 0 and 20.
Use Python’s functional programming constructs to implement your function. Do not use any loops or recursion in your solution.
Answer:
def generate_odds():
return (x for x in range(1,21,2))
6.Week12_InClass(None)
7.Week13_InClass
1.BankAccount
Description:
Write a class of objects named BankAccount that remembers information about a user’s account at a bank. You must include the following public members:
member name | type | description |
---|---|---|
BankAccount(name) | constructor | constructs a new account for the person with the given name, with $0.00 balance |
ba.name | property | the account name as a string (read-only) |
ba.balance | property | the account balance as a real number (read-only) |
ba.deposit(amount) | method | adds the given amount of money, as a real number, to the account balance; if the amount is negative, does nothing |
ba.withdraw(amount) | method | subtracts the given amount of money, as a real number, from the account balance; if the amount is negative or exceeds the account’s balance, does nothing |
You should define the entire class including the class heading, the private instance variables, and the declarations and definitions of all the public member functions and constructor.
Answer:
class BankAccount(object):
def __init__(self,name):
self.name=name
self.balance=0
def deposit(self,amount):
self.amount=amount
if self.amount<0:
return
self.balance+=self.amount
def withdraw(self,amount):
if amount<0 or amount>self.balance:
return
self.balance-=amount
2.BankAccount_str
3.BankAccount_transaction_fee
4.Date
5.Date_absolute_day
5.Date_from_absolute_day
二、Outclass exercises
1.Week7_OutClass
1. expressions_exam3
Description: Trace the evaluation of the following expressions, and give their resulting values. Make sure to give a value of the appropriate type (such as including “” quotes around a string or a .0 at the end of a float).
Answer:
2. expressions_exam4
Description: Trace the evaluation of the following expressions, and give their resulting values. Make sure to give a value of the appropriate type (such as including “” quotes around a string or a .0 at the end of a float).
Answer:
3. expressions_exam6
Description: Trace the evaluation of the following expressions, and give their resulting values. Make sure to give a value of the appropriate type (such as including “” quotes around a string or a .0 at the end of a float).
Answer:
2.Week8_OutClass
1.hello_world
Description: Write a Python program that prints the following console output:
Hello, world!
(You don’t need to write any ‘import’ statements.)
Answer:
print("Hello, world!")
2.escape1
Description:
Write a Python console program that prints the following console output. (The second line is indented by one tab.)
(You don’t need to write any ‘import’ statements.)
Answer:
print("Which is better?\n"+"\t"+"A \\ or a /?\n" + "/\\_/\\"+"\n"+" . .")
3.fear_the_tree
Description:
Write a Python program that prints the following console output:
Answer:
print(20*"\\"+"\n"+"||"+" FEAR THE TREE! "+"||"+"\n"+20*"/")
4.inches_to_centimeters(♥)
Description: Write an interactive console program that prompts the user to read in two input values: a number of feet, followed on a separate line by a number of inches. The program should convert this amount to centimeters. Here is a sample run of the program (user input is shown like this):
Answer:
# In[1]
# It is a my stupid solution.
# The first answer.
print("This program converts feet and inches to centimeters.")
input_a=input("Enter number of feet: ")
a=int(input_a)
input_b=input("Enter number of inches: ")
b=int(input_b)
c=(a*12.0+b)*2.54
if c*100%10!=0:
print("%d ft %d in = %-.2f cm" % (a,b,c))
else:
print("%d ft %d in = %-.1f cm" % (a,b,c))
# In[2]
# The second answer.(recommend)
print("This program converts feet and inches to centimeters.")
f=int(input("Enter number of feet: "))
g=int(input("Enter number of inches: "))
cm=2.54*(12*f+g)
print("%d ft %d in = %.2f cm"%(f,g,cm))
5.add_commas(♥)
Description:
Write a function named add_commas that accepts a string representing a number and returns a new string with a comma at every third position, starting from the right. For example, the call of add_commas(“12345678”) returns “12,345,678”.
Answer:
def add_commas(num):
count=0
str_num=str(num)
str_add=''
for one_str in str_num[::-1]:
count+=1
if count%3==0 and count!=len(str_num):
str_add=','+one_str+str_add
else:
str_add=one_str+str_add
return str_add
6.marshall_mathers
Description:
Given the following variable declarations:
Give the results of the following expressions. Make sure to indicate a value of the proper type (e.g. strings in " " quotes).
Answer:
7.archie
Description:
What is the output produced from the following statements? (Treat tabs as aligning to every multiple of eight spaces.)
(NOTE ABOUT SPACING: Many students fail this problem by not understanding how the \t character works, causing them to have the wrong number of spaces. A tab inserts multiple spaces until the total number of characters on the current line so far is a multiple of 8. So for example, in the string “hi\thello\tgoodbye\tbeautiful\thi”, the first \t becomes 6 spaces (because “hi” is 2 characters, so it takes 6 more to get to 8), the second \t is 3 spaces (because “hello” is 5 characters wide, so it takes 3 more characters to get to 8), the third is 1 (because “goodbye” is 7 characters), and the fourth \t is 7 spaces (because “beautiful” is 9 characters, so it takes 7 more to get to 16, which is the next multiple of 8).
Answer:
8.difference
Description:
Write a complete program that prints the following output:
Answer:
print("What is the difference between")
print('a \' and a \\\'? Or between a " and a \\\"?')
print("\' and \" can be used to define strings")
print("\\\' and \\\" are used to print quotes")
9.downward_spiral
Description:
What is the output produced from the following statements? (Treat tabs as aligning to every multiple of eight spaces.)
(NOTE ABOUT SPACING: Many students fail this problem by not understanding how the \t character works, causing them to have the wrong number of spaces. A tab inserts multiple spaces until the total number of characters on the current line so far is a multiple of 8. So for example, in the string “hi\thello\tgoodbye\tbeautiful\thi”, the first \t becomes 6 spaces (because “hi” is 2 characters, so it takes 6 more to get to 8), the second \t is 3 spaces (because “hello” is 5 characters wide, so it takes 3 more characters to get to 8), the third is 1 (because “goodbye” is 7 characters), and the fourth \t is 7 spaces (because “beautiful” is 9 characters, so it takes 7 more to get to 16, which is the next multiple of 8).
Answer:
10.egg
Description:
Write a complete program that displays the following output:
Answer:
print(2*" "+7*"_")
print(" "+"/"+7*" "+"\\")
print("/"+9*" "+"\\")
print(2*"-\"-\'"+"-\"-")
print("\\"+9*" "+"/")
print(" "+"\\"+7*"_"+"/")
11.legal_identifiers
Description:
Which of the following can be used in a Python program as identifiers? Check all of the identifiers that are legal.
Answer:
12.output_syntax
Description:
Which of the following is the correct syntax to output a message?
Answer:
13.print_slashes
Description:
Write a print statement that produces the following output:
Answer:
print("/"+" "+"\\"+" "+"//"+" "+2*"\\"+" "+"///"+" "+3*"\\")
14.shaq
Description:
What is the output produced from the following statements?
Answer:
3.Week9_OutClass
1.ftoc
Description:
What is wrong with the following program? Correct it to behave properly.
Answer:
# converts Fahrenheit temperatures to Celsius
def ftoc(tempf, tempc):
tempc = (tempf - 32) /(9/5)
return tempc
def main():
tempf = 98.6
tempc = 0.0
a=ftoc(tempf, tempc)
print("Body temp in C is:", round(a,0))
main()
2.get_last_digit
Description:
Write a function named get_last_digit that returns the last digit of an integer. For example, the call of get_last_digit(3572) should return 2.
Answer:
def get_last_digit(num):
abs_num=abs(num)
last_num=abs_num%10
return last_num
3.average_of_3
Description:
Write a function named average_of_3 that accepts three integers as parameters and returns the average of the three integers as a number. For example, the call of average_of_3(4, 7, 13) returns 8.
Answer:
def average_of_3(num_a,num_b,num_c):
av_num=1/3*(num_a+num_b+num_c)
return av_num
4.count_unique
Description:
Write a function named count_unique that takes three integers as parameters and that returns the number of unique integers among the three. For example, the call count_unique(18, 3, 4) should return 3 because the parameters have 3 different values. By contrast, the call count_unique(6, 7, 6) should return 2 because there are only 2 unique numbers among the three parameters: 6 and 7.
Answer:
def count_unique(num_a,num_b,num_c):
if num_a==num_b and num_b==num_c:
return 1
elif num_a == num_b or num_a==num_c or num_b==num_c:
return 2
else:
return 3
5.factorial
Description:
Write a function named factorial that accepts an integer n as a parameter and prints the factorial of n, or n!, as output. A factorial of an integer is defined as the product of all integers from 1 through that integer inclusive. For example, the call of factorial(4) should print the following output:
The factorial of 0 and 1 are defined to be 1. You may assume that the value passed is non-negative and that its factorial can fit in the range of type int.
Answer:
def factorial(n):
s=1
num=n
while n!=0:
s*=n
n-=1
print("{} factorial = {}".format(num,s))
Description:
Answer:
4.Week10_OutClass
1.fill_data_list
Description:
Fill in the list with the values that would be stored after the code executes:
Answer:
2.list_declare
Description:
Which of the following choices is the correct syntax for quickly declaring/initializing a list of six integers named a to store a particular list of values?
Answer:
3.double_list
Description:
Write a function named double_list that takes a list of strings as a parameter and that replaces every string with two of that string. For example, if the list stores the values [“how”, “are”, “you?”] before the function is called, it should store the values [“how”, “how”, “are”, “are”, “you?”, “you?”] after the function finishes executing.
Answer:
def double_list(a):
for i in range(0,2*len(a),2):
a.insert(i+1,a[i])
print(a)
4.index_of
Description:
Write a function named index_of that returns the index of a particular value in a list of integers. The function should return the index of the first occurrence of the target value in the list. If the value is not in the list, it should return -1. For example, if a list called list stores the following values:
Then the call index_of(list, 8) should return 4 because the index of the first occurrence of value 8 in the list is at index 4. The call index_of(list, 2) should return -1 because value 2 is not in the list.
Answer:
def index_of(a,num):
for i in range(len(a)):
if num==a[i]:
return i
return -1
5.list_range
Description:
Write a function named list_range that returns the range of values in a list of integers. The range is defined as 1 more than the difference between the maximum and minimum values in the list. For example, if a list called nums contains [36, 12, 25, 19, 46, 31, 22], the call of list_range(list) should return 35. You may assume that the list has at least one element. You should not modify the contents of the list.
Answer:
def list_range(a):
min=a[0]
max=a[0]
for i in range(1,len(a)):
if min>a[i]:
min=a[i]
if max<a[i]:
max=a[i]
return max-min+1
5.Week11_OutClass
1.dict_mystery
Description:
What is the output of the following code? For the purposes of this problem, assume that the dictionary will print with its keys in sorted order.
Answer:
2.lambda_concat_name
Description:
Define a lambda expression named f that accepts two string parameters representing a first and last name and concatenates them together to return a string in “Last, First” format. For example, if passed “Cynthia” and “Lee”, it would return “Lee, Cynthia”. Do not write an entire function; just write a statement of the form:
Answer:
f=lambda x,y: y+", "+x
3.lambda_larger
Description:
Define a lambda expression named f that accepts two integer parameters and returns the larger of the two; for example, if passed 4 and 11, it would return 11. Do not write an entire function; just write a statement of the form:
Answer:
f=lambda x,y: max(x,y)
4.lambda_square
Description:
Define a lambda expression named f that accepts an integer parameter and converts it into the square of that integer; for example, if 4 were passed, your lambda would return 16. Do not write an entire function; just write a statement of the form:
Answer:
f= lambda x: x**2
5.lambda_tracing
Description:
What is the output of the following code?
Answer:
6.Week12_OutClass(None)
7.Week13_OutClass
1.class_concepts
Description:
Answer the following questions about classes and objects:
Answer:
2.Calculator_class
Description:
Suppose you were making a class named Calculator to use as the underlying data model for a calculator application like the one in your operating system. Answer the following questions about developing this class:
Answer:
3.class_tracing
Description:
What is the output of the following program? Write each of the four lines as it would appear on the console.
class Date:
def __init__(self,m,d):
self.month=m
self.day=d
def add_to_month_twice(a,d):
a=a+a
d.month=a
print(a,d.month)
def main():
a=7
b=9
d1=Date(2,2)
d2=Date(2,2)
add_to_month_twice(a,d1)
print(a,b,d1.month,d2.month)
add_to_month_twice(b,d2)
print(a,b,d1.month,d2.month)
main()
Answer:
输出结果:
14 14
7 9 14 2
7 9 14 18
总结
python高级编程课程,可以让我快速掌握基本语法.一定坚持,每天动手编程,每天进步一点点儿.