105k views
0 votes
Every day, Farmer John milks his 8 dairy cows, named Bessie, Buttercup, Belinda, Beatrice, Bella, Blue, Betsy, and Sue. The cows are rather picky, unfortunately, and require that Farmer John milks them in an order that respects N constraints (1≤N≤7). Each constraint is of the form "X must be milked beside Y", stipulating that cow X must appear in the milking order either directly after cow Y or directly before cow Y.

Please help Farmer John determine an ordering of his cows that satisfies all of these required constraints. It is guaranteed that an ordering is always possible. If several orderings work, then please output the one that is alphabetically first. That is, the first cow should have the alphabetically lowest name of all possible cows that could appear first in any valid ordering. Among all orderings starting with this same alphabetically-first cow, the second cow should be alphabetically lowest among all possible valid orderings, and so on.

User Stav
by
5.9k points

1 Answer

5 votes

Answer:

def milk_pattern():

global cows

cows = sorted(['Bessie', 'Buttercup', 'Belinda', 'Beatrice', 'Bella', 'Blue', 'Betsy', 'Sue'])

is_end = False

for _ in iter(dict, 0):

if is_end == True:

break

constraint = input("How would you order the cow, X before Y: ")

names = constraint.split(" before ")

is_end = bool(input("Do not want to add more constraint? True/Fale or any key for true: "))

if names[0] in cows and names[1] in cows:

lay_back = cows.index(names[0])

mv_fwd = cows.index(names[1])

if mv_fwd < lay_back:

count =0

for _ in range(lay_back - mv_fwd):

count += 1

hold = cows[mv_fwd]

cows[mv_fwd] = cows[mv_fwd + count]

cows[mv_fwd + count] = hold

else:

count1 = 0

for _ in range(mv_fwd - lay_back):

count1 += 1

hold = cows[mv_fwd]

cows[mv_fwd] = cows[mv_fwd - count1]

cows[mv_fwd - count1] = hold

milk_pattern()

print(cows)

Step-by-step explanation:

The python code defines a function called "milk_pattern" that defines a global list called "cows" and sorts the cow names in the list and with constraints given from the user prompts the list of milking the cows is sorted accordingly.

User Gotcha
by
5.2k points