[Tutor] Binary to Decimal conversion
I am having some difficulties in producing the correct code for a simple binary to decimal conversion program. The arithmetic I want to use is the doubling method - so if I wanted to get the decimal equivalent of 1001, I would start with multiplying 0 * 2 and adding the left most digit. I would then take the sum of 1 and multiply it by 2 and add the next digit to that product and so on and so forth until I come to an end sum of 9. I seem to come up with something like this: binnum = raw_input("Please enter a binary number: ") for i in range(0, len(binum), 1): item = "0" if i < len(binum) - 1: item = binum[i + 1] binsum = binsum * int(item) * 2 + binsum + int(binum[i]) print "\nThe binary number ", binum, " you entered converts to", binsum, " in decimal." I can't really figure out what is going wrong here. Please help me - this has been driving me insane. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Binary to Decimal conversion
Thanks for clearing that up. I knew it was much simpler than I was trying to make it I just couldn't quite see the logic that I needed for the problem clearly. Thanks for the elegant code. On Mon, Mar 9, 2009 at 10:53 PM, Moos Heintzen wrote: > You're making it more complicated than it needs to. > Also, you first used binnum then binum, and you didn't define binsum. > > It could easily be done like this: > > binnum = raw_input("Please enter a binary number: ") > decnum = 0 > rank = 1 > > for i in reversed(binnum): >decnum += rank * int(i) >rank *= 2 > > Moos > ___ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Binary Real to Decimal
myinput = raw_input("Please enter a binary real number: ") myinput = myinput.split(".") binstr1 = myinput[0] binstr2 = myinput[1] decnum1 = 0 decnum2 = 0 for i in binstr1: decnum1 = decnum1 * 2 + int(i) for k in binstr2: decnum2 = decnum2 * 2 + int(k) print "\nThe binary real number ", binstr1, ".", binstr2, " converts to ", decnum1,".",decnum2," in decimal." that is what I have so far but I need to create a condition where I need only 10 sufficient numbers from the variable decnum2. I know I need something like if len(decnum2) > 11: decnum2 = decnum2[0:11] but I keep getting unsubscriptable errors. I know it has to do with types but it's late and I just need some help. thank you in advance. - chris ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Binary Real to Decimal
yeah that function would help but how would I join both sides again to get a decimal real(float) to round? for example myfloat = decnum1, ".", decnum2 doesn't work because the string "." isn't a valid int type. how would I join those to be a float again? On Sun, Mar 29, 2009 at 10:46 PM, John Fouhy wrote: > 2009/3/30 Chris Castillo : > > that is what I have so far but I need to create a condition where I need > > only 10 sufficient numbers from the variable decnum2. I know I need > > something like > > if len(decnum2) > 11: > > decnum2 = decnum2[0:11] > > Perhaps the round() function will help? > > >>> round(12345, -2) > 12300.0 > > -- > John. > ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] base n fractional
I need some help converting the fractional (right side of the decimal) to base 10. I have this but it doesn't work mynum = raw_input("Please enter a number: ") myint, myfrac = mynum.split(".") base = raw_input("Please enter the base you would like to convert to: ") base = int(base) mydecfrac = 0 fraclen = len(myfrac) - 1 for digit in range(len(myfrac) -1, -1, -1): mydecfrac = mydecfrac + int(myfrac[digit]) mydecfrac = mydecfrac / base ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] base n fractional
well i want to use a for loop to work from the right most digit to the left most digit at a negative 1 increment. For each digit i want to divide it by 1/base and add the next digit. Then I need to take that sum and multiply it by 1/b to get the decimal equivalent so when I say that to myself i see: number = 234 mysum = 0 for digit in range(len(number) -1, -1, -1): mysum = (mysum) * (1/base) + int(number[digit]) On Sun, Apr 5, 2009 at 6:25 PM, Alan Gauld wrote: > > "Chris Castillo" wrote > > I need some help converting the fractional (right side of the decimal) to >> base 10. >> I have this but it doesn't work >> > > Frankly, based on your algorithm, I'm not sure what exactly you want > to do but taking the above statement as a starting point > > I'd convert the fractional part into an integer then divide by 10**(len(n)) > > Something like: > > n = raw_input('') # say n ->1.234 > d,f = n.split('.') # so d -> '1', f -> '234' > result = int(f)/(10**len(f)) # result = 234/10**3 = 234/1000 = > 0.234 > > Or you could just add a dot back on and convert to float: > > f = float('.'+f)# float('.234') -> 0.234 > > for digit in range(len(myfrac) -1, -1, -1): >> mydecfrac = mydecfrac + int(myfrac[digit]) >> mydecfrac = mydecfrac / base >> > > This just confused me. > I think this might do what you are trying to do: > > for digit in reversed(list('234')): >mydecfrac = (mydecfrac + int(digit)) / base > > But that doesn't seem to do what I think you wanted? > > > -- > Alan G > Author of the Learn to Program web site > http://www.alan-g.me.uk/l2p/ > > ___ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] base n fractional
yes that was what I was looking for. And the reason I am using the loop is the teacher I am currently taking wants us to fully comprehend iteration for the material we are covering in the class. Thank you for your help though, I definitely see where I was going wrong with it. On Mon, Apr 6, 2009 at 7:53 AM, Dave Angel wrote: > Chris Castillo wrote: > > Message: 1 >> Date: Sun, 5 Apr 2009 15:36:09 -0500 >> From: Chris Castillo >> Subject: [Tutor] base n fractional >> To: tutor@python.org >> Message-ID: >><50e459210904051336v60dfc6ddt280d3c9c8f6e0...@mail.gmail.com> >> Content-Type: text/plain; charset="iso-8859-1" >> >> I need some help converting the fractional (right side of the decimal) to >> base 10. >> I have this but it doesn't work >> >> mynum = raw_input("Please enter a number: ") >> myint, myfrac = mynum.split(".") >> base = raw_input("Please enter the base you would like to convert to: ") >> base = int(base) >> mydecfrac = 0 >> fraclen = len(myfrac) - 1 >> >> for digit in range(len(myfrac) -1, -1, -1): >>mydecfrac = mydecfrac + int(myfrac[digit]) >>mydecfrac = mydecfrac / base >> -- next part -- >> An HTML attachment was scrubbed... >> URL: < >> http://mail.python.org/pipermail/tutor/attachments/20090405/612ca99f/attachment-0001.htm >> > >> >> > First we need a clear statement (with examples) of your goal. Your prompts > to the user indicate you want to convert from decimal to some other base. > But your comments here and elsewhere on the thread indicate the exact > opposite. The two problems are related, but mixing them will just confuse > everybody. > > so when I say that to myself i see: >> number = 234 >> mysum = 0 >> for digit in range(len(number) -1, -1, -1): >> mysum = (mysum) * (1/base) + int(number[digit]) >> > > This just isn't valid python. You can't subscript an integer. You > probably need a string here. That is what raw_input() would produce. > > So let's get a specific example, and try to work with it. > > > Perhaps you want > base = 5 > myfrac = "234" > > and you want to figure the value that .234 would mean if it's interpreted > as base 5. First, let's do it by hand. > The two is in the first digit to the right of the decimal place, and > therefore represents 2/5 > The three is in the next place, and represents 3/25 > And the four is in the next place and represents 4/125 > Result is 0.552 decimal > > There are two ways to work a base conversion. One is to do the arithmetic > in the source base, and do successive multiplies of the destination base. > That would mean working in base 5 in this case, which is probably more work > in Python. The other is to work in the result base, and do the multiplies > of the source base. That's the approach you were taking, and it works great > if the precision of a float is acceptable. > > > Your code is fine, although a bit convoluted. Only problem is that you're > working in integers, when you need float. So just change mydecfrac to 0.0 > and it'll work. > > > ___ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Reading from files problem
I am trying to open a text file and read multiple lines containing the following: 745777686,Alam,Gaus,CIS,15,30,25,15,5,31,15,48,70,97 888209279,Anderson,Judy,Math Ed,14,30,30,13,11,30,16,18,58,72 I want to ask the user for the student number, check to see if that number is even valid and display something like: last name, first name, student number, major time info was accessed(i know i need to import time module) exam scores homework scores average score for the class #Open and read text file gradesfile = open("grades.dat", "rfor lines in gradesfile: lines = lines.split(",") identifier = lines[0] lastname = lines[1] firstname = lines[2] major = lines[3] hw1 = lines[4] hw2 = lines[5] hw3 = lines[6] hw4 = lines[7] hw5 = lines[8] hw6 = lines[9] hw7 = lines[10] test1 = lines[11] test2 = lines[12] test3 = lines[13] totalpoints = 550 hwgrades = float(hw1) + float(hw2) + float(hw3) + float(hw4) + float(hw5) + float(hw6) + float(hw7) testgrades = float(test1) + float(test2) + float(test3) studentpoints = float(hwgrades) + float(testgrades) avgrades = round(float(studentpoints / totalpoints) * 100.0, 2) print identifier gradesfile.close() That's what I have so far but I have a feeling I shouldn't use a for loop. I would really like any help trying to figure out this program. Thanks in advance. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Reading from files problem
so how would I check to see if the student number entered by the user matches one of the student numbers in the file and then display that students info? On 4/19/09, R. Alan Monroe wrote: > >> gradesfile = open("grades.dat", "r >> for lines in gradesfile: >> [snip] >> That's what I have so far but I have a feeling I shouldn't use a for >> loop. > > Actually a for loop seems like the right tool for this job, assuming > you really _do_ want to process every line in the file. > > Alan > > ___ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Reading from files problem
this worked for me fine. #Author - Chris Castillo #Created 4/19/09 #Program 6 import time #Open and read text file with student information gradesfile = open("grades.dat", "r") time_acc = time.asctime() #Ask user for student ID to lookup student information sought_id = raw_input("Please enter a student identifier to look up grades: ") #Assign values for each students' info in list for line in gradesfile: lines = line.split(",") student_id = lines[0] last_name = lines[1] first_name = lines[2] major = lines[3] hw1 = lines[4] hw2 = lines[5] hw3 = lines[6] hw4 = lines[7] hw5 = lines[8] hw6 = lines[9] hw7 = lines[10] test1 = lines[11] test2 = lines[12] test3 = lines[13] #Arithmetic operations for all students' grades total_points = 550 hw_grades = float(hw1) + float(hw2) + float(hw3) + float(hw4) + float(hw5) + float(hw6) + float(hw7) test_grades = float(test1) + float(test2) + float(test3) student_points = float(hw_grades) + float(test_grades) avg_grade = round(float(student_points / total_points) * 100.0, 2) #Assign grades to letter values if avg_grade < 60: letter_grade="F" elif avg_grade < 70: letter_grade="D" elif avg_grade < 80: letter_grade="C" elif avg_grade < 90: letter_grade="B" elif avg_grade < 101: letter_grade="A" else: print avg_grade, "is not valid" #variable for output to request.dat text file req_output = student_id + ", " + last_name + ", " + first_name + ", " + time_acc #Check to see if student id number is in the list of student id numbers if lines[0] == sought_id: new_file = open("requests.dat", "w+") new_file.write(req_output) print "\n", last_name + ", "+ first_name + ", " + student_id + ", " + major print "\n", time_acc print "\nExams - ", test1 + ", " + test2 + ", " + test3 print "Homework - ", hw1, ", ",hw2, ", ", hw3, ", ", hw4, ",", hw5, ", ", hw6, ", ", hw7 print "\nTotal points earned - ", student_points print "\nGrade: ", avg_grade, "that is a ", letter_grade gradesfile.close() hope this helps someone. I know it's probably not the most efficient way to handle this kind of problem but It works nonetheless. On Mon, Apr 20, 2009 at 8:24 AM, Alan Gauld wrote: > > "Scott SA" wrote > > May have been a bad assumption on my part as I envisioned pickling a >> dict. and that just got too complicated. >> > > A pickled dict? > That would be a shelve mebbe? > > > PS. My email is acting up, did my prev. message actually make it to the >> list? >> > > Yes, I saw it just after sending mine... > > Alan G > > > ___ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] reading complex data types from text file
I'm having some trouble reading multiple data types from a single text file. say I had a file with names and numbers: bob 100 sue 250 jim 300 I have a few problems. I know how to convert the lines into an integer but I don't know how to iterate through all the lines and just get the integers and store them or iterate through the lines and just get the names and store them. please help. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] reading complex data types from text file
*so far I have this and the format is what i want:* -- # Set all necessary variables name = None fileOut = open('outputFile.txt', 'w') total = 0 averageScore = 0 numofScores = 0 score = 0 # Header for output file fileOut.write("Bowling Report\n" + ("-" * 40) + "\n") # Iterate line by line through file to get names and their corresponding scores for line in open('bowlingscores.txt', 'r'): line = line.strip() if line: if line.isdigit(): score = int(line) numofScores += 1 total += score averageScore = total / numofScores # Get average score # Decides where bowler stands compared to the average score if score < averageScore: score = "\tBelow average" elif score > averageScore and score != 300: score = "\tAbove average!" elif score == 300: score = "\tPerfect score!" else: name = line # Checks to see if name and score have values if name and score: fileOut.write('%s\t%s\r\n' % (name, score)) name, score = None, None fileOut.close() *the problem is that it's not comparing the first bowler's score to the average score and the output file looks like this: * Bowling Report David120 HectorPerfect score! MaryBelow average * is the logic in my if-elif statements wrong or is it just skipping the first bowler's score? * On Thu, Jul 16, 2009 at 8:26 AM, Glen Zangirolami wrote: > All lines that come back from a text file come back as strings. You can use > string methods to detect the data like so: > f = open('test.txt') > lines = f.readlines() > numbers = [] > strings = [] > > for line in lines: > if line.strip().isdigit(): > numbers.append(int(line)) > else: > strings.append(line.strip()) > > print numbers > print strings > > > > On Wed, Jul 15, 2009 at 1:55 PM, Chris Castillo wrote: > >> I'm having some trouble reading multiple data types from a single text >> file. >> >> say I had a file with names and numbers: >> >> bob >> 100 >> sue >> 250 >> jim >> 300 >> >> I have a few problems. I know how to convert the lines into an integer but >> I don't know how to iterate through all the lines and just get the integers >> and store them or iterate through the lines and just get the names and store >> them. >> >> please help. >> >> ___ >> Tutor maillist - Tutor@python.org >> http://mail.python.org/mailman/listinfo/tutor >> >> > ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] reading complex data types from text file
so could I also replace the score of each bowler (key value) in the dictionary with a new key such as "below average" or "above average" according to each if-elif-else structure and then write to a text file in the following format? Jim Above Average SueBelow Average BobPerfect score On Fri, Jul 17, 2009 at 12:48 PM, bob gailer wrote: > Chris Castillo wrote: > >> how would i go about adding the names to a dictionary as a key and the >> scores as a value in this code? >> >> >> # refactored for better use of Python, correct logic, and flow > > scores = {} # empty dictionary > total = 0 > for line in open("bowlingscores.txt", "r"): > if line.strip().isdigit(): > score = int(line) > scores[name] = score > total += score > else: > name = line.strip() > averageScore = total / len(scores) > fileOut = open("bowlingaverages.txt", "w") > fileOut.write("Bowling Report\n" + ("-" * 50) + "\n") > for name, score in scores.items(): > if score == 300: > score = "\tPerfect score!" > elif score < averageScore: > score = "\tBelow average" > elif score > averageScore: > score = "\tAbove average!" > else: > score = "\tAverage!" > print name, score > > > -- > Bob Gailer > Chapel Hill NC > 919-636-4239 > ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] reading complex data types from text file
okay so I figured my program out. I am posting the final version so if someone else is having problems with something like this it may benefit the community. (comments are included to help those who might not understand the code) ''' Program reads names of bowlers and their corresponding scores, then writes their names to a new text file with a description of either below average, average, above average or a perfect score ''' scores = {}# empty dictionary total = 0#initalize total to 0 value for line in open("bowlingscores.txt", "r"):# iterate through txt file with names and scores if line.strip().isdigit(): score = int(line)# convert score into int type scores[name] = score# add scores to dictionary total += score# add score to running total else: name = line.strip()# if the line isn't a digit name will be the key in the dictionary averageScore = total / len(scores)# get average of all scores fileOut = open("bowlingaverages.txt", "w")# create a file to write names and scores to fileOut.write("Bowling Report\n" + ("-" * 50) + "\n")# header for name, score in scores.items():#iterate through each score in the dictionary to get an score value for each player if score == 300: score = "\tPerfect score!\n" scores[name] = score elif score < averageScore: score = "\tBelow average\n" scores[name] = score elif score > averageScore: score = "\tAbove average!\n" scores[name] = score else: score = "\tAverage!\n" scores[name] = score for items in scores.items():#iterate through the items in the dictionary and format them to the output file fileOut.write("%s%s\n" % items) --- your output for this code should look like this inside the text file: *Bowling Report -- sueBelow average billAbove average! natBelow average tomPerfect score!* Thanks to everyone who helped me with this. On Sun, Jul 19, 2009 at 12:15 AM, Chris Castillo wrote: > so could I also replace the score of each bowler (key value) in the > dictionary with a new key such as "below average" or "above average" > according to each if-elif-else structure and then write to a text file in > the following format? > > Jim Above Average > SueBelow Average > BobPerfect score > > > On Fri, Jul 17, 2009 at 12:48 PM, bob gailer wrote: > >> Chris Castillo wrote: >> >>> how would i go about adding the names to a dictionary as a key and the >>> scores as a value in this code? >>> >>> >>> # refactored for better use of Python, correct logic, and flow >> >> scores = {} # empty dictionary >> total = 0 >> for line in open("bowlingscores.txt", "r"): >> if line.strip().isdigit(): >> score = int(line) >> scores[name] = score >> total += score >> else: >> name = line.strip() >> averageScore = total / len(scores) >> fileOut = open("bowlingaverages.txt", "w") >> fileOut.write("Bowling Report\n" + ("-" * 50) + "\n") >> for name, score in scores.items(): >> if score == 300: >> score = "\tPerfect score!" >> elif score < averageScore: >> score = "\tBelow average" >> elif score > averageScore: >> score = "\tAbove average!" >> else: >> score = "\tAverage!" >> print name, score >> >> >> -- >> Bob Gailer >> Chapel Hill NC >> 919-636-4239 >> > > ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] File I/O help
*I'm supposed to be reading in names a grades from a text file like so: * Chris 100 89 76 0 Dave 56 45 30 23 10 0 Sara 55 76 78 60 0 *the 0 indicates that's the end of the student's grades and not an actual 0 number grade for the student. This is what my code looks like so far:* from myFunctions import * grades = [] names = [] gradeTotal = 0 numStudents = 0 inputFile = open("input.txt", "r" )# Read in a file with student names a grades for line in open("input.txt", "r"):# iterate through txt file with names and grades if line.strip().isdigit(): grade = float(line)# convert score into float type gradeTotal += grade# adds score to running total if grade != 0: grade = grades.append(grade) else: name = line.strip() name = names.append(name)# Append name to names list studentTotal = str(len(names))# Get student total grades.sort() # Sort the grades in ascending order --- *and then I need to output something that looks like this:* Name of student 76,89,100 - and then their letter grade average(A, B, C, etc..) Name of student 76,89,100 - and then their letter grade average(A, B, C, etc..) *How do I do this with the code I have so far ( if possible )* ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Reading Data From File
Okay I really need help with the program I am writing. I've can't seem to figure out what I need to do and have tried several different methods. I need to read in a text file in python that contains the following: Student Name ( could be unknown amount in file ) Numeric Grade ( could be unknown amount in file also ) Numeric Grade Numeric Grade 0 (zero value to terminate and move on to next student and their grades) I need to print the following to the screen: Student NameNumeric Grade, Numeric Grade, Numeric grade, etc.. - ( then A, B C, D, or F average ) PLEASE HELP ME. I need to put the grades into a list and process each student's grades before processing the next student's grades so that I can print each Name, their grades, and average on the same line ( like above ). Thanks ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Reading Data From File
ya i was kind of in a hurry composing the email earlier. sorry for the typos and misunderstanding. This is what I actually have. grades = [] names = [] gradeTotal = 0 numStudents = 0 inputFile = open("input.txt", "r") for line in inputFile: if line.strip().isdigit(): grade = float(line) if grade != 0.0: gradeTotal += grade grade = grades.append(grade) else: name = line.strip() name = names.append(name) So even If I take the stuff out that you said, My structure still wouldn't be right because I'm processing everything all at once with no way to reference any of the grades with the student. How do I structure this differently to do that? That's what I'm having trouble with. On 7/25/09, Dave Angel wrote: > ctc...@gmail.com wrote: >> grades = [] >> names = [] >> gradeTotal = 0 >> numStudents = 0 >> >> inputFile = open("input.txt", "r" >> >> for line in inputFile: >> if line.strip().isdigit(): >> grade = float(line) >> if grade != 0.0: >> gradeTotal += grade >> grade = grades.append(grade) >> else: >> name = line.strip() >> name = names.append(name) >> >> This just loops over the entire file basically and just continually >> adds the grades to the grades list and names to the names list. How do >> I just process each student's set of grades before moving on to the >> next one (since there is a zero terminating value telling the loop >> that a new student and his or her grades are about to follow) >> >> By the way I'm not worrying about determining the letter grade average >> right now, i'm importing a module I wrote after I figure this part out. >> >> On Jul 25, 2009 8:34am, bob gailer wrote: >>> I concur with wesley and dave re homework. >> >> > There are syntax errors of at least two kinds here. The first is you're > missing a trailing parenthesis. And the second is you lost all your > indentation when you retyped the code. It'd really be better if you > pasted the actual code instead. Not much of a problem in this case, at > least if I guess the same as you had, but in many cases the indentation > *is* the problem. > > Next problem is that you're assuming that list.append() returns > something useful. It doesn't return anything, which is to say it returns > "None." So it's not useful to do: > grade = grades.append(grade) > > just leave off the left half of that. And likewise leave off the name= > from the other call to append(). > > The next problem is that you have two independent lists, but no way to > correlate which elements of one correspond to which elements of the > other. So you have a choice to make. Do you need all the data for > post-processing, or is it enough that you print it out, and discard it > afterwards? > > I'll assume that you'd answer that it's enough to just be able to print > it out. In that case, you just need some well placed print statements. > Each time you come to a line with a zero in it, you have enough > information to print out one student's information. And in this case, > you don't need a list of students, just the name of the current one. > > Do you expect any numbers to be non-integers? I'd assume so because you > used the float() function instead of int(). But isdigit() is going to > be a problem if there's a decimal in there. > > DaveA > > ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Reading Data From File
On 7/26/09, Dave Angel wrote: > Chris Castillo wrote: >> ya i was kind of in a hurry composing the email earlier. sorry for the >> typos and misunderstanding. This is what I actually have. >> >> grades = [] >> names = [] >> gradeTotal = 0 >> numStudents = 0 >> >> inputFile = open("input.txt", "r") >> >> for line in inputFile: >> if line.strip().isdigit(): >> grade = float(line) >> if grade != 0.0: >> gradeTotal += grade >> grade = grades.append(grade) >> else: >> name = line.strip() >> name = names.append(name) >> >> >> So even If I take the stuff out that you said, My structure still >> wouldn't be right because I'm processing everything all at once with >> no way to reference any of the grades with the student. How do I >> structure this differently to do that? That's what I'm having trouble >> with. >> >> On 7/25/09, Dave Angel wrote: >> >>> ctc...@gmail.com wrote: >>> >>>> grades = [] >>>> names = [] >>>> gradeTotal = 0 >>>> numStudents = 0 >>>> >>>> inputFile = open("input.txt", "r" >>>> >>>> for line in inputFile: >>>> if line.strip().isdigit(): >>>> grade = float(line) >>>> if grade != 0.0: >>>> gradeTotal += grade >>>> grade = grades.append(grade) >>>> else: >>>> name = line.strip() >>>> name = names.append(name) >>>> >>>> This just loops over the entire file basically and just continually >>>> adds the grades to the grades list and names to the names list. How do >>>> I just process each student's set of grades before moving on to the >>>> next one (since there is a zero terminating value telling the loop >>>> that a new student and his or her grades are about to follow) >>>> >>>> By the way I'm not worrying about determining the letter grade average >>>> right now, i'm importing a module I wrote after I figure this part out. >>>> >>>> On Jul 25, 2009 8:34am, bob gailer wrote: >>>> >>>>> I concur with wesley and dave re homework. >>>>> >>>> >>>> >>>> >>> There are syntax errors of at least two kinds here. The first is you're >>> missing a trailing parenthesis. And the second is you lost all your >>> indentation when you retyped the code. It'd really be better if you >>> pasted the actual code instead. Not much of a problem in this case, at >>> least if I guess the same as you had, but in many cases the indentation >>> *is* the problem. >>> >>> Next problem is that you're assuming that list.append() returns >>> something useful. It doesn't return anything, which is to say it returns >>> "None." So it's not useful to do: >>> grade = grades.append(grade) >>> >>> just leave off the left half of that. And likewise leave off the name= >>> from the other call to append(). >>> >>> The next problem is that you have two independent lists, but no way to >>> correlate which elements of one correspond to which elements of the >>> other. So you have a choice to make. Do you need all the data for >>> post-processing, or is it enough that you print it out, and discard it >>> afterwards? >>> >>> I'll assume that you'd answer that it's enough to just be able to print >>> it out. In that case, you just need some well placed print statements. >>> Each time you come to a line with a zero in it, you have enough >>> information to print out one student's information. And in this case, >>> you don't need a list of students, just the name of the current one. >>> >>> Do you expect any numbers to be non-integers? I'd assume so because you >>> used the float() function instead of int(). But isdigit() is going to >>> be a problem if there's a decimal in there. >>> >>> DaveA >>> >>> >>> > (In a mailing list like this one, putting a response at the top of your > message is called top-posting, and makes it harder for the next person > to see the sequence of messages.) > > As I said before: > *So you have a choice to make. Do you need all the data for > post-proces
[Tutor] Eng to Leet Speek
so I have a string: 1 4|-| 50 |_33+. I love [#ick3n 4nd ch3353. Don't you love +|_|2|\e7 \/\/1+# the |#a|-|i|_7? and I am trying to turn it into english with the following code: fileIn = open("encrypted.txt", "r").read() def eng2leet(astring): astring = astring.replace("4","a") astring = astring.replace("8","b") astring = astring.replace("[","c") astring = astring.replace("|)","d") astring = astring.replace("3","e") astring = astring.replace("|#","f") astring = astring.replace("6","g") astring = astring.replace("#","h") astring = astring.replace("1","i") astring = astring.replace("]","j") astring = astring.replace("|\\","k") astring = astring.replace("|_","l") astring = astring.replace("|-|","m") astring = astring.replace("|\\","n") astring = astring.replace("0","o") astring = astring.replace("|*","p") astring = astring.replace("0\\","q") astring = astring.replace("2","r") astring = astring.replace("5","s") astring = astring.replace("+","t") astring = astring.replace("|_|","u") astring = astring.replace("\/","v") astring = astring.replace("\/\/","w") astring = astring.replace("><","x") astring = astring.replace("7","y") astring = astring.replace("7_","z") return astring print eng2leet(fileIn) Only problem is that when it needs to translate a U or a W it prints an L or 2 V's. Need some help please. Thanks ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Eng to Leet Speek
On Mon, Jul 27, 2009 at 1:38 PM, J Sisson wrote: > You need a deterministic algorithm for conversion. It's impossible > (without analyzing the context of the word) to translate "|_|#" (it's either > "lf" or "uh", but which?). > > > > > On Mon, Jul 27, 2009 at 1:13 PM, Chris Castillo wrote: > >> so I have a string: >> >> 1 4|-| 50 |_33+. I love [#ick3n 4nd ch3353. Don't you love +|_|2|\e7 >> \/\/1+# the |#a|-|i|_7? >> >> >> and I am trying to turn it into english with the following code: >> >> fileIn = open("encrypted.txt", "r").read() >> >> def eng2leet(astring): >> astring = astring.replace("4","a") >> astring = astring.replace("8","b") >> astring = astring.replace("[","c") >> astring = astring.replace("|)","d") >> astring = astring.replace("3","e") >> astring = astring.replace("|#","f") >> astring = astring.replace("6","g") >> astring = astring.replace("#","h") >> astring = astring.replace("1","i") >> astring = astring.replace("]","j") >> astring = astring.replace("|\\","k") >> astring = astring.replace("|_","l") >> astring = astring.replace("|-|","m") >> astring = astring.replace("|\\","n") >> astring = astring.replace("0","o") >> astring = astring.replace("|*","p") >> astring = astring.replace("0\\","q") >> astring = astring.replace("2","r") >> astring = astring.replace("5","s") >> astring = astring.replace("+","t") >> astring = astring.replace("|_|","u") >> astring = astring.replace("\/","v") >> astring = astring.replace("\/\/","w") >> astring = astring.replace("><","x") >> astring = astring.replace("7","y") >> astring = astring.replace("7_","z") >> return astring >> >> print eng2leet(fileIn) >> >> Only problem is that when it needs to translate a U or a W it prints an L >> or 2 V's. Need some help please. Thanks >> >> ___ >> Tutor maillist - Tutor@python.org >> http://mail.python.org/mailman/listinfo/tutor >> >> > > > -- > Computers are like air conditioners... > They quit working when you open Windows. so is their some other way to go about this? ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Eng to Leet Speek
On Mon, Jul 27, 2009 at 2:08 PM, Dave Angel wrote: > Chris Castillo wrote: > >> so I have a string: >> >> 1 4|-| 50 |_33+. I love [#ick3n 4nd ch3353. Don't you love +|_|2|\e7 >> \/\/1+# the |#a|-|i|_7? >> >> >> and I am trying to turn it into english with the following code: >> >> fileIn = open("encrypted.txt", "r").read() >> >> def eng2leet(astring): >>astring = astring.replace("4","a") >>astring = astring.replace("8","b") >>astring = astring.replace("[","c") >>astring = astring.replace("|)","d") >>astring = astring.replace("3","e") >>astring = astring.replace("|#","f") >>astring = astring.replace("6","g") >>astring = astring.replace("#","h") >>astring = astring.replace("1","i") >>astring = astring.replace("]","j") >>astring = astring.replace("|\\","k") >>astring = astring.replace("|_","l") >>astring = astring.replace("|-|","m") >>astring = astring.replace("|\\","n") >>astring = astring.replace("0","o") >>astring = astring.replace("|*","p") >>astring = astring.replace("0\\","q") >>astring = astring.replace("2","r") >>astring = astring.replace("5","s") >>astring = astring.replace("+","t") >>astring = astring.replace("|_|","u") >>astring = astring.replace("\/","v") >>astring = astring.replace("\/\/","w") >>astring = astring.replace("><","x") >>astring = astring.replace("7","y") >>astring = astring.replace("7_","z") >>return astring >> >> print eng2leet(fileIn) >> >> Only problem is that when it needs to translate a U or a W it prints an L >> or >> 2 V's. Need some help please. Thanks >> >> >> > Your problem is in the order of substitution. If you put the "v" test > *after* the "w" test, you'll avoid one of your problems. And put the "l" > test after the "u" test. And you didn't mention it, but "z" should come > before "y". This is because some of your strings are substrings of others. > A more general rule might be to put all the four-character substitutions > first, then do all the three-character ones, then two, then one. That's not > guaranteed to work, but by inspection I think it will. > > Another problem that could have hit you is that "\" is an escape character > in strings. So you're taking advantage of the fact that \/ (for example) > doesn't happen to be a valid escape sequence. The usual workaround is to > use raw strings. For another example, look at the string for "n". Did you > want two backslashes? You'll only get one as it sits. > > Did you mean for "k" and "n" to be the same? > > DaveA > > Yes that solved it and caught all exceptions (after changing the typo I had for the n) I really did not think about changing the order like that. I feel stupid for not thinking of that. Thank you for your insight. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] (no subject)
# Module demonstrates use of lists and set theory principles def Unite(set1, set2): # evaluate 2 lists, join both into 1 new list newList = [] for item in set1: newList.append(item) for item in set2: newList.append(item) newList.sort() return newList def Intersect(set1, set2): # evaluate 2 lists, check for commonalities, output commonalities to 1 new list newList = [] for item in set1: if item in set1 and item in set2: newList.append(item) newList.sort() return newList def Negate(set1, set2): # evaluate 2 lists, return negation of 1st list newList = [] for item in set1: if item in set2: set1.remove(item) newList = set1 return newList could this be done in a more elegant fashion? ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor