Facebook
From Anorexic Plover, 3 Years ago, written in Plain Text.
Embed
Download Paste or View Raw
Hits: 54
  1. # zad 2
  2. class Stos:
  3.  
  4.     def __init__(self):
  5.  
  6.         self.s = []
  7.  
  8.     def push(self, x):
  9.  
  10.         # assert self.size() < 20, "Too many elements"
  11.  
  12.         self.s.append(x)
  13.  
  14.     def pop(self):
  15.  
  16.         assert not self.is_empty(), "Stack is empty"
  17.  
  18.         return self.s.pop(-1)
  19.  
  20.     def top(self):
  21.  
  22.         assert not self.is_empty(), "Stack is empty"
  23.  
  24.         return self.s[-1]
  25.  
  26.     def size(self):
  27.  
  28.         return len(self.s)
  29.  
  30.     def is_empty(self):
  31.  
  32.         return not bool(len(self.s))
  33.  
  34.    
  35.  
  36. def ciag_nawiasowy_poprawny(s):
  37.  
  38.     """Zwraca 'TAK' jesli podany ciag nawiasowy (string) jest poprawny,
  39.  
  40.     w przeciwnym wypadku 'NIE'."""
  41.  
  42.     nawiasy = {
  43.  
  44.         "{": "}",
  45.  
  46.         "[": "]",
  47.  
  48.         "(": ")",
  49.  
  50.         "<": ">",
  51.  
  52.     }
  53.  
  54.     ciag = Stos()
  55.  
  56.     for c in s:
  57.  
  58.         if c in nawiasy:
  59.  
  60.             ciag.push(c)
  61.  
  62.         elif nawiasy[ciag.top()] == c:
  63.  
  64.             ciag.pop()
  65.  
  66.         else:
  67.  
  68.             return "NIE"
  69.  
  70.     if ciag.is_empty():
  71.  
  72.         return "TAK"
  73.  
  74.     return "NIE"
  75.  
  76.        
  77.  
  78. print(ciag_nawiasowy_poprawny("{{[()()]}}"))  # TAK
  79.  
  80. print(ciag_nawiasowy_poprawny("([)()]"))  # NIE
  81.  
  82.  
  83. print(ciag_nawiasowy_poprawny("([(){}])[]"))  # TAK
  84.  
  85. print(ciag_nawiasowy_poprawny("([(){}]>"))  # NIE
  86.  
  87. print(ciag_nawiasowy_poprawny("([(){}>)"))  # NIE
  88.  
  89. print(ciag_nawiasowy_poprawny("([(]))"))  # NIE