コード例 #1
0
ファイル: ps1.py プロジェクト: PetrKosvanec/6.00.2X
def brute_force_cow_transport(cows,limit=10):
    """
    Finds the allocation of cows that minimizes the number of spaceship trips
    via brute force.  The brute force algorithm should follow the following method:

    1. Enumerate all possible ways that the cows can be divided into separate trips
    2. Select the allocation that minimizes the number of trips without making any trip
        that does not obey the weight limitation
            
    Does not mutate the given dictionary of cows.

    Parameters:
    cows - a dictionary of name (string), weight (int) pairs
    limit - weight limit of the spaceship (an int)
    
    Returns:
    A list of lists, with each inner list containing the names of cows
    transported on a particular trip and the overall list containing all the
    trips
    """
    import copy
    
    cowsNames = cows.keys()
    cowsNamesList = []
    
    for cowName in cowsNames:
        if cows[cowName] <= limit:
            cowsNamesList.append(cowName)
    
    leastNumOfTripsInSuccessflTransport = len(cowsNamesList)
    
    bestTransport = []
    
    for oneTransport in (get_partitions(cowsNamesList)):
        breakInThisTransport = False
        numOfTripsInThisTransport = 0
        for oneTrip in oneTransport:
            if breakInThisTransport:
                break            
            tripTonnage = 0
            for oneCow in oneTrip:
                tripTonnage += cows[oneCow]
                if tripTonnage <= limit:
                    continue
                else:
                    breakInThisTransport = True
                    break
            if not breakInThisTransport:
                numOfTripsInThisTransport += 1
        if (numOfTripsInThisTransport <= leastNumOfTripsInSuccessflTransport) and not breakInThisTransport:
            leastNumOfTripsInSuccessflTransport = numOfTripsInThisTransport
            bestTransport = copy.deepcopy(oneTransport)
    
    return bestTransport
コード例 #2
0
def brute_force_cow_transport(cows,limit=10):
    """
    Finds the allocation of cows that minimizes the number of spaceship trips
    via brute force.  The brute force algorithm should follow the following method:

    1. Enumerate all possible ways that the cows can be divided into separate trips
    2. Select the allocation that minimizes the number of trips without making any trip
        that does not obey the weight limitation

    Does not mutate the given dictionary of cows.

    Parameters:
    cows - a dictionary of name (string), weight (int) pairs
    limit - weight limit of the spaceship (an int)

    Returns:
    A list of lists, with each inner list containing the names of cows
    transported on a particular trip and the overall list containing all the
    trips
    """
    pCow = []
    accept = True
    w = 0
    w1 = []
    w2 = []
    for item in get_partitions(cows):
        for it in item:
            w = 0
            for j in it:
                w += cows[j]
                if w > limit:
                    accept = False
                    break
            if accept:
                w1.append(w)
            else:
                break
        if accept:
            if len(pCow) < 1:
                pCow.append(item)
                w2 = w1
            else:
                if len(w1) <= len(w2):
                    for i in range(len(w1)):
                        if w1[i] < w2[i]:
                            accept = False
                            break
                    if accept:
                        pCow.pop()
                        pCow.append(item)
                        w2 = w1
        accept = True
        w1 = []
    return pCow
コード例 #3
0
ファイル: ps1.py プロジェクト: aandres99/play_optimizer
def brute_force_cow_transport(cows, limit=10):
    """
    Finds the allocation of cows that minimizes the number of spaceship trips
    via brute force.  The brute force algorithm should follow the following
    method:

    1. Enumerate all possible ways that the cows can be divided into separate
       trips
    2. Select the allocation that minimizes the number of trips without making
       any trip that does not obey the weight limitation

    Does not mutate the given dictionary of cows.

    Parameters:
    cows - a dictionary of name (string), weight (int) pairs
    limit - weight limit of the spaceship (an int)

    Returns:
    A list of lists, with each inner list containing the names of cows
    transported on a particular trip and the overall list containing all the
    trips
    """
    c_cows = cows.copy()
    good_trips = []
    test_count = 0
    # find trips that don't exceed weight limit
    for trip_list in (get_partitions(c_cows)):
        test_count += 1
        # print('Trip list: ', trip_list)
        heavy_trip = False
        for trip in trip_list:
            trip_wt = 0
            for cow in range(len(trip)):
                trip_wt += c_cows[trip[cow]]
            # print('last cow in trip: ', trip[cow], 'total trip wt: ',
            #       trip_wt)
            if trip_wt > limit:
                # print('Trip too heavy')
                heavy_trip = True
                continue
        if heavy_trip is False:
            good_trips.append(trip_list)
        # if test_count == 200:
        #     break
    # find trips that have the minimum number of trips
    best_trips = []
    min_trip = len(good_trips[0])
    for trip_list in good_trips:
        if len(trip_list) < min_trip:
            min_trip = len(trip_list)
    for trip_list in good_trips:
        if len(trip_list) == min_trip:
            best_trips.append(trip_list)
    return best_trips
def brute_force_cow_transport(cows, limit=10):
    """
    Finds the allocation of cows that minimizes the number of spaceship trips
    via brute force.  The brute force algorithm should follow the following method:

    1. Enumerate all possible ways that the cows can be divided into separate trips 
        Use the given get_partitions function in ps1_partition.py to help you!
    2. Select the allocation that minimizes the number of trips without making any trip
        that does not obey the weight limitation
            
    Does not mutate the given dictionary of cows.

    Parameters:
    cows - a dictionary of name (string), weight (int) pairs
    limit - weight limit of the spaceship (an int)
    
    Returns:
    A list of lists, with each inner list containing the names of cows
    transported on a particular trip and the overall list containing all the
    trips
    """

    """
    get_partitions([1,2,3])的结果是
    [
    [[1, 2, 3]]
    [[2, 3], [1]]
    [[1, 3], [2]]
    [[3], [1, 2]]
    [[3], [2], [1]]
    ]
    但实际上,它的产生顺序并不是先1等分,然后2等分,被这个迷惑了.
    """

    all_cow_name = list(cows.keys())
    for trip_list in sorted(get_partitions(all_cow_name), key=lambda x: len(x)):
        is_trip_list_ok = True  # 标志判定此trip_list是否满足要求
        for trip in trip_list:
            total_weight = 0
            is_trip_ok = True  # 标志判定此trip是否满足要求
            for cow_name in trip:
                total_weight += cows[cow_name]
                if total_weight > limit:
                    is_trip_ok = False
                    break

            if not is_trip_ok:  # 如果此trip不行,那么此trip_list也不行,退出此次循环
                is_trip_list_ok = False
                break
        if is_trip_list_ok:
            return trip_list

    return None  # 如果是None 那么只说明了一个问题 至少有一只Cow的重量超过了limit_size
