当前位置:网站首页>freeCodeCamp----arithmetic_ Arranger exercise

freeCodeCamp----arithmetic_ Arranger exercise

2022-04-23 13:51:00 Lily's autumn

Catalog

1 subject

2 Specify requirements

3 Thought analysis

3.1 Split input parameters

3.2 Determine whether the printing conditions are met

3.3 Printing and typesetting ( alignment )

3.4 The second parameter is True

3.5 arithmetic_arranger function

3 arithmetic_arranger.py

4 Common error reports


1 subject

Simply put, it is the vertical calculation of printing addition and subtraction

2 Specify requirements

  1. Two parameters , The first parameter is the data to be calculated , The second parameter is bool value ,TRUE You need to print the vertical calculation results at the same time ,FALSE You don't need to ;
  2. Enter at most... At a time 5 Group data , More than that, return to :Error: Too many problems.
  3. Operator only supports addition and subtraction , Other return :Error: Operator must be '+' or '-'.
  4. Enter the calculated data (operand) Only numbers... Are supported , Otherwise return to :Error: Numbers must only contain digits.
  5. The biggest support 4 Digit operation , Otherwise return to :Error: Numbers cannot be more than four digits.

3 Thought analysis

The general idea is to write and print a vertical function first basic_num(), then arithmetic_arranger() According to the parameters passed in , Call the printing function in turn basic_num(),

3.1 Split input parameters

Analyze ideas according to test cases :

arithmetic_arranger(["32 + 8", "1 - 3801", "9999 + 9999", "523 - 49"], True)

Don't consider the second parameter first , Treat the first parameter as a two-dimensional array blocks=[block1,block2,block3...] And the length should not exceed 5, namely len(blocks)<5;  

arithmetic_arranger(blocks,result)

In this case, the first parameter is block Every element of is string type ( for example :"32 + 8"), Each one string Split into... According to the space operand[0]、operator and operand[1], And deposit in block Array ( example :block = [ 32 , '+' , 8 ] ), among operand It's just numbers , And the biggest is 4 digit len(operand)<4,operator Can only be + perhaps - Number ;

here :

block=[operand[0],operator,operand[1]]

3.2 Determine whether the printing conditions are met

First judge whether the conditions are met , Once it does not meet the requirements, the subsequent code does not need to be executed , Direct printing error .

Enter the calculated data (operand) Only numbers... Are supported , Otherwise return to :Error: Numbers must only contain digits.

#  if operand exceed 2 A or operator More than one , Indicates that there is a non digital input 
    if len(operand) > 2 or len(operator) > 1:
        return "Error: Numbers must only contain digits."

The biggest support 4 Digit operation , Otherwise return to :Error: Numbers cannot be more than four digits.

# operand The length itself is 2, There are 2 A digital ,operand[0] and operand[1]
    #  Only accept the two largest numbers 4 Digit operation , The length exceeds 4 An error will be reported in the first place 
    if len(operand[0]) > 4 or len(operand[1]) > 4:
        return "Error: Numbers cannot be more than four digits."

Operator only supports addition and subtraction , Other return :Error: Operator must be '+' or '-'.

#  Operator only supports + and -
#  Use here operator[0] The reason is that ,operator Itself is an array ,operator[0] It's an element , And it's a string 
    if operator[0] not in ('+', '-'):
        return "Error: Operator must be '+' or '-'."

There are two remaining requirements , Need to be on the top arithmetic_arranger() Function .

3.3 Printing and typesetting ( alignment )

A vertical display is about the following :

 

We'll show that it's divided into 4 That's ok , The width is set as the maximum digital width plus two digits, that is maxlen+2 , A left operator , The other is a space , Prevent carry generation .

The first line is operand[0]; The second line is operator[0]+ Space +operand[1]; The third line is the dividing line '-', The length is maxlen+2, The fourth line is the result of the calculation ( If any ), These four lines need to be aligned to the right .

