How to Solve “houseOfCats” in CodeFights

The Problem:

There are some people and cats in a house. You are given the number of legs they have all together. Your task is to return an array containing every possible number of people that could be in the house sorted in ascending order. It’s guaranteed that each person has 2 legs and each cat has 4 legs.

Example

  • For legs = 6, the output should be
    houseOfCats(legs) = [1, 3].There could be either 1 cat and 1 person (4 + 2 = 6) or 3 people (2 * 3 = 6).
  • For legs = 2, the output should be
    houseOfCats(legs) = [1].There can be only 1 person.

Input/Output

  • [time limit] 4000ms (py)
  • [input] integer legsThe total number of legs in the house.

    Constraints:
    0 ≤ legs ≤ 45.

  • [output] array.integerEvery possible number of people that can be in the house.

The Solution:
def houseOfCats(legs):
r=[]
p=0
while legs>=0:
if legs%4==2 or legs%4==0:
c = 1 if (legs%4) == 2 else 0
r.append(p+c)
p+=2
legs-=4
return r

The Explanation:

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s