Home > Back-end >  split string into a custom tuple
split string into a custom tuple

Time:01-29

I have a string, like below where .. represent array and . represent struct and if nothing non_array_struct

map_str =  "entry..resource.insurance..item..authorizationRequired"

I would like to split it into below format

Desired result:

result = [("entry", "array"), ("entry..resource", "struct"), ("entry..resource.insurance", "array"),
("entry..resource.insurance..item", "array"), ("entry..resource.insurance..item..authorizationRequired", "non_array_non_struct")]

I believe we need to maintain a dictionary to identify array, struct and non_array_struct elements. May I know if there is any algorithm or data structure can help achieve the desired format.But Can't think of a way to achieve the result.

dict_mapping = {'..':'array', '.':"struct"}

CodePudding user response:

map_str =  "entry..resource.insurance..item..authorizationRequired"
# expected result provided by user
expected_result = [
    ("entry", "array"),
    ("entry..resource", "struct"),
    ("entry..resource.insurance", "array"),
    ("entry..resource.insurance..item", "array"),
    ("entry..resource.insurance..item..authorizationRequired", "non_array_non_struct"),
]

map_str_splitted = []
idx = 0
while idx < len(map_str):
    if map_str[idx] == '.':
        if idx < len(map_str) - 1 and map_str[idx:idx 2] == '..':
            map_str_splitted.append((map_str[:idx], 'array'))
            idx  = 1
        else:
            map_str_splitted.append((map_str[:idx], 'struct'))
    idx  = 1

if map_str[-1] != '.':
    map_str_splitted.append((map_str, 'non_array_non_struct'))

# print lists to compare/prove
for expected, splitted in zip(expected_result, map_str_splitted):
    print(f'expected: {expected}')
    print(f'splitted: {splitted}')

Output:

expected: ('entry', 'array')
splitted: ('entry', 'array')
expected: ('entry..resource', 'struct')
splitted: ('entry..resource', 'struct')
expected: ('entry..resource.insurance', 'array')
splitted: ('entry..resource.insurance', 'array')
expected: ('entry..resource.insurance..item', 'array')
splitted: ('entry..resource.insurance..item', 'array')
expected: ('entry..resource.insurance..item..authorizationRequired', 'non_array_non_struct')
splitted: ('entry..resource.insurance..item..authorizationRequired', 'non_array_non_struct')
  • Related