block = [operand[0].rjust(maxlen + 2), operator[0]+' '+operand[1].rjust(maxlen), '-'*(maxlen+2)]

3.4 The second parameter is True

Now give block Add the fourth line

block.append(str(int(operand[0]) + int(operand[1])).rjust(maxlen + 2))

The added line is divided into two cases , The operator is + perhaps -, All the steps are to calculate the result according to the operator , And then the length maxlen+2, Align right .

Don't worry, the result is more than 6 Bit situation , because rjust() Function , If the specified length is less than the length of the string, the original string is returned .

3.5 arithmetic_arranger function

After the basic printing function is completed ,arithmetic_arranger Call... In turn according to the passed in parameters , Before calling, you need to judge the incoming data , Enter at most... At a time 5 Group data , More than that, return to :Error: Too many problems.

This is not hard to , Judge the length .

The next step is to judge whether the second parameter is True, if ,basic_num() The print function is 4 That's ok , Include result lines , Otherwise, it would be 3 That's ok .

There's nothing to write , Pay attention to :

1. Although the vertical display is vertical , But it is printed horizontally , The first line is the first vertical first line + The second vertical first line + The third vertical first line +…… The second line in turn ;

2. Between two vertical should be added 4 Separate with a space , In which position , See source code ;

3. Remember to add a line break at the end of each line , Otherwise, it is obviously incorrect to pile them all in one line ;

3 arithmetic_arranger.py

arithmetic_arranger.py See the source code below

The content has reference bloggers :FreeCodeCamp----Scientific Computing with Python Projects----Arithmetic Formatter_m0_43406494 The blog of -CSDN Blog AssignmentStudents in primary school often arrange arithmetic problems vertically to make them easier to solve. For example, “235 + 52” becomes: 235+ 52-----Create a function that receives a list of strings that are arithmetic problems and returns https://blog.csdn.net/m0_43406494/article/details/112731471?ops_request_misc=%257B%2522request%255Fid%2522%253A%2522163633257116780264054904%2522%252C%2522scm%2522%253A%252220140713.130102334.pc%255Fall.%2522%257D&request_id=163633257116780264054904&biz_id=0&utm_medium=distribute.pc_search_result.none-task-blog-2~all~first_rank_ecpm_v1~rank_v31_ecpm-1-112731471.first_rank_v2_pc_rank_v29&utm_term=Students+in+primary+school+often+arrange+arithmetic+problems+vertically+to+make+them+easier+to+solve.+For+example%2C+%22235+%2B+52%22+becomes%3A&spm=1018.2226.3001.4187


The notes have been written very clearly , as follows : 

# def arithmetic_arranger(problems):