コード例 #5
0
ファイル: ps1a.py プロジェクト: algoflow19/MY_CS_Courses
def brute_force_cow_transport(cows, limit=10):
    """
    Finds the allocation of cows that minimizes the number of spaceship trips
    via brute force.  The brute force algorithm should follow the following method:

    1. Enumerate all possible ways that the cows can be divided into separate trips 
        Use the given get_partitions function in ps1_partition.py to help you!
    2. Select the allocation that minimizes the number of trips without making any trip
        that does not obey the weight limitation
            
    Does not mutate the given dictionary of cows.

    Parameters:
    cows - a dictionary of name (string), weight (int) pairs
    limit - weight limit of the spaceship (an int)
    
    Returns:
    A list of lists, with each inner list containing the names of cows
    transported on a particular trip and the overall list containing all the
    trips
    """
    cows_dict = {}
    print(cows)
    for i in range(1, 11):
        cows_dict[i] = []
    cows_name_list = []
    for cow in cows:
        cows_name_list.append(cow)
        cows_dict[cows[cow]].append(cow)

    def translate_name2num(cows_list):
        for i in cows_list:
            if (type(i) == type([])):
                cows_list.remove(i)
                cows_list.insert(0, translate_name2num(i))
            elif (cows.get(i, -1) != -1):
                cows_list.remove(i)
                cows_list.insert(0, cows.get(i, -1))
        return cows_list

    trip_generator = get_partitions(cows_name_list)
    trip_generator = list(trip_generator)
    trip_generator = translate_name2num(trip_generator)

    for trips in sorted(trip_generator, key=len):
        if (is_trip_possible(trips, limit)):
            trip_found = trips
            break
    trips_result = []
    for trip in map(lambda x: list(map(lambda cow: cows_dict[cow].pop(0), x)),
                    trip_found):
        trips_result.append(trip)
    return trips_result
コード例 #6
0
ファイル: ps1a.py プロジェクト: Carpetoid/6.0002_sols
def brute_force_cow_transport(cows, limit=10):
    """
    Finds the allocation of cows that minimizes the number of spaceship trips
    via brute force.  The brute force algorithm should follow the following method:

    1. Enumerate all possible ways that the cows can be divided into separate trips 
        Use the given get_partitions function in ps1_partition.py to help you!
    2. Select the allocation that minimizes the number of trips without making any trip
        that does not obey the weight limitation
            
    Does not mutate the given dictionary of cows.

    Parameters:
    cows - a dictionary of name (string), weight (int) pairs
    limit - weight limit of the spaceship (an int)
    
    Returns:
    A list of lists, with each inner list containing the names of cows
    transported on a particular trip and the overall list containing all the
    trips
    """
    possibilties = []
    for trip_possibilty in get_partitions(cows):
        possibilties += [trip_possibilty]

    possibiltiescopy = possibilties.copy()

    for possibilty in possibilties:

        for trip in possibilty:
            total = 0

            for cow in trip:
                total += cows[cow]

            if total > limit:
                possibiltiescopy.remove(possibilty)
                break

    mnmm_possibilty = None
    mnmm = None

    for i in possibiltiescopy:
        try:
            if len(i) <= mnmm:
                mnmm_possibilty = i
                mnmm = len(i)

        except TypeError:
            mnmm_possibilty = i
            mnmm = len(i)

    return mnmm_possibilty
コード例 #7
0
def brute_force_cow_transport(cows, limit=10):
    """
    Finds the allocation of cows that minimizes the number of spaceship trips
    via brute force.  The brute force algorithm should follow the following method:

    1. Enumerate all possible ways that the cows can be divided into separate trips
    2. Select the allocation that minimizes the number of trips without making any trip
        that does not obey the weight limitation
            
    Does not mutate the given dictionary of cows.

    Parameters:
    cows - a dictionary of name (string), weight (int) pairs
    limit - weight limit of the spaceship (an int)
    
    Returns:
    A list of lists, with each inner list containing the names of cows
    transported on a particular trip and the overall list containing all the
    trips
    """
    # initial setup
    bestCount = len(cows)
    bestCase = []
    countTrips = 0
    allCases = []
    for item in (get_partitions(cows)):
        allCases.append(item)

    for case in allCases:
        # print('CASE: ', case, '\n')
        for trip in case:
            # print('     TRIP: ', trip, '\n')
            # validate that this trip is legitimate, if so, count the trip
            cowWeightSum = 0
            for cow in trip:
                cowWeightSum += cows[cow]
                # print('     cowWeightSum: ', cowWeightSum)

            if cowWeightSum <= limit:
                countTrips += 1
                # print('     countTrips: ', countTrips, '\n')
                # if the enumeration reaches to the last one
                if trip == case[len(case) - 1]:
                    # print('     if the enumeration reaches to the last one', '\n')
                    if countTrips <= bestCount:
                        bestCount = countTrips
                        bestCase = case
                        countTrips = 0
                    countTrips = 0
            else:
                countTrips = 0
                break
