Tell me more ×
Programming Puzzles & Code Golf Stack Exchange is a question and answer site for programming puzzle enthusiasts and code golfers. It's 100% free, no registration required.

Based on this closed question on stack overflow, what is the shortest way to stimulate scope for variables in an input. For simplicity, print is replaced with >.

copying critical information from the linked source:

[ and ] start and end a new scope.

Within scopes any changes to a variable outside of that scope is not permanent and is reverted when the scope has left, but the outer values are used to determine if a variable is undefined and its starting value.

Input will always start with [ and will end with matching ]
If its not defined then value should be 0
All input that is not a variable is a number with no decimal points. as in 10 or 582
> a means print the contents of a
a 10 assigns 10 to a
a b assigns the contents of b to a
Variables should be considered strings: one 1 is valid syntax
It is not required for the input to contain the print command >

Note on scoring:

You may chose how to input and output the "code", but it should be explained in the answer.

I answered this on the linked page in java, but I did not go for shortest code.
Comment any suggestions or questions, so I can improve my future posts. Shortest code by character wins. Good luck.

share|improve this question
What is meant by "All input that is not a variable is an integer"? And why mention Java, which is actually quite different? – Peter Taylor Feb 7 at 8:17

2 Answers

up vote 1 down vote accepted

Python, 165

def f(v):
 while 1:
    s=raw_input().split()
    if'['in s:f(dict(v))
    elif']'in s:break
    elif'>'in s:print v.get(s[1],0)
    else:v[s[0]]=v.get(s[1],s[1])
raw_input()
f({})

Character count assumes tabs are used for the second level of indentation.

share|improve this answer
1  
Nice solution. c=b in v and v[b]or 0 can be replaced with c=v.get(b,0). – primo Feb 7 at 8:38
Thanks. Great suggestion; using .get helps a lot. – grc Feb 7 at 9:03

Python 231 bytes

import sys
v=[]
def g(s):
 for h in v:
  if s in h:return h[s]
 return int(s.isdigit()and s)
for c in list(sys.stdin):
 c=c.strip()
 if c in'[]':v=([{}]+v)[ord(c)%7:]
 else:
  a,b=c.split()
  if'>'==a:print g(b)
  else:v[0][a]=g(b)

Using a global context stack. Whenever [ is encountered, a new hash is pushed onto the stack, and whenever ] is entcountered, the most recent is popped off. The getter function g() does most of the work, although the only literals allowed are integers; everything else is assumed to be a variable name.

Sample input:

[
a 10
> a
b 20
[
a 10
> a
> b
b 23
> b
b a
> b
b 23
]
> a
> b
> c
]

Sample output:

$ python scope.py < input.dat
10
10
20
23
10
10
20
0
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.