Python代写-INFO1110
时间:2021-11-20

FEIT EDUCATION
'6��.Q:�
期末总复习 – INFO1110
by
李指导
1INFO1110 Final 课程
目录
INFO1110 Final课程............................................................................................................................................. 1
基本 Python 语法........................................................................................................................................... 4
Python 必备函数............................................................................................................................................ 5
1. input() ....................................................................................................................................................... 5
2. Data type.....................................................................................................................................................5
3. Variable 变量.............................................................................................................................................6
4. String formatting.........................................................................................................................................6
5. 全部大写/小写.......................................................................................................................................... 7
6. Float 和 int 的细节处理 ........................................................................................................................7
7. Modulo 模除..............................................................................................................................................7
在代码中产生分支(If)..............................................................................................................................8
1.if...................................................................................................................................................................8
代码分支进阶................................................................................................................................................ 8
Python 中的循环.......................................................................................................................................... 10
while............................................................................................................................................................. 10
for..................................................................................................................................................................10
多个变量在一块就是 List........................................................................................................................... 11
List 相关 function.......................................................................................................................................11
Explain an array/list......................................................................................................................................12
Declaring an array variable...........................................................................................................................12
Setting an array element value......................................................................................................................12
Reading an array element value....................................................................................................................13
Operations on an array element value.......................................................................................................... 13
“外部“的参数 - Command line argument.............................................................................................. 13
Sys.argv ...................................................................................................................................................... 13
Vector/Matrices............................................................................................................................................ 18
Function........................................................................................................................................................ 19
What is a function and what are the features of a function prototype?........................................................ 19
Whats a function prototype?.........................................................................................................................20
What happens to the variables and calculations in the function when it finishes?.......................................20
How does a function deal with errors that it cannot handle?........................................................................20
2Describe what happens to the values of the arguments when calling a function......................................... 20
Global/Local variable................................................................................................................................... 21
Dictionary..................................................................................................................................................... 21
自定义 Module.............................................................................................................................................21
基础概念........................................................................................................................................................23
Testing........................................................................................................................................................... 25
Why do we bother to test programs if it works for the first time?................................................................25
Explain unit testing....................................................................................................................................... 25
Create tests for a given problem description without the code.....................................................................25
What is test driven development?.................................................................................................................26
What is End to End Testing?........................................................................................................................ 26
Integration Tests........................................................................................................................................... 26
Regression testing.........................................................................................................................................26
Testing示例代码......................................................................................................................................... 27
Collections相关技巧.................................................................................................................................... 29
Set................................................................................................................................................................. 29
Zip.................................................................................................................................................................29
Enumerate..................................................................................................................................................... 30
Idioms............................................................................................................................................................ 30
Write code to search a list based on tracking one thing (e.g. find minimum).............................................. 30
Write code to search a list based on tracking two things (e.g. find index of minimum).............................. 31
Functions....................................................................................................................................................... 32
What is a function and what are the features of a function prototype?........................................................ 32
Whats a function prototype?.........................................................................................................................32
What happens to the variables and calculations in the function when it finishes?.......................................32
How does a function deal with errors that it cannot handle?........................................................................32
Describe what happens to the values of the arguments when calling a function foo(3, someObject)......... 33
Classes........................................................................................................................................................... 33
What is a [default] constructor?....................................................................................................................33
What are instance variables?........................................................................................................................ 33
How are instance variables accessed?.......................................................................................................... 33
What is the meaning of self?........................................................................................................................ 33
Object............................................................................................................................................................ 34
How do you create an Object?....................................................................................................................... 34
3How to use the constructor for an object...................................................................................................... 34
Methods......................................................................................................................................................... 34
Files................................................................................................................................................................35
How do you read/write each character of a file at a time?........................................................................... 35
How do you read/write each line of a file at a time?.................................................................................... 35
How do you read the entire contents of a file into working memory?......................................................... 35
Techniques.................................................................................................................................................... 36
Zip.................................................................................................................................................................36
Lambda......................................................................................................................................................... 36
Static functions............................................................................................................................................. 36
初级练习题....................................................................................................................................................37
Write a function to accept a list of objects, sort them, then return a copy in reversed order....................... 37
Write a function to accept a list of objects, copy them, then sort the copy, then return the copy in reversed
order..............................................................................................................................................................37
Write a function to accept a list of strings, sort them, then return a copy.................................................... 38
Write a function to accept a list of strings, sort each string, then return a copy of the list in reversed order38
Write a function to accept a list of strings, copy them, sort each string in reverse order in the copy, then
return the copy of the list in reversed order..................................................................................................39
Write code to extract the 3rd and the 5th argument from command line arguments................................... 39
Write the equivalent of the zip() function.....................................................................................................40
Write the equivalent of the enumerate() function.........................................................................................40
Write code to equivalent function to get a copy of a list similar to the slice operation [from:to)................41
Write code an alternate function to get a deep copy of a list........................................................................41
Write the function get_png()........................................................................................................................ 42
Write a function prototype and a function body to perform the following:................................................. 43
Write a program that would calculate the sum of all integer numbers of a file and print the sum to standard
output............................................................................................................................................................ 44
You are tasked to complete the methods of the following class ShoeRepair...............................................45
Using your command line argument (argv), do the following in your program.......................................... 48
4基本 Python 语法
Tab/空格的区别
在 Python 中,我们最初的小型程序也许并不需要注意空格或 tab
随着程序逐渐变得复杂,我们需要注意我们的“对齐”,也就是 Indentation
不合法的 indentation 将会带来诸多错误,如 IndentationError
冒号/Colon/
Colon/冒号通常代表一个条件的开启点,或是一个 function 的开头结束(课程进度
目前还没接触到)
非英语字符
我们并不是只能够使用英语作为 python 的编写语言,用中文同样可以写出可以运行
的代码
问题在于,很多时候我们会误用许多符号而导致出现非常晦涩难找到的 Bug
::, “”, [【, ((
以上的字符都是一些非常痛心的回忆
多个同样字符
= , == , += , -= , *= , /*
5Python 必备函数
1. input()
a) 这是一个用来接住对程序输入内容的 function
b) Function 就是平时编程时会使用到的”功能”, 更官方的说法应该叫”方法”或者”
函数”
c) 例子
a = input() #接下输入的内容并存于 a 中
a = input(“Hi”) #接下输入的内容, 并在输入前提示”Hi”
a = int(input()) #将输入的内容接下后, 转换为 int 形式存储与 a 中
2. Data type
a) 常用的 data type 有六种
i. int 整数
顾名思义,只能是整数
ii. float 浮点数
浮点数,又名小数,可以储存有小数部分的数字
iii. string 字符串
字符串,字符串是由引号包裹起来的一连串字符。
字符串和以上变量的区别是他在我们的课程中将会有非常多的相关 function 或是
method,大家如果有兴趣我可以在课程的最后和大家进行展开讲解
iv. boolean 真或假/是或否
布尔值,它的值只有 True 或是 False 两种
一定注意第一个字母必须是大写,其他字母必须是小写
6v. None 空白值
用来代表变量空白
b) 不同的 type 间相加会出现意料之外的错误
“123” + 123 = “123123”
此处为 string + int, 而非大家以为的 int + int
字符串只能和字符串合并,其他类型的变量需要进行转换(casting)后才能和 string
之间互相运算
3. Variable 变量
a) 每个变量都有自己的 type, 这和他们所代表的内容有关系
b) 例子
a = 1 这里的 a 因为装入了 1, 所以自己的 type 就是和 1 一样的 int
ii. 同理, 如果 a = 1.5, 这里 a 的 type 就变成了 float
c) 在 python 中, variable 的 type 是不固定的, 所以每次重新用”=”, 也就是等号
重新给 variable 一个值的时候, type 也是有可能会变化的
4. String formatting
a) 让一个字符串按照自己的格式来变化
b) 例子
name = “Chen”
age = 21
7formatted = “Hello my name is {} and my age is
{}”.format(name,age)
formatted 的内容则会变为“Hello my name is Chen and my age is 21”
c) {}起到的是留白的作用, 按照顺序在 format(*)的*处按顺序填入自己的内容即

5. 全部大写 /小写
a) 通过使用.lower()或.upper() function 就可以使整个 string 全部变为大写或小写
b) 例子:
x = “All in one”.upper()
x 的内容则等于 “ALL IN ONE”
x = “Las Vegas Neveda”.lower()
x 的内容则等于 “las vegas neveda”
6. Float 和 int 的细节处理
a) 如果想要将 float 转为 int, 那么小数点后的所有内容都会被去尾
b) 例子
A = 1.97
B = int(a)
B 在此处的值为 1
7. Modulo 模除
8a) 模除的功能是得出两数相除后的余数
b) 例子
17 % 4 = 1, 因为 17/4 的结果是 4 余 1, 而这里的 1 就是正常除法留下的余
数, 也就是我们 modulo 的结果
c) Modulo 最简单的应用 - 测试某个数字, x, 是偶数还是奇数
i. 如果 x 和 2 之间 modulo 的结果是 0, 那么?
ii. 如果 x 和 2 之间 modulo 的结果是 1, 那么?
在代码中产生分支( If)
1.if
a) if 等同于中文里的”如果”, 在代码中起到决定是否执行的作用
b) 例子:
if age > 3:
print(“age is older than 3)
代码分支进阶
1.if
a) if 等同于中文里的”如果”, 在代码中起到决定是否执行的作用
9b) 例子:
if age > 3:
print(“age is older than 3)
2. elif
a) elif 等同于中文里的”那么如果”, 在代码中起到决定在”如果”不成立后, 是否
执行”另一条件”的内容的作用
b) 例子:
if age > 3:
print(“age is older than 3”)
elif age < 10:
print(“age is younger than 10”)
3. else
a) else 等同于中文里的”那就”, 在代码中起到”如果其他条件都不成立, 那只能
执行以下内容”的作用
b) 例子:
if age > 3:
print(“age is older than 3”)
elif age < 10:
10
print(“age is younger than 10”)
else:
print(“age is not between 3 and 10”)
Python 中的循环
while
a) while 等同于中文里的”只要还没”, 在代码中起到”只要条件还成立, 那就一直
执行”的作用
b) 例子:
counter = 0
while counter < 10:
print(“Hi”)
counter += 1
此代码会 print 十次”Hi”
for
a) for 等同于中文里的”在这期间”, 在代码中起到”在给定的条件期间, 我会一直
执行”的作用
b) 例子:
for i in range(10):
print(“Hi”)
此代码会 print 十次”Hi”
Problem set 逐题分析
11
多个变量在一块就是 List
在程序中永远只是用一个一个的变量很明显是非常令人不适的,那么为了方便我们进行
多个变量同时进行某项操作,我们可以使用 List,也就是列表
初始化一个列表:
my_list = []
如果要往我的列表里加一个东西:
my_list.append(something)
此时,我们列表中的内容就等同于变成了:
my_list = [something] #此处的 something 是我们的一个已经存在的变量
List 相关 function
append()
向 list 内加入一个元素
my_list = [] my_list.append(“a”) #现在 my_list 变为 [“a”]
remove()
从 list 内移除一个元素
my_list = [“a”] my_list.remove(“a”) #现在 my_list 变为 []
sort()
将 list 按照默认的顺序,或是自定义的顺序排序,数字排序默认为升序
my_list = [9,2,12,5]
my_list.sort()
12
print(my_list) #[2,5,9,12]
count()
得到某元素在 list 或其他集合内出现的频率
my_list = [9,2,2,12,5]
print(my_list.count(2)) # = 2
clear()
清空 list 或者其他集合内的所有元素
my_list = [9,2,2,12,5]
my_list.clear()
print(my_list.count(2)) #结果为[]
Explain an array/list
An array/list is a data structure that holds multiple elements in one object, and can be
traversed using indices.
My_num = ‘12345’
Print(my_num[4])
Declaring an array variable
my_list = [ ]
OR
my_list = [1,2,3,4,5]
Setting an array element value
13
first_list = [1,2,3,4,5]
second_list = first_list[0]
Reading an array element value
value_read = my_list[index]
Operations on an array element value
my_list[index] = my_value
“外部“的参数 - Command line argument
Sys.rgv
a) 代表的是在输入 python3 ....... 指令时, python3 后用空格隔开的所有内容
b) 用空格隔开的内容以 string 的形式存储于 argv 中
c) Argv 的本质是一个 list
d) 使用 argv 前, 需要先加入一行 import sys
例题拆解
Q1
14
本题拆解:
如何接入 Product name
如何接入价格
如何接入折扣
输出精确到两位小数
本题提示:
在使用 input 时, 我们如果在圆括号中放入 string 的话, 会是什么效果?
我们该如何使用 round 或是.format 来进行控制小数点的操作?
Q2
15
本题拆解:
如何接入数字
如何根据数字升序地打出多个空格
如何根据数字降序地打出多个空格
本题提示:
我们如何自动化执行多次代码?
我们如何避免多执行一次?

题!
16
常用 python 内置 function
print()
最常见的 function,用来对屏幕(stdout,暂时不用详细了解)输出内容
len()
用来求各种 object 的长度
len(“string”) = 6,len( [1,2,3] ) = 3
sum()
用来求一整个 list 或是其他集合中数字的和
sum( [1,2,3] ) = 6
upper()
将一整个 string 内所有的字母全部变为大写
“Nihao”.upper() = “NIHAO”
lower()
将一整个 string 内所有的字母全部变为小写 “Nihao”.lower() = “nihao”
abs()
得到数字的绝对值
abs(-0.234) = 0.234
round()
将数字精确到某一小数点
round(0.4444,2) = 0.44
17
min()
得到一串数字,list 或是其他集合内最小的数字
min(2,3,4) = 2
max()
得到一串数字,list 或是其他集合内最大的数字
max(2,3,4) = 4
type()
得到 variable 的 type type(“XXXX”) = string
strip()
移除 string 中前后的空格或是换行符
“ An xs size shirt ”.strip() = “An xs size shirt”
replace()
在一个 string 中将某些字符转换为另一些字符
“Boooom”.replace(‘o’,’a’) = “Baaaam”
split()
将一个 string 按照分隔符分割为一个 string
“A Big Ball”.split(‘ ‘) = [“A”,”Big”,”Ball”]
join()
将一个 list 内的 string 以分隔符来分割,拼合为一个 string
[“A”,”Big”,”Ball”].join(‘ ’) = “A Big Ball”
18
For 循环
a) for 等同于中文里的”在这期间”, 在代码中起到”在给定的条件期间, 我会一直
执行”的作用
b) 例子:
for i in range(10):
print(“Hi”)
此代码会 print 十次”Hi”
i 等同于一个临时的变量,每个被遍历到的元素会在被遍历到的时候被称作 i
在本例中,i 是在 range 中不断跳动的数字
Vector/Matrices
我们可以把 vector 单纯的理解为 1 维的 list,matrices 为 2 维的 list
my_vec = [1,2,3,4,5]
my_matrix = [[1,2,3],[4,5,6]]
19
思考问题:
平时我们是怎样得到一个 vector 的长度的?
我们应该如何得到我们 matrix 的维度?
平时我们是怎样通过循环来 print 出一个 vector 内所有的元素的?
我们应该如何 print 出一个 matrix 中所有元素的内容?
Function
本质上,就是一个可以接收参数的,独立写出去的代码块
格式:
def function_name( parameter1,parameter2 ):
# code
# if you do not want to have any code,
# add a line like the below
pass
如果需要利用 function 的运算结果,则可以 return 运算结果 例子
def minus( number1,number2 ):
result = number1-number2
return result
What is a function and what are the features of a function prototype?
A function is a block of organized, reusable code that is used to perform a single, related
action.
Functions provide better modularity for your application and a high degree of code reusing.
20
Whats a function prototype?
Function prototype includes the function name and parameters that the function takes in.
What happens to the variables and calculations in the function when it finishes?
If the variables were created in this function and are never returned as a result of the
function, they will be removed from the program’s memory.
How does a function deal with errors that it cannot handle?
It will throw an exception at the line where the error occurs. During the traceback, you may
increasingly trace what had caused the error to happen.
Describe what happens to the values of the arguments when calling a function
func(3, someObject)
Both arguments will be passed into the function, and will be correspondingly modified by
the function if any modifications were made.
Note that 3 is pass by value.
Pass by value
-> primitive data type
Pass by reference
21
-> composite data type
Global/Local variable
Global:
全局的,全范围内的,全球的
这些是在我们的程序中任意情况下都能够接触到的变量
如果我们在 function 中试图使用 function 外重名的 global variable,需要在变量名前
加上关键词 global
Local:
本地的,当前范围的
如果我们在 function 中声明了一个变量,那么在出了 function 之后这个变量将会失
去效应
即便是通过 global 关键词也无法得到这个变量
Dictionary
相对于 list 而言,将 index 的概念抛弃,而是用 Key 对应 Value 的概念
在语法上,等同于“用某个任意类型的变量当 index”
my_dict[“name”] = “Hi”
print(my_dict[“name”])
自定义 Module
22
当我们将代码保存至某个 python 文件后,我们可以在另一份 python 文件中以 import
的形式来获取已保存 python 文件中的任意内容
Import 后的文件将以 module 的形式存在,故我们在使用任意 function/method 时都需
要用到 module 名作为前缀
如,我在另一份叫做 helper.py 的文件中写了一个名为 pretty_print()的 function,如果我
新开了一个文件名叫作 user.py,那么我如果想要使用 helper.py 的内容中的代码则需要
用到 import helper,或 import helper as h
当我们的 python 项目逐渐变得庞大后,我们是需要将代码放在不同文件中进行区分以
及归类的,所以会经常的涉及到如何拆分我们的代码,以及如何最优化的去使用 import
Problem set 逐题分析
23
基础概念
What is a compiler?
Compiler是什么?
A compiler converts high level code
such as python to low level machine instructions, so they can be executed by computer.
Compiler 的作用在于把你的 high level code,比如 python code,转化成 low level machine
instructions, 这样电脑就可以执行他们。
What is syntax?
Syntax 是什么?
Syntax is the spelling or grammar of the language, in terms of python it may refer to the rules
of writing code so that it can be interpreted by the compiler.
Syntax 就是一个语言里的语法或者拼写,在 python 里指的是写 code 规则,只有按照特
定的规则写 compiler 才能理解你的 code。
What does it mean for a compilation error or syntax error?
24
Compilation error 或者 syntax error 代表什么?
Compilation error means that the compiler is unable to process the targeted file.
Syntax error means that the written code does not follow the syntax of the language.
Compilation error 代表的是 compiler 不能够处理选定的 file。
Syntax error 代表的是你写的 code 不符合某个语言的语法。
What error does the below cause?
What error does the below cause?
25
Testing
Why do we bother to test programs if it works for the first time?
Working at the first time does not mean it will work in all cases, so we need to make sure it
fully satisfies other requirements.
Explain unit testing
Unit testing is testing each functionality or method in the code individually.
Create tests for a given problem description without the code
Question: Give test cases for a piece of code that computes the square of a given number
26
What is test driven development?
Test-driven development (TDD) is a software development process relying on software
requirements being converted to test cases before software is fully developed, and tracking
all software development by repeatedly testing the software against all test cases. This is
opposed to software being developed first and test cases created later
What is End to End Testing?
End to end testing (E2E testing) refers to a software testing method that involves testing an
application’s workflow from beginning to end. This method basically aims to replicate real
user scenarios so that the system can be validated for integration and data integrity.
Integration Tests
Integration tests are the class of tests that verify that multiple moving pieces and gears
inside the clock work well together.
Regression testing
A type of software testing to confirm that a recent program or code change has not
adversely affected existing features. Regression Testing is nothing but a full or partial
selection of already executed test cases which are re-executed to ensure existing
functionalities work fine.
27
Testing 示例代码
def test_sum():
assert sum([1, 2, 3]) == 6, "Should be 6"
def test_sum_tuple():
assert sum((1, 2, 2)) == 6, "Should be 6"
if __name__ == "__main__":
test_sum()
test_sum_tuple()
print("Everything passed")
28
29
Collections 相关技巧
Set
Set 可以用来避免出现重复的元素,使用方法如下
thisset = {"apple", "banana", "cherry", "apple"}
thisset.add(“apple”)
print(thisset)
Zip
Zip 可以用来将两个 list“缝合在一起”,使用方法如下
ls1 = [1,2,3,4,5,6]
ls2 = [‘a’,‘b’,‘c’,‘d’,‘e’,‘f’]
for x in zip(ls1,ls2):
print(s)
# (1,’a’),(2,’b’)....
30
Enumerate
类似 Zip,但是等同于是给一个喂进去的 collection 自动配上 index
ls = [‘a’,‘b’,‘c’,‘d’,‘e’,‘f’]
for x in enumerate(ls1):
print(s)
# (0,’a’),(1,’b’)....
Idioms
Loop n times using the while structure
Write code to search a list based on tracking one thing (e.g. find minimum)
#Find the largest value
counter = 0
numbers = [ …….. ]
largest = numbers[0]
while counter < len(numbers):
if numbers[counter] > largest:
largest = numbers[counter]
counter += 1
31
Write code to search a list based on tracking two things (e.g. find index of
minimum)
counter = 0
numbers = [ …….. ]
largest_index = 0
while counter < len(numbers):
if numbers[counter] > numbers[largest_index]:
largest_index = counter
counter += 1
32
Functions
What is a function and what are the features of a function prototype?
Function is a block of code
that are written outside the main function
and
can be executed through other code invoking its function name.
Whats a function prototype?
Function prototype includes the function name and parameters that the function takes in.
What happens to the variables and calculations in the function when it finishes?
If the variables were created in this function and are never returned as a result of the function,
they will be removed from the program’s memory.
How does a function deal with errors that it cannot handle?
It will throw an exception at the line where the error occurs, or the error may be dealt by
another try except block that has is containing the function.
33
Describe what happens to the values of the arguments when calling a function
foo(3, someObject)
Both arguments will be passed into the function, and will be correspondingly modified by the
function if any modifications were made.
Classes
What is a [default] constructor?
If we did not explicitly make a __init__ function by ourselves, the default constructor is what
is being used to initialize the instances of that class.
What are instance variables?
Instance variables are variables that belong to that certain class, and each instance of the class
will have such variables along with them.
How are instance variables accessed?
Either through a dot (some_var.some_attribute) or a function (get_some_attribute()’s return
value)
What is the meaning of self?
Self refers to the instance itself, meaning functions within the class having self as its first
parameter may use the instance variables of the class.
34
Object
How do you create an Object?
Knowing the class of the object to be created, normally there are two ways.
A = 1.5, an object of type float is created
my_car = Car(…), the … denotes all necessary parameters needed
How to use the constructor for an object
It is not necessary to use the constructor explicitly, the constructor is called automatically by
default when the object is created.
Methods
Write a method to read the instance variable value and return it
Write a method to initialise certain instance variables as default values defined by the
description
Design a method that would change the state of an object, instance variables, based on a
given description.
35
Files
How do you read/write each character of a file at a time?
First open the file:
f = open(file_dir,’r’)
Having the file opened:
character = f.read(1)
How do you read/write each line of a file at a time?
Having the file opened:
line = f.readline()
How do you read the entire contents of a file into working memory?
Having the file opened:
all_lines = f.readlines()
36
Techniques
Zip
Given two lists, they will be zipped into one list, with each entry constructing a tuple with the
corresponding entry in the other list
To unzip, use the zip through zip(*zipped_list)
Lambda
Used to denote a mini function during the line
For example
max_first = max(some_list, lambda a : a[0])
Enumerate
Parameters The enumerate() method takes two parameters:
iterable - a sequence, an iterator, or objects that supports iteration
start (optional) - enumerate() starts counting from this number. If start is omitted, 0 is taken
as start
Static functions
No self in function denotes a static function for the class
Does not need an instance to invoke such function
37
初级练习题
Write a function to accept a list of objects, sort them, then return a copy in
reversed order
Write a function to accept a list of objects, copy them, then sort the copy, then
return the copy in reversed order
38
Write a function to accept a list of strings, sort them, then return a copy
Write a function to accept a list of strings, sort each string, then return a copy of
the list in reversed order
39
Write a function to accept a list of strings, copy them, sort each string in reverse
order in the copy, then return the copy of the list in reversed order
Write code to extract the 3rd and the 5th argument from command line arguments.
40
Write the equivalent of the zip() function
Write the equivalent of the enumerate() function
41
Write code to equivalent function to get a copy of a list similar to the slice
operation [from:to)
Write code an alternate function to get a deep copy of a list
42
Write the function get_png().
get_png() returns a list of strings that contain the suffix ".png" where it is case insensitive.
The function accepts a list of strings as input. If there are no results, an empty list is returned.
If the input is not a list type, an empty list is returned.
Hint: use isinstance(obj, class) The suffix match is not case-sensitive.
Examples of valid suffix: ".png", ".PNG", ".pNg", ".Png", ".PnG", ···
Restrictions:
In your function you may only use while loops, if statements, function len(), keywords elif,
else, return, break, continue, def, None and any arithmetic or boolean comparison operators.
str comparator == and str method lower().
Do not use a for loop, marks will be deducted.
You cannot use slices, cannot use str comparator other than ==, cannot use string methods
other than len () and lower(), cannot use the in keyword.
43
Write a function prototype and a function body to perform the following:
The function returns the index of the last value in a list that satisfies the criteria:
vi > z - 3x - 4y
where vi is the ith value in the list.
The input to the function is a list of integers, and three integer values x, y, and z.
-1 is returned If no such value exists, or the input list is empty, or the types of x, y, z or any of
the values vi are not integer types.
Restrictions: In your function you may only use
while loops,
if statements,
function len(),
keywords elif,
else,
return,
break,
continue,
def,
None and any arithmetic or boolean comparison operators.
Do not use a for loop, marks will be deducted.
You cannot use slices, cannot use the in keyword.
44
Write a program that would calculate the sum of all integer numbers of a file and
print the sum to standard output.
The input to the program is a file provided as the first argument to the program.
Within the file, there is expected to be one number per line with no spaces.
However, there may be numbers which have a e instead of a 3.
Only integer values contribute to the sum and lines that are not integers are discarded. If there
are no values in the file, then zero is the sum.
Example of running the program: $ python total.py numbers_file
If there is no file name provided your program will behave as follows:
$ python total.py
No argument
If the file does not exist your program will behave as follows:
$ python total.py file.txt
Cannot open file
45
You are tasked to complete the methods of the following class ShoeRepair.
A shoe repair shop serves customers who bring one or two shoes to be repaired. Each
customer has an identifier that is assumed unique. They give their right and/or left shoe to the
shop along with their identifier.
The shop records the customers status in a dictionary for each shoe. The possible status
values can be ”repair”, ”restore”, or ”ready”.
The shoes in the shop are stored in two queues: the work queue and the completed queue.
The work queue represents shoes that are waiting to be, or are currently being repaired. The
completed queue are the shoes that have been repaired and are awaiting collection.
If one shoe has exactly one issue, it is a repair job and takes 1 unit of time. If a shoe has at
least two issues, it is a restore job and takes n units of time, where n is the number of issues
with the shoe.
When a shoe is repaired or restored two events take place: 1) they are moved from the work
queue to the completed queue and; 2) the customer status of the shoe is updated.
Shoes with zero issues are immediately moved to the completed queue. A customer can
collect their shoe(s) if they are all ready.
46
A shoe object has multiple issues recorded as True or False values
47
48
Using your command line argument (argv), do the following in your program.
Excluding the filename, find the longest string in the argv and print it out
For all of the pure numbers that are found in argv, print the sum of these numbers
Calculate how many dot/’.’ characters have occurred in the all of the argv values
Print the cubed value of the length of the argv list.
python3
import sys
sys.argv->
[“xxx.py” ,”123” ,”asdin”]
49
概念相关题目
Iterator vs Iterable
True or False: local variables only exist within the scope of a function
What is a pure function
What are side effects of a function
What is initializing
What is the difference between == and is
What are the advantages of using if
if - elif
elif - else
else rather than a bunch of if
if statements
What is a flow chart
What is a desk check
What datatype is mutable in python
What datatype is iterable in python
What is the difference between []*5
[]*5 vs [0]*5
[0]*5
What does aa store at the end of this snippet?
50
Describe the differences between black box testing and white box testing
What is a module lecture 14 slide 4
a = True
b = False
a and b
a or b
a and b or a
a or b or c
a and b or c
a = [1,2, 3, 4, 5, 6]
for i in a:
i += 1
How do you modify a global variable in Python
True or False, you always have to close a file after reading or writing them. If not, when can
you get away with it?
What is sys.stdout
sys.stdout ?
True or False: Tuples are mutable
How do you do x^4 in Python without importing Math module?
True or False: A function does not have to return anything
True or False: A tuple can vary in size
51
What happens when you try to create an object from a class that doesn't have a pre-defined
constructor?
By default, what gets printed when you print an object?
By default, what does Python compare when you compare two objects?
What is the difference between static, class and instance methods?
True or False: A function can have multiple returns
Why is testing important?
What is integration testing?
How do you perform end-to-end testing?
What is regression testing?
52
53







































































































































































































































































































































































































































































































































































































































































































































































































学霸联盟


essay、essay代写