コード例 #8
0
ファイル: ps1.py プロジェクト: Zedmor/EDX_6.00.1x
def brute_force_cow_transport(cows,limit=10):
    """
    Finds the allocation of cows that minimizes the number of spaceship trips
    via brute force.  The brute force algorithm should follow the following method:

    1. Enumerate all possible ways that the cows can be divided into separate trips
    2. Select the allocation that minimizes the number of trips without making any trip
        that does not obey the weight limitation
            
    Does not mutate the given dictionary of cows.

    Parameters:
    cows - a dictionary of name (string), weight (int) pairs
    limit - weight limit of the spaceship (an int)
    
    Returns:
    A list of lists, with each inner list containing the names of cows
    transported on a particular trip and the overall list containing all the
    trips
    """
    # TODO: Your code here
    import operator
    # print(cows)
    mintrips = len(cows)
    result = []

    def flatten(items, seqtypes=(list)):
        for i, x in enumerate(items):
            while i < len(items) and isinstance(items[i], seqtypes):
                items[i:i + 1] = items[i]
        return items

    for item in get_partitions(cows.items()):
        #print([sum(i[1]) for i in item] )
        variant =  [i for i in item if (sum( [x[1] for x in i] )) <= limit]
        # if len(variant) ==1 : variant = variant[0]
        # if len(flatten(i[:]))==4


        # print(len(variant), len(flatten(variant)), variant)
        if len(variant) <= mintrips and len(flatten(variant[:])) == len(cows):
            result = variant
            mintrips = len(variant)
    outerlist = []
    for i in result:
        innerlist = []
        for j in i:
            innerlist.append(j[0])
        outerlist.append(innerlist)

    #print(outerlist)
    return outerlist
コード例 #9
0
ファイル: ps1.py プロジェクト: nardellajr/Edx
def brute_force_cow_transport(cows, limit=10):
    """
    Finds the allocation of cows that minimizes the number of spaceship trips
    via brute force.  The brute force algorithm should follow the following method:

    1. Enumerate all possible ways that the cows can be divided into separate trips
    2. Select the allocation that minimizes the number of trips without making any trip
        that does not obey the weight limitation
            
    Does not mutate the given dictionary of cows.

    Parameters:
    cows - a dictionary of name (string), weight (int) pairs
    limit - weight limit of the spaceship (an int)
    
    Returns:
    A list of lists, with each inner list containing the names of cows
    transported on a particular trip and the overall list containing all the
    trips
    """
    trips = []
    names = []
    count = 0
    start = time.perf_counter_ns()
    # start = datetime.datetime.now()
    # start = time.time()
    for partition in get_partitions(
            sorted(cows.items(), key=lambda kv: kv[1], reverse=True)):
        # print("partition created", partition)
        count += 1
        include_partition = True
        for cow_name_array in partition:
            if sum([c[1] for c in cow_name_array]) > limit:
                include_partition = False
                break
            else:
                names.append([c[0] for c in cow_name_array])

        if include_partition:
            print("Valid partition: ", partition)
            trips = names
            names = []
            # break after first valid partition is found, which contains the least about of trips
            break
    end = time.perf_counter_ns() - start
    # end = datetime.datetime.now() - start
    # end = time.time()
    # print(end - start)
    print(end)
    print(end / 1000000)  # convert nanoseconds to milliseconds
    print("brute force1", count)
    return trips
コード例 #10
0
def brute_force_cow_transport(cows, limit=10):
    def itempick(D):
        m = []
        for x in D:
            box = []
            for i in x:
                box += [i[0]]
            m.append(box)
        return m

    cowsCopy = cows.copy()
    cowslist = sorted(cowsCopy.items(), key=lambda x: x[1])
    power_list = get_partitions(cowslist)
    best_rout = []
    best_counter = len(cowslist) + 1
    #    if best_counter<len(next(power_list)):
    #        best_rout = itempick(best_rout)
    #        return best_rout
    #    else:
    for minor_set in power_list:
        temp_rout = []
        temp_counter = 0
        flag = True
        temp_counter = len(minor_set)
        for set_part in minor_set:
            if flag:
                weight_sum = 0

            else:
                break

            for item in set_part:
                if item[1] + weight_sum <= limit:
                    weight_sum += item[1]

                else:
                    temp_rout = []
                    weight_sum = 0
                    flag = False

                    break
        if temp_counter < best_counter and weight_sum != 0:

            best_counter = temp_counter
            temp_rout = minor_set
            best_rout = temp_rout
            print(temp_rout, "t")
        else:

            continue
    best_rout = itempick(best_rout)
    return best_rout
コード例 #11
0
def brute_force_cow_transport(cows, limit):
    """
    Finds the allocation of cows that minimizes the number of spaceship trips
    via brute force.  The brute force algorithm should follow the following method:

    1. Enumerate all possible ways that the cows can be divided into separate trips
    2. Select the allocation that minimizes the number of trips without making any trip
        that does not obey the weight limitation
            
    Does not mutate the given dictionary of cows.

    Parameters:
    cows - a dictionary of name (string), weight (int) pairs
    limit - weight limit of the spaceship (an int)
    
    Returns:
    A list of lists, with each inner list containing the names of cows
    transported on a particular trip and the overall list containing all the
    trips
    """

    # cowsWeight = list(sorted(cows.values(), reverse=True))
    # print(cowsWeight)

    cowsCopy = sorted(cows, key=cows.get, reverse=True)
    best_partition = []
    for partition in get_partitions(cowsCopy):
        if best_partition == []:
            for item in partition:
                flag = 0
                cowsWeight = sum([cows[x] for x in item])
                if cowsWeight > limit:
                    flag = 0
                    break
                else:
                    flag = 1
            if flag == 1:
                best_partition = partition
        if len(partition) < len(best_partition):
            for item in partition:
                flag = 0
                cowsWeight = sum([cows[x] for x in item])
                if cowsWeight > limit:
                    flag = 0
                    break
                else:
                    flag = 1
            if flag == 1:
                best_partition = partition

    return best_partition
コード例 #12
0
def brute_force_cow_transport(cows, limit=10):
    """
    Finds the allocation of cows that minimizes the number of spaceship trips
    via brute force.  The brute force algorithm should follow the following method:

    1. Enumerate all possible ways that the cows can be divided into separate trips
    2. Select the allocation that minimizes the number of trips without making any trip
        that does not obey the weight limitation
            
    Does not mutate the given dictionary of cows.

    Parameters:
    cows - a dictionary of name (string), weight (int) pairs
    limit - weight limit of the spaceship (an int)
    
    Returns:
    A list of lists, with each inner list containing the names of cows
    transported on a particular trip and the overall list containing all the
    trips
    """
    c = cows.copy()
    completedPartitions = []

    # We are going to process all combinations of trips
    for partition in get_partitions(c):
        # Check that all trips in this combination are valid
        for trip in partition:
            abort = False
            tripWeight = 0
            for cow in trip:
                tripWeight = tripWeight + c[cow]
                # If we pass the limit abort trip
                if (tripWeight > limit):
                    abort = True
                    break
            # If we abort a single trip, we abort that combination
            if abort == True:
                break
        # If we did not abort any trip, the combination is valid
        if abort == False:
            completedPartitions.append(partition)

    minTrips = len(cows)
    chosenPartition = []
    # Find out which combination has the fewer number of trips
    for completedPartition in completedPartitions:
        completedPartitionTrips = len(completedPartition)
        if completedPartitionTrips < minTrips:
            minTrips = completedPartitionTrips
            chosenPartition = completedPartition
    return chosenPartition
