Newbee needs Help ref Using Function Statements not Loops(For)

Discussion in 'Python' started by jstreet10, Dec 3, 2003.

  1. jstreet10

    jstreet10 Guest

    How would i use function statements instead of loops(for) in this code? i
    have tried some, but not working.

    # this program is suppose to read fm a file, computes the average and
    reads fm a file
    # file grade info: dave, 75; david, 70; davy, 60; john, 70; jon, 60; nina,
    55; nino, 50; ray, 65; sherry, 90; terry, 85

    import os, sys, string
    student_table = {}
    grade_counter = 0
    input_file = open("grades.txt","r")
    sum = 0
    for record in input_file.readlines():
    grade_counter += 1
    record_key , record_value = string.split(record,",")
    student_table[record_key] = record_value
    sum += int (record_value)
    average = sum/grade_counter

    student_names = student_table.keys()
    output_file = open("processed.txt", "w")

    for student_name in student_names:
    output_file.write(student_name +"," + student_table
    output_file.write("Average grade is" + str(average))
    jstreet10, Dec 3, 2003
    1. Advertisements

  2. jstreet10

    Sean Ross Guest


    I'm sure someone else will ask you why you want to do it this way,
    since your code was already very clean and understandable, so I won't
    bother - I'll just show you one way that it can be done without for loops,
    and without list comprehensions (which use "for"). Someone else will
    probably show you the list comprehension version.

    # requires python 2.3+
    import string
    input_file = open("grades.txt","r")
    records = input_file.readlines()
    commasplit = lambda record: string.split(record,",")
    record_items = map(commasplit, records)
    student_table = dict(record_items)
    grade_counter = len(records)
    # sum is a builtin in python 2.3
    total = sum(map(int, student_table.values()))
    average = total/grade_counter

    student_names = student_table.keys()
    output_file = open("processed.txt", "w")
    rebuild_info = lambda student_name: \
    student_name +"," + student_table[student_name]
    student_info = map(rebuild_info, student_names)
    map(output_file.write, student_info)
    output_file.write("Average grade is " + str(average))

    Perhaps I misunderstood what you were asking for with
    "function statements". Perhaps you wanted to define some
    functions of your own? Or maybe you were looking for
    some builtin functions that did this sort of processing?
    I'm not sure.

    Anyway, HTH,

    p.s. Small note on your original code:
    in later versions of python this can be written as

    for record in input_file:
    Sean Ross, Dec 3, 2003
    1. Advertisements

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments (here). After that, you can post your question and our members will help you out.