Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Greedy Cow Transport
#1
A colony of Aucks (super-intelligent alien bioengineers) has landed on Earth and has created new species of farm animals! The Aucks are performing their experiments on Earth, and plan on transporting the mutant animals back to their home planet of Aurock. In this problem set, you will implement algorithms to figure out how the aliens should shuttle their experimental animals back across space.
The aliens have succeeded in breeding cows that jump over the moon! Now they want to take home their mutant cows. The aliens want to take all chosen cows back, but their spaceship has a weight limit and they want to minimize the number of trips they have to take across the universe. Somehow, the aliens have developed breeding technology to make cows with only integer weights.


def load_cows(filename):
    cow_dict = dict()
    f = open(filename, 'r')
    for line in f:
        line_data = line.split(',')
        cow_dict[line_data[0]] = int(line_data[1])
    return cow_dict

def greedy_cow_transport(cows,limit=10):
    lista = []
    totalWeight = 0
    scows = sorted(cows)
    while totalWeight <= limit:
        for key, value in enumerate(scows):
            totalWeight += value
            lista.append(cow)
        return lista 

cows = load_cows("ps1_cow_data.txt")
limit=100
print(cows)

print(greedy_cow_transport(cows, limit))
print(brute_force_cow_transport(cows, limit))
error:
Error:
Traceback (most recent call last): File "C:\Python36\kodovi\6.00.2x\ps1.py", line 79, in <module> cows = load_cows("ps1_cow_data.txt") File "C:\Python36\kodovi\6.00.2x\ps1.py", line 16, in load_cows cow_dict[line_data[0]] = int(line_data[1]) ValueError: invalid literal for int() with base 10: '7Betsy'
this is how ps1_cow_data.txt looks like:
Maggie,3
Herman,7Betsy,9
Oreo,6
Moo Moo,3
Milkshake,2
Millie,5
Lola,2Florence,2Henrietta,9

I don't understand this error message.
I assume that function argument limit=10 refers to the weight that spaceship can take in one flight and 100 is how much weight they want at all.
Reply
#2
The load_cows() function assumes that there is exactly one cow per line, but this is obviously not the case in your file. You need to modify load_cows() to handle several cows on each line.
Reply
#3
Or you need to fix your data file. It really looks like there are missing line endings in the file. If the file intended to have more than one cow per line, I would expect a comma or other delimiter between the weight of the previous cow and the name of the next cow.
Craig "Ichabod" O'Brien - xenomind.com
I wish you happiness.
Recommended Tutorials: BBCode, functions, classes, text adventures
Reply
#4
(Apr-08-2019, 10:13 PM)Truman Wrote:
line_data = line.split(',')
cow_dict[line_data[0]] = int(line_data[1])
this is how ps1_cow_data.txt looks like:
..
Herman,7Betsy,9
..

I don't understand this error message.
ValueError: invalid literal for int() with base 10: '7Betsy'

You split on comma and then try to convert element with index 1 to int. Quite obviously you can't convert 7Betsy to int. There should be comma: 7, Betsy
I'm not 'in'-sane. Indeed, I am so far 'out' of sane that you appear a tiny blip on the distant coast of sanity. Bucky Katt, Get Fuzzy

Da Bishop: There's a dead bishop on the landing. I don't know who keeps bringing them in here. ....but society is to blame.
Reply
#5
this is why i raise goats.

maybe the Auckmobile is too small.

do you have a definition of your data file format?
Tradition is peer pressure from dead people

What do you call someone who speaks three languages? Trilingual. Two languages? Bilingual. One language? American.
Reply
#6
I changed txt file to:
Maggie,3
Herman,7
Betsy,9
Oreo,6
Moo Moo,3
Milkshake,2
Millie,5
Lola,2
Florence,2
Henrietta,9

then I got error on line 15 regarding int vs str problem. So I changed it to:
totalWeight += int(value)
and then I got this linter error:
Error:
{'Maggie': 3, 'Herman': 7, 'Betsy': 9, 'Oreo': 6, 'Moo Moo': 3, 'Milkshake': 2, 'Millie': 5, 'Lola': 2, 'Florence': 2, 'Henrietta': 9} Traceback (most recent call last): File "C:\Python36\kodovi\6.00.2x\ps1.py", line 83, in <module> print(greedy_cow_transport(cows, limit)) File "C:\Python36\kodovi\6.00.2x\ps1.py", line 25, in greedy_cow_transport totalWeight += int(value) ValueError: invalid literal for int() with base 10: 'Betsy'
Not sure why Betsy since it's a first element in this new order.

Skaperen, not sure what you mean by your question. I was given this txt file in the on-line course to download it and write a code based on it.
Reply
#7
Often data files will come with a specification of the data in them: what the columns are, what exactly they mean, what is the range of possible values. That would have clarified whether you needed to account for multiple cows per line, or whether the data file was missing new lines.
Craig "Ichabod" O'Brien - xenomind.com
I wish you happiness.
Recommended Tutorials: BBCode, functions, classes, text adventures
Reply
#8
No, I don't have such a thing.
Reply
#9
Function 'greedy_cow_transport' parameter 'cows' is dictionary. On row #12 you use sorted on this dictionary. Result is not dictionary anymore - it's a list of keys ("Return a new sorted list from the items in iterable.").

>>> d = {'Maggie': 3, 'Herman': 7, 'Betsy': 9, 'Oreo': 6, 'Moo Moo': 3, 'Milkshake': 2, 
...      'Millie': 5, 'Lola': 2, 'Florence': 2, 'Henrietta': 9}
>>> sorted(d)
['Betsy',
 'Florence',
 'Henrietta',
 'Herman',
 'Lola',
 'Maggie',
 'Milkshake',
 'Millie',
 'Moo Moo',
 'Oreo']
If you iterate over this list with for loop on row #14 and try to convert elements to int you will get error on first element ('Betsy').

I observed that on row #16 you append 'cow'. This name is not assigned, so you should get error there after you fix your current problem.
I'm not 'in'-sane. Indeed, I am so far 'out' of sane that you appear a tiny blip on the distant coast of sanity. Bucky Katt, Get Fuzzy

Da Bishop: There's a dead bishop on the landing. I don't know who keeps bringing them in here. ....but society is to blame.
Reply
#10
I tried to sort a dictionary by value with this code:
scows = sorted(cows.items(), key=lambda x: x[1])
but it makes a tuple of it which is not good. It seems that dictionaries can't be sorted by value.

There is one more question that arises. How to fill the spaceship with cows if one cow should be skipped. For example, let's say that the weight of the first cow is 7, of the second is 5 and of the third is 2. It should take the first one, skip the second because limit is 10 and take the third one which gives value 9 in total.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  How do I correct multiplication error? Greedy algorithm help student8 1 3,861 Oct-02-2017, 03:00 AM
Last Post: Mekire

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020