コード例 #13
0
ファイル: ps1a.py プロジェクト: tyday/60002PS1
def brute_force_cow_transport(cows, limit=10):
    """
    Finds the allocation of cows that minimizes the number of spaceship trips
    via brute force.  The brute force algorithm should follow the following method:

    1. Enumerate all possible ways that the cows can be divided into separate trips 
        Use the given get_partitions function in ps1_partition.py to help you!
    2. Select the allocation that minimizes the number of trips without making any trip
        that does not obey the weight limitation
            
    Does not mutate the given dictionary of cows.

    Parameters:
    cows - a dictionary of name (string), weight (int) pairs
    limit - weight limit of the spaceship (an int)
    
    Returns:
    A list of lists, with each inner list containing the names of cows
    transported on a particular trip and the overall list containing all the
    trips  
    """
    copycows = cows.copy()  #copy of the cow dictionary
    scenariolist = []  #store all permutations in this list
    bestrun = []  #store list of the best run
    ''' How does the iteration work here?
    
        '''
    for partition in get_partitions(copycows):
        scenariolist.append(partition)
    # look at each scenario individually
    # The scenarios consist of trips and the trips consist of cows
    # if any trip weighs more than the limit then the entire scenario can be discarded
    scraptrip = False
    bestrun = []
    for scenario in range(1, len(scenariolist), 1):
        scraptrip = False
        for trip in scenariolist[scenario]:
            if scraptrip == True:
                break
            tot_weight = 0
            for cow in trip:
                tot_weight += int(cows[cow])
            if tot_weight > limit:
                scraptrip = True
                break
        if scraptrip == False:
            if bestrun == []:
                bestrun = scenariolist[scenario]
            elif len(scenariolist[scenario]) < len(bestrun):
                bestrun = scenariolist[scenario]
    return bestrun
コード例 #14
0
def brute_force_cow_transport(cows,limit=10):
    """
    Finds the allocation of cows that minimizes the number of spaceship trips
    via brute force.  The brute force algorithm should follow the following method:

    1. Enumerate all possible ways that the cows can be divided into separate trips 
        Use the given get_partitions function in ps1_partition.py to help you!
    2. Select the allocation that minimizes the number of trips without making any trip
        that does not obey the weight limitation
            
    Does not mutate the given dictionary of cows.

    Parameters:
    cows - a dictionary of name (string), weight (int) pairs
    limit - weight limit of the spaceship (an int)
    
    Returns:
    A list of lists, with each inner list containing the names of cows
    transported on a particular trip and the overall list containing all the
    trips
    """
    cows = [(key, value) for key, value in cows.items()]
    candidates = []
    for combination in get_partitions(cows):
        # sanity check: check if every list is in limit
        all_valid = True
        for trip in combination:
            current_trip_weight = 0
            for cow, weight in trip:
                current_trip_weight += weight
            if current_trip_weight > limit:
                all_valid = False
                break

        if all_valid:
            candidates.append(combination)

    # find the candidates with minimal trips
    current_shortest_length, best_candidate = None, None
    for candidate in candidates:
        if current_shortest_length is None:
            current_shortest_length = len(candidate)
            best_candidate = candidate
        elif len(candidate) < current_shortest_length:
            current_shortest_length = len(candidate)
            best_candidate = candidate

    # print(len(best_candidate))
    # print(best_candidate)
    # insert only names in result
    return [[name for name, weight in sub] for sub in best_candidate] 
コード例 #15
0
def brute_force_cow_transport(cows, limit=10):
    """
    Finds the allocation of cows that minimizes the number of spaceship trips
    via brute forc
    e.  The brute force algorithm should follow the following method:

    1. Enumerate all possible ways that the cows can be divided into separate trips
    2. Select the allocation that minimizes the number of trips without making any trip
        that does not obey the weight limitation
            
    Does not mutate the given dictionary of cows.

    Parameters:
    cows - a dictionary of name (string), weight (int) pairs
    limit - weight limit of the spaceship (an int)
    
    Returns:
    A list of lists, with each inner list containing the names of cows
    transported on a particular trip and the overall list containing all the
    trips
    """
    def count_sum(listofcows, cows):
        weight = 0
        for i in listofcows:
            weight += cows[i]
            if weight > limit:
                return False
                break
        return True

    cow_list = list(cows.keys())

    flight_list = []
    all_partitions = get_partitions(cow_list)

    for i in all_partitions:
        switch = 'green'
        for j in i:
            if count_sum(j, cows) == False:
                switch = 'red'
                break
        if switch == 'green':
            flight_list.append(i)

    trip_len_list = [len(i) for i in flight_list]

    for i in flight_list:
        if len(i) == min(trip_len_list):
            ideal_trip = i
            break
    return ideal_trip
def brute_force_cow_transport(cows,limit=10):
    """
    Finds the allocation of cows that minimizes the number of spaceship trips
    via brute force.  The brute force algorithm should follow the following method:

    1. Enumerate all possible ways that the cows can be divided into separate trips
        Use the given get_partitions function in ps1_partition.py to help you!
    2. Select the allocation that minimizes the number of trips without making any trip
        that does not obey the weight limitation

    Does not mutate the given dictionary of cows.

    Parameters:
    cows - a dictionary of name (string), weight (int) pairs
    limit - weight limit of the spaceship (an int)

    Returns:
    A list of lists, with each inner list containing the names of cows
    transported on a particular trip and the overall list containing all the
    trips
    """
    # Make a copy for cows dict
    cows_copy = cows.copy()
    # The list that contains all trips
    trips_list = []

    # Set flag to mark whether it is over the weight limit
    flag = False
    for partition in get_partitions(cows_copy):
        for list_elem in partition:
            # Get the total weight for each list in the partition
            total_weight = sum([cows_copy[k] for k in list_elem])
            if total_weight > limit:
                flag = False
                break
            else:
                flag = True

        # If flag is true, the partition satisfies the condition
        if flag:
            trips_list.append(partition)

    # Get the least trips for transport
    min_len = len(cows_copy)
    for k in trips_list:
        if len(k) < min_len:
            min_len = len(k)

    # Get all lists whose length is equal to minimal length
    result = [k for k in trips_list if len(k) == min_len]
    return result[0]