#     return arranged_problems
#  introduce  re  Module enable  Python  The language has all the regular expression functions 
import re
#  Single problem Function of , Multiple problems This function can be called in turn ,a In the form of '21 + 23'
def basic_num(a, xxx):
    # re.findall(pattern, string)
    #  Find all the substrings that the regular expression matches in the string , And return a list , If no match is found , Then return to the empty list .
    # operand Filter out numbers 
    # operator Find the operation symbol 
    operand = re.findall(r'\d+', a)
    operator = re.findall(r'[^\d ]', a)

    #  According to the meaning of the question :
    #  if operand exceed 2 A or operator More than one , Indicates that there is a non digital input 
    if len(operand) > 2 or len(operator) > 1:
        return "Error: Numbers must only contain digits."

    # operand The length itself is 2, There are 2 A digital ,operand[0] and operand[1]
    #  Only accept the two largest numbers 4 Digit operation , The length exceeds 4 An error will be reported in the first place 
    if len(operand[0]) > 4 or len(operand[1]) > 4:
        return "Error: Numbers cannot be more than four digits."

    #  Operator only supports + and -
    if operator[0] not in ('+', '-'):
        return "Error: Operator must be '+' or '-'."

    #  Find the maximum length , Prepare for back alignment 
    #  Use the maximum length plus two digits of width , One bit left to operator , A bit is used as a space to prevent negative numbers in addition, carry and subtraction 
    maxlen = max(len(operand[0]), len(operand[1]))

    # rjust() Returns an original string to the right , And use fillchar Fill to length width New string of 
    #  Returns the original string if the specified length is less than the length of the string 
    # width-- Specify the total length after filling ;fillchar-- Filled characters , Default is space 
    # str.rjust(width[, fillchar])
    #  Output block Display in three lines :
    #  The first line is the first number operand[0], The length is maxlen+2( Two more , A given operator , The other is used as a space ), Align right 
    #  The second line starts with the operator operator[0], Then there are spaces , Finally, the second number , The length is maxlen, Align right 
    #  The third line is all '-', As a dividing line , The length is maxlen+2, Align right 
    #  Note that there operator Is an array , To splice, you must use the elements inside 
    block = [operand[0].rjust(maxlen + 2), operator[0]+' '+operand[1].rjust(maxlen), '-'*(maxlen+2)]

    #  If the second parameter is TRUE, You need to block Add a row 
    #  The added line is divided into two cases , The operator is + perhaps -, All the steps are to calculate the result according to the operator , And then the length maxlen+2, Align right 
    #  Don't worry, the result is more than 6 Bit situation , because rjust() Function , If the specified length is less than the length of the string, the original string is returned 
    if xxx == True:
        if operator[0] == '+':
            block.append(str(int(operand[0]) + int(operand[1])).rjust(maxlen + 2))
        if operator[0] == '-':
            block.append(str(int(operand[0]) - int(operand[1])).rjust(maxlen + 2))
    # print(block)
    return block

#  Define vertical functions 
#  Ideas as follows :
#  First judge whether the element in the first parameter exceeds 5 individual , If more than , Returns an error ( The topic requires a maximum of 5 Vertical )
#  Traverse problems All elements in ,basic_num function , Back to block Deposit... In turn blocks Array ,
def arithmetic_arranger(problems, result = False):
    if len(problems) > 5:
        return "Error: Too many problems."
    if result:
        count = 4
    else:
        count = 3
    #  Define a two-dimensional array blocks, Because every element in it block They're all one-dimensional arrays 
    blocks = []
    for s in problems:
        blocks.append(basic_num(s, result))
        #  If there is an error , You just quit , Output error content 
        #  What needs ideas here is , The judgment is blocks[-1], Because errors may occur in the first or last group , No matter which position is the last element 
        #  At the same time judge blocks[-1] Whether the type of is a string , Because the right thing to do is list
        print(blocks)
        if (type(blocks[-1]) == str):
            return blocks[-1]
    arranged_problems = ''
    for i in range(count):
        for j in blocks:
            arranged_problems += j[i]+(' '*4)
            #  The following judgment is to reach the end of each line , Do not add the space in the previous step 
            if j == blocks[-1]:
              arranged_problems = arranged_problems[0:-4] # It doesn't contain -4 Location 
        arranged_problems += '\n'
    #  Use [0:-1] To remove the blank line in the last line 
    return arranged_problems[0:-1]


# if __name__ == "__main__":
#     print(arithmetic_arranger(["11222 + 815", "454 - 8125", "123 - 49", "888 - 40", "653 + 87"], True))




4 Common error reports

  1. Error Printing of , Note that even spaces and punctuation should be consistent with the requirements of the topic , Otherwise, there will be errors in the test , I can't find the problem for a long time ;
  2. Notice the hidden spaces , For example, does the end of each line also add 4 A space ? You can't pass the test ;
  3. Notice the blank line on the last line , Need to get rid of it. , Or you won't pass the test ;
  4. The second parameter needs to be set. The default value is False, Avoid giving an error when the second parameter is not given .

版权声明
本文为[Lily's autumn]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/04/202204230555127106.html