USACO Practice Question Python Solutions


2020 Decemver

Do you know your ABCs

list1 = input().split()
for i in range(6):
  list1[i] = int(list1[i])

for listnum in range(0, len(list1)):
  minvalue = list1[listnum]
  indexnum = listnum
  for i in range(listnum, len(list1)):
    if list1[i] < minvalue:
      minvalue = list1[i]
      indexnum = i
  list1[indexnum], list1[listnum] = list1[listnum], list1[indexnum]

largestnum = list1[5]
leastnum1 = list1[0]
leastnum2 = list1[1]
othernum = largestnum - leastnum1 - leastnum2
print(leastnum1, leastnum2, othernum)

Daisy Chains

totalflowers = input()
list1 = input()
list1 = list1.split()
totalflowers = int(totalflowers)
times = 0
for m in range(totalflowers):
  list1[m] = int(list1[m])
for i in range(totalflowers):
    h = list1[i]
    for j in range(i + 1, totalflowers + 1):
        total = sum(list1[i:j])
        average = total/len(list1[i:j])
        for k in list1[i:j]:
            if k == average:
                times = times+1
                break
print(times)

Stuck in a Rut

#Reads input
numCow = int(input())
cowList = []
for i in range(numCow):
  cowElement = input().split()
  cowElement[1] = int(cowElement[1])
  cowElement[2] = int(cowElement[2])
  cowList.append(cowElement)

#Function that calculates when cow1 would potentially be stopped by cow2
def timeStopped(cow1, cow2):
  if cow1[0] == cow2[0]:
    return False, False
  if cow1[0] == "E":
    if cow2[2] > cow1[2] or cow2[1] < cow1[1]:
      return False, False
    elif cow2[1] - cow1[1] > cow1[2] - cow2[2]:
      return cow2[1] - cow1[1], cow1[2] - cow2[2]
    else:
      return False, False
  
  if cow1[0] == "N":
    if cow2[2] < cow1[2] or cow2[1] > cow1[1]:
      return False, False
    elif cow2[2] - cow1[2] > cow1[1] - cow2[1]:
      return cow2[2] - cow1[2], cow1[1] - cow2[1]
    else:
      return False, False



#Loops through all possible cow combinations, and run function "timeStopped"
stops = [] #store all possible stops in this list
for i in range(numCow):
  for j in range(numCow):
    time, steps_required = timeStopped(cowList[i], cowList[j])
    if time:
      stops.append({'stopped_cow': i, 'stopped_time': time, "stopped_by": j, "steps_required": steps_required})
      stops = sorted(stops, key=lambda d: d['stopped_time'])

#Remove all the stops that would not actually happen
i = 0
while i < len(stops):
    current_stop = stops[i]
    j = i + 1
    while j < len(stops):
      other_stop = stops[j]
      if current_stop["stopped_cow"] == other_stop["stopped_by"]:
        stops.pop(j)
      elif current_stop["stopped_cow"] == other_stop["stopped_cow"]:
        stops.pop(j)
      else:
        j += 1
    i += 1


#Make a List for the Final output
output = []
#By Default, value set to Infinity
for i in range(50):
  output.append("Infinity")

#Set values from stops
for i in stops:
  output[i['stopped_cow']] = i['stopped_time']

#Output Final result
for i in range(numCow):
  print(output[i])