コード例 #17
0
ファイル: ps1a.py プロジェクト: asdhamidi/6.0002
def brute_force_cow_transport(cows,limit=10):
    """
    Finds the allocation of cows that minimizes the number of spaceship trips
    via brute force.  The brute force algorithm should follow the following method:

    1. Enumerate all possible ways that the cows can be divided into separate trips 
        Use the given get_partitions function in ps1_partition.py to help you!
    2. Select the allocation that minimizes the number of trips without making any trip
        that does not obey the weight limitation
            
    Does not mutate the given dictionary of cows.

    Parameters:
    cows - a dictionary of name (string), weight (int) pairs
    limit - weight limit of the spaceship (an int)
    
    Returns:
    A list of lists, with each inner list containing the names of cows
    transported on a particular trip and the overall list containing all the
    trips
    """
    continueSignal = False
    
    # Assuming worst case would be each cow being transported individually.
    trips = len(cows) 
    # This will store the best combination at the end to be returned.
    bestChoice = [] 
    for partition in get_partitions(cows.copy()):
        for sets in partition: # Going through each element of the sublists.
            sumOfElements = 0
            # Adding weights for each sublists.
            for element in sets:
                sumOfElements += cows[element]
            
            # If any sublist of a list breaks the weight limit, we move onto the next list.
            if sumOfElements > limit: 
                continueSignal = True
                break
        
        # If continueSignal is true, we just move to the next list, without comparing,
        # with best choice.
        if continueSignal:
            continueSignal = False
            continue
        
        # Comparing number of trips taken by current combo with the best combo.
        if len(partition) < trips:
            trips = len(partition)
            bestChoice = partition
    
    return bestChoice
コード例 #18
0
ファイル: ps1.py プロジェクト: C0MPU73R/MITx-Course-6.00.2x
def brute_force_cow_transport(cows, limit=10):
    """
    Finds the allocation of cows that minimizes the number of spaceship trips
    via brute force.  The brute force algorithm should follow the following method:

    1. Enumerate all possible ways that the cows can be divided into separate trips
    2. Select the allocation that minimizes the number of trips without making any trip
        that does not obey the weight limitation
            
    Does not mutate the given dictionary of cows.

    Parameters:
    cows - a dictionary of name (string), weight (int) pairs
    limit - weight limit of the spaceship (an int)
    
    Returns:
    A list of lists, with each inner list containing the names of cows
    transported on a particular trip and the overall list containing all the
    trips
    """
    # TODO: Your code here

    copia_cows = cows.copy()
    listaCows = []
    listaViagensExcluidas = []
    listaViagens = []
    listaViagensDisponiveis = []

    for key in cows.keys():
        listaCows.append(key)

    for partition in get_partitions(listaCows):
        listaViagens.append(partition)

        for viagem in partition:
            pesoMaximo = 0
            for vaca in viagem:
                pesoMaximo = pesoMaximo + copia_cows.get(vaca)

                if pesoMaximo > limit:
                    listaViagensExcluidas.append(partition)
                    break

    for viagem in listaViagens:
        if viagem not in listaViagensExcluidas:
            listaViagensDisponiveis.append(viagem)

    viagensOrdenadas = sorted(listaViagensDisponiveis, key=len)

    return viagensOrdenadas[0]
コード例 #19
0
def brute_force_cow_transport(cows,limit=10):
    """
    Finds the allocation of cows that minimizes the number of spaceship trips
    via brute force.  The brute force algorithm should follow the following method:

    1. Enumerate all possible ways that the cows can be divided into separate trips
    2. Select the allocation that minimizes the number of trips without making any trip
        that does not obey the weight limitation
            
    Does not mutate the given dictionary of cows.

    Parameters:
    cows - a dictionary of name (string), weight (int) pairs
    limit - weight limit of the spaceship (an int)
    
    Returns:
    A list of lists, with each inner list containing the names of cows
    transported on a particular trip and the overall list containing all the
    trips
    """
    # TODO: Your code here
    # intialize final list of trips
    trips = []
    # create power list using helper function, and sort it - shortest first!
    power_list = sorted(get_partitions(cows), key = len)
    # Note that this returns a list of names (strings), and we will need to do
    # dictionary lookup later
    # Now time to filter the power list:
    possibilities = []
    for i in power_list:
        ship = []
        for j in i:
            ship_weights = []
            for k in j:
                ship_weights.append(cows[k])
                #print(ship_weights)
            ship.append(sum(ship_weights))
            #print(ship)
        if all(d <= limit for d in ship):
            possibilities.append(i)
    # possibiliies now contains some duplicates, which need to be removed
    pruned_possibilities = []
    for k in possibilities:
        if k not in pruned_possibilities:
            pruned_possibilities.append(k)
    # now find the minimum list length:
    min_list_len = min(map(len, pruned_possibilities))
    for l in pruned_possibilities:
        if len(l) == min_list_len:
            return l
コード例 #20
0
ファイル: ps1.py プロジェクト: ElAwbery/MIT-6.00.2x
    def brute_force_cow_transport(cows, limit=10):
        """
        I/O as defined in program above
        """
        best_yet = None

        for partition in get_partitions(cows):

            if within_weight_limit(cows, partition, limit):

                if (best_yet == None) or len(partition) < len(best_yet):
                    best_yet = partition

        return best_yet
