dashrath1526's blog

By dashrath1526, history, 4 years ago, In English

Getting a time limit exceeds error on test #7. Help and understanding of efficient solution would be well appreciated.

n = int(input())
string = ''
group_count = 0
for i in range(n):
    num = input()

    if i == 0 or num[0] == string[-1]:
        string += num     
        group_count += 1
    else:
        string += num

print(group_count)
  • Vote: I like it
  • -16
  • Vote: I do not like it

»
4 years ago, # |
  Vote: I like it 0 Vote: I do not like it

What is question but ?

  • »
    »
    4 years ago, # ^ |
      Vote: I like it 0 Vote: I do not like it

    Mad scientist Mike entertains himself by arranging rows of dominoes. He doesn't need dominoes, though: he uses rectangular magnets instead. Each magnet has two poles, positive (a "plus") and negative (a "minus"). If two magnets are put together at a close distance, then the like poles will repel each other and the opposite poles will attract each other.

    Mike starts by laying one magnet horizontally on the table. During each following step Mike adds one more magnet horizontally to the right end of the row. Depending on how Mike puts the magnet on the table, it is either attracted to the previous one (forming a group of multiple magnets linked together) or repelled by it (then Mike lays this magnet at some distance to the right from the previous one). We assume that a sole magnet not linked to others forms a group of its own.

    Mike arranged multiple magnets in a row. Determine the number of groups that the magnets formed.

    Or you can refer to problem #344A

    • »
      »
      »
      4 years ago, # ^ |
      Rev. 6   Vote: I like it 0 Vote: I do not like it
      Solution
      Code
      • »
        »
        »
        »
        4 years ago, # ^ |
          Vote: I like it 0 Vote: I do not like it

        Tried what you suggested, but still its breaking o test#7.

        n = int(input())
        string = ''
        group_count = 1
        nums = []
        for i in range(n):
            nums.append(int(input()))
        
        for i in range(1,len(nums)):
            if nums[i] != nums[i-1]:
                group_count += 1
        
        print(group_count)