Basics.sjtu.edu.cn



9话an'hua??????????闹??g value. ?clicks inside the “Done” rect- clicks inside the “Done” rect- 27ection 5.8es running from -10,27ection 5.8es running from -10,2016. 9. 27 Homework11. Modify the Chaos program so that it prints out 20 values instead of 10.(Section 1.10 Programming Exercises 4)2. Write a program that converts from Fahrenheit to Celsius.(Section 2.9 Programming Exercises 8)3. Modify the convert.py program with a loop so that it executes 5 times before quitting (i.e., it converts 5 temperatures in a row). (Section 2.9 Programming Exercises 3)4. (Advanced) Modify the Chaos program so that it accepts two inputs and then prints a table with two columns similar to the one shown.(Section 1.10 Programming Exercises 6)2015.9.29 Practice11. Modify the Chaos program so that the number of values to print is determined by the user. You will have to add a line near the top of the program to get another value from the user:n = input(“How many numbers should I print?”)Then you will need to change the loop to use n instead of a specific number.(Section 1.10 Programming Exercises 5)2. Modify the avg2.py program to find the average of three exam scores. (Section 2.9 Programming Exercises 2)3. Write a program that converts distances measured in kilometers to miles. One kilometer is approximately 0.62 miles. (Section 2.9 Programming Exercises 9)4. (Advanced) Write a program to determine the length of a ladder required to reach a given height when leaned against a house. The height and angle of the ladder are given as inputs. To compute length use length = height/(sin angle).Note: the angle must be in radians. Prompt for an angle in degrees and use this formula to convert:radians = (pi/180) * degrees(Section 3.8 Programming Exercises 10)2016. 10.11 Homework21. Write a program to sum a series of numbers entered by the user. The program should first prompt the user for how many numbers are to be summed. It should then input each of the numbers and print a total sum. (Section 3.8 Programming Exercises 13)2. A Fibonacci sequence is a sequence of numbers where each successive number is the sum of the previous two. The classic Fibonacci sequence begins: 1, 1, 2, 3, 5, 8, 13, … . Write a program that computes the nth Fibonacci number where n is a value input by the user. For example, if n=6, then the result is 8.Choice 1: The user is admitted to ask for one number.Choice 2: The user is admitted to ask for three numbers.Choice 3: (Advanced)The user is admitted to ask for numbers as many as he/she wants.(Section 3.8 Programming Exercises 16)2016.10.13 Practice21. Write a program to calculate the area of a triangle given the length of its three sides a, b, and c using these formulas: ? (Section 3.8 Programming Exercises 9)2. Write a program to find the sum of the first n natural numbers, where the value of n is provided by the user. ?(Section 3.8 Programming Exercises 11)2016.10.18 Homework31. A Caesar cipher is a simple substitution cipher based on the idea of shifting each letter of the plaintext message a fixed number (called the key) of positions in the alphabet. For example, if the key value is 2, the word “Sourpuss” would be encoded as “Uqwtrwuu.” The original message can be recovered by “reencoding” it using the negative of the key. Write a program that can encode and decode Caesar ciphers. The input to the program will be a string of plaintext and the value of the key. The output will be an encoded message where each character in the original message is replaced by shifting it characters in the ASCII character set. For example, if is a character in the string and is the amount to shift, then the character that replaces can be calculated as: chr(ord(ch)+key)(Section 4.8 Programming Exercises 8)2. Write an improved version of the future value program from Chapter 2. Your program will prompt the user for the amount of the investment, the annualized interest rate, and the number of years of the investment. The program will then output a nicely formatted table that tracks the value of the investment year by year. Your output might look something like this: (Section 4.8 Programming Exercises 13)3. Word count. A common utility on Unix/Linux systems is a small program called “wc.” This program analyzes a file to determine the number of lines, words, and characters contained therein. Write your own version of wc. The program should accept a file name as input and then print three numbers showing the count of lines, words, and characters in the file. (Section 4.8 Programming Exercises 15)4. (Advanced) A certain CS professor gives 100-point exams that are graded on the scale 90–100:A, 80–89:B, 70–79:C, 60–69:D, 60:F. Write a program that accepts an exam score as input and prints out the corresponding grade. (Section 4.8 Programming Exercises 4)2016.10.25 Homework42. A babysitter charges $2.50 an hour until 9:00 PM when the rate drops to $1.75 an hour (the children are in bed). Write a program that accepts a starting time and ending time in hours and minutes and calculates the total babysitting bill. You may assume that the starting and ending times are in a single 24 hour period. Partial hours should be appropriately prorated. ?(Section 7.7 Programming Exercises 7)?3. A year is a leap year if it is divisible by 4, unless it is a century year that is not divisible by 400. (1800 and 1900 are not leap years while 1600 and 2000 are.) Write a program that calculates whether a year is a leap year. ?(Section 7.7 Programming Exercises 11)?2016.10.27 Practice31. Define a one-dimensional array and a two-dimensional array. Initialized as 0. Print out the elements in each array.2.(考拉兹猜想)The Syracuse(also called Collatz or Hailstone) sequence is generated by starting with a natural number and repeatedly applying the following function until reaching 1For example, the Syracuse sequence starting with 5 is: 5, 16, 8, 4, 2 , 1. It is an open question in mathematics whether this sequence will always go to 1 for every possible starting value. Write a program that gets a starting value from the user and then prints the Syracuse sequence for that starting value. ?3. (Advanced) A positive whole number n>2 is prime if no number between 2 andn (inclusive) evenly divides n. Write a program that accepts a value of n as input and determines if the value is prime. If n is not a prime, your program should quit as soon as it finds a value that evenly divides n. 2016.11.1 Homework51. 设n是一任意自然数,若将n的各位数字反向排列所得自然数n1与n相等(如:12321),则称n为回文数(Palindrome number)。以下函数实现判别n是否为回文数:def is_Palindrome_number(n):# return True if yes, or False if not.2. 编写函数find_balance_point(A),实现一个包含了n个自然数的列表A中寻找平衡点。如果存在,返回它的下标,否则返回-1。注意:列表中每个元素智能访问一次,不能修改列表A,不要使用其他辅助列表。?平衡点的含义:给定一个序列A,如果存在一个元素,其前面的部分数值的和等于后面部分数值的和,那么这个点就是平衡点。如A=[1,2,2,5,1,4],那么元素5就是平衡点。?>>> a=[1,2,2,5,1,4]>>> find_balance_point(a)3>>> a=[1,2,3,6,7,2,3,4,5]>>> find_balance_point(a)-12016.11.8 Homework61. Write and test a recursive function max to find the largest number in a list. The max is the larger of the first item and the max of all the other items.2. 编写程序,打印N阶魔阵(N为奇数)。如3阶魔阵:8 1 63 5 74 9 2魔阵的排列规律如下:(1) 将1放在第一行中间一列;(2) 从2开始直到n×n止各数依次按下列规则存放;每一个数存放的行比前一个数的行数减1,列数加1(例如上面的三阶魔方阵,5在4的上一行后一列);(3) 如果上一个数的行数为1,则下一个数的行数为n(指最下一行);例如1在第一行,则2应放在最下一行,列数同样加1;(4) 当上一个数的列数为n时,下一个数的列数应为1,行数减去1。例如2在第3行最后一列,则3应放在第二行第一列;(5) 如果按上面规则确定的位置上已有数,或上一个数是第一行第n列时,则把下一个数放在上一个数的下面。例如按上面的规定,4应该放在第1行第2列,但该位置已经被占据,所以4就放在3的下面。 3. 将给定的列表 a 中的重复元素从列表中删除。 注意:a的元素可以是一个嵌套的列表。 def de_duplicate(a,sth=None): # sth can be used to do sth...>>> a = [2,4,6,range(10)]>>> de_duplicate(a)>>> a[2, 4, 6, [0, 1, 3, 5, 7, 8, 9]]>>> 2016/11/10 Practice41. The greatest common divisor(GCD) of two values can be computed using Euclid’s algorithm. Starting with the values m and n, we repeatedly apply the formula: n, m = m, n%m until m is 0. At that point, n is the GCD of the original m and n. Write a program that finds the GCD of two numbers using this algorithm. ?(Section 8.7 Programming Problems 8)?2. Write a program that accepts a date in the form month/day/year and outputs whether or not the date is valid. For example 5/24/1962 is valid, but 9/31/2000 is not. (September has only 30 days.) ?(Section 7.7 Programming Exercises 12)3. (Advanced) The days of the year are often numbered from 1 through 365 (or 366). This number can be computed in three steps using int arithmetic: (a)?dayNum = 31 (month-1)+day(b) if the month is after February subtract?(4month + 23)/10(c) if it’s a leap year and after February 29, add 1 ?Write a program that accepts a date as month/day/year, verifies that it is a valid date, and then calculates the corresponding day number. ?(Section 7.7 Programming Exercises 13)?练习:程序填空题(填写程序中的空格,以实现既定的功能)1)判断mylist中的整数是否为从小到大的序列:def is_sorted_list(mylist):#return True if sorted#or False if not sortedprior=Nonefor item in mylist:if prior==None or :prior=itemelse: return True2) 完全数是一些特殊的自然数,它所有的真因子(即除了自身之外的约数)的和恰好等于它本身,以下函数实现判别num是不是一个完全数:def is_perfect_number(num):# return True if yes,# or False if not.if num<=0:return Falsesum=0for i in range( ):if :sum+=iif sum==num:return Trueelse:return False答案:6)判断mylist中的整数是否为从小到大的序列:def is_sorted_list(mylist):#return True if sorted#or False if not sortedprior=Nonefor item in mylist:if prior==None or prior <= item:prior=itemelse:return Falsereturn True7) 完全数是一些特殊的自然数,它所有的真因子(即除了自身之外的约数)的和恰好等于它本身,以下函数实现判别num是不是一个完全数:def is_perfect_number(num):# return True if yes,# or False if not.if num<=0:return Falsesum=0for i in range(1,num):if num%i==0:sum+=iif sum==num:return Trueelse:return False2016/11/15 Homework71. P163给定两个平面上的点p1和p2(用元组表示),函数slope(p1, p2)返回通过p1和p2的直线的斜率,函数intercept(p1, p2) 返回该直线在y轴上的截距。2. 请写一个程序,计算每个月的十三号落在星期一到星期天的次数。给出 N 年(N为正整数),要求计算从1900年1月1日至(1900+N-1)年12月31日中13号落在星期一到星期日的次数(提示:1900年1月1日是星期一)。已知:N的值存放在文件input.dat中,该文件只有一个正整数N。 要求:(1)输出结果存放在文件output.dat中,格式为7个在一行且用空格分开的整数,它们分别代表13日是星期一、星期二、星期三、星期四、星期五、星期六和星期日的次数。 (2)尽可能用到模块化程序设计的思想。 例如:input.dat 的内容如下:40则文件 output.dat 的内容如下:69 68 70 68 69 68 68 3. A random walk is a particular kind of probabilistic simulation that models certain statistical systems such as the Brownian motion of molecules. You can think of a one-dimensional random walk in terms of coin flipping. Suppose you are standing on a very long straight sidewalk that extends both in front of and behind you. You flip a coin. If it comes up heads, you take a step forward; tails means to take a step backward. Suppose you take a random walk of steps. On average, how many steps away from the starting point will you end up? Write a program to help you investigate this question. (P342)4. (Advanced) Suppose you are doing a random walk (see previous problem) on the blocks of a city street. At each “step” you choose to walk one block (at random) either forward, backward, left or right. In steps, how far do you expect to be from your starting point? Write a program to help answer this question. 2016/11/22 Homework81. Modify the graphical future value program so that the input (principal and apr) also are done in a graphical fashion using Entry objects.(Section 5.10 Programming Exercises 6)2. Five-click house. You are to write a program that allows the user to draw a simple house using five mouse-clicks. The first two clicks will be the opposite corners of the rectangular frame of the house. The third click will indicate the center of the top edge of a rectangular door. The door should have a total width that is of the width of the house frame. The sides of the door should extend from the corners of the top down to the bottom of the frame. The fourth click will indicate the center of a square window. The window is half as wide as the door. The last click will indicate the peak of the roof. The edges of the roof will extend from the point at the peak to the corners of the top edge of the house frame. (Section 5.8 Programming Exercises 4)3. (Advanced) (Section 5.8 Programming Exercises 13)1. Rectangle Information.This program displays information about a rectangle drawn by the user. ?Input: 2 mouse clicks for the opposite corners of a rectangle. 73660021526500Output: Draw the rectangle. Print the perimeter and area of the rectangle. Formulas: (Section 5.10 Programming Exercises 9)?2. Circle Intersection.Write a program that computes the intersection of a circle with a horizontal line and displays the information textually and graphically. ?Input: Radius of the circle and the y-intercept of the line. ?Output: Draw a circle centered at (0, 0) with the given radius in a window with coordinates running from -10, -10 to 10, 10.?Draw a horizontal line across the window with the given y-intercept. ?Draw the two points of intersection in red.?Print out the x values of the points of intersection. Formula: 6686556667500(Section 5.10 Programming Exercises 2)?3. (Advanced) (Section 5.10 Programming Exercises 13)An archery target consists of a central circle of yellow surrounded by con- centric rings of red, blue, black and white. Each ring has the same “width,” which is the same as the radius of the yellow circle. Write a program that draws such a target. Hint: Objects drawn later will appear on top of objects drawn earlier.2016.11.24 Practice51. Rectangle Information.This program displays information about a rectangle drawn by the user. ?Input: 2 mouse clicks for the opposite corners of a rectangle. 73660021526500Output: Draw the rectangle. Print the perimeter and area of the rectangle. Formulas: (Section 5.10 Programming Exercises 9)?2. Circle Intersection.Write a program that computes the intersection of a circle with a horizontal line and displays the information textually and graphically. ?Input: Radius of the circle and the y-intercept of the line. ?Output: Draw a circle centered at (0, 0) with the given radius in a window with coordinates running from -10, -10 to 10, 10.?Draw a horizontal line across the window with the given y-intercept. ?Draw the two points of intersection in red.?Print out the x values of the points of intersection. Formula: 6686556667500(Section 5.10 Programming Exercises 2)?3. (Advanced) (Section 5.10 Programming Exercises 13)An archery target consists of a central circle of yellow surrounded by concentric rings of red, blue, black and white. Each ring has the same “width,” which is the same as the radius of the yellow circle. Write a program that draws such a target. Hint: Objects drawn later will appear on top of objects drawn earlier.2016/11/29 Homework91. Here is a simple class that draws a (grim) face in a graphics window.Add methods to this class that cause the face to change expression. For example you might add methods such as smile, wink, frown, flinch, etc. Your class should implement at least three such methods. Use your class to write a program that draws a face and provides the user with buttons to change the facial expression. (Section 10.8 Programming Problems 13)2. Modify the face class from the previous problem to include a method similar to other graphics objects. Using the move method, create a program that makes a face bounce around in a window (see Programming Exercise 17 from Chapter 7). Bonus: have the face change expression each time it “hits” the edge of the window. (Section 10.8 Programming Problems 14)2016/12/6 Homework10Write a program that simulates an Automatic Teller Machine (ATM). Since you probably don’t have access to a card reader, have the initial screen ask for user id and a PIN. The user id will be used to look up the info for the user’s accounts (including the PIN to see if it matches what the user types). Each user will have access to a checking account and a savings account. The user should able to check balances, withdraw cash, and transfer money between accounts. Design your interface to be similar to what you see on your local ATM. The user account information should be stored in a file when the program terminates. This file is read in again when the program restarts. (Section 12.6 Programming Problems 4)2016.12.8 Practice 61. Write a class to represent the geometric solid sphere. Your class should implement the following methods: ?Creates a sphere having the given radius. Returns the radius of this sphere. ?Returns the surface area of the sphere. Returns the volume of the sphere. ?Use your new class to Write a program to calculate the volume and surface area of a sphere from its radius, given as input. (Section 10.8 Programming Problems 9)2. Most languages do not have the flexible built-in list (array) operations that Python has. Write an algorithm for each of the following Python operations and test your algorithm by writing it up in a suitable function. For example, as a function, reverse(myList) should do the same as myList.reverse(). Obviously, you are not allowed to use the corresponding Python method to implement your function.(a) count(myList, x) (like myList.count(x)) (b) isin(myList, x) (like x in myList))(c) index(myList, x) (like myList.index(x))(d) reverse(myList) (like myList.reverse()) (e) sort(myList) (like myList.sort())(Section 11.8 Programming Problems 5)3. Create a class called StatSet that can be used to do simple statistical calculations. The methods for the class are: ?__init__(self) : Creates a statSet with no data in it.?addNumber(self, x): x is a number. Adds the value x to the statSet. ?mean(self): Returns the mean of the numbers in this statSet.?median(self): Returns the median of the numbers in this statSet.?stdDev(self): Returns the standard deviation of the numbers in this statSet.count(self): Returns the count of numbers in this statSet. min(self):Returns the smallest value in this statSet. max(self): Returns the largest value in this statSet. ?Test your class with a program similar to the simple statistics program from this chapter. ?(Section 11.8 Programming Problems 16)2016/12/13 Homework111. 实现class queueenqueue(self, item)dequeue(self)isEmpty(self)getLen(self)2. Create and test a Set class to represent a classical set. Your sets should support the following methods: Set(elements) Create a set (elements is the initial list of items in the set). addElement(x) Adds x to the set.?deleteElement(x) Removes x from the set, if present. If x is not in the set, the set is left unchanged. member(x) Returns true if x is in the set and false otherwise.intersection(set2) Returns a new set containing just those elements that are common to this set and set2. union(set2) Returns a new set containing all of elements that are in this set, set2, or both. subtract(set2) Returns a new set containing all the elements of this set that are not in set2. (Section 11.8 Programming Problems 19)2016/12/20 Homework12真题2016/12/22 Practice 71. 编写一个程序,分析并打印英文的文本文件中包含的单词和对应的频度,其中单词是由空格或者换行符分隔。具体要求如下:(1)实现函数count_words(ss, dd),分析并统计一个文本行ss中包含的单词,以及频度,计入字典dd中。(2)实现函数dict_sort(dd),将dd中的单词按照频度降序排列。提示:从字典dd中提取信息到列表L,然后对列表L进行排序。(3)实现函数main(),打开用户输入的文件,从中逐行读入文本,调用(1)中的函数,统计整个文件中的单词和对应的频度,调用(2)中的函数,整理单词,继而打印之。2. 编写函数count_in_list(A, x),对给定的列表A统计x的出现次数。注意:列表A的元素可以是一个列表。并在原地访问A的元素,不能改变A,不能使用全局变量或者局部函数。程序处理的时间复杂度不高于O(n)3. 实现时钟类型Clock:class Clock: def __init__(self, h=0, m=0, s=0):self. hour, slef.minute, self.second = h, m, s def getTime(self):return def __add__(self, c2):h = self.hour + c2.Hourm = self.minute + c2.minutes = self.second + c2.second def __str__(self):return “ ” % self. getTime()def main(): c1=Clock(10, 20, 30) c2=Clock(1, 2, 3) c3=c1+c2 print c3main()output: (11 : 22 : 33) ................
................

In order to avoid copyright disputes, this page is only a partial summary.

Google Online Preview   Download