Huawei machine test questions: HJ92 Find the longest continuous number string in a string (python)

(1) Title description

insert image description here

(2) Python3 implementation

while True:
    try:
        str1 = input()
        max_len, max_str, cur_len, cur_str = 0, [], 0, ''
        for i, v in enumerate(str1):
            if v.isnumeric():
                cur_len += 1
                cur_str += v
                if cur_len > max_len:
                    max_len = cur_len
                    max_str = [cur_str]
                elif cur_len == max_len:
                    max_str.append(cur_str)
            else:
                cur_len = 0
                cur_str = ""
        print("".join(max_str) + "," + str(max_len))
    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. 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

4. String str(): Convert the parameter to a string type (forcible conversion) - a string is an ordered immutable sequence.

Function description: str(x, base=10)
Generally speaking, ordered sequence types areSupports indexing, slicing, addition, multiplication, member operations

print('返回空字符串:', str())
print('整数转换为字符串:', str(-23))
print('浮点数转换为字符串:', str(1.3e2))

print('返回空字符串:', type(str()))
print('整数转换为字符串:', type(str(-23)))
print('浮点数转换为字符串:', type(str(1.3e2)))

print('列表转换为字符串:', str([12, '-23.1', 'Python']))
print('元组转换为字符串:', str((23, '9we', -8.5)))
print('字典转换为字符串:', str({
    
    'Huawei': 'China', 'Apple': 'USA'}))
print('集合转换为字符串:', str({
    
    'China', 'Japan', 'UK'}))

'''
返回空字符串: 
整数转换为字符串: -23
浮点数转换为字符串: 130.0

返回空字符串: <class 'str'>
整数转换为字符串: <class 'str'>
浮点数转换为字符串: <class 'str'>

列表转换为字符串: [12, '-23.1', 'Python']
元组转换为字符串: (23, '9we', -8.5)
字典转换为字符串: {'Huawei': 'China', 'Apple': 'USA'}
集合转换为字符串: {'China', 'UK', 'Japan'}
'''

5. str.join(): Connect the elements in the sequence (string, tuple, list, dictionary) with the specified character and return a new string.

Function description: 'Separator'.join(Sequence)
Function description: Use Separator as the delimiter to split all elements of Sequence one by one and return a new string.
Input parameters:

  • Separator: Represents the delimiter. Can be a single character (eg: ''、','、'.'、'-'、'*'etc.) or a string (eg: 'abc').
  • Sequence: Represents the sequence of elements to be connected. Can be string, tuple, list, dictionary.
    Remark 1: Separatorand Sequenceboth can only be string type, not int type or float type, otherwise the system will report an error.
    Remark 2: The reading of the dictionary is random.
a1 = 'I Love China !'
print('字符串: ', ' '.join(a1))

a11 = 'I Love China !'
print('字符串: ', ''.join(a11))

a2 = ['I', 'Love', 'China', '!']
print('列表: ', ' '.join(a2))

a3 = ('I', 'Love', 'China', '!')
print('元祖: ', ' '.join(a3))

a4 = {
    
    'I': 1, 'Love': 2, 'China': 3, '!': 4}
print('字典: ', ' '.join(a4))

'''
字符串:  I   L o v e   C h i n a   !
字符串:  I Love China !
列表:  I Love China !
元祖:  I Love China !
字典:  I Love China !
'''
import os     	# 导入路径模块
os.getcwd()   	# 获取当前路径
data_save = os.path.join(os.getcwd(), 'data_save')  # 获取当前路径并组合新的路径
print(data_save)

6. str.isdigit(), str.isnumeric(), str.isdecimal(): Check whether the string contains only decimal numbers and return a Boolean value.

Unicode encoding range of Chinese characters and English numbers

method Unicode numbers Full-width number (double-byte) Roman numerals Chinese characters and numbers byte number (single byte) floating point number negative number Scientific notation binary Octal hexadecimal
isdecimal() True True False False Error False False False False False False
isdigit() True True False False True False False False False False False
isnumeric() True True True True Error False False False False False False
str = '123'
print(str.isdecimal())  	
print(str.isdigit())  	
print(str.isnumeric())  

'''
True
True
True
'''

7. Enumeration function - enumerate(): Input an iterable object, and get the index and value of the object at the same time. Used with for loop.

Function Description: index, value = enumerate(iteration, start)
Input Parameters:

  • iteration: Iterable object.
  • start: Custom starting index value, optional parameter, default is 0.
    Remark:Specify the starting point, and only the index corresponding to each element in the iterable object changes. That is, whether or not a starting point is specified, the iterable object is read from the first element.

Output parameters:

  • index: Index value.
  • value: The element value corresponding to the index in the iterable object.
    Feature 1: Anonymous function, that is, a function without a name.
list1 = [1,2,3,4,5,6]
for index, value in enumerate(list1):			# 默认起始点
    print(indx, value)
########################################
print('*'*10)
########################################
for indx, value in enumerate(list1, 2):			# 指定起始点
    print(indx, value)

"""
0 1
1 2
2 3
**********
5 1
6 2
7 3
"""

Guess you like

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