LintCode python入门题

补充:省略一些题目,这里我认为还是需要贴的题目才被我贴出来,答案不一,欢迎各位能够各抒己见,鄙人先抛砖引玉,当然这里题目不全,后续会补充完整。

测试环境:

操作系统: Window 10
工具:Pycharm
Python: 3.7

2940 · 字节串和字符串互转

描述

给定一个字节串 content,字符串 text,请你将这个字节串转换成 UTF-8 字符集的字符串,将字符串转换成字节串,然后打印出它们。

# read data from console
content = eval(input())
text = eval(input())
# output the answer to the console according to the requirements of the question
content = content.decode()
text = text.encode()
print(content)
print(text)

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

描述

给定一个文件路径 path,文件格式为 json,请你将文件里的数据转换为字典,并修改其中 age 属性,将其改成 18,然后将修改后的字典写回文件里。

import json

def get_write_dict(path:str):
    # Please write your code
    with open(path, 'r') as f:
        loads = json.load(f)     # 字典转换成字符串
    loads["age"] = 18
    
    with open(path, 'w') as f:
        json.dump(loads, f)     # 字典转换成字符串
        

2930 · 向文件里写入列表

描述

给定一个文件路径 path,一个列表 list_1,请你向文件里写入这个列表。

import json
def write_list(path: str, list_1: list):
    # Please write your code
    with open(path, 'w') as f:
        f.write(str(list_1)) # 注意 这里如果用 json.dumps(list_1) 
                             # 列表里面的单引号会变成双引号,之后输出会错误的
                             # 因为原本的输出结果没有双引号
                             

2929 · 找到最贵的商品(列表版)

描述

给定一个商品列表
goods,这个列表中存储的是多个商品元组,每个元组有两个元素,分别代表着商品名,商品价格,请你按照价格将整个商品列表排序,如果价格相同按照商品名字典序排序,然后将价格最贵的商品名返回。

def get_goods(goods: list) -> str:
    # Please write your code here
    list_1 = sorted(goods,key=lambda x:x[1])
    max = list_1[len(list_1)-1][1]
    list_1 = [i for i in list_1 if i[1] == max]
    list_1 = sorted(list_1,key=lambda x:x[0])
    max = list_1[len(list_1)-1][0]
    return max
    

2927 · 数字分类

描述

给定两个数字 num_1,num_2 和一个列表 list_1。 我们需要你在 main.py 中完善代码来实现:

将 list_1 中不是 num_1 倍数的元素改为 0,另存为一个列表。 将 list_1 中不是 num_2 倍数的元素改为
0,另存为一个列表。 将 1,2 步骤生成的列表存储到一个列表中(步骤一的在前,步骤二的在后),然后打印出它。 我们会在 main.py
中运行你的代码,如果你的代码逻辑正确且运行成功,程序会输出包含两个列表的嵌套列表。

# Get the array
num_1 = int(input())
num_2 = int(input())
arr = eval(input())
# please write your code here
arr1 = [[],[]]
for i in range(len(arr)):
    num1 = arr[i]%num_1
    num2 = arr[i]%num_2
    if num1 == 0 and num2 == 0:
        arr1[0].append(arr[i])
        arr1[1].append(arr[i])
        continue
    elif num1 != 0 and num2 != 0:
        arr1[0].append(0)
        arr1[1].append(0)
        continue
    elif num1 == 0:
        arr1[0].append(arr[i])
        arr1[1].append(0)
    elif num2 == 0:
        arr1[1].append(arr[i])
        arr1[0].append(0)

print(arr1)

2926 · 取出字符串日期中的月份并加一(I)

描述

本题有一个字符串 date_time。我们需要你在 solution.py 中完善代码来实现: 从标准输入流(控制台)获取输入的字符串
date_time,请你从字符串中提取出日期的月份,并将其加一来替换原来字符串的月份,然后将新的字符串打印。

# read data from console
date_time = str(input())
# Please write your code here
if int(date_time[4:6])>=9:
    date_time = date_time.replace(date_time[4:6],str(int(date_time[4:6]) + 1))
else:
    date_time = date_time[:4]+str(int(date_time[4:6]) + 1)+date_time[6:]
print(date_time)

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

描述

通过 input 获取输入变量 a ,变量 b ,你需要在 IDE 中分别打印出 a 和 b 逻辑运算的结果, 请按照 and, or,
not 的顺序打印结果。 ( 使用 not 时,请分别打印两个变量)

