# reads in a list of numbers, sorts them in increasing order # ECS 10, May 29, 2009 # Matt Bishop # read in a list of comma-separated numbers from the input # parameters: none # returns: 2 values # 1st: the list, if read successfully; empty list, if not # 2nd: True, if list read successfully; False, if not def getlist(): # read the input # catch any problems and bail out at once try: inp = input("Enter a comma-separated sequence of numbers: ") except (EOFError, TypeError, NameError, SyntaxError): return [], False # now check each element is a number # we actually build the list here lst = [] for i in inp: # number check: if adding 0 causes a TypeError, # it's not a number and we skip it (with a # suitable error message) try: i += 0 except TypeError: print i, "is not a number -- ignoring it" else: # it's a number -- add it to the list lst.append(i) # return results return lst, True # do a selection sort over the list # parameters: lst, the list of numbers to sort # returns: nothing def selsort(lst): # go through the list # each (outer) loop puts the smallest number # at the head of the list beginning with the # given index n = len(lst) for i in range(n-1): # assume smallest is already at head of list mp = i # look for a smaller number in the rest of the list for j in range(i+1, n): # if it's smaller, remember where it is if lst[mp] > lst[j]: mp = j # now swap the smallest to the head lst[i], lst[mp] = lst[mp], lst[i] # this puts it all together def main(): # get the list lst, okay = getlist() # if the list is good, sort and print it if okay: selsort(lst) print lst main()