不会飞的章鱼

熟能生巧,勤能补拙;念念不忘,必有回响。

LintCode Python教程 练习题答案

基础语法、变量与运算

2274 · 第一个 Python 程序:打印 Hello World

1
2
3
# Your first python code
# print Hello World to console
print("Hello World")

2920 · 获取输入数据并打印它

1
2
3
# Please write your code here
name = input()
print(name)

2924 · 定义字符串和数字并打印

1
2
3
4
5
6
7
# Please write your code here
str_1 = 'Hello world'
num_1 = 1
print(type(str_1))
print(type(num_1))
print(str_1)
print(num_1)

2407 · 计算 a + aa + aaa + aaaa 的值

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
def calculate_sum(int_1: int) -> None:
"""
:param int_1: Input number
:return: None
"""
# -- write your code here --
answer = 0
temp = 0

for i in range(4):
temp += int_1
answer += temp
temp *= 10

print(answer)

2271 · 整数运算(Python 版)

1

基本数据类型

2271 · 整数运算(Python 版)

1
2
3
4
5
6
7
8
9
10
# write your code here
# read data from console
a = int(input())
b = int(input())

# output the answer to the console according to the requirements of the question
print(a + b)
print(a - b)
print(a * b)
print(a // b)

2919 · 整数运算2

1
2
3
4
5
6
7
8
9
# write your code here
# read data from console
a = int(input())
b = int(input())

# output the answer to the console according to the requirements of the question
print(a % b)
print(a ** b)
print(a // b)

2269 · 交换两个整数(Python 版)

1
2
3
4
5
6
7
8
# write your code here
# read data from console
a = int(input())
b = int(input())
a, b = b, a
# output the answer to the console according to the requirements of the question
print('a =', a, end='')
print(', b =', b)

2267 · 求三个数的最大值(Python 版)

1
2
3
4
5
6
7
8
import sys

a = int(sys.argv[1])
b = int(sys.argv[2])
c = int(sys.argv[3])
# write your code here
# you need to print the maximum
print(max(a, b, c))

2271 · 整数运算(Python 版)

1
2
3
4
5
6
7
# output the answer to the console according to the requirements of the question
a = int(input())
b = int(input())
print(a + b)
print(a - b)
print(a * b)
print(a // b)

2269 · 交换两个整数(Python 版)

1
2
3
4
a = int(input())
b = int(input())
a , b = b , a
print("a = {}, b = {}".format(a , b))

2267 · 求三个数的最大值(Python 版)

1
2
3
4
5
6
import sys

a = int(sys.argv[1])
b = int(sys.argv[2])
c = int(sys.argv[3])
print(max(a,b,c))

2917 · 两个变量间的逻辑运算

1
2
3
4
5
6
7
8
# read data from console
a = eval(input())
b = eval(input())
# write your code here
print(a and b)
print(a or b)
print(not a)
print(not b)

2418 · 位运算左移三位(Python 版)

1
2
3
4
5
# write your code here
# read data from console
n = int(input())
# output the answer to the console according to the requirements of the question
print(n << 3)

2937 · 二进制数最右边的 1

1
2
3
4
5
# Get the number a
num_1 = int(input())
# Please write your code here
x = num_1&(num_1-1)
print(num_1-x)

2948 · 给会员打折

1
2
3
4
5
6
7
8
9
10
11
# Get Variables
price = int(input())
customer = eval(input())
vip = eval(input())
blacklist = eval(input())
# please write your code here
if customer in vip: # 判断顾客是否是VIP
price="%.2f"%(0.70*price)
elif customer in blacklist: # 判断顾客是否在黑名单
price=-1
print(price)

2950 · 查看是否是同一对象

1
2
3
4
5
# Please write your code here
print(True)
print(True)
print(True)
print(True)

基本数据类型

2216 · 字符串的相加、重复输出、切片

1
2
3
4
5
6
7
8
9
10
11
12
def add_repeat_slicing(str_1: str, str_2: str) -> tuple:
"""
:param str_1: The first source string
:param str_2: The Second source string
:return: tuple: A tuple containing three new strings
"""
# -- write your code here --
a = str_1 + str_2
b = str_1 * 2
c = str_1[1:4]
res = (a,b,c)
return res

2363 · 根据行边界符拆分字符串并找出最长行

1
2
3
4
5
6
7
def splitlines(src: str) -> str:
"""
:param src: The source string needs to be processed
:return: The maximum length of the string
"""
# -- write your code here --
return max(src.splitlines(),key=len)

2395 · 统计字符串出现的次数

1
2
3
4
5
6
7
8
9
def count_string(str_1: str) -> tuple:
'''
:param str_1: Input string
:return: Count the number of occurrences of a string
'''
# -- write your code here --
coun_a = str_1.count('a')
coun_going = str_1.count('going',0,40)
return (coun_a,coun_going)

2923 · 定义一个列表

1
2
3
4
5
6
# read data from console
str_1 = str(input())
num_1 = int(input())
# Please print the list of definitions
list_1=[str_1,num_1]
print(list_1)

2314 · 列表修改、添加和删除元素

1
2
3
4
5
6
7
8
9
10
11
12
13
14
def list_update_del(list_1: list) -> list:
"""
:param list_1: the source list
:return: modified list_1
"""
# --write your code here--
# 修改第三个元素为1999
list_1[2] = 1999
# 列表添加一个元素‘jiuzhang’
list_1.append('jiuzhang')
# 删除列表的第一个元素
list_1.remove(list_1[0])

return list_1

2925 · 定义一个元组

1
2
3
4
5
6
# read data from console
num_1 = int(input())
num_2 = eval(input())
# Please print the list of definitions
t =(num_1,num_2)
print(t,type(t),sep='\n')

3137 · 分割元组

1
2
3
4
5
6
# read data from console
my_tuple = eval(input())
# write your code here
i = int(len(my_tuple) / 2)
print(my_tuple[:i])
print( my_tuple[i:])

3138 · 元素在元组内的出现次数

1
2
3
4
5
# read data from console
my_tuple = eval(input())
x = int(input())
# write your code here
print(my_tuple.count(x))

3139 · 集合中最大的元素

1
2
3
4
# read data from console
my_set = eval(input())
# write your code here
print(max(my_set))

3140 · 集合运算

1
2
3
4
5
6
# read data from console
my_set1 = eval(input())
my_set2 = eval(input())
my_set3 = eval(input())
# write your code here
print(len(my_set1 & my_set2 - my_set3))

3141 · 集合中绝对值小于 10 的元素之和

1
2
3
4
# read data from console
my_set = eval(input())
# write your code here
print(sum([num for num in my_set if abs(num) <10]))

3142 · 字典中不同的 value 数目

1
2
3
4
# read data from console
my_dict = eval(input())
# write your code here
print(len(set(my_dict.values())))

3143 · 字典合并后的大小

1
2
3
4
5
6
# read data from console
my_dict1 = eval(input())
my_dict2 = eval(input())
# write your code here
my_dict1.update(my_dict2)
print(len(my_dict1))

3144 · 根据字典替换列表元素

1
2
3
4
5
# read data from console
my_dict = eval(input())
nums = eval(input())
# write your code here
print([my_dict[i] for i in nums ])

控制语句

2315 · 判断三角形(Python 版)

1
2
3
4
5
6
7
8
9
10
11
# write your code here
# read data from console
a = int(input())
b = int(input())
c = int(input())
# output the answer to the console according to the requirements of the question
lis = [a, b, c]
if 2 * max(lis) < sum(lis) :
print("Is a triangle")
else:
print("Not a triangle")

2202 · 求和(Python 版)

1
2
3
4
5
6
7
8
# write your code here
# read data from console
n = int(input())
# output the answer to the console according to the requirements of the question
num = 0
for i in range(1, n+1):
num = num + i
print(num)

2356 · 打印九九乘法表(Python 版)

1
2
3
4
5
# write your code here
# output the answer to the console according to the requirements of the question
for i in range(1, 10):
for j in range(1, i+1):
print(f"{j}*{i}={i*j}", end=" " if j<i else '\n')

3167 · 交错和(Python 版)

1
2
3
4
5
6
7
8
9
10
# read data from console
n = eval(input())
# write your code here
sum=0
for i in range(1,n+1):
if i%2==1:
sum+=-i
else :
sum+=i
print(sum)

3170 · 找到第一个平方大于 n 的整数

1
2
3
4
5
6
7
# read data from console
n = eval(input())
# write your code here
candidate = 1 # 从整数1开始递增
while candidate ** 2 <= n: # 循环直到找到第一个平方大于n的整数
candidate += 1
print(candidate)

3174 · 值为下标的倍数的元素个数(Python 版)

1
2
3
4
5
6
7
8
9
10
11
# read data from console
arr = eval(input())
# write your code here
count = 0 # 初始化计数器
for i, num in enumerate(arr): # 遍历列表arr
if i == 0:
if num == 0: # i为0时,特判arr[i]是否为0
count += 1
elif num % i == 0: # i不为0时,判断arr[i]是否为i的倍数
count += 1
print(count)

3175 · 组成三角形的元组个数

1
2
3
4
5
6
7
8
9
10
11
# read data from console
n = eval(input())
# write your code here
count = 0
for i in range(1,n+1): # 遍历所有元素值不超过n的三元组
for j in range(1,n+1):
for k in range(1,n+1):
triplet = sorted((i,j,k)) # 对每个三元组进行排序
if triplet[0]+triplet[1] > triplet[2]: # 判断最小的两个数之和是否大于第三个数
count +=1 # 计数器加1
print(count)

函数

2932 · 打印学生平均成绩

1
2
3
4
5
6
# Please write your code here
def print_avg(*score, **info):
return ("name: %s, age: %d, avg: %.2f" %
(info['student_name'],
info['student_age'],
sum(score)/len(score)))

2124 · 打印 Hello Python

1
2
3
def hello_python():
# --write your code here--
print("Hello Python!")

3166 · 求两数绝对值之和(Python 版)

1
2
3
4
5
# Write your code here.
def my_func(num1,num2):
return(numAbs(num1)+numAbs(num2))
def numAbs(num):
return (-num if num<0 else num)

3171 · 找出 1 - n 中能被 x 整除的数

1
2
3
4
# Write your code here.
def my_func(n:int,x:int):
list=[x*i for i in range(1,n//x+1)]
return list,len(list)

2126 · 导入一个模块文件夹下的中一个文件

1
2
3
4
# write your code here
from branch import solution
# keep the code below
solution.do()

3164 · 重命名导入的同名文件

1
2
3
4
5
6
# Write your code here
from branch1 import solution as a
from branch2 import solution as b
# Keep the code below
a.do()
b.do()

3176 · 输出对应日期的正午时间点

1
2
3
4
# Write your code here.
from datetime import datetime
def my_func(year,month,day):
return datetime(year,month,day,12)

3148 · 使用 lambda 函数构造一元二次多项式

1
2
3
4
def equation(a, b, c):
# Write your code here.
k = lambda x : a*x**2 + b*x + c
return k

3162 · 根据年龄对成员进行排序

1
2
3
def sort_list(members: list):
# Write your code here.
return sorted(members,key=lambda x:x[2])

文件操作

2930 · 向文件里写入列表

1
2
3
4
5
def write_list(path: str, list_1: list):
# Please write your code
with open(path,'w') as f:
f.write(str(list_1))
f.close()

2931 · 从文件中读取字典并修改它

1
2
3
4
5
6
7
8
9
10
import json

def get_write_dict(path:str):
# Please write your code
with open(path) as fp:
py_dic = json.load(fp)
py_dic['age']=18
js_str = f'{py_dic}'
with open(path,'w') as fps:
json.dump(js_str,fps)

2934 · 读取 csv 文件并修改

1
2
3
4
5
6
7
8
9
10
import csv

def get_write_csv(path:str):
# Please write your code
with open(path,'r') as f:
lines=f.readlines()
lines[0]=lines[0].replace('name','student_name')
with open(path,'w') as f:
f.writelines(lines)
f.close()

异常处理

2942 · 阻止黑名单上的人

1
2
3
4
5
6
7
8
9
10
class DiscoverBlacklist(Exception):
pass


def selection(blacklist: list, customers: list):
# please write your code here
for customer in customers:
if customer in blacklist:
raise DiscoverBlacklist('Alert, %s is on the blacklist.' % customer)
return 'Welcome to the next visit'

2933 · 打印学生平均成绩(异常版)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
# Please define the exception here
class KeywordNotFound(Exception):
my_message = "Incomplete keywords"
def __init__(self):
super(KeywordNotFound, self).__init__(self.my_message)

class NotAllNumbers(Exception):
my_message = "It's not all about numbers"
def __init__(self):
super(NotAllNumbers, self).__init__(self.my_message)

def print_avg(*args, **kwargs) -> str:
# Please write your code here
if 'student_name' not in kwargs or 'student_age' not in kwargs:
raise KeywordNotFound()

for value in args:
if not isinstance(value, int):
raise NotAllNumbers()

return "name: {}, age: {}, avg: {:.2f}".format(kwargs['student_name'], kwargs['student_age'], float(sum(args))/len(args))
------ 本文结束------
如果本篇文章对你有帮助,可以给作者加个鸡腿~(*^__^*),感谢鼓励与支持!