Re: [Tutor] Help with program
Courtney Skinner wrote: Hello, I am trying to build a program that approximates the value of cosine - this is my program so far. It is not returning the right values. Could you tell me what I am doing wrong? def main(): import math print(This program approximates the cosine of x by summing) print(the terms of this series: x^0 / 0!, -x^2 / 2!,) print(x^4 / 4!, -x^6 / 6!...) n = eval(input(How many terms should be used? )) x = eval(input(What value should be used for x? )) Consider the more restrictive int() and float() instead of eval(). s = 1 A nice suggestive name like sign instead of s might help you with your debugging efforts. Of course the same goes for your other names. d = 1 e = 1 value = 0 for i in range(n - 1): value = value + s + (x**e / math.factorial(d)) With the name suggested above the error value = value + sign + (x**e / math.factorial(d)) should almost be obvious. sign plus? wait what... Add print(current exponent, e) to see another problem. s = s * 1 That shows signs of a missing sign ;) e = e + 2 d + d + 2 print(Approximation for cos(x) calculated by this program: ) print(value) print() difference = math.cos(x) - value print(Difference between this value and math.cos(x): ) print(difference) main() Thank you! C.Skinner ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Help with program
On 16/02/2015 16:27, Courtney Skinner wrote: Hello, I am trying to build a program that approximates the value of cosine - this is my program so far. It is not returning the right values. Could you tell me what I am doing wrong? def main(): import math Not that it matters but imports are usually done at the top of the module. print(This program approximates the cosine of x by summing) print(the terms of this series: x^0 / 0!, -x^2 / 2!,) print(x^4 / 4!, -x^6 / 6!...) n = eval(input(How many terms should be used? )) x = eval(input(What value should be used for x? )) *DON'T* use eval, it's potentially dangerous. n = int(input(How many terms should be used? )) x = float(input(What value should be used for x? )) s = 1 d = 1 e = 1 value = 0 for i in range(n - 1): Are you aware that this will count from zero to n - 2? value = value + s + (x**e / math.factorial(d)) s = s * 1 e = e + 2 d + d + 2 Whoops :) print(Approximation for cos(x) calculated by this program: ) print(value) print() difference = math.cos(x) - value print(Difference between this value and math.cos(x): ) print(difference) main() We'd usually write:- if __name__ == __main__: main() Thank you! C.Skinner -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Help with program
On 16/02/15 16:27, Courtney Skinner wrote: Hello, I am trying to build a program that approximates the value of cosine def main(): import math Its usual to do the imports outside the function at the tyop of the file. Python doesn't actually care much but its 'standard practice'. print(This program approximates the cosine of x by summing) print(the terms of this series: x^0 / 0!, -x^2 / 2!,) print(x^4 / 4!, -x^6 / 6!...) n = eval(input(How many terms should be used? )) x = eval(input(What value should be used for x? )) Don't use eval(). Use int() for the first one and float() for the second. eval() is a security hazard and potentially dangerous. s = 1 d = 1 e = 1 value = 0 for i in range(n - 1): value = value + s + (x**e / math.factorial(d)) Your description says you subtract every second value (eg -x**2/2!) You are adding them all. Also you are adding 1(s) every time, surely you just want to add it the first time. In other words you want value to start at 1 and the loop to iterate from 2-(n-1)? You also want a sign multiplier which toggles between +/-1 Also you can get Python to do most the work for you by specifying a third step-size argument to range: ... for e in range(2, (n*2)+1, 2): #step by 2 value += (x**e)/math.factorial(e) * sign ... You no longer need any of the other increments or variables. s = s * 1 e = e + 2 d + d + 2 print(Approximation for cos(x) calculated by this program: ) print(value) print() You probably want all of these outside the loop. You might like to add a print(value) though while you are debugging. difference = math.cos(x) - value print(Difference between this value and math.cos(x): ) print(difference) HTH -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: 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 with program
On 02/16/2015 11:27 AM, Courtney Skinner wrote: Hello, I am trying to build a program that approximates the value of cosine - this is my program so far. It is not returning the right values. Could you tell me what I am doing wrong? You've got several answers that point out several problems in your code. But I think you're missing a key concept. If you're faced with a problem that's beyond your present abilities, or that's got you stumped, always consider factoring the problem into simpler ones. To me the first thing you should factor out is a factorial function. Write one, that takes a positive int and returns the factorial, and test it against the one in the math library. Once it's correct, then use it in the cosine problem. Now you've got a simpler loop to write. And you know part of the code works. Next, see if you can avoid most of those three variables you're using. For example, What do you get when you calculate (-1) ** (i) Can you use that to simplify things? -- DaveA ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Help on Python drop-down list options
What is the user interface that your program is using, currently? IE: QT, GTK, Tkinter, Curses, Kivy, Pygame, Or None? What is the target system on which your program runs? How are you currently viewing the mean and standard deviation results? What version of Python are you using and what is your OS? On 12/31/2014 08:49 AM, Tammy Miller wrote: Hello All, I need help on the following: I have a created a project from a csv file to calculate the mean and standard deviation. However, I would like to create a drop-down list and display the mean and standard deviation? Is there a module for that? Thank you, Tammy ___ 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] Help on Python drop-down list options
On 31/12/14 13:49, Tammy Miller wrote: I need help on the following: I have a created a project from a csv file to calculate the mean and standard deviation. I assume that means you read the data from the CSV file and display the stats? However, I would like to create a drop-down list and display the mean and standard deviation? I assume you mean you want to create a GUI that has a drop down list containing data and you want to display the stats based on the list contents? If so you need to decide what kind of UI you want to use. Your choices are: 1) CLI using curses (Not on windows) 2) Web UI based on HTML/Javascript 3) Desktop GUI using Tkinter/WxPython/PyGTK (or some other toolkit) And once you decide your option you need to design what the UI looks like - how does the output appear? Is it in a label? a text widget? a pop-up dialog? Is there a module for that? Yes, for all of the above. Option 1 uses the curses module Option 2 uses standard HTML linked to a CGI(standard library) or a web framework(several third-party options) Option 3: the standard library includes Tkinter, the others are third-party downloads. We can't help much until you make the choices above. It will help if you tell us which python version and which OS you use. And once you choose an option which tookkit you want to go with (or at least which option and we can advise on toolkits based on your experience and your UI visual design) -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: 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 with tic-tac-toe program
If I understand what you're asking you need to write the current gameboard and the info you get in 'gameBoard' is the current state of the game. There are several ways of doing this (with different degrees of cleverness) but to keep it simple: Start by printing out the current state, different ways of doing this but perhaps a loop within a loop similar to your loadGameBoard code When you have got this working, add the lines by modifying the code you just wrote. An observation here is that if you print the first line then the rest is board line followed by a new line, second observation is that if you start each line with a | the repeating patterns is Z | where Z is X/O. On Sun, Nov 16, 2014 at 7:52 PM, Andrew McReynolds amcreynol...@yahoo.com.dmarc.invalid wrote: The section of the assignment that I'm working on states: 2) Write a function called loadGameBoard (player_marks) where player_marks is a dictionary that contains the players’ marks. This function creates a 3x3 array with the players’ marks populated in the correct row/column indices using the formula 3*row+column. This function returns the 3x3 array. You must use a loop at least once. 3) Write a function called printGameBoard (gameBoard) where gameBoard is a 3x3 array that contains the players’ marks. This function draws the game board and returns None. You must use a loop at least once in this function or in a function that this function calls. An example is if gameBoardArray[0][1] has ‘X’ and gameBoardArray[1][1] has ‘O’, this function should draw the game board like: | | X | | | | O | | | | | | What I have so far is: def loadGameBoard (player_marks): null= board= [[null,null,null],[null,null,null],[null,null,null]] for row in range(3): for column in range (3): position = 3*row+column if position in player_marks[X]: board[row][column]=X if position in player_marks[O]: board[row][column]=O return (board) def printGameBoard(gameBoard): board=((-*8,(| )*4))*3 #for line in board: return () Any advice for continuing? Thanks in advance for assistance, Andrew ___ 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] help with tic-tac-toe program
On Sun, Nov 16, 2014 at 1:52 PM, Andrew McReynolds amcreynol...@yahoo.com.dmarc.invalid wrote: The section of the assignment that I'm working on states: 2) Write a function called loadGameBoard (player_marks) where player_marks is a dictionary that contains the players’ marks. This function creates a 3x3 array with the players’ marks populated in the correct row/column indices using the formula 3*row+column. This function returns the 3x3 array. You must use a loop at least once. 3) Write a function called printGameBoard (gameBoard) where gameBoard is a 3x3 array that contains the players’ marks. This function draws the game board and returns None. You must use a loop at least once in this function or in a function that this function calls. An example is if gameBoardArray[0][1] has ‘X’ and gameBoardArray[1][1] has ‘O’, this function should draw the game board like: | | X | | | | O | | | | | | A few style points: 1.Normally people use all lower case for function names with underscore to separate words. 2. Use plain text to write your question. It makes it easier to understand 3. What is player_marks? Can you show what the data looks like in player_parks? 4. You might want to rename null to empty. For me that would make it easier to understand. What I have so far is: def loadGameBoard (player_marks): null= board= [[null,null,null],[null,null,null],[null,null,null]] for row in range(3): for column in range (3): position = 3*row+column if position in player_marks[X]: board[row][column]=X if position in player_marks[O]: board[row][column]=O return (board) def printGameBoard(gameBoard): board=((-*8,(| )*4))*3 #for line in board: return () Any advice for continuing? What happens when you run your code? Thanks in advance for assistance, Andrew ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor -- Joel Goldstick http://joelgoldstick.com ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Help understanding classes
Thank you Alan and Danny. It amazes me at the lengths you guys, as well as everyone else who contributes, will go to to help explain things to us; it is greatly appreciated! Alan, I decided to dumb down the learning classes just a little. By this I mean, I am not using Tkinter to learn classes. I am using one of the examples from your website, which I did change it just a little. I figured, I am having a hard time wrapping my head around classes and Tkinter would just add to the confusion. So, I have the below code. When I run this from terminal, it obviously prints This is a test. If I may, break the code down and ask questions as it pertains to the code? # class Message: def __init__(self, aString): self.text = aString def printIt(self): print self.text m = Message(This is a test) m.printIt() ## With the first part... class Message: def __init__(self, aString): self.text = aString Will I always use _init_ when defining the first function in a class? I noticed on your website, you created a class where you did not use _init_ (see below). Was this because you did not define a function? class BalanceError(Exception): value = Sorry you only have $%6.2f in your account I noticed that I can change text to anything and I still get the same results by running the code; I changed them to blah just as a test. When I define a function in a class, will I always use self as the first entry in the parenthesis? On the next part... m = Message(This is a test) m.printIt() I noticed I cannot run printIt() unless I make it an object i.e. m = Message(This is a test)...? I noticed I could change m = Message(This is a test) to m = Message(raw_input()), which works. What if I wanted to create a function in Message that receives text from another function and then prints that text instead of the text from m = Message(This is a test)...; can I pass or return values to another function inside a class? Theself is really throwing me off, when I think about creating different functions that do misc things just to practice. For example, I have a function that kills a Linux program. I just don't see how to rethink that function to where it could be defined in a class? def kill_proc(process1): i = psutil.Popen([ps, cax], stdout=PIPE) for proc in psutil.process_iter(): if proc.name(process1): proc.kill() Would it be something like...? class processKiller: def _init_(self): def kill_proc(self, process1): i = psutil.Popen([ps, cax], stdout=PIPE) for proc in psutil.process_iter(): if proc.name(process1): proc.kill() Then outside of the class, call it like so...? p = processKiller() p.proc.kill() Again, I am just practicing, trying to wrap my head around classes and understand how to create and use them. Oh yeah, Alan I preordered your new book maybe a month or so ago. Any word on when it will be released and shipped? Again, thanks. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Help understanding classes
On 15/11/14 18:19, Bo Morris wrote: With the first part… class Message: def __init__(self, aString): self.text = aString Will I always use “_init_” when defining the first function in a class? It can go anywhere in the class definition. it is just another method of the class. But because it is where the initialization of the class data happens, it is logical and conventional to have it first. But there is no rule about it. I noticed on your website, you created a class where you did not use “_init_” (see below). Was this because you did not define a function? class BalanceError(Exception): value = Sorry you only have $%6.2f in your account” Any class where you do not need to initialize any data can do without an __init__(). In this case it's just a subclass of the built in exception class - a new bespoke error type - so has no need of an init() I noticed that I can change “text” to anything and I still get the same results by running the code; I changed them to “blah” just as a test. text is just a name. Its a variable inside the class. In this case its where the message text is stored. Remember, classes are trying to model real concepts. a message has text so it has to be stored somewhere and an attribute called text is as good as anything. When I define a function in a class, will I always use “self” as the first entry in the parenthesis? Its a convention that is best observed. Pythoin doesn't actually care, you can use any name. The first parameter will allways refer to the instance calling the method. Other names sometimes seen are 'this' and 'object' but in Python self is the convention. m = Message(This is a test) m.printIt() I noticed I cannot run “printIt()” unless I make it an object i.e. “m = Message(This is a test”)…?” Because printIt() is a method of the class. You must have an instance to call a method. That's what makes it a method rather than an ordinary function. I noticed I could change m = Message(This is a test”)” to m = Message(raw_input()),” which works. Because the init expects a string. it doesn't matter how you create the string, it canbe a literal, a variable or using raw_ijnput. So long sas the result is a string it will work(Actually because of pythons flexible approach to types it can be other things too... m = Message(42) m.printit() will print 42. But thats because the print will convert it to a string for you. What if I wanted to create a function in Message that receives text from another function and then prints that text instead of the text from “m = Message(This is a test”)…; can I pass or return values to another function inside a class? Of course, methods are just functions, they can have any kind of parameter that an ordinary function can have. methods can call other methods (using the self. prefix) and methods can be called by external functions provided that function has an object of the right type to call it on. The”self” is really throwing me off, when I think about creating different functions that do misc things just to practice. methods shouldn't do miscellaneous things. Thats what modules andv functions are for(sort of). Methods should define the behaviour of an object type. Try to think of an object and what you can do with that object. Write methods that do those things. For example, I have a function that kills a Linux program. I just don’t see how to rethink that function to where it could be defined in a class? You could have a program class. It starts, it stops, it ends. It may produce output. In fact we already have a class that does this, its the Popen class in the subprocess module. You can learn a lot about OOOP by looking at the classes defined in the standard library and seeing what methods (and attributes) they define. def kill_proc(process1): i = psutil.Popen([ps, cax], stdout=PIPE) for proc in psutil.process_iter(): if proc.name(process1): proc.kill() Would it be something like…? class processKiller: class names should be nouns. Everytime you have a verb name it probably means you are just writing a function. The classic case is a xxxManager class, that's usually wrong. So you want class Process: def _init_(self): You might want a command string in the init. That would let you start the process before you can kill it. You might want to store the PID in the process object self.pid = def kill_proc(self, process1): self will be process1 so you don't need to pass it as a parameter. i = psutil.Popen([ps, cax], stdout=PIPE) You shouldn't need this if you start the process in init() since you can get the pid at that stage. for proc in psutil.process_iter(): if proc.name(process1): proc.kill() Then outside of the class, call it like so…? p = processKiller() p.proc.kill() So I'd suggest p = Process('top') p.kill() Oh yeah, Alan I
Re: [Tutor] Help understanding classes
On Sat, Nov 15, 2014 at 06:19:56PM +, Bo Morris wrote: Thank you Alan and Danny. It amazes me at the lengths you guys, as well as everyone else who contributes, will go to to help explain things to us; it is greatly appreciated! Alan, I decided to dumb down the learning classes just a little. By this I mean, I am not using Tkinter to learn classes. I am using one of the examples from your website, which I did change it just a little. I figured, I am having a hard time wrapping my head around classes and Tkinter would just add to the confusion. Good plan! Before I get to your example, let's dumb things down even more. What is the *simplest possible* class we can create? class MyClass(object): pass That's pretty simple. (Actually, we can make it even shorter by removing the word object, but that makes it more complicated because it will work differently in Python 2 and 3, so let's not do that.) What do those two lines of code do? The header class MyClass(object) tells Python to define a new class called MyClass. The body is the line pass, which is just a placeholder to tell Python that there's nothing else there. (Otherwise the compiler will complain.) MyClass inherits from object. object is a special built-in name which Python already knows about. The object class defines some extremely basic behaviour, such as knowing how to print itself, and so our MyClass inherits that behaviour. Classes on their own usually aren't very interesting. There's not a lot of work you can do with them, normally you work with *instances*. The relationship between a class and its instances is similar to that between a kind of thing and a specific example of that thing. E.g.: class: Dog instances: Lassie, Rin-Tin-Tin, Snowy, Hooch, Ol' Yella class: President of the USA instances: Barrack Obama, George Bush Jr, George Washington class: Tool subclasses: Screwdriver, Spanner, Hammer, etc. instances: this red handled screwdriver, that 3 spanner etc. Instances get their behaviour from their class; their class get their behaviour either from code you program, or code they inherit from the superclasses. MyClass is a subclass of object, so object is a superclass of MyClass. I can create an instance of MyClass, and then print it: py obj = MyClass() py print(obj) __main__.MyClass object at 0xb7b52f6c How did `obj` know what to print when I never wrote any code to handle printing MyClass instances? It inherited that code from the superclass `object`, which already knows how to convert itself into a string, which print can then use: py str(obj) '__main__.MyClass object at 0xb7b52f6c' So far, every MyClass instance is indistinguishable except by their identity, their ID number which you can see written in hex in that string display or by calling id(): py id(obj) 3082104684 py hex(id(obj)) '0xb7b52f6c' [Aside: every single object in Python has an ID. It's usually going to be a cryptic multi-digit number, but some implementations will instead use an incrementing counter so that IDs will be 1, 2, 3, 4, ... ] We can associate some data with individual instances. That makes them distinguishable, and useful. What makes the ints 17 and 23 different is their *state*, that is the internal data (whatever that is!) which distinguishes the instance with value 17 from the instance with value 23. So far, our MyClass instances don't have any state, but we can give them some. Let's create a couple of instances of MyClass: py a = MyClass() py b = MyClass() py a.colour = 'red' py a.size = 23 py b.colour = 'green' py b.size = 42 py if a.size = b.size: ... print(the %s instance is bigger % a.colour) ... else: ... print(the %s instance is bigger % b.colour) ... the green instance is bigger The colour and size attributes count as examples of per-instance state. In a nutshell, that is what classes are all about: classes control the state of the instances, and define their behaviour. So, I have the below code. When I run this from terminal, it obviously prints This is a test. If I may, break the code down and ask questions as it pertains to the code? # class Message: def __init__(self, aString): self.text = aString def printIt(self): print self.text m = Message(This is a test) m.printIt() ## With the first part... class Message: def __init__(self, aString): self.text = aString Will I always use _init_ when defining the first function in a class? I noticed on your website, you created a class where you did not use _init_ (see below). Was this because you did not define a function? Note that there are *two* underscores __init__ not one _init_. Such dunder (Double leading and trailing UNDERscore) methods normally have special meaning to Python, or are reserved for future use. __init__ is one such special method. It is the initialiser method, and Python will automatically
Re: [Tutor] Help understanding classes
On 15/11/14 00:29, Bo wrote: help understanding classes and how they work. What is the point in OOP if I don’t understand classes, are classes not the heart and soul of OOP? Actually not necessarily. There are OOP languages where classes are not included or little used. Javascript is a good example but there are others too. However, since this is a Python list, we'll ignore those and agree with you that you need to know about classes... :-) I have been trying to learn classes by practicing with Tkinter building GUIs. While OOP is usually used in creating GUIs they are not the best place to learn about classes because the GUI frameworks (Tkinter in your case) do a fair bit of magic internally that confuses things a little bit. window. I just don’t understand why it works? Let's start with that. Where would the rest of my code go That's where the GUI magic happens so the code doesn't go where you might initially think it would! Later... class test(Frame): This creates a new class called 'test' that defines a new kind of Frame object (style note: class names are usually capitalized so it should be called Test). This means that you can create instances of it (objects of type Test) using the usual Python syntax of class name followed by () so: myTestObject = Test() As a subclass of Frame it inherits a lot of functionality from the Frame class, including how to display itself on screen, resize itself and so on. A Frame is a general purpose GUI container (a bit like a visual list if you like, except it can only hold GUI widgets). As such it acts as the top level window of your application. All other widgets and sub-frames will go into the top level Frame. This is an important point. In a GUI there is a top level parent object and all other objects are children of that, They form a tree-like data structure called the containment tree. This tree is crucial to how GUIs interact with user events (and how the widgets communicate internally) and is the core of the GUI magic that I mentioned earlier. def __init__(self, parent): Frame.__init__(self, parent) self.parent = parent self.initUI() This is the first method of the class. A method is a special type of function that is defined inside a class and provides the functionality (or operations) of the class. In this case it is a special method that gets called by python when a new object of type Test is created (this is OOP magic not GUI magic, it happens for all classes). Its purpose is to initialize the data variables (or attributes) of the new instance. In your case that includes calling the Frame superclass to initialize it then setting a local parent variable (you really shouldn't need to do that! Frame does it for you) and then calling the initGUI() method of the new instance (denoted by self). def initUI(self): self.parent.title(“TestApp) self.pack(fill=BOTH, expand=1) And this is the initGUI() method which is just a helper function like any other but, because it's inside the class and has a self parameter is a custom method of your class. It's not obligatory, but is quite common, to have a separate method to initialize the GUI widgets in the window (not least because it allows you to reset the window without restarting the application). In this case it sets the Window title then packs the window into its parent. Recall the containment tree? When you create the instance you must pass a parent into init() and that call to pack() will cause Tkinter to insert your new window under the parent within the tree. In this case the parent will be the top level Window but it could be a dialog box or a sub frame of a larger window. def main(): root = Tk() root.geometry(250x150+300+300) app = test(root) root.mainloop() The main function creates a root object for your GUI using the Tk() function (remember that containment tree?). It sets the initial geometry(size and position) of the window then creates an instance of your Test class passing the root object as the parent. (The self parameter is filled in using more OOP magic by Python. It takes the value of your new object - app in this case.) So at this point your __init__() method gets called as: Test.__init__(app, root) Once everything has been initialized the mainloop() of the root widget is called which starts Tkinter looking for events to process. It will send the events to the lowest level widget it can find - your app widget in this case. But if it cannot find an event handling function/method there it will pass the event up the containment tree (this is the GUI magic bit!) until it finds something that can handle it. If the event reaches the top of the tree(root) without finding a handler then it gets thrown away(usually). Most GUI events in your app are picked up by Frame or root (move, resize, close etc) so you don;t need to provide any code yet. Now we can look at what happens when you add
Re: [Tutor] Help understanding classes
On Fri, Nov 14, 2014 at 4:29 PM, Bo crushe...@gmail.com wrote: Hello everyone, hope all is well. Was just wondering if I could get some help understanding classes and how they work. What is the point in OOP if I don’t understand classes, are classes not the heart and soul of OOP? I have been trying to learn classes by practicing with Tkinter building GUIs. Below is my code, which does work. It simply opens a window. I just don’t understand why it works? GUI programming is a special class of programming. What makes it significantly different from what you might be used to is this: you eventually pass control of your program to some third-party manager. From that point forward, you don't do anything on your own. The third-party manager calls your functions when it decides that something interesting has happened that needs your input. This takes a large mental re-adjustment, from being the head, the one in charge of control flow, to being a servant, a provider of a service! Note that I haven't said anything about OOP, because fundamentally I think GUIs are different not because they're composed of classes, but because control flow is driven by something else. For Tkinter, the third-party manager is an event loop which we treat as a black box. We enter this event loop right here in your main function: # def main(): root = Tk() # ... code cut root.mainloop() ## Once we reach root.mainloop(), it's the event loop that dictates what happens next. We take our hands off the steering wheel. To follow along these lines, let's take a look at a simple button example here: http://effbot.org/tkinterbook/button.htm Here's the code: # import Tkinter master = Tkinter.Tk() def callback(): print click! b = Tkinter.Button(master, text=OK, command=callback) b.pack() Tkinter.mainloop() # Here, we tell the GUI system: when you press this button, call our callback function. We run the mainloop(). A window appears with a button, and when we press the button, we see that our function gets called. This is strange for beginners, because we're telling the GUI system how to use our functions. But we're not the ones calling them. Also, somehow we're using functions in the future, rather than immediately by calling them. That's the big point of a line like: b = Tkinter.Button(master, text=OK, command=callback) where callback is a function. Note the lack of parens there! It's not being called yet. Instead, the function is just a value that the button knows about. The event loop will call that function later on. That's why we're saying callback instead of callback() on that line. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Help with Dice game
corylog...@yahoo.com.dmarc.invalid Wrote in message: !-- p.MsoListParagraph, li.MsoListParagraph, div.MsoListParagraph { margin-top:0in; margin-right:0in; margin-bottom:0in; margin-left:.5in; margin-bottom:.0001pt; } p.MsoNormal, li.MsoNormal, div.MsoNormal { margin:0in; margin-bottom:.0001pt; } p.MsoListParagraphCxSpFirst, li.MsoListParagraphCxSpFirst, div.MsoListParagraphCxSpFirst, p.MsoListParagraphCxSpMiddle, li.MsoListParagraphCxSpMiddle, div.MsoListParagraphCxSpMiddle, p.MsoListParagraphCxSpLast, li.MsoListParagraphCxSpLast, div.MsoListParagraphCxSpLast { margin-top:0in; margin-right:0in; margin-bottom:0in; margin-left:.5in; margin-bottom:.0001pt; line-height:115%; } -- Hello, I can not for the life of me figure out where I have gone wrong. I wrote the following code as a simulation for the table top game x-wing. It basically simulates dice rolls but the issue is the fact that every time I choose a number of dice to roll, they all hit. None of them ever miss. Thank You. import random print(X-wing dice simulator) x = int(input(How many dice will the offensive player be rolling?\n)) y = int(input(How many dice will the defensive player be rolling?\n)) hits = 0 crits = 0 dodges = 0 offense = 0 defense = 0 while offense x: odie = random.randint(1,8) if odie = 4: hits = hits + 1 offense = offense + 1 if odie == 4: This should be indented, to line up with offens= line crits = crits + 1 offense = offense + 1 else: Then this else will mean odie 4 But then instead of continue, you'll need to increment offense. continue while defense y: ddie = random.randint(1,8) if ddie = 3: dodges = dodges + 1 defense = defense + 1 else: continue Continue doesn't help, you need to increment defense. print(The offensive player lands, hits,hits and, crits,crits\n) print(The defensive player dodges, dodges, hits\n) print(The offensive player deals, int((hits + crits) - dodges), to the defensive player) You'd have done yourself a favor to do loops with range (), instead of the while loops. For example for qq in range (x): -- DaveA ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Help with Dice game
On 10/11/14 20:57, corylog...@yahoo.com.dmarc.invalid wrote: I wrote the following code as a simulation for the table top game x-wing. I don;t know it so can only give some general comments below... import random print(X-wing dice simulator) x = int(input(How many dice will the offensive player be rolling?\n)) y = int(input(How many dice will the defensive player be rolling?\n)) Might be better to use more descriptive names like 'offense_turns' and defense_turns'? hits = 0 crits = 0 dodges = 0 offense = 0 defense = 0 while offense x: odie = random.randint(1,8) Is it really an 8 sided dice? if odie = 4: hits = hits + 1 offense = offense + 1 if odie == 4: crits = crits + 1 offense = offense + 1 else: continue You don't need the else: continue, the loop does that by itself. Also by not incrementing the offense counter you effectively let the player have unlimited misses - is that really what you want? Finally, the Pythonic idiom for incrementing a counter, n, is n += 1 It saves a few keystrokes... while defense y: ddie = random.randint(1,8) if ddie = 3: dodges = dodges + 1 defense = defense + 1 else: continue Same comments as above To help you debug this it might be worth adding a few print statements inside the loop, like so: while offense x: odie = random.randint(1,8) print('odie is: ',odie) if odie = 4: hits = hits + 1 offense = offense + 1 print('hits, offense = ',hits,offense) print(The offensive player lands, hits,hits and, crits,crits\n) print(The defensive player dodges, dodges, hits\n) print(The offensive player deals, int((hits + crits) - dodges), to the defensive player) Doing all the printing after the loop finishes gives you a very limited view of what's happening inside. 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 with Dice game
I am not familiar with the game, but maybe using offense += 1 and defense += 1 to replace the corresponding continue would help? On Mon, Nov 10, 2014 at 2:57 PM, corylog...@yahoo.com.dmarc.invalid wrote: Hello, I can not for the life of me figure out where I have gone wrong. I wrote the following code as a simulation for the table top game x-wing. It basically simulates dice rolls but the issue is the fact that every time I choose a number of dice to roll, they all hit. None of them ever miss. Thank You. import random print(X-wing dice simulator) x = int(input(How many dice will the offensive player be rolling?\n)) y = int(input(How many dice will the defensive player be rolling?\n)) hits = 0 crits = 0 dodges = 0 offense = 0 defense = 0 while offense x: odie = random.randint(1,8) if odie = 4: hits = hits + 1 offense = offense + 1 if odie == 4: crits = crits + 1 offense = offense + 1 else: continue while defense y: ddie = random.randint(1,8) if ddie = 3: dodges = dodges + 1 defense = defense + 1 else: continue print(The offensive player lands, hits,hits and, crits,crits\n) print(The defensive player dodges, dodges, hits\n) print(The offensive player deals, int((hits + crits) - dodges), to the defensive player) Sent from Windows Mail ___ 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] Help with running an API
The usage of the api as documented here - https://github.com/zachwill/fred - suggests : import fred # Save your FRED API key. fred.key('my_fred_api_key') # Interact with economic data categories. fred.category() ... Cheers, Anish Tambe On 26 Oct 2014 00:23, Joel Goldstick joel.goldst...@gmail.com wrote: On Sat, Oct 25, 2014 at 12:08 PM, Mark Meanwell mmeanw...@gmail.com wrote: Hi Folks - new to python and trying to run an API. Running version 2.7.3. on Windows 7 machine. Here is the scenario for the given API (FRED API in this case): easy_install Fred from C:\ - this installs to C:\site packages then I fire up the python shell and run file created for fred api: from fredapi import Fred fred = Fred(api_key='my api key') data = fred.get_series('SP500') keep getting below error message: ImportError: cannot import name Fred thanks for any suggestions! I'm not familiar with FRED, but a quick look on stackoverflow used the lowercase name to import ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor -- Joel Goldstick http://joelgoldstick.com ___ 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] Help with running an API
On 25/10/14 17:08, Mark Meanwell wrote: Hi Folks - new to python and trying to run an API. Running version 2.7.3. on Windows 7 machine. Here is the scenario for the given API (FRED API in this case): easy_install Fred from C:\ - this installs to C:\site packages then I fire up the python shell and run file created for fred api: I'm not sure what you mean by this bit? Do you mean you run the file using python somefile.py Or do you start the interpreter to get the prompt and then somehow execute the file? (If so how do you run it?) Or are you using some kind of IDE such as IDLE? In which case how do you run the file? from fredapi import Fred fred = Fred(api_key='my api key') data = fred.get_series('SP500') keep getting below error message: ImportError: cannot import name Fred Taking it back to basics start the Python interpreter and get a prompt. Then type import fredapi Does that work without errors? Also check that your Python version is compatible with your module version. Third party APIs are often version specific. Finally, since Fred is not part of the standard library, you might be better asking on a Fred specific forum, if one exists. This list is mainly for the language and standard libraries. Anything beyond that will have less chance of a good answer. -- 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 with running an API
On Sat, Oct 25, 2014 at 12:08 PM, Mark Meanwell mmeanw...@gmail.com wrote: Hi Folks - new to python and trying to run an API. Running version 2.7.3. on Windows 7 machine. Here is the scenario for the given API (FRED API in this case): easy_install Fred from C:\ - this installs to C:\site packages then I fire up the python shell and run file created for fred api: from fredapi import Fred fred = Fred(api_key='my api key') data = fred.get_series('SP500') keep getting below error message: ImportError: cannot import name Fred thanks for any suggestions! I'm not familiar with FRED, but a quick look on stackoverflow used the lowercase name to import ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor -- Joel Goldstick http://joelgoldstick.com ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Help with guess my number game
if guess != the_number: print (you failed, the number was, the_number) elif guess==the_number: print(You guessed it! The number was, the_number) print(And it only took you, tries, tries!\n) This block of code appears to be applied for every iteration through your loop. Is that your intention? ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Help with guess my number game
On 13/10/14 11:40, אופיר לירון wrote: # set the initial values the_number = random.randint(1, 100) guess = int(input(Take a guess: )) tries = 1 # guessing loop while guess != the_number: if guess the_number: print(Lower...) else: print(Higher...) guess = int(input(Take a guess: )) tries += 1 if tries 5: break so far so good almost... if guess != the_number: print (you failed, the number was, the_number) This is still inside the loop. You want to remove the indentation so this only happens after you exit the loop. Otherwise you tell the user the answer before they guess it (or have 5 goes) and it doesn't work right if the first guess is correct... input(\n\nPress the enter key to exit.) You need the if/else to look like this. -- 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
http://cscircles.cemc.uwaterloo.ca/run-at-home/ On Fri, Sep 19, 2014 at 11:04 AM, Danny Yoo d...@hashcollision.org wrote: On Wed, Sep 17, 2014 at 4:36 PM, Art Pelletier artp...@gmail.com wrote: I am a beginner with pythons programming I would like to see if their is a site that has samples programs that I can practice on. Hi Art, Yes, there are some good resources you can check out. Here's a link to some of them: https://wiki.python.org/moin/BeginnersGuide/NonProgrammers Personally, I like How to Think Like a Computer Scientist: http://openbookproject.net/thinkcs/python/english2e/ but any of the tutorials in the beginner's guide should be helpful. Feel free to ask questions here on this mailing list too. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor -- Diliup Gabadamudalige http://www.diliupg.com http://soft.diliupg.com/ ** This e-mail is confidential. It may also be legally privileged. If you are not the intended recipient or have received it in error, please delete it and all copies from your system and notify the sender immediately by return e-mail. Any unauthorized reading, reproducing, printing or further dissemination of this e-mail or its contents is strictly prohibited and may be unlawful. Internet communications cannot be guaranteed to be timely, secure, error or virus-free. The sender does not accept liability for any errors or omissions. ** ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Help
Check this guy's youtube channel. He has very basic examples. His username is thenewboston On Wed, Sep 17, 2014 at 4:36 PM, Art Pelletier artp...@gmail.com wrote: I am a beginner with pythons programming I would like to see if their is a site that has samples programs that I can practice on. Sent from my iPad ___ 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] Help
On Wed, Sep 17, 2014 at 4:36 PM, Art Pelletier artp...@gmail.com wrote: I am a beginner with pythons programming I would like to see if their is a site that has samples programs that I can practice on. Hi Art, Yes, there are some good resources you can check out. Here's a link to some of them: https://wiki.python.org/moin/BeginnersGuide/NonProgrammers Personally, I like How to Think Like a Computer Scientist: http://openbookproject.net/thinkcs/python/english2e/ but any of the tutorials in the beginner's guide should be helpful. Feel free to ask questions here on this mailing list too. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Help on best way to check resence of item inside list
On 27/05/2014 09:05, jarod...@libero.it wrote: Dear All clubA= [mary,luke,amyr,marco,franco,lucia, sally,genevra, electra] clubB= [mary,rebecca,jane,jessica,judit,sharon,lucia, sally, Castiel,Sam] I have a list of names that I would to annotate in function of presence in different clubs: my input files is a long file where I have this : mary luke luigi jane jessica rebecca luis à with open(file.in) as p: mit = [] for i in p: lines =i.strip(\n).split(\t) if (lines[0] in clubA: G =lines[-1] +[clubA] else: G = lines[-1] +[no] mit.append(G) for i in mit: if i.strip(\n).split(\t)[0] in clubB: G =lines[-1] +[clubB] else: G = lines[-1] +[no] finale.append(G) ### I just wonder if is appropriate to use a loops to check if is present the value on a list. Is it the right way? I can use a dictionary because I have many repeated names. In the end I wan to have mary clubA clubB luke clubA luigi no Thanks in advance for any help You can use the in keyword to check for an item in a list. However a very quick glance at your code suggests that you could cut out the list completely and do the same using the in keyword against your dict. Better still I think the defaultdict is what you need here, I'll leave you to look it up as I must dash :) -- 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] Help on best way to check resence of item inside list
jarod...@libero.it jarod...@libero.it Wrote in message: Dear All clubA= [mary,luke,amyr,marco,franco,lucia, sally,genevra, electra] clubB= [mary,rebecca,jane,jessica,judit,sharon,lucia, sally, Castiel,Sam] I have a list of names that I would to annotate in function of presence in different clubs: my input files is a long file where I have this : mary luke luigi jane jessica rebecca luis à with open(file.in) as p: mit = [] for i in p: lines =i.strip(\n).split(\t) if (lines[0] in clubA: G =lines[-1] +[clubA] else: G = lines[-1] +[no] mit.append(G) for i in mit: if i.strip(\n).split(\t)[0] in clubB: G =lines[-1] +[clubB] else: G = lines[-1] +[no] finale.append(G) ### I just wonder if is appropriate to use a loops to check if is present the value on a list. Is it the right way? I can use a dictionary because I have many repeated names. In the end I wan to have mary clubA clubB luke clubA luigi no Thanks in advance for any help There are numerous errors in the above code. You should use copy/paste, so we don't waste energy identifying errors that don't even exist in your actual code. As it stands, it wouldn't even compile. But even if you fix the typos and indentation errors and initialization errors, you still have logic errors if you want the output you specify. First, the second loop doesn’t set the lines variable at all, but just uses the value from the last iteration of the first loop. Second, even if you untangle that, luigi would end up with two 'no's, not one. You don't say what list could have repeats. I don't see any in your sample data. You also don't say how they should be treated. For example, Are all seventeen mary's in clubA? Now to your specific question. You aren't using the loops to check the lists for a name. You're quite reasonably using 'in'. You can accomplish your apparent goal much more reasonably by using a single loop and more complex if elif and else. -- DaveA ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Help on best way to check resence of item inside list
On Tue, May 27, 2014 at 10:05:30AM +0200, jarod...@libero.it wrote: [...] with open(file.in) as p: mit = [] You have lost the indentation, which makes this code incorrect. But the rest of the code is too complicated. for i in p: lines =i.strip(\n).split(\t) if (lines[0] in clubA: G =lines[-1] +[clubA] else: G = lines[-1] +[no] mit.append(G) for i in mit: if i.strip(\n).split(\t)[0] in clubB: G =lines[-1] +[clubB] else: G = lines[-1] +[no] finale.append(G) Look at the result you want to get: mary clubA clubB luke clubA luigi no That suggests to me that the best data structure is a dict with sets: {'mary': set(['clubA', 'clubB']), 'luke': set(['clubA']), 'luigi': set(), } Something like this should work: names = {} with open(file.in) as p: # This assumes the data file is one name per line. for line in p: name = line.strip() s = names.get(name, set()) # If name not in the names, # return an empty set. if name in clubA: s.add(clubA) if name in clubB: s.add(clubB) names[name] = s print(names) And I think that should work. -- Steven ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Help on best way to check resence of item inside list
jarod...@libero.it wrote: Dear All clubA= [mary,luke,amyr,marco,franco,lucia, sally,genevra, electra] clubB= [mary,rebecca,jane,jessica,judit,sharon,lucia, sally, Castiel,Sam] I have a list of names that I would to annotate in function of presence in different clubs: my input files is a long file where I have this : mary luke luigi jane jessica rebecca luis à with open(file.in) as p: mit = [] for i in p: lines =i.strip(\n).split(\t) if (lines[0] in clubA: G =lines[-1] +[clubA] else: G = lines[-1] +[no] mit.append(G) for i in mit: if i.strip(\n).split(\t)[0] in clubB: G =lines[-1] +[clubB] else: G = lines[-1] +[no] finale.append(G) ### I just wonder if is appropriate to use a loops to check if is present the value on a list. Is it the right way? I can use a dictionary because I have many repeated names. You mean you have people who are members in more than one club? You can still use a dictionary if you make the value a list: # untested code! membership = {} club = club_of_people_who_are_not_in_any_club members = [Erwin, Kurt, Groucho] for name in members: # can be simplified with dict.setdefault() or collections.defaultdict if name in membership: membership[name].append(club) else: membership[name] = [club] Put that in a loop over (club, members) pairs, and you'll end up with a dict that maps name -- list_of_clubs. Then iterate over the lines in the file: with open(file.in) as source: for line in source: name = line.strip() if name in membership: print(name, *membership[name]) else: print(name, no) In the end I wan to have mary clubA clubB luke clubA luigi no Thanks in advance for any help ___ 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] Help with Python
On 16/05/14 02:58, Glen Chan wrote: Hello, I am student trying to fugure out why when I enter any number it says error. Because that's what you programmed it to do. Almost. If you enter 1 or 10 you won't get an error. Look at your logic: number = input('Enter a number between 1 and 10: ') while number 1 or number 10: print 'Please enter a number between 1 and 10' number = input('Enter a number between 1 and 10: ') number = input('Enter a number between 1 and 10: ') while number 1 or number 10: print 'Error' number = input('Enter a number between 1 and 10: ') If the first number you enter is say 7. It skips the first while loop and asks for another number. If you enter 7 again It then goes into the second while loop and reports an error. The only numbers which don't fall into one of the two loops are 1 and 10. BTW It's bad practice to use input() in Python v2 becauise it has security issues. Instead use raw_input() and convert to an int() or float() explicitly. while not (endProgram == 'yes' or endProgram == 'no'): print 'Please enter a yes or no' There is a bug here too since you don't provide a way for the user to enter a new number. It will loop forever. 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 with Python
Hi Glen, and welcome! My responses below. On Thu, May 15, 2014 at 09:58:07PM -0400, Glen Chan wrote: Hello, I am student trying to fugure out why when I enter any number it says error. It's only suppose to do that if it's out the 1-10 range. Please help. Thank you. You've made an mistake in your logic below. You print an error for *every* number: number = input('Enter a number between 1 and 10: ') while number 1 or number 10: print 'Please enter a number between 1 and 10' number = input('Enter a number between 1 and 10: ') This part is okay. You check that if number is out of range, and if it is, it prints a message. Check for yourself: Suppose I choose 5. Is 5 less than 1? No. Is it larger than 10? No. So the while loop immediately ends, and I move on. So at this stage, you have now successfully asked the user for a number between 1 and 10. But here you make the mistake: number = input('Enter a number between 1 and 10: ') Hmmm. You've already asked the user for a number. But then you ignore it, and ask for another one. But even that's not really the mistake: while number 1 or number 10: print 'Error' number = input('Enter a number between 1 and 10: ') And this is where you get the logic backwards. This while loop runs forever, or until you manually cancel it. Check for yourself: Suppose I choose 5. Is 5 larger than 1? Yes. So the while loop continues, and 'Error' is printed. Suppose I choose 0. Is 0 larger than 1? No. Is 0 less than 10? Yes. So again, the while loop continues, and 'Error' is printed. Are there *any* numbers *smaller* than 1 AND *larger* than 10 at the same time? No, of course not. So the while loop condition is always true, and the while loop will always run no matter what number I choose. This second while loop has the logic backwards. You should compare this one, the faulty one, with the first one, the correct one. Can you see the difference? A couple of other comments about your code: * In a few places, you use input, but in other places, you use raw_input. You should never use input. It was a mistake, and has been removed from newer versions of Python. Instead, you should write int(raw_input(Enter a number...)). * You check that number is in range like this: number 1 or number 10 There's an easier way: 1 = number = 10 which is not only less typing, but makes it more obvious what you are trying to do. You want number to be in the range 1 through 10 inclusive. That makes it harder to screw up the logic: 1 = number = 10 # Wrong! What do you mean, 1 is BIGGER than number, which is bigger than 10? That's impossible! -- Steven ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Help with Python
Hi This will solve your purpose: Yes we can write in better way also : -- #The Dice Game #add libraries needed import random #the main function def main(): print #initialize variables playerOne = 'No Name' playerTwo = 'No Name' endProgram =no #call to inputNames playerOne, playerTwo = inputNames(playerOne, playerTwo) #while loop to run program again while endProgram == 'no': #call to rollDice winnersName = rollDice(playerOne, playerTwo) #call to displayInfo print Winner is , winnersName endProgram = raw_input('Do you want to end program? (Enter yes or no): ') #this function gets the players names def inputNames(playerOne, playerTwo): playerOne = raw_input(Enter Name) playerTwo = raw_input(Enter Name) return playerOne, playerTwo #this function will get the random values def rollDice(playerOne, playerTwo): p1number = random.randint(1, 6) p2number = random.randint(1, 6) #this function displays the winner if p1number == p2number: winnerName = TIE elif p1number p2number: winnerName = playerOne else: winnerName = playerTwo return winnerName if __name__ == __main__: # calls main main() On Sun, May 11, 2014 at 8:46 AM, Glen Chan gchan...@msn.com wrote: Hello, I am a student trying to figure out Python. I am getting errors that I don't know how to fix. What do you do after you get the error message and something is highlighted? Does that have to be deleted? Anyway, here is what I mean... # The Dice Game #add libraries needed import random #the main function def main(): print #initialize variables playerOne = 'No Name' playerTwo = 'No Name' #call to inputNames playerOne, playerTwo = inputNames(playerOne, playerTwo) #while loop to run program again while endProgram == 'no': #initialize variables winnersName = 'NO NAME' p1number = 0 p2number = 0 #call to rollDice winnerName = rollDice(p1number, p2number, playerOne, playerTwo, winnerName) #call to displayInfo winnerName endProgram = raw_input('Do you want to end program? (Enter yes or no): ') #this function gets the players names def inputNames(playerOne, playerTwo): playerOne = raw_input(Enter Name) playerTwo = raw_input(Enter Name) return playerOne, playerTwo #this function will get the random values def rollDice(p1numer, p2numer, playerOne, playerTwo, winnerName): p1number = random.randint(1, 6) p1number = random.randint(1, 6) #this function displays the winner if p1number == p2number: winnerName = TIE elif p1number p2number: winnerName = playerOne else: winnerName = playerTwo return winnerName # calls main main() ___ 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] Help with Python
Hey Glen, include the error you are getting. It will make answering your question easier. How are you running this program, in an IDE? On Sat, May 10, 2014 at 11:16 PM, Glen Chan gchan...@msn.com wrote: Hello, I am a student trying to figure out Python. I am getting errors that I don't know how to fix. What do you do after you get the error message and something is highlighted? Does that have to be deleted? Anyway, here is what I mean... # The Dice Game #add libraries needed import random #the main function def main(): print #initialize variables playerOne = 'No Name' playerTwo = 'No Name' #call to inputNames playerOne, playerTwo = inputNames(playerOne, playerTwo) #while loop to run program again while endProgram == 'no': #initialize variables winnersName = 'NO NAME' p1number = 0 p2number = 0 #call to rollDice winnerName = rollDice(p1number, p2number, playerOne, playerTwo, winnerName) #call to displayInfo winnerName endProgram = raw_input('Do you want to end program? (Enter yes or no): ') #this function gets the players names def inputNames(playerOne, playerTwo): playerOne = raw_input(Enter Name) playerTwo = raw_input(Enter Name) return playerOne, playerTwo #this function will get the random values def rollDice(p1numer, p2numer, playerOne, playerTwo, winnerName): p1number = random.randint(1, 6) p1number = random.randint(1, 6) #this function displays the winner if p1number == p2number: winnerName = TIE elif p1number p2number: winnerName = playerOne else: winnerName = playerTwo return winnerName # calls main main() ___ 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] Help with Python
On 11/05/14 04:16, Glen Chan wrote: Hello, I am a student trying to figure out Python. I am getting errors that I don't know how to fix. What do you do after you get the error message and something is highlighted? Does that have to be deleted? The error doesn't need to be deleted because it appears in the interpreter, not in your code. However,... # The Dice Game Are you trying to type the whole program into the interactive Python shell? If so that's the wrong approach. The prompt is only intended for entering a few lines to experiment and find out how things work. You should create a new text file and write the code into that. You can then run the file in the interpreter. If you are using an IDE (such as IDLE) that usually means you use the File-New menu and an editor window will appear. There will then be a Run menu somewhere (in IDLE its Run-Run Module) to run the program. If you are using IDLE take a look at Danny's tutorial here: http://hkn.eecs.berkeley.edu/~dyoo/python/idle_intro/index.html As to your error please copy the en tire error message and send it to us, otherwise we have to guess what the problem is... 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 with Python
On 05/10/2014 11:16 PM, Glen Chan wrote: Hello, I am a student trying to figure out Python. I am getting errors that I don't know how to fix. What do you do after you get the error message and something is highlighted? Does that have to be deleted? Anyway, here is what I mean... def main(): print #initialize variables playerOne = 'No Name' playerTwo = 'No Name' #call to inputNames playerOne, playerTwo = inputNames(playerOne, playerTwo) #while loop to run program again while endProgram == 'no': #initialize variables winnersName = 'NO NAME' p1number = 0 p2number = 0 #call to rollDice winnerName = rollDice(p1number, p2number, playerOne, playerTwo, winnerName) #call to displayInfo winnerName endProgram = raw_input('Do you want to end program? (Enter yes or no): ') When posting a question, you should always specify the Python version and OS, though it probably doesn't matter here. As others have said, please paste the exact error message. This is a text mailing list, so any highlighting you may have tried to include is lost on most of us. Please post in a text message, not html, as many things can go wrong in the re-interpretation, especially in any source code. I pasted your code into a text editor, saved the file, and ran it a terminal window in Python 2.7 under Linux, davea@think2:~/temppython$ python glen.py File glen.py, line 25 endProgram = raw_input('Do you want to end program? (Enter yes or no): ') ^ IndentationError: unexpected indent davea@think2:~/temppython$ As you can see the callstack shows the line that has a problem, and shows s a specific error message. The problem is that you indented a line improperly. You only add to the indentation within a function, an if/else statement statement block, class, with clause, etc. Ordinary statemdents have to line up with the ones before, not counting comments. If you line up the endProgram line with the previous winnername line, this particular error will go away. But you have others. I notice you mix spaces and tabs for indentation, which is dangerously confusing. You should stick to one or the other, and I prefer spaces. I configured my text editor (emacs) to turn any tabs into 4 spaces, so that I won't get into trouble. in some places you only indent by one space. That's hard to read and you can wind up with problems from that. Better to stick with 4, though some people seem to prefer 2. Next problem is: davea@think2:~/temppython$ python glen.py File glen.py, line 44 elif p1number p2number: ^ IndentationError: unindent does not match any outer indentation level This error is because the elif clause does not line up with the if clause. But a bigger problem in that portion of code is that you're apparently starting a new function, but never define it. No def line follows the comment: #this function displays the winner If you add that def xxx(): line, and indent the if, then the elif will line up as expected. After fixing that, the next error is: Traceback (most recent call last): File glen.py, line 51, in module main() File glen.py, line 15, in main while endProgram == 'no': UnboundLocalError: local variable 'endProgram' referenced before assignment That comes because you have a while statement that refers to the variable endProgram, which has not been yet bound to a value. You need endProgram = no before that if statement. In each of these cases, the error message tells you pretty closely what's wrong, and where. You will need to learn to read the error messages, the tracebacks. Your next problem is one of program logic, and I leave it to you. -- DaveA ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] HELP! How do I remove the black after s=
On Sat, May 10, 2014 at 8:35 AM, 1 2 bothe...@gmail.com wrote: In the result it shows s= 8 pls tell me how to remove the blank? s,t,n = 0,0,1 while t = s: s,t,n = s+2,t+n,n+1 else: print('s=',s,n) You must use something else. For example: print('s={0} {1}'.format(s, n)) This will produce s=8 5. If you want s=85, remove the space in the format string. -- Chris “Kwpolska” Warrick http://kwpolska.tk PGP: 5EAAEA16 stop html mail | always bottom-post | only UTF-8 makes sense ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] HELP! How do I remove the black after s=
On 10/05/14 07:35, 1 2 wrote: In the result it shows s= 8 pls tell me how to remove the blank? s,t,n = 0,0,1 while t = s: s,t,n = s+2,t+n,n+1 else: print('s=',s,n) Assuming you are using Python version 3 you need to specify the sep option to print: print('s=',s,n,sep='') help(print) Help on built-in function print in module builtins: print(...) print(value, ..., sep=' ', end='\n', file=sys.stdout) Prints the values to a stream, or to sys.stdout by default. Optional keyword arguments: file: a file-like object (stream); defaults to the current sys.stdout. sep: string inserted between values, default a space. end: string appended after the last value, default a newline. (END) 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! How do I remove the black after s=
Hello 1 2, and welcome! (By the way, I feel quite silly calling you by the name you show in your email address. Do you have another name you would prefer to be known by?) My response below. On Sat, May 10, 2014 at 02:35:07PM +0800, 1 2 wrote: In the result it shows s= 8 pls tell me how to remove the blank? There are a few different ways. The easiest is to tell the print() function not to use a space as seperator between terms. (This only works in Python 3.) py print(s=, 8, 9) s= 8 9 py print(s=, 8, 9, sep='') s=89 But note that the separator applies between all the items, so that's not very useful in your case. Instead, you can build up a string, then print the string. Here are two different ways to do it, the first may be familiar with you if you know how to program in C. py print(s=%s %s % (8, 9)) s=8 9 py print(s={} {}.format(8, 9)) s=8 9 Hope this helps. -- Steven ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Help With Code
On 01/05/14 01:18, jordan smallwood wrote: Hey there, I have this code below (in to cm conversion) and I want to have the user try again if they enter in a non integer. What am I missing: A loop. There is a common pattern or idiom in Pytthon: while True: get input if input ok: break # exits the loop else: print error # and go round the loop again So in your case it will look like this: while True: try: value = float(raw_input('Please enter a number: ')) break # only gets here if no error except ValueError: print Not a valid number. Those two extra lines are all you need. 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 With Code
jordan smallwood jsmallwoo...@yahoo.com.dmarc.invalid Wrote in message: want to have the user try again if they enter in a non integer. What am I missing: Do you perhaps mean float? If so, see the other response. -- DaveA ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Help needed
On 26/04/14 01:46, Suhana Vidyarthi wrote: I have this file: 1,3,5,0.03 2,3,5,5,4,0.11 3,3,5,5,4,5,8,0.04 And each line is interpreted as: * 1,3,5,0.03- This line means 1 link can be down i.e. between 3—5 with a probability of failure *0.03* * 2,3,5,5,4,0.11 - This line means 2 links can be down i.e. between 3--5 and 5--4 with a probability of failure *0.11* (for each link) * 3,3,5,5,4,5,8,0.04 - Similarly this line means 3 links can be down i.e. between 3--5 , 5—4 and 5—8 with a probability of failure *0.04* (for each link) ... I want to create two arrays using the above file (Links array and Prob array) that should give following output: *Links *= { [3,5] [5,4] [5,8] [7,8] [14,10] [14,13] [17,13] [14,18] [10,13] [14,13] [17,13] [12,13] [11,6] [11,9][11,12] [11,19] [19,20] [15,20] [21,20] [20,21] [21,16] [21,22] } *Prob *= {[0.28] [0.15] [0.08] [0.04] [0.04] [0.04] [0.08] [0.04] [0.08] [0.08] [0.08] [0.08] [0.24] [0.24] [0.34] [0.27] [0.27]} I don't understand how you develop this? The first list has 22 items the second 17. I would have expected them to be the same? Also why do you want these two lists? What do you plan on doing with them? I would have thought a mapping of link to probability would be much more useful? (mapping = dictionary) So the first element in Links array is [3,5] and its probability of failure is the first element in Prob array i.e. 0.28 Can anyone help me with this please? Do you know how to open and read a file line by line? Do you know how to extract the elements from a line? Do you know how to define a list and add elements to it? Do you know how to find an element in a list? Do you know how to modify an element in a list? If you know the above you have all the pieces you need to complete the task. If not tell us which bits you are stuck with. And show us some code, we will not do your work for you but are happy to help. -- 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
Hi Suhana, Also note that you asked this question just a few days ago. https://mail.python.org/pipermail/tutor/2014-April/101019.html We're not robots. We don't like repetition unless there's a reason for it, and in this case, you got responses to the earlier question. For example: https://mail.python.org/pipermail/tutor/2014-April/101022.html https://mail.python.org/pipermail/tutor/2014-April/101029.html Did you see these responses? If not, please check your mail settings. If you want to continue working on this problem, I'd recommend continuing that thread rather than start a fresh one. Reason is, if I were to look at your question fresh, I'd answer the exact same way to it. I'm trying to lightly probe what you've done and what you understand already. If you're repeating the question in the hopes that repetition will wear down the people you're trying to get answers from, please change your learning strategy: it won't be effective here. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Help needed
Hi, The reason I opened a link is because there are changes in the code. Does it make sense? Else I can definitely go back to the thread. On Sat, Apr 26, 2014 at 9:05 AM, Danny Yoo d...@hashcollision.org wrote: Hi Suhana, Also note that you asked this question just a few days ago. https://mail.python.org/pipermail/tutor/2014-April/101019.html We're not robots. We don't like repetition unless there's a reason for it, and in this case, you got responses to the earlier question. For example: https://mail.python.org/pipermail/tutor/2014-April/101022.html https://mail.python.org/pipermail/tutor/2014-April/101029.html Did you see these responses? If not, please check your mail settings. If you want to continue working on this problem, I'd recommend continuing that thread rather than start a fresh one. Reason is, if I were to look at your question fresh, I'd answer the exact same way to it. I'm trying to lightly probe what you've done and what you understand already. If you're repeating the question in the hopes that repetition will wear down the people you're trying to get answers from, please change your learning strategy: it won't be effective here. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Help needed
Thanks for the response Alan. my clarifications are below: On Sat, Apr 26, 2014 at 1:41 AM, Alan Gauld alan.ga...@btinternet.comwrote: On 26/04/14 01:46, Suhana Vidyarthi wrote: I have this file: 1,3,5,0.03 2,3,5,5,4,0.11 3,3,5,5,4,5,8,0.04 And each line is interpreted as: * 1,3,5,0.03- This line means 1 link can be down i.e. between 3—5 with a probability of failure *0.03* * 2,3,5,5,4,0.11 - This line means 2 links can be down i.e. between 3--5 and 5--4 with a probability of failure *0.11* (for each link) * 3,3,5,5,4,5,8,0.04 - Similarly this line means 3 links can be down i.e. between 3--5 , 5—4 and 5—8 with a probability of failure *0.04* (for each link) ... I want to create two arrays using the above file (Links array and Prob array) that should give following output: *Links *= { [3,5] [5,4] [5,8] [7,8] [14,10] [14,13] [17,13] [14,18] [10,13] [14,13] [17,13] [12,13] [11,6] [11,9][11,12] [11,19] [19,20] [15,20] [21,20] [20,21] [21,16] [21,22] } *Prob *= {[0.28] [0.15] [0.08] [0.04] [0.04] [0.04] [0.08] [0.04] [0.08] [0.08] [0.08] [0.08] [0.24] [0.24] [0.34] [0.27] [0.27]} I don't understand how you develop this? The first list has 22 items the second 17. I would have expected them to be the same? In the Prob array the elements are less because if you read the note below: I said the links that are repeating for example [3,5] their probabilities get added and stored as a single value in the Prob array. Also why do you want these two lists? What do you plan on doing with them? I would have thought a mapping of link to probability would be much more useful? (mapping = dictionary) I want these two lists because using the links and probs array, I will check which link has the lowest probability. Here lowest probability means the risk of failure for that link. So based on which link has least probability of failure, I will use it to setup a connection (I have a source and destination and the links mentioned above are the paths between them) I want to select the path which has least failure probability. Did it make sense? So the first element in Links array is [3,5] and its probability of failure is the first element in Prob array i.e. 0.28 Can anyone help me with this please? Do you know how to open and read a file line by line? Do you know how to extract the elements from a line? Do you know how to define a list and add elements to it? Do you know how to find an element in a list? Do you know how to modify an element in a list? If you know the above you have all the pieces you need to complete the task. If not tell us which bits you are stuck with. I have been studying about it and have come up with my code. And show us some code, we will not do your work for you but are happy to help. I actually used the map and dictionary function to write the code, please see the attachment. The only problem I am having is that when I try to display the links and probabilities, they are not displayed in the order of the file content. This is how it should display: Links = { [3,5] [5,4] [5,8] [7,8] [14,10] [14,13] [17,13] [14,18] [10,13] [14,13] [17,13] [12,13] [11,6] [11,9][11,12] [11,19] [19,20] [15,20] [21,20] [20,21] [21,16] [21,22] } Prob = {[0.18] [0.15] [0.08] [0.04] [0.04] [0.04] [0.08] [0.04] [0.08] [0.08] [0.08] [0.08] [0.24] [0.24] [0.34] [0.27] [0.27]} However when I run my code, this is how the arrays are displayed: Links - [('10', '13'), ('14', '18'), ('7', '8'), ('15', '20'), ('5', '8'), ('5', '4'), ('11', '9'), ('21', '22'), ('12', '13'), ('21', '20'), ('17', '13'), ('20', '21'), ('21', '16'), ('14', '10'), ('11', '12'), ('11', '19'), ('14', '13'), ('3', '5'), ('11', '6'), ('19', '20')] Probability - [0.04, 0.06, 0.04, 0.24, 0.08, 0.15, 0.08, 0.27, 0.04, 0.29, 0.08, 0.27, 0.27, 0.04, 0.08, 0.08, 0.08, 0.18002, 0.08, 0.24] Can you please see my code and help me find out what is wrong? -- 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 with open('/Users/suhana/Downloads/disastersWMD_ATT.txt', 'r') as content_file: #print content_file.read() #from collections import defaultdict newdict = dict() linedict = {} #links array links_array = [] #probability array prob_array = [] #this gets executed for no of lines in files for line in content_file: #print line.strip() data = line.split(,) #print data data_Len = len(data) #print data_Len j = data[0] # print j LastItem = data[data_Len-1]; #print LastItem #data[1:-1] gives all array contents except 1st and last #data[-1] gives last element of array
Re: [Tutor] Help needed
I want to create two arrays using the above file (Links array and Prob array) that should give following output: *Links *= { [3,5] [5,4] [5,8] [7,8] [14,10] [14,13] [17,13] [14,18] [10,13] [14,13] [17,13] [12,13] [11,6] [11,9][11,12] [11,19] [19,20] [15,20] [21,20] [20,21] [21,16] [21,22] } *Prob *= {[0.28] [0.15] [0.08] [0.04] [0.04] [0.04] [0.08] [0.04] [0.08] [0.08] [0.08] [0.08] [0.24] [0.24] [0.34] [0.27] [0.27]} I don't understand how you develop this? The first list has 22 items the second 17. I would have expected them to be the same? In the Prob array the elements are less because if you read the note below: I said the links that are repeating for example [3,5] their probabilities get added and stored as a single value in the Prob array. But what will you plan to do with these values afterwards? I think Alan's point here is that if there's no direct relationship between the elements in Links and the elements in Probs, those values aren't going to be very useful to solve the rest of the problem. One way to look at this problem is to simplify or normalize the input; the original structure in the file is slightly weird to process, since a single line of the input represents several link/failure pairs. One concrete example is: 4,10,13,14,13,17,13,12,13,0.04 where all these numbers are uninterpreted. You can imagine something that takes the line above, and breaks it down into a series of LinkFailure items. ## class LinkFailure(object): Represents a link and the probability of failure. def __init__(self, start, end, failure): self.start = start self.end = end self.failure = failure ## which represent a link and failure structure. If we have a structure like this, then it explicitly represents a relationship between a link and its failure, and the string line: 4,10,13,14,13,17,13,12,13,0.04 can be distilled and represented as a collection of LinkFailure instances: [LinkFailure(10, 13, 0.04), LinkFailure(14, 13, 0.04), LinkFailure(17, 13, 0.04), LinkFailure(12, 13, 0.04)] Then the relationship is explicit. Also why do you want these two lists? What do you plan on doing with them? I would have thought a mapping of link to probability would be much more useful? (mapping = dictionary) I want these two lists because using the links and probs array, I will check which link has the lowest probability. Here lowest probability means the risk of failure for that link. So based on which link has least probability of failure, I will use it to setup a connection (I have a source and destination and the links mentioned above are the paths between them) I want to select the path which has least failure probability. Did it make sense? Unfortunately, I'm still confused. If you just have the Links and the Probs lists of unequal length, unless there's some additional information that you're represented, then I don't see the necessary connection between the two lists that lets you go any further in the problem. There's no one-to-one-ness: given a link in Links, which Probs do you want to look at? If you don't represent that linkage in some way, I don't understand yet where you go next. So the first element in Links array is [3,5] and its probability of failure is the first element in Prob array i.e. 0.28 But if the two lists are different lengths, what probability of failure is associates with the last element in the Prob array? The representation of data is important: if you choose an awkward representation, it makes solving this problem more difficult than it needs be. That is, if you're already compressing multiple elements in Prob that correspond to the same link, you also need some way to figure out what link that a compressed probability refer to. Otherwise, you don't have enough information to solve the problem anymore. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Help needed
Hi Danny, Let me give you a high level brief of what I am doing: I am working on doing disaster aware routing considering the 24-node US network where I will be setting up connection between two any two nodes (I will select the source and destination nodes randomly). Also I have some links whose probability of failure is mentioned in the attached file. Other links, which are not mentioned in the file - we suppose their probability of failure is zero. So between the source-destination nodes, there will be multiple paths and I will select the one which has least probability of failure. Now to setup the connection between two nodes, I have to select a path whose probability of failure is least. To do that first I will calculate the risk of each path from the attached file and then select the path with least risk value. Did you get this part? I know it can be a bit confusing. Now I break the problem into parts: 1. I have to topology of the 24-node map 2. I have the link values of each link - where risk values are the probability of failure 3. I calculate the total probability of failure of each path (a path may have multiple links): Suppose my source node is a and destination node is b. I can setup a path between a to b via c or via d (a-c-b or a-d-c): Here I will check the risk values of a-c and c-b; also risk values of a-d and d-c. If the total risk valure of a-c-b is lower that risk value of a-d-c, then I select the path a-c-d to setup the connection. (again risk value = probability of failure) Now, I will first calculate the total probability of failure of each link (using the file.txt) and since some links are repeated their values will be added. The probabilities get added if a link is mentioned twice or thrice. For example: link 3—5 is repeated 3 times: in line one, it has a probability of failure as 0.03, in line two it is 0.11 and in line three it is 0.04. So the probability of failure for link 3—5 is 0.03+0.11+0.04 = 0.18 The length of each array will be same. You see the code I wrote: here is the output for it: Links - [('10', '13'), ('14', '18'), ('7', '8'), ('15', '20'), ('5', '8'), ('5', '4'), ('11', '9'), ('21', '22'), ('12', '13'), ('21', '20'), ('17', '13'), ('20', '21'), ('21', '16'), ('14', '10'), ('11', '12'), ('11', '19'), ('14', '13'), ('3', '5'), ('11', '6'), ('19', '20')] Probability - [0.04, 0.06, 0.04, 0.24, 0.08, 0.15, 0.08, 0.27, 0.04, 0.29, 0.08, 0.27, 0.27, 0.04, 0.08, 0.08, 0.08, 0.18002, 0.08, 0.24] It means that link [10,13] has a probability of failure as [0.04] and since the link [3-5] is repeated thrice with probability of 0.03, 0.11 and 0.04, its probability of failure is [0.18] (third last element in the Probability array). For some reason instead of 0.18 it is showing 0.1802, which I cannot figure to why. Please see the attached code. If you see the file.txt and my output: the output is not displayed in sequence and that is what I need help with. I want this to display : Links = { [3,5] [5,4] [5,8] [7,8] [14,10] [14,13] [17,13] [14,18] [10,13] [14,13] [17,13] [12,13] [11,6] [11,9] [11,12] [11,19] [19,20] [15,20] [21,20] [20,21] [21,16] [21,22] } Prob = {[0.18] [0.15] [0.08] [0.04] [0.04] [0.04] [0.08] [0.04] [0.08] [0.08] [0.08] [0.08] [0.24] [0.24] [0.34] [0.27] [0.27]} If you can figure why the output is not generated in same sequence as in the file.txt for me, it will be very helpful. let me know if I explained correctly, and if you have any questions or doubts? On Sat, Apr 26, 2014 at 11:41 AM, Danny Yoo d...@hashcollision.org wrote: I want to create two arrays using the above file (Links array and Prob array) that should give following output: *Links *= { [3,5] [5,4] [5,8] [7,8] [14,10] [14,13] [17,13] [14,18] [10,13] [14,13] [17,13] [12,13] [11,6] [11,9][11,12] [11,19] [19,20] [15,20] [21,20] [20,21] [21,16] [21,22] } *Prob *= {[0.28] [0.15] [0.08] [0.04] [0.04] [0.04] [0.08] [0.04] [0.08] [0.08] [0.08] [0.08] [0.24] [0.24] [0.34] [0.27] [0.27]} I don't understand how you develop this? The first list has 22 items the second 17. I would have expected them to be the same? In the Prob array the elements are less because if you read the note below: I said the links that are repeating for example [3,5] their probabilities get added and stored as a single value in the Prob array. But what will you plan to do with these values afterwards? I think Alan's point here is that if there's no direct relationship between the elements in Links and the elements in Probs, those values aren't going to be very useful to solve the rest of the problem. One way to look at this problem is to simplify or normalize the input; the original structure in the file is slightly weird to process, since a single line of the input represents several link/failure pairs. One concrete example is: 4,10,13,14,13,17,13,12,13,0.04 where all these numbers are uninterpreted. You can imagine something
Re: [Tutor] Help needed
Just glancing at your work, I see you have curly braces around what looks like it should be a list. If you are concerned with the order of your output, dictionaries do not have a concept of order. On Sat, Apr 26, 2014 at 3:16 PM, Suhana Vidyarthi suhanavidyar...@gmail.com wrote: Hi Danny, Let me give you a high level brief of what I am doing: I am working on doing disaster aware routing considering the 24-node US network where I will be setting up connection between two any two nodes (I will select the source and destination nodes randomly). Also I have some links whose probability of failure is mentioned in the attached file. Other links, which are not mentioned in the file - we suppose their probability of failure is zero. So between the source-destination nodes, there will be multiple paths and I will select the one which has least probability of failure. Now to setup the connection between two nodes, I have to select a path whose probability of failure is least. To do that first I will calculate the risk of each path from the attached file and then select the path with least risk value. Did you get this part? I know it can be a bit confusing. Now I break the problem into parts: 1. I have to topology of the 24-node map 2. I have the link values of each link - where risk values are the probability of failure 3. I calculate the total probability of failure of each path (a path may have multiple links): Suppose my source node is a and destination node is b. I can setup a path between a to b via c or via d (a-c-b or a-d-c): Here I will check the risk values of a-c and c-b; also risk values of a-d and d-c. If the total risk valure of a-c-b is lower that risk value of a-d-c, then I select the path a-c-d to setup the connection. (again risk value = probability of failure) Now, I will first calculate the total probability of failure of each link (using the file.txt) and since some links are repeated their values will be added. The probabilities get added if a link is mentioned twice or thrice. For example: link 3—5 is repeated 3 times: in line one, it has a probability of failure as 0.03, in line two it is 0.11 and in line three it is 0.04. So the probability of failure for link 3—5 is 0.03+0.11+0.04 = 0.18 The length of each array will be same. You see the code I wrote: here is the output for it: Links - [('10', '13'), ('14', '18'), ('7', '8'), ('15', '20'), ('5', '8'), ('5', '4'), ('11', '9'), ('21', '22'), ('12', '13'), ('21', '20'), ('17', '13'), ('20', '21'), ('21', '16'), ('14', '10'), ('11', '12'), ('11', '19'), ('14', '13'), ('3', '5'), ('11', '6'), ('19', '20')] Probability - [0.04, 0.06, 0.04, 0.24, 0.08, 0.15, 0.08, 0.27, 0.04, 0.29, 0.08, 0.27, 0.27, 0.04, 0.08, 0.08, 0.08, 0.18002, 0.08, 0.24] It means that link [10,13] has a probability of failure as [0.04] and since the link [3-5] is repeated thrice with probability of 0.03, 0.11 and 0.04, its probability of failure is [0.18] (third last element in the Probability array). For some reason instead of 0.18 it is showing 0.1802, which I cannot figure to why. Please see the attached code. If you see the file.txt and my output: the output is not displayed in sequence and that is what I need help with. I want this to display : Links = { [3,5] [5,4] [5,8] [7,8] [14,10] [14,13] [17,13] [14,18] [10,13] [14,13] [17,13] [12,13] [11,6] [11,9] [11,12] [11,19] [19,20] [15,20] [21,20] [20,21] [21,16] [21,22] } Prob = {[0.18] [0.15] [0.08] [0.04] [0.04] [0.04] [0.08] [0.04] [0.08] [0.08] [0.08] [0.08] [0.24] [0.24] [0.34] [0.27] [0.27]} If you can figure why the output is not generated in same sequence as in the file.txt for me, it will be very helpful. let me know if I explained correctly, and if you have any questions or doubts? On Sat, Apr 26, 2014 at 11:41 AM, Danny Yoo d...@hashcollision.orgwrote: I want to create two arrays using the above file (Links array and Prob array) that should give following output: *Links *= { [3,5] [5,4] [5,8] [7,8] [14,10] [14,13] [17,13] [14,18] [10,13] [14,13] [17,13] [12,13] [11,6] [11,9][11,12] [11,19] [19,20] [15,20] [21,20] [20,21] [21,16] [21,22] } *Prob *= {[0.28] [0.15] [0.08] [0.04] [0.04] [0.04] [0.08] [0.04] [0.08] [0.08] [0.08] [0.08] [0.24] [0.24] [0.34] [0.27] [0.27]} I don't understand how you develop this? The first list has 22 items the second 17. I would have expected them to be the same? In the Prob array the elements are less because if you read the note below: I said the links that are repeating for example [3,5] their probabilities get added and stored as a single value in the Prob array. But what will you plan to do with these values afterwards? I think Alan's point here is that if there's no direct relationship between the elements in Links and the elements in Probs, those values aren't going to be very useful to solve the rest of the problem.
Re: [Tutor] Help needed
err, set also is unordered. I can see you are using set for a reason, but has no concept of order. On Sat, Apr 26, 2014 at 3:20 PM, C Smith illusiontechniq...@gmail.comwrote: Just glancing at your work, I see you have curly braces around what looks like it should be a list. If you are concerned with the order of your output, dictionaries do not have a concept of order. On Sat, Apr 26, 2014 at 3:16 PM, Suhana Vidyarthi suhanavidyar...@gmail.com wrote: Hi Danny, Let me give you a high level brief of what I am doing: I am working on doing disaster aware routing considering the 24-node US network where I will be setting up connection between two any two nodes (I will select the source and destination nodes randomly). Also I have some links whose probability of failure is mentioned in the attached file. Other links, which are not mentioned in the file - we suppose their probability of failure is zero. So between the source-destination nodes, there will be multiple paths and I will select the one which has least probability of failure. Now to setup the connection between two nodes, I have to select a path whose probability of failure is least. To do that first I will calculate the risk of each path from the attached file and then select the path with least risk value. Did you get this part? I know it can be a bit confusing. Now I break the problem into parts: 1. I have to topology of the 24-node map 2. I have the link values of each link - where risk values are the probability of failure 3. I calculate the total probability of failure of each path (a path may have multiple links): Suppose my source node is a and destination node is b. I can setup a path between a to b via c or via d (a-c-b or a-d-c): Here I will check the risk values of a-c and c-b; also risk values of a-d and d-c. If the total risk valure of a-c-b is lower that risk value of a-d-c, then I select the path a-c-d to setup the connection. (again risk value = probability of failure) Now, I will first calculate the total probability of failure of each link (using the file.txt) and since some links are repeated their values will be added. The probabilities get added if a link is mentioned twice or thrice. For example: link 3—5 is repeated 3 times: in line one, it has a probability of failure as 0.03, in line two it is 0.11 and in line three it is 0.04. So the probability of failure for link 3—5 is 0.03+0.11+0.04 = 0.18 The length of each array will be same. You see the code I wrote: here is the output for it: Links - [('10', '13'), ('14', '18'), ('7', '8'), ('15', '20'), ('5', '8'), ('5', '4'), ('11', '9'), ('21', '22'), ('12', '13'), ('21', '20'), ('17', '13'), ('20', '21'), ('21', '16'), ('14', '10'), ('11', '12'), ('11', '19'), ('14', '13'), ('3', '5'), ('11', '6'), ('19', '20')] Probability - [0.04, 0.06, 0.04, 0.24, 0.08, 0.15, 0.08, 0.27, 0.04, 0.29, 0.08, 0.27, 0.27, 0.04, 0.08, 0.08, 0.08, 0.18002, 0.08, 0.24] It means that link [10,13] has a probability of failure as [0.04] and since the link [3-5] is repeated thrice with probability of 0.03, 0.11 and 0.04, its probability of failure is [0.18] (third last element in the Probability array). For some reason instead of 0.18 it is showing 0.1802, which I cannot figure to why. Please see the attached code. If you see the file.txt and my output: the output is not displayed in sequence and that is what I need help with. I want this to display : Links = { [3,5] [5,4] [5,8] [7,8] [14,10] [14,13] [17,13] [14,18] [10,13] [14,13] [17,13] [12,13] [11,6] [11,9] [11,12] [11,19] [19,20] [15,20] [21,20] [20,21] [21,16] [21,22] } Prob = {[0.18] [0.15] [0.08] [0.04] [0.04] [0.04] [0.08] [0.04] [0.08] [0.08] [0.08] [0.08] [0.24] [0.24] [0.34] [0.27] [0.27]} If you can figure why the output is not generated in same sequence as in the file.txt for me, it will be very helpful. let me know if I explained correctly, and if you have any questions or doubts? On Sat, Apr 26, 2014 at 11:41 AM, Danny Yoo d...@hashcollision.orgwrote: I want to create two arrays using the above file (Links array and Prob array) that should give following output: *Links *= { [3,5] [5,4] [5,8] [7,8] [14,10] [14,13] [17,13] [14,18] [10,13] [14,13] [17,13] [12,13] [11,6] [11,9][11,12] [11,19] [19,20] [15,20] [21,20] [20,21] [21,16] [21,22] } *Prob *= {[0.28] [0.15] [0.08] [0.04] [0.04] [0.04] [0.08] [0.04] [0.08] [0.08] [0.08] [0.08] [0.24] [0.24] [0.34] [0.27] [0.27]} I don't understand how you develop this? The first list has 22 items the second 17. I would have expected them to be the same? In the Prob array the elements are less because if you read the note below: I said the links that are repeating for example [3,5] their probabilities get added and stored as a single value in the Prob array. But what will you plan to do with these values afterwards? I think Alan's point here
Re: [Tutor] Help needed
Thanks for the response Smith, I was thinking make be I have done something incorrect and if there is some other function that can be used to display the output in desired order but don't see it possible thats why was wondering if any of you Python gurus have any inputs for me :-) On Sat, Apr 26, 2014 at 12:36 PM, C Smith illusiontechniq...@gmail.comwrote: err, set also is unordered. I can see you are using set for a reason, but has no concept of order. On Sat, Apr 26, 2014 at 3:20 PM, C Smith illusiontechniq...@gmail.comwrote: Just glancing at your work, I see you have curly braces around what looks like it should be a list. If you are concerned with the order of your output, dictionaries do not have a concept of order. On Sat, Apr 26, 2014 at 3:16 PM, Suhana Vidyarthi suhanavidyar...@gmail.com wrote: Hi Danny, Let me give you a high level brief of what I am doing: I am working on doing disaster aware routing considering the 24-node US network where I will be setting up connection between two any two nodes (I will select the source and destination nodes randomly). Also I have some links whose probability of failure is mentioned in the attached file. Other links, which are not mentioned in the file - we suppose their probability of failure is zero. So between the source-destination nodes, there will be multiple paths and I will select the one which has least probability of failure. Now to setup the connection between two nodes, I have to select a path whose probability of failure is least. To do that first I will calculate the risk of each path from the attached file and then select the path with least risk value. Did you get this part? I know it can be a bit confusing. Now I break the problem into parts: 1. I have to topology of the 24-node map 2. I have the link values of each link - where risk values are the probability of failure 3. I calculate the total probability of failure of each path (a path may have multiple links): Suppose my source node is a and destination node is b. I can setup a path between a to b via c or via d (a-c-b or a-d-c): Here I will check the risk values of a-c and c-b; also risk values of a-d and d-c. If the total risk valure of a-c-b is lower that risk value of a-d-c, then I select the path a-c-d to setup the connection. (again risk value = probability of failure) Now, I will first calculate the total probability of failure of each link (using the file.txt) and since some links are repeated their values will be added. The probabilities get added if a link is mentioned twice or thrice. For example: link 3—5 is repeated 3 times: in line one, it has a probability of failure as 0.03, in line two it is 0.11 and in line three it is 0.04. So the probability of failure for link 3—5 is 0.03+0.11+0.04 = 0.18 The length of each array will be same. You see the code I wrote: here is the output for it: Links - [('10', '13'), ('14', '18'), ('7', '8'), ('15', '20'), ('5', '8'), ('5', '4'), ('11', '9'), ('21', '22'), ('12', '13'), ('21', '20'), ('17', '13'), ('20', '21'), ('21', '16'), ('14', '10'), ('11', '12'), ('11', '19'), ('14', '13'), ('3', '5'), ('11', '6'), ('19', '20')] Probability - [0.04, 0.06, 0.04, 0.24, 0.08, 0.15, 0.08, 0.27, 0.04, 0.29, 0.08, 0.27, 0.27, 0.04, 0.08, 0.08, 0.08, 0.18002, 0.08, 0.24] It means that link [10,13] has a probability of failure as [0.04] and since the link [3-5] is repeated thrice with probability of 0.03, 0.11 and 0.04, its probability of failure is [0.18] (third last element in the Probability array). For some reason instead of 0.18 it is showing 0.1802, which I cannot figure to why. Please see the attached code. If you see the file.txt and my output: the output is not displayed in sequence and that is what I need help with. I want this to display : Links = { [3,5] [5,4] [5,8] [7,8] [14,10] [14,13] [17,13] [14,18] [10,13] [14,13] [17,13] [12,13] [11,6] [11,9] [11,12] [11,19] [19,20] [15,20] [21,20] [20,21] [21,16] [21,22] } Prob = {[0.18] [0.15] [0.08] [0.04] [0.04] [0.04] [0.08] [0.04] [0.08] [0.08] [0.08] [0.08] [0.24] [0.24] [0.34] [0.27] [0.27]} If you can figure why the output is not generated in same sequence as in the file.txt for me, it will be very helpful. let me know if I explained correctly, and if you have any questions or doubts? On Sat, Apr 26, 2014 at 11:41 AM, Danny Yoo d...@hashcollision.orgwrote: I want to create two arrays using the above file (Links array and Prob array) that should give following output: *Links *= { [3,5] [5,4] [5,8] [7,8] [14,10] [14,13] [17,13] [14,18] [10,13] [14,13] [17,13] [12,13] [11,6] [11,9][11,12] [11,19] [19,20] [15,20] [21,20] [20,21] [21,16] [21,22] } *Prob *= {[0.28] [0.15] [0.08] [0.04] [0.04] [0.04] [0.08] [0.04] [0.08] [0.08] [0.08] [0.08] [0.24] [0.24] [0.34] [0.27] [0.27]} I don't understand how you develop this? The first list has 22 items the
Re: [Tutor] Help needed
As others have pointed out, a mapping/dictionary or just a list of lists seems like how you would want to organize the data for input. I think your problem is insistence on using sets. I am no Python guru, but I think this list is more for exploratory learning of Python. I think people are trying to get you to answer your own questions or coax more information from you rather than simply provide their own version of your code. On Sat, Apr 26, 2014 at 3:48 PM, Suhana Vidyarthi suhanavidyar...@gmail.com wrote: Thanks for the response Smith, I was thinking make be I have done something incorrect and if there is some other function that can be used to display the output in desired order but don't see it possible thats why was wondering if any of you Python gurus have any inputs for me :-) On Sat, Apr 26, 2014 at 12:36 PM, C Smith illusiontechniq...@gmail.comwrote: err, set also is unordered. I can see you are using set for a reason, but has no concept of order. On Sat, Apr 26, 2014 at 3:20 PM, C Smith illusiontechniq...@gmail.comwrote: Just glancing at your work, I see you have curly braces around what looks like it should be a list. If you are concerned with the order of your output, dictionaries do not have a concept of order. On Sat, Apr 26, 2014 at 3:16 PM, Suhana Vidyarthi suhanavidyar...@gmail.com wrote: Hi Danny, Let me give you a high level brief of what I am doing: I am working on doing disaster aware routing considering the 24-node US network where I will be setting up connection between two any two nodes (I will select the source and destination nodes randomly). Also I have some links whose probability of failure is mentioned in the attached file. Other links, which are not mentioned in the file - we suppose their probability of failure is zero. So between the source-destination nodes, there will be multiple paths and I will select the one which has least probability of failure. Now to setup the connection between two nodes, I have to select a path whose probability of failure is least. To do that first I will calculate the risk of each path from the attached file and then select the path with least risk value. Did you get this part? I know it can be a bit confusing. Now I break the problem into parts: 1. I have to topology of the 24-node map 2. I have the link values of each link - where risk values are the probability of failure 3. I calculate the total probability of failure of each path (a path may have multiple links): Suppose my source node is a and destination node is b. I can setup a path between a to b via c or via d (a-c-b or a-d-c): Here I will check the risk values of a-c and c-b; also risk values of a-d and d-c. If the total risk valure of a-c-b is lower that risk value of a-d-c, then I select the path a-c-d to setup the connection. (again risk value = probability of failure) Now, I will first calculate the total probability of failure of each link (using the file.txt) and since some links are repeated their values will be added. The probabilities get added if a link is mentioned twice or thrice. For example: link 3—5 is repeated 3 times: in line one, it has a probability of failure as 0.03, in line two it is 0.11 and in line three it is 0.04. So the probability of failure for link 3—5 is 0.03+0.11+0.04 = 0.18 The length of each array will be same. You see the code I wrote: here is the output for it: Links - [('10', '13'), ('14', '18'), ('7', '8'), ('15', '20'), ('5', '8'), ('5', '4'), ('11', '9'), ('21', '22'), ('12', '13'), ('21', '20'), ('17', '13'), ('20', '21'), ('21', '16'), ('14', '10'), ('11', '12'), ('11', '19'), ('14', '13'), ('3', '5'), ('11', '6'), ('19', '20')] Probability - [0.04, 0.06, 0.04, 0.24, 0.08, 0.15, 0.08, 0.27, 0.04, 0.29, 0.08, 0.27, 0.27, 0.04, 0.08, 0.08, 0.08, 0.18002, 0.08, 0.24] It means that link [10,13] has a probability of failure as [0.04] and since the link [3-5] is repeated thrice with probability of 0.03, 0.11 and 0.04, its probability of failure is [0.18] (third last element in the Probability array). For some reason instead of 0.18 it is showing 0.1802, which I cannot figure to why. Please see the attached code. If you see the file.txt and my output: the output is not displayed in sequence and that is what I need help with. I want this to display : Links = { [3,5] [5,4] [5,8] [7,8] [14,10] [14,13] [17,13] [14,18] [10,13] [14,13] [17,13] [12,13] [11,6] [11,9] [11,12] [11,19] [19,20] [15,20] [21,20] [20,21] [21,16] [21,22] } Prob = {[0.18] [0.15] [0.08] [0.04] [0.04] [0.04] [0.08] [0.04] [0.08] [0.08] [0.08] [0.08] [0.24] [0.24] [0.34] [0.27] [0.27]} If you can figure why the output is not generated in same sequence as in the file.txt for me, it will be very helpful. let me know if I explained correctly, and if you have any questions or doubts? On Sat, Apr 26, 2014 at 11:41 AM, Danny Yoo d...@hashcollision.orgwrote:
Re: [Tutor] Help With an Assignment
On 25/04/14 20:52, jordan smallwood wrote: Hello, I am new to Python. I mean completely new and we're working on this problem set where they give us specs and we have to build something based off these specs. I have no idea what they're asking. Its pretty clear. They want you to build a module containing two functions. Now how much of that do you not understand? Also do you know which version of python you are using - it can make a difference when you get to the details. And which operating system - less important for a task like this. -- 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 With an Assignment
jordan smallwood jsmallwoo...@yahoo.com.dmarc.invalid Wrote in message: Do you know what a module is? Can you use a text editor to create one? Do you know what a function looks like? Try writing the first one they asked. Post it here, along with some test code showing it works, or describe what goes wrong. And while you're at it, switch your emails to plain text, and tell us at least what version of Python you're trying to use. -- DaveA ___ 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
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] 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] Help Noob Question
On 03/28/2014 02:17 AM, Alan Gauld wrote: On 27/03/14 21:01, Chris “Kwpolska” Warrick wrote: On Mar 27, 2014 8:58 PM, Alan Gauld alan.ga...@btinternet.com mailto:alan.ga...@btinternet.com wrote: On 27/03/14 06:43, Leo Nardo wrote: Im on windows 8 and i need to open a file called string1.py that is on my desktop, Thats your first problem. Its usually a bad idea to store your python code on the desktop, because the desktop is a pain to find from a command line. Painful? How painful can `cd Desktop` be? Certainly less than `D:` followed by `cd PythonProjects`… Because the desktop is hardly ever anywhere near where the cmd prompt lands you. So cd desktop usually results in an error and typing the full path (even with directory completion, Mark) is a royal pain because you have to remember where it is. There is no ~ shortcut in Windows. On my system that means typing something like: C:\Documents and Settings\alang\Desktop Can't you make a symlink pointing to Desktop? (in C:\ or anywhere else) or some such nonsense, complete with spaces in the path that add to the pain. Now I probably could use something like cd %HOMEPATH% to get to what Windows laughingly considers my 'home' directory and then find it from there but even so its not always obvious depending on the windows version and the install options used. And of course if the file happens to be on the all users Desktop looking in my local Desktop doesn't help. I find it much easier to know where my Python code lives from wherever I happen to find myself in the labrynthian file system that is Windows. Well, all filesystems are labyrinthians, AFAIK (at least, for people like me who cannot learn by heart). I never know where things are are, in my box (Linux), apart from my own home. d ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Help Noob Question
On 28/03/2014 01:17, Alan Gauld wrote: On 27/03/14 21:01, Chris “Kwpolska” Warrick wrote: On Mar 27, 2014 8:58 PM, Alan Gauld alan.ga...@btinternet.com mailto:alan.ga...@btinternet.com wrote: On 27/03/14 06:43, Leo Nardo wrote: Im on windows 8 and i need to open a file called string1.py that is on my desktop, Thats your first problem. Its usually a bad idea to store your python code on the desktop, because the desktop is a pain to find from a command line. Painful? How painful can `cd Desktop` be? Certainly less than `D:` followed by `cd PythonProjects`… Because the desktop is hardly ever anywhere near where the cmd prompt lands you. So cd desktop usually results in an error and typing the full path (even with directory completion, Mark) is a royal pain because you have to remember where it is. There is no ~ shortcut in Windows. The point is you type it once and then rerun the command from the run prompt. How can anything be easier? On my system that means typing something like: C:\Documents and Settings\alang\Desktop or some such nonsense, complete with spaces in the path that add to the pain. Now I probably could use something like cd %HOMEPATH% to get to what Windows laughingly considers my 'home' directory and then find it from there but even so its not always obvious depending on the windows version and the install options used. And of course if the file happens to be on the all users Desktop looking in my local Desktop doesn't help. I find it much easier to know where my Python code lives from wherever I happen to find myself in the labrynthian file system that is Windows. -- 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] Help Noob Question
On 28/03/14 09:28, spir wrote: On 03/28/2014 02:17 AM, Alan Gauld wrote: you have to remember where it is. There is no ~ shortcut in Windows. On my system that means typing something like: C:\Documents and Settings\alang\Desktop Can't you make a symlink pointing to Desktop? (in C:\ or anywhere else) You could, and that would help a little. But the problem on Windows is that what appears on the Desktop *display* is an amalgam of (up to 3?) different folders in the file system. So just because you see an icon on the 'desktop' doesn't mean you actually know which folder it is in. Secondly this correlation between desktop folder and desktop display means that's a bad place to store python files since every file you create will add to the clutter of icons on your display. In my python projects file I have over 100 small test files. That would be a lot of icons messing up my screen. So because of a combination of: a) path complexity, b) the disconnect between display and physical location and c) the correlation between files and displayed icons I recommend not using the desktop to store python files. Of course everyone is free to ignore this recommendation, it's just my experience/opinion. :-) Well, all filesystems are labyrinthians Yes but Windows is much more so because of the disconnect between how it displays things in visual tools and how it stores things on the disk (and the fact that it has multiple disks often with partially duplicated file structures!) Very few things wind up in one place only. For a user, this is ameliorated by the use of Libraries to group folders with similar content, but they only serve to make life even harder for the programmer! [Even worse is the iPad with its insistance on storing files with the app that last worked on them. A moving target indeed, even assuming you can find the files in the first place. Stupid decision.] -- 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 Noob Question
On Fri, Mar 28, 2014 at 2:17 AM, Alan Gauld alan.ga...@btinternet.com wrote: On 27/03/14 21:01, Chris “Kwpolska” Warrick wrote: Painful? How painful can `cd Desktop` be? Certainly less than `D:` followed by `cd PythonProjects`… Because the desktop is hardly ever anywhere near where the cmd prompt lands you. I just tested on my Windows 7 box. It got me to C:\Users\Kwpolska. `cd Desktop` is enough. I also tested on a third-party’s XP box. C:\Documents and Settings\[username]. `cd Desktop`, too (though it’s locale-dependent). Does not look far from the desktop, does it? Well, the only places where this might not work are Administrator prompts in Vista-and-newer (which there is NO REAL REASON to use for Python) — or possibly some ultra-crazy corporate environments (but you should not be learning Python there — and if you are working there, you know how to work with the command line/Windows/source control already). Or, of course, systems where you changed something and it is not your profile directory — but it’s your doing. So, it’s pretty much the home directory everywhere you should be concerned with. you have to remember where it is. There is no ~ shortcut in Windows. On my system that means typing something like: C:\Documents and Settings\alang\Desktop or just cd %USERPROFILE%. Different drives would make you jump to %HOMEDRIVE% and then to %HOMEPATH%. Can't you make a symlink pointing to Desktop? (in C:\ or anywhere else) You could, and that would help a little. But the problem on Windows is that what appears on the Desktop *display* is an amalgam of (up to 3?) different folders in the file system. So just because you see an icon on the 'desktop' doesn't mean you actually know which folder it is in. But, for user-created files, it always goes to %USERPROFILE%/Desktop. Secondly this correlation between desktop folder and desktop display means that's a bad place to store python files since every file you create will add to the clutter of icons on your display. In my python projects file I have over 100 small test files. That would be a lot of icons messing up my screen. Create a folder on the desktop, or even in the home directory. A much nicer place than the drive root — and a much modern way to store it (drive root sounds DOS-y) -- Chris “Kwpolska” Warrick http://kwpolska.tk PGP: 5EAAEA16 stop html mail | always bottom-post | only UTF-8 makes sense ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Help Noob Question
Hi Leo, On 27 March 2014 08:43, Leo Nardo waterfallr...@gmail.com wrote: Im on windows 8 and i need to open a file called string1.py that is on my desktop, in both the interpreter and notepad++, so that i can work on it. I already have it open in notepad, but for the life of me cannot figure out how to open it in the interpreter. Invalid syntax is the error message when i type in python string1.py into the interpreter! maybe a dumb question but i would appreciate the help for sure. thanks :) I know a lot's been said already, but nothwithstanding, here's my answer to your question(s): You need to type python string1.py into a Windows command prompt, not directly into a running Python interpreter. For that command to work as shown, at least 2 things need to be true: 1) The Python interpreter (python.exe) must be on the system PATH (so the operating system will be able to locate it) 2) The file string1.py must be in the Current Directory (folder) of the Windows command prompt. This is the path location displayed in the prompt to the left of the cursor. A simple way to open a command prompt with the current directory set to a known location, is to open a Windows file explorer window, then browse to the folder you'd like a command prompt in, then overtype the address in the explorer window with cmd and press Enter. This little feature makes it trivial to open command prompts in any chosen folder as needed. (Note: This feature is only available in Windows 7 and higher.) Walter ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Help Noob Question
* Chris “Kwpolska” Warrick kwpol...@gmail.com [2014-03-28 16:27]: Create a folder on the desktop, or even in the home directory. A much nicer place than the drive root — and a much modern way to store it (drive root sounds DOS-y) I'll have to disagree with this statement. Dropping all your files in you Desktop directory puts all the files ON the Desktop, which quickly becomes a mess. Regardless of whether it's a new directory at the base, or a new directory under your User directory, you should at least have a dedicated directory to put the files. I'm not discussing the merits of one place over the other, just that simple organization is a good thing. Put it wherever you want, but at least keep it organized. Dropping everything in Desktop is not organized. -- David Rock da...@graniteweb.com ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Help Noob Question
On 28/03/14 15:27, Chris “Kwpolska” Warrick wrote: On Fri, Mar 28, 2014 at 2:17 AM, Alan Gauld alan.ga...@btinternet.com wrote: Because the desktop is hardly ever anywhere near where the cmd prompt lands you. I just tested on my Windows 7 box. It got me to C:\Users\Kwpolska. `cd Desktop` is enough. I also tested on a third-party’s XP box. C:\Documents and Settings\[username]. `cd Desktop`, too (though it’s locale-dependent). Does not look far from the desktop, does it? True when you first open the DOS box, but not after you've been using it for a while. I usually find I've moved around several folders and even several disks. Python) — or possibly some ultra-crazy corporate environments (but you should not be learning Python there — and if you are working there, you know how to work with the command line/Windows/source control already). Both are true for me, and a large part of why I wouldn't put stuff on the desktop. For example my desktop was made up of my personal desktop, the PC all-user desktop and the corporate shared desktop (only when connected to the corporate network). Knowing which files/icons belonged to which location was a nightmare. or just cd %USERPROFILE%. Different drives would make you jump to %HOMEDRIVE% and then to %HOMEPATH%. Which is true for files I create but not for other users of the PC or for shared desktops. And its still a lot to type compared to Unix (~) or using a drive root. Can't you make a symlink pointing to Desktop? (in C:\ or anywhere else) You could, and that would help a little. But the problem on Windows is that what appears on the Desktop *display* is an amalgam of (up to 3?) different folders in the file system. So just because you see an icon on the 'desktop' doesn't mean you actually know which folder it is in. But, for user-created files, it always goes to %USERPROFILE%/Desktop. But which user? It may not be me that created the file. And I may have deliberately copied/saved it to one of the shared desktops a long time ago and forgotten. Create a folder on the desktop, or even in the home directory. I agree a folder is more sensible and avoids the icon overkill but the OP specifically had his *file* on the desktop. nicer place than the drive root — and a much modern way to store it (drive root sounds DOS-y) I accept that but its still the shortest absolute path to type on Windows! And if you are a programmer typing is what you wind up doing a lot of! -- 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 Noob Question
Hello, What do you mean by open it in the interpreter? Do you want to open it and read from it its content? or do you want to execute its python code within the interpreter? Best 2014-03-27 7:43 GMT+01:00 Leo Nardo waterfallr...@gmail.com: Im on windows 8 and i need to open a file called string1.py that is on my desktop, in both the interpreter and notepad++, so that i can work on it. I already have it open in notepad, but for the life of me cannot figure out how to open it in the interpreter. Invalid syntax is the error message when i type in python string1.py into the interpreter! maybe a dumb question but i would appreciate the help for sure. thanks :) ___ 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] Help Noob Question
On 27/03/2014 08:55, David Palao wrote: Hello, What do you mean by open it in the interpreter? Do you want to open it and read from it its content? or do you want to execute its python code within the interpreter? Best 2014-03-27 7:43 GMT+01:00 Leo Nardo waterfallr...@gmail.com: Im on windows 8 and i need to open a file called string1.py that is on my desktop, in both the interpreter and notepad++, so that i can work on it. I already have it open in notepad, but for the life of me cannot figure out how to open it in the interpreter. Invalid syntax is the error message when i type in python string1.py into the interpreter! maybe a dumb question but i would appreciate the help for sure. thanks :) Please don't top post on this list. -- 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] Help Noob Question
Leo Nardo waterfallr...@gmail.com writes: Im on windows 8 and i need to open a file called string1.py that is on my desktop, in both the interpreter and notepad++, so that i can work on it. It's not clear what you want. What does it mean to you for a Python program to be “open in the interpreter”? You have opened the file in a text editor, which is fine; the editor presents the file contents for you to edit and save. There isn't really an equivalent with the Python interactive interpreter. It takes its input from you typing at the console. Do you mean “import the module”? That executes the module and makes it available in a distinct namespace. But it doesn't seem to be quite what you're asking. Do you mean “run the module as a program”? That is done *non*-interactively, so you don't do it at the interactive Python interpreter. Instead, you do it by issuing a command at your operating system's command prompt. I already have it open in notepad, but for the life of me cannot figure out how to open it in the interpreter. Welcome to the forum :-) Hopefully you can make clearer what it is you want to do. -- \“Intellectual property is to the 21st century what the slave | `\ trade was to the 16th.” —David Mertz | _o__) | Ben Finney ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Help Noob Question
Leo Nardo waterfallr...@gmail.com Wrote in message Im on windows 8 and i need to open a file called string1.py that is on my desktop, in both the interpreter and notepad++, so that i can work on it. I already have it open in notepad, but for the life of me cannot figure out how to open it in the interpreter. Invalid syntax is the error message when i type in python string1.py into the interpreter! maybe a dumb question but i would appreciate the help for sure. thanks :) . (Please post in text mode, not html. Sometimes html is a pain on a text mailing list like this one. ) I'm assuming you're asking how to *run* your string1.py script. First you need a shell prompt. For Windows, that's cmd.exe, which you usually get by opening a DOS box. Then at the cmd prompt, you type python string1.py That will start the interpreter, import the script, run the script, and exit the interpreter. -- DaveA ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Help Noob Question
On 27/03/14 06:43, Leo Nardo wrote: Im on windows 8 and i need to open a file called string1.py that is on my desktop, Thats your first problem. Its usually a bad idea to store your python code on the desktop, because the desktop is a pain to find from a command line. Instead create a folder at the top level of a disk - if you have a D drive then D:\PythonProjects or some such name. Move your file into that folder Then you can start a CMD shell window by hitting Windows-R and typing cmd into the dialog that opens. That should open a CMD shell(aka DOS box) with a prompt like: C:\WINDOWS or similar At that prompt type python D:\PythonProjects\string1.py And your file should run, display any output (or errors) and stop. error message when i type in python string1.py into the interpreter! You never type 'python' into the Python interpreter. You run python propgrams by typing 'python progmname.py' into your Operating system shell(CMD.exe on windows) You can also run them by double clicking the file in Windows explorer but that often results in a DOS box opening, the code running and the DOS box closing again too fast for you to see anything. So opening the DOS box in advance as described above is usually better. Get used to using the OS command line, programmers tend to use it a lot. (In fact you might want to create a shortcut on your desktop/start screen to open it...) :-) 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 Noob Question
On Mar 27, 2014 8:58 PM, Alan Gauld alan.ga...@btinternet.com wrote: On 27/03/14 06:43, Leo Nardo wrote: Im on windows 8 and i need to open a file called string1.py that is on my desktop, Thats your first problem. Its usually a bad idea to store your python code on the desktop, because the desktop is a pain to find from a command line. Painful? How painful can `cd Desktop` be? Certainly less than `D:` followed by `cd PythonProjects`… -- Chris “Kwpolska” Warrick ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Help Noob Question
On 27/03/2014 19:56, Alan Gauld wrote: On 27/03/14 06:43, Leo Nardo wrote: Im on windows 8 and i need to open a file called string1.py that is on my desktop, Thats your first problem. Its usually a bad idea to store your python code on the desktop, because the desktop is a pain to find from a command line. I disagree with this. From the run prompt I use cmd /F:ON /T:02 /K cd your\code\path /F:ON Enable file and directory name completion characters /T:fg Sets the foreground/background colors /K Carries out the command specified by string -- 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] Help Noob Question
On 27/03/14 21:01, Chris “Kwpolska” Warrick wrote: On Mar 27, 2014 8:58 PM, Alan Gauld alan.ga...@btinternet.com mailto:alan.ga...@btinternet.com wrote: On 27/03/14 06:43, Leo Nardo wrote: Im on windows 8 and i need to open a file called string1.py that is on my desktop, Thats your first problem. Its usually a bad idea to store your python code on the desktop, because the desktop is a pain to find from a command line. Painful? How painful can `cd Desktop` be? Certainly less than `D:` followed by `cd PythonProjects`… Because the desktop is hardly ever anywhere near where the cmd prompt lands you. So cd desktop usually results in an error and typing the full path (even with directory completion, Mark) is a royal pain because you have to remember where it is. There is no ~ shortcut in Windows. On my system that means typing something like: C:\Documents and Settings\alang\Desktop or some such nonsense, complete with spaces in the path that add to the pain. Now I probably could use something like cd %HOMEPATH% to get to what Windows laughingly considers my 'home' directory and then find it from there but even so its not always obvious depending on the windows version and the install options used. And of course if the file happens to be on the all users Desktop looking in my local Desktop doesn't help. I find it much easier to know where my Python code lives from wherever I happen to find myself in the labrynthian file system that is Windows. -- 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
List On Mar 18, 2014 11:08 AM, y j yashp...@gmail.com wrote: how can i split a word into letters in python 2.7.6? -- Y D Jain ___ 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] help
On 18/03/14 18:21, Joel Goldstick wrote: List On Mar 18, 2014 11:08 AM, y j yashp...@gmail.com mailto:yashp...@gmail.com wrote: how can i split a word into letters in python 2.7.6? or more specifically list(aString) - lowercase and with params. That will give you a list of the individual letters. Assuming that's what you mean. As David says there are several other options depending on what exactly you want. -- 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 with Guess the number script
On Mar 11, 2014, at 7:50 PM, William Ray Wing w...@mac.com wrote: Simple. In Mail Preferences - Composing - Message Format - Plain Text (Your setting is probably currently Rich Text.) Got it, hopefully that helps. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Help with Guess the number script
On Mar 11, 2014, at 1:57 AM, Alan Gauld alan.ga...@btinternet.com wrote: OK so far, you don't need all the print statements but that's just a style issue. (You could just insert '\n' characters instead.) You’re right, I’m actually not sure why I did it that way. if guess secret - 10 or guess secret - 10: This is the right idea for cutting the line count but you have the comparison values wrong. Look back to earlier emails, you are repeating the same error as before. Manually think through what happens in the line above if guess == secret. Oh, do you mean it should be = and =?? I’m not sure why that would work, because if guess==secret I have another statement in my code that takes care of that. I didn’t want to add my whole code because it’s too long but that is in there. And then once you get that fixed you can rewrite using the chained comparison trick to tidy it up. ie if not (lower limit guess upper limit): I see what you’re saying about the chained comparison. What I’m having problems with is condensing it to half the lines of code so I don’t have to have the same conditionals under both ‘too low’ and ‘to high’. If that makes sense. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Help with Guess the number script
On Mar 10, 2014, at 11:18 PM, Dave Angel da...@davea.name wrote: if guess secret - 10 or guess secret - 10: Think about that line. You might even want to put in a separate function to test what it does. HINT: it's wrong. Got it! I realized what I was doing wrong. I needed that plus sign for the too high part of it and what you said helped me figure it out! Thanks Dave, all you actually! ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Help with Guess the number script
On 03/12/2014 05:13 AM, Scott Dunning wrote: if guess secret - 10 or guess secret - 10: This is the right idea for cutting the line count but you have the comparison values wrong. Look back to earlier emails, you are repeating the same error as before. Manually think through what happens in the line above if guess == secret. Oh, do you mean it should be = and =?? I’m not sure why that would work, because if guess==secret I have another statement in my code that takes care of that. I didn’t want to add my whole code because it’s too long but that is in there. Such errors are either obvious or invisible. A remedy is often to figure the problem on paper (or in your head if you're good at thinking visually). Here, just draw a line segment with secret in the middle and the interval borders around. Then, write there on the drawing the _values_ of the borders, as arithmetic expressions. d ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Help with Guess the number script
Scott W Dunning scott@cox.net Wrote in message: On Mar 11, 2014, at 7:50 PM, William Ray Wing w...@mac.com wrote: Simple. In Mail Preferences - Composing - Message Format - Plain Text (Your setting is probably currently Rich Text.) Got it, hopefully that helps. Perfect, thanks. -- DaveA ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Help with Guess the number script
Such errors are either obvious or invisible. A remedy is often to figure the problem on paper (or in your head if you're good at thinking visually). Here, just draw a line segment with secret in the middle and the interval borders around. Then, write there on the drawing the _values_ of the borders, as arithmetic expressions. Very much so. Diagrams are important. Not everything is textual. (Which you might consider with some irony based on some of the meta-discussion on this thread.) See some of the problem-solving heuristics described in: http://en.wikipedia.org/wiki/How_to_Solve_It Can you think of a picture or a diagram that might help you understand the problem? ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Help with Guess the number script
Scott W Dunning swdunn...@cox.net Wrote in message: Would you please stop posting in html? def print_hints(secret, guess):   if guess 1 or guess 100:     print     print Out of range!     print   if guess secret:     print     print Too low!   if guess secret:     print     print Too high!   if guess secret - 10 or guess secret - 10: Think about that line. You might even want to put in a separate function to test what it does. HINT: it's wrong.     print You are cold!     print     print Sorry please try again.     print     print   elif guess secret - 5 or guess secret - 5: Same mistake.     print You are warmer!     print     print Sorry please try again.     print     print   else:     print You're on fire!!     print     print Sorry please try again.     print     print -- DaveA ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Help with Guess the number script
On Mar 10, 2014, at 11:18 PM, Dave Angel da...@davea.name wrote: Scott W Dunning swdunn...@cox.net Wrote in message: Would you please stop posting in html? I don’t know what you mean? I just use the text for my email provider. It’s not html? I types up the code I had in the script.___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Help with Guess the number script
On Mar 10, 2014, at 11:18 PM, Dave Angel da...@davea.name wrote: Where are you guys using the forum? Through google? I was using that at first but someone complained about something that google does and told me to get it through my email. That’s what I’m doing now and I get bombarded with about 500 emails a day but I’m still doing something wrong? I’d rather go though a site to view the forum anyways, it seems way easier then having to sort through hundreds of emails. I’m not trying to be rude I’m just wondering, I don’t want to be irritating people if by doing something wrong. Thanks again for all of your help! ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Help with Guess the number script
On 11/03/14 07:42, Scott W Dunning wrote: On Mar 10, 2014, at 11:18 PM, Dave Angel da...@davea.name wrote: Where are you guys using the forum? Personally I use the news feed from Gmane.org I read it in Thunderbird (or occasionally via a newsreader on my smartphone/tablet). You can also read it online in a browser if you must. ...someone complained about something that google does and told me to get it through my email. Its possible to get Google to behave properly but it seems like its usually easier to switch to a mail tool... :-( That’s what I’m doing now and I get bombarded with about 500 emails a day Not from the tutor list though. It only has a few mails normally - less than 50 most days. But you should be abler to set up auto filtering rules on your mail tool to route all the tutor mails into a separate folder for reading later. Also if you turn on threading in your mail tool for that folder you'll get them grouped by subject. I’d rather go though a site to view the forum anyways, I can never understand why people like web forums, they are so limited in functionality. But if you must go that way try the gmane feed. Tutor is in (with a zillion other Python lists) under comp.python.tutor. it seems way easier then having to sort through hundreds of emails. See the comments above, also consider digest mode. I’m not trying to be rude I’m just wondering, It's ok, everyone is allowed preferences. :-) What tends to irritate folks is the HTML content which different readers display differently. Especially the indentation which often gets lost. You need to explicitly go into your mail tool options and select plain text rather than rich text or HTML which will likely be the default. You can often tell if you don't have plain text because you will have options to change font, size, colour etc. You can't do any of that with plain text. But modern mail tools often make it very difficult to set plain text, especially web based ones. -- 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 with Guess the number script
On 11/03/14 04:07, Scott W Dunning wrote: On Mar 8, 2014, at 3:57 AM, spir denis.s...@gmail.com mailto:denis.s...@gmail.com wrote: And now that you have the right set of tests you can half the number of lines by combining your if conditions again, like you had in the original post. ie. Bring your hot/cold/warm tests together. I think that was me rather than Denis, but that's irrelevant... This is what I have right now, obviously it’s not working. I’ve been playing around with it but I’m just not seeing where I’m going wrong. Any suggestions are greatly appreciated! def print_hints(secret, guess): if guess 1 or guess 100: print print Out of range! print if guess secret: print print Too low! if guess secret: print print Too high! OK so far, you don't need all the print statements but that's just a style issue. (You could just insert '\n' characters instead.) if guess secret - 10 or guess secret - 10: This is the right idea for cutting the line count but you have the comparison values wrong. Look back to earlier emails, you are repeating the same error as before. Manually think through what happens in the line above if guess == secret. And then once you get that fixed you can rewrite using the chained comparison trick to tidy it up. ie if not (lower limit guess upper limit): 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 with Guess the number script
On 03/11/2014 04:32 AM, Scott W Dunning wrote: On Mar 8, 2014, at 11:50 AM, Scott dunning swdunn...@cox.net wrote: And now that you have the right set of tests you can half the number of lines by combining your if conditions again, like you had in the original post. ie. Bring your hot/cold/warm tests together. I’m having a hard time doing that because the guess can be either too low or too high but it is always either cold, warm, or on fire. I can’t figure out how to make it work with out splitting the cold, warm and on fire under two branches, one too low and one too high. Any suggestions? Well, what is the meaning of absolute value? Cold, warm, or on fire depend on the distance between both numbers, secret and guess, right? d ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Help with Guess the number script
On 03/11/2014 09:57 AM, Alan Gauld wrote: On 11/03/14 04:07, Scott W Dunning wrote: On Mar 8, 2014, at 3:57 AM, spir denis.s...@gmail.com mailto:denis.s...@gmail.com wrote: And now that you have the right set of tests you can half the number of lines by combining your if conditions again, like you had in the original post. ie. Bring your hot/cold/warm tests together. I think that was me rather than Denis, but that's irrelevant... You are right! d ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Help with Guess the number script
On 03/11/2014 05:07 AM, Scott W Dunning wrote: On Mar 8, 2014, at 3:57 AM, spir denis.s...@gmail.com wrote: Well done. And now that you have the right set of tests you can half the number of lines by combining your if conditions again, like you had in the original post. ie. Bring your hot/cold/warm tests together. So below is what I finally came up with that works. I’m trying to condense it to half the number of lines like Denis suggested. I was hoping to clarify a couple things if you guys don’t mind…. I wanna make sure I understand how this code is working. So, from what I gather it first checks to see if the ‘guess’ is out of range and if that is false it continues to the next ‘if’ statement checking wether it’s too low. Now this is where I’m not 100% sure if the too low ‘if’ statement is false does it skip everything that is nested below it (you are cold, warm, on fire) and go to the ‘if statement checking if it’s too high? And now say the too low ‘if’ statement is true, because it’s an ‘if’ the code does not stop it continues but when it gets to the elif the code stops? def print_hints(secret, guess): if guess 1 or guess 100: print print Out of range! print I think here if the condition is true, you could just quit the function (return), no? The rest does not make much sense, I guess... if guess secret: print print Too low! if guess secret - 10: print You are cold! print print Sorry please try again. print print elif guess secret - 5: print You are warmer! print print Sorry please try again. print print else: print You're on fire!! print print Sorry please try again. print print if guess secret: print print Too high! if guess secret + 10: print You are cold! print print Sorry please try again. print print elif guess secret + 5: print You are warmer! print print Sorry please try again. print print else: print You're on fire!! print print Sorry please try again. print print This is what I have right now, obviously it’s not working. I’ve been playing around with it but I’m just not seeing where I’m going wrong. Any suggestions are greatly appreciated! def print_hints(secret, guess): if guess 1 or guess 100: print print Out of range! print if guess secret: print print Too low! if guess secret: print print Too high! if guess secret - 10 or guess secret - 10: print You are cold! print print Sorry please try again. print print elif guess secret - 5 or guess secret - 5: print You are warmer! print print Sorry please try again. print print else: print You're on fire!! print print Sorry please try again. print print Below, the temperature hint and low/high hint are logically independant. The first one depends on the distance between secret and guess numbers, the second one depends on their relative values (greater/smaller). And the second hint (low/high) only makes sense iff the player did not win, meaning iff not on fire!. However, both are related to the difference. Conceptually, after having passed the test out-of-range, I would start with something like: diff = guess - secret # (we know guess is in range) # temperature hint dist = abs(diff) if dist == 0: ... on fire! return elif dist 5: ... # (we know secret was not found) # high/low hint neg = diff 0 ... As an exercise, you could write each kind of hint in a separate tool func, and call each one only when relevant. Denis ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Help with Guess the number script
On Mar 11, 2014, at 1:49 AM, Alan Gauld alan.ga...@btinternet.com wrote: Not from the tutor list though. It only has a few mails normally - less than 50 most days. Actually now that you say that most of the emails are coming through the reg python-lists, not the tutor section. I guess I should just unsubscribe from python-lists because my questions are going through the tutor section for awhile. I’m not trying to be rude I’m just wondering, What tends to irritate folks is the HTML content which different readers display differently. Especially the indentation which often gets lost. You need to explicitly go into your mail tool options and select plain text rather than rich text or HTML which will likely be the default. You can often tell if you don't have plain text because you will have options to change font, size, colour etc. You can't do any of that with plain text. But modern mail tools often make it very difficult to set plain text, especially web based ones. Yeah, I had no idea that my messages were coming through in HTML, nor what it looked like until someone sent me a section showing me what it looked like, I can see how that would be frustrating. I’m using the mail app on my macbook pro, any suggestions on how to stop it from going out as html? Do I need to change the font? Also, I think last time I sent a section of my code I copy and pasted it from my script, could that be the problem? Thanks again! ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Help with Guess the number script
On Mar 11, 2014, at 8:06 PM, Scott W Dunning swdunn...@cox.net wrote: [mega byte] Yeah, I had no idea that my messages were coming through in HTML, nor what it looked like until someone sent me a section showing me what it looked like, I can see how that would be frustrating. I’m using the mail app on my macbook pro, any suggestions on how to stop it from going out as html? Do I need to change the font? Also, I think last time I sent a section of my code I copy and pasted it from my script, could that be the problem? Thanks again! Simple. In Mail Preferences - Composing - Message Format - Plain Text (Your setting is probably currently Rich Text.) -Bill ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Help with Guess the number script
On Mar 8, 2014, at 7:29 AM, eryksun eryk...@gmail.com wrote: i.e. guess 1 or guess 100 becomes not not (guess 1 or guess 100) Why a not not? Wouldn’t that just be saying do this because the second not is undoing the first? distribute over the disjunction not (not (guess 1) and not (guess 100)) logically negate the comparisons not (1 = guess and guess = 100) finally, write the conjoined comparisons as a chained comparison: not (1 = guess = 100) i.e., guess isn't in the closed interval [1, 100]. Anyway, you needn't go out of your way to rewrite the expression using a chained comparison. The disjunctive expression is actually implemented more efficiently by CPython's compiler, which you can verify using the dis module to disassemble the bytecode. I’m not sure what you’re talking about in the above paragraph. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Help with Guess the number script
On Mar 8, 2014, at 7:35 AM, Mark Lawrence breamore...@yahoo.co.uk wrote: I have no interest in the efficiency, only what is easiest for me to read, which in this case is the chained comparison. As a rule of thumb I'd also prefer it to be logically correct :) What exactly is ment by a chained comparison? Wouldn’t what I wrote be chained? ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Help with Guess the number script
On 10/03/2014 02:05, Scott W Dunning wrote: On Mar 8, 2014, at 7:35 AM, Mark Lawrence breamore...@yahoo.co.uk wrote: I have no interest in the efficiency, only what is easiest for me to read, which in this case is the chained comparison. As a rule of thumb I'd also prefer it to be logically correct :) What exactly is ment by a chained comparison? Wouldn’t what I wrote be chained? A chained comparison refers to the fact that the comparison can be written without using and or or, see http://docs.python.org/3/reference/expressions.html, not the if/elif chain. -- 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] Help with Guess the number script
On 10/03/2014 02:03, Scott W Dunning wrote: On Mar 8, 2014, at 7:29 AM, eryksun eryk...@gmail.com wrote: Anyway, you needn't go out of your way to rewrite the expression using a chained comparison. The disjunctive expression is actually implemented more efficiently by CPython's compiler, which you can verify using the dis module to disassemble the bytecode. I’m not sure what you’re talking about in the above paragraph. As a newbie don't worry about it (yet). Personally I think it's plain daft to put such advanced language topics on a tutor mailing list. -- 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] Help with Guess the number script
On Mon, Mar 10, 2014 at 5:29 AM, Mark Lawrence breamore...@yahoo.co.uk wrote: As a newbie don't worry about it (yet). Personally I think it's plain daft to put such advanced language topics on a tutor mailing list. Different strokes for different folks. I like to tinker with and disassemble things as I'm learning about them. I would have been ecstatic about open source as a kid. I learn simultaneously from the top down and bottom up -- outside to inside and inside to outside. I need an abstract overview (a map) combined with a concrete realization. Tell me and show me -- and let me tinker and experiment. If learning isn't fun, I'm not learning. The Python language reference, while being far more accessible than an ISO standard or technical report, is still an abstract, highly verbal specification. I understand it, but I don't truly 'grok' a lot of things until I see how it's implemented in bytecode, or even down to the C source level. Putting the two together, I meet in the middle with a better understanding of how it works. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] help me
hi I need your help plz with this cods ( I want u to tell wht cod I miss to stop the while loop whene I get 3 stars) rm = [] stars = 0 ##if stars == 3: ## print You win ##else: ## print hh def ask_yes_no(question): Ask a yes or no question. answer = None while answer not in (y, n): answer = raw_input(question).lower() return answer def congrate_winner(stars = 3): print congradulation you have., stars, stars you won!\n return stars ##def stars(): ## #stars = 0 ## global stars ## stars = stars + 1 ## print stars:, stars, \n ## ## if stars == 3: ## print congadulation you win ## else: ## print Go to the next room ## return stars def rest_room(): restroom = [shower, sink] print restroom global stars ans = ask_yes_no(It does star ther?: ) print This is the value of ans., ans if ans == y: print \nOK stars = stars + 1 print Stars:, stars, \n\n else: print hmm go to another room. print Stars:, stars, \n\n return ans, restroom def living_room(): livingroom = [uyyg, hfgfd, star] print livingroom global stars ans = ask_yes_no(It does star ther?: ) print Your answe is., ans if ans == y: print \nOK stars = stars + 1 print Stars:, stars, \n\n else: print hmm go to another room. print Stars:, stars, \n\n return ans, livingroom def bed_room(): bedroom = [iuyg, star] print bedroom global stars ans = ask_yes_no(It does star ther?: ) print Your answe is., ans if ans == y: print \nOK stars = stars + 1 print Stars:, stars, \n\n else: print hmm go to another room. print Stars:, stars, \n\n return ans, bedroom def Kichen(): kichen = [star, jyhffd] global stars print kichen ans = ask_yes_no(It does star ther?: ) print Your answe is., ans if ans == y: print \nOK stars = stars + 1 print Stars:, stars, \n\n else: print hmm go to another room. print Stars:, stars, \n\n return ans, kichen def main(): print Wlecome to my house. rm = None while rm != stars: print\ 0 - Northe 1 - South 2 - East 3 - Weast rm = raw_input(What room you want to go?: ) if rm == 0: rest_room() elif rm == 1: living_room() elif rm == 2: bed_room() elif rm == 3: Kichen() ##if stars == 3: ## congrate_winner() main() raw_input(\nPress the enter key to exit.) On Saturday, February 1, 2014 6:40 PM, hind fathallah hind_fathal...@yahoo.com wrote: thank you so much because I got it :) On Saturday, February 1, 2014 1:28 PM, Danny Yoo d...@hashcollision.org wrote: On Fri, Jan 31, 2014 at 8:55 PM, hind fathallah hind_fathal...@yahoo.com wrote: hi can you answer this question for me plz [question omitted] Many of us probably could answer this. But this is not a homework-answering mailing list. The problem itself is not interesting to us. What is interesting is why the problem is giving you trouble. We'd rather focus on where you are having difficulty: we'd rather help *you*. Tell us what you've tried, where you're getting stuck, what other kinds of problems you've done that are similar to this one. That is, show us what general problem solving strategies you're using now. Maybe some of those strategies are not working for you.___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] help me
hind fathallah hind_fathal...@yahoo.com Wrote in message: while rm != stars:     print\         0 - Northe     1 - South     2 - East     3 - Weast         rm = raw_input(What room you want to go?: ) Why are you looping till he gets to the weast room? Why not loop till stars reaches 3? -- DaveA ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] help me
hind fathallah wrote: hi I need your help plz with this cods ( I want u to tell wht cod I miss to stop the while loop whene I get 3 stars) rm = [] I think you are comparing a string and an integer. That gives False even if the values look the same: i = 3 s = 3 print i, s 3 3 i == s False Use repr() debug the problem: print repr(i), repr(s) 3 '3' ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Help with Guess the number script
On Mar 10, 2014, at 4:15 AM, eryksun eryk...@gmail.com wrote: Different strokes for different folks. I like to tinker with and disassemble things as I'm learning about them. I would have been ecstatic about open source as a kid. I learn simultaneously from the top down and bottom up -- outside to inside and inside to outside. I need an abstract overview (a map) combined with a concrete realization. Tell me and show me -- and let me tinker and experiment. If learning isn't fun, I'm not learning. I agree I learn the same way. I just didn’t understand what you were saying. What exactly is Cpython? Is it different from the python I’m using? Also, what did you mean by; The disjunctive expression is actually implemented more efficiently by CPython's compiler, which you can verify using the dis module to disassemble the bytecode. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Help with Guess the number script
On Mar 8, 2014, at 3:57 AM, spir denis.s...@gmail.com wrote: Well done. And now that you have the right set of tests you can half the number of lines by combining your if conditions again, like you had in the original post. ie. Bring your hot/cold/warm tests together. So below is what I finally came up with that works. I’m trying to condense it to half the number of lines like Denis suggested. I was hoping to clarify a couple things if you guys don’t mind…. I wanna make sure I understand how this code is working. So, from what I gather it first checks to see if the ‘guess’ is out of range and if that is false it continues to the next ‘if’ statement checking wether it’s too low. Now this is where I’m not 100% sure if the too low ‘if’ statement is false does it skip everything that is nested below it (you are cold, warm, on fire) and go to the ‘if statement checking if it’s too high? And now say the too low ‘if’ statement is true, because it’s an ‘if’ the code does not stop it continues but when it gets to the elif the code stops? def print_hints(secret, guess): if guess 1 or guess 100: print print Out of range! print if guess secret: print print Too low! if guess secret - 10: print You are cold! print print Sorry please try again. print print elif guess secret - 5: print You are warmer! print print Sorry please try again. print print else: print You're on fire!! print print Sorry please try again. print print if guess secret: print print Too high! if guess secret + 10: print You are cold! print print Sorry please try again. print print elif guess secret + 5: print You are warmer! print print Sorry please try again. print print else: print You're on fire!! print print Sorry please try again. print print This is what I have right now, obviously it’s not working. I’ve been playing around with it but I’m just not seeing where I’m going wrong. Any suggestions are greatly appreciated! def print_hints(secret, guess): if guess 1 or guess 100: print print Out of range! print if guess secret: print print Too low! if guess secret: print print Too high! if guess secret - 10 or guess secret - 10: print You are cold! print print Sorry please try again. print print elif guess secret - 5 or guess secret - 5: print You are warmer! print print Sorry please try again. print print else: print You're on fire!! print print Sorry please try again. print print ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Help with Guess the number script
On Mar 8, 2014, at 11:50 AM, Scott dunning swdunn...@cox.net wrote: And now that you have the right set of tests you can half the number of lines by combining your if conditions again, like you had in the original post. ie. Bring your hot/cold/warm tests together. I’m having a hard time doing that because the guess can be either too low or too high but it is always either cold, warm, or on fire. I can’t figure out how to make it work with out splitting the cold, warm and on fire under two branches, one too low and one too high. Any suggestions? Thanks! ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Help with Guess the number script
On Mar 8, 2014, at 7:29 AM, eryksun eryk...@gmail.com wrote: not not (guess 1 or guess 100) Why a not not? Wouldn’t that just be saying do this because the second not is undoing the first? In boolean algebra, `not (A or B)` is equivalent to `not A and not B` (De Morgan's law). I double negated in order to mechanically apply this rule, e.g. A or B = not not (A or B) = not (not A and not B) Anyway, you needn't go out of your way to rewrite the expression using a chained comparison. The disjunctive expression is actually implemented more efficiently by CPython's compiler, which you can verify using the dis module to disassemble the bytecode. I’m not sure what you’re talking about in the above paragraph. There's hardly any difference in how the interpreter evaluates the code in a simple case like this, and it's actually slightly more efficient (in CPython) without chaining. That said, chained comparisons are more efficient when the expressions being compared are computationally expensive, since each expression is only evaluated once. Regarding bytecode, CPython compiles Python source code to a sequence of bytecode operations that get interpreted at runtime. It's an implementation detail, but examining CPython bytecode is nonetheless informative. Here's a basic example: def f(): ... x = 'abc' The function's code object contains the compiled code as a byte sting in its co_code attribute: f.__code__.co_code b'd\x01\x00}\x00\x00d\x00\x00S' This assembled code isn't easy to read. Also, reading it requires referencing other fields of the code object such as co_consts and co_varnames. The dis module disassembles it to a form that's a bit easier to read: dis.dis(f) 2 0 LOAD_CONST 1 ('abc') 3 STORE_FAST 0 (x) 6 LOAD_CONST 0 (None) 9 RETURN_VALUE The documentation for the dis module includes a basic description of each operation. http://docs.python.org/3/library/dis ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor