上一次,我们基本了解了python的发展以及python的应用,这一次我们将进一步了解使用python,让更多的人学会这门语言。
python语言清晰明了,能大大降低程序员的工作量,从而大大提升程序的质量,其易学性和扩展性也有助于新手学习,所以目前深受各类人群喜爱,也是当下最流行的语言之一。
我们将通过不同类型的python习题带你走进python大门。
python经典习题
编写一个程序,提示用户输入一个整数,然后输出该数字的最低有效位数。你可以假设这个数是非负的。
例如:
| Input | Result |
|---|---|
134 |
Enter a number: 134 The least significant digit of 134 is 4. |
1249 |
Enter a number: 1249 The least significant digit of 1249 is 9. |
num=str(input('Enter a number: '))
num1=num[-1]
print(f'The least significant digit of {num} is {num1}.')
定义一个名为get_sum_of_neighbors (a_list)的函数,该函数接受一个整数列表作为参数,并返回一个新列表。新列表中的每个元素都是对应元素的两个邻居(即左和右)的和。注意:您可以假设参数列表至少有两个元素。例如,考虑下面的代码片段:
source = [20, -3, 6, 9, 6, -5] print(get_sum_of_neighbours(source))
结果是[-3,26,6,12,4,6],因为在第一个和最后一个元素中只有一个邻居:
第一个元素的邻居是-3(即result[0]),
最后一个元素的邻居是6(即result[5]),
第二个元素的相邻元素是20和6。因此和是26。
例如:
| Test | Result |
|---|---|
print(get_sum_of_neighbours([20, -3, 6, 9, 6, -5])) |
[-3, 26, 6, 12, 4, 6] |
print(get_sum_of_neighbours([10, -30, 62])) |
[-30, 72, -30] |
def get_sum_of_neighbours(a_list):
a=[]
a.append(a_list[1])
if len(a_list)%2==0:
for i in range(len(a_list)-2):
b=a_list[i]+a_list[i+2]
a.append(b)
if len(a_list)%2==1:
for i in range(len(a_list) - 2):
b = a_list[i] + a_list[i + 2]
a.append(b)
a.append(a_list[-2])
return a
定义一个名为index_of_nearest (a_list, number)的函数,该函数以一个整数列表和一个整数作为参数。该方法返回列表中与参数number值最接近的数字的INDEX。如果列表中有多个数字与参数数的值同样接近,则该函数返回列表中与参数数最接近的第一个数字的索引。注:
可以假设参数列表不是空的。
您可能会发现abs()函数在这个问题中很有用。
例如,考虑下面的代码片段:
print(index_of_closest([20, -3, 6, 9, 6, -5], 7))
结果是在索引“2”处,因为距离为:[13,10,1,2,1,12]。第一个最小值是1,下标为2。
例如:
| Test | Result |
|---|---|
print(index_of_closest([20, -3, 6, 9, 6, -5], 7)) |
2 |
print(index_of_closest([10, 9, 8, 7], 5)) |
3 |
def index_of_closest(a_list, number):
a = []
for i in a_list:
current = abs(number - i)
a.append(current)
y=sorted(a)
b=int(y[0])
c=a.index(b)
return c
定义一个名为create_username_dictionary(names_list)的函数,该函数接受一个元组列表作为参数,并返回一个字典。参数列表中的每个元组都包含一个学生名和相应的用户名。该函数创建一个字典,其中每个键-值对由用户名(键)和相应的学生名(值)组成。
注意:如果用户名已经存在,那么函数应该打印"ERROR: xxx is already in the dictionary."其中xxx是用户名。
例如:
| Test | Result |
|---|---|
a_list = [('Dick Smith', 'dsmi001'), ('Peter Wong', 'pwong002'), ('David Smith', 'dsmi001')]
usernames = create_username_dictionary(a_list)
for key in sorted(usernames):
print(key, usernames[key])
|
ERROR: dsmi001 is already in the dictionary. dsmi001 Dick Smith pwong002 Peter Wong |
a_list = [('Junbo Wang', '1576905332@qq.com')]
usernames = create_username_dictionary(a_list)
for key in sorted(usernames):
print(key, usernames[key])
|
1576905332@qq.com Junbo Wang |
def create_username_dictionary(names_list):
dict1 = {}
for i in names_list:
if i[1] not in dict1:
dict1[i[1]] = i[0]
else:
print("ERROR: {} is already in the dictionary.".format(i[1]))
return dict1
异常处理
文件处理
定义一个名为count_words_of_length(filename, number)的函数,该函数以文件名和整数作为参数,并以参数整数给出的字符串长度返回文件中的字数。您可以假设单词是由空格分隔的。使用try-except-else块来处理可能发生的任何异常。
如果参数filename是空字符串,函数将返回"ERROR: Invalid filename!"
如果文件无法打开,函数将返回"ERROR: the file '…"’并不存在。”文件名。
注意:如果文件可以打开,记得正确关闭文件。
例如,如果"hello.txt"包含以下内容:
Hello World
然后,考虑下面的代码片段:
print(count_words_of_length('hello.txt', 3))
print(count_words_of_length('hello.txt', 5))
将会输出:
0
2
例如:
| Test | Result |
|---|---|
print(count_words_of_length('lincoln.txt', 5))
|
37 |
print(count_words_of_length('input_unknown.txt', 2))
|
ERROR: The file 'input_unknown.txt' does not exist. |
print(count_words_of_length('', 2))
|
ERROR: Invalid filename! |
def count_words_of_length(filename, number):
a=[]
try:
if filename=='':
raise TypeError()
else:
with open(filename) as f:
content = f.read()
content1 = content.split()
except TypeError:
return 'ERROR: Invalid filename!'
except FileNotFoundError:
return "ERROR: The file '%s' does not exist."%filename
else:
for m in content1:
if len(m)==number:
a.append(m)
b=len(a)
return b
f.close()
时间复杂度
考虑以下函数:
def rate(n):
total = 0
i = 0
while i < 10:
total += i
i += 1
i = 0
while i < n:
j = n
while j > 0:
total += 1
j -= 2
i += 2
return total
修改函数,使其打印出在所显示的rate()函数中执行的操作总数。在修改代码时,不要计算添加到代码中的任何额外语句。当while i >0作为每次检查条件时执行。注意,循环条件检查的时间比循环体执行的时间多1次。输出的格式应该是:"Number of operations: <count>"其中<count>为整数值。
举例:
| Test | Result |
|---|---|
rate(2) |
Number of operations: 43 |
rate(3) |
Number of operations: 56 |
def rate(n):
count=6
total = 0
i = 0
while i < 10:
count+=3
total += i
i += 1
i = 0
while i < n:
count+=4
j = n
while j > 0:
count+=3
total += 1
j -= 2
i += 2
print(f'Number of operations: {count}')
排序问题
选择排序是一种简单的排序算法。该排序算法是一种基于就地比较的算法,将列表分为两部分,右侧为排序区域,左侧为未排序区域。最初,已排序区域为空,未排序区域为整个列表。从未排序区域中选择最大的元素,并与最右边的元素交换,该元素成为已排序区域的一部分。这个过程继续将未排序的区域边界向左移动一个元素。
注意:你不能使用Python内置的sort()或sorted()函数。
考虑下面的不完全函数:
def selection_sort(data):
for pass_num in range(len(data)-1, 0, -1):
...
举例:
| Test | Result |
|---|---|
numbers = [6] print(selection_sort(numbers)) |
0 |
numbers = [70, 48, 54, 79, 33] print(selection_sort(numbers)) |
2 |
def selection_sort(data):
num = 0
for pass_num in range(len(data)-1, 0, -1):
max = data[0]
max_index = 0
for j in range(pass_num + 1):
if data[j] > max:
max = data[j]
max_index = j
if max_index != pass_num:
num += 1
data[max_index] = data[pass_num]
data[pass_num] = max
return num
异常处理+文件处理
考虑下面的文本文件,它将Java概念及其对应的含义存储在一个文本文件中,每行一个,以便在学习时检索。
Variable:用于存储单个值以供以后使用
String:表示字符串的类
double:表示浮点数的基元数据类型。
Double:用方便的方法在Object中包装Double的类。
Zero:数字零。数组中的第一个索引和列表的第一个位置
编写一个名为get_study_guide(文件名,关键字)的函数,该函数以文件名和关键字作为参数。该函数应返回作为参数给出的关键字的含义。使用字典来存储概念对和相应的含义。
如果关键字没有出现在字典中,那么函数应该返回一个错误消息,指出特定的关键字不可用。
如果关键字是空字符串,函数应该返回错误消息" error: Invalid keyword!"。
如果关键字的类型无效(即不是字符串),函数应该返回错误消息" error: invalid input!"。
注意:你*必须*使用try…除了语法,并在解决方案中处理KeyError。
注意:你可以假设参数'filename'中指定的文件总是可用的。
例如:
| Test | Result |
|---|---|
filename = "java.txt" print(get_study_guide(filename, 'String')) |
A class for representing character strings |
filename = "java.txt" print(get_study_guide(filename, 'int')) |
ERROR: int is not available. |
filename = "java.txt" print(get_study_guide(filename, '')) |
ERROR: Invalid keyword! |
filename = "java.txt" print(get_study_guide(filename, 2.5)) |
ERROR: Invalid input! |
def get_study_guide(filename, keyword):
try:
dict1 = {}
if keyword == "":
raise ValueError("ERROR: Invalid keyword!")
elif not isinstance(keyword,str):
raise ValueError("ERROR: Invalid input!")
with open(filename) as f:
f = f.read().splitlines()
for i in f:
list2 = i.split(":")
dict1[list2[0]] = list2[1]
if keyword not in dict1:
raise KeyError()
else:
return dict1[keyword]
except ValueError as a:
return a
except KeyError as b:
return "ERROR: {} is not available.".format(keyword)
python类学习
定义一个叫做Student的类,它可以用来描述学生。每个Student对象存储有关学生的姓、名、学号和项目分数列表的信息。该类必须具有以下功能:
创建一个学生。例如:
s1 = Student('Smith', 'Dick', 123)
注意:数据字段(姓氏,名字,student_id, project_scores)必须全部定义为私有实例变量。
返回表示该学生信息的字符串。例如:代码:print(s1)
将产生输出:
Smith Dick(123), average score = 0
该类还应该提供添加项目分数的功能。分数必须在0到10之间。例如:
s1.add_project_score(9) s1.add_project_score(2) s1.add_project_score(-1) #invalid s1.add_project_score(99) #invalid
该类还应该提供获取姓名、学生id和项目分数列表的功能。例如:代码:
print(s1.get_names(), s1.get_student_id(), e1.get_project_scores())
将产生输出:
Smith Dick 123 [9, 2]
该类还应该提供获取平均分的功能。将结果四舍五入到小数点后1位。如果列表为空,则该方法应返回0。例如:
print(s1.get_average())
将会输出:
4.5
提交整个类定义。注意:所有实例变量都必须定义为private。
from decimal import Decimal
from decimal import ROUND_HALF_UP
from decimal import Decimal
from decimal import ROUND_HALF_UP,ROUND_HALF_EVEN
class Student:
def __init__(self,surname,firstname,student_id):
self.__surname = surname
self.__firstname =firstname
self.__student_id = student_id
self.__project_scores = []
def __str__(self):
if len(self.__project_scores) == 0:
average = 0
else:
average = sum(self.__project_scores) / len(self.__project_scores)
average = Decimal(average).quantize(Decimal('0.0'), rounding=ROUND_HALF_UP)
return "{} {}({}), average score = {}".format(self.__surname,self.__firstname,self.__student_id,average)
def add_project_score(self,num):
if 0 <= num <= 10:
self.__project_scores.append(num)
def get_names(self):
return "{} {}".format(self.__surname,self.__firstname)
def get_student_id(self):
return self.__student_id
def get_project_scores(self):
return self.__project_scores
def get_average(self):
if len(self.__project_scores) == 0:
average = 0
else:
average = sum(self.__project_scores) / len(self.__project_scores)
average = Decimal(average).quantize(Decimal('0.0'), rounding=ROUND_HALF_UP)
return "{}".format(average)
继续上一个问题,现在定义一个名为Project的类,它可以用来描述学生准备的项目。每个Project对象都存储有关项目id、标题和参与项目的学生列表的信息。该类必须具有以下功能:
用给定的项目id和标题创建一个项目。例如:
p1 = Project(1, "Project01")
初始化器还应该创建一个学生对象的空列表。注意:数据字段(project_id, title, students)必须全部定义为私有实例变量。
该类应该提供返回项目id和项目标题的功能。例如,代码:
print(p1.get_project_id(), p1.get_title())
将产生输出:
1 Project01
该类还应该提供将学生添加到项目中的功能。例如:
s1 = Student('Smith', 'Dick', 123)
s2 = Student( 'Jones', 'Sally', 111)
p1.add_student(s1)
p1.add_student(s2)
该类还应该提供打印项目学生人数的功能。例如,代码:
print(p1.get_number_of_students())
将产生输出:
2
该类还应该提供返回项目中学生姓名的功能。例如,代码:
print(p1.get_students())
将产生输出:
Smith Dick,Jones Sally
返回表示项目信息的字符串。例如,代码:
print(p1)
将产生输出:
ID=1,(Project01):Smith Dick,Jones Sally
类还应该提供为项目中的所有学生设置分数的功能。例如:代码:
p1.set_score(9) print(s1) print(s2)
将会输出:
Smith Dick(123), average score = 9.0 Jones Sally(111), average score = 9.0
from decimal import Decimal
from decimal import ROUND_HALF_UP,ROUND_HALF_EVEN
class Student:
def __init__(self,surname,firstname,student_id):
self.__surname = surname
self.__firstname =firstname
self.__student_id = student_id
self.__project_scores = []
def __str__(self):
if len(self.__project_scores) == 0:
average = 0
else:
average = sum(self.__project_scores) / len(self.__project_scores)
average = Decimal(average).quantize(Decimal('0.0'), rounding=ROUND_HALF_UP)
return "{} {}({}), average score = {}".format(self.__surname,self.__firstname,self.__student_id,average)
def add_project_score(self,num):
if 0 <= num <= 10:
self.__project_scores.append(num)
def get_names(self):
return "{} {}".format(self.__surname,self.__firstname)
def get_student_id(self):
return self.__student_id
def get_project_scores(self):
return self.__project_scores
def get_average(self):
if len(self.__project_scores) == 0:
average = 0
else:
average = sum(self.__project_scores) / len(self.__project_scores)
average = Decimal(average).quantize(Decimal('0.0'), rounding=ROUND_HALF_UP)
return "{}".format(average)
class Project:
def __init__(self,id,title):
self.__project_id = id
self.__title = title
self.__students = []
def get_project_id(self):
return self.__project_id
def get_title(self):
return self.__title
def add_student(self,stu):
if stu.get_names() not in self.__students:
self.__students.append(stu)
def get_number_of_students(self):
return len(self.__students)
def get_students(self):
a = ""
for i in self.__students:
a = a + i.get_names() + ","
a = a[:-1]
return a
def __str__(self):
return "ID={},({}):{}".format(self.__project_id, self.__title, self.get_students())
def set_score(self,num):
for i in self.__students:
i.add_project_score(num)
python排序问题
编写一个名为get_missing_items_list(items)的函数,该函数以连续整数列表作为参数。整数将始终以升序排列,但有些整数可能会丢失。例如,在列表[3,4,5,7,8,9,11,12]中,整数6和10缺失。
该函数返回一个包含缺失整数的列表(按升序排列)。如果列表中没有缺失的整数,或者参数列表为空,则函数返回一个空列表。
注意:在这个问题中不允许使用in操作符或set操作符。
举例:
| Test | Result |
|---|---|
list = [] print(get_missing_items_list(list)) |
[] |
list = [10] print(get_missing_items_list(list)) |
[] |
list = [5, 6] print(get_missing_items_list(list)) |
[] |
list = [5, 7] print(get_missing_items_list(list)) |
[6] |
def get_missing_items_list(items):
list1 = []
if len(items) <= 1:
return []
else:
i = 0
len_l = len(items)
while i < len_l - 1:
if (items[i+1] - items[i]) > 1:
items.insert(i+1,items[i]+1)
list1.append(items[i] + 1)
i += 1
len_l += 1
elif (items[i+1] - items[i]) <= 1:
i += 1
return list1
这些都是python相关的进阶题型,希望能帮助到大家。
本文介绍了几个Python编程题目,包括获取数字最低有效位、计算列表中元素邻居之和、找到列表中最接近的数字索引以及创建用户名字典等。同时讨论了异常处理、文件操作和时间复杂度分析。此外,还涉及选择排序算法和自定义Student、Project类的设计,以及查找缺失整数的方法。

1万+

被折叠的 条评论
为什么被折叠?



