上海交通大学python期末考试样题加解析
- 格式:docx
- 大小:18.17 KB
- 文档页数:6
上海交大程序设计python期末测验题Python是一种简单易学、高效可靠的编程语言,广泛用于各种领域的开发和实践。
作为上海交大程序设计课程的期末测验题,该测试旨在评估学生对Python编程的掌握程度和应用能力。
本文将按照测试题的要求,分析和解答各个问题,展示学生在程序设计方面的能力。
第一题:编写程序,实现计算两个数的乘积解答:```pythonnum1 = float(input("请输入第一个数:"))num2 = float(input("请输入第二个数:"))result = num1 * num2print("两个数的乘积为:", result)```对于这道题目,我们需要从用户输入中获取两个数,通过乘法运算符将它们相乘,并将结果输出。
以上代码实现了这一功能。
第二题:编写程序,实现对一个整数列表的排序解答:```pythonnums = [5, 3, 8, 2, 1]nums.sort()print("排序后的列表:", nums)```这道题目要求我们对一个整数列表进行排序。
Python提供了list的sort()方法,可以直接对列表进行排序。
以上代码对给定的整数列表进行了排序,并将结果输出。
第三题:编写程序,实现一个简单的猜数字游戏解答:```pythonimport randomtarget = random.randint(1, 100)guess = int(input("请猜一个1到100之间的整数:"))if guess > target:print("猜大了!")elif guess < target:print("猜小了!")else:print("恭喜你,猜对了!")```这道题目要求我们编写一个猜数字游戏,程序随机生成一个1到100之间的整数,用户猜测这个数字是多少,程序根据猜测结果给予提示。
Python语言期末考试试卷及答案本次考试总分100分,共10道题,每题10分。
1. 下面哪个是Python的基本数据类型?A. intB. floatC. boolD. all of the above答案:D2. 输出以下代码的结果:a = ["apple", "banana", "cherry"]print(len(a))答案:33. 输出以下代码的结果:x = 5y = 3print(x % y)答案:24. 以下哪个方法可以在Python中打开文件?A. open()B. close()C. read()D. write()答案:A5. 输出以下代码的结果:a = ["apple", "banana", "cherry"]print(a[-1])答案:cherry6. 下面哪个Python模块可以帮助实现正则表达式?A. reB. osC. sysD. math答案:A7. 输出以下代码的结果:x = 2if x < 10:print("x is less than 10")else:print("x is greater or equal to 10")答案:x is less than 108. 以下哪个是Python中的循环语句?A. forB. ifC. elseD. try答案:A9. 输出以下代码的结果:x = 1while x < 5:x += 1print(x)答案:510. 以下哪个是Python中的内置函数?A. print()B. len()C. range()D. all of the above答案:D。
python期末试卷试题及答案一、选择题(每题10分,共20题)1.以下哪个是Python的关键字?A. mainB. forC. whileD. switch答案:B2.Python中用来定义一个函数的关键字是:A. defB. functionC. defineD. func答案:A3.Python中可以表示真或假的两个特殊值是:A. true 和 falseB. yes 和 noC. on 和 off答案:A4.以下关于Python列表的描述正确的是:A. 列表内的元素可以是不同类型的B. 列表内的元素只能是相同类型的C. 列表内的元素不能修改D. 列表内的元素是有序的答案:A5.Python中用来读取用户输入的函数是:A. input()B. print()C. read()D. scan()答案:A6.Python中的循环语句是:A. forB. whileC. loop答案:A、B7.Python中用来分割字符串的方法是:A. split()B. strip()C. slice()D. divide()答案:A8.Python中用来连接字符串的符号是:A. +B. -C. *D. /答案:A9.Python中的if语句后面要加上:A. 逗号B. 冒号C. 分号答案:B10.Python中用来定义一个类的关键字是:A. defB. classC. funcD. object答案:B二、填空题(每题10分,共5题)1.Python的注释符号是_________。
答案:#2.Python的逻辑与运算符是_________。
答案:and3.Python中用来取绝对值的方法是_________。
答案:abs()4.Python中用来计算列表长度的函数是_________。
答案:len()5.Python中用来获取用户输入的函数是_________。
答案:input()三、简答题(每题20分,共4题)1.请简要概述Python的特点。
python期末考试题及答案详解Python期末考试题及答案详解一、选择题(每题2分,共20分)1. 下列哪个是Python的内置数据类型?A. ListB. ArrayC. SetD. Vector答案:A2. Python中的函数定义关键字是什么?A. defineB. functionC. methodD. procedure答案:B3. 在Python中,哪个操作符用于获取列表中元素的长度?A. len()B. size()C. count()D. length()答案:A4. 下列哪个语句可以遍历列表中的每个元素?A. for item in listB. for item = listC. for list in itemD. for item = 0 to list答案:A5. 在Python中,哪个关键字用于定义类?A. classB. typeC. structD. object答案:A6. 下列哪个是Python中的异常处理语句?A. try-exceptB. if-elseC. switch-caseD. while-do答案:A7. 在Python中,如何将整数转换为字符串?A. int_to_str()B. str()C. to_string()D. string()答案:B8. 下列哪个是Python的文件操作模式,用于写入?A. 'r'B. 'w'C. 'a'D. 'rb'答案:B9. Python中的列表推导式是用于什么?A. 循环遍历列表B. 列表排序C. 创建列表D. 列表去重答案:C10. 下列哪个是Python的装饰器语法?A. @functionB. function()C. @decoratorD. decorator()答案:C二、简答题(每题5分,共30分)1. 请简述Python中列表和元组的区别。
《Python程序设计基础》测试题参考答案一、单项选择题(每个2分,共20分)1.B 2.B 3. B 4.D 5.C6. A7. C8.B9.C 10.D二、填空题(每个空1.5分,共15分)1.(pyc)2.(None)3.(9)4.(’11’)5.(def)6.(global)7.(break)8.(5)9. (join())10.(3)三、判断题(每个1.5分,共15分)1.(对)2.(错)3.(错)4.(对)5.(对)6.(对)7.(对)8.(对)9.(错)10.(对)四、简答题(每个5分,共10分)1. Python采用的是基于值得内存管理方式,在Python中可以为不同变量赋值为相同值,这个值在内存中只有一份,多个变量指向同一个内存地址;Python具有自动内存管理功能,会自动跟踪内存中所有的值,对于没有任何变量指向的值,Python自动将其删除。
2.异常是指因为程序执行过程中出错而在正常控制流以外采取的行为。
严格来说,语法错误和逻辑错误不属于异常,但有些语法错误往往会导致异常,例如由于大小写拼写错误而访问不存在的对象,或者试图访问不存在的文件,等等。
五、读程序题(每个5分,共20分)1.答:a,b,ca:b:c2.答:1316153. 写出下面代码的执行结果。
答:-34.说出下面代码所实现的主要功能。
答:冒泡排序法对一组数据从小到大的顺序排列。
六、编程题(每个10分,共20分)1.for i in range(1000):if i<100:continues = 0a = int(i//100)b = int(i//10%10)c = int(i%10)s = a**3+b**3+c**3if s == i:print("{} 是水仙花数".format(i))2.#coding=utf-8customer_price=float(raw_input("please input pay money:")) if customer_price >=50 and customer_price<=100:print "disconunt 10%% ,after discount you shoud pay %s" \ %(customer_price*(1-0.1))elif customer_price >100:print "disconunt 20%% ,after discount you shoud pay %s" \ %(customer_price*(1-0.2))else:print "disconunt 0%% ,after discount you shoud pay %s" \%customer_price。
大学Python期末考试试题带答案一、选择题1. 下列哪个是Python的整数除法符号?a. %b. //c. /d. *答案:b. //2. 在Python中,以下哪个是合法的变量名?a. 2myVarb. my_varc. my-vard. my var答案:b. my_var3. 下列哪个关键字用于定义一个函数?a. returnb. ifc. defd. for答案:c. def4. 在Python中,以下哪个是用于打开文件的关键字?a. closeb. fetchc. opend. save答案:c. open5. 以下哪种数据类型不能被修改?a. listb. tuplec. dictionaryd. set答案:b. tuple二、填空题1. 完成下列代码,使其输出"Hello, World!"。
print(_____)答案:print("Hello, World!")2. 创建一个名为`my_list`的空列表。
答案:my_list = []3. 完成下列代码,使其输出字典中键值对的数量。
my_dict = {"a": 10, "b": 20, "c": 30}print(_____)答案:print(len(my_dict))4. 编写一个`for`循环,打印出列表`my_list`中的每个元素。
my_list = [1, 2, 3, 4, 5]for item in my_list:print(_____)答案:print(item)5. 完成下列代码,使其将输入的字符串转换为大写并打印输出。
input_str = input("请输入字符串:")print(_____)答案:print(input_str.upper())三、简答题1. 请简要介绍Python的特点。
python期末笔试题及答案在本文中,我将为您提供一份Python期末笔试题及答案。
我会按照考试试卷的格式,分为多个小节来介绍这些问题,并提供相应的答案。
请您随时跟随文中的指导进行阅读。
一、选择题1. 下列哪个选项不是Python的基本数据类型?A. 整数B. 浮点数C. 字符串D. 列表【答案】D2. 在Python中,如何获取用户的输入?A. input()B. print()C. get()D. read()【答案】A3. 下面哪个选项可以用于循环执行代码块?A. forB. ifC. inD. else【答案】A二、填空题1. 在Python中,用于表示真值的关键字是____。
【答案】True/False2. 使用____可以将多个字符串连接成一个字符串。
【答案】"+" (加号)3. __________ 是一种用于存储多个数据的有序集合。
【答案】列表/List三、简答题1. 请简要介绍Python的特点和优势。
【答案】Python是一种简单易学、可读性强的编程语言。
它具有以下特点和优势:- 语法简洁清晰,代码易于编写和理解;- 内置丰富的函数和模块,使开发人员能够更快速地实现功能;- 库和框架众多,使得扩展和开发更加方便;- 跨平台性强,可以运行在多个操作系统上;- 具有良好的可移植性,可以轻松地将代码迁移到其他系统上;- 社区活跃,拥有众多的资源和支持。
2. 简要解释Python中的异常处理机制。
【答案】在Python中,可以使用try-except语句来处理可能发生的异常。
try块中的代码用于执行可能引发异常的操作,而except块中的代码则定义了当发生异常时应该执行的操作。
通过使用异常处理机制,我们可以优雅地处理程序中的错误,确保程序能够继续执行而不中断。
3. 请简要介绍Python中的面向对象编程(OOP)。
【答案】面向对象编程是一种程序设计范例,旨在通过将数据和方法封装在对象中,以实现更清晰、模块化的代码结构。
Python期末测试试卷(A卷)姓名:___________班级:___________分数:___________【满分:时间:90分钟】一、选择题(40分,每题2分)1. Python面向对象的特征不包括()A. 封装B. 继承C. 多态D. 定义【答案】D【解析】面向对象的特征是:封装、继承和多态。
2. Python源代码程序编译后的文件扩展名为()。
A. .pyB. .cC. .javaD. .php【答案】A【解析】A 正确Python源代码文件扩展名为.py。
B 错误C语言源代码文件扩展名为.c。
C 错误Java源代码文件扩展名是.java。
D 错误PHP源代码文件扩展名是.php。
3.Python单行注释使用的是那个符号()。
A. ( )B. “ ”C. ,D. #【答案】D【解析】A 错误Python中内置函数使用括号( )表示。
B 错误Python字符串需要用单引号或双引号括起来。
C 错误Python可以接受多个字符串的输入和输出,中间用”,”隔开即可。
D 正确Python中的注释起提示作用,单行注释以#开头。
4.关于字符串下列说法错误的是()。
A. 字符应该视为长度为1的字符串B. 字符串以\0标志字符串的结束C. 既可以用单引号,也可以用双引号创建字符串D. 在三引号字符串中可以包含换行回车等特殊字符【答案】B【解析】Python字符串其实是一个固定长度的字符数组,所以不用结束标志。
5. Python语言语句块的标记是()。
A. 分号B. 逗号C. 缩进D. /【答案】C【解析】Python在程序编写的过程中严格遵守缩进原则。
6. 下面哪个不是Python合法的变量名()。
A. int_32B. 40YLC. priceD. _name_【答案】B【解析】变量名只能是字母、数字或下划线的任意组合,但是变量名首字符不能是数字。
7. 关于流程图的常用标识,以下选项中描述错误的是()。
大学python期末试题及答案一、选择题(每题2分,共20分)1. Python中,以下哪个关键字用于定义函数?A. defB. ifC. forD. while答案:A2. 在Python中,以下哪个方法用于获取列表中的最大值?A. max()B. min()C. sum()D. len()答案:A3. 下列哪个选项是Python中的注释方式?A. //B.C.D. //答案:D4. 在Python中,以下哪个选项不是内置数据类型?A. intB. listC. dictD. class答案:D5. Python中,以下哪个选项用于实现循环结构?A. ifB. forC. whileD. both B and C答案:D6. 在Python中,以下哪个选项用于定义类?A. classB. defC. importD. from答案:A7. Python中,以下哪个选项用于实现异常处理?A. try...except...B. if...else...C. for...in...D. while...loop...答案:A8. 在Python中,以下哪个选项用于定义列表推导式?A. [x for x in range(10)]B. {x for x in range(10)}C. (x for x in range(10))D. all of the above答案:A9. Python中,以下哪个选项用于实现元组推导式?A. [x for x in range(10)]B. (x for x in range(10))C. {x for x in range(10)}D. all of the above答案:B10. 在Python中,以下哪个选项用于实现字典推导式?A. [x for x in range(10)]B. {x: x2 for x in range(10)}C. (x for x in range(10))D. all of the above答案:B二、填空题(每题2分,共20分)1. Python中,用于定义空列表的语法是________。
Project ASimulating a Physical SystemIntroductionYou have already seen a number of examples using randomization to solve problems and to generate experimental results. In the percolation project, grids were generated according to a specified probability distribution to experimentally determine the percolation probability. This approach is an example of a Monte Carlo method, an algorithm that relies on repeated random sampling to compute results. Monte Carlo methods are often used for simulating physical and mathematical systems when other methods are impossible or computationally infeasible.Objective and BackgroundThe objective of this project is to use the Monte Carlo “demon algorithm” to estimate parameters (for example, temperature) in a physical system, specifically an ideal gas with moving molecules. We could simulate such a system by computing the pairwise interactions among all molecules at every time step in the simulation, but that approach would be computationally intractable. Moreover, in these systems we're not typically interested in the specific behavior of each individual molecule, but rather in the overall system behavior. For example, we want to know the expected distribution of molecule velocities in a gas (e.g., to understand its temperature), not which molecules have collided with which other molecules.The key concept behind the demon algorithm is that any simulation must both preserve the total energy of the system (energy is conserved) and insure that no particle winds up with negative kinetic energy. The algorithm proceeds by choosing a molecule at random and proposing to make a small random change to its energy (e.g., to simulate the effect of a collision). To compensate for the change in energy of the molecule / particle, the oppos ite change is made to a special “demon” molecule, thus conserving the total energy of the system. Note that the demon molecule is never chosen at random for this change; it only acts to store the difference between the system energy and the total energy.Before describing the demon algorithm in detail, we give a brief description of the system to be simulated. In the ideal gas, we want to study the velocity of molecules in the gas. This average velocity gives a measure of the temperature of the gas. Consider the state of the gas in an insulated container at an instant of time. Each of its molecules has some velocity that remains constant until the next collision involving the molecules. Because the molecules move quickly, on average, many of them will have experienced collisions during a short time span. Consequently, most of the molecules will have substantially different velocities than they originally did. This process can, in principle, be simulated directly. In practice, doing so is computationally too expensive or is infeasible (e.g., one step of the situation could mean solving n differential equations, with each equation having n² terms).Sketch of Demon AlgorithmThe demon algorithm is a common technique for simulating selected parameters of a complex system by maintaining a given macroscopic (total) energy, while randomly changing the microstate of the system. If a trial change would result in a reduction of energy in the system, additional energy is given to a demon (fictitious). If the change would result in additional system energy, the difference is taken from the demon (assuming it has sufficient energy). In our simulation, making a trial change will refer to changing a particle's velocity.Initialize the system state. The sum of the system energy and the demon energy always equals the specified total energy. The demon energy must always be non-negative.Execute one simulation step. One simulation step consists of making a specified number of trials, with each trial doing the following: Make a change to the state of the system and record the change in system energy as deltaEnergy. If the change is legitimate, i.e., if the demon energy resulting from making the change is non-negative, the change is accepted and we set demonEnergy = demonEnergy - deltaEnergysystemEnergy = systemEnergy + deltaEnergyUpdate any parameters to be maintained during the simulation.Repeat making trials until one simulation step is complete.After one simulation step, update any additional parameters. Execute as many simulation steps as specified.It is not obvious that this process can effectively simulate a physical system. In fact, there is no rigorous proof that it does. In practice, however, this algorithm works very well. The first part of the project uses the demon algorithm in an ideal gas simulation.Ideal Gas SimulationAn ideal gas is a simple, uniform system: Molecules with energy are bouncing around inside a closed container. The internal molecular dynamics is simple –free motion with occasional intermolecular collisions. When using the demon algorithm for a simulation, we view the result of a collision as a random change of the molecule's velocity. Each molecule has a particular momentum, and collisions exchange part of that momentum.Consider the velocity of a single molecule over time. Each collision can be thought of as a random change in velocity. Since we are interested in the average velocity of all molecules, the exact number and time of the collisions is not important. Rather, what matters is the total change in velocity over the time period we are considering. The demon algorithm takes advantage of this idea. We choose a total energy for the system (view it as the temperature). One step of the simulation consists of a number of trials. One trial perturbs the velocity of a random molecule by a random amount. The change is accepted if system and demon energy are less than the total energy. The difference between the system energy and the total energy is held by the algorithm’s namesake, the demon.Your first task is to write an ideal gas simulator that uses the demon algorithm. Download the demon.py file to begin your work. The ideal gas simulator should be written in a function that isalready defined for you as ideal_gas:def ideal_gas(N, totalEnergy, steps, state = 1, visuals = True):...The arguments to the function are as follows:N: The number of molecules in the systemtotalEnergy: The total amount of energy. That is, the energy of the N molecules + the demon energy.steps: The number of steps to execute. Each step consists of N demon trials, as described below. state: The initial state of the molecules, which can be one or two.visuals: Whether or not to draw visuals for the simulation, which are described in the next section.The energy of the system state is fully described by the molecular velocities. Recall that the energy of a moving molecule is ½mv², where m is the mass of the molecule and v is the velocity. For our simulation, assume unit mass (i.e., m = 1). Steps 1 and 2 of the demon algorithm now look as follows. Your function should do the following:Initialize the system state according to the state argument passed to the function. Since the function only accepts a number of molecules to simulate, you must set initial velocities for each molecule. The state variable determines whether or not the demon begins with all or none of totalEnergy:If state == 1, we will give each molecule the same velocity. Since the energies given the velocities must sum up to totalEnergy (our demon initially has no energy), this means that each molecule starts with a velocity of sqrt(2 * totalEnergy / N).If state == 2, we simply set all molecule velocities to zero and give the demon all of the energy. Create a loop that will execute step iterations. Each iteration executes N trials, so we describe one trial:Choose a random molecule (remember, the demon cannot be chosen here)Generate a random number between -Dv and Dv, where Dv is the velocity corresponding to 10% of the total system energy divided by N. Thus, Dv = sqrt(2 * totalEnergy / N / 10).Calculate the change in energy. Since we use unit mass (m = 1), the change in energy is deltaEnergy = vNew² / 2 - vOld² / 2.If the change in energy is valid, then accept the change in velocity for that molecule. Remember that the change in energy is valid as long as the resulting demon energy is non-negative. Because not every change is legal, every iteration may not change N molecules, even though it executes N trials.The demon and system energies must be updated to use in the next trial. However, since we must generate visuals for the next part of the project, we need to record these values in a list to keep track of the value at each iteration (not trial).Calculate the average system energy and return it.Experiments for the Ideal Gas SimulationFirst, write and test the function ideal_gas. Note that in this project you will be handing in the function and the experimental work at the same time. Test the function ideal_gas with small values of N and small values of step. You won't know that you are computing the correct quantities until you generate the plots described next. Test the function with both initial system states.Your experimental work should consider systems with N= 50 to 500, with an increment of 50. For each N, run the function ideal_gas with steps = 3000 and totalEnergy = 500. Each experiment should be done for each of the two initial system states.The simulation can use MatPlotLib or VPython. Warning: If you use VPython, you should remove all traces of MatPlotLib from the skeleton code. The two have not been known to play well together. A starting point for the varying values of N is provided in the main of the skeleton code. This part of the project requires you to write code to draw two graphs and two histograms.The main of the simulation uses the values returned by ideal_gas to generate the graph N_versus_Energy.The value returned by the function ideal_gas represents the average system energy of a simulation with particular value of N. You should graph the average system energy on the y-axis and N on the x-axis. In the same plot, show the total system energy in a different color (in the required experiment it is 500 for every value of N). You can generate the plot after the entire simulation or generate it incrementally after ideal_gas returns a value. Here is an example plot. nvsenergy1.pngThe ideal_gas function should generate two histograms and one graph. Whether and when these plots are generated is determined by the fifth parameter (visuals) of ideal_gas. For example, ideal_gas(N, 500, 3000, 2, N==500) will generate plots only when N=500 and start in initial state 2. Note that omitting the 5th argument will plot every time ideal_gas is called.Histogram Final_Molecule_Velocity uses the values of the N molecule velocities after steps iterations of ideal_gas (i.e., the values just before ideal_gas returns). Plot the velocities on x-axis and their frequencies on y-axis. You should use the signed velocities and 0 is thus in the center of the x-axis. You should experiment with the most appropriate number of bins. Here is an example plot. velocitydistr1.pngHistogram Demon_Energy generates a histogram of the observed demon energy. The plot is generated after the steps of ideal_gas are completed. The demon energy is recorded after each simulation step (using a list or array of size step). Show the demon energies on the x-axis and their frequencies on the y-axis. Again, select an appropriate number of bins. Here is an example plot.demonenergy1.pngGraph Demon_Energy_Time shows the steps demon energies over time. The graph has values from 1 to steps on the x-axis and the corresponding demon energies on the y-axis. Make sure to show these 3000 steps in an effective way.If you are using VPython, you can show a histogram plot as soon you have data needed. If you areusing Matplotlib, the interactive option allows showing results during the computation (SeeInteractive Matplotlib):Interactive MatplotlibNormally, matplotlib will not show plots until you call pylab.show(). However, if you callpylab.ion() before plotting, matplotlib will show the window immediately. For best results,decorate (set title, axis labels, etc) after calling pylab.plot().Example code:import pylabxs = []ys = []pylab.ion()for x in range(10):xs.append(x)ys.append(x ** 2)pylab.plot(xs, ys, 'b-o')pylab.pause(1)pylab.title("curve of x squared")pylab.xlabel("x")pylab.ylabel("x ** 2")pylab.show()pylab.pause(10)pylab.close()DiscussionYou need to hand in a discussion of your experimental results. The following questions should be addressed:In graph N_versus_Energy, how close is the actual system energy to the total energy? How does it change as N changes? How do the plots differ for the two different initial system states?Using histogram Final_Particle_Velocity, what kind of distribution do you judge the velocities to come from? How close is the molecule velocity to the initial velocity of sqrt(2*totalEnergy/N) used in initial state 1?Using histogram Demon_Energy, what kind of distribution do you judge the demon energies to come from?Comment of the differences and similarities of graph Demon_Energy_Time for different values of N and the two initial states.Submission InstructionsSubmit a program including the function ideal_gas, the main function driving the simulation in demon.py. Your program will contain the loop for the values of N considered. The rest of the code will differ significantly between students depending how the visualization is handled (such as building a user interface for displaying menus and the above graphs). You also need to include a PDF file (*.pdf) that includes a final report with the discussion of your experiment and answers the questions listed (The format of the final report is shown below). These files should all be placed into one folder in a compressed file (e.g. 5120309000_XXX(team_projA_v3).rar) and submitted to the course representative of your class. The course representatives compress all of them with a *.rar file and upload it in the subdirectory team_projA.The deadline is due the midnight on Jan. 3, 2014.ReferencesComputational Physics. /wiki/Computational_physics/Fredrik Lundh. An Introduction to Tkinter. 1999.Matplotlib. /matplotlib-1.2.0.win32-py3.2.exe. /~gohlke/pythonlibs/Molecular Dynamics. /wiki/Molecular_dynamics/Monte Carlo Method. /wiki/Monte_Carlo_method/Numpy: The Fundamental Package for Scientific Computing with Python. / numpy-MKL-1.6.2.win32-py3.2.exe. /~gohlke/pythonlibs/Tkinter./moin/TkInter/Tkinter Documentation. 2010. /moin/TkInterVPython: 3D Programming for Ordinary Mortals. /VPython-5.74.win32-py3.2.exe. /~gohlke/pythonlibs/ Appendix: Final Report FormatTeam Name: Team Leader:Date:1 Prototype System Introduction1.1 Functions1.2 Running EnvironmentWindows 71.3 Developing EnvironmentPyScripter 2.5.3…2 Task AllocationThe tasks for each team member.3 System Architecture3.1 User Interface ComponentGraph and explanation.3.2 Simulation ComponentGraph and explanation.3.3 Visualization ComponentGraph and explanation.4 Algorithm Description4.1 User Interface ComponentFlowchart and explanation.4.2 Simulation ComponentFlowchart and explanation.4.3 Visualization ComponentFlowchart and explanation.5 Demo and Testing Result5.1 ScreenshotsUser interface and every operation.5.2 Testing Procedure, Data and ResultExplanation, testing data and result table, and result analysis6 ConclusionThe discussion of your experiment and answers the questions listed above.What is your research result? What are your experience and lesson on this project?。
上海交通大学试卷(A 卷)
(2010 至2011学年第2学期)
班级号______________________ 学号____________________ 姓名_______________ 课程名称程序设计思想和方法成绩
一、选择题:将唯一正确的选项写在题前括号中.每题2分.
【】(1)本课程的目标定位是什么?
[A] 学习Python 语言
[B] 学习计算机的工作原理
[C] 学习各种算法
[D] 学习用计算机解决问题
【】(2)下列哪个标识符是合法的?
[A] var-n ame [B] !@#$% [C]. _100 [D] elif
【】(3)执行下列语句后的显示结果是什么?
>>> s = ” hi ”
>>> print “hi” , 2*s
[A] hihihi [B] ” hi ” hihi [C] hi hihi
[D] hi hi hi
【】(4)如何解释下面的执行结果?
>>> pri nt 1.2 - 1.0 == 0.2
False
[A] Python 的实现有错误
[B] 浮点数无法精确表示
[C] 布尔运算不能用于浮点数比较
[D] Python 将非0数视为False
【】(5)想用一个变量来表示出生年份,下列命名中哪个最可取?
[A] b_y [B] birth_year [C] _birthYear_ [D] birthyear
【】(6)执行下列语句后的显示结果是什么
>>> a = 1
>>> b = 2 * a / 4
>>> a = 'One ”
>>> pri nt a,b
[A] o ne 0 [B] 1 0 [C] o ne 0.5 [D] o ne,0.5
【】(7)执行下列语句后的显示结果是什么
>>> s = ” GOOD MORNING'
>>> print s[3:-4]
[A] D MOR [B] D MORN [C] OD MOR [D] OD MORN
【】(8)表达式1+2L*3.14>0 的结果类型是
[A] int [B] lo ng [C] float [D] bool
【】(9) 程序设计的原型(Prototyping) 方法是指:
[A] 先设计程序框架结构,再逐步精化细节
[B] 先设计类,再实例化为对象
[C] 先设计简单版本,再逐步增加功能
[D] 以上都不是
【】(10) 对n个数做归并排序(merge sort), 这个算法是
[A] log n时间的[B] 线性时间的[C] nlog n时间的[D] n2时间的
二、判断题:在题目前面的括号中打勾或叉•每题2分.
[】(1) 高级语言程序要被机器执行,只有用解释器来解释执行•
[】⑵不同类型的数据不能相互运算•
[】⑶由于引号表示字符串的开始和结束,所以字符串本身不能包含引号
[】⑷计算机科学并非研究计算机的科学,正如天文学并非研究望远镜
[】(5) 算法和程序是不同的概念.
[】下面的程序段是错的:
temp = 42
print "The temperature is" + temp
【】(7)同一Python变量可以先后赋予不同类型的值.
【】(8)计算机的计算是确定的,因此并不能真正产生随机数
【】(9)对象就是类的实例.
【】(10) Hanoi 塔问题属于不可解问题.
(10) Pyth on
的标准随机数生成器模块是
四、读程序并回答问题:每题5分.
(1) 下面的程序根据用户输入的三个边长 之.(设用户输入合法,面积公式无误) import math a, b, c = raw_ in put( En ter a,b,c: s = a + b + c s = s / 2.0
area = sqrt(s*(s-a)*(s-b)*(s-c))
print The area is: ”,area 将 raw_ in put 改成 in put 将 sqrt 改成 math.sqrt
(2) 下面的程序要求用户输入二进制数字 bit = in put( En ter a binary digit:
if bit = 0 or 1:
print Your in put is: ”,bit
else
print Your in put is in valid.
0/1并显示之.找出程序中的错误并改正之
将 bit = 0 or 1 将 else 改成 else:
三、填空题:每题2分. 表达式2**3*4%5 的值为: 函数 range(1,1,1)
的值是:
格式化输出浮点数 :宽度10,2位小数,左对齐,则格式串为: 表达式chr(ord(
a ')的值为:
(5) 表达式((2>=2) or (2<2)) and 2 的值为:
无穷循环while True: 的循环体中可用
语句退出循环.
不用math 模块中的sqrt(),
如何计算 4的平方根:
(8) 给出一个计算机本质上不可解问题的例子
(9) 表达式%d%%%'%(1%2,3%4)的值为:
a,b,c 来计算三角形面积•请找出程序中的错误并改正
”)
改成 bit == 0 or bit== 1
(3) 下面程序的输出是什么?
def f(a, b, c):
x = y = 0
for i in ran ge(c):
x = x + a + y
y = y + b return x
print f(-5, 2, 10)
注意return x 在for的缩进里面,所以最后只有一个数据输出range(10) 其实是从0开始计数到9
再不断迭代即可
(4) 下面程序的输出是什么?
def f(a,b):
a = 4
print a, b
def main():
a = 5
b = 6
print a, b
f(a,b)
print a, b
mai n()
56
46
56
(5) 下面程序的功能是什么?
def f(a, b):
if b == 0:
pri nt a
else:
f(b, a%b)
a, b = in put( “ En ter two n atural nu mbers: ”)
print f(a, b)
求最大公因式
A 卷总5 页第_4_页
五、程序设计:15分.
(1)用分而治之(divide and conquer) 和递归方法设计程序:产生并打印一个序列的全排列
例如,序列[1,2,3]的全排列123,132,213,231,312,321 可以这样获得: 1为前缀,后接[2,3]的全排列
2为前缀,后接[1,3]的全排列
3为前缀,后接[1,2]的全排列
而[2,3]等序列的全排列依此类推.
下面给出了这个程序的部分代码,在理解上述算法的基础上补足所缺的代码•#函数perm(list,k,m): 产生前缀为list[O:k]后接list[k:m+1]的全排列def perm(list,k,m):
if k == m:
for i in ran ge(m+1) ①:
pr int list[i], pri nt else:
for i in ran ge(k,m+1) ②:
list[k],list[i] = list[i],list[k]
perm(list,k+1,m) ③
list[k],list[i] = list[i],list[k] myList =
in put( “n put a list([1,2,3, ...]):
perm(myList,O, len (myList)-1 ■④)
(2)编写程序:输入一个文件A, A中每行包含若干数值.生成文件B, B中每行是A中对应行的数值的平均值.
Import str ing
fileA = raw_input( Enter a data file: ”)
in file = open(fileA,'')
outfile = open ( B.dat','w')
line = in file.readli ne() while line != “":
sum = 0.0
count = 0
for xStr in str in g.split(li ne):
sum = sum + eval(xStr) count = count + 1
avg = sum/co unt
outfile.write(str(avg)+ '')
li ne = in file.readli ne() in file.close()。