Skip to content

Instantly share code, notes, and snippets.

@ShaneRich5
Last active May 25, 2017 04:03
Show Gist options
  • Save ShaneRich5/e6b8de4f9f0fa568ef37730e32f49960 to your computer and use it in GitHub Desktop.
Save ShaneRich5/e6b8de4f9f0fa568ef37730e32f49960 to your computer and use it in GitHub Desktop.
Solution to the Happy Ladybugs problems. https://www.hackerrank.com/challenges/happy-ladybugs
#!/bin/python
import sys
def happy_ladybugs(n, bugs):
mappings = {}
free_cell = False
happy = True
for i, bug in enumerate(bugs):
if i == 0 and i + 1 < len(bugs):
happy = bug == bugs[i + 1]
elif i == len(bugs) - 1:
happy = bugs[i - 1] == bug and happy
else:
happy = happy and (bugs[i - 1] == bug or bugs[i + 1] == bug)
# count the bugs
if bug == '_':
free_cell = True
elif bug in mappings:
mappings[bug] += 1
else:
mappings[bug] = 1
singles = 0
for bug, count in mappings.items():
if count == 1:
singles += 1
if singles > 0:
return 'NO'
if not free_cell:
return 'YES' if happy else 'NO'
return 'YES'
games = int(raw_input())
for _ in xrange(games):
n = int(raw_input())
b = raw_input()
print happy_ladybugs(n, b)
37
1
_
1
X
2
XX
2
X_
2
XY
3
X_X
3
XYX
3
XYZ
3
_XX
3
YXX
3
X__
3
X_Y
4
XXYY
4
XXYZ
4
XYXY
4
XXXY
4
XYXX
4
X_XX
4
X__X
4
XY_X
4
X___
5
XYZZZ
5
X_XYY
5
_XY_Y
5
_XX__
5
_XXYY
5
X_XYY
5
X___X
5
X__YX
6
X_X_Y_
6
XXXYYY
6
____ZZ
6
XYZYZY
6
XXYYZZ
6
X_XYXY
7
XZY_YZX
7
_XYYYXX
YES
NO
YES
NO
NO
YES
NO
NO
YES
NO
NO
NO
YES
NO
NO
NO
NO
YES
YES
NO
NO
NO
YES
NO
YES
YES
YES
YES
NO
NO
YES
YES
NO
YES
YES
YES
YES
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment