We are asked: For each input string that is a concatenation of "north" and "west", compute the angle according to the rules:
- "north" means 0 degrees.
- "west" means 90 degrees.
- If direction dir means a degrees and the sum of occurrences of "north" and "west" in dir is n (>=1), then "north"+dir means a - 90/(2^n) degrees, and "west"+dir means a + 90/(2^n) degrees.
Interpretation: We have a recursive definition. For a given string s composed of words "north" and "west" concatenated (no spaces), we can parse it as a sequence of these tokens. The rules define the angle recursively: base cases: "north": 0; "west": 90. For any string s that is not a base? Actually, the rules say: if dir is a direction meaning a degrees, and the sum of occurrences of "north" and "west" in dir is n (>=1), then "north"+dir means a - 90/2^n, and "west"+dir means a + 90/2^n. This suggests that we start from the innermost? Actually, we can think of building the direction by adding a prefix to an existing direction. For example, "northwest": take dir = "west" which has n=1 (since west has 1 occurrence) then "north"+"west" means a - 90/2^1 = 90 - 45 = 45. Good.
Now, "northnorthwest": That is "north"+"northwest". For "northwest", its sum of occurrences is 2 (north and west). So n=2, a = 45, then "north"+"northwest" means 45 - 90/2^2 = 45 - 90/4 = 45 - 22.5 = 22.5 = 45/2. That matches output.
Now, "westwestwestnorth": Let's parse: It is likely "west"+"westwestnorth"? Or maybe we need to parse from leftmost? The definition uses prefix concatenation: "north"dir or "west"dir. So the string is formed by repeatedly adding a word to the front of an existing direction. So we need to parse the string as a sequence of tokens: It's a concatenation of "north" and "west", so we can read from left to right: the leftmost token is the first prefix, and we recursively compute the rest. But the rule: For a given dir, the prefix is added to the front. So the recursion is: angle(s) = if s == "north": 0; if s == "west": 90; else if s starts with "north": then let t = s.substr(5); // after removing "north" Let a = angle(t); Let n = count of tokens in t ( sum of occurrences of north and west in t). Then angle(s) = a - 90/(2^n); similarly for "west": angle(s) = a + 90/(2^n). But careful: According to the problem statement: "If the direction dir means a degrees and the sum of the occurrences of 'north' and 'west' in dir is n (≥ 1), 'north'dir means a - 90/2^n degrees and 'west'dir means a + 90/2^n degrees." Here dir is the suffix after adding a prefix. So if we have s = prefix + dir, then the n used is the number of tokens in dir, not in s. Yes, they explicitly say: "the sum of the occurrences of 'north' and 'west' in dir is n". So when we have "northwest": prefix = "north", dir = "west". n = occurrences in "west" = 1, a = angle("west") = 90, so angle = 90 - 90/2^1 = 45. So that matches.
Thus algorithm: Given string s consisting only of "north" and "west" concatenated, we can parse tokens from left to right, but the recursion is leftmost prefix: angle(s) = f(s) defined recursively: if s equals "north": 0; if "west": 90; else if s starts with "north": then let tail = s without first 5 chars; compute a = f(tail); let n = number of tokens in tail (which we can compute as length of tail / 5 because each token is exactly 5 letters? Actually "north" and "west" are both 5 letters? "north" length 5, "west" length 4? Wait: "west" is 4 letters! I need to double-check: "north" length 5, "west" length 4. Are both 5? "west" is 4 letters. So tokens are not same length. The string is concatenation of "north" and "west". So the tokens are of length either 5 or 4. So we cannot simply divide length. We must parse token by token. For recursion, we need to know the tail string after removing the first token. So we need to parse the first token: if the string starts with 'n', it's "north" (since both start with distinct letters: north starts with 'n', west starts with 'w'). So we can check first character. Then the token length: if 'n', length=5; if 'w', length=4. So we can strip that many chars to get tail.
Then recursion: angle(s) = if s is base case? But what about strings like "northnorth"? That would be "north"+"north". But base cases are only "north" and "west"? Actually they define that "north" means 0, "west" means 90. And the recursive definition applies when we have a prefix and a dir, where dir presumably can be any direction derived by these rules (including composite). So the recursive definition works for any non-empty string: if s is exactly "north" or "west", it's base. Otherwise, it's a concatenation of a prefix and a tail, and tail must be a valid direction (since total string is concatenation of those words). So recursion works.
But we need to compute the angle as rational number exactly. Because the operations involve subtraction/addition of fractions like 90/2^n. 90 is integer, 2^n integer. So the result will be rational. We need to output as integer if it's integer; else as irreducible fraction (like numerator/denominator). Also note that the angle is between 0 and 90 inclusive, so numerator/denom should represent a value in [0,90].
Implementation approach: We can parse the string into a list of tokens. The recursive definition essentially computes the angle by traversing from the end (rightmost) to the left? Actually, the recursion: angle(prefix+dir) = angle(dir) +/- 90/2^{count(dir)}. So if we consider the full token sequence t1 t2 ... tk, where each ti is either "north" or "west". Then define recursively: for i from k down to 1: we compute something? Let f(i) be angle for tokens from i to k (i.e., suffix). Base: if i == k and token_k is "north": angle = 0; if "west": 90. Otherwise for i<k, we have token_i + suffix_{i+1..k}. Then f(i) = f(i+1) +/- 90/2^{k-i}, where n = number of tokens in suffix = (k - i) (since count of tokens in dir is length of suffix). Actually, count of tokens in dir = number of tokens after the prefix = (k - i). So we can compute from right to left: start with angle = base for last token. Then for each preceding token (from right to left, except the last), adjust: if token is "north", angle = angle - 90/2^{(remaining_length)}? Wait careful: At step where we are processing token i (i from k-1 down to 1), the suffix is tokens i+1..k, which has count = k - i. So we need to subtract or add 90 / 2^{(k - i)}. But note: The order: token i is prefix, suffix is tokens i+1..k. So we set angle = (angle of suffix) +/- 90/2^{len(suffix)}. So if we process from the rightmost token to leftmost, we can keep track of current angle (the angle of the suffix processed so far) and also the count of tokens in that suffix. Starting with last token: angle = 0 or 90; count = 1 (since suffix of length 1? Actually when we have the whole string, the last token is itself a direction; but the recursion base cases are exactly for single token. So we can start with the last token as base. Then for each token to its left, we update angle = angle +/- 90 / 2^{current_token_count}, where current_token_count is the number of tokens already in the suffix (i.e., the number of tokens we have already processed). And after updating, the suffix grows to include one more token, so the count increments. However, careful: The recurrence uses n = sum of occurrences in dir. So when we have processed the suffix of size m (the tokens to the right), that's exactly the dir for the next token to the left. So we add/subtract 90/2^m. Then the new direction (including the left token) will have size m+1. That's correct. So we can process tokens from right to left.
Thus algorithm: Parse string into list of tokens in order (left to right). Then process from last token to first: let count = 0 initially? Actually we need base for the last token. For the last token alone, if it's "north": angle = 0; if "west": angle = 90. Then set m = 1 (since suffix dir had 1 token). Then for i from len-2 down to 0 (previous tokens): token = tokens[i]; if token == "north": angle = angle - 90/2^m; else: angle = angle + 90/2^m; then m = m + 1.
That yields the final angle. Note that m at each step is the number of tokens in the suffix before adding the new prefix. So at step with suffix size m, we adjust by 90/2^m. After adjustment, suffix size becomes m+1.
Check with "northwest": tokens = ["north","west"]? Actually "northwest" is "north"+"west". So parse: left to right: token1 = "north", token2 = "west". Process from right: last token = "west" => angle = 90, m=1. Then i=0: token="north": angle = 90 - 90/2^1 = 90 - 45 = 45. m=2. OK.
"northnorthwest": tokens = ["north","north","west"]? Actually "northnorthwest" is "north"+"north"+"west"? Let's see: The string is "northnorthwest". It can be parsed as "north"+"north"+"west"? Because "north"+"north"+"west" yields "northnorthwest"? Check: "north"+"north" = "northnorth"; then + "west" = "northnorthwest". That seems correct. But the example output is 45/2 = 22.5. Let's compute: tokens = ["north","north","west"]. Process from right: last="west": angle=90, m=1; previous token = "north": angle = 90 - 90/2^1 = 45, m=2; previous token = "north": angle = 45 - 90/2^2 = 45 - 90/4 = 45 - 22.5 = 22.5 => 45/2. OK.
Now "westwestwestnorth": tokens: Let's parse left to right: "west"+"west"+"west"+"north"? That gives "westwestwestnorth". That's plausible. Compute: last token = "north": angle=0, m=1; previous token="west": angle = 0 + 90/2^1 = 45, m=2; previous token="west": angle = 45 + 90/2^2 = 45 + 22.5 = 67.5, m=3; previous token="west": angle = 67.5 + 90/2^3 = 67.5 + 11.25 = 78.75 = 315/4? 315/4 = 78.75. Yes. So that matches sample output.
Thus the algorithm works.
Now the main challenge: Represent the angle as a rational number exactly. Since all operations are +/- 90 divided by powers of 2, the denominator will be a power of 2, up to 2^20 perhaps (since max tokens 20). Actually the maximum m used in adjustments is at most 20? The sum of occurrences is up to 20, so maximum suffix size m can be up to 19 (since we start with last token of 1, then add up to 19 more prefixes, total <=20). So denominators are powers of 2 up to 2^19 (or 2^20?). Let's see: In the final angle, it could be sum of terms: starting from base (0 or 90) plus/minus 90/2^m for m=1,...,k-1 where k is total tokens. So denominator up to LCM of these powers, which is 2^{k-1} or less. Actually the sum of rationals with denominators powers of 2 yields denominator at most 2^{max exponent}. But we can accumulate as rational using numerator denominator as integers, or better: Represent the angle as a rational with denominator being a power of 2. Since each term is 90 * (some integer divided by power of 2). Let's derive formula: Let the tokens be t1, t2, ..., tk. The angle can be expressed as base + sum_{i=1}^{k-1} sign_i * (90 / 2^{suffix_len_i}) where suffix_len_i is number of tokens after the i-th token (i.e., for token at position i, suffix length = k - i). But more elegantly: If we denote b = 0 if last token is north else 90, and then for each preceding token we add +/- 90/2^{len_of_remaining}. So we can compute total = sum_{j=1}^{k} c_j * 90 / 2^{j}? Not exactly. Let's index from the right: the last token (position k) contributes base: if west -> 90 else 0. This can be thought of as 90 * (isWest) * 1/2^0? Not exactly. But we can unify: Let's denote an expression: The angle = 90 * (s0 + s1/2 + s2/4 + ... + s_{k-1}/2^{k-1})? Possibly with s_i being -1,0,1? Let's try to derive.
Alternatively, we can compute using fractions exactly by accumulating numerator over denominator = 2^{k-1} maybe. Since we have at most 20 tokens, we can compute using integer arithmetic: represent the angle as a rational number N/D where D = 2^{max_power} and keep numerator integer. But careful: The base 0 or 90 can be expressed as 0/2^p or 90 * 2^{p}/2^{p}. But we can just accumulate as a rational with denominator = 2^{k-1}? Actually the maximum exponent for denominator in adjustments is up to 2^{k-1} for the first prefix (if we reverse direction). Let's find maximum denominator needed: Suppose k tokens. The smallest adjustment's denominator is 2^{k-1} (since the first token (leftmost) uses suffix of size k-1, so adjustment uses denominator 2^{k-1}). The base (last token) is integer 0 or 90, which can be expressed with denominator 2^{k-1} by multiplying by that. So final denominator at most 2^{k-1}. But also subsequent adjustments have denominators 2^1,...,2^{k-1}. So the LCM is 2^{k-1}. So we can represent everything with denominator = 2^{k-1}. That's at most 2^19 = 524288, which fits in 32-bit? 2^19 = 524288, 2^20 = 1048576. 2^19 * 90 < about 47 million, fine for 64-bit. Actually we can also just use Python fractions (Fraction) which simplifies automatically.
But the output wants integer if integer, else irreducible fraction. So we can compute as Fraction from fractions module or implement manually.
Implementation steps:
- While True: read line, strip newline. If line == "#": break.
- For each dataset, compute angle.
- To parse tokens: We'll process the string left to right to get list. We know that "north" and "west" are the only tokens. Since "north" starts with 'n', "west" starts with 'w'. So we can iterate index i=0; while i < len(s): if s[i] == 'n': token = "north", i += 5; else if s[i] == 'w': token = "west", i += 4; else error. Append token to list tokens.
- Compute angle:
let k = len(tokens)
Set angle = Fraction(0,1) or as ints: num = 0, den = 1. We'll use Fraction for simplicity.
Process from last token backwards:
Set m = 0 (this will be the size of suffix already processed? Actually we need to know current suffix length. At start, when we haven't processed any? Better: Start with last token. Let i = k-1.
if tokens[i] == "north": cur = Fraction(0,1); else: cur = Fraction(90,1)
let suffix_len = 1 (since the direction so far is the last token, its token count is 1)
for i from k-2 down to 0:
adjust = Fraction(90, 2**suffix_len) # denominator 2^suffix_len
if tokens[i] == "north": cur -= adjust
else: cur += adjust
suffix_len += 1
final_angle = cur
But note: In the recursion, when we add prefix, the suffix_len used is exactly the number of tokens in the dir (the suffix we have computed). So indeed we start suffix_len=1 for the base direction (last token). Then for each prefix added, we use that suffix_len to adjust, then increase suffix_len.
Check: For "northwest", tokens ["north","west"], base from last token "west": cur=90, suffix_len=1. Process i=0 "north": adjust=90/2^1=45, cur=90-45=45, suffix_len=2. Done.
For "north": k=1, just base: cur=0. That's correct.
Thus algorithm correct.
We must output as integer if integer, else irreducible fraction.
Using Fraction: after computing cur = Fraction(num, den) we can get numerator and denominator. If denominator == 1: print numerator. else print f"{cur.numerator}/{cur.denominator}" (but need to ensure fraction is reduced, Fraction does that). However careful: In Python's fractions.Fraction, numerator and denominator are integers with sign positive denominator. So fine.
But watch for negative numbers? The angle is between 0 and 90 inclusive, so nonnegative.
Edge Cases: The string could be something like "westnorth"? That's "west"+"north": tokens: ["west","north"]. base: last token "north": cur=0, suffix_len=1. Process i=0 "west": adjust=90/2=45, cur=0+45=45. So "westnorth" = 45? But is that valid? The string must be concatenation of north and west; it's valid. However, note that "westnorth" might be interpreted as "west"+"north" but the problem may not mention that ordering, but it's still a concatenation. The rules allow any concatenation as long as it's obtained by recursively prefixing "north" or "west" to a direction. Starting from base "north" or "west", we can only prefix tokens. So any concatenation is allowed? For example, "westnorth" would be "west"+"north" which is valid because "north" is a direction. So allowed. However, we must ensure that the angle is between 0 and 90 inclusive, as guaranteed.
Now, about input: The input contains several datasets, each line a string, terminated by "#". Up to 100 datasets. Strings length: sum of occurrences up to 20, each token length 4 or 5, so max length maybe 20*5=100, plus maybe less. Fine.
Implementation with Fraction:
from fractions import Fraction
def compute_angle(s):
tokens = []
i = 0
while i < len(s):
if s[i] == 'n':
tokens.append('north')
i += 5
elif s[i] == 'w':
tokens.append('west')
i += 4
else:
# shouldn't happen
raise ValueError
# Process from rightmost
k = len(tokens)
if k == 0:
return Fraction(0) # not possible as sum >=1
# base
if tokens[-1] == 'north':
cur = Fraction(0,1)
else:
cur = Fraction(90,1)
suffix_len = 1
for idx in range(k-2, -1, -1):
adjust = Fraction(90, 1 << suffix_len) # 90 / 2^suffix_len
if tokens[idx] == 'north':
cur -= adjust
else:
cur += adjust
suffix_len += 1
return cur
But careful: "adjust = Fraction(90, 1 << suffix_len)" yields Fraction(90, 2^suffix_len). That's fine.
Alternatively, we could compute using integer numerator with denominator = 2^(k-1) to avoid fractions, but Fraction is simpler.
But there is a nuance: The recursion uses n = sum of occurrences in dir. That is exactly the number of tokens in the suffix. Our suffix_len after base starts at 1 and increments after each addition. That matches.
Double-check with sample: "westwestwestnorth": tokens: w,w,w,north. Process: last=north -> cur=0, suffix_len=1. idx=2 (third west? Actually tokens indices: 0,1,2,3? Let's list: tokens[0]="west", tokens[1]="west", tokens[2]="west", tokens[3]="north". Process from right: base: tokens[3]="north": cur=0, suffix_len=1. Then idx=2: token="west": adjust=90/2=45, cur=45, suffix_len=2. idx=1: token="west": adjust=90/4=22.5, cur=67.5, suffix_len=3. idx=0: token="west": adjust=90/8=11.25, cur=78.75, suffix_len=4. Final = 315/4? 78.75 = 7875/100 = simplify? Actually 78.75 = 315/4 (since 78.75*4=315). So yes.
Now, output format: print integer if integer else fraction as "numerator/denominator". Must not have spaces. For fraction, should be irreducible. Fraction automatically reduces.
Potential pitfalls: Fractions might become large numerators but within limits. k up to 20, denominator up to 2^19 = 524288, numerator may be up to about 90 * 2^19 = 47185920, plus maybe sign sums, within 64-bit. Python int unlimited anyway.
Check with "west"*20? But tokens up to 20. Might produce numerator large but fine.
Edge Cases: When the final angle is exactly integer, e.g., "northwest" = 45, integer. "north" = 0, integer. "west" = 90, integer. "northwestnorth"? Let's test: tokens: north, west, north? Actually "northwestnorth": parse? That would be "north"+"west"+"north"? That's valid? Let's compute: base last=north: cur=0, suffix_len=1. idx=1: token=west: cur=0+45=45, suffix_len=2. idx=0: token=north: adjust=90/4=22.5, cur=45-22.5=22.5 => 45/2, fraction. So fine.
Now we must handle multiple datasets until "#". Input sample shows:
north
west
northwest
northnorthwest
westwestwestnorth
Output:
0
90
45
45/2
315/4
Our algorithm yields those.
Now potential alternative: The problem statement might have an error about the sum of occurrences: "the sum of the occurrences of 'north' and 'west' in dir is n (>= 1)". For a direction like "northwest", dir = "west", occurrences = 1, okay. So n is the number of tokens in the suffix (dir). So our method is correct.
Now implement solve() function:
def solve():
import sys
from fractions import Fraction
out_lines = []
for line in sys.stdin:
line = line.strip()
if line == "#":
break
tokens = []
i = 0
s = line
while i < len(s):
if s[i] == 'n':
tokens.append('north')
i += 5
else: # 'w'
tokens.append('west')
i += 4
# compute angle
k = len(tokens)
if tokens[-1] == 'north':
cur = Fraction(0,1)
else:
cur = Fraction(90,1)
suffix_len = 1
for idx in range(k-2, -1, -1):
adjust = Fraction(90, 1 << suffix_len) # 2^suffix_len
if tokens[idx] == 'north':
cur -= adjust
else:
cur += adjust
suffix_len += 1
# output
if cur.denominator == 1:
out_lines.append(str(cur.numerator))
else:
out_lines.append(f"{cur.numerator}/{cur.denominator}")
sys.stdout.write("\n".join(out_lines))
But careful: In adjust = Fraction(90, 1 << suffix_len) we should ensure denominator is integer; it's fine.
One more check: For "north", tokens = ['north'], k=1. We go into base: tokens[-1]=='north' -> cur=0. suffix_len=1, then loop from k-2 = -1 down to 0? range(-1, -1, -1) is empty, so no adjustments. So cur=0. Output "0".
For "west": cur=90, output "90".
All good.
Now consider scenario with many tokens, denominator becomes large but Fraction simplifies. However, adjust = Fraction(90, 1<<suffix_len) will be simplified? Fraction(90, 8) becomes 45/4 after simplification. That's fine.
But note: cur might accumulate to something like 45 - 45/2 = 45/2? Actually 45 is 90/2? Wait 45 is Fraction(45,1). Subtract 45/2 yields (90/2 - 45/2) = 45/2 => Fraction(45,2). That's simplified.
Now ensure that when we compute cur -= adjust, if both have different denominators, Fraction handles it.
Alternatively, we could accumulate using integer numerator and common denominator 2^{k-1}. But easier is using Fraction.
Potential performance: Up to 100 lines, max tokens 20, so trivial.
Now check sample output: The output lines are exactly as shown. Good.
But we need to ensure that the order of tokens we parse from left to right matches the recursive definition of prefix concatenation. The definition says: "If direction dir means a degrees and the sum ... 'north'dir means ...". So the direction is formed by prefixing. So the leftmost token is the last prefix added. That matches our right-to-left processing. So parse left-to-right to get token sequence, then process right-to-left. Yes.
Edge Cases: Input may have leading/trailing spaces? Use strip().
Now, we need to output as per format: each dataset result on its own line.
Testing more examples:
Input: "northwest" => tokens ["north","west"] => base west=90, suffix_len=1, north adjust 90/2=45 => cur=45 => output "45". Good.
Input: "westnorth" => tokens ["west","north"] => base north=0, suffix_len=1, west adjust 90/2=45 => cur=45 => output "45". So "westnorth" also 45. That's interesting: "northwest" and "westnorth" both give 45? Let's test: "westnorth": base north=0; prefix west adds +90/2=45 => 45. So indeed both give 45. Is that intended? According to rules, "northwest" and "westnorth" are different strings but both produce 45? Let's verify: "westnorth" means: dir = "north" (0), n = occurrences in dir = 1 (since north), so "west"+"north" means 0 + 90/2 = 45. Yes, same. So they are synonyms? But the problem statement might not consider both as valid? It says "concatenating some 'north' and 'west'" so both are valid. So angle same. That's fine.
Now input: "northwestnorthwest"? Might produce something else.
Thus algorithm done.
But wait: The problem says "the sum of the occurrences of 'north' and 'west' in dir is n (≥ 1)". So for a direction like "north"+"north"? That would be "northnorth". Let's test: tokens = ["north","north"]. Base: last = "north" => cur=0; prefix north: adjust=90/2^1=45; cur = 0-45 = -45, which is less than 0. But problem says angle is between 0 and 90 inclusive. So such direction might not appear? The input guarantee says the angle described is between 0 and 90 inclusive. So such strings will not appear. So all inputs satisfy that property.
Now we need to ensure we handle the input termination: line containing "#". Possibly there may be empty lines? But problem says each dataset described by a single line containing string, no blank lines. So fine.
Now about output: Should we output integer as just the integer, fraction as numerator/denominator? Yes, sample shows "45/2", "315/4". Ensure no leading/trailing spaces.
Potential issue: The fraction might be simplified to an integer? But we already check denominator == 1.
Now implement.
But there is also an alternative approach: The angle can be computed by interpreting the string as a binary fraction? Let's think: Since each addition/subtraction is 90/2^n, the final angle can be expressed as 90 * (some binary fraction). Actually we can see: For each position from the right, the contribution of a token can be encoded as +/-1/2^k. In fact, the recurrence resembles that of binary representation: Starting from the rightmost token, which is either 0 or 90 (i.e., 90 * b0 where b0 is 0 or 1). Then each preceding token adds or subtracts 90/2^m, where m is the number of tokens to the right. So final angle = 90 * (c0 + sum_{i=1}^{k-1} c_i / 2^i) where c_i are +1 or -1 or 0? Not exactly. Let's derive: Let tokens be t1 t2 ... tk. Define b_k = 1 if tk == 'west' else 0. Then for i from k-1 down to 1, define s_i = +1 if ti == 'west', else -1 (if ti == 'north')? Actually adjustment: if ti == 'west', we add 90/2^{(k-i)}; if ti == 'north', we subtract. So final angle = 90 * (b_k + sum_{i=1}^{k-1} s_i / 2^{(k-i)}). But note that the exponent for s_i is (k-i). That is 1,2,...,k-1. So we can rewrite as: angle = 90 * (b_k + sum_{j=1}^{k-1} s_{k-j} / 2^{j}). That's essentially a binary fraction where bits can be +1 or -1? But b_k is 0 or 1, and s_i are +/-1. So angle = 90 * ( sum_{j=0}^{k-1} d_j / 2^{j} ) where d_0 = b_k? Actually if we index from least significant (rightmost): Let d_0 = b_k (0 or 1). For j=1..k-1: d_j = (1 if t_{k-j} == 'west' else -1)? That would be weird because binary digits are usually 0/1, not -1. So better to keep as fraction.
Anyway, using Fraction is fine.
Now implement solve() as described.
But check that we parsed tokens correctly: For string "westwestwestnorth", we need to parse tokens: Starting with 'w', so token "west" (4 chars), then next character at index 4 is 'w'? Actually after first "west", index becomes 4; s[4] is 'w' because string is "westwestwestnorth": positions: 0-3 "west", 4-7 "west", 8-11 "west", 12-? Actually "north" is 5 chars, so total length: 3*4 + 5 = 12+5=17. So parse works.
Edge case: When string starts with 'n' we take 5 chars. Must ensure we don't go out of bounds; but input is valid.
Now code.
But I should consider that the fraction might be negative? Not according to constraints. So fine.
Now test with some custom:
-
"north": output 0.
-
"west": 90.
-
"northwest": 45.
-
"westnorth": 45.
-
"northnorthwest": 45/2.
-
"northnorthnorthwest": tokens: north,north,north,west. Compute: base=90 (west) suffix_len=1; i=2 (north): cur=90-45=45; suffix_len=2; i=1 (north): adjust=90/4=22.5 -> cur=45-22.5=22.5; suffix_len=3; i=0 (north): adjust=90/8=11.25 -> cur=22.5-11.25=11.25 = 45/4? 45/4 = 11.25 yes. So output 45/4. That seems plausible.
-
"westwestwestwest": tokens: west,west,west,west. Base last=west -> cur=90, suffix_len=1; i=2 west: cur=90+45=135? But 135 > 90. This direction probably not allowed because angle must be between 0 and 90. So input won't include such.
Now, we should verify that the algorithm works for the maximum tokens 20. The denominator may become as large as 2^19, but Fraction reduces if numerator is even. That's fine.
Now about output: In sample output, they have "315/4" for "westwestwestnorth". Let's recompute: 78.75 = 7875/100 = reduce: divide by 25: 315/4. So fine.
Now check for any potential pitfalls: The sum of tokens parsed must equal the length of string exactly. Our parsing uses fixed lengths: 5 for 'n', 4 for 'w'. That should cover all tokens. But what if there is stray character? Not in valid input.
Now we need to process up to 100 datasets. Implementation done.
But we might also consider using integer arithmetic to avoid Fraction if desired. However, it's easy.
Now test with the sample input:
Input lines:
north
west
northwest
northnorthwest
westwestwestnorth
Our code yields:
0
90
45
45/2
315/4
Matches.
Now consider potential alternative interpretation: Could the direction be read from left to right rather than right to left? But the problem's recursive definition uses prefix concatenation, so our interpretation is correct.
Double-check with a more complex scenario: The recursive definition states: If dir means a degrees and the sum of occurrences in dir is n, then "north"dir means a - 90/2^n, and "west"dir means a + 90/2^n. So indeed, the dir is the suffix. So building from the innermost base (the last token) outward is appropriate.
Thus solution is correct.
Now think about any tricky parsing: The tokens "north" and "west" can be unambiguously identified because they start with different letters. So parsing is straightforward.
Now we could also compute directly from token list using formula: angle = 90 * sum_{i=1}^{k} sign_i / 2^{i-1}? Let's derive to confirm. Let's index tokens from left to right: t1, t2, ..., tk. Then angle = 90 * (c_k + sum_{i=1}^{k-1} c_i / 2^{k-i})? Where c_i = 1 if t_i is west, -1 if north? Not exactly, because base is 0 for north and 90 for west, which is 90 * b_k where b_k = 1 if west else 0. And for i<k, contribution is +/- 90 / 2^{k-i}. So angle = 90 * (b_k + sum_{i=1}^{k-1} s_i / 2^{k-i}) where s_i = +1 if t_i = west, -1 if north. That's equivalent to 90 * sum_{j=0}^{k-1} d_j / 2^j, where d_0 = b_k? But then for j>=1, d_j = s_{k-j}. So the angle is 90 times a rational with denominator 2^{k-1}. Could compute numerator = 90 * (b_k * 2^{k-1} + sum_{i=1}^{k-1} s_i * 2^{i-1})? Wait: multiply by 2^{k-1}: angle * 2^{k-1} = 90 * (b_k * 2^{k-1} + sum_{i=1}^{k-1} s_i * 2^{k-1} / 2^{k-i}) = 90 * (b_k * 2^{k-1} + sum_{i=1}^{k-1} s_i * 2^{i-1}). Because 2^{k-1}/2^{k-i} = 2^{i-1}. So numerator_int = 90 * (b_k * 2^{k-1} + sum_{i=1}^{k-1} s_i * 2^{i-1}). Denominator = 2^{k-1}. Then reduce fraction. This might be more efficient but not needed.
Our Fraction approach is simpler.
One more nuance: The definition: "the sum of the occurrences of 'north' and 'west' in dir is n (≥ 1)". For the case dir is empty? Not allowed, because n ≥ 1. So base cases are exactly when dir is a single token? Actually base "north" and "west" are given separately. They are not derived from the recursive rule because for those, the dir would be empty? So our recursion works only when the string length >5? But we have explicit base cases for single tokens. That's fine.
Now, confirm that our processing uses suffix_len correctly: For the step where we have suffix of length L (number of tokens in dir), we use denominator 2^L. That's consistent. After adding prefix, the new direction (which will become dir for a further prefix if any) will have length L+1. That's why we increment suffix_len after adjustment.
Now, think about input like "northwestnorth"? Let's compute manually: tokens: north, west, north. base = north => 0, suffix_len=1; i=1 (west): adjust=90/2=45 => cur=0+45=45; suffix_len=2; i=0 (north): adjust=90/4=22.5 => cur=45-22.5=22.5 => 45/2. So "northwestnorth" gives 45/2. Wait, "northwestnorth" is "north"+"west"+"north". That's "northwest"+"north"? But "northwest" is 45, then "north"+"northwest"? Actually "north"+"northwest" is "northnorthwest", which gave 45/2. So "northwestnorth" gives same as "northnorthwest"? Let's test "northnorthwest" gave 45/2, yes. So both yield same angle. Interesting.
Now confirm that our algorithm yields the same result. This is plausible because of associativity? Not exactly, but the operations might be commutative in this specific sense? Possibly due to the binary fraction representation, order matters? But we got same results for these two. Let's test manually: "northwestnorth" using recursion: parse as "north"+"westnorth"? Actually which way? According to definition, the string is a concatenation, but we need to apply the prefix rule recursively. For "northwestnorth", we could parse it as "north"+"westnorth" (since we add prefixes to existing direction). But is there a unique way? The definition doesn't explicitly say that the decomposition is unique, but it's defined recursively: starting from base tokens "north" or "west", we can construct longer ones by prefixing. So any valid direction string must be derivable by a sequence of prefix operations. That implies that the derivation is unique: you keep stripping off the first token to get the suffix direction, as long as the suffix is a valid direction. However, is it always the case that any concatenation of the words "north" and "west" can be uniquely parsed from the left? Yes, because the tokens are of different lengths? Actually the tokens are "north" (5) and "west" (4). So the concatenation might be ambiguous if we try to split into tokens from left to right? For example, the string "northwest" could be parsed as "north"+"west" (5+4=9) or "northwest" isn't a token. That's fine. The string is built by concatenating tokens; there is no ambiguity in parsing because we know the tokens and we can parse greedily from left: if first char is 'n', take 5 chars; if 'w', take 4. That yields a unique tokenization. So indeed any string formed by concatenating these tokens can be uniquely tokenized. So derivation is unique.
Now, for "northwestnorth": tokens: "north", "west", "north". According to the derivation: we start with base direction "north" (the last token). Then we prefix "west": "west"+"north" gives direction with angle = angle(north) + 90/2^1 = 0 + 45 = 45. Then we prefix "north": "north"+"westnorth" gives angle = angle(westnorth) - 90/2^{2} because dir = "westnorth" has 2 tokens? Actually "westnorth" has tokens: west and north, so sum of occurrences = 2, so n=2. So angle = 45 - 90/4 = 45 - 22.5 = 22.5. So indeed "northwestnorth" = 22.5.
Now "northnorthwest": tokens: "north","north","west". Derivation: base = "west" = 90. Prefix "north": "north"+"west" = 90 - 45 = 45. Then prefix "north": "north"+"northwest" = 45 - 90/4 = 22.5. So both same.
Thus different sequences can give same angle.
Thus algorithm is consistent.
Now, potential simplification: we can compute using binary fraction representation as described, but we don't need.
Edge case: tokens list may have length 0? Not as per problem.
Now code ready.
But we should be careful about reading input: There may be trailing spaces. Use strip.
Now implement.
Will there be any empty lines before '#'? Possibly not, but we can handle by stripping and skipping empty lines if any, but better to just break on "#". Usually UVa style: multiple datasets, terminated by "#" line. So we can just read lines until "#".
Now test with sample:
Input:
north
west
northwest
northnorthwest
westwestwestnorth
Our code output should match.
Now potential nuance: The sample output has "315/4" not "78.75". So fraction irreducible. 315/4 is indeed reduced because 315 and 4 have gcd=1.
Our Fraction will reduce: Fraction(315,4) already? But we compute as 78.75 exactly? Actually Fraction(78.75) might not be exact due to floating? We shouldn't use float. We'll compute using integers: cur = Fraction(0) and adjust = Fraction(90, 1<<suffix_len). That's exact.
Let's simulate "westwestwestnorth" manually with Fraction: start cur=0; suffix_len=1; idx2 west: adjust=Fraction(90,2)=45; cur=45; suffix_len=2; idx1 west: adjust=Fraction(90,4)=45/2? Actually 90/4 reduces to 45/2. So cur = 45 -? Actually it's addition: 45 + 45/2 = (90/2 + 45/2) = 135/2 = 67.5? Wait 45 + 22.5 = 67.5. 45 as Fraction(45,1) + Fraction(45,2) = (90+45)/2 = 135/2 = 67.5. That's Fraction(135,2). Then suffix_len=3; idx0 west: adjust=Fraction(90,8)=45/4? Actually 90/8 = 45/4. cur = 135/2 + 45/4 = (270/4 + 45/4) = 315/4. So Fraction(315,4) simplifies? 315 and 4 gcd=1, so it's 315/4. Good.
Now output: if denominator == 1, print numerator else print f"{numerator}/{denominator}". That's correct.
Now we might consider that the angle could be zero? "north" yields 0. That's integer, output "0".
Now, what about "westwest"? tokens: west, west. base = west => 90, suffix_len=1, prefix west: adjust = 90/2 =45, cur = 135. That's >90, but input says angle between 0 and 90 inclusive, so not given.
Now also "northnorth" would yield -45, not allowed.
Thus inputs are within [0,90].
Now we should consider if there is any scenario where the angle is exactly integer but fraction reduces to denominator 1. For instance "westnorth" gave 45 integer.
Now code is straightforward.
But before finalizing, we must ensure that we treat the case when the string length is not a multiple of token lengths? Problem says it's a concatenation of "north" and "west", so it's valid.
Now implement.
We'll write a function solve() and call it if name == 'main'.
Potential improvement: Use while loop reading line by line. Use sys.stdin.read().splitlines() perhaps.
But caution: Input may have trailing newline after "#"? It's fine.
Now we must handle possible large number of datasets.
Now we will produce final answer.
But wait, there is an important nuance: In the recursive definition, they said: "If the direction dir means a degrees and the sum of the occurrences of "north" and "west" in dir is n (≥ 1), "north"dir (the concatenation of "north" and dir) means a - 90/2^n degrees and "west"dir means a + 90/2^n degrees." This uses n = sum of occurrences in dir. Note that dir may itself be composite, so n is the total number of tokens in dir. So in our processing, when we add a prefix, we need to use the number of tokens in the current suffix. That's exactly what we do.
But what about base cases: "north" and "west" are defined directly, not through the rule. So when the string is a single token, we use base values. That's consistent.
Now, could there be strings like "northwestwest"? tokens: north, west, west. base=west=90, suffix_len=1; idx1=west: cur=90+45=135; suffix_len=2; idx0=north: cur=135 - 90/4=135-22.5=112.5; >90. So not in input.
Thus fine.
Now, consider complexity: For each dataset, we parse O(L) and then O(k) operations with Fraction. Each Fraction operation involves gcd computations which are O(log N). Fine.
Now, we should also consider that some fractions might be simplified to integers even before final. Fraction automatically simplifies.
Now, one more nuance: The angle may be exactly 0 or 90. Output integer.
Now, test with "westnorthnorth"? tokens: west, north, north. base=north=0; suffix_len=1; idx1=north: cur=0-45=-45; suffix_len=2; idx0=west: cur=-45+90/4=-45+22.5=-22.5; negative, not allowed. So not input.
Now, we are done.
But I want to double-check the parsing: When we see a string that starts with "north", we take 5 chars. But what about a string that starts with "northwest"? That's fine. But if we accidentally parse incorrectly due to overlapping? Not possible because "north" and "west" have distinct first letters.
Thus implementation.
Now final code.
One more thing: The problem might be from an old contest and expects output exactly as described. So we should print each result on its own line, no extra spaces.
Now I'll produce final solution.
But before final answer, we should consider if using fractions.Fraction is allowed in the judge environment? It's Python's standard library, should be fine. However, some judges may not allow import fractions? It's allowed in typical programming contests like UVA? UVA accepts Python with standard libraries. So fine.
Alternatively, we can implement our own rational with numerator and denominator using integers, simplifying via gcd. But using Fraction is simpler.
Now, we might want to precompute powers of two up to 20 for performance: pow2 = [1<<i for i in range(21)].
But not necessary.
Now final answer.
We should write robust code.
Now I'll produce final answer with explanation.
But the user asked for "final" answer: I should output the code? The problem statement is a typical programming problem. They likely expect a solution. In this chat context, they want a solution. So I'll provide Python code.
I'll also add comments.
Thus final.
```python
import sys
from fractions import Fraction
def solve() -> None:
out_lines = []
for line in sys.stdin:
line = line.strip()
if line == "#":
break
# ---------- tokenize ----------
tokens = []
i = 0
s = line
while i < len(s):
if s[i] == 'n': # "north"
tokens.append('north')
i += 5
else: # 'w' -> "west"
tokens.append('west')
i += 4
# ---------- compute angle ----------
k = len(tokens)
# base (rightmost token)
cur = Fraction(90, 1) if tokens[-1