In this challenge, the goal is to find the values of some variables after a number of assignments are done. An example input:
a = 5
b = 4
c = a = b
a = 2
b = a
This would result in:
a = 2
b = 2
c = 4
Each statement will be one of the following:
- A variable name (
[a-z_]+
) - A numeric value (
[0-9]+
) - An assignment operation, with a variable name on the left and a statement on the right
You may assume that the input will be a list of statements, formatted however you want. Variable names will have differing lengths (if you need a hard value to gold within, assume 16 chars max).
Note that statements can contain more or less than one assignment (such as a
, 23
, or a = b = c = 4
), and that variables can appear that are never assigned to. Assume no undefined variables are used as values in an assignment (such as a = undefined_variable
), and that no variable will be on both sides of an assignment (such as a = a
or a = a = 1
).
You can take input any way you wish (such as a string with a character to delimit statements, a list formatted as [["a", 5], ["b", "a"]]
, etc.), and output can be in any consistent format (such as a hash map of names to values, or a list of values in the order that the variables first appeared).
Test cases:
a = 5 -> a = 5
b = 512, c = a = 2 -> a = 2, b = 512, c = 2
def, 2, e = 8, 101 -> e = 8
->
a ->
fgh = 4, i = 3, fgh = i -> fgh = 3, i = 3
j = k = l = m = n = 14 -> j = 14, k = 14, l = 14, m = 14, n = 14
s = t = u = 6, t = v = 7 -> s = 6, t = 7, u = 6, v = 7
o = 3, o = p -> [undefined]
q = r -> [undefined]
w = w = 2 -> [undefined]
x = 4, x = x -> [undefined]
This is code-golf, so shortest answer per language wins!
eval
and the like is unlikely to work, as the variable could be named like a keyword in your language. \$\endgroup\$23
ora
would (nothing). I think most answers already work that way anyway. \$\endgroup\$