-2
  fd = open('Class1.txt')
  lines = [line.strip() for line in fd]
  s = {}
  for line in lines:
    splitted = [i for i in line.split(',')]
    key = splitted[0]
    s[key] = [int(n) for n in splitted[1:]]
  def average():
          avg_mark = lambda name:sum(s[name])/len(s[name])
          for i in sorted(s.keys(),key=avg_mark,reverse=True):
              print (i,avg_mark(i),"\n")
          average()
          average()
  average()

Right so i've changed the code so then it just does the average but when i run it it doesn't stop can anyone help me. thanks

I need help shortening this piece of code because it is too long. I need to do this for three other classes as well and don't want it to be lines of code and was just wandering if it could be shortened.

Thanks

  • 3
    Please don't use SO to cheat on your GCSEs. You should be submitting **your own work**, not getting the internet to rewrite it. – jonrsharpe Mar 12 '15 at 14:46
  • Why would you want it shortened? – user Mar 12 '15 at 14:48
  • Repeating a request for input by recursively calling the function is bad design. See [Asking the user for input until they give a valid response](http://stackoverflow.com/q/23294658/953482) – Kevin Mar 12 '15 at 14:49
  • to make it look more professional – BeggineratPython Mar 12 '15 at 14:52
  • 1
    Since this almost certainly about your [GCSE programming problem](http://www.reddit.com/r/Python/comments/2gawvg/gcse_computing_programming_tasks_14_16_year_olds/), please do read [Open letter to students with homework problems](http://meta.programmers.stackexchange.com/q/6166). – Martijn Pieters Mar 12 '15 at 15:47

1 Answers1

0

Here is what I think you're after:

import csv

with open('Class1.txt') as fd:
    s = {row[0]:[int(n) for n in row[1:]] for row in csv.reader(fd, delimiter=',')}

def average():
    avg_mark = lambda name : sum(s[name])/len(s[name])
    for name in sorted(s, key=avg_mark, reverse=True):
        print(name, avg_mark(name))  # newline prints automatically

Of course, in reality, because of the call to average within average, you're going to run into maxrecursiondepth issues. So if you really want code to do that, you may as well just do this:

def f(): f()
inspectorG4dget
  • 110,290
  • 27
  • 149
  • 241