4
\$\begingroup\$

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.

\$\endgroup\$
2
  • \$\begingroup\$ What is meant by "All input that is not a variable is an integer"? And why mention Java, which is actually quite different? \$\endgroup\$ – Peter Taylor Feb 7 '13 at 8:17
  • \$\begingroup\$ The interesting thing is, > is a special variable that outputs its value when assigned to! \$\endgroup\$ – CalculatorFeline Mar 2 '16 at 15:59
1
\$\begingroup\$

Python 2, 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.

\$\endgroup\$
2
  • 1
    \$\begingroup\$ Nice solution. c=b in v and v[b]or 0 can be replaced with c=v.get(b,0). \$\endgroup\$ – primo Feb 7 '13 at 8:38
  • \$\begingroup\$ Thanks. Great suggestion; using .get helps a lot. \$\endgroup\$ – grc Feb 7 '13 at 9:03

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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