0

I'm trying this HackerRank problem. So far, I've ended up with this code :

n = int(raw_input())
ar = []

for i in xrange(n):
    ar.append(raw_input().split())

output = [0] * 1000000
count = [0] * 100

for a in ar:    
    count[int(a[0])] += 1

total = 0

for a in xrange(100):
    old = count[a]
    count[a] = total
    total += old

for a in ar:
    if ar.index(a) < n/2:
        output[count[int(a[0])]] = '-'
    else:
        output[count[int(a[0])]] = a[1]
    count[int(a[0])] += 1

for o in output:
    if type(o) != str:
        break
    else:
        print o,

Out of 5 test cases, it only passed one. 2 were timed out because of high running time, but that's not my priority now. My priority is passing the other 2 test cases which completely failed. I can't figure where I could have gone wrong. I know I can probably make my code more efficient, but for now, I'm focusing on just getting the right output.

1
  • I can only run one test case without signing up; but for performance: a) do all the int() conversions once at the start - while loading the data. Split it, convert to int() and then do ar.append. b) Same for replacing the first half with dashes, don't use output[count[int(a[0 when know the first half right at the very top when loading them into the array. Load a dash instead for the first half. c) No need to make output that big, make it [0] * n instead - lower memory use. d) Maybe skip the type(o) test on every output and just print o. Commented May 14, 2016 at 6:24

1 Answer 1

1

I suspect all your issues (both time and correctness) come from using ar.index(a) to check if a value is in the first half of the input list.

That line will always be very slow all the time (searching the list takes O(N) time), and it will give the wrong answer if there are two identical lines, one in the first half of the input and one in the second half. Instead, use enumerate to get the index as you are iterating over the list:

for i, a in enumerate(ar):
    if i < n/2:
        output[count[int(a[0])]] = '-'
    else:
        output[count[int(a[0])]] = a[1]
    count[int(a[0])] += 1

You can probably improve several other things (like making output length n, or converting each key to an int just once), but getting rid of the calls to list.index() is probably the most important fix.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you! The enumerate() did do the trick. I also made output length n.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.