fork(24) download
  1. '''
  2. Score validator for PPCG question 'Brainfuck subprograms with unique outputs'
  3.  
  4. Expects brainfuck code from standard input.
  5.  
  6. Forked from https://g...content-available-to-author-only...b.com/TieSoul/Multilang/blob/master/brainfuck.py
  7. '''
  8.  
  9. def balanced(r):
  10. o=0
  11. for c in r:
  12. if c=='[':
  13. o+=1
  14. elif c==']':
  15. o-=1
  16. if o<0:
  17. return False
  18. if o==0:
  19. return True
  20. else:
  21. return False
  22.  
  23. def evaluate(r,maxstep=20000):
  24. if not balanced(r):
  25. return None
  26. s = [0]
  27. i = 0
  28. j = 0
  29. step = 0
  30. try:
  31. while j in range(len(r)) and step < maxstep:
  32. if r[j] == '>':
  33. i += 1
  34. if i >= len(s):
  35. s.append(0)
  36. elif r[j] == '<':
  37. i -= 1
  38. if i < 0:
  39. return None
  40. elif r[j] == '+':
  41. s[i] = (s[i] + 1) % 256
  42. elif r[j] == '-':
  43. s[i] = (s[i] - 1) % 256
  44. elif r[j] == '.':
  45. return s[i]
  46. elif r[j] == ',':
  47. s[i] = 0
  48. elif r[j] == '[':
  49. if s[i] == 0:
  50. loopcount = 1
  51. while loopcount > 0:
  52. j += 1
  53. if r[j] == '[':
  54. loopcount += 1
  55. elif r[j] == ']':
  56. loopcount -= 1
  57. elif r[j] == ']':
  58. if s[i] != 0:
  59. loopcount = 1
  60. while loopcount > 0:
  61. j -= 1
  62. if r[j] == ']':
  63. loopcount += 1
  64. elif r[j] == '[':
  65. loopcount -= 1
  66. j += 1
  67. step += 1
  68. return None
  69. except:
  70. return None
  71.  
  72. if __name__ == '__main__':
  73. s=input()
  74. vs=set()
  75. for i in range(len(s)):
  76. subs=s[0:i]+s[i+1:]
  77. v=evaluate(subs)
  78. vs.add(v)
  79. print(subs,'=>',v)
  80. vs.discard(None)
  81. print('\nUnique outputs are',sorted(vs))
  82. print('\nScore is ',len(vs),' for ',s,' (length = ',len(s),')',sep='')
Success #stdin #stdout 0.07s 8736KB
stdin
++,+[-]+><.-,-.
stdout
+,+[-]+><.-,-. => 1
+,+[-]+><.-,-. => 1
+++[-]+><.-,-. => 1
++,[-]+><.-,-. => 1
++,+-]+><.-,-. => None
++,+[]+><.-,-. => None
++,+[-+><.-,-. => None
++,+[-]><.-,-. => 0
++,+[-]+<.-,-. => None
++,+[-]+>.-,-. => 0
++,+[-]+><-,-. => 255
++,+[-]+><.,-. => 1
++,+[-]+><.--. => 1
++,+[-]+><.-,. => 1
++,+[-]+><.-,- => 1

Unique outputs are [0, 1, 255]

Score is 3 for ++,+[-]+><.-,-. (length = 15)