Codeforces: C. Cd and pwd commands


The problem is from codeforces: http://www.codeforces.com/problemset/problem/158/C

158C Codeforces: C. Cd and pwd commands algorithms beginner code codeforces data structure implementation programming languages python string technical

Using a stack will help solve this problem. Luckly, python supports stack structure by using list. The append() and pop() are used to support the two operations on the stack. The solution is quite simple and straightforward:

n = int(raw_input())

cur = []

def pwd(cur):
    if len(cur) == 0:
        print '/'
    else:
        print "/" + "/".join(cur) + "/";

def process(cmd, cur):
    cmd = cmd[3:]
    ds = cmd.split("/")
    if cmd[0] =="/":
        cur = []
    for d in ds:
        if d == "..":
            cur.pop()
        elif len(d) > 0:
            cur.append(d)
    return cur

while n > 0:
    n -= 1
    c = raw_input()
    if c == "pwd":
        pwd(cur)
    else:
        cur = process(c, cur)

My first submission on this problem got accepted within 60ms using python. However, at first, i spent sometime debugging and couldn’t figure out why my first solution was not working… At last, I found out it is that in python, you can not access the global variables from functions… For example, the following will illustrate this.

n = 1

def c():
    n = 2

c()
# output 1
print n

In function c(), the value of ni s different than the global variable n(different copy). Therefore, the output still is 1.

In order to use global variable, you have to use the keyword global. The example is similar to the usage in PHP.

n = 1

def c():
    global n
    n = 2

c()
# output 2
print n

–EOF (The Ultimate Computing & Technology Blog) —

GD Star Rating
loading...
332 words
Last Post: Codeforces: A. Watermelon
Next Post: Codeforces: A. String Task

The Permanent URL is: Codeforces: C. Cd and pwd commands

Leave a Reply