コード例 #21
0
def brute_force_cow_transport(cows, limit=10):
    """
    Finds the allocation of cows that minimizes the number of spaceship trips
    via brute force.  The brute force algorithm should follow the following method:

    1. Enumerate all possible ways that the cows can be divided into separate trips 
        Use the given get_partitions function in ps1_partition.py to help you!
    2. Select the allocation that minimizes the number of trips without making any trip
        that does not obey the weight limitation
            
    Does not mutate the given dictionary of cows.

    Parameters:
    cows - a dictionary of name (string), weight (int) pairs
    limit - weight limit of the spaceship (an int)
    
    Returns:
    A list of lists, with each inner list containing the names of cows
    transported on a particular trip and the overall list containing all the
    trips
    """
    start = time.time()
    cowsNames = cows.keys()
    sortedCows = sortedCowsList(cows)
    powerSet = get_partitions(cowsNames)
    smallest = limit**limit
    smallestSets = []
    for partitions in powerSet:
        if len(partitions) <= smallest:
            exceedsWeight = False
            for permutation in partitions:
                weight = 0
                for cow in permutation:
                    weight += cows[cow]
                    if weight > limit:
                        exceedsWeight = True
                        break
                if exceedsWeight == True:
                    break
            if exceedsWeight == False:
                if len(partitions) == smallest:
                    smallestSets.append(partitions)
                else:
                    smallestSets = []
                    smallestSets.append(partitions)
                    smallest = len(partitions)
    end = time.time()
    print("Time taken for Brute Force: ", end - start)

    return smallestSets
コード例 #22
0
ファイル: ps1.py プロジェクト: Nik620/edX_MITx_6.00.2x
def brute_force_cow_transport(cows,limit=10):
    """
    Finds the allocation of cows that minimizes the number of spaceship trips
    via brute force.  The brute force algorithm should follow the following method:

    1. Enumerate all possible ways that the cows can be divided into separate trips
    2. Select the allocation that minimizes the number of trips without making any trip
        that does not obey the weight limitation
            
    Does not mutate the given dictionary of cows.

    Parameters:
    cows - a dictionary of name (string), weight (int) pairs
    limit - weight limit of the spaceship (an int)
    
    Returns:
    A list of lists, with each inner list containing the names of cows
    transported on a particular trip and the overall list containing all the
    trips
    """
    
    # now don't need a sorted list, running through cows
    cows_dict = cows.copy()
    cow_names = list(cows)
    valid_trips = []
    shortest_trips = [] 
    
    # loop to collect valid partitioned possibilities
    for trips in get_partitions(cow_names): # breaking into partitions
        valid_trip = [] # bool will check if any invalid partitions
        for trip in trips: # breaking partitions into ships
            trip_weight = 0 # reset weight
            for cow in trip: # individual cow in ship, assess wt
                trip_weight += cows_dict[cow] # calc wt
            if trip_weight <= limit: # wt limit check, true if <lim
                valid_trip.append(True)
            else:
                valid_trip.append(False)
        if False not in valid_trip: # checking to make sure no trips over 10
            valid_trips.append(trips)
    
    # loop over the valid_trips to find fewest
    for trips in valid_trips:
        if len(shortest_trips) == 0:
            shortest_trips = trips
        elif len(trips) < len(shortest_trips):
            shortest_trips = trips
    
    # return shortest trip
    return shortest_trips
コード例 #23
0
ファイル: ps1a.py プロジェクト: vwozhaoxin/mit-6.0002
def brute_force_cow_transport(cows, limit=10):
    """
    Finds the allocation of cows that minimizes the number of spaceship trips
    via brute force.  The brute force algorithm should follow the following method:

    1. Enumerate all possible ways that the cows can be divided into separate trips 
        Use the given get_partitions function in ps1_partition.py to help you!
    2. Select the allocation that minimizes the number of trips without making any trip
        that does not obey the weight limitation
            
    Does not mutate the given dictionary of cows.

    Parameters:
    cows - a dictionary of name (string), weight (int) pairs
    limit - weight limit of the spaceship (an int)
    
    Returns:
    A list of lists, with each inner list containing the names of cows
    transported on a particular trip and the overall list containing all the
    trips
    """
    # TODO: Your code here
    start = time.time()
    brutelist = [trip for trip in get_partitions(cows.keys())]
    bestnumber = 100000
    for outloop in brutelist:
        results = []

        for middleloop in outloop:
            result = []
            listlimit = 0
            if type(middleloop) == list:
                for innerloop in middleloop:
                    listlimit += int(cows[innerloop])
                if listlimit <= limit:
                    result.append(middleloop)
                else:
                    break
            else:
                result.appen(middleloop)
            results.append(result)
        if result != []:
            number = len(results)
            if number < bestnumber:
                bestnumber = number
                best_results = results
#               print(best_results)
    end = time.time()
    #    print('brute cost time:', end-start)
    return best_results
コード例 #24
0
def brute_force_cow_transport(cows,limit=10):
    """
    Finds the allocation of cows that minimizes the number of spaceship trips
    via brute force.  The brute force algorithm should follow the following method:

    1. Enumerate all possible ways that the cows can be divided into separate trips
    2. Select the allocation that minimizes the number of trips without making any trip
        that does not obey the weight limitation

    Does not mutate the given dictionary of cows.

    Parameters:
    cows - a dictionary of name (string), weight (int) pairs
    limit - weight limit of the spaceship (an int)

    Returns:
    A list of lists, with each inner list containing the names of cows
    transported on a particular trip and the overall list containing all the
    trips
    """
    # for item in get_partitions(cows):
    #     good = True
    #     #assume this item is good
    #     for i in range(len(item)):
    #         # good = True
    #     #determine if every trip is goo
    #         if good:
    #             total = 0
    #             for j in range(len(item[i])):
    #                 total += cows[item[i][j]]
    #             if total >= limit:
    #                 good = False
    #     if good:
    #         return item
    for item in get_partitions(cows):
        good = True
        #assume this item is good

        for i in range(len(item)):
            if good:
                # good = True
                #determine if every trip is goo

                total = 0
                for j in range(len(item[i])):
                    total += cows[item[i][j]]
                if total >= limit:
                    good = False
        if good:
            return item
