Journey to the Moon

  • + 0 comments

    Python solution using combinations. I calculate all the combinations and substract the pairs from the same country. Firstly I divide astronauts into countries and later I calculate number of combinations for each country.

    from math import factorial
    
    def combinations(n,k):
        return factorial(n)/(factorial(k)*factorial(n-k))
    
    def journeyToMoon(n, astronaut):
        countries = []
        for p in astronaut:
            x,y = p
            if len(countries) == 0:
                countries.append(astronaut[0])
            i = 0
            a = None
            b = None
            while i < len(countries):
                if x in countries[i]:
                    a = i
                if y in countries[i]:
                    b = i
                i+=1
            if a == None and b == None:
                countries.append(p)
            elif a == None and b != None:
                countries[b].append(x)
            elif a != None and b == None:
                countries[a].append(y)
            elif a!=b:
                countries[a].extend(countries[b])
                countries.remove(countries[b])
        pairs = 0
        for c in countries:
            if len(c) > 1:
                pairs += combinations(len(c),2)
        return int(combinations(n,2)-pairs)