in SPOJ

SPOJ: 1163. Java vs C ++ (JAVAC)

I started doing programming challenges again and chose SPOJ for it. I try to do about three challenges per week which should be possible. As Stephen King says:

Read and write four to six hours a day. If you cannot find the time for that, you can’t expect to become a good writer.

I actually wonder how much you would learn if you’re going to solve (harder) algorithmic problems four hours a day for a year. Probably a lot! In any case here’s the first problem and its solution.

Problem: Sphere Online Judge (SPOJ) – Problem JAVAC

def recognize(s):
    # -1: c++
    #  0: error
    # +1: java
    

    if s == s.lower():
        typ = 1
        last = 0
        for c in s:
            if c == '_':
                if last == 0: # last character was _
                    typ = -1
                    last = 1
                else:
                    typ = 0
                    break
            else:
                last = 0

        if s[-1] == '_' or s[0] == '_':
            typ = 0
    else:
        if s[0] == s[0].lower():
            typ = 1
            # if _ in java => error
            for c in s:
                if c == '_':
                    typ = 0
        else:
            typ = 0
    return typ

def transformJava(s):
    l = list(s)
    r = []
    for i in xrange(0, len(l)):
        if l[i] == l[i].upper():
            r.append('_')
            r.append(l[i].lower())
        else:
            r.append(l[i])

    return "".join(r)

def transformCpp(s):
    l = list(s)
    r = []
    for i in xrange(0, len(l)):
        if i > 1 and l[i-1] == '_':
            continue

        if l[i] == '_':
            r.append(l[i+1].upper())
            continue
        else:
            r.append(l[i])


    return "".join(r)


while True:
    try:
        s = raw_input()
    except:
        break

    r = recognize(s)
    if r == -1:
        print transformCpp(s)
    elif r == 1:
        print transformJava(s)
    else:
        print "Error!"

Write a Comment

Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.