コード例 #25
0
def brute_force_cow_transport(cows,limit=10):
    """
    Finds the allocation of cows that minimizes the number of spaceship trips
    via brute force.  The brute force algorithm should follow the following method:

    1. Enumerate all possible ways that the cows can be divided into separate trips 
        Use the given get_partitions function in ps1_partition.py to help you!
    2. Select the allocation that minimizes the number of trips without making any trip
        that does not obey the weight limitation
            
    Does not mutate the given dictionary of cows.

    Parameters:
    cows - a dictionary of name (string), weight (int) pairs
    limit - weight limit of the spaceship (an int)
    
    Returns:
    A list of lists, with each inner list containing the names of cows
    transported on a particular trip and the overall list containing all the
    trips
    """
    # TODO: Your code here
    #possible partitions
    possible_parts=sorted(get_partitions(cows))
    trips=[]

    for x in possible_parts:
        trip=[]
        for y in x:
            #create a new empty list for each partition called weights
            weights=[]
            for l in y:
                #add cows weight to weight
                weights.append(cows[l])
            #add the sum of each trip to the trip list
            trip.append(sum(weights))
        #if each entry in trip is less than the limit, than that is a valid trip and we add it to trips
        if all(trip<=limit for trip in trip):
            trips.append(x)
    remove_dupes=[]
    #remove duplicate trips
    for x in trips:
        if x not in remove_dupes:
            remove_dupes.append(x)
    trips_length=[]
    #add the length of each trip to a new list called trips_length
    for x in remove_dupes:
        trips_length.append(len(x))
    #return the trip which has the least length
    return trips_length.index(min(trips_length))
コード例 #26
0
def brute_force_cow_transport(cows, limit=10):
    """
    Finds the allocation of cows that minimizes the number of spaceship trips
    via brute force.  The brute force algorithm should follow the following method:

    1. Enumerate all possible ways that the cows can be divided into separate trips 
        Use the given get_partitions function in ps1_partition.py to help you!
    2. Select the allocation that minimizes the number of trips without making any trip
        that does not obey the weight limitation
            
    Does not mutate the given dictionary of cows.

    Parameters:
    cows - a dictionary of name (string), weight (int) pairs
    limit - weight limit of the spaceship (an int)
    
    Returns:
    A list of lists, with each inner list containing the names of cows
    transported on a particular trip and the overall list containing all the
    trips
    """

    # init least number of shuttles based on having one cow in each shuttle
    # (worst case scenario)
    least_shuttles = len(cows)
    shuttles = [[cow] for cow in cows.keys()]
    # init generator to enumerate all possible shuttle partitionings
    partitionings = get_partitions(cows)
    # check weight of each partition in each partitioning
    for partition in partitionings:
        # get number of shuttles in partition
        nb_shuttles = len(partition)
        # if not better than current best number, skip to next partition
        if nb_shuttles >= least_shuttles:
            continue
        # check all shuttles meet weight requirements
        limit_exceeded = False
        for shuttle in partition:
            # sum weight of all cows in shuttle
            shuttle_weight = sum([cows[name] for name in shuttle])
            # if weight is over the limit, flag and break out of loop
            if shuttle_weight > limit:
                limit_exceeded = True
                break
        if not limit_exceeded:
            least_shuttles = nb_shuttles
            shuttles = partition

    return shuttles
コード例 #27
0
def brute_force_cow_transport(cows, limit=10):
    """
    Finds the allocation of cows that minimizes the number of spaceship trips
    via brute force.  The brute force algorithm should follow the following method:

    1. Enumerate all possible ways that the cows can be divided into separate trips 
        Use the given get_partitions function in ps1_partition.py to help you!
    2. Select the allocation that minimizes the number of trips without making any trip
        that does not obey the weight limitation
            
    Does not mutate the given dictionary of cows.

    Parameters:
    cows - a dictionary of name (string), weight (int) pairs
    limit - weight limit of the spaceship (an int)
    
    Returns:
    A list of lists, with each inner list containing the names of cows
    transported on a particular trip and the overall list containing all the
    trips
    """
    cows_copy = cows.copy()  # copy of cows dict
    best_trips = 0
    result = []

    for partition in get_partitions(cows_copy):  # for each partition of the
        # dictionary of cows i.e. each possible subset of cows
        number_trips = 0  # reset number of trips
        for trip in partition:  # for each trip in a partition i.e. for each
            # subset in a partition
            totalWeight = 0  # reset totalWeight
            for name in trip:  # for each cow in that trip
                totalWeight += cows_copy[name]  # add their weight to the total
                if totalWeight >= limit:  # if weight exceeds the limit
                    number_trips += 1000  # add many trips (filters out those
                    # subsets which contain cows exceeding the weight limit
                    # for 1 trip, as this are not possible)
            number_trips += 1  # if the total weight of all cows in that trip
            # is less than the limit, this is a valid trip, so add 1 to number
            # of trips
        if best_trips == 0:  # make the first run the best run
            best_trips = number_trips
            result.append(partition)
        elif number_trips < best_trips:  # if any subsequent runs require less
            # trips than the current best trip
            best_trips = number_trips  # make it the new best
            result.clear()  # clear the result
            result.append(partition)  # add this partition as new best
    return result
コード例 #28
0
def brute_force_cow_transport(cows,limit=10):
    """
    Finds the allocation of cows that minimizes the number of spaceship trips
    via brute force.  The brute force algorithm should follow the following method:

    1. Enumerate all possible ways that the cows can be divided into separate trips 
        Use the given get_partitions function in ps1_partition.py to help you!
    2. Select the allocation that minimizes the number of trips without making any trip
        that does not obey the weight limitation
            
    Does not mutate the given dictionary of cows.

    Parameters:
    cows - a dictionary of name (string), weight (int) pairs
    limit - weight limit of the spaceship (an int)
    
    Returns:
    A list of lists, with each inner list containing the names of cows
    transported on a particular trip and the overall list containing all the
    trips
    """
    # TODO: Your code here
    start_time = time.time()
    # use get_partitions to generate all the possible combinations of cows
    cowsa = get_partitions(cows) 
    summ = 0.0
    count = 0
    tripslen = []
    trips = []
    for row in cowsa:
        for trip in row:
            for i in trip:
                summ += cows[i]
            if summ <= limit:
                summ = 0.0
                continue
            else:
                count = 1
                break
        if count == 0:
            trips.append(row)
            tripslen.append(len(row))
        summ = 0.0
        count = 0
    minpos = tripslen.index(min(tripslen))
    finaltrips = trips[minpos]
    print('executed time = ', time.time() - start_time)
    
    return finaltrips
