2

My code produces satisfied result in hacker rank compiler window for eleven out of fifteen test input in a certain problem. However, when i make subtle change in my code, all the the test inputs are run as OK.

This is a snippet of my previous code which shows error (terminated due to timeout).

for ind, letter in enumerate(string):
    if letter in vowels:
        kevin += len(string[ind:])
    else:
        stuart += len(string[ind:])

When i changed the above code as below all inputs are run successfully.

for ind, letter in enumerate(string):
    if letter in vowels:
        kevin += len(string) - ind
    else:
        stuart += len(string) - ind

Aren't these two codes equivalent?

7
  • ind is an integer correct? I really don't know what you're trying to do here. Commented Jun 29, 2018 at 13:26
  • enumerate function gives the first value as integer i think. Commented Jun 29, 2018 at 13:27
  • hacker rank the minion game problem. Commented Jun 29, 2018 at 13:33
  • 1
    What is the error? Commented Jun 29, 2018 at 13:35
  • 1
    You probably want to be more careful. Your question first reads like you want to know about a real "compiler error". But in essence, you are asking about the differences of two code snippets that do the same, but not exactly the same ;-) Commented Jun 29, 2018 at 13:37

1 Answer 1

2

These code snippets are entirely equivalent apart from two things:

  1. Second one is more optimized - There are no multiple subset creations of string.
  2. Second one works for any collection - can work on dict, list, tuple, string and anything that implements both __len__ and __iter__.

As you've added the error, saying it's a timeout error, I'm leaning towards issue #1 which is the string creation.

If you're creating a subset of a very long string you do the following operations for each iteration:

  1. Allocate n-1 bytes of space. (Slowish)
  2. Set all that space to zero (done internally, probably using calloc())
  3. Copy n-1 bytes from the original string to that new space. (Slow)
  4. Find out the length (A very fast operation)
  5. Deallocate the space. (Fast as well)

For long strings, this whole sequence can be a heavy operation, especially done for every iteration.

Second algortithm does this:

  1. Get length (fast operation)
  2. Substract integer (fast operation)
  3. ???
  4. Profit.
Sign up to request clarification or add additional context in comments.

1 Comment

indeed, adding assert len(string) - ind == len(string[ind:]) demonstrates the equivalence.

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.