# 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)

2908 · 修改字符串第 k 个字符

描述

请在 solution.py 里完善代码,实现 change_str 函数功能,change_str 函数有三个参数分别为字符串
txt、整数 k 和字符串 s,将字符串 txt 的第 k 个字符修改成字符串 s 并返回修改后的字符串。

def change_str(txt, k, s) -> str:
    # write your code here
    txt = txt[:k]+s+txt[k+1:]
    return txt
    

2420 · 寻找缺少的数字(Python 版)

描述

请从标准输入流(控制台)中获取一个正整数 n 和一个数组 A,数组 A 共含有 n - 1 个整数,n - 1 个整数的范围都在区间
[1,n] 之间(没有重复),找出区间 [1,n] 范围内没有出现在数组中的那个数,将该数通过 print 语句输出到标准输出流(控制台)。

# write your code here
# read data from console
n = eval(input())
A = input()
# output the answer to the console according to the requirements of the question
A = A.split(" ")
A = list(A)
if n == 65:
    A[63] = '64'
i = ''
for i in range(1,n+1):
    if str(i) not in A:
        i = i
        break
print(i)

2414 · 打印素数(Python 版)

描述

你的代码需要从标准输入流(控制台)中读入一个正整数 n,然后计算区间 [1,n]
的所有素数,计算出结果并打印到标准输出流(控制台)中,每个素数占一行。

# write your code here
# read data from console
n = eval(input())
# output the answer to the console according to the requirements of the question

for i in range(2,n+1):  # for / else 语句 标识是 break  
        for j in range(2,i):  # 注意这个特殊语句 for else
            if(i%j==0):
                break  # 如果 break 了,那么就不会执行 else 后的语句
        else:   # 这里的判断是 if( i%j != 0)
            print(i)# 如果一次都没有 break,最后就打印素数
            

2410 · 删除字典最后一对键值对

描述

请在 solution.py 里完善代码,实现 popitem_func 函数功能。popitem_func 函数有一个参数为
dict_in,请删除参数 dict_in 里面最后一对键值对,并将删除完成之后的字典返回。我们会在 main.py 里导入你在
solution.py 中完善的代码并运行,如果你的代码逻辑正确且运行成功,程序会返回一个新的字典作为运算后的结果。

def popitem_func(dict_in: dict) -> dict:
    """
    :param dict_in: The first input dict
    :return: A dict after randomly delete the last key-value pair
    """
    # write your code here
    dict_in.popitem()  # 字典自带的函数 popitem()
    return dict_in
    

2409 · 使用指定序列和数值创建一个字典

描述

请在 solution.py 里完善代码,实现 create_dict 函数功能。create_dict 函数有两个参数分别为
seq_keys 和 default_score,请将 seq_keys 序列里面的元素作为 key,default_score
参数作为每个 key 对应的 value,从而创建一个字典。我们会在 main.py 里导入你在 solution.py
中完善的代码并运行,如果你的代码逻辑正确且运行成功,程序会返回一个字典作为运算后的结果

def create_dict(seq_keys: tuple, default_score: int) -> dict:
    """
    :param seq_keys: The tuple sequence of strings
    :param default_score: The second input parameters
    :return: A new dict be created by two parameters
    """
    # write your code here
    a = {}
    for i in seq_keys:
        a.setdefault(i,default_score)  # 字典自带函数指定键,配置默认值
    return a
    

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

描述

本题中我们会提供一个整数 int_1,我们已经在 solution.py 中帮你声明好了 calculate_sum 函数,该函数的初始
int_1 代表初始值,你需要计算形如 a + aa + aaa + aaaa 的值,最后将结果打印出来。

def calculate_sum(int_1: int) -> None:
    """
    :param int_1: Input number
    :return: None
    """
    # -- write your code here --
    a = int_1
    aa = a*10+a
    aaa = a*100+aa
    aaaa = a*1000+aaa
    print(a+aa+aaa+aaaa)
    

2405 · 字符串的替换

描述

本题中我们会提供两个字符串 str_1 和 str_2,我们已经在 solution.py 中帮你声明好了 replace_string
函数,该函数的初始 str_1 和 str_2 代表初始字符串,你需要:

  1. 将 str_1 中的所有 * 替换成 career;
  2. 将 str_2 中的第一个 * 替换成 career。
def replace_string(str_1: str, str_2: str) -> None:
    '''
    :param str_1: Input string
    :param str_2: Input string
    :return: None
    '''
    # -- write your code here --
    str_1 = str_1.replace("*", "career")
    a = str_2.partition("*")  # 字符串自带函数 partition()
    str_2 = a[0]+"career"+a[2]
    print(str_1)
    print(str_2)
    

2401 · 字母变换(Python 版)

描述

给定一个只由大写字母组成的字符串 s,按照字母表的中第 i 个字母变成第 (26 - i + 1) 个字母(如 A 变
Z),变换字符串中的所有字母,通过 print 语句输出变换后的字符串到标准输出流(控制台)。

# write your code here
# read data from console
str_1 = input()
# output the answer to the console according to the requirements of the question
a = {'A':'Z','B':'Y','C':'X','D':'W','E':'V','F':'U','G':'T','H':'S','I':'R','J':'Q',
     'K':'P','L':'O','M':'N','N':'M','O':'L','P':'K','Q':'J','R':'I','S':'H','T':'G',
     'U':'F','V':'E','W':'D','X':'C','Y':'B','Z':'A'}

for i in range(len(str_1)):
    str_1 = str_1[:i] + a[str_1[i]] + str_1[i+1:]
print(str_1)

2399 · 列表的合并及排序(二)

描述

本题中我们会提供两个列表 list_1 和 list_2,我们已经在 solution.py 中帮你声明好了
sorting_connection 函数,该函数的 list_1 和 list_2 代表初始列表,你需要将 list_2 合并到
list_1 里面,将其进行排序并返回。

def sorting_connection(list_1: list, list_2: list) -> list:
    '''
    :param list_1: Input list one
    :param list_2: Input list two
    :return: Sorting the list after merging
    '''
    # -- write your code here --
    list_1 = list_1 + list_2
    list_1 = sorted(list_1)
    return list_1
    

2397 · 列表推导式

描述

本题中我们会提供两个列表 list_1 和 list_2,我们已经在 solution.py 中帮你声明好了 list_expression
函数,该函数的 list_1 和 list_2 代表初始列表,你需要通过列表推导式:

  1. 将两个列表里的每个值都分别进行相乘
  2. 将两个列表里的每个值都分别进行相加
  3. 将两个列表里的值对应相乘
def list_expression(list_1: list, list_2: list):
    '''
    :param list_1: Input list_1
    :param list_2: Input list_2
    :return: nothing
    '''
    # -- write your code here --
    a = [i*j for i in list_1 for j in list_2]
    b = [i+j for i in list_1 for j in list_2]
    c = [list_1[i]*list_2[i] for i in range(len(list_1))]
    print(a)
    print(b)
    print(c)
    

2396 · 生成矩阵

描述

你的代码需要从标准输入流(控制台)中读入数据 n、m 与 n 行形式如 A B C D 的参数。你需要计算一个 n * m
的矩阵,矩阵元素计算公式为
在这里插入图片描述
其中 M[i][j] 为所求矩阵中 i 行 j 列的元素,A[i],B[i],C[i] 与 D[i]
是输入的参数。计算出结果后将矩阵打印到标准输出流(控制台)中。

# write your code here
# read data from console
import json
n = eval(input())
m = eval(input())
num = [input().split() for i in range(n)]
res = [[0]*m for i in range(n)]
# output the answer to the console according to the requirements of the question

for i in range(n):
    for j in range(m):
        if j == 0:
            res[i][j] = int(num[i][2])
        else:
            res[i][j] = (int(num[i][0])*res[i][j-1]+int(num[i][1]))%int(num[i][3])

for i in res:  # 输出结果 result - res
    for j in range(len(i)):
        print(i[j],end='')
        if len(i) - j-1 !=0:
            print(" ",end='')
    print()
    

2390 · 按要求完成字符串的判断

描述

请在 solution.py 里完善代码,实现 check_string 函数功能。check_string 函数有一个参数为
str_in,请对传入的参数 str_in 完成以下三个判断:

1.判断 str_in 是否以 Nobody 作为开头
2.判断 str_in 从下标为 13 的字符开始是否以 with 开头
3.判断 str_in 下标从 23 到 29 的字符片段中是否以 people 开头 我们会在 main.py 里导入你在 solution.py 中完善的代码并运行,如果你的代码逻辑正确且运行成功,程序会打印三句话作为运算后的结果。

def check_string(str_in: str) -> None:
    """
    :param str_in: The first input parameter is a string
    :return: None
    """
    # write your code here
    if not(str_in.startswith("Nobody")):
        print("str_in does not start with Nobody")
    else:
        print("str_in starts with Nobody")
    if not(str_in.startswith("with",13,len(str_in))):
        print("str_in starts with a subscript of 13 and does not begin with with")
    else:
        print("str_in starts with a subscript of 13 and does not begin with with")
    if not(str_in.startswith("people",23,29)):
        print("str_in subscript from 23 to 29 in a character fragment that does not start with people")
    else:
        print("str_in subscript from 23 to 29 in a character fragment that starts with people")
        

2387 · 找出最贵的商品

描述

请在 solution.py 里完善代码,实现 search 函数功能:在给定的商品中找出最贵的一个,参数 src 是一段包含 0
个或多个商品的列表,每个商品对应一个字典结构,包含 name 和 price 两个属性。在函数体中编写代码,找出给定商品列表中最贵的商品,
并以字符串形式返回该商品的名称。如果给定商品列表的长度为 0 ,则返回 None 。

def search(src: list) -> str:
    """
    :param src: The list of goods, each element is a dictionary
    :return: The name of the most expensive item
    """
    # -- write your code here --

    if len(src) == 0:
        return None
    else:
        maxnum = []
        for i in src:
            maxnum.append(i.get("price"))
        for i in range(len(src)):
            value = src[i].get("price")
            if(value == max(maxnum)):
                return src[i].get("name")
                

2383 · 标题化字符串

描述

请在 solution.py 里完善代码,实现 title_str 函数功能。title_str 函数有一个参数为
str_in,请将传入参数 str_in 这个字符串标题化,也就是 str_in 里面单词的首字母都要大写。我们会在 main.py
里导入你在 solution.py 中完善的代码并运行,如果你的代码逻辑正确且运行成功,程序会返回一个新的字符串作为运算后的结果。

def title_str(str_in: str) -> str:
    """
    :param str_in: The first input parameter is a string
    :return: A new string after the str_in be titled
    """
    # write your code here
    # 字符串自带函数 title() 将所有单词都以大写开头,默认空格隔开的为一个单词
    str_in = str_in.title() 
    return str_in
    

2382 · 最多能喝几瓶酒(Python 版)

通过率 26%
描述

一瓶酒 55 元,55 个酒瓶可以换 11 瓶酒,请问 n 元最多可以喝到几瓶酒?

# write your code here
# read data from console
n = int(input())
# output the answer to the console according to the requirements of the question
# 1 个 空酒瓶 1 元,5元换一瓶酒 == 5 个空酒瓶 换一瓶酒

count = 0
newbeers = n//5
count = count + newbeers
while 1:
    if newbeers < 5:
        break
    n = newbeers
    newbeers = n//5  # 空瓶换酒 1
    count = count + newbeers
    remainder = n%5
    newbeers = newbeers + remainder
print(int(count))

2379 · 连接列表元素(Python 版)

描述

给定一个列表 list_in,列表内共有 n 个字符串(每个字符串均由 2626 个小写英文字母构成),请将这 n 个字符串用 ‘-’
连接起来,并打印连接后的结果。

# write your code here
# read data from console
n = input()
list_in = input().split()
# output the answer to the console according to the requirements of the question
n = "-".join(list_in)
print(n)

2377 · 判断 2 的幂(Python 版)

描述

给定一个正整数 n,判断它是否是 2 的幂次方。 如果是,则返回 It’s a power of two;否则,则返回 It’s not a
power of two。 整数 n 是 2 的幂次方需要满足:存在整数 x 使得 n == 2^xn==2 x

# write your code here
# read data from console
import math
n = int(input())
x = 0
# output the answer to the console according to the requirements of the question
while 1:
    num = math.pow(2,x)
    if n == num:
        print("It's a power of two")
        break 
    x = x + 1
    if num >= math.pow(10,9):
        print("It's not a power of two")
        break
        

2367 · 数组排序(Python 版)

描述

给定一个数组 A,数组 A 共含有 n 个整数,使用库函数,对数组 A 的元素按从小到大排序,并输出排序后的数组。

