Huawei machine test questions: HJ95 RMB conversion (python)

(1) Title description

insert image description here

(2) Python3 implementation

under10 = '零壹贰叁肆伍陆柒捌玖'

def helper(num):
    if num == 0:
        return ''					# 删除0
    elif num < 10:
        return under10[num]			# 大小写转换
    elif num < 20:					# (20以内)规则生成
        if num % 10 == 0:
            return '拾'
        else:
            return '拾' + helper(num%10)
    elif num < 100:					# (100以内)十位数规则生成
        if num % 10 == 0:
            return helper(num//10) + '拾'
        else:
            return helper(num//10) + '拾' + helper(num%10)
    elif num < 1000:				# (1000以内)百位数规则生成
        if num % 100 == 0:
            return helper(num//100) + '佰'
        elif 0 < num % 100 <= 9:
            return helper(num//100) + '佰零' + helper(num%100)
        else:
            return helper(num//100) + '佰' + helper(num%100)
    elif num < 10000:				# (1万以内)千位数规则生成
        if num % 1000 == 0:
            return helper(num//1000) + '仟'
        elif 0 < num % 1000 <= 99:
            return helper(num//1000) + '仟零' + helper(num%1000)
        else:
            return helper(num//1000) + '仟' + helper(num%1000)
    elif num < 100000000:			# (1亿以内)千万位数规则生成
        if num % 10000 == 0:
            return helper(num//10000) + '万'
        elif 0 < num % 10000 <= 999:
            return helper(num//10000) + '万零' + helper(num%10000)
        else:
            return helper(num//10000) + '万' + helper(num%10000)
    elif num < 1000000000000:		# (万亿以内)千亿位数规则生成
        if num % 100000000 == 0:
            return helper(num//100000000) + '亿'
        elif 0 < num % 100000000 <= 9999999:
            return helper(num//100000000) + '亿零' + helper(num%100000000)
        else:
            return helper(num//100000000) + '亿' + helper(num%100000000)
    else:
        return ''					# 若不在当前范围,则取消整数部分输出。
        
while True:
    try:
        num1, num2 = list(map(int, input().split('.')))
        chinese = '人民币'
        chinese += helper(num1)
        if chinese != '人民币':				# 整数位(单位:元)
            chinese += '元'
        if 0 < num2 < 10:					# 第二个小数位(单位:分)
            chinese += under10[num2] + '分'
        elif num2 == 0:						# 小数位为空
            chinese += '整'
        else:								# 第一个小数位(单位:角)
            if num2%10 != 0:
                chinese += under10[num2//10] + '角' + under10[num2%10] + '分'
            else:							# 第二个小数位为空
                chinese += under10[num2//10] + '角'
        print(chinese)
    except:
        break
        

(3) Detailed explanation of knowledge points

1. input(): Get the input of the console (in any form). The output is all string type.

str1 = input()
print(str1)
print('提示语句:', str1)
print(type(str1))

'''
asd123!#
提示语句: asd123!#
<class 'str'>
'''
Commonly used forced transfer types illustrate
int(input()) Forced to an integer (the input must be an integer)
list(input()) Coerce to list (input can be of any type)

1.1. The difference between input() and list(input()) and their mutual conversion methods

  • Same point: Both methods can perform a for loop iteration to extract characters, and both are string types after extraction.
  • difference: str = list(input())Convert the input string to list type, and related operations can be performed. like: str.append()
  • Convert list to string:str_list = ['A', 'aA', 2.0, '', 1]
  • method one:print(''.join(str))
  • Method Two:print(''.join(map(str, str_list)))

Remark:If the list contains numbers, it cannot be directly converted into a string, otherwise the system reports an error.

  • method one:print(''.join([str(ii) for ii in str_list]))
  • Method 2: print(''.join(map(str, str_list)))
    map(): Map the specified sequence according to the given function. That is, the incoming function is applied to each element of the sequence in turn, and a new sequence is returned.

(1) Example: If the list contains numbers, it cannot be directly converted into a string, otherwise the system will report an error.

str = ['25', 'd', 19, 10]
print(' '.join(str))

'''
Traceback (most recent call last):
 File "C:/Users/Administrator/Desktop/test.py", line 188, in <module>
   print(' '.join(str))
TypeError: sequence item 3: expected str instance, int found
'''

(2) Example: If the list contains numbers, convert all elements in the list to strings.

str_list = ['A', 'aA', 2.0, '', 1]
print(''.join(str(ii) for ii in str_list))
print(''.join([str(ii) for ii in str_list]))
print(''.join(map(str, str_list))) 		# map():根据给定函数对指定序列进行映射。即把传入函数依次作用到序列的每一个元素,并返回新的序列。

'''
AaA2.01
AaA2.01
AaA2.01
'''

2. print(): print output.

[Python] usage of print() function

x, y = 1, 9
print('{},{}' .format(x, y))	# 打印方法一
print('*'*10)					# 打印分割符
print(x, ',', y)				# 打印方法二

'''
1,9
**********
1 , 9
'''

3. Integer type int(): Convert a string or number in the specified base system (default decimal system) to a decimal integer type (forced conversion).

  • Python2 has long int type,And Python3 integer has no range limit, so it can be used as long int.
  • Boolean type bool is a subtype of integer, including two types: True == 1、False == 0.

Function Description: int(x, base=10)
Input Parameters:

  • x: string or number (integer, float).
  • base: 默认十进制.
    Remark 1: If there is a parameter base, it means to convert the (binary, decimal, hexadecimal) x to decimal.
    Remark 2: If the parameter base is used, the input must be an integer, and the integer must be input in the form of a string.
enter return value example output
int('整数', base=16) The input integer is specified as hexadecimal, and converted to decimal integer (similarly: other hexadecimal) print(int('20', 16))andprint(int('0XAA', 16)) 32 and 170
(1) The input is empty or an integer \ \ \
int() \ print(int()) 0
int(浮点数) \ print(int(-2.1)) -2
(2) input as a string \ \ \
int(字符串) \ print(int('-2')) -2
int(字符串(浮点数)) It is necessary to convert str to float first, and then to int, otherwise an error will be reported. print(int(float('-2.1'))) -2

Convert decimal to hexadecimal

hex range: 0 ~ 65536(0000 ~ FFFF)
method:

  • (1) Divide a decimal number by 16 (取余数1)to get a quotient of 1
  • (2) Divide quotient 1 by 16 (取余数2)to get quotient 2
  • (3) Divide quotient 2 by 16 (取余数3)to get quotient 3
  • (4) The final quotient 3 is equal to 0 (取余数4).
  • The final result is the reverse remainder = [余数4, 余数3, 余数2, 余数1].

Example (integer: 65036) :
(1) When 65036 is divided by 16, the quotient is 4064, and the remainder is 12 (hexadecimal C)
(2) When 4064 is divided by 16, the quotient is 254, and the remainder is 0 (hexadecimal 0)
(3) When 254 is divided 16, quotient 15, remainder 14 (hexadecimal E)
(4) 15 divided by 16, quotient 0, remainder 15 (hexadecimal F).
(5) End: get hexadecimal = FE0C

decimal 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
Hexadecimal 0 1 2 3 4 5 6 7 8 9 A B C D E F
Binary 0000 0001 0010 0011 0100 0101 0110 0111 1000 1001 1010 1011 1100 1101 1110 1111

3.1, bin(): Convert decimal integers to binary codes. The return value is a string.

Function description:bin(整型)

print(bin(-3))
print(type(bin(-3)))

'''
-0b11
<class 'str'>
'''

3.2, ord(): ASCII characters are converted to decimal integers (Unicode characters - Unicode values).

Function description:ord(字符)

print(ord('A'))
print(type(ord('A')))

'''
65
<class 'int'>
'''

3.3. chr(): convert decimal or hexadecimal numbers into ASCII characters. (Unicode value - Unicode character).

Function description:chr(number)

print(chr(97))
print(type(chr(97)))

'''
a
<class 'str'>
'''

4. map(): Apply the specified function to each element in the sequence in turn—return an iterator, and the result needs to be converted and output by specifying the data structure.

Function Description: map(function, iterable)
Input Parameters:

  • function: Specifies the function.
  • iterable: iterable object
print('返回一个迭代器: ', map(int, (1, 2, 3)))
# 返回一个迭代器:  <map object at 0x0000018507A34130>

The result needs to specify the data structure for conversion and output

  • Data structure: list, tuple, set. output after conversion
  • Data structure: str. returns an iterator
  • Data structure: dict. ValueError, two parameters are required
print('将元组转换为list: ', list(map(int, (1, 2, 3))))
print('将字符串转换为list: ', tuple(map(int, '1234')))
print('将字典中的key转换为list: ', set(map(int, {
    
    1: 2, 2: 3, 3: 4})))

'''
将元组转换为list:  [1, 2, 3]
将字符串转换为list:  (1, 2, 3)
将字典中的key转换为list:  {1, 2, 3}
'''

################################################################################
dict_a = [{
    
    'name': 'python', 'points': 10}, {
    
    'name': 'java', 'points': 8}]
print(list(map(lambda x : x['name'] == 'python', dict_a)))
print(dict(map(lambda x : x['name'] == 'python', dict_a)))

"""
[True, False]
TypeError: cannot convert dictionary update sequence element #0 to a sequence
"""

5. Common operations of lists (15+9 functions) —— A list is an ordered variable sequence.

In general, ordered sequence types support indexing, slicing, addition, multiplication, and member operations.

  • Immutable data types :布尔类型(bool)、整型(int)、字符串(str)、元组(tuple)
  • Mutable data types :列表(list)、集合(set)、字典(dict)
serial number function illustrate
0 list1 = [] create empty list
0 list1 = list() create empty list
1 list2 = [元素] Create lists. Input parameters can be of any type
1 list2 = list(元素) Create lists. Input parameters can be of any type
—— —— ——
2 list[index] index (negative numbers indicate flashbacks)
3 list[start, end] slice (get the specified range of elements)
4 list[::-1] Output in reverse order (step size is 1)
—— —— ——
5 list.append(元素) Add an element of any type to the end of the list
6 list.extend(元素) add iterable sequence
7 list.insert(index, 元素) Insert an element at the specified position
—— —— ——
8 list.remove(元素) Delete the specified element. (1) If there are multiple identical elements, only the first element will be deleted. (2) If it does not exist, the system will report an error.
9 list.pop(index) Delete the element at the specified position. The last item is deleted by default.
10 del list(index) Delete the element at the specified position
11 list.clear() Clear the content, return an empty list
—— —— ——
12 list.index(元素) Index element position. (1) If there are multiple identical elements, only the position of the first element will be returned. (2) If it does not exist, the system will report an error.
13 list.count(元素) Count the number of occurrences of the specified element
14 list.reverse() output in reverse order
15 list.sort(*, key=None, reverse=False) (1) Arrange from small to large by default. (2) reverse=True means sorting from big to small.
—— —— ——
(1) len(list) number of elements
(2) type(list) view data type
(3) max(list) Returns the largest value (cannot have nested sequences)
(4) min(list) returns the minimum value (cannot have nested sequences)
(5) list(tuple) convert tuple to list
(6) list1 + list2 + operator (concatenation)
(7) list * 3 * operator (repeat)
(8) 元素 in list (in / not in) membership operator (determines whether a given value is in a sequence)
(9) for i in list: traverse

6. str.split(): Slice the string by specifying the delimiter (space by default), and return the split string list (list).

Function Description: str.split(str=".", num=string.count(str))[n]
Parameter Description:

  • str: Indicates the delimiter, which is a space by default, but cannot be empty. If there are no delimiters in the string, the entire string is treated as an element of the list.
  • num: Indicates the number of divisions. If the parameter num is present, only num+1 substrings are separated, and each substring can be assigned to a new variable.
  • [n]: Indicates that the nth slice is selected.
    • Note: When using spaces as delimiters, items that are empty in the middle will be ignored automatically.
s = 'www.dod.com.cn'
print('分隔符(默认): ', s.split())                    # 【输出结果】分隔符(默认):  ['www.dod.com.cn']
print('分隔符(.): ', s.split('.'))                   # 【输出结果】分隔符(.):  ['www', 'dod', 'com', 'cn']
print('分割1次, 分隔符(.): ', s.split('.', 1))        # 【输出结果】分割1次, 分隔符(.):  ['www', 'dod.com.cn']
print('分割2次, 分隔符(.): ', s.split('.', 2))        # 【输出结果】分割2次, 分隔符(.):  ['www', 'dod', 'com.cn']
print('分割2次, 分隔符(.), 取出分割后下标为1的字符串: ', s.split('.', 2)[1])      # 【输出结果】分割2次, 分隔符(.), 取出分割后下标为1的字符串:  dod
print(s.split('.', -1))                             # 【输出结果】['www', 'dod', 'com', 'cn']
###########################################
# 分割2次, 并分别保存到三个变量
s1, s2, s3 = s.split('.', 2)
print('s1:', s1)                                    # 【输出结果】s1: www
print('s2:', s1)                                    # 【输出结果】s2: www
print('s3:', s2)                                    # 【输出结果】s3: dod
###########################################
# 连续多次分割
a = 'Hello<[www.dodo.com.cn]>Bye'
print(a.split('['))                                 # 【输出结果】['Hello<', 'www.dodo.com.cn]>Bye']
print(a.split('[')[1].split(']')[0])                # 【输出结果】www.dodo.com.cn
print(a.split('[')[1].split(']')[0].split('.'))     # 【输出结果】['www', 'dodo', 'com', 'cn']

Guess you like

Origin blog.csdn.net/shinuone/article/details/129392186