473,804 Members | 3,163 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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

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.tx t","r")
sum = 0
for record in input_file.read lines():
grade_counter += 1
record_key , record_value = string.split(re cord,",")
student_table[record_key] = record_value
sum += int (record_value)
average = sum/grade_counter

input_file.clos e()
student_names = student_table.k eys()
student_names.s ort()
output_file = open("processed .txt", "w")

for student_name in student_names:
output_file.wri te(student_name +"," + student_table
[student_name])
output_file.wri te("Average grade is" + str(average))
output_file.clo se()


Jul 18 '05 #1
1 1374
"jstreet10" <js*******@cox. net> wrote in message
news:DLozb.4141 5$Ac3.27964@lak eread01...
How would i use function statements instead of loops(for) in this code? i
have tried some, but not working. [snip]

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.tx t","r")
records = input_file.read lines()
input_file.clos e()
commasplit = lambda record: string.split(re cord,",")
record_items = map(commasplit, records)
student_table = dict(record_ite ms)
grade_counter = len(records)
# sum is a builtin in python 2.3
total = sum(map(int, student_table.v alues()))
average = total/grade_counter

student_names = student_table.k eys()
student_names.s ort()
output_file = open("processed .txt", "w")
rebuild_info = lambda student_name: \
student_name +"," + student_table[student_name]
student_info = map(rebuild_inf o, student_names)
map(output_file .write, student_info)
output_file.wri te("Average grade is " + str(average))
output_file.clo se()
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,
Sean

p.s. Small note on your original code:
for record in input_file.read lines():


in later versions of python this can be written as

for record in input_file:

Jul 18 '05 #2

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

4
1895
by: Ken Fine | last post by:
No joy on Macromedia's boards after a few days; maybe someone can help me here. I got an excellent string handling function off of planet-source-code.com that converts text strings to proper case, i.e. "the REMAINS of the DAY" is converted to "The Remains Of The Day". This function is particularly good in that it handles certain exceptions. Can you help me make it handle more? I'm interested in two tweaks, one easy, one hard.
1
3149
by: A. Farber | last post by:
Hi, I'm trying to port a bigger program from Visual C++ to Linux and after rewriting few Visual C++ functions (strnicmp, filelength, findnext, etc.) I'm finally down to just one (!) error message and now I'm stuck :-( Does anybody please know, what could this error mean: h_utl.cpp: In function `istrstream &operator>> (istrstream &, TVersion &)':
2
7048
by: laurenq uantrell | last post by:
I have been using the following function to test the speed of various functions, however, quite often the return value is zero. I'm hoping someone can help improve on this. Function TimeIt() As Single On Error GoTo CodeErr 'PURPOSE: Times a process in seconds from start to finish 'USAGE: msgbox TimeIt Dim sngStart As Single
14
2244
by: Julia | last post by:
Hi, When writing class library do you validate ALL incoming parameters? Is this a good approach,to valid them ALL!!!,and throw exceptions? I realize that if I am not validating them,than my logged exceptions ,raised from objects or calsses which uses them,are some what more hard to dissect. Thanks in advance.
89
6090
by: Cuthbert | last post by:
After compiling the source code with gcc v.4.1.1, I got a warning message: "/tmp/ccixzSIL.o: In function 'main';ex.c: (.text+0x9a): warning: the 'gets' function is dangerous and should not be used." Could anybody tell me why gets() function is dangerous?? Thank you very much. Cuthbert
19
1638
by: dickinsm | last post by:
Here's an example of a problem that I've recently come up against for the umpteenth time. It's not difficult to solve, but my previous solutions have never seemed quite right, so I'm writing to ask whether others have encountered this problem, and if so what solutions they've come up with. Suppose you're writing a class "Rational" for rational numbers. The __init__ function of such a class has two quite different roles to play. ...
4
2083
by: GeekBoy | last post by:
I am reading a file of numbers using for loops. The numbers are in a grid as follows: 8 36 14 11 31 17 22 23 17 8 9 33 23 32 18 39 23 25 9 38 14 38 4 22 18 11 31 19 16 17 9 32 25 8 1 23
2
5153
by: beginner | last post by:
Hi Everyone, An extended module (.pyd) written in C have an init function that is called when the module is imported. Does anyone know if there is a way to provide an init function for a module written in python? Thanks, Geoffrey
3
1591
by: JanW | last post by:
Somewhat a C++ beginner, I'm trying to make a general test function that could test unary operators (or methods) of an object of any class. Arguments are a member-pointer to the function, a single input argument of some type for that function, and the expected result of some type. Then it tests if the result is as expected, and does some logging of the results (pass, fail) etc. Well, the template "mess" does not quite work out.
0
9585
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10586
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10338
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
10082
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
7622
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5525
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5658
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
3823
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2997
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.