[Tutor] Help needed with Python programming
My knowledge of coding is fairly limited and I am having a hard time writing a Python code which might be pretty simple for you :-) Here is what I am doing and I need help with: I have a python code that shows a set of shortest paths between nodes A and B. Now I have to select the least risky path among them. To do that I have to consider the risk values of each link. I know how to calculate the path's risk using its link value. For example: There is a path between node A and B wiht two links. Probability of failure for link 1 is 0.001 and for link 2 is 0.003. Here is the link with its risk values: A oo-o B 0.001 0.003 So the probability of the link being down will be: 1 - (0.999 x 0.997) = 0.996003 You can find the attached file with disaster risk values of each link. For instance; first line is : 1,3,5,0.03 -- this means, first disaster affects links 1-3 and 5-0 and its occurrence rate is 0.03. So you need to assign link (1-3)'s risk to 0.03. Then you will continue with the next disaster which is the one in the next line. Note that, if a link gets affected by 2 disasters, you will add the probability of those 2 disasters to find that link's risk. If anyone can help me code the first line, I will be able to do the rest. You need use array list and some functions like file reader and delimiter I guess. Thanks in advance. 1,3,5,0.03 2,3,5,5,4,0.11 3,3,5,5,4,5,8,0.04 2,5,8,7,8,0.04 3,14,10,14,13,17,13,0.04 1,14,18,0.06 4,10,13,14,13,17,13,12,13,0.04 4,11,6,11,9,11,12,11,19,0.08 3,19,20,15,20,21,20,0.24 1,21,20,0.05 3,20,21,21,16,21,22,0.27___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Beginning Python 3.4.0 Programmer:Stephen Mik: Cannot get input variable to make While Loop conditional to work
On 22/04/14 01:18, Alan Gauld wrote: input takes as an argument a prompt string and returns the value input by the user so your usage should look like: smv_grandVariable(Enter a 1 to play or 0 to exit:) Whoops, something went badly wrong in an edit there. It should read: smv_grandVariable = input(Enter a 1 to play or 0 to exit:) apologies for that. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.flickr.com/photos/alangauldphotos ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Help needed with Python programming
On 22/04/14 02:16, Suhana Vidyarthi wrote: I have a python code that shows a set of shortest paths between nodes A and B. It would help if you showed us this code. Otherwise we are just making wild guesses about how you are modelling this. Also knowing which Python version you are using would be good. If anyone can help me code the first line, I will be able to do the rest. You need use array list and some functions like file reader and delimiter I guess. Have you written these functions already? Are they part of some module or library you are using? Or is it the writing of these functions you want help with? Graph or network analysis is a fairly standard math problem. There are probably algorithms (or even solutions) in other languages (or even in Python if you are lucky) that you can convert if you do a search. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.flickr.com/photos/alangauldphotos ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Help needed with Python programming
On Mon, Apr 21, 2014 at 06:16:20PM -0700, Suhana Vidyarthi wrote: [...] I have a python code that shows a set of shortest paths between nodes A and B. Now I have to select the least risky path among them. To do that I have to consider the risk values of each link. I know how to calculate the path's risk using its link value. For example: There is a path between node A and B wiht two links. Probability of failure for link 1 is 0.001 and for link 2 is 0.003. Here is the link with its risk values: A oo-o B 0.001 0.003 So the probability of the link being down will be: 1 - (0.999 x 0.997) = 0.996003 I don't think that calculation is correct. I think you mean that the probability of the link being UP is (0.999 x 0.997) = 0.996003, and the prob of it being DOWN is 1-0.996003 = 0.003997. So that path has a risk of 0.003997. You can find the attached file with disaster risk values of each link. For instance; first line is : 1,3,5,0.03 -- this means, first disaster affects links 1-3 and 5-0 and its occurrence rate is 0.03. So you need to assign link (1-3)'s risk to 0.03. Then you will continue with the next disaster which is the one in the next line. Note that, if a link gets affected by 2 disasters, you will add the probability of those 2 disasters to find that link's risk. If anyone can help me code the first line, I will be able to do the rest. You need use array list and some functions like file reader and delimiter I guess. Okay, let's start with reading the file. filename = path/to/file.txt Notice that I use forward slashes. Even if you are on Windows, you should code your paths with forward slashes. Either that, or you have to double every backslash: # on Windows either of these will be okay filename = C:/path/to/file.txt filename = C:\\path\\to\\file.txt Now let's read the file, one line at a time: filename = path/to/file.txt fp = open(filename, r) for line in fp: # process that single line ... How might we process the line? I'm not sure what your requirements are, but at a guess you'll want something like this: - ignore leading and trailing whitespace, including the end of line marker at the end of each line; - skip blank lines; - split non-blank lines into four fields; - convert the first three into integers; - and the last field into a float. filename = path/to/file.txt fp = open(filename, r) for line in fp: # process that single line line = line.strip() # ignore leading and trailing whitespace if not line: continue # skip blank lines a, b, c, d = line.split(,) # Split on commas a = int(a) # convert to an int instead of string b, c = int(b), int(c) d = float(d) # And now you can handle the values a, b, c, d ... And finally, when you are done, close the file: fp.close() Does this help? -- Steven ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
[Tutor] inheritance and super() function in python
Good day, I have programmed a base class for an environment I have with no problem, but when it comes to referencing the base class's constructor in the derived class's constructor I have been getting errors: *TypeError: Error when calling the metaclass bases* *module.__init__() takes at most 2 arguments (3 given)* Here's how my base class' constructor looks like (position = [x, y, z]): *class Obstacle:* *def __init__(self,position):* *self.position = position* Here's how my derived class's constructor looks like *class Cylinder(Obstacle):* * def __init__(self,position, height, radius):* * super(Obstacle,self).__init__(position)* I have no idea where the 3 given arguments are being taken from. I have modified the code on the super line just in case I missed something but that has not changed a thing. I have read that in Python you may be able to double reference, but there are no other classes interfacing the base and derived class. If anyone has had some prior experience with this I'd appreciate your input. Regards, Jorge ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] inheritance and super() function in python
On Tue, Apr 22, 2014 at 09:48:51AM -0400, Jorge Leon wrote: Good day, I have programmed a base class for an environment I have with no problem, but when it comes to referencing the base class's constructor in the derived class's constructor I have been getting errors: What version of Python are you using? With super, that is actually critical. *TypeError: Error when calling the metaclass bases* *module.__init__() takes at most 2 arguments (3 given)* Read the error message. Why is it refering to *module*.__init__? My guess is that you have a module called Obstacle, and a class called Obstacle, and you have mixed them up. Maybe you are doing this: # file Obstacle.py class Obstacle: # code goes here # Another file import Obstacle class Cylinder(Obstacle) I can reproduce your error that way: py import math py class X(math): ... pass ... Traceback (most recent call last): File stdin, line 1, in module TypeError: module.__init__() takes at most 2 arguments (3 given) You need to say class Cylinder(Obstacle.Obstacle) Better still, use the naming convention that modules are in lowercase, and classes in CamelCase: import obstacle class Cylinder(obstacle.Obstacle): ... Even better still, Python is not Java. There is no need to put every class in its own file. Here's how my base class' constructor looks like (position = [x, y, z]): *class Obstacle:* *def __init__(self,position):* *self.position = position* In Python 2, that is a classic class, or old-style class, and super will not work correctly. You need to inherit from object: class Obstacle(object) In Python 3, there is no difference and it should be fine. -- Steven ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
[Tutor] subprocess not returning
This works when I have a class for ldd and nothing else, but when I run it like this: https://gist.github.com/ag4ve/11171201 I don't get any of the libraries and I can't figure out where it's failing. ['fattr', [['/testroot', 0, 0, 777], ['/bin/dash']]] HERE1 [/testroot] HERE2 [/bin/dash] ['ldd', ['/lib/x86_64-linux-gnu/libc.so.6', '/lib64/ld-linux-x86-64.so.2']] HERE2 [/lib/x86_64-linux-gnu/libc.so.6] ['ldd', ['/lib64/ld-linux-x86-64.so.2']] HERE2 [/lib64/ld-linux-x86-64.so.2] ['ldd', ['statically']] HERE1 [statically] HERE2 [/lib64/ld-linux-x86-64.so.2] ['ldd', ['statically']] HERE1 [statically] [ 'filelist', [['/testroot', 0, 0, 777], ['/bin/dash', 0, 0, '755'], [[[]], [ Obviously it's returning something - but no usable info. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Groups of mutually exclusive options
On 2014-04-21 19:35, Steven D'Aprano wrote: Does docopt solve the Original Poster's question? If not, that advice is not terribly helpful. I don't pretend to fully understand the Original Poster's requirement but I believe mutual exclusivity is supported. Here's a short excerpt. Example uses brackets [ ], parens ( ), pipes | and ellipsis ... to describe optional, required, mutually exclusive, and repeating elements. By the way, I think you mean Single Point Of Truth, not Light. http://www.faqs.org/docs/artu/ch04s02.html SPOT, also known as DRY (Don't Repeat Yourself), is an excellent principle to follow, but in my experience it is often too difficult to follow religiously. Thanks for the correction. I too have found it difficult but have always considered it a failure on my part when I'm forced to put it aside. The point I was making is that docopt makes it much easier. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Help needed with Python programming
On 22/04/2014 12:41, Steven D'Aprano wrote: On Mon, Apr 21, 2014 at 06:16:20PM -0700, Suhana Vidyarthi wrote: [...] # on Windows either of these will be okay filename = C:/path/to/file.txt filename = C:\\path\\to\\file.txt Or a raw string r'C:\path\to\file.txt' -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence --- This email is free from viruses and malware because avast! Antivirus protection is active. http://www.avast.com ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] subprocess not returning
On 22/04/14 10:14, shawn wilson wrote: This works when I have a class for ldd and nothing else, but when I run it like this: https://gist.github.com/ag4ve/11171201 I don't get any of the libraries and I can't figure out where it's failing. ['fattr', [['/testroot', 0, 0, 777], ['/bin/dash']]] HERE1 [/testroot] HERE2 [/bin/dash] ['ldd', ['/lib/x86_64-linux-gnu/libc.so.6', '/lib64/ld-linux-x86-64.so.2']] HERE2 [/lib/x86_64-linux-gnu/libc.so.6] ['ldd', ['/lib64/ld-linux-x86-64.so.2']] HERE2 [/lib64/ld-linux-x86-64.so.2] ['ldd', ['statically']] HERE1 [statically] HERE2 [/lib64/ld-linux-x86-64.so.2] ['ldd', ['statically']] HERE1 [statically] [ 'filelist', [['/testroot', 0, 0, 777], ['/bin/dash', 0, 0, '755'], [[[]], [ Obviously it's returning something - but no usable info. We have no clue what you are doing. You say this works but we can't see what 'this' is. Is the code on the pastebin link the working or the broken version? It's also a very long listing. Can you produce a shorter example, perhaps with hard coded values that exhibits the problem? HTH -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.flickr.com/photos/alangauldphotos ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Help needed with Python programming
Unfortunately, we can't give too much specific help on your particular problem because it's homework. You should use the knowledge you learned in your introductory programming class about designing programs. In particular, give a name to the function or functions your are designing. Be rigorous in the terms you are using when you talk about the problem. Formalize what the types of inputs and outputs are. Probably most importantly, express test cases that will demonstrate what you want the output to be. And not hand-wavy things, but actual test cases that you can execute. What's the expected result of parsing the first line? That is, you're saying that the string: 1,3,5,0.03 has some kind of meaning that can be parsed. Can you express this meaning as a data structure? Can you give that data structure a name? Can you write a unit test that can test that your parser is behaving properly? ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] inheritance and super() function in python
Jorge Leon jorge.a.leo...@gmail.com Wrote in message: I think Steven has nailed your main problem, but I have two other suggestions: Use text mail, not html. This is a text list, and it can make a difference in half a dozen ways. Any decent email program has a way to select that. When showing an error, include the whole traceback. Steven would not have had to guess if you had. The file names would show him/us for sure. -- DaveA ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] subprocess not returning
On Tue, Apr 22, 2014 at 3:10 PM, Alan Gauld alan.ga...@btinternet.com wrote: We have no clue what you are doing. You say this works but we can't see what 'this' is. Is the code on the pastebin link the working or the broken version? Per what is expected output (which I forgot to provide - sorry about that). Should be something like this: [ ['/testroot', '0', '0', '777'], ['/bin/dash', 0, 0, '755'], ['/lib/x86_64-linux-gnu/libc.so.6', '0', '0', '777'], ['/lib64/ld-linux-x86-64.so.2', '0', '0', '777'], ['/lib/x86_64-linux-gnu/libc-2.17.so', '0', '0', '755'], ['/lib/x86_64-linux-gnu/ld-2.17.so', '0', '0', '755'] ] Ie, find libraries a program is linked against (just try ldd against any file because I'm not caring about optimizing at this point) and then find the permissions of them and follow symlinks and do the same. Though, what I'm asking specifically is why __ldd isn't returning any values in my module. The best I can simplify to show the part working that should also be working in the gist code is: import subprocess import sys import pprint pp = pprint.PrettyPrinter(indent=4) class T: def ldd(filename): libs = [] for x in filename: p = subprocess.Popen([ldd, x], universal_newlines=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) for line in p.stdout: s = line.split() pp.pprint(s) if = in s: if len(s) == 3: # virtual library continue else: libs.append(s[2]) else: if len(s) == 2: libs.append(s[0]) return libs if __name__ == __main__: t = T fattr = [ '/bin/dash' ] pp.pprint([OUT, t.ldd(fattr)]) Past this, I can see that the ldd method is being called in my actual code but nothing is being returned from it like it is here. It's also a very long listing. Can you produce a shorter example, perhaps with hard coded values that exhibits the problem? I really did try to simplify t.py (where all of the data is included in the script). I guess the reason for my question is because I'm not sure what's not working or what to try next? ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
[Tutor] loop couldn't work well and file couldn't close
I'm a newbie to Python. I want to make python useful to my work, to write a script for get some data out. But there are some setbacks. I really needs your help. Please, help me. ---the first one-- for x in range(1,a): tem=open('results\\temp'+str(x)) tem.seek(0) i_line=tem.readline() while i_line: i_list=i_line.split('\t') if float(i_list[1])float(b[x]): o=open('results\\'+str(x),'a') o.write(i_line) o.close else: tem02=open('results\\temp'+str(x+1),'a') tem02.write(i_line) tem02.close i_line=tem.readline() tem.close for x in range(a,a+1): close('results\\temp'+str(x)) os.rename('results\\temp'+str(x),'results\\'+str(x)) ## for the last line, the code couldn't work. I run the script in Windows XP, i don't know if there is something to do with the OS. for another question:--- for x in range (a,a+1): m=open(01) m_line=m.readline() b=open('02','w') while m_line: b.write(m_line) m_line=m.readline() b.close m.close ## for this one, file 02 and 01are not the same. to tell the truth, the last line of 01 has not been written into file 02. What's wrong? I hope you guys can help me. Thank you all very much. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
[Tutor] methods of sorting
I'm practicing with lists. I was looking for documentation on sorting with cmp() because it isn't immediately clear to me how comparing items two at a time can sort the entire list. Identify max or min values, yes, but not sort the whole list. So, the Sorting HOW TO (Dalke, Hettinger) posted on python.org goes into detail on using a key parameter for sorted() and .sort(), and using operator module functions. How obsolete are the cmp() and the decorate-sort-undecorate methods? To be understood but probably not used in new code? Python Programming, Zelle; Python 2.7.3, PowerShell, Notepad ++ I tried several means of sorting for exercises, eg # sortgpa3.py # extended to let user print report out by name,GPA or credit hours from gpa import Student, makeStudent def readStudents(filename): infile = open(filename, 'r') students = [] for line in infile: students.append(makeStudent(line)) infile.close() return students def writeStudents(students, filename): outfile = open(filename, 'w') for s in students: outfile.write(%0.2f\t%s\t%0.2f\t%0.2f\n % (s.gpa(),s.getName(), s.getHours(), s.getQPoints())) outfile.close() def cmpGPA(s1, s2): #function compares two students based on GPA return cmp(s1.gpa(), s2.gpa()) def cmpHours(s1, s2): #function compares two students based on credits return cmp(s1.getHours(), s2.getHours()) def cmpNames(s1, s2): #function compares two students' names return cmp(s1.getName(), s2.getName()) def main(): print This program sorts student grade information by GPA. order = raw_input(Do you want results printed by name, credits or GPA? ) filename = raw_input(Enter the name of the data file: ) data = readStudents(filename) if order[0] == ('c' or 'C'): data.sort(cmpHours) elif order[0] == ('g' or G): data.sort(cmpGPA) else: data.sort(cmpNames) filename = raw_input(Enter a name for the output file: ) writeStudents(data, filename) print The data has been written to file %s. % (filename) main() or, def main(): print This program sorts students based on user request. filename = raw_input(Enter name of the file containing student data: ) data = readStudents(filename) order = raw_input(Choose the field on which to sort students (name, GPA or credits): ) #print order[0] if order[0] == ('n' or N): tuples = [(student.getName(), student) for student in data] tuples.sort() data = [(tuples[i][1]) for i in range(len(tuples))] #data.sort() elif order[0] == ('c' or C): tuples = [(student.getHours(), student) for student in data] tuples.sort() data = [(tuples[i][1]) for i in range(len(tuples))] elif order[0] == ('g' or G): tuples = [(student.gpa(), student) for student in data] tuples.sort() data = [(tuples[i][1]) for i in range(len(tuples))] filename = raw_input(Enter a name for the output file: ) writeStudents(data, filename) print The data has been written to %s . % (filename) if __name__=='__main__': main() or, def main(): print This program sorts students based on user request. filename = raw_input(Enter name of the file containing student data: ) data = readStudents(filename) order = raw_input(Choose the field on which to sort students (name, GPA or credits): ) print order[0] if order[0] == ('g' or G): data = sorted(data, key=lambda student: student.gpa()) elif order[0] == ('c' or C): data = sorted(data, key=lambda student: student.getHours()) elif order[0] == ('n' or N): data = sorted(data, key=lambda student: student.getName()) filename = raw_input(Enter a name for the output file: ) writeStudents(data, filename) print The data has been written to %s . % (filename) if __name__=='__main__': main()___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] methods of sorting
On Tue, Apr 22, 2014 at 4:18 PM, Patti Scott pscott...@yahoo.com.dmarc.invalid wrote: I'm practicing with lists. I was looking for documentation on sorting with cmp() because it isn't immediately clear to me how comparing items two at a time can sort the entire list. As you note, comparison itself doesn't sort a list. Comparing elements by itself is a query, not an action. But what it does is give Python enough tools to do the sort for you. Python uses a comparison based sorting routine which works by taking in a user-defined notion of when two elements are in order or not. http://en.wikipedia.org/wiki/Comparison_sort As a handwavy explanation of the idea: imagine a list that hasn't been sorted. Python can use the comparison function you give it to repeatedly compare elements in the list. Whenever if it sees disorder, it can swap elements and thereby reduce the disorder in the list. Assuming the comparison is a good one, then we can eventually sort the whole list by repeating this over and over. Note that Python will be calling the comparison function on your behalf: you won't be calling it directly yourself. (By good, we mean a total ordering in the sense described in: http://en.wikipedia.org/wiki/Total_order) This is a handwavy explanation because Python does these comparisons and swapping in a fairly sophisticated way to avoid a lot of work. See: http://en.wikipedia.org/wiki/Timsort It maybe that you have not seen instances of functions that take functions as arguments. If so, consider two functions f and g: # def f(x): return x * x def g(x): return 2 * x # Toy functions, of course. Now they themselves don't do much but compute the square and the double of a number. But they can be passed as arguments to other functions to do something. For example, if we have some list of numbers: # numbers = [3, 1, 4, 1, 5, 9, 2, 6] # then we may apply f and g pointwise across those functions, using the map() function: # print(map(f, numbers)) print(map(g, numbers)) # and you'll see that we can compute bulk operations on lists. Again, we're leaving the map() function to call 'f' and 'g' for us. This is an example of a function that can take in other functions. The sorting routine you're looking at is conceptually doing a similar thing by taking in a comparison function, which it will use during its own work. Passing functions as values allows for a notion of variable that's really powerful: what is varying isn't just some static piece of plain data, but rather a behavior. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] loop couldn't work well and file couldn't close
On 22/04/14 17:13, baidusandy wrote: I'm a newbie to Python. I want to make python useful to my work, to write a script for get some data out. But there are some setbacks. I really needs your help. Please, help me. Its too late for me to study your code properly but here are a few immediate observations... ---the first one-- for x in range(1,a): tem=open('results\\temp'+str(x)) tem.seek(0) You shouldn'yt need to seek(0) immediately after opening to read since the file cursor will already be at the beginning. i_line=tem.readline() while i_line: i_list=i_line.split('\t') if float(i_list[1])float(b[x]): o=open('results\\'+str(x),'a') o.write(i_line) o.close else: tem02=open('results\\temp'+str(x+1),'a') tem02.write(i_line) tem02.close i_line=tem.readline() This looks like it could be done more elegantly using a for loop over the file; for i_line in tem: ... tem.close And if you use with you don;t need a close: with open(...) as tem: for i_line in tem: ... for x in range(a,a+1): close('results\\temp'+str(x)) You can't close a file by passing its filename in. You can only close it by calling close on the open file object - which you have already done for your files in the earlier loops. (Or if you use 'with' is done automatically) os.rename('results\\temp'+str(x),'results\\'+str(x)) ## for the last line, the code couldn't work. I run the script in Windows XP, i don't know if there is something to do with the OS. Wjhat do you mean by 'wouldnt work'? Do you get an error? If the file not changed? Is it lost? We need more detail. for another question:--- for x in range (a,a+1): m=open(01) I assume the lack of quotes is a typo? Its better to paste real code rather than retype it. m_line=m.readline() b=open('02','w') while m_line: b.write(m_line) m_line=m.readline() Again this would be better as a for loop for m_line in m: ... But better still would be to just copy the file using the shutil.copy() function. b.close m.close ## for this one, file 02 and 01are not the same. to tell the truth, the last line of 01 has not been written into file 02. What's wrong? Sorry, not sure, it looks OK from that point of view. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.flickr.com/photos/alangauldphotos ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] inheritance and super() function in python
Thank you Steve and Dave for the prompt response and advise, and sorry about the format. The version of Python I'm working under is 2.7.5. About the .super(): I'm going to try out the format you gave me for the files, and yes: that's exactly how I had it. Something that has stuck from all the C++ programming I'm doing, which also leads me to believe that it may be better for me to step away from using .super() if I don't get the program to work as intended when I apply your advise. Going to consult more tutorials from the page about inheritance and operator and function overloading. Regards, Jorge On Tue, Apr 22, 2014 at 3:54 PM, Dave Angel da...@davea.name wrote: Jorge Leon jorge.a.leo...@gmail.com Wrote in message: I think Steven has nailed your main problem, but I have two other suggestions: Use text mail, not html. This is a text list, and it can make a difference in half a dozen ways. Any decent email program has a way to select that. When showing an error, include the whole traceback. Steven would not have had to guess if you had. The file names would show him/us for sure. -- DaveA ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] inheritance and super() function in python
On Tue, Apr 22, 2014 at 08:59:59PM -0400, Jorge Leon wrote: Thank you Steve and Dave for the prompt response and advise, and sorry about the format. The version of Python I'm working under is 2.7.5. About the .super(): I'm going to try out the format you gave me for the files, and yes: that's exactly how I had it. Something that has stuck from all the C++ programming I'm doing, which also leads me to believe that it may be better for me to step away from using .super() if I don't get the program to work as intended when I apply your advise. Using super() is fine. (Note that super is a function, not a method -- there is no dot at the front.) You just have to remember to inherit from object (or some other built-in type). You might like to read this to understand why there is a difference between inheriting from object and not: http://import-that.dreamwidth.org/3098.html -- Steven ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] methods of sorting
Hi Patti, My answers below, interleaved between your questions. On Tue, Apr 22, 2014 at 04:18:38PM -0700, Patti Scott wrote: I'm practicing with lists. I was looking for documentation on sorting with cmp() because it isn't immediately clear to me how comparing items two at a time can sort the entire list. Identify max or min values, yes, but not sort the whole list. So, the Sorting HOW TO (Dalke, Hettinger) posted on python.org goes into detail on using a key parameter for sorted() and .sort(), and using operator module functions. Think about how you might sort four items 42, 23, 57, 30. There are many different ways to sort, and this is one of the least efficient, but easiest to understand. We start by putting the unsorted items on the left, and the sorted items on the right, as if we were sorting a handful of playing cards: [42, 23, 57, 30] [] Take the first item from the left, and find where it belongs on the right. Since the right is currently empty, that's easy: [23, 57, 30] [42] Now take the next item from the left, and find where it belongs on the right. How do you do that? By comparing it to each item already there. If it compares less than the item, insert it just before the item; otherwise keep going. In this case, we compare 23 42, which returns True, so we insert 23 to the left of 42. [57, 30] [23, 42] Now repeat with the next item. In this case, 57 23 returns False, so we continue. 57 42 also returns False, and there are no more numbers to check so we put 57 at the end: [30] [23, 42, 57] Finally we compare 30 23, which returns False, then 30 42, which returns True, so we insert 30 just to the left of 42: [] [23, 30, 42, 57] Now that we know how to sort using less than as the comparison function, we can use some other comparison function that works similarly. Instead of using we can use the built-in function cmp(a, b), which returns -1 if a b, 0 if a == b, and +1 if a b. Or instead of using the built-in cmp function, we can use any function that takes two arguments, the items to be compared, and returns one of -1, 0 or 1. Even though the Python list.sort() method is a lot faster and more clever than what I show above, it too allows you to provide a custom comparison function to decide which comes earlier or later when sorting. Here's an example with and without a comparison function: py sorted(['dog', 'aardvark', 'chicken', 'horse']) ['aardvark', 'chicken', 'dog', 'horse'] py sorted(['dog', 'aardvark', 'chicken', 'horse'], ... lambda a, b: cmp(len(a), len(b))) ['dog', 'horse', 'chicken', 'aardvark'] In the second case, we sort by the length of the words, not the content of the word. So dog (three letters) compares less than aardvark (eight letters). A couple of other notes: - Rather than define a comparison function using def, I use lambda as a shortcut. lambda creates a function, but limited only to a single expression. So lambda a, b: cmp(len(a), len(b)) is equivalent to: def function(a, b): return cmp(len(a), len(b)) - Notice that I use the built-in cmp function inside my comparison function. That's just for convenience, you don't have to do that. How obsolete are the cmp() and the decorate-sort-undecorate methods? To be understood but probably not used in new code? Both are very obsolute, but for different reasons. The problem with using a comparison function is that it is very inefficient and it can really slow down sorting of large lists by a lot. It is better to use the DSU idiom rather than call a comparison function. In fact, that is so much better, that recent versions of Python make the DSU idiom built-in: that's what the key argument to the sort() and sorted() functions is for. When you supply a key function to sort, it internally uses the DSU idiom. You almost never need to use it yourself. Using the key function is so much better than using a comparison function that in Python 3 the comparison function was dropped altogether and using key is the only way to customize sorting. Python Programming, Zelle; Python 2.7.3, PowerShell, Notepad ++ I tried several means of sorting for exercises, eg [lots of code shown] I'm sorry, did you have a question about the sorting code or were you just sharing it with us? If you're asking which should be preferred, I would prefer the version using the key=... argument to sort. -- Steven ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] loop couldn't work well and file couldn't close
baidusandy baidusa...@126.com Wrote in message: [invisible message not copied here] By posting in html, you managed to pick black on black text. I literally could see none of your message except the boilerplate. Please tell your email program to use text mode. -- DaveA ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] inheritance and super() function in python
Jorge Leon jorge.a.leo...@gmail.com Wrote in message: Thank you Steve and Dave for the prompt response and advise, and sorry about the format. The version of Python I'm working under is 2.7.5. About the .super(): I'm going to try out the format you gave me for the files, and yes: that's exactly how I had it. Something that has stuck from all the C++ programming I'm doing, which also leads me to believe that it may be better for me to step away from using .super() if I don't get the program to work as intended when I apply your advise. Going to consult more tutorials from the page about inheritance and operator and function overloading. Please don't top-post. Put your comments after the part you're quoting, and delete anything you're not responding to, which would certainly be anything following your message. There's another flaw in your call to super. You had : class Cylinder(Obstacle): def __init__(self,position, height, radius): super(Obstacle,self).__init__(position) But it looks to me like the last line should be super(Cylinder, self).__init__(position) -- DaveA ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor