Introduction to LintCode python

Add: omit some questions. Here I think the questions that need to be posted are posted by me. The answers are different. You are welcome to express your views. I'll start with a brick to attract jade. Of course, the questions here are incomplete, and they will be supplemented in the follow-up.

2940. Byte string and string conversion

describe

Given a byte string content and string text, please convert this byte string into a string of UTF-8 character set, convert the string into a byte string, and then print them out.

# 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 · read the dictionary from the file and modify it

describe

Given a file path path and the file format is json, please convert the data in the file into a dictionary, modify the age attribute to 18, and then write the modified dictionary back to the file.

import json

def get_write_dict(path:str):
    # Please write your code
    with open(path, 'r') as f:
        loads = json.load(f)     # Convert dictionary to string
    loads["age"] = 18
    
    with open(path, 'w') as f:
        json.dump(loads, f)     # Convert dictionary to string
        

2930 · write list to file

describe

Given a file path, a list_1. Please write this list into the file.

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)) # Note that if you use JSON dumps(list_1) 
                             # The single quotation marks in the list will become double quotation marks, and then the output will be wrong
                             # Because the original output result has no double quotation marks
                             

2929 · find the most expensive item (list version)

describe

Given a list of products
goods, this list stores multiple commodity tuples. Each tuple has two elements, representing the commodity name and commodity price respectively. Please sort the whole commodity list according to the price. If the prices are the same, sort according to the commodity name dictionary, and then return the commodity name with the most expensive price.

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. Digital classification

describe

Given two numbers num_1,num_2 and a list_1. We need you in main Improve the code in py to realize:

List_ Not num in 1_ The element of multiple of 1 is changed to 0 and saved as a list. List_ Not num in 1_ The element of 2 times is changed to
0, save as a list. Store the list generated in steps 1 and 2 into a list (step 1 first, step 2 last), and then print it out. We'll be in main py
Run your code in. If your code logic is correct and runs successfully, the program will output a nested list containing two lists.

# 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 · take out the month in the string date and add one (I)

describe

This question has a string date_time. We need you in solution Py: get the input string from the standard input stream (console)
date_time, please extract the month of the date from the string, add it to replace the month of the original string, and then print the new string.

# 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. Logical operation between two variables

describe

Get the input variables A and b through input. You need to print the results of logical operations of a and b in the IDE respectively. Please follow and, or,
Print the results in the order of not. (when not is used, please print two variables separately)

# 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 · modify the k-th character of the string

describe

Please click solution Improve the code in py and realize change_str function function, change_ The str function has three parameters, which are strings
txt, integer k and string s, modify the kth character of string txt into string s and return the modified string.

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

2420 · find missing numbers (Python version)

describe

Please obtain A positive integer n and an array A from the standard input stream (console). Array A contains n - 1 integers, and the range of N - 1 integers is in the range
Between [1,n] (no repetition), find the number that does not appear in the array within the range of [1,n], and output the number to the standard output stream (console) through the print statement.

# 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 · print prime (Python version)

describe

Your code needs to read a positive integer n from the standard input stream (console), and then calculate the interval [1,n]
Calculate and print the results to the standard output stream (console), with each prime occupying one line.

# 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):  # The for / else statement ID is break  
        for j in range(2,i):  # Notice this special statement for else
            if(i%j==0):
                break
        else:
            print(i)#Print prime
            

2410 · delete the last pair of key value pairs in the dictionary

describe

Please click solution Improve the code in py and realize popitem_func function. popitem_func function has one argument
dict_in, please delete the parameter dict_in and returns the dictionary after deletion. We'll be in main Import you in PY
solution.py and run it. If your code logic is correct and runs successfully, the program will return a new dictionary as the result of the operation.

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()  # The dictionary's own function popitem()
    return dict_in
    

2409 · create a dictionary using the specified sequence and values

describe

Please click solution Improve the code in py and realize create_dict function. create_ The dict function has two parameters:
seq_keys and default_score, please set seq_ The elements in the keys sequence are used as keys and default_score
Parameter is used as the value corresponding to each key to create a dictionary. We'll be in main Py to import your solution py
If your code logic is correct and runs successfully, the program will return a dictionary as the result of the operation

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)  # The dictionary has its own function to specify the key and configure the default value
    return a
    

2407 · calculate the value of a + aa + aaa + aaaa

describe

In this question, we will provide an integer int_1. We are already in solution Py to help you declare calculate_sum function, the initial value of the function
int_1 represents the initial value. You need to calculate the value in the form of a + aa + aaa + aaaa, and finally print the result.

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 · string replacement

describe

In this question, we will provide two strings str_1 and str_2. We are already in solution Py to help you declare replace_string
Function, the initial STR of the function_ 1 and str_2 represents the initial string. You need:

  1. Str_ Replace all * in 1 with career;
  2. Str_ Replace the first * in 2 with 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("*")  # The string has its own function partition()
    str_2 = a[0]+"career"+a[2]
    print(str_1)
    print(str_2)
    

2401 · letter transformation (Python version)

describe

Given A string s composed of only uppercase letters, it becomes the (26th - i + 1) letter according to the ith letter of the alphabet (e.g. A becomes
Z) , transform all letters in the string, and output the transformed string to the standard output stream (console) through the print statement.

# 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. Merging and sorting of lists (II)

describe

In this topic, we will provide two lists_ 1 and list_2. We are already in solution Py to help you declare it
sorting_connection function, the list of this function_ 1 and list_2 represents the initial list. You need to change the list_2 merge into
list_1, sort it and return it.

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 derivation

describe

In this topic, we will provide two lists_ 1 and list_2. We are already in solution Py to help you declare the list_expression
Function, the list of the function_ 1 and list_2 represents the initial list. You need to deduce from the list:

  1. Multiply each value in the two lists separately
  2. Add each value in the two lists separately
  3. Multiply the values in the two lists
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 · generating matrix

describe

Your code needs to read the data n, m and N lines from the standard input stream (console), such as the parameters of a, B, C and D. You need to calculate an n * m
The matrix element calculation formula is

Where M[i][j] is the element of row I and column j in the matrix, A[i], B[i], C[i] and D[i]
Is the input parameter. After calculating the results, print the matrix to the standard output stream (console).

# 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:  # Output result - res ult
    for j in range(len(i)):
        print(i[j],end='')
        if len(i) - j-1 !=0:
            print(" ",end='')
    print()
    

2390 · complete the judgment of string as required

describe

Please click solution Py to improve the code and realize check_string function. check_ The string function has a parameter of
str_in, please set STR for the passed in parameter_ In complete the following three judgments:

1. Judge str_ Does in begin with Nobody
2. Judge str_in starts with a character with a subscript of 13. Does it start with with with
3. Judge str_ Whether the character segment with in subscript from 23 to 29 starts with people will be discussed in main Py to import your solution Py and run it. If your code logic is correct and runs successfully, the program will print three sentences as the result of the operation.

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. Find the most expensive goods

describe

Please click solution Improve the code in py and realize the function of search function: find the most expensive one in a given commodity, and the parameter src is a section containing 0
A list of one or more products. Each product corresponds to a dictionary structure, including name and price attributes. Write code in the function body to find the most expensive item in a given item list,
And return the name of the product in the form of string. Returns None if the length of the given item list is 0.

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. Captioned string

describe

Please click solution Py to improve the code and realize the title_str function function. title_ The str function has a parameter of
str_in, please pass in the parameter str_in is a string header, that is, str_in, the first letter of the word should be capitalized. We'll be in main py
Import you in solution Py and run it. If your code logic is correct and runs successfully, the program will return a new string as the result of the operation.

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
    # The string's own function title() starts all words with uppercase. By default, one word is separated by spaces
    str_in = str_in.title() 
    return str_in
    

2382. How many bottles of wine can you drink at most (Python version)

Pass rate 26%
describe

A bottle of wine is 55 yuan. 55 bottles can be exchanged for 11 bottles. How many bottles of wine can you drink at most for n yuan?

# 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 empty bottle 1 yuan, 5 yuan for a bottle of wine = = 5 empty bottles for a bottle of wine

count = 0
newbeers = n//5
count = count + newbeers
while 1:
    if newbeers < 5:
        break
    n = newbeers
    newbeers = n//5 # empty bottle change 1
    count = count + newbeers
    remainder = n%5
    newbeers = newbeers + remainder
print(int(count))

2379 · connection list element (Python version)

describe

Given a list_in, there are n strings in the list (each string consists of 2626 lowercase English letters). Please use '-' for these n strings
Connect and print the connected results.

# 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 · power of judgment 2 (Python version)

describe

Given a positive integer n, judge whether It is a power of 2. If yes, It's a power of two; Otherwise, It's not a is returned
power of two. The integer n is the power of 2, which needs to be satisfied: there is an integer x such that 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 · array sorting (Python version)

describe

Given an array A, array A contains n integers. Use the library function to sort the elements of array A from small to large, and output the sorted array.

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

Keywords: Python Algorithm data structure Back-end

Added by LeslieHart on Tue, 01 Mar 2022 18:14:43 +0200