コード例 #29
0
def brute_force_cow_transport(cows, limit=10):
    """
    Finds the allocation of cows that minimizes the number of spaceship trips
    via brute force.  The brute force algorithm should follow the following method:

    1. Enumerate all possible ways that the cows can be divided into separate trips
        Use the given get_partitions function in ps1_partition.py to help you!
    2. Select the allocation that minimizes the number of trips without making any trip
        that does not obey the weight limitation

    Does not mutate the given dictionary of cows.

    Parameters:
    cows - a dictionary of name (string), weight (int) pairs
    limit - weight limit of the spaceship (an int)

    Returns:
    A list of lists, with each inner list containing the names of cows
    transported on a particular trip and the overall list containing all the
    trips
    """
    # Get list of cow names, copying to avoid mutation
    cow_names = list(cows)
    shortest_number_of_trips = len(cow_names)
    best_trip_plan = []

    # Try every possible set of trips, trying a single trip first, then two trips, etc.
    for set_of_trips in get_partitions(cow_names):
        current_number_of_trips = len(set_of_trips)
        trips_under_limit = True

        for trip in set_of_trips:
            # Calculate the weight of the current trip
            current_trip_weight = 0
            for cow in trip:
                current_trip_weight += cows[cow]

            # If any of the trips are over the weight limit, move on to the next set
            if current_trip_weight > limit:
                trips_under_limit = False
                break

        # If the spaceship isn't broken and this set used fewer trips, it's the best plan
        if (trips_under_limit) and (current_number_of_trips <
                                    shortest_number_of_trips):
            shortest_number_of_trips = current_number_of_trips
            best_trip_plan = set_of_trips

    return best_trip_plan
コード例 #30
0
def brute_force_cow_transport(cows,limit=10):
    """
    Finds the allocation of cows that minimizes the number of spaceship trips
    via brute force.  The brute force algorithm should follow the following method:

    1. Enumerate all possible ways that the cows can be divided into separate trips
        Use the given get_partitions function in ps1_partition.py to help you!
    2. Select the allocation that minimizes the number of trips without making any trip
        that does not obey the weight limitation

    Does not mutate the given dictionary of cows.

    Parameters:
    cows - a dictionary of name (string), weight (int) pairs
    limit - weight limit of the spaceship (an int)

    Returns:
    A list of lists, with each inner list containing the names of cows
    transported on a particular trip and the overall list containing all the
    trips
    """
    # TODO: Your code here
    partitions = get_partitions(cows)

    pruned_partitions = []
    for partition in partitions :
        is_pruned = True
        for trip in partition:
            sum_weights = 0
            for cow in trip:

                sum_weights += int(cows[cow])
            if sum_weights > limit:
                is_pruned = False
                break
        if is_pruned:
            pruned_partitions.append(partition)
   #now pruned_partitions contains all partitions in which each trip
   #has weight less than 10
    min_partition = pruned_partitions[0]
    for partition in pruned_partitions:
       if(len(partition) < len(min_partition)):
           min_partition = partition

    return min_partition



    return min_trip
コード例 #31
0
ファイル: ps1.py プロジェクト: 1337tester/pyfund
def brute_force_cow_transport(cows,limit=10):
    """
    Finds the allocation of cows that minimizes the number of spaceship trips
    via brute force.  The brute force algorithm should follow the following method:

    1. Enumerate all possible ways that the cows can be divided into separate trips
    2. Select the allocation that minimizes the number of trips without making any trip
        that does not obey the weight limitation
            
    Does not mutate the given dictionary of cows.

    Parameters:
    cows - a dictionary of name (string), weight (int) pairs
    limit - weight limit of the spaceship (an int)
    
    Returns:
    A list of lists, with each inner list containing the names of cows
    transported on a particular trip and the overall list containing all the
    trips
    """
#    kravy = cows.copy()
#    for krava in cows:
#        if cows[krava] > limit:
#            del kravy[krava]  
    result = []
    minimum_length = len(cows) + 1
    for item in (get_partitions(cows)):
        item_valid = True
        for set_of_cows in item:
            sum_weights = 0
            for cow_name in set_of_cows:
                sum_weights += cows[cow_name]
            if sum_weights > limit:
                item_valid = False                
                break
        if len(item) < minimum_length and item_valid:
            minimum_length = len(item)
            result = item
    return result
コード例 #32
0
ファイル: ps1.py プロジェクト: 2ea581088c/studies
def brute_force_cow_transport(cows,limit=10):
    """
    Finds the allocation of cows that minimizes the number of spaceship trips
    via brute force.  The brute force algorithm should follow the following method:

    1. Enumerate all possible ways that the cows can be divided into separate trips
    2. Select the allocation that minimizes the number of trips without making any trip
        that does not obey the weight limitation
            
    Does not mutate the given dictionary of cows.

    Parameters:
    cows - a dictionary of name (string), weight (int) pairs
    limit - weight limit of the spaceship (an int)
    
    Returns:
    A list of lists, with each inner list containing the names of cows
    transported on a particular trip and the overall list containing all the
    trips
    """
    # TODO: Your code here
    cowlist = list(get_partitions(cows.keys()))
    #all combinations of cow names
    
    #merge sort here so that list is ordered from least no of trips(ie lowest len()) to highest
    
            
    def merge(l, r):
        i, j = 0, 0
        merged = []
        while i < len(l) and j < len(r):
            if len(l[i]) < len(r[j]):
                merged.append(l[i])
                i+=1
            else:
                merged.append(r[j])
                j+=1
        while (i < len(l)):
                merged.append(l[i])
                i+=1
        while (j < len(r)):
                merged.append(r[j])
                j += 1
        return merged
                
    def mergesorted(list):
        if len(list)<2:
            return list[:]
        else:
            middle = len(list)//2
            l = mergesorted(list[:middle])
            r = mergesorted(list[middle:])
            return merge(l, r)
            
        
    sorted = mergesorted(cowlist)
    
    #iterate over the list to find the first one that doesnt exceed weight limits. lookup values of cows in dict
        
    def besttrip(list):
        for trips in sorted:
            for trip in trips:
                weight = 0
                for cow in trip:
                    weight += cows[cow]
                if weight > limit:
                    break
                if trip == trips[(len(trips))-1]:
                    return trips
                    
    return besttrip(sorted)