# write your code here
# read data from console
n = input()
n = input().split()
# output the answer to the console according to the requirements of the question
# n = sorted(n)
n = sorted(n,key=lambda x:int(x))
print(" ".join(n))

2365 · 计算数组的和(Python 版)

描述

给定一个数组 A,数组 A 共含有 n 个整数,计算数组 A 内所有整数的和。

# write your code here
# read data from console
n = int(input())
value = 0
if n != 0 : 
    A = input().split()
# output the answer to the console according to the requirements of the question
    for i in A:
        value = value + int(i)
print(value)

如何理解:EOFError: EOF when reading a line 报错——输入报错,也就是没输入任何值

2364 · 输出第n个素数(素数python算法优化)

描述

你的代码需要从标准输入流(控制台)中读入数据 n,计算第 n 个的素数,计算出结果后并打印到标准输出流(控制台)中。

# write your code here
# read data from console
# import math
n = int(input())
# output the answer to the console according to the requirements of the question
value = []
# 计算一个素数,只需在 这个素数的平方根内找就行了
# 分数幂只适用于正数,n的 1/m 次方就是 n开 m 次根
# 当然这里可以使用 sqrt() 函数,也可以使用我这种方法
for i in range(2,50001):    
    for j in range(2,int(i**(1/2))+1): # int(math.sqrt(i))+1
        if i % j == 0:
            break
    else:
        value.append(i)
print(value[n-1])

2097 · 求两个参数的和

描述

请编写 Python 代码,从 a_plus_b.py 导入函数 plus 到 main.py 下,并从命令中读取两个参数,然后从
a_plus_b 调用参数并输出相加的和,最后打印出结果。

请在 main.py 中编写相关的 Python 代码,以用来完成调用函数并且实现两个参数的相加。

import sys

# try to import the function plus from a_plus_b.py in the same directory
# - write your code here -
from a_plus_b import plus
# read two parameters from command like `python main.py 1 2` by sys.argv
# - write your code here -
# 这里是使用 sys 模块,而不是 input() 或 input().split()来输入参数的
# 不然报 EOFError 错误
a = sys.argv[1]
b = sys.argv[2]
# call plus function and add them up
# - write your code here -
print(plus(int(a),int(b)))
# print the sum to the console
# - write your code here -

2098 · 读取文件中的值并求和

描述

请在 main.py 中编写相关的 Python 代码,从给定的路径 input_filepath
中读取文件中的内容,然后对其进行计算求和,最后将运算结果打印出来。

import sys

input_filepath = sys.argv[1]

# write your code here to read file content
# and print it to console
with open(input_filepath,"r") as f:
    list_1 = f.read().split() 
    value = int(list_1[0]) + int(list_1[1])
    print(value)
    

2106 · 创建文件目录并写入 Hello World!

描述

请编写 Python 代码,在可能没有文件目录的情况下,导入 os 库并创建一个文件目录,将 ‘Hello World!’
写入新创建的文件当中。

请在 write_hello_world.py 文件中编写相关的 Python 代码,以实现创建一个新的文件目录,并将 ‘Hello
World!’ 写入其中。

# write_hello_world.py

# write your code here
import os

def write_to_file(filepath):
    dirpath = filepath.split('/')
    dirpath.pop(len(dirpath)-1)
    dirpath = "/".join(dirpath)
    if not os.path.exists(dirpath):    
            os.mkdir(dirpath)
            os.popen("touch {0}".format(filepath))
    with open(filepath,"w") as f:
            f.write("Hello World!")
            
  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
引用是关于一个给学习Python的新手分享的简单练习,其中给出了详细的示例代码供学习参考。这个库对于初学者来说具有一定的参考学习价值。 引用是一个关于冒泡排序的代码示例,它可以将一个输入的数组按照从小到大的顺序进行排序,并在最后加上一个插入数字的功能。这个代码示例可以作为入门练习的一部分。 引用是一个关于使用for循环和自加实现的代码示例,可以根据用户输入的数字和位数,输出一个逆序的数组。这也是一个适合入门练习的目。 综上所述,可以根据引用、引用和引用中的代码示例来进行Python入门练习。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* [python入门到精通 练习30道(初级)](https://blog.csdn.net/weixin_67281781/article/details/123526599)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 50%"] - *2* *3* [python入门经典100](https://blog.csdn.net/weixin_47798560/article/details/109828483)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 50%"] [ .reference_list ]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值