Advertisement
go6odn28

ranges-2

May 30th, 2024
97
0
Never
1
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.81 KB | None | 0 0
  1. import re
  2.  
  3.  
  4. class RangeParser:
  5.     def __init__(self, ranges_):
  6.         self.ranges_str = ranges_
  7.         self.result = []
  8.         self.parse_ranges()
  9.  
  10.     def parse_ranges(self):
  11.         pattern = re.compile(r'(\d+)-(\d+)')
  12.         ranges_list = self.ranges_str.split(',')
  13.         for record in ranges_list:
  14.             match = pattern.match(record)
  15.             if match:
  16.                 start, end = int(match.group(1)), int(match.group(2))
  17.                 self.add_range(start, end)
  18.  
  19.     def add_range(self, start, end):
  20.         for num in range(start, end + 1):
  21.             self.result.append(num)
  22.  
  23.     def get_result(self):
  24.         return self.result
  25.  
  26.  
  27. ranges_str = '1-2,8-15,23-25'
  28. parser = RangeParser(ranges_str)
  29. print(parser.get_result())
  30. # [1, 2, 8, 9, 10, 11, 12, 13, 14, 15, 23, 24, 25]
  31.  
Advertisement
Comments
  • Nenogzar
    175 days
    # Python 0.52 KB | 0 0
    1. class ParseRange:
    2.     def __init__(self, ranges_string):
    3.         self.ranges_string = ranges_string
    4.         self.numbers = []
    5.         self.ranges = self.ranges_string.split(',')
    6.  
    7.     def parse_ranges(self):
    8.         for r in self.ranges:
    9.             start, end = map(int, r.split('-'))
    10.             self.numbers.extend(range(start, end + 1))
    11.         return self.numbers
    12.  
    13.  
    14. parser = ParseRange('1-2,8-15,23-25')
    15. print(parser.parse_ranges())
    16.  
    17. parser = ParseRange('0-0, 4-8, 20-20, 43-45')
    18. print(parser.parse_ranges())
Add Comment
Please, Sign In to add comment
Advertisement