Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Python – convert string to array

I have a string that I want to convert to an array in python. The string has a few possible formats:

  1. Xstart(xstep)Xend,X2.
  2. Xstart(xstep)Xend
  3. X1,X2,X3
  4. X1

For example:

  1. 6(6)24 should give me [6,12,18,24].
  2. 6(6)24,48 should give me [6,12,18,24,48]
  3. 6,24,42,50 should give me [6,24,42,50]
  4. 6 should give me [6]

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

A naive solution without using a regex could be to just split on ',' and then look for the presence of an opening bracket indicating the presence of a step:

from prettytable import PrettyTable
from typing import NamedTuple

def str_to_extracted_list(s: str) -> list[int]:
    extracted_list = []
    s_parts = s.split(',')
    for part in s_parts:
        if '(' in part:
            opening_pos = part.find('(')
            ending_pos = part.find(')')
            start = int(part[:opening_pos])
            step = int(part[part.find('(') + 1:part.find(')')])
            end = int(part[ending_pos + 1:])
            x = start
            while x <= end:
                extracted_list.append(int(x))
                x += step
        else:
            extracted_list.append(int(part))
    return extracted_list

class TestCase(NamedTuple):
    s: str
    expected: list[int]

def main() -> None:
    t = PrettyTable(['s', 'expected', 'actual'])
    t.align = "l"
    for s, expected in [TestCase(s='6(6)24', expected=[6, 12, 18, 24]),
                        TestCase(s='6(6)24,48', expected=[6, 12, 18, 24, 48]),
                        TestCase(s='6,24,42,50', expected=[6, 24, 42, 50]),
                        TestCase(s='6', expected=[6])]:
        t.add_row([s, expected, str_to_extracted_list(s)])
    print(t)

if __name__ == '__main__':
    main()

Output:

+------------+---------------------+---------------------+
| s          | expected            | actual              |
+------------+---------------------+---------------------+
| 6(6)24     | [6, 12, 18, 24]     | [6, 12, 18, 24]     |
| 6(6)24,48  | [6, 12, 18, 24, 48] | [6, 12, 18, 24, 48] |
| 6,24,42,50 | [6, 24, 42, 50]     | [6, 24, 42, 50]     |
| 6          | [6]                 | [6]                 |
+------------+---------------------+---------------------+
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading