fork download
  1. from copy import deepcopy
  2. class Stack:
  3. def __init__(self):
  4. self._values = []
  5. return
  6.  
  7. def is_empty(self):
  8. if self._values == []:
  9. r = True
  10. else:
  11. r=False
  12. return r
  13.  
  14. def push(self, value):
  15. self._values.append(deepcopy(value))
  16. return
  17.  
  18. def pop(self):
  19. assert len(self._values) > 0, "Cannot pop from an empty stack"
  20. value=self._values.pop()
  21. return value
  22.  
  23. def peek(self):
  24. assert len(self._values) > 0, "Cannot peek at an empty stack"
  25. value=self._values[-1]
  26. return value
  27.  
  28. def reroute(opstring, values_in):
  29. """
  30. -------------------------------------------------------
  31. Reroutes values in a list according to a operating string and
  32. returns a new list of values. values_in is unchanged.
  33. In opstring, 'X' means push onto stack,
  34. 'S' means pop from stack into values_out.
  35. Use: values_out = reroute(opstring, values_in)
  36. -------------------------------------------------------
  37. Preconditions:
  38. opstring - String containing only 'S' and 'X's (str)
  39. values_in - A valid list (list of ?)
  40. Postconditions:
  41. returns
  42. values_out - if opstring is valid then values_out contains a
  43. reordered version of values_in, otherwise returns
  44. None (list of ?)
  45. -------------------------------------------------------
  46. """
  47. st=Stack()
  48. vo=[]
  49. i=0
  50. j=0
  51. while i<len(opstring):
  52. if opstring[i]=='X':
  53. st.push(values_in[j])
  54. j+=1
  55. elif opstring[i]=='S':
  56. if st.is_empty()==False:
  57. vo=vo.append(st.pop())
  58. else:
  59. return None
  60. i+=1
  61. return vo
  62.  
  63. out=[]
  64. out= reroute("XXSSXXSS",[1,2,3,4])
  65. print out
Runtime error #stdin #stdout #stderr 0.01s 9008KB
stdin
Standard input is empty
stdout
Standard output is empty
stderr
Traceback (most recent call last):
  File "prog.py", line 64, in <module>
  File "prog.py", line 57, in reroute
AttributeError: 'NoneType' object has no attribute 'append'