From it.iswill at yahoo.com Mon Dec 1 10:07:08 2014 From: it.iswill at yahoo.com (William Becerra) Date: Mon, 1 Dec 2014 09:07:08 +0000 (UTC) Subject: [Tutor] Trouble creating a pygame.font.SysFont, was Re: (no subject) In-Reply-To: References: Message-ID: <1471831087.3495603.1417424828980.JavaMail.yahoo@jws11171.mail.ir2.yahoo.com> It seems I forgot to write pygame.init()?Thank you guys for your time it is much appreciated.? On Saturday, 29 November 2014, 15:31, Peter Otten <__peter__ at web.de> wrote: William wrote: Hello William; please provide a meaningful subject line so that your readers get a hint whether your question is in their area of expertise. > Hello there I'm using Python? 3.4 running on Ubuntu 14.04LTS > I'm new to programming and also new to linux > I'm trying to learn the pygame library > I was reading : > > http://programarcadegames.com/index.php?chapter=introduction_to_graphics&lang=en#section_5 > > On the section on how to draw text the writer has the following code > | > font ||=||pygame.font.SysFont(||'Calibri'||, ||25||, ||True||, ||False||)| > |text ||=||font.render(||"My text"||,||True||,BLACK) > ||screen.blit(text, [||250||, ||250||]) That is very hard to read. If you have to post Python code please do it in plain text without those funny "|". Thank you. > When I run the code using the IDLE the Python shell gives me the > following error > > Traceback (most recent call last): > File "/home/william/Desktop/Pygame/Python 3X/Drawing_Shapes.py", line > 48, in > font = pygame.font.SysFont('Calibri', 25, True, False) > File "/usr/local/lib/python3.4/dist-packages/pygame/sysfont.py", line > 614, in SysFont > return constructor(fontname, size, set_bold, set_italic) > File "/usr/local/lib/python3.4/dist-packages/pygame/sysfont.py", line > 537, in font_constructor > font = pygame.font.Font(fontpath, size) > pygame.error: font not initialized > > > I think the problem is that the fonts in Ubuntu are probably stored in a > different > location than in Windows OS.And therefore python can not find it using > the SysFont > method > Can anyone give me any suggestion on how to edit the code so that I can > write text > on my graphics? Quoting the page you link to: """ The first code a Pygame program needs to do is load and initialize the Pygame library. Every program that uses Pygame should start with these lines: Importing and initializing Pygame # Import a library of functions called 'pygame' import pygame # Initialize the game engine pygame.init() """ Did you follow that advice? If you did and your script is reasonably short please post it here so that we can have a look or try to run it ourselves. _______________________________________________ Tutor maillist? -? Tutor at python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor -------------- next part -------------- An HTML attachment was scrubbed... URL: From niyanaxx95 at gmail.com Mon Dec 1 02:01:32 2014 From: niyanaxx95 at gmail.com (niyanaxx95 at gmail.com) Date: Mon, 1 Dec 2014 01:01:32 +0000 Subject: [Tutor] =?utf-8?q?Sets_Python?= Message-ID: <547bbf1d.91268c0a.220f.3741@mx.google.com> I am not understanding how I am supposed to do the highlighted things on the problem statement. If someone could please direct me on the steps to go about doing what is highlighted. Have do I read each command, by making the program read each line?? How do I add the invalid commands into a set? When printing the command is invalid, do I simply do as I did with the valid commands print? Problem Statement: We are going to write a program that reads an input file of commands (Commands.txt) to Arnold the Robot. The four valid command are: Up Down Left Right After you read each command, make sure it is valid (included in the set of valid commands). If the command is valid, print ?Valid command entered, the command was:? and the command. If the command is invalid, print ?Invalid command entered, the command was:? and the command. If the command is invalid, add it to a set of invalid commands. Keep a count of: The total number of commands read The total number of valid commands read The total number of invalid commands read After all of the commands have been read: Print the total number of commands read Print the total number of valid commands read Print the total number of invalid commands read Print the number of unique invalid commands read Print the set of invalid commands. The format of the input files is: Each line in the file contains a command, not all command are valid My Code So Far: def main() : # Define main variables leftCount = 0 rightCount = 0 upCount = 0 downCount = 0 commandCount = 0 invalidCommands = 0 command = ("left", "right", "up", "down") numUnique = 0 numInvalid = 0 invalidCommands = set() filename = input("Enter filename (default: Commands.txt): ") if len(filename) == 0 : filename = "Commands.txt" inputFile = open(filename, "r") command = input("Please enter a command for Arnold: ") if command in command : commandCount = commandCount + 1 print("The total amount of commands: ", commandCount) if command == "up" : upCount = upCount + 1 print("Valid command entered, the command was: up") elif command == "down" : downCount = downCount + 1 print("Valid command entered, the command was: down") elif command == "left" : leftCount = leftCount + 1 print("Valid command entered, the command was: left") elif command == "right" : rightCount = rightCount + 1 print("Valid command entered, the command was: right") else : print("Invalid command entered, the command entered was: ", command) numInvalid = numInvalid + 1 if not command in invalidCommands : numUnique = numUnique + 1 invalidCommands.add(command) for line in inputFile : theWords = line.split() for word in theWords : cleaned = clean(word) if cleaned != "" : numUnique.append(cleaned) print("The file contains", len(numUnique), "unique words.") # Cleans a string by making letters lowercase and removing characters that are not letters # @param string the string to be cleaned # @return the cleaned string def clean(string) : result = "" for char in string : if char.isalpha() : result = result + char return result.lower() # Start the program. main() What Happens When Ran: 3.4.1 (v3.4.1:c0e311e010fc, May 18 2014, 10:38:22) [MSC v.1600 32 bit (Intel)] Python Type "help", "copyright", "credits" or "license" for more information. [evaluate CommandsDraft.py] Enter filename (default: Commands.txt): Commands.txt Please enter a command for Arnold: dawn The total amount of commands: 1 Invalid Traceback (most recent call last): File "C:\Program Files (x86)\Wing IDE 101 5.0\src\debug\tserver\_sandbox.py", line 70, in File "C:\Program Files (x86)\Wing IDE 101 5.0\src\debug\tserver\_sandbox.py", line 52, in main builtins.AttributeError: 'int' object has no attribute 'append' -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Mon Dec 1 12:07:48 2014 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 01 Dec 2014 11:07:48 +0000 Subject: [Tutor] Sets Python In-Reply-To: <547bbf1d.91268c0a.220f.3741@mx.google.com> References: <547bbf1d.91268c0a.220f.3741@mx.google.com> Message-ID: On 01/12/14 01:01, niyanaxx95 at gmail.com wrote: > Have do I read each command, by making the program read each line?? Yes, each line of the file contains one command. read the file line by line. Do you know how to do that? > How do I add the invalid commands into a set? Do you know how to create and use sets in Python? This exercise seems to be based on using sets so I would expect your teacher/tutorial to have explained sets before setting the problem. > When printing the command is invalid, do I simply do as I > did with the valid commands print? You just use the print function as usual. > Problem Statement: > > We are going to write a program that reads an input file of commands > (Commands.txt) to Arnold the Robot. > > The four valid command are: > Up > Down > Left > Right You need to store these four strings in a set. > After you read each command, make sure it is valid (included in the > */set/*of valid commands). Then check the input from the file against the contents of your set. > If the command is valid, print ?Valid command entered, the command was:? > and the command. > If the command is invalid, print ?Invalid command entered, the command > was:? and the command. Use an if/else statement to print the valid or invalid result. > If the command is invalid, add it to a */set/*of invalid commands. And if its invalid add the new command to a new set of invalid commands, which starts out empty. > Keep a count of: > The total number of commands read > The total number of valid commands read > The total number of invalid commands read You will need counters for these and increment them after each command. > After all of the commands have been read: > Print the total number of commands read > Print the total number of valid commands read > Print the total number of invalid commands read These are just the counters above > Print the number of unique invalid commands read > Print the set of invalid commands. This is just the size of the invalid set and the members of that set. > def main() : > # Define main variables > leftCount = 0 > rightCount = 0 > upCount = 0 > downCount = 0 You aren't asked to count each individual command just the total of valid commands so you could simplify this by having one variable instead of 4. > commandCount = 0 > invalidCommands = 0 > command = ("left", "right", "up", "down") This is not a set. You were asked to use a set. > numUnique = 0 > numInvalid = 0 You already have invalidCommands what is the purpose of this new variable? > invalidCommands = set() Is it because this wipes out the original variable? > filename = input("Enter filename (default: Commands.txt): ") > if len(filename) == 0 : > filename = "Commands.txt" > inputFile = open(filename, "r") So far so good. > command = input("Please enter a command for Arnold: ") But this is wrong. The commands are in the file so you need to loop over the file reading and processing each line. > if command in command : Here you are trying to use two variables with the same name - that won;t work. You need to rename your set of valid commands - to validCommands maybe? > commandCount = commandCount + 1 > print("The total amount of commands: ", commandCount) You only need to print the totals at the end. But you are supposed to print a message: > If the command is valid, > print ?Valid command entered, the command was:? > and the command. In programming it is important to stick to the specification you have been given and not try to interpret the problem in your own way. > if command == "up" : > upCount = upCount + 1 > print("Valid command entered, the command was: up") > elif command == "down" : > downCount = downCount + 1 > print("Valid command entered, the command was: down") > elif command == "left" : > leftCount = leftCount + 1 > print("Valid command entered, the command was: left") > elif command == "right" : > rightCount = rightCount + 1 > print("Valid command entered, the command was: right") This is OK but its more complicated than it needs to be to meet the specification. > else : > print("Invalid command entered, the command entered was: > ", command) > numInvalid = numInvalid + 1 > if not command in invalidCommands : > numUnique = numUnique + 1 > invalidCommands.add(command) Again this looks ok. > for line in inputFile : > theWords = line.split() > for word in theWords : > cleaned = clean(word) > if cleaned != "" : > numUnique.append(cleaned) > print("The file contains", len(numUnique), "unique words.") This is all a bit odd. Its not clear what purpose it brings. It is almost what you should be doing at the top of your function to read the commands from the file. But it all looks a bit like overkill for this task. I'd just use something like: for line in inputFile: command = line.strip().lowercase() All the cleaning stuff isn't really relevant since you should be testing for valid input in your if/else code above. > Enter filename (default: Commands.txt): Commands.txt > Please enter a command for Arnold: dawn > The total amount of commands: 1 > Invalid > Traceback (most recent call last): > File "C:\Program Files (x86)\Wing IDE 101 > 5.0\src\debug\tserver\_sandbox.py", line 70, in > File "C:\Program Files (x86)\Wing IDE 101 > 5.0\src\debug\tserver\_sandbox.py", line 52, in main > builtins.AttributeError: 'int' object has no attribute 'append' That's because in the file reading bit, at the end, you have numUnique.append but numUnique is an integer. You can't append to integers. But that whole section is too complex and in the wrong place. -- 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 From ljetibo at gmail.com Mon Dec 1 13:15:00 2014 From: ljetibo at gmail.com (=?ISO-8859-2?Q?Dino_Bekte=B9evi=E6?=) Date: Mon, 1 Dec 2014 13:15:00 +0100 Subject: [Tutor] Sets PythonTutor Digest, Vol 130, Issue 1 Message-ID: Hey, > invalidCommands = 0 > command = ("left", "right", "up", "down") > numUnique = 0 > numInvalid = 0 > invalidCommands = set() It seems you have defined invalidCommads as borh of int type and a set type. Also a nice trick for multiple options in the future is: If command is in ("up","down","left","right"): print command Of course thos wont worj now vecause yoy have ti keep track of tge counters, but I personaly like it and find it usefull. Good luck, Dino > Message: 2 > Date: Mon, 1 Dec 2014 01:01:32 +0000 > From: > To: "=?utf-8?Q?tutor at python.org?=" > Subject: [Tutor] Sets Python > Message-ID: <547bbf1d.91268c0a.220f.3741 at mx.google.com> > Content-Type: text/plain; charset="utf-8" > > I am not understanding how I am supposed to do the highlighted things on the problem statement. If someone could please direct me on the steps to go about doing what is highlighted. Have do I read each command, by making the program read each line?? How do I add the invalid commands into a set? When printing the command is invalid, do I simply do as I did with the valid commands print? > > > Problem Statement: > We are going to write a program that reads an input file of commands (Commands.txt) to Arnold the Robot. > > The four valid command are: > > Up > > > Down > > > Left > > > Right > > > After you read each command, make sure it is valid (included in the set of valid commands). > > If the command is valid, print ?Valid command entered, the command was:? and the command. > > If the command is invalid, print ?Invalid command entered, the command was:? and the command. > > If the command is invalid, add it to a set of invalid commands. > > Keep a count of: > > The total number of commands read > > > The total number of valid commands read > > > The total number of invalid commands read > > > After all of the commands have been read: > > Print the total number of commands read > > > Print the total number of valid commands read > > > Print the total number of invalid commands read > > > Print the number of unique invalid commands read > > > Print the set of invalid commands. > > > The format of the input files is: > > Each line in the file contains a command, not all command are valid > > > > > > My Code So Far: > > def main() : > # Define main variables > leftCount = 0 > rightCount = 0 > upCount = 0 > downCount = 0 > commandCount = 0 > invalidCommands = 0 > command = ("left", "right", "up", "down") > numUnique = 0 > numInvalid = 0 > invalidCommands = set() > > filename = input("Enter filename (default: Commands.txt): ") > if len(filename) == 0 : > filename = "Commands.txt" > inputFile = open(filename, "r") > > > command = input("Please enter a command for Arnold: ") > if command in command : > commandCount = commandCount + 1 > print("The total amount of commands: ", commandCount) > if command == "up" : > upCount = upCount + 1 > print("Valid command entered, the command was: up") > elif command == "down" : > downCount = downCount + 1 > print("Valid command entered, the command was: down") > elif command == "left" : > leftCount = leftCount + 1 > print("Valid command entered, the command was: left") > elif command == "right" : > rightCount = rightCount + 1 > print("Valid command entered, the command was: right") > else : > print("Invalid command entered, the command entered was: ", command) > numInvalid = numInvalid + 1 > if not command in invalidCommands : > numUnique = numUnique + 1 > invalidCommands.add(command) > > > > > > for line in inputFile : > theWords = line.split() > for word in theWords : > cleaned = clean(word) > if cleaned != "" : > numUnique.append(cleaned) > print("The file contains", len(numUnique), "unique words.") > > > > # Cleans a string by making letters lowercase and removing characters that are not letters > # @param string the string to be cleaned > # @return the cleaned string > def clean(string) : > result = "" > for char in string : > if char.isalpha() : > result = result + char > return result.lower() > > > > > > # Start the program. > main() > > > > What Happens When Ran: > > 3.4.1 (v3.4.1:c0e311e010fc, May 18 2014, 10:38:22) [MSC v.1600 32 bit (Intel)] > Python Type "help", "copyright", "credits" or "license" for more information. > [evaluate CommandsDraft.py] > Enter filename (default: Commands.txt): Commands.txt > Please enter a command for Arnold: dawn > The total amount of commands: 1 > Invalid > Traceback (most recent call last): > File "C:\Program Files (x86)\Wing IDE 101 5.0\src\debug\tserver\_sandbox.py", line 70, in > File "C:\Program Files (x86)\Wing IDE 101 5.0\src\debug\tserver\_sandbox.py", line 52, in main > builtins.AttributeError: 'int' object has no attribute 'append' > -------------- next part -------------- > An HTML attachment was scrubbed... > URL: < http://mail.python.org/pipermail/tutor/attachments/20141201/fecd2537/attachment.html > > > ------------------------------ > > Subject: Digest Footer > > _______________________________________________ > Tutor maillist - Tutor at python.org > https://mail.python.org/mailman/listinfo/tutor > > > ------------------------------ > > End of Tutor Digest, Vol 130, Issue 1 > ************************************* -------------- next part -------------- An HTML attachment was scrubbed... URL: From mydayfabu at gmail.com Mon Dec 1 15:30:29 2014 From: mydayfabu at gmail.com (fabu desay) Date: Mon, 1 Dec 2014 15:30:29 +0100 Subject: [Tutor] Pygame fonts not been initialised Message-ID: If you still don't have a solution I suggest using the default font for pygame freesansbold.tiff it is located in the python library files just search for it in the python-pygame directory. I think your code fails because it does not pick the font you wanted hence not initialised. Below is a sample code of a font been used from a file you can equally download fonts from google fonts fontObj = pygame.font.Font("freesansbold.ttf", 40) fontObj is our object been initialised. Hope it helps On Sun, Nov 30, 2014 at 12:00 PM, wrote: > Send Tutor mailing list submissions to > tutor at python.org > > To subscribe or unsubscribe via the World Wide Web, visit > https://mail.python.org/mailman/listinfo/tutor > or, via email, send a message with subject or body 'help' to > tutor-request at python.org > > You can reach the person managing the list at > tutor-owner at python.org > > When replying, please edit your Subject line so it is more specific > than "Re: Contents of Tutor digest..." > > > Today's Topics: > > 1. (no subject) (William) > 2. Trouble creating a pygame.font.SysFont, was Re: (no subject) > (Peter Otten) > 3. Re: (no subject) (Danny Yoo) > 4. Re: (no subject) (Japhy Bartlett) > > > ---------------------------------------------------------------------- > > Message: 1 > Date: Sat, 29 Nov 2014 11:31:57 +0200 > From: William > To: tutor at python.org > Subject: [Tutor] (no subject) > Message-ID: <5479928D.9000009 at yahoo.com> > Content-Type: text/plain; charset=utf-8; format=flowed > > Hello there I'm using Python 3.4 running on Ubuntu 14.04LTS > I'm new to programming and also new to linux > I'm trying to learn the pygame library > I was reading : > > > http://programarcadegames.com/index.php?chapter=introduction_to_graphics&lang=en#section_5 > > On the section on how to draw text the writer has the following code > | > font ||=||pygame.font.SysFont(||'Calibri'||, ||25||, ||True||, ||False||)| > |text ||=||font.render(||"My text"||,||True||,BLACK) > ||screen.blit(text, [||250||, ||250||]) > > When I run the code using the IDLE the Python shell gives me the > following error > > Traceback (most recent call last): > File "/home/william/Desktop/Pygame/Python 3X/Drawing_Shapes.py", line > 48, in > font = pygame.font.SysFont('Calibri', 25, True, False) > File "/usr/local/lib/python3.4/dist-packages/pygame/sysfont.py", line > 614, in SysFont > return constructor(fontname, size, set_bold, set_italic) > File "/usr/local/lib/python3.4/dist-packages/pygame/sysfont.py", line > 537, in font_constructor > font = pygame.font.Font(fontpath, size) > pygame.error: font not initialized > > > I think the problem is that the fonts in Ubuntu are probably stored in a > different > location than in Windows OS.And therefore python can not find it using > the SysFont > method > Can anyone give me any suggestion on how to edit the code so that I can > write text > on my graphics? > Thank you. > | > > > ------------------------------ > > Message: 2 > Date: Sat, 29 Nov 2014 14:31:04 +0100 > From: Peter Otten <__peter__ at web.de> > To: tutor at python.org > Subject: [Tutor] Trouble creating a pygame.font.SysFont, was Re: (no > subject) > Message-ID: > Content-Type: text/plain; charset="ISO-8859-1" > > William wrote: > > Hello William; please provide a meaningful subject line so that your > readers > get a hint whether your question is in their area of expertise. > > > > Hello there I'm using Python 3.4 running on Ubuntu 14.04LTS > > I'm new to programming and also new to linux > > I'm trying to learn the pygame library > > I was reading : > > > > > > http://programarcadegames.com/index.php?chapter=introduction_to_graphics&lang=en#section_5 > > > > On the section on how to draw text the writer has the following code > > | > > font ||=||pygame.font.SysFont(||'Calibri'||, ||25||, ||True||, > ||False||)| > > |text ||=||font.render(||"My text"||,||True||,BLACK) > > ||screen.blit(text, [||250||, ||250||]) > > That is very hard to read. If you have to post Python code please do it in > plain text without those funny "|". Thank you. > > > When I run the code using the IDLE the Python shell gives me the > > following error > > > > Traceback (most recent call last): > > File "/home/william/Desktop/Pygame/Python 3X/Drawing_Shapes.py", line > > 48, in > > font = pygame.font.SysFont('Calibri', 25, True, False) > > File "/usr/local/lib/python3.4/dist-packages/pygame/sysfont.py", line > > 614, in SysFont > > return constructor(fontname, size, set_bold, set_italic) > > File "/usr/local/lib/python3.4/dist-packages/pygame/sysfont.py", line > > 537, in font_constructor > > font = pygame.font.Font(fontpath, size) > > pygame.error: font not initialized > > > > > > I think the problem is that the fonts in Ubuntu are probably stored in a > > different > > location than in Windows OS.And therefore python can not find it using > > the SysFont > > method > > Can anyone give me any suggestion on how to edit the code so that I can > > write text > > on my graphics? > > Quoting the page you link to: > > """ > The first code a Pygame program needs to do is load and initialize the > Pygame library. Every program that uses Pygame should start with these > lines: > > Importing and initializing Pygame > # Import a library of functions called 'pygame' > import pygame > # Initialize the game engine > pygame.init() > """ > > Did you follow that advice? If you did and your script is reasonably short > please post it here so that we can have a look or try to run it ourselves. > > > > ------------------------------ > > Message: 3 > Date: Sat, 29 Nov 2014 12:26:16 -0800 > From: Danny Yoo > To: William > Cc: Python Tutor Mailing List > Subject: Re: [Tutor] (no subject) > Message-ID: > < > CAGZAPF6isQCiV+nSQr5wJK0tA8mTqWCvsHoNQTz_emCeBr1p+g at mail.gmail.com> > Content-Type: text/plain; charset=UTF-8 > > > When I run the code using the IDLE the Python shell gives me the > following > > error > > > > Traceback (most recent call last): > > File "/home/william/Desktop/Pygame/Python 3X/Drawing_Shapes.py", line > 48, in > > > > font = pygame.font.SysFont('Calibri', 25, True, False) > > File "/usr/local/lib/python3.4/dist-packages/pygame/sysfont.py", line > 614, > > in SysFont > > return constructor(fontname, size, set_bold, set_italic) > > File "/usr/local/lib/python3.4/dist-packages/pygame/sysfont.py", line > 537, > > in font_constructor > > font = pygame.font.Font(fontpath, size) > > pygame.error: font not initialized > > > Hi William, > > Please check with the pygame folks on this one; pygame is a > third-party library, and we at Tutor might not be too familiar with > the library. There should be an active pygame-users mailing list at > the following URL: > > http://www.pygame.org/wiki/info > > According to web searches, the term "pygame.error: font not > initialized" means that you may have forgotten to initialize PyGame > first. > > Reference: http://inventwithpython.com/pygame/chapter2.html, where > they say: "If you ever see an error message like pygame.error: font > not initialized, check to see if you forgot to call pygame.init() at > the start of your program." > > > Again, I have no direct experience with PyGame, so I can not confirm > that this will fix the issue for your own program. This is why you'll > probably want to ask on pygame-users. > > > Good luck to you! > > > ------------------------------ > > Message: 4 > Date: Sat, 29 Nov 2014 13:06:05 -0600 > From: Japhy Bartlett > To: William > Cc: Python Tutor > Subject: Re: [Tutor] (no subject) > Message-ID: > h5ZjYzUtNoaN-g at mail.gmail.com> > Content-Type: text/plain; charset="utf-8" > > It looks like this is a pretty common stumbling block, and you need to call > `pygame.font.init()` before the code you pasted. > > Also.. the way you've pasted that code has added '||' all over the place. > Not sure what's going on there (some sort of tabs/spaces thing?), but it > makes it extremely hard to read! > > On Sat, Nov 29, 2014 at 3:31 AM, William > > wrote: > > > Hello there I'm using Python 3.4 running on Ubuntu 14.04LTS > > I'm new to programming and also new to linux > > I'm trying to learn the pygame library > > I was reading : > > > > http://programarcadegames.com/index.php?chapter= > > introduction_to_graphics&lang=en#section_5 > > > > On the section on how to draw text the writer has the following code > > | > > font ||=||pygame.font.SysFont(||'Calibri'||, ||25||, ||True||, > ||False||)| > > |text ||=||font.render(||"My text"||,||True||,BLACK) > > ||screen.blit(text, [||250||, ||250||]) > > > > When I run the code using the IDLE the Python shell gives me the > following > > error > > > > Traceback (most recent call last): > > File "/home/william/Desktop/Pygame/Python 3X/Drawing_Shapes.py", line 48, > > in > > font = pygame.font.SysFont('Calibri', 25, True, False) > > File "/usr/local/lib/python3.4/dist-packages/pygame/sysfont.py", line > > 614, in SysFont > > return constructor(fontname, size, set_bold, set_italic) > > File "/usr/local/lib/python3.4/dist-packages/pygame/sysfont.py", line > > 537, in font_constructor > > font = pygame.font.Font(fontpath, size) > > pygame.error: font not initialized > > > > > > I think the problem is that the fonts in Ubuntu are probably stored in a > > different > > location than in Windows OS.And therefore python can not find it using > the > > SysFont > > method > > Can anyone give me any suggestion on how to edit the code so that I can > > write text > > on my graphics? > > Thank you. > > | > > _______________________________________________ > > Tutor maillist - Tutor at python.org > > To unsubscribe or change subscription options: > > https://mail.python.org/mailman/listinfo/tutor > > > -------------- next part -------------- > An HTML attachment was scrubbed... > URL: < > http://mail.python.org/pipermail/tutor/attachments/20141129/fc69c773/attachment-0001.html > > > > ------------------------------ > > Subject: Digest Footer > > _______________________________________________ > Tutor maillist - Tutor at python.org > https://mail.python.org/mailman/listinfo/tutor > > > ------------------------------ > > End of Tutor Digest, Vol 129, Issue 73 > ************************************** > -------------- next part -------------- An HTML attachment was scrubbed... URL: From ramrokstheweb at gmail.com Tue Dec 2 09:53:11 2014 From: ramrokstheweb at gmail.com (ram rokr) Date: Tue, 2 Dec 2014 09:53:11 +0100 Subject: [Tutor] Importing an existing plot and manipulating it ! Message-ID: Hello people, I'm a beginner with Python and I'm new to the mailing list. It's nice to know that there is a mailing list with people/tutors who can help me learn Python. So, my difficulty now is that, I already have a script that plots a polygon. But now I'm trying to script a Python class that would enable me to import parameters(or the plot itself) from the previous script and control it too (like specifying parameters: spacing, width, height or the like). My approach was to create a new layout and try to import the existing plot and then try to manipulate it: import math import numpy as np import pya ly = pya.Layout("L10") # create the top cell top_cell = ly.create_cell("TOP") # finding the PCell declaration object ... class Dec: # locating the earlier script to get the parameters for the polygon def __init__(self): self.lib = pya.Library.library_by_name("MyLib") # PCell is a file that contains the polygon with all the parameters of interesrt. if self.lib == None: raise Exception("Unknown lib 'MyLib'") #I'm trying to get parameters from this file/plot to make more. self.pcell_decl = lib.layout().pcell_declaration("CanaryCell"); if pcell_decl == None: raise Exception("Unknown PCell 'CanaryCell'") # instantiating that cell ... Dec() # transformation class Position: def __init__(self, xpos, ypos, t): self.xpos = 0 self.ypos = 0 self.t = pya.Trans(pya.Trans.r0(), -1000 + xpos, -1000 + ypos) # insert into "top_cell" (must be provided by the caller) class top_cell (Dec, Position): def __init__(self, insert, pcell_inst): top_cell = pya.CellView.active().cell self.a = pya.Point(x1,0) self.b = pya.Point(0,y1) self.na = 5 self.nb = 7 pcell_inst = top_cell.insert(pya.CellInstArray(pcell_decl, t, a, b, na, nb)) Position(xpos, ypos, t) top_cell(insert, pcell_inst) # write the layout ly.write("done.gds") How could you advise me to aprroach this problem accomplish this? I've time constrains and that's a big problem ! Thanks. P.S: Yes, the script looks weird. Because I've to use Klayout with python integration. Since I'm new to both I'm having a hard time. If somebody can enlighten me about how to do this in Python, maybe I can comprehend and work it out with KLayout. Regards, Ram. -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Tue Dec 2 11:32:56 2014 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 02 Dec 2014 10:32:56 +0000 Subject: [Tutor] Importing an existing plot and manipulating it ! In-Reply-To: References: Message-ID: On 02/12/14 08:53, ram rokr wrote: > Hello people, > I'm a beginner with Python and I'm new to the mailing > list. It's nice to know that there is a mailing list with people/tutors > who can help me learn Python. Hi Ram, While we are happy to try and help, Numpy is not part of standard Python, which is what this list focuses on. There is a separate numpy list and you might find more folks there who are able to help with specific numpy/plotlib queries. But we do have some numpy users here so maybe they can answer the question for you. -- 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 From rhce.san at gmail.com Tue Dec 2 17:16:08 2014 From: rhce.san at gmail.com (Santosh Kumar) Date: Tue, 2 Dec 2014 21:46:08 +0530 Subject: [Tutor] A small project In-Reply-To: References: Message-ID: All, Any suggestion to my question ? On Thu, Nov 27, 2014 at 12:43 PM, Santosh Kumar wrote: > Hi All, > > I am planning to start a small project , so i need some suggestions on how > to go about it. > > 1) It basically takes some inputs like (name,age,course,joining > date,remarks) so on. > 2) I want a light front end for it. > 3) i should be able to query for a particular person on a particular date > or a joining date. > 4) The app should be easily deployable both in the linux and windows > machines. ( something like a .exe in windows) > > So this is my requirement as stated in the above four points. Now i need > suggestions on how to go ahead with these. > > for 2) should i go for tkinter or do we have something even lighter. > for 3) to achieve this should i just go for a database, if yes i need > something which can be easily moved across. > for 4) if i have to create a executable , how to make sure all the above > requirements can be packaged into a application or a software. > > Thanks in advance. > -- > D. Santosh Kumar > > -- D. Santosh Kumar RHCE | SCSA +91-9703206361 Every task has a unpleasant side .. But you must focus on the end result you are producing. -------------- next part -------------- An HTML attachment was scrubbed... URL: From cs at zip.com.au Tue Dec 2 21:37:08 2014 From: cs at zip.com.au (Cameron Simpson) Date: Wed, 3 Dec 2014 07:37:08 +1100 Subject: [Tutor] A small project In-Reply-To: References: Message-ID: <20141202203708.GA69216@cskk.homeip.net> On 27Nov2014 12:43, Santosh Kumar wrote: >I am planning to start a small project , so i need some suggestions on how >to go about it. > >1) It basically takes some inputs like (name,age,course,joining >date,remarks) so on. >2) I want a light front end for it. >3) i should be able to query for a particular person on a particular date >or a joining date. >4) The app should be easily deployable both in the linux and windows >machines. ( something like a .exe in windows) > >So this is my requirement as stated in the above four points. Now i need >suggestions on how to go ahead with these. > >for 2) should i go for tkinter or do we have something even lighter. If you're familiar with tkinter, use it. Otherwise I don't know enough to advise. At least tkinter comes with Python, so that is one problem solved for you. Disclaimer: I have not used it; I work almost entirely in terminals with text. >for 3) to achieve this should i just go for a database, if yes i need >something which can be easily moved across. You may find that sqlite files are portable. (Or not.) CSV files are portable, but not random access. If your data set is small they might do though: read it into memory; write it out at program exit (or strategic other times). >for 4) if i have to create a executable , how to make sure all the above >requirements can be packaged into a application or a software. Can't help here. My suggestions is: (1) find components that will work on UNIX and Windows (GUI toolkit and data storage specificly). (2) Get it working in as simple a way as possible. The GUI toolkit aside, the rest of it is probably easy to change if needed. But make it work _first_. Cheers, Cameron Simpson Of course I believe that solipsism is the correct philosophy, but that's only one man's opinion. - Bill Garrett From jarod_v6 at libero.it Wed Dec 3 10:36:36 2014 From: jarod_v6 at libero.it (jarod_v6 at libero.it) Date: Wed, 3 Dec 2014 10:36:36 +0100 (CET) Subject: [Tutor] Parse files and create sqlite3 db Message-ID: <1797597213.537751417599396262.JavaMail.httpd@webmail-07.iol.local> Dear all I aattach the file I want to parse and I wanto to create a sqlite database. The problem is I'm not able to create in the right way because there is some logic problems on my script. I have this code: import sqlite import sqlite3 import os # Creates or opens a file called mydb with a SQLite3 DB db = sqlite3.connect('Fastqcd_completo.db') cursor = db.cursor() create_table_sql = """ create table fastqc_summary ( fileid varchar, module varchar, status varchar, total int, duplicate varchar );""" cursor.execute(create_table_sql) create_table_sql2=""" create table fastqc_details ( id serial primary key, fileid varchar, module varchar, col1 varchar, ocols varchar ); """ cursor.execute(create_table_sql2) db.commit() for root, dirs, files in os.walk("/home/mauro/Desktop/LAVORO_CRO/2014/Statitica_RNAseqalign/FASTQC_completo/fastqcdecembre/"): # walk a r for name in files: if (name == "fastqc_data.txt"): fileid = name # use string slicing here if you only want part of the with open(os.path.join(root,name),"r") as p: # automatically close the file when done for i in p: line =i.strip() if "Filename" in line: fileid = line.split()[1] if "Total Sequence" in line: total = line.split()[2] if "Total Duplicate" in line: dup = line.split()[3] if (line[:2] == ">>" and line[:12] != ">>END_MODULE"): module = line[2:-5] # grab module name status = line[-4:] # and overall status pass/warn/fail sql = "insert into fastqc_summary(fileid,module,status,total,duplicate) values(?,?,?,?,?);" data = (fileid,module,status,total,dup) cursor.execute(sql,data) elif (line[:2] != ">>" and line[:2] != "##"): # grab details under each module cols = line.split("\t") col1 = cols[0] ocols = "|".join(cols[1:]) sql = "insert into fastqc_details(fileid,module,col1,ocols) values(?,?,?,?);" data = (fileid,module,col1,ocols) cursor.execute(sql,data) db.commit() So the problem is how to excatct only some parts of the files. In red are the point of the problems. The say the Filename are not defined On the file atached I want to take this part and use for create the database: ##FastQC 0.10.1 >>Basic Statistics pass #Measure Value Filename R05_CTTGTA_L004_R1_001.fastq.gz File type Conventional base calls Encoding Sanger / Illumina 1.9 Total Sequences 27868496 Filtered Sequences 0 Sequence length 50 %GC 50 >>END_MODULE How can I resolve this problem? I need to use the number of rows? bw, -------------- next part -------------- An HTML attachment was scrubbed... URL: -------------- next part -------------- An embedded and charset-unspecified text was scrubbed... Name: fastqc_data.txt URL: From alan.gauld at btinternet.com Wed Dec 3 11:24:07 2014 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 03 Dec 2014 10:24:07 +0000 Subject: [Tutor] Parse files and create sqlite3 db In-Reply-To: <1797597213.537751417599396262.JavaMail.httpd@webmail-07.iol.local> References: <1797597213.537751417599396262.JavaMail.httpd@webmail-07.iol.local> Message-ID: On 03/12/14 09:36, jarod_v6 at libero.it wrote: > Dear all > I aattach the file I want to parse and I wanto to create a sqlite database. > The problem is I'm not able to create in the right way because there is > some logic problems on my script. I have this code: Do you get an error message? If so please send a cut n paste of the full error text. > import sqlite > import sqlite3 You only need the second of these imports > import os > > # Creates or opens a file called mydb with a SQLite3 DB > db = sqlite3.connect('Fastqcd_completo.db') > cursor = db.cursor() > create_table_sql = """ > create table fastqc_summary ( > fileid varchar, > module varchar, > status varchar, > total int, > duplicate varchar > );""" > cursor.execute(create_table_sql) This looks fine except its normal to have a unique key somewhere. But if you are confident that you will have uniqueness in your data you don't strictly need it. > create_table_sql2=""" > create table fastqc_details ( > id serial primary key, But this is odd. I can't find anything about a serial keyword for SQLite. The normal format of this would be id INTEGER PRIMARY KEY which makes id an auto-incrementing unique value. > fileid varchar, > module varchar, > col1 varchar, > ocols varchar > ); > """ > cursor.execute(create_table_sql2) > db.commit() The other potential issue is that you are creating these tables each time you run the script. But if you run the script a second time the tables willalready exist and the CREATES will fail. You should either drop the tables at the top of the script or use the CREATE TABLE IF NOT EXISTS ... format of create. Then if the tab;le already exists your data will be appended. (If you want it overwritten use the drop table technique) > for root, dirs, files in > os.walk("/home/mauro/Desktop/LAVORO_CRO/2014/Statitica_RNAseqalign/FASTQC_completo/fastqcdecembre/"): > # walk a r > for name in files: > if (name == "fastqc_data.txt"): You are searching for a specific name. Could there be multiple such files or are you just using wa;lk to find one? If the latter it would be better to exit the os.walk loop once you find it and then process the file. You need to store the root and filename first of course. > fileid = name # use string slicing here if you only want > part of the > > with open(os.path.join(root,name),"r") as p: # automatically close > the file when done > for i in p: > line =i.strip() > > if "Filename" in line: > fileid = line.split()[1] > if "Total Sequence" in line: > total = line.split()[2] > > if "Total Duplicate" in line: > dup = line.split()[3] > > if (line[:2] == ">>" and line[:12] != ">>END_MODULE"): > module = line[2:-5] # grab module name > status = line[-4:] # and overall status > pass/warn/fail > sql = "insert into > fastqc_summary(fileid,module,status,total,duplicate) values(?,?,?,?,?);" > data = (fileid,module,status,total,dup) > cursor.execute(sql,data) > elif (line[:2] != ">>" and line[:2] != "##"): # > grab details under each module > cols = line.split("\t") > col1 = cols[0] > ocols = "|".join(cols[1:]) > sql = "insert into > fastqc_details(fileid,module,col1,ocols) values(?,?,?,?);" > data = (fileid,module,col1,ocols) > cursor.execute(sql,data) > db.commit() > > > So the problem is how to excatct only some parts of the files. In red > are the point of the problems. The say the Filename are not defined What says that? It's true that you don't have a variable Filename defined. But I don't see Filename in your code anywhere either. So I don't understand the error message. Can you post it in full please? > the file atached I want to take this part and use for create the database: > ##FastQC 0.10.1 > >>Basic Statistics pass > #Measure Value > Filename R05_CTTGTA_L004_R1_001.fastq.gz > File type Conventional base calls > Encoding Sanger / Illumina 1.9 > Total Sequences 27868496 > Filtered Sequences 0 > Sequence length 50 > %GC 50 > >>END_MODULE -- 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 From zhanggordon999 at gmail.com Tue Dec 2 21:28:36 2014 From: zhanggordon999 at gmail.com (gordon zhang) Date: Tue, 2 Dec 2014 13:28:36 -0700 Subject: [Tutor] Does the user need to install Python, when we deploy our c++ products using python? Message-ID: I downloaded python 3.4.2 for c++ and create a vc++ project using python, but I have no idea what python dlls and other stuff needed to deploy the products. I know if we put Python34.dll and Python.dll in the folder of executable, it is not enough. What else do we need to put in the folder of executable?(the application does not run) If anyone knows please let me know. Thanks, Gordon -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Wed Dec 3 12:29:32 2014 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 03 Dec 2014 11:29:32 +0000 Subject: [Tutor] Does the user need to install Python, when we deploy our c++ products using python? In-Reply-To: References: Message-ID: On 02/12/14 20:28, gordon zhang wrote: > I downloaded python 3.4.2 for c++ and create a vc++ project using > python, but I have no idea what python dlls and other stuff needed to > deploy the products. Python is an interpreter so you will need the full Python interpreter and all the module files that you use. Some of these are DLLs others are Python scripts. > I know if we put Python34.dll and Python.dll in the folder of > executable, it is not enough. What else do we need to put in the folder > of executable?(the application does not run) Using Python just to build an installer script where the users don't already have Python installed sounds like a bad idea to me. Especially on Windows(which given the mention of VC++ seems to be the platform). There are plenty of installer tools for Windows that would be more suitable and some of them are even free. If Python was already installed on your target PCs it would be a reasonable decision but, if not, you effectively need two installers - one for Python and another for your app. There are tools such as freeze or py2exe that can bundle up a Python script as a single exe file but that means installing the interpreter as part of the exe. You could of course delete the python exe bundle after the install completed but it still seems overkill for an install script. -- 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 From steve at pearwood.info Wed Dec 3 12:30:05 2014 From: steve at pearwood.info (Steven D'Aprano) Date: Wed, 3 Dec 2014 22:30:05 +1100 Subject: [Tutor] Does the user need to install Python, when we deploy our c++ products using python? In-Reply-To: References: Message-ID: <20141203113004.GC9865@ando.pearwood.info> On Tue, Dec 02, 2014 at 01:28:36PM -0700, gordon zhang wrote: > I downloaded python 3.4.2 for c++ and create a vc++ project using python, > but I have no idea what python dlls and other stuff needed to deploy the > products. > > I know if we put Python34.dll and Python.dll in the folder of executable, > it is not enough. What else do we need to put in the folder of > executable?(the application does not run) I'm afraid I have very little idea what "python 3.4.2 for c++" is, or what a "vc++ project using python" means. Do you mean Microsoft Visual C++? Where did you download this from? How do you use it in C++? C++ and Python are two very different languages. Normally people just use Python alone, or C++ alone. This mailing list is for beginners wanting to learn Python, and we may not have the experience needed to answer advanced questions like building C++ applications with embedded Python. For that, I recommend you ask on the comp.lang.python newsgroup, or on the forums of whatever embedded python software you are using. -- Steven From __peter__ at web.de Wed Dec 3 13:11:03 2014 From: __peter__ at web.de (Peter Otten) Date: Wed, 03 Dec 2014 13:11:03 +0100 Subject: [Tutor] A small project References: Message-ID: Santosh Kumar wrote: > All, > > Any suggestion to my question ? > > On Thu, Nov 27, 2014 at 12:43 PM, Santosh Kumar > wrote: > >> Hi All, >> >> I am planning to start a small project , so i need some suggestions on >> how to go about it. >> >> 1) It basically takes some inputs like (name,age,course,joining >> date,remarks) so on. >> 2) I want a light front end for it. If you use a web browser you may be able evade the deployment hassles. Here's a simple example: >> 3) i should be able to query for a particular person on a particular date >> or a joining date. >> 4) The app should be easily deployable both in the linux and windows >> machines. ( something like a .exe in windows) >> >> So this is my requirement as stated in the above four points. Now i need >> suggestions on how to go ahead with these. >> >> for 2) should i go for tkinter or do we have something even lighter. >> for 3) to achieve this should i just go for a database, if yes i need >> something which can be easily moved across. >> for 4) if i have to create a executable , how to make sure all the above >> requirements can be packaged into a application or a software. >> >> Thanks in advance. >> -- >> D. Santosh Kumar From jarod_v6 at libero.it Wed Dec 3 14:07:51 2014 From: jarod_v6 at libero.it (jarod_v6 at libero.it) Date: Wed, 3 Dec 2014 14:07:51 +0100 (CET) Subject: [Tutor] Parse files and create sqlite3 db (Alan Gauld) Message-ID: <387082369.654931417612071650.JavaMail.httpd@webmail-07.iol.local> thanks so much,here you have the error: --------------------------------------------------------------------------- NameError Traceback (most recent call last) in () 43 status = line[-4:] # and overall status pass/warn/fail 44 sql = "insert into fastqc_summary(fileid,module,status,total,duplicate) values(?,?,?,?,?);" ---> 45 data = (fileid,module, status,total,dup) 46 cursor.execute(sql, data) 47 elif (line[:2] != ">>" and line [:2] != "##"): # grab details under each module NameError: name 'total' is not defined The problem It is I need to write only if exist that names and values. So from the original file each time I have this rows: ##FastQC 0.10.1 >>Basic Statistics pass #Measure Value Filename R05_CTTGTA_L004_R1_001.fastq.gz File type Conventional base calls Encoding Sanger / Illumina 1.9 Total Sequences 27868496 Filtered Sequences 0 Sequence length 50 %GC 50 >>END_MODULE So they need to be defined. So know I need to do: if Total and if Filename and Total then do the script? From davea at davea.name Wed Dec 3 15:52:05 2014 From: davea at davea.name (Dave Angel) Date: Wed, 03 Dec 2014 09:52:05 -0500 Subject: [Tutor] Parse files and create sqlite3 db (Alan Gauld) In-Reply-To: <387082369.654931417612071650.JavaMail.httpd@webmail-07.iol.local> References: <387082369.654931417612071650.JavaMail.httpd@webmail-07.iol.local> Message-ID: <547F2395.7070008@davea.name> On 12/03/2014 08:07 AM, jarod_v6 at libero.it wrote: > thanks so much,here you have the error: > --------------------------------------------------------------------------- > NameError Traceback (most recent call last) > in () > 43 status = line[-4:] # > and overall status pass/warn/fail > 44 sql = "insert into > fastqc_summary(fileid,module,status,total,duplicate) values(?,?,?,?,?);" > ---> 45 data = (fileid,module, > status,total,dup) > 46 cursor.execute(sql, > data) > 47 elif (line[:2] != ">>" and line > [:2] != "##"): # grab details under each module > > NameError: name 'total' is not defined That's because you defined it only inside an if statement. So if that condition is false, total is NOT a variable. Perhaps you just want to give it a default value. I'd tend to do that in an else clause: if "Total Sequence" in line: total = line.split()[2] else: total = "" Similarly for fileid and dup. Now, you can test those values, or use their defaults directly, in whatever other place you need. While I've got you can I request a few things to make the forum go smoother: 1) use text not html messages. You did here, but in your original message you mentioned something about "red" and that doesn't show up everywhere. This is a text forum. 2) Use reply-list or reply-all, or whatever your email program will manage. Whenever you just compose a new message you start a new thread, and that just breaks the flow. Many newsreaders don't handle split threads, and those that do still cause pain for the user. 3) Don't use attachments. Just paste it in with everything else (in a text email, of course, as html messes up indentation about 50% of the time.) Many environments don't even see the attachment. -- DaveA From coolshwetu at gmail.com Wed Dec 3 19:18:22 2014 From: coolshwetu at gmail.com (shweta kaushik) Date: Wed, 3 Dec 2014 23:48:22 +0530 Subject: [Tutor] How to split string into separate lines Message-ID: Hi, I need help for doing this task. I know it will be simple but I am not able to do it. output_message_packet= fe01b84100000000000000002756fe02fe01b94100000000000000006239fe02fe01ba410000000000000000ad88fe02fe01bb410000000000000000e8e7fe02fe01bc41000000000000000012fbfe02fe01bd4100000000000000005794fe02 I want to split this into separate message packets like this: fe01b84100000000000000002756fe02 fe01b94100000000000000006239fe02 fe01ba410000000000000000ad88fe02 fe01bb410000000000000000e8e7fe02 fe01bc41000000000000000012fbfe02 fe01bd4100000000000000005794fe02 After this I want to split this into bytes: fe 01 b8 41 00 00 00 00 00 00 00 00 27 56 fe 02 Please help me with code for how to do this. Thanks in advance. Regards, Shweta -------------- next part -------------- An HTML attachment was scrubbed... URL: From jackjasper at me.com Wed Dec 3 22:02:33 2014 From: jackjasper at me.com (jack jasper) Date: Wed, 03 Dec 2014 15:02:33 -0600 Subject: [Tutor] Python Message-ID: Why do I get SyntaxErrors when I type in an article like a or a colon : Enter an integer an gets listed as a SyntaxError x == 0: The colon gets flagged This is part of an if else program with an x = raw_input('Enter an integer: ') sort of statement above it. I've had trouble with -> with the > being flagged. I just don't get it. Thank you, Jack Jasper jackjasper at mac.com From joel.goldstick at gmail.com Wed Dec 3 23:17:39 2014 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Wed, 3 Dec 2014 17:17:39 -0500 Subject: [Tutor] How to split string into separate lines In-Reply-To: References: Message-ID: On Wed, Dec 3, 2014 at 1:18 PM, shweta kaushik wrote: > Hi, > > I need help for doing this task. I know it will be simple but I am not able > to do it. > > output_message_packet= > fe01b84100000000000000002756fe02fe01b94100000000000000006239fe02fe01ba410000000000000000ad88fe02fe01bb410000000000000000e8e7fe02fe01bc41000000000000000012fbfe02fe01bd4100000000000000005794fe02 > > I want to split this into separate message packets like this: > fe01b84100000000000000002756fe02 > fe01b94100000000000000006239fe02 > fe01ba410000000000000000ad88fe02 > fe01bb410000000000000000e8e7fe02 > fe01bc41000000000000000012fbfe02 > fe01bd4100000000000000005794fe02 > > After this I want to split this into bytes: > fe 01 b8 41 00 00 00 00 00 00 00 00 27 56 fe 02 > > Please help me with code for how to do this. > > Thanks in advance. > > Regards, > Shweta > Look up python string methods to start. Does each line start with fe01? > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor > -- Joel Goldstick http://joelgoldstick.com From joel.goldstick at gmail.com Wed Dec 3 23:20:45 2014 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Wed, 3 Dec 2014 17:20:45 -0500 Subject: [Tutor] Python In-Reply-To: References: Message-ID: On Wed, Dec 3, 2014 at 4:02 PM, jack jasper wrote: > Why do I get SyntaxErrors when I type in an article like a or a colon : > Enter an integer an gets listed as a SyntaxError > > x == 0: The colon gets flagged This is part of an if else program with an colon only goes on end of def, if, elif, else, and for statements > x = raw_input('Enter an integer: ') sort of statement above it. > > I've had trouble with -> with the > being flagged. > > I just don't get it. show your code, give version number (2.x or 3.x). I'm guessing 2.x since you are using raw_input > > Thank you, > > Jack Jasper > jackjasper at mac.com > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor -- Joel Goldstick http://joelgoldstick.com From alan.gauld at btinternet.com Wed Dec 3 23:31:12 2014 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 03 Dec 2014 22:31:12 +0000 Subject: [Tutor] How to split string into separate lines In-Reply-To: References: Message-ID: On 03/12/14 18:18, shweta kaushik wrote: > I need help for doing this task. I know it will be simple but I am not > able to do it. Your description of the task is not very precise so I'll make some guesses below. > output_message_packet= fe01b84100000000000000002756fe02fe01b94100000.... > > I want to split this into separate message packets like this: > fe01b84100000000000000002756fe02 > fe01b94100000000000000006239fe02 It looks like the packet terminator is either fe02 or a fixed length record. It's not clear whether the fixed length is accidental or deliberate or whether its the terminator that is coincidentally the same. I'm guessing its probably based on terminator... To split by 'fe02' just use string split then add the separator back on: sep = 'fe02' packets = [pkt+sep for pkt in data.split(sep)] If it is based on length it will look something like: data = [] while s: data.append(s[:length]) s = s[length:] > After this I want to split this into bytes: > fe 01 b8 41 00 00 00 00 00 00 00 00 27 56 fe 02 This is the same split by length problem applied to each packet with length 2. In fact if it is split by length in both you could write a helper function: def split_by_length(s,length): data = [] while s: data.append(s[:length]) s = s[length:] return data And call it with packets = split_by_length(inputData, packetLength) bytes = [split_by_length(p,2) for p in packets] 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 From alan.gauld at btinternet.com Wed Dec 3 23:33:18 2014 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 03 Dec 2014 22:33:18 +0000 Subject: [Tutor] Python In-Reply-To: References: Message-ID: On 03/12/14 21:02, jack jasper wrote: > Why do I get SyntaxErrors when I type in an article like a or a colon : > Enter an integer an gets listed as a SyntaxError > > x == 0: The colon gets flagged This is part of an if else program with an > x = raw_input('Enter an integer: ') sort of statement above it. > That doesn't help, just post real code that generates the error. And tell us which Python version and OS you are using to run it. > I've had trouble with -> with the > being flagged. I have no idea what you mean by that. When do you ever use -> in Python? -- 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 From coolshwetu at gmail.com Thu Dec 4 06:36:57 2014 From: coolshwetu at gmail.com (shweta kaushik) Date: Thu, 4 Dec 2014 11:06:57 +0530 Subject: [Tutor] How to split string into separate lines In-Reply-To: References: Message-ID: Hi Joel, Yes all lines start with fe01 and ends with fe02. I tried few things and able to split it as list and then I want to split it into bytes of two like s= fe 01 but when I am taking s[0] then it is giving only f instead of fe. On 04-Dec-2014 3:47 am, "Joel Goldstick" wrote: > On Wed, Dec 3, 2014 at 1:18 PM, shweta kaushik > wrote: > > Hi, > > > > I need help for doing this task. I know it will be simple but I am not > able > > to do it. > > > > output_message_packet= > > > fe01b84100000000000000002756fe02fe01b94100000000000000006239fe02fe01ba410000000000000000ad88fe02fe01bb410000000000000000e8e7fe02fe01bc41000000000000000012fbfe02fe01bd4100000000000000005794fe02 > > > > I want to split this into separate message packets like this: > > fe01b84100000000000000002756fe02 > > fe01b94100000000000000006239fe02 > > fe01ba410000000000000000ad88fe02 > > fe01bb410000000000000000e8e7fe02 > > fe01bc41000000000000000012fbfe02 > > fe01bd4100000000000000005794fe02 > > > > After this I want to split this into bytes: > > fe 01 b8 41 00 00 00 00 00 00 00 00 27 56 fe 02 > > > > Please help me with code for how to do this. > > > > Thanks in advance. > > > > Regards, > > Shweta > > > > Look up python string methods to start. > > Does each line start with fe01? > > _______________________________________________ > > Tutor maillist - Tutor at python.org > > To unsubscribe or change subscription options: > > https://mail.python.org/mailman/listinfo/tutor > > > > > > -- > Joel Goldstick > http://joelgoldstick.com > -------------- next part -------------- An HTML attachment was scrubbed... URL: From akleider at sonic.net Thu Dec 4 18:25:25 2014 From: akleider at sonic.net (Alex Kleider) Date: Thu, 04 Dec 2014 09:25:25 -0800 Subject: [Tutor] How to split string into separate lines In-Reply-To: References: Message-ID: <28cd5eb73bb1f4fe9c30dc5a014b672b@sonic.net> On 2014-12-03 21:36, shweta kaushik wrote: > Hi Joel, > > Yes all lines start with fe01 and ends with fe02. Might this problem not be more easily solved using the re module? import re pat_obj = re.compile(r'fe01[0-9a-f]+?fe02') my_list = pat_obj.findall(string2split) > > I tried few things and able to split it as list and then I want to > split it > into bytes of two like s= fe 01 but when I am taking s[0] then it is > giving only f instead of fe. > On 04-Dec-2014 3:47 am, "Joel Goldstick" > wrote: > >> On Wed, Dec 3, 2014 at 1:18 PM, shweta kaushik >> wrote: >> > Hi, >> > >> > I need help for doing this task. I know it will be simple but I am not >> able >> > to do it. >> > >> > output_message_packet= >> > >> fe01b84100000000000000002756fe02fe01b94100000000000000006239fe02fe01ba410000000000000000ad88fe02fe01bb410000000000000000e8e7fe02fe01bc41000000000000000012fbfe02fe01bd4100000000000000005794fe02 >> > >> > I want to split this into separate message packets like this: >> > fe01b84100000000000000002756fe02 >> > fe01b94100000000000000006239fe02 >> > fe01ba410000000000000000ad88fe02 >> > fe01bb410000000000000000e8e7fe02 >> > fe01bc41000000000000000012fbfe02 >> > fe01bd4100000000000000005794fe02 >> > >> > After this I want to split this into bytes: >> > fe 01 b8 41 00 00 00 00 00 00 00 00 27 56 fe 02 >> > >> > Please help me with code for how to do this. >> > >> > Thanks in advance. >> > >> > Regards, >> > Shweta >> > >> >> Look up python string methods to start. >> >> Does each line start with fe01? >> > _______________________________________________ >> > Tutor maillist - Tutor at python.org >> > To unsubscribe or change subscription options: >> > https://mail.python.org/mailman/listinfo/tutor >> > >> >> >> >> -- >> Joel Goldstick >> http://joelgoldstick.com >> > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor From phillifeng at gmail.com Thu Dec 4 21:29:27 2014 From: phillifeng at gmail.com (Lifeng Lin) Date: Thu, 4 Dec 2014 14:29:27 -0600 Subject: [Tutor] How to split string into separate lines In-Reply-To: References: Message-ID: would this work? >>> a="fe01b84100000000000000002756fe02fe01b94100000000000000006239fe02fe01ba410000000000000000ad88fe02fe01bb410000000000000000e8e7fe02fe01bc41000000000000000012fbfe02fe01bd4100000000000000005794fe02" >>> b=a.replace('fe02fe01','fe02\nfe01').split('\n') >>> for c in b: ... print ' '.join([c[i:i+2] for i in range(0, len(c), 2)]) ... fe 01 b8 41 00 00 00 00 00 00 00 00 27 56 fe 02 fe 01 b9 41 00 00 00 00 00 00 00 00 62 39 fe 02 fe 01 ba 41 00 00 00 00 00 00 00 00 ad 88 fe 02 fe 01 bb 41 00 00 00 00 00 00 00 00 e8 e7 fe 02 fe 01 bc 41 00 00 00 00 00 00 00 00 12 fb fe 02 fe 01 bd 41 00 00 00 00 00 00 00 00 57 94 fe 02 On Wed, Dec 3, 2014 at 12:18 PM, shweta kaushik wrote: > Hi, > > I need help for doing this task. I know it will be simple but I am not > able to do it. > > > output_message_packet= fe01b84100000000000000002756fe02fe01b94100000000000000006239fe02fe01ba410000000000000000ad88fe02fe01bb410000000000000000e8e7fe02fe01bc41000000000000000012fbfe02fe01bd4100000000000000005794fe02 > > I want to split this into separate message packets like this: > fe01b84100000000000000002756fe02 > fe01b94100000000000000006239fe02 > fe01ba410000000000000000ad88fe02 > fe01bb410000000000000000e8e7fe02 > fe01bc41000000000000000012fbfe02 > fe01bd4100000000000000005794fe02 > > After this I want to split this into bytes: > fe 01 b8 41 00 00 00 00 00 00 00 00 27 56 fe 02 > > Please help me with code for how to do this. > > Thanks in advance. > > Regards, > Shweta > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From walksloud at gmail.com Fri Dec 5 04:21:09 2014 From: walksloud at gmail.com (=?windows-1252?Q?=22Andr=E9_Walker-Loud_=3Cwalksloud=40gmail=2Ec?= =?windows-1252?Q?om=3E=22?=) Date: Thu, 4 Dec 2014 22:21:09 -0500 Subject: [Tutor] emacs and tabs/spaces Message-ID: <36B2A6A4-98CB-4515-80A2-1B199AE7B292@gmail.com> Hi All, I haven?t found an answer yet to this question via google or tutor archives. For those of you who use emacs as an editor, I have the following problem. I have edited my .emacs file to have (add-hook 'python-mode-hook (lambda () (setq indent-tabs-mode t) (setq tab-width 4) (setq python-indent 4))) which sets my ?tab? to 4 spaces. However, if I have a line that is too long (more than 80 characters), I often break the line in multiple lines and use ?tab? to align them, eg. params.update({'MAX_T':iv.nt,'ENSEMBLE_ID':ens_base, 'MOM_MBS_MAX':'0', 'BARYON_DB':mbs_dir+'/'+mbs, }) In this case, the ?tab? alignment does not make it an integer number of 4 spaces - so when I try and edit the file on a different machine, with another editor (TextWrangler) that does actually put all tabs to 4 spaces, I end up breaking my files often. Does anyone know how to get emacs to force ?tab? to stay at integer numbers of 4 spaces with these multi-lines? Thanks, Andre From ben+python at benfinney.id.au Fri Dec 5 06:39:29 2014 From: ben+python at benfinney.id.au (Ben Finney) Date: Fri, 05 Dec 2014 16:39:29 +1100 Subject: [Tutor] emacs and tabs/spaces References: <36B2A6A4-98CB-4515-80A2-1B199AE7B292@gmail.com> Message-ID: <85bnniu032.fsf@benfinney.id.au> "Andr? Walker-Loud " writes: > In this case, the ?tab? alignment does not make it an integer number > of 4 spaces - so when I try and edit the file on a different machine, > with another editor (TextWrangler) that does actually put all tabs to > 4 spaces, I end up breaking my files often. This is an excellent reason to stop using U+0009 (HT) characters for indentation at all. Instead, set ?indent-tabs-mode? to false (?nil?), and Emacs will indent with the specified number of U+0020 (SPACE) characters. You won't be at the mercy of the chaotic differences in rendering of U+0009 characters. -- \ ?I went to a restaurant that serves ?breakfast at any time?. So | `\ I ordered French Toast during the Renaissance.? ?Steven Wright | _o__) | Ben Finney From marina.woodson at gmail.com Fri Dec 5 17:37:32 2014 From: marina.woodson at gmail.com (Marina Woodson) Date: Fri, 5 Dec 2014 09:37:32 -0700 Subject: [Tutor] Tutor Message-ID: <3AE4AE1E-0D7D-4D2D-8D60-A3C4D4A19A54@gmail.com> I am looking for a tutor. I have a project due in a couple of days and cannot complete the code on my own. How does this system here work? Thank you, Marina Woodson From joel.goldstick at gmail.com Fri Dec 5 21:05:52 2014 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Fri, 5 Dec 2014 15:05:52 -0500 Subject: [Tutor] Tutor In-Reply-To: <3AE4AE1E-0D7D-4D2D-8D60-A3C4D4A19A54@gmail.com> References: <3AE4AE1E-0D7D-4D2D-8D60-A3C4D4A19A54@gmail.com> Message-ID: On Fri, Dec 5, 2014 at 11:37 AM, Marina Woodson wrote: > I am looking for a tutor. I have a project due in a couple of days and cannot complete the code on my own. How does this system here work? You may find someone who would be willing to help you, but the way this works is you state your problem, show the code you have written, and ask a question. You should include which version of python you are using, and also cut and paste any traceback errors that are displayed when you run your code. Be thoughtful with your subject line,so as to attract people who might know something about what you need to learn. There are lots of people here to help. > > Thank you, > > Marina Woodson > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor -- Joel Goldstick http://joelgoldstick.com From alan.gauld at btinternet.com Fri Dec 5 21:10:03 2014 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 05 Dec 2014 20:10:03 +0000 Subject: [Tutor] Tutor In-Reply-To: <3AE4AE1E-0D7D-4D2D-8D60-A3C4D4A19A54@gmail.com> References: <3AE4AE1E-0D7D-4D2D-8D60-A3C4D4A19A54@gmail.com> Message-ID: On 05/12/14 16:37, Marina Woodson wrote: > I am looking for a tutor. You've just found several hundred... :-) > I have a project due in a couple of days and cannot complete the > code on my own. How does this system here work? We won't do your code for you but you can post samples and ask for feedback, you can also ask general programming questions. Our scope is the Python language and standard library. 3rd party library issues should be resolved on those library fora. When posting always include full error text and tell us the Python version and OS in use. If you are using a specific tutorial or development tool that can be useful info too. Post in plain text please. -- 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 From dyoo at hashcollision.org Fri Dec 5 21:24:19 2014 From: dyoo at hashcollision.org (Danny Yoo) Date: Fri, 5 Dec 2014 12:24:19 -0800 Subject: [Tutor] Tutor In-Reply-To: References: <3AE4AE1E-0D7D-4D2D-8D60-A3C4D4A19A54@gmail.com> Message-ID: On Fri, Dec 5, 2014 at 12:05 PM, Joel Goldstick wrote: > On Fri, Dec 5, 2014 at 11:37 AM, Marina Woodson > wrote: >> I am looking for a tutor. I have a project due in a couple of days and cannot complete the code on my own. How does this system here work? > > You may find someone who would be willing to help you, but the way > this works is you state your problem, show the code you have written, > and ask a question. You should include which version of python you > are using, and also cut and paste any traceback errors that are > displayed when you run your code. Be thoughtful with your subject > line,so as to attract people who might know something about what you > need to learn. I want to second that there are plenty of folk here who like to help. But as a caveat: you may have heard the phrase: "There's no such thing as a bad question." In a sense, this aphorism is right, but in another sense, it's wrong. There are certain questions that will produce bad results in context. In the context of a volunteer mailing list that teaches programming, there are few things that kill enthusiasm more quickly than a "question" of the form: "My project's not working. Fix it for me." Instead of a request for someone to finish your homework, make effort to ask a good question: try to isolate the problem you're having, reduce it down to a small question, and try to verbalize what you're having difficulty with. That is, direct your goals from: "I need to get this project done tomorrow." to: "Here's something I don't understand. I thought this and this would work, but it doesn't. Can you help me understand why?" Good luck! From ben+python at benfinney.id.au Fri Dec 5 21:38:21 2014 From: ben+python at benfinney.id.au (Ben Finney) Date: Sat, 06 Dec 2014 07:38:21 +1100 Subject: [Tutor] Tutor References: <3AE4AE1E-0D7D-4D2D-8D60-A3C4D4A19A54@gmail.com> Message-ID: <85y4qlsugy.fsf@benfinney.id.au> Marina Woodson writes: > I am looking for a tutor. I have a project due in a couple of days and > cannot complete the code on my own. How does this system here work? Welcome! This system works by discussing, in this public forum, your code and the questions you have. This is not a forum for getting a private tutor, but for learning in public to help all of us together. -- \ ?He who laughs last, thinks slowest.? ?anonymous | `\ | _o__) | Ben Finney From anubhav1691 at gmail.com Sun Dec 7 15:24:53 2014 From: anubhav1691 at gmail.com (Anubhav Yadav) Date: Sun, 7 Dec 2014 19:54:53 +0530 Subject: [Tutor] Need a little help in formatting print statement Message-ID: I am trying to solve the CS1 Python Exercises. The first exercise calculates the energy released from an earthquake based on it's ritcher scale. I wrote the code. Here is the code. I am supposed to get this output: If I use the %f formatter, I get this output: Ritcher Scale Energy TNT 1.0 1995262.314969 0.0005 5.0 1995262314968.882812 476.8791 9.1 2818382931264449024.000000 673609687.2047 9.2 3981071705534952960.000000 951498973.5982 9.5 11220184543019653120.000000 2681688466.3049 and If I use the %e or %g format specifier I get this: Ritcher Scale Energy TNT 1.0 1.99526e+06 0.0005 5.0 1.99526e+12 476.8791 9.1 2.81838e+18 673609687.2047 9.2 3.98107e+18 951498973.5982 9.5 1.12202e+19 2681688466.3049 In the sample output given by the exercise, the first two values do not use the scientific notation. So either they are not using a loop to print the table, or there is a format specifier that prints the floating value in scientific notation only if some condition is checked. I know there is a String function called format with which I can achieve great string formatting but I want to stick with the old C ways of formatting for now. Any suggestions would be greatly appreciated. -- Regards, Anubhav Yadav KPIT Technologies, Pune. -------------- next part -------------- An HTML attachment was scrubbed... URL: From crushed26 at gmail.com Sun Dec 7 16:22:28 2014 From: crushed26 at gmail.com (Bo Morris) Date: Sun, 7 Dec 2014 10:22:28 -0500 Subject: [Tutor] Python Projects Message-ID: The book arrived this morning. Thanks Alan! Bo -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at pearwood.info Sun Dec 7 16:35:53 2014 From: steve at pearwood.info (Steven D'Aprano) Date: Mon, 8 Dec 2014 02:35:53 +1100 Subject: [Tutor] Need a little help in formatting print statement In-Reply-To: References: Message-ID: <20141207153553.GL9865@ando.pearwood.info> Hello Anubhav and welcome! On Sun, Dec 07, 2014 at 07:54:53PM +0530, Anubhav Yadav wrote: > I am trying to solve the CS1 Python > Exercises. > > The first exercise calculates the energy released from an earthquake based > on it's ritcher scale. > > I wrote the code. Here is the code. If your code is short enough, say, less than 50 lines, please include it directly in your email. Some of us are reading and replying to posts at a time where it is inconvenient to access the web, or at least parts of the web. > I am supposed to get this output: > > If I use the %f formatter, I get this output: [...] Try using the %r formatter: py> for x in (1995262.314969, 1995262314968.882812, ... 2818382931264449024.0, 11220184543019653120.0): ... print( "%r" % x ) # same as print(repr(x)) ... 1995262.314969 1995262314968.8828 2.818382931264449e+18 1.1220184543019653e+19 -- Steven From 2010-3902 at slougheton.com Sun Dec 7 16:27:42 2014 From: 2010-3902 at slougheton.com (Awais Idris) Date: Sun, 7 Dec 2014 15:27:42 +0000 Subject: [Tutor] Coding Message-ID: Hi there, I'm currently in secondary school yr 11 studying the computing course and I've been set a task in creating a vending machine code. I found some coding online and I have changed some of it, but it still doesn't work. I think theres a problem with the loops and a few other things that I cant put my finger on. I was wondering if you could help me by fixing the code for me. this would be a massive help. Thanks -------------- next part -------------- An HTML attachment was scrubbed... URL: -------------- next part -------------- ##Vending Machine print ("Welcome to the Awais's Vending Machine\n") total = 0 drinks = 4 snacks = 4 print ("Prices: Drinks: ?4, Snacks: ?4\n") print ("If you want to be surprised, and have a random choice, type: 'random'\n") Drinks = {'Coke','Sprite','Water'} Snacks = {'Hershey', 'Snickers','Twix','Maltesers','Crisps'} print (Drinks) print (Snacks) FirstChoice = input ("Enter the item of your choice: ") ##First Choices if FirstChoice == 'Coke' or 'Pepsi' or 'Water': print ("That will be a total of ?",drinks) elif FirstChoice == 'Hershey' or 'Snickers' or 'Twix' or 'Maltesers' or 'Crisps': print ("That ^will be a total of ?",snacks) else: print ("****er") SecondChoice = input ("Would you like anything else? Yes/No ") ##Second Choices if SecondChoice == "Yes" or "yes": print (Drinks) print (Snacks) if SecondChoice == (Drinks): print ("That will be a total of ?",drinks) elif SecondChoice == (Snacks): print ("That will be a total of ?",snacks) else: print ("****er") if SecondChoice == "no" or "No": print ("Excellent! Have a good day!") From anubhav1691 at gmail.com Sun Dec 7 18:01:21 2014 From: anubhav1691 at gmail.com (Anubhav Yadav) Date: Sun, 7 Dec 2014 22:31:21 +0530 Subject: [Tutor] Need a little help in formatting print statement In-Reply-To: <20141207153553.GL9865@ando.pearwood.info> References: <20141207153553.GL9865@ando.pearwood.info> Message-ID: > If your code is short enough, say, less than 50 lines, please include it > directly in your email. Some of us are reading and replying to posts at > a time where it is inconvenient to access the web, or at least parts of > the web. > > Yes sure, next time I will keep that in mind. > Try using the %r formatter: > > py> for x in (1995262.314969, 1995262314968.882812, > ... 2818382931264449024.0, 11220184543019653120.0): > ... print( "%r" % x ) # same as print(repr(x)) > ... > 1995262.314969 > 1995262314968.8828 > 2.818382931264449e+18 > 1.1220184543019653e+19 > > I had read about this formatter before, thanks a lot. Cheers!! -- Regards, Anubhav Yadav KPIT Technologies, Pune. -------------- next part -------------- An HTML attachment was scrubbed... URL: From diliupg at gmail.com Sun Dec 7 18:38:02 2014 From: diliupg at gmail.com (diliup gabadamudalige) Date: Sun, 7 Dec 2014 23:08:02 +0530 Subject: [Tutor] getting input for stdin Message-ID: Dear alll, my code is given below if __name__ == '__main__': p = os.getcwd() filename = "\get scale of choice.txt" filepath = p + filename sys.stdout = open(filepath, "w") os.startfile(filepath) for i in data.info: # print all the scale info to window print i run = True while run: scaletemplate = ["C", "D", "E", "F", "G", "A", "B"] getscale = sys.stdin.raw_input(filepath) #getscale = raw_input("Which scale do you require?:") if len(getscale) > 1: getscale = getscale[0].upper() + getscale[1:] else: getscale = getscale.upper() if getscale in data.scalenames: scale = main(getscale) print scale elif getscale == "Q" or getscale == "X" or getscale == "": run = False print"exiting..." else: print "No such scale" I need to get the stdin input from the text I type into the same text file that I have stdout at. How do I do that. None of the answers at stackoverflow got me going. Any help on a code snippet would be appreciated. Thanks in advance -- 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. ********************************************************************************************** -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Mon Dec 8 02:47:39 2014 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 08 Dec 2014 01:47:39 +0000 Subject: [Tutor] Coding In-Reply-To: References: Message-ID: On 07/12/14 15:27, Awais Idris wrote: > found some coding online and I have changed some of it, but it still > doesn't work. I think theres a problem with the loops and a few other > things that I cant put my finger on. First, Please post the code into your message rather than as an attachment. Its easier to reply to that way... Second, you don't have any loops. Loops are where the code repeats itself until some condition is true. You have selections not loops. With those nitpicks out of the way... > Drinks = {'Coke','Sprite','Water'} > Snacks = {'Hershey', 'Snickers','Twix','Maltesers','Crisps'} > > FirstChoice = input ("Enter the item of your choice: ") > if FirstChoice == 'Coke' or 'Pepsi' or 'Water': > print ("That will be a total of ?",drinks) The or statements don't do what you think. Python sees it like: if FirstChoice == ('Coke' or 'Pepsi' or 'Water'): So evaluates the bit in parens first which results in a boolean value of True. So it sees the 'if' part as: if FirstChoice == True: Which it isn't, so the if never prints. > elif FirstChoice == 'Hershey' or 'Snickers' or 'Twix' or 'Maltesers' Same here... > else: > print ("****er") So this is what gets printed each time... > SecondChoice = input ("Would you like anything else? Yes/No ") > if SecondChoice == "Yes" or "yes": And again... if SecondChoice == (Drinks): print ("That will be a total of ?",drinks) elif SecondChoice == (Snacks): print ("That will be a total of ?",snacks) Not sure what you think happens here but again they will both be False so won't print. I suspect you need to look at the 'in' operator. Then you can do things like: if FirstChoice in Drinks: and so on. 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 From dyoo at hashcollision.org Mon Dec 8 02:44:38 2014 From: dyoo at hashcollision.org (Danny Yoo) Date: Sun, 7 Dec 2014 17:44:38 -0800 Subject: [Tutor] getting input for stdin In-Reply-To: References: Message-ID: > I need to get the stdin input from the text I type into the same text file > that I have stdout at. How do I do that. None of the answers at > stackoverflow got me going. Any help on a code snippet would be appreciated. In-place edits of a file are dangerous, especially as a beginner. This is because if your program makes a mistake before the end, you have very limited ways to recover. What's usually better practice is to write outputs to a separate file, with a similar-but-different name. That way, once your program has completed, you can inspect the contents of the new file, and then if things look ok, finally you can copy the new file over the old file. Can you do this instead? From dyoo at hashcollision.org Mon Dec 8 02:52:28 2014 From: dyoo at hashcollision.org (Danny Yoo) Date: Sun, 7 Dec 2014 17:52:28 -0800 Subject: [Tutor] Coding In-Reply-To: References: Message-ID: On Sun, Dec 7, 2014 at 7:27 AM, Awais Idris <2010-3902 at slougheton.com> wrote: > Hi there, I'm currently in secondary school yr 11 studying the computing > course and I've been set a task in creating a vending machine code. I found > some coding online and I have changed some of it, but it still doesn't work. > I think theres a problem with the loops and a few other things that I cant > put my finger on. I was wondering if you could help me by fixing the code > for me. this would be a massive help. We will try to help you understand your problems. But you are responsible for fixing your program, not us. There's a difference between a tutor and a contractor. A tutor helps you to learn to do your job. A contractor does the job for you. A tutor is not a contractor. Can you describe what you mean by "doesn't work"? Do you see an error message? What behavior do you think is wrong, and why? I will point out a possible mistake that you are making a few times in your program: I see the following: if FirstChoice == 'Coke' or 'Pepsi' or 'Water': ... I will try to paraphrase what Python will take as the meaning of this statement. "If: FirstChoice == 'Coke' is a true value, or if 'Pepsi' is a true value, or if 'Water' is a true value, then do the following: ..." Does this match what you are trying to do? From alan.gauld at btinternet.com Mon Dec 8 03:03:16 2014 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 08 Dec 2014 02:03:16 +0000 Subject: [Tutor] getting input for stdin In-Reply-To: References: Message-ID: On 07/12/14 17:38, diliup gabadamudalige wrote: > if __name__ == '__main__': You don't really need that unless your code can be treated as a module, which yours can't. > p = os.getcwd() > filename = "\get scale of choice.txt" > filepath = p + filename > sys.stdout = open(filepath, "w") Why are you overwriting stdout with a file? Why not just write to the file directly? Usually if you do overwrite stdout you make a reference to the old stdout first so you can restore it later. > os.startfile(filepath) This tries to execute filepath, but you just opened it in write mode which creates an empty file. So you are trying to execute an empty file? > for i in data.info : What is data? and what is the url like thing supposed to be? Have you done a tutorial on Python? Do you understand how the for loop works? It needs an iterator/collection to operate on. # print all the scale info > to window > print i This will print to stdout, which you have assigned to a file above. So it won't print in any window. > run = True > while run: > scaletemplate = ["C", "D", "E", "F", "G", "A", "B"] > getscale = sys.stdin.raw_input(filepath) Not sure what this is doing but raw_input reads from stdin - it is not a method of stdin. And the argument to stdin is supposed to be a prompt to the user, you have passed a filename? > #getscale = raw_input("Which scale do you require?:") > > if len(getscale) > 1: > getscale = getscale[0].upper() + getscale[1:] getscale is commented out so this will raise an error. > else: > getscale = getscale.upper() > if getscale in data.scalenames: > scale = main(getscale) > print scale Again, what is data? > elif getscale == "Q" or getscale == "X" or getscale == "": > run = False > print"exiting..." > else: > print "No such scale" Again, these prints will go to your file since it is stdout. > I need to get the stdin input from the text I type into the same text > file that I have stdout at. How would that work exactly? You want to open the file in a text editor or somesuch? Then as you type into it you want Python to read the values you type? Before you save it? Or after? And you also want the output from Python to go into the file that you are editing? While you are editing it? Can you explain exactly how the user is expected to use this combination of things? It is not clear, very unlike any normal computing task and probably impossible. I suspect you have a concept in your mind but it's not what you are describing here. > How do I do that. None of the answers at > stackoverflow got me going. I'm not surproised, I think what you are asking is impossible (or at least very difficult) , and even if it isn't it would be a weird way of working. -- 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 From steve at pearwood.info Mon Dec 8 03:24:09 2014 From: steve at pearwood.info (Steven D'Aprano) Date: Mon, 8 Dec 2014 13:24:09 +1100 Subject: [Tutor] Coding In-Reply-To: References: Message-ID: <20141208022409.GN9865@ando.pearwood.info> On Mon, Dec 08, 2014 at 01:47:39AM +0000, Alan Gauld wrote: > > FirstChoice = input ("Enter the item of your choice: ") > > if FirstChoice == 'Coke' or 'Pepsi' or 'Water': > > print ("That will be a total of ?",drinks) > > The or statements don't do what you think. > > Python sees it like: > > if FirstChoice == ('Coke' or 'Pepsi' or 'Water'): > > So evaluates the bit in parens first which results in a boolean value of > True. Actually it sees it as: if ((FirstChoice == 'Coke') or 'Pepsi' or 'Water'): which will always evaluate as True. *Technically* it will evaluate as either True or 'Pepsi', which is a truthy value, so the if block will always run. What we actually want is one of these: # The long way if (FirstChoice == 'Coke') or (FirstChoice == 'Pepsi') or (FirstChoice == 'Water'): # The short way if FirstChoice in ('Coke', 'Pepsi', 'Water'): -- Steven From alan.gauld at btinternet.com Mon Dec 8 09:14:51 2014 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 08 Dec 2014 08:14:51 +0000 Subject: [Tutor] getting input for stdin In-Reply-To: References: Message-ID: <54855DFB.2010603@btinternet.com> Forwarding tom list Please always use Reply All (or Reply List) to include the list. On 08/12/14 03:11, diliup gabadamudalige wrote: > Dear Allen, > > :) > > Thank you very much for the responses but some things have been > totally misunderstood here. :) > > 1.What I want to do is to redirect the output of the program to a text > file instead of the standard Python output. That is why I opened the > text file. That part of the program works fine. > > 2. data is a py file named data.py which holds all the text I need to > be printed to the console. As it is an explanation of music theory and > will be large i have put it into a separate file which is loaded as a > module at the begining of the program. hence data.info > which is a list of strings which are printed to the > scree. Hence in my program I open a text file and send the print out > put to that which is then printed to the text file. This works too. > > 3. When I ask for input in python the prompt which is usually in the > Python output console waits for the user input and returns that as a > string. > 4.Insted of 3 above I would like the user to be able to type into a > text file which may be opened by the program to collect input. For > instance i open a text file named give_me_your_input.txt and then the > user types his requirement in that text file which is taken as a > string by the program which in turn either returns the appropriate answer. > > I know how to do everything else above except how to get the input > from the text file in real time. > > My program works without any flaws without any of the stdin or stdout > in the normal console. > > I hope this is clear enough to supply me with an answer. > > I thank you once again for your time and hope you can spare a little > more to help me on the way. > > > On Mon, Dec 8, 2014 at 7:33 AM, Alan Gauld > wrote: > > On 07/12/14 17:38, diliup gabadamudalige wrote: > > if __name__ == '__main__': > > > You don't really need that unless your code can be treated > as a module, which yours can't. > > p = os.getcwd() > filename = "\get scale of choice.txt" > filepath = p + filename > sys.stdout = open(filepath, "w") > > > Why are you overwriting stdout with a file? > Why not just write to the file directly? > Usually if you do overwrite stdout you make a reference > to the old stdout first so you can restore it later. > > os.startfile(filepath) > > > This tries to execute filepath, but you just opened it > in write mode which creates an empty file. So you are > trying to execute an empty file? > > for i in data.info : > > > What is data? > and what is the url like thing supposed to be? > > Have you done a tutorial on Python? > Do you understand how the for loop works? > It needs an iterator/collection to operate on. > > # print all the scale info > > to window > print i > > > This will print to stdout, which you have assigned > to a file above. So it won't print in any window. > > run = True > while run: > scaletemplate = ["C", "D", "E", "F", "G", "A", "B"] > getscale = sys.stdin.raw_input(filepath) > > > Not sure what this is doing but raw_input reads from > stdin - it is not a method of stdin. And the argument to stdin is > supposed to be a prompt to the user, you have passed a filename? > > #getscale = raw_input("Which scale do you require?:") > > if len(getscale) > 1: > getscale = getscale[0].upper() + getscale[1:] > > > getscale is commented out so this will raise an error. > > else: > getscale = getscale.upper() > > > if getscale in data.scalenames: > scale = main(getscale) > print scale > > > Again, what is data? > > elif getscale == "Q" or getscale == "X" or getscale > == "": > run = False > print"exiting..." > else: > print "No such scale" > > > Again, these prints will go to your file since it is stdout. > > I need to get the stdin input from the text I type into the > same text > file that I have stdout at. > > > How would that work exactly? > You want to open the file in a text editor or somesuch? Then as > you type into it you want Python to read the values you type? > Before you save it? Or after? And you also want the output from > Python to go into the file that you are editing? While you are > editing it? > > Can you explain exactly how the user is expected to use this > combination of things? > > It is not clear, very unlike any normal computing task and > probably impossible. I suspect you have a concept in your mind but > it's not > what you are describing here. > > How do I do that. None of the answers at > stackoverflow got me going. > > > I'm not surproised, I think what you are asking is impossible > (or at least very difficult) , and even if it isn't it would be > a weird way of working. > > -- > 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 at 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. > ********************************************************************************************** > From alan.gauld at btinternet.com Mon Dec 8 09:17:54 2014 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 08 Dec 2014 08:17:54 +0000 Subject: [Tutor] Coding In-Reply-To: <20141208022409.GN9865@ando.pearwood.info> References: <20141208022409.GN9865@ando.pearwood.info> Message-ID: On 08/12/14 02:24, Steven D'Aprano wrote: >> Python sees it like: >> >> if FirstChoice == ('Coke' or 'Pepsi' or 'Water'): >> >> So evaluates the bit in parens first which results in a boolean value of >> True. > > > Actually it sees it as: > > if ((FirstChoice == 'Coke') or 'Pepsi' or 'Water'): > > which will always evaluate as True. Oops, you're right. Always test... > # The short way > if FirstChoice in ('Coke', 'Pepsi', 'Water'): Which is what I was suggesting so we get to the same end game :-) -- 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 From alan.gauld at btinternet.com Mon Dec 8 09:15:28 2014 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 08 Dec 2014 08:15:28 +0000 Subject: [Tutor] getting input for stdin In-Reply-To: References: Message-ID: <54855E20.8020603@btinternet.com> Forwarding tom list Please always use Reply All (or Reply List) to include the list. On 08/12/14 03:50, diliup gabadamudalige wrote: > I managed to get the output file and input file working. > The output works fine but the input does not. It simply exits the > program. No crash. Exits.It DOES NOT WAIT FOR ME TO TYPE IN THE > inputfile.txt > > here is the program in all. > > I have attached the whole program if you think that will help. > if __name__ == '__main__': > ## menna me kaalla to change the output path > p = os.getcwd() > outfile = "\output_file.txt" > infile = "\input_file.txt" > > outfilepath = p + outfile > infilepath = p + infile > > sys.stdout = open(outfilepath, "w+") > sys.stdin = open(infilepath, "w+") > > os.startfile(outfilepath) > os.startfile(infilepath) > ##-------------------------------------------- > > for i in data.info : # print all the scale info > to window > > print i > > run = True > > while run: > scaletemplate = ["C", "D", "E", "F", "G", "A", "B"] > ## menna input ganna thana > getscale = sys.stdin.readline() > raw_input("Which scale do you require?:") > ##--------------------------------------- > print getscale > > > > if len(getscale) > 1: > getscale = getscale[0].upper() + getscale[1:] > else: > getscale = getscale.upper() > > > > if getscale in data.scalenames: > > scale = main(getscale) > > print scale > > elif getscale == "Q" or getscale == "X" or getscale == "": > run = False > print"exiting..." > > else: > print "No such scale" > > On Mon, Dec 8, 2014 at 8:49 AM, diliup gabadamudalige > > wrote: > > I do not need to save any info in the text files opened for stdout > and stdin. > The text files are empty files used only for Python output or Input. > I only need to use them as standard output and input. > I do not need to both above in the same file. > They may be in two different files. > after the user gets his answers from the program, on exit the > files may be closed without saving. > > Sorry for not adding the above in the previous email. > Thank you again. > > On Mon, Dec 8, 2014 at 8:41 AM, diliup gabadamudalige > > wrote: > > Dear Allen, > > :) > > Thank you very much for the responses but some things have > been totally misunderstood here. :) > > 1.What I want to do is to redirect the output of the program > to a text file instead of the standard Python output. That is > why I opened the text file. That part of the program works fine. > > 2. data is a py file named data.py which holds all the text I > need to be printed to the console. As it is an explanation of > music theory and will be large i have put it into a separate > file which is loaded as a module at the begining of the > program. hence data.info which is a list of > strings which are printed to the scree. Hence in my program I > open a text file and send the print out put to that which is > then printed to the text file. This works too. > > 3. When I ask for input in python the prompt which is usually > in the Python output console waits for the user input and > returns that as a string. > 4.Insted of 3 above I would like the user to be able to type > into a text file which may be opened by the program to collect > input. For instance i open a text file named > give_me_your_input.txt and then the user types his requirement > in that text file which is taken as a string by the program > which in turn either returns the appropriate answer. > > I know how to do everything else above except how to get the > input from the text file in real time. > > My program works without any flaws without any of the stdin or > stdout in the normal console. > > I hope this is clear enough to supply me with an answer. > > I thank you once again for your time and hope you can spare a > little more to help me on the way. > > > On Mon, Dec 8, 2014 at 7:33 AM, Alan Gauld > > > wrote: > > On 07/12/14 17:38, diliup gabadamudalige wrote: > > if __name__ == '__main__': > > > You don't really need that unless your code can be treated > as a module, which yours can't. > > p = os.getcwd() > filename = "\get scale of choice.txt" > filepath = p + filename > sys.stdout = open(filepath, "w") > > > Why are you overwriting stdout with a file? > Why not just write to the file directly? > Usually if you do overwrite stdout you make a reference > to the old stdout first so you can restore it later. > > os.startfile(filepath) > > > This tries to execute filepath, but you just opened it > in write mode which creates an empty file. So you are > trying to execute an empty file? > > for i in data.info > : > > > What is data? > and what is the url like thing supposed to be? > > Have you done a tutorial on Python? > Do you understand how the for loop works? > It needs an iterator/collection to operate on. > > # print all the scale info > > to window > print i > > > This will print to stdout, which you have assigned > to a file above. So it won't print in any window. > > run = True > while run: > scaletemplate = ["C", "D", "E", "F", "G", > "A", "B"] > getscale = sys.stdin.raw_input(filepath) > > > Not sure what this is doing but raw_input reads from > stdin - it is not a method of stdin. And the argument to > stdin is supposed to be a prompt to the user, you have > passed a filename? > > #getscale = raw_input("Which scale do you > require?:") > > if len(getscale) > 1: > getscale = getscale[0].upper() + getscale[1:] > > > getscale is commented out so this will raise an error. > > else: > getscale = getscale.upper() > > > if getscale in data.scalenames: > scale = main(getscale) > print scale > > > Again, what is data? > > elif getscale == "Q" or getscale == "X" or > getscale == "": > run = False > print"exiting..." > else: > print "No such scale" > > > Again, these prints will go to your file since it is stdout. > > I need to get the stdin input from the text I type > into the same text > file that I have stdout at. > > > How would that work exactly? > You want to open the file in a text editor or somesuch? > Then as you type into it you want Python to read the > values you type? Before you save it? Or after? And you > also want the output from Python to go into the file that > you are editing? While you are editing it? > > Can you explain exactly how the user is expected to use > this combination of things? > > It is not clear, very unlike any normal computing task and > probably impossible. I suspect you have a concept in your > mind but it's not > what you are describing here. > > How do I do that. None of the answers at > stackoverflow got me going. > > > I'm not surproised, I think what you are asking is impossible > (or at least very difficult) , and even if it isn't it > would be > a weird way of working. > > -- > 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 at 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. > ********************************************************************************************** > > > > > -- > 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. > ********************************************************************************************** > > > > > -- > 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. > ********************************************************************************************** > From alan.gauld at btinternet.com Mon Dec 8 09:15:08 2014 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 08 Dec 2014 08:15:08 +0000 Subject: [Tutor] getting input for stdin In-Reply-To: References: Message-ID: <54855E0C.1010006@btinternet.com> Forwarding tom list Please always use Reply All (or Reply List) to include the list. On 08/12/14 03:19, diliup gabadamudalige wrote: > I do not need to save any info in the text files opened for stdout and > stdin. > The text files are empty files used only for Python output or Input. > I only need to use them as standard output and input. > I do not need to both above in the same file. > They may be in two different files. > after the user gets his answers from the program, on exit the files > may be closed without saving. > > Sorry for not adding the above in the previous email. > Thank you again. > > On Mon, Dec 8, 2014 at 8:41 AM, diliup gabadamudalige > > wrote: > > Dear Allen, > > :) > > Thank you very much for the responses but some things have been > totally misunderstood here. :) > > 1.What I want to do is to redirect the output of the program to a > text file instead of the standard Python output. That is why I > opened the text file. That part of the program works fine. > > 2. data is a py file named data.py which holds all the text I need > to be printed to the console. As it is an explanation of music > theory and will be large i have put it into a separate file which > is loaded as a module at the begining of the program. hence > data.info which is a list of strings which are > printed to the scree. Hence in my program I open a text file and > send the print out put to that which is then printed to the text > file. This works too. > > 3. When I ask for input in python the prompt which is usually in > the Python output console waits for the user input and returns > that as a string. > 4.Insted of 3 above I would like the user to be able to type into > a text file which may be opened by the program to collect input. > For instance i open a text file named give_me_your_input.txt and > then the user types his requirement in that text file which is > taken as a string by the program which in turn either returns the > appropriate answer. > > I know how to do everything else above except how to get the input > from the text file in real time. > > My program works without any flaws without any of the stdin or > stdout in the normal console. > > I hope this is clear enough to supply me with an answer. > > I thank you once again for your time and hope you can spare a > little more to help me on the way. > > > On Mon, Dec 8, 2014 at 7:33 AM, Alan Gauld > > wrote: > > On 07/12/14 17:38, diliup gabadamudalige wrote: > > if __name__ == '__main__': > > > You don't really need that unless your code can be treated > as a module, which yours can't. > > p = os.getcwd() > filename = "\get scale of choice.txt" > filepath = p + filename > sys.stdout = open(filepath, "w") > > > Why are you overwriting stdout with a file? > Why not just write to the file directly? > Usually if you do overwrite stdout you make a reference > to the old stdout first so you can restore it later. > > os.startfile(filepath) > > > This tries to execute filepath, but you just opened it > in write mode which creates an empty file. So you are > trying to execute an empty file? > > for i in data.info : > > > What is data? > and what is the url like thing supposed to be? > > Have you done a tutorial on Python? > Do you understand how the for loop works? > It needs an iterator/collection to operate on. > > # print all the scale info > > to window > print i > > > This will print to stdout, which you have assigned > to a file above. So it won't print in any window. > > run = True > while run: > scaletemplate = ["C", "D", "E", "F", "G", "A", "B"] > getscale = sys.stdin.raw_input(filepath) > > > Not sure what this is doing but raw_input reads from > stdin - it is not a method of stdin. And the argument to stdin > is supposed to be a prompt to the user, you have passed a > filename? > > #getscale = raw_input("Which scale do you require?:") > > if len(getscale) > 1: > getscale = getscale[0].upper() + getscale[1:] > > > getscale is commented out so this will raise an error. > > else: > getscale = getscale.upper() > > > if getscale in data.scalenames: > scale = main(getscale) > print scale > > > Again, what is data? > > elif getscale == "Q" or getscale == "X" or > getscale == "": > run = False > print"exiting..." > else: > print "No such scale" > > > Again, these prints will go to your file since it is stdout. > > I need to get the stdin input from the text I type into > the same text > file that I have stdout at. > > > How would that work exactly? > You want to open the file in a text editor or somesuch? Then > as you type into it you want Python to read the values you > type? Before you save it? Or after? And you also want the > output from Python to go into the file that you are editing? > While you are editing it? > > Can you explain exactly how the user is expected to use this > combination of things? > > It is not clear, very unlike any normal computing task and > probably impossible. I suspect you have a concept in your mind > but it's not > what you are describing here. > > How do I do that. None of the answers at > stackoverflow got me going. > > > I'm not surproised, I think what you are asking is impossible > (or at least very difficult) , and even if it isn't it would be > a weird way of working. > > -- > 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 at 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. > ********************************************************************************************** > > > > > -- > 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. > ********************************************************************************************** > From alan.gauld at btinternet.com Mon Dec 8 09:39:10 2014 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 08 Dec 2014 08:39:10 +0000 Subject: [Tutor] getting input for stdin In-Reply-To: <54855DFB.2010603@btinternet.com> References: <54855DFB.2010603@btinternet.com> Message-ID: On 08/12/14 08:14, Alan Gauld wrote: >> 1.What I want to do is to redirect the output of the program to a text >> file instead of the standard Python output. That is why I opened the >> text file. That part of the program works fine. Thats OK, although its still usual to keep a reference to the real stdout in case you want to print to it. >> 2. data is a py file named data.py which holds all the text >> ...into a separate file which is loaded as a >> module at the begining of the program. hence data.info Your code doesn't show that? >> which is a list of strings which are printed to the >> scree. Hence in my program I open a text file and send the print out >> put to that which is then printed to the text file. This works too. I don't understand how the thing can work. Its not a string and not a valid variable name and a for loop won't work on a construct like that. OK, I just went back to your original message. I see that the url is being generated by my mail reader from what is presumably an HTML post. You actually just had data.info in your code. Apologies, but it shows the dangers of posting to a text based list using HTML... :-( >> 3. When I ask for input in python the prompt which is usually in the >> Python output console waits for the user input and returns that as a >> string. >> 4.Insted of 3 above I would like the user to be able to type into a >> text file which may be opened by the program to collect input. OK, Just to clarify. You expect the file to already exist before the program runs? How does Python learn the name of this file? Normally you would pass it into the program as a parameter or use redirection. In fact it sounds like redirection would solve most of your problems here. You can write the program to output to normal stdout and read from normal stdin. When you start the program you can redirect those at the command line like: $ python myscript >myoutfile.txt < myinfile.txt. Would that do what you want? >> instance i open a text file named give_me_your_input.txt and then the >> user types his requirement in that text file which is taken as a >> string by the program which in turn either returns the appropriate >> answer. This is the bit I don;t understand. It still sounds like you want the user to open the file and type in it while your python code is running? Can you elaborate on how that works? How exactly would your user interact with the computer in this scenario? >> I know how to do everything else above except how to get the input >> from the text file in real time. raw_input can read from a file that already exists. It just reads one line at a time. You just need to modify sys,stdin in the same way you modified sys.stdout. Is that all you want? Or do you want raw_input to read changes in a file as its being edited by a user? That's much harder - maybe impossible. -- 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 From alan.gauld at btinternet.com Mon Dec 8 09:53:02 2014 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 08 Dec 2014 08:53:02 +0000 Subject: [Tutor] getting input for stdin In-Reply-To: <54855E20.8020603@btinternet.com> References: <54855E20.8020603@btinternet.com> Message-ID: > On 08/12/14 03:50, diliup gabadamudalige wrote: >> I managed to get the output file and input file working. >> The output works fine but the input does not. It simply exits the >> program. No crash. Exits.It DOES NOT WAIT FOR ME TO TYPE IN THE >> inputfile.txt Can you show us what your input file looks like? >> if __name__ == '__main__': >> ## menna me kaalla to change the output path >> p = os.getcwd() >> outfile = "\output_file.txt" >> infile = "\input_file.txt" One point, you probably should make these raw strings otherwise the first character may get interpreted as a specioal one due to the back slash: infile = r"\input_file.txt" I assume you are running on Windows? And you use the \ as a path specifier? >> outfilepath = p + outfile >> infilepath = p + infile You should use os.path.join to do this safely and portably. >> sys.stdout = open(outfilepath, "w+") >> sys.stdin = open(infilepath, "w+") You probably should make the input have read mode. Using 'w+' for an input is not usually what you want. >> os.startfile(outfilepath) >> os.startfile(infilepath) What do you think this does? I suspect it starts a copy of Notepad running? Is that right? Any changes in the files will not be reflected in Notepad, and any changes in Notepad will not be reflected in the files until the user saves the file. However you may also have problems opening the files since the OS should have put a lock on them when Python opened them in write mode. >> run = True >> while run: >> scaletemplate = ["C", "D", "E", "F", "G", "A", "B"] >> getscale = sys.stdin.readline() >> raw_input("Which scale do you require?:") I suspect the prompt will get printed on the console (using stderr) but you are not assigning the return value (from infile.txt) to anything so it will get lost. I suspect you want to reverse those lines and use a print: print "Which scale do you require?:" getscale = sys.stdin.readline() >> if len(getscale) > 1: >> getscale = getscale[0].upper() + getscale[1:] Don't you only want the first character? Otherwise it might mess up the 'in' test below. If not, you could use string.capitalize() to do it in a single operation. >> else: >> getscale = getscale.upper() >> if getscale in data.scalenames: >> scale = main(getscale) Where did main() come from? It's not defined in your code? >> print scale >> >> elif getscale == "Q" or getscale == "X" or getscale == "": >> run = False >> print"exiting..." -- 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 From colin.ross.dal at gmail.com Mon Dec 8 16:48:41 2014 From: colin.ross.dal at gmail.com (Colin Ross) Date: Mon, 8 Dec 2014 11:48:41 -0400 Subject: [Tutor] Plotting subsets of data Message-ID: Good afternoon, I am using the following to code to plot the output from an optical encoder: import numpy as np from numpy import ma, logical_or import pylab from pylab import * import matplotlib.pyplot as plt from matplotlib.ticker import AutoMinorLocator import sys # Defining x and y minorlocator xminorLocator=AutoMinorLocator() yminorLocator=AutoMinorLocator() # Load data from .txt file data = np.loadtxt('2014_12_04-16_30_03.txt',skiprows = 0 ,usecols = (0,1)) print "\n Chopper Test for X-SPEC Prototype" print "\n Time (sec) Pos (deg)" print data # Place column data in array to be plotted time = np.array(data[:,0]) print "Time (sec):" #print time pos = np.array(data[:,1]) print "Position (deg):" print pos # Setting minor ticks ax = plt.subplot(111) ax.xaxis.set_minor_locator(xminorLocator) ax.yaxis.set_minor_locator(yminorLocator) #Plotting commands. subplot(2,1,1) plot(time, pos, 'ro') title('Encoder Output') ylabel('Pos (deg)') subplot(2,1,2) plot(t_small, pos, 'ro') xlabel('Time (sec)') ylabel('Pos (deg)') show() The desired result is a square wave, but this is not readily available from the plot (see attached). For the subplot(2,1,2) I would like to plot the output over a 5 second interval so that the behaviour becomes more evident. Can someone please advise me as to the easiest way isolate the first 5 seconds of data? Thank you. -------------- next part -------------- An HTML attachment was scrubbed... URL: -------------- next part -------------- A non-text attachment was scrubbed... Name: encoder_output.png Type: image/png Size: 49710 bytes Desc: not available URL: From dyoo at hashcollision.org Mon Dec 8 20:49:16 2014 From: dyoo at hashcollision.org (Danny Yoo) Date: Mon, 8 Dec 2014 11:49:16 -0800 Subject: [Tutor] Plotting subsets of data In-Reply-To: References: Message-ID: On Mon, Dec 8, 2014 at 7:48 AM, Colin Ross wrote: > Good afternoon, > > I am using the following to code to plot the output from an optical encoder: Hi Colin, Matplotlib is a third-party library, so you may also consider asking the matplotlib folks. >From a brief look at: http://matplotlib.org/1.4.2/users/pyplot_tutorial.html#working-with-multiple-figures-and-axes it appears that you can override the default axis, and specify xmin, ymin, xmax, and ymax values. http://matplotlib.org/1.4.2/api/pyplot_api.html#matplotlib.pyplot.axis For your particular case, you may want to just limit your x axis, in which case xlim() might be appropriate. http://matplotlib.org/1.4.2/api/pyplot_api.html#matplotlib.pyplot.xlim If all else fails, just filter your data before submitting it to the grapher. The program loads data here, using loadtxt (http://docs.scipy.org/doc/numpy/reference/generated/numpy.loadtxt.html): data = np.loadtxt('2014_12_04-16_30_03.txt',skiprows = 0 ,usecols = (0,1)) and it's just a numpy array: you can manipulate numpy arrays. See: http://stackoverflow.com/questions/26154711/filter-rows-of-a-numpy-array as an example of an approach. From colin.ross.dal at gmail.com Mon Dec 8 21:10:59 2014 From: colin.ross.dal at gmail.com (Colin Ross) Date: Mon, 8 Dec 2014 16:10:59 -0400 Subject: [Tutor] Plotting subsets of data In-Reply-To: References: Message-ID: Perfect, thank you Danny! On Mon, Dec 8, 2014 at 3:49 PM, Danny Yoo wrote: > On Mon, Dec 8, 2014 at 7:48 AM, Colin Ross > wrote: > > Good afternoon, > > > > I am using the following to code to plot the output from an optical > encoder: > > Hi Colin, > > Matplotlib is a third-party library, so you may also consider asking > the matplotlib folks. > > From a brief look at: > > > http://matplotlib.org/1.4.2/users/pyplot_tutorial.html#working-with-multiple-figures-and-axes > > it appears that you can override the default axis, and specify xmin, > ymin, xmax, and ymax values. > > http://matplotlib.org/1.4.2/api/pyplot_api.html#matplotlib.pyplot.axis > > For your particular case, you may want to just limit your x axis, in > which case xlim() might be appropriate. > > http://matplotlib.org/1.4.2/api/pyplot_api.html#matplotlib.pyplot.xlim > > > If all else fails, just filter your data before submitting it to the > grapher. The program loads data here, using loadtxt > (http://docs.scipy.org/doc/numpy/reference/generated/numpy.loadtxt.html): > > data = np.loadtxt('2014_12_04-16_30_03.txt',skiprows = 0 ,usecols = > (0,1)) > > and it's just a numpy array: you can manipulate numpy arrays. See: > > > http://stackoverflow.com/questions/26154711/filter-rows-of-a-numpy-array > > as an example of an approach. > -------------- next part -------------- An HTML attachment was scrubbed... URL: From dyoo at hashcollision.org Mon Dec 8 22:22:22 2014 From: dyoo at hashcollision.org (Danny Yoo) Date: Mon, 8 Dec 2014 13:22:22 -0800 Subject: [Tutor] Coding In-Reply-To: References: Message-ID: On Mon, Dec 8, 2014 at 12:14 PM, Awais Idris <2010-3902 at slougheton.com> wrote: > The problem is when i enter my first choice it accepts it fine and well. > When it says would you like a second item, andi say yes it listd the options > and says have a good day and the program cuts off. In wondering if this is a > problem with the loops? > Please use Reply to All on this mailing list, so that all of us here can help respond. I have a day job, so sometimes I actually have to do something other than answer email. :P >From your description, it sounds like you should look at the *conditions* in your if statements, because they aren't branching in a way that you want. Other replies to your thread should point out things you want to look at. Read all the replies, and start asking questions when you hit something you don't understand. This is a conversation: we'll listen to what you're saying. Also, be careful about what terms you are using. You are using the term "loop", and have done so repeatedly, but there are no loops in your program, as Alan has pointed out earlier. From 2010-3902 at slougheton.com Mon Dec 8 23:49:14 2014 From: 2010-3902 at slougheton.com (Awais Idris) Date: Mon, 8 Dec 2014 22:49:14 +0000 Subject: [Tutor] Coding In-Reply-To: References: Message-ID: Ok thank you i appreciate your help On Monday, 8 December 2014, Danny Yoo wrote: > On Mon, Dec 8, 2014 at 12:14 PM, Awais Idris <2010-3902 at slougheton.com > > wrote: > > The problem is when i enter my first choice it accepts it fine and well. > > When it says would you like a second item, andi say yes it listd the > options > > and says have a good day and the program cuts off. In wondering if this > is a > > problem with the loops? > > > > Please use Reply to All on this mailing list, so that all of us here > can help respond. I have a day job, so sometimes I actually have to > do something other than answer email. :P > > From your description, it sounds like you should look at the > *conditions* in your if statements, because they aren't branching in a > way that you want. Other replies to your thread should point out > things you want to look at. Read all the replies, and start asking > questions when you hit something you don't understand. This is a > conversation: we'll listen to what you're saying. > > > Also, be careful about what terms you are using. You are using the > term "loop", and have done so repeatedly, but there are no loops in > your program, as Alan has pointed out earlier. > -------------- next part -------------- An HTML attachment was scrubbed... URL: From dyoo at hashcollision.org Tue Dec 9 00:34:21 2014 From: dyoo at hashcollision.org (Danny Yoo) Date: Mon, 8 Dec 2014 15:34:21 -0800 Subject: [Tutor] Coding In-Reply-To: References: Message-ID: On Mon, Dec 8, 2014 at 3:06 PM, Awais Idris <2010-3902 at slougheton.com> wrote: > The problem is when i enter my first choice it accepts it fine and well. > When it says would you like a second item, andi say yes it listd the options > and says have a good day and the program cuts off. In wondering if this is a > problem with the statements? Hi Awais, Yes, there is a problem that we can see. Look for Alan and Stephen's responses in your email inbox. They should explain what's going on, and how to correct the bug. Can you confirm that you're getting these emails from them? You can also see these responses if you look at the email archive. Your question: https://mail.python.org/pipermail/tutor/2014-December/103581.html and the responses: https://mail.python.org/pipermail/tutor/2014-December/103584.html https://mail.python.org/pipermail/tutor/2014-December/103586.html https://mail.python.org/pipermail/tutor/2014-December/103588.html https://mail.python.org/pipermail/tutor/2014-December/103590.html From 2010-3902 at slougheton.com Tue Dec 9 00:06:48 2014 From: 2010-3902 at slougheton.com (Awais Idris) Date: Mon, 8 Dec 2014 23:06:48 +0000 Subject: [Tutor] Coding In-Reply-To: References: Message-ID: The problem is when i enter my first choice it accepts it fine and well. When it says would you like a second item, andi say yes it listd the options and says have a good day and the program cuts off. In wondering if this is a problem with the statements? On 8 December 2014 at 22:49, Awais Idris <2010-3902 at slougheton.com> wrote: > Ok thank you i appreciate your help > > On Monday, 8 December 2014, Danny Yoo wrote: > >> On Mon, Dec 8, 2014 at 12:14 PM, Awais Idris <2010-3902 at slougheton.com> >> wrote: >> > The problem is when i enter my first choice it accepts it fine and well. >> > When it says would you like a second item, andi say yes it listd the >> options >> > and says have a good day and the program cuts off. In wondering if this >> is a >> > problem with the loops? >> > >> >> Please use Reply to All on this mailing list, so that all of us here >> can help respond. I have a day job, so sometimes I actually have to >> do something other than answer email. :P >> >> From your description, it sounds like you should look at the >> *conditions* in your if statements, because they aren't branching in a >> way that you want. Other replies to your thread should point out >> things you want to look at. Read all the replies, and start asking >> questions when you hit something you don't understand. This is a >> conversation: we'll listen to what you're saying. >> >> >> Also, be careful about what terms you are using. You are using the >> term "loop", and have done so repeatedly, but there are no loops in >> your program, as Alan has pointed out earlier. >> > -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Tue Dec 9 11:58:10 2014 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 09 Dec 2014 10:58:10 +0000 Subject: [Tutor] Coding In-Reply-To: References: Message-ID: On 08/12/14 23:06, Awais Idris wrote: > The problem is when i enter my first choice it accepts it fine and well. > When it says would you like a second item, andi say yes it listd the > options and says have a good day and the program cuts off. In wondering if > this is a problem with the statements? As Danny pointed out both Steven and I suggested a better way to test. In case you missed it here is Steven's response: ################################ Actually it sees it as: if ((FirstChoice == 'Coke') or 'Pepsi' or 'Water'): which will always evaluate as True. *Technically* it will evaluate as either True or 'Pepsi', which is a truthy value, so the if block will always run. What we actually want is one of these: # The long way if (FirstChoice == 'Coke') or (FirstChoice == 'Pepsi') or (FirstChoice == 'Water'): # The short way if FirstChoice in ('Coke', 'Pepsi', 'Water'): ################################### And since you already have the drinks in a set you can shorten the last line even further to: if FirstChoice in drinks: -- 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 From hanzer at riseup.net Tue Dec 9 16:31:28 2014 From: hanzer at riseup.net (Adam Jensen) Date: Tue, 9 Dec 2014 10:31:28 -0500 Subject: [Tutor] Memory management in Python In-Reply-To: References: Message-ID: <20141209103128.badbbdb56acf951e73f05e29@riseup.net> On Wed, 26 Nov 2014 14:08:53 +0000 Ra?l Cumplido wrote: > This web is quite useful to visualize what is happening: > http://www.pythontutor.com/visualize.html#mode=edit > Very nifty web app, thanks for the link! From lufimtse at redhat.com Tue Dec 9 16:39:46 2014 From: lufimtse at redhat.com (Leo Ufimtsev) Date: Tue, 09 Dec 2014 10:39:46 -0500 Subject: [Tutor] Memory management in Python In-Reply-To: <20141209103128.badbbdb56acf951e73f05e29@riseup.net> References: <20141209103128.badbbdb56acf951e73f05e29@riseup.net> Message-ID: <548717C2.6070902@redhat.com> Thanks for sharing. On 12/09/2014 10:31 AM, Adam Jensen wrote: > On Wed, 26 Nov 2014 14:08:53 +0000 > Ra?l Cumplido wrote: > >> This web is quite useful to visualize what is happening: >> http://www.pythontutor.com/visualize.html#mode=edit >> > > Very nifty web app, thanks for the link! > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor > From 2010-3902 at slougheton.com Tue Dec 9 18:50:05 2014 From: 2010-3902 at slougheton.com (Awais Idris) Date: Tue, 9 Dec 2014 17:50:05 +0000 Subject: [Tutor] Coding In-Reply-To: References: Message-ID: I haven't got a reply from alan and stephen On 8 December 2014 at 23:34, Danny Yoo wrote: > On Mon, Dec 8, 2014 at 3:06 PM, Awais Idris <2010-3902 at slougheton.com> > wrote: > > The problem is when i enter my first choice it accepts it fine and well. > > When it says would you like a second item, andi say yes it listd the > options > > and says have a good day and the program cuts off. In wondering if this > is a > > problem with the statements? > > Hi Awais, > > Yes, there is a problem that we can see. Look for Alan and Stephen's > responses in your email inbox. They should explain what's going on, > and how to correct the bug. Can you confirm that you're getting these > emails from them? > > > You can also see these responses if you look at the email archive. > > > Your question: > > https://mail.python.org/pipermail/tutor/2014-December/103581.html > > and the responses: > > https://mail.python.org/pipermail/tutor/2014-December/103584.html > https://mail.python.org/pipermail/tutor/2014-December/103586.html > https://mail.python.org/pipermail/tutor/2014-December/103588.html > https://mail.python.org/pipermail/tutor/2014-December/103590.html > From alan.gauld at btinternet.com Tue Dec 9 22:51:03 2014 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 09 Dec 2014 21:51:03 +0000 Subject: [Tutor] Coding In-Reply-To: References: Message-ID: <54876EC7.5000006@btinternet.com> On 09/12/14 17:50, Awais Idris wrote: > I haven't got a reply from alan and stephen You should have gotten another one from me, quoting Steven's response, earlier today. How are you reading the list? Is it by email or are you using an archive or newsfeed. (For example I use the gmane.org newsfeed) And are you checking the email account that you subscribed with? I notice that this address: 2010-3902 at slougheton.com is not registered on the tutor mailing list, so won't be getting sent any responses. >> Yes, there is a problem that we can see. Look for Alan and Stephen's >> responses in your email inbox. They should explain what's going on, >> and how to correct the bug. Can you confirm that you're getting these >> emails from them? PS. I'm using ReplyAll rather than ReplyLiust to ensure Awais gets the mail, apologies for any duplicates received by other recipients. -- 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 From alan.gauld at btinternet.com Tue Dec 9 22:51:03 2014 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 09 Dec 2014 21:51:03 +0000 Subject: [Tutor] Coding In-Reply-To: References: Message-ID: <54876EC7.5000006@btinternet.com> On 09/12/14 17:50, Awais Idris wrote: > I haven't got a reply from alan and stephen You should have gotten another one from me, quoting Steven's response, earlier today. How are you reading the list? Is it by email or are you using an archive or newsfeed. (For example I use the gmane.org newsfeed) And are you checking the email account that you subscribed with? I notice that this address: 2010-3902 at slougheton.com is not registered on the tutor mailing list, so won't be getting sent any responses. >> Yes, there is a problem that we can see. Look for Alan and Stephen's >> responses in your email inbox. They should explain what's going on, >> and how to correct the bug. Can you confirm that you're getting these >> emails from them? PS. I'm using ReplyAll rather than ReplyLiust to ensure Awais gets the mail, apologies for any duplicates received by other recipients. -- 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 From wallenpb at gmail.com Thu Dec 11 01:42:38 2014 From: wallenpb at gmail.com (Bill Allen) Date: Wed, 10 Dec 2014 18:42:38 -0600 Subject: [Tutor] cx_Oracle and Pyinstaller Message-ID: I have had success with producing a single file executable from a Python script that includes cx_Oracle. Here are the details. Hopefully this will also help someone struggling to get this working. OS was Windows 7 Pro 64 bit. Python was 2.7.8 32 bit. cx_Oracle-5.13 for 2.7 PyInstaller-2.1 Python script oracle_connect.py, this was my program. Oracle 11g instant client DLL files, OCI.dll and oraociei11.dll (OCI.dll seems to stay constant from version to version of Oracle, but the other DLL file's name will change with Oracle versions.) A properly designed tnsnames.ora file. This contains the necessary connection information for your Oracle database. A Pyinstaller-2.1 .spec file to make sure Pyinstaller did everything that was needed to produce the single file .exe. Pyinstaller-2.1 will not automatically include both DLLs into the .exe without using a .spec file. It does pick up the OCI.dll file automatically, but not oraociei11.dll. First, I began by writing my Python script, which imports cx_Oracle, makes the connection to the database, and does some work. My working directory was C:\Python27, so the script, two DLL files and .ora file were all placed there. Test the code to make sure that via the interpreter the script interacted with the database correctly. Second, I ran Pyinstaller-2.1 against the oracle_connect.py script without the -F option (for single file .exe). This created an oracle_connect.spec file which I used as a template which was edited to include the needed settings. Third, I edited the oracle_connect.spec file (see bellow) to specify a single file executable and to include the oraociei11.dll in the compilation The paths were specific to my installation environment and where I had placed by Python source file and other files, adjust to match your environment. This oracle_connect.spec file I then placed in my c:\Python27\PyInstaller-2.1 direcory. Then I executed the following to produce the single file executable. C:\Python27\PyInstaller-2.1>..\python.exe .\pyinstaller.py .\oracle_connect.spec The resulting oracle_connect.exe may now be distributed without including loose DLLs. The only additional file needed is the tnsnames.ora file. This cannot be compiled into the program and must reside in the same location as the executable program. It is a configuration file for the communications parameters necessary to make the connection to the Oracle database. I include a sample of a tnsnames.ora file below. oracle_connect.spec file contents: # -*- mode: python -*- a = Analysis(['..\\oracle_connect.py'], pathex=['C:\\Python27\\PyInstaller-2.1\\oracle_connect'], hiddenimports=[], hookspath=None, runtime_hooks=None) pyz = PYZ(a.pure) exe = EXE(pyz, a.scripts, a.binaries + [('oraociei11.dll','c:\python27\oraociei11.dll','BINARY')], a.zipfiles, a.datas, name='oracle_connect.exe', debug=False, strip=None, upx=False, console=True ) Sample tnsnames.ora, values in <> are Oracle installation specific, contact your local Oracle admin for the correct values to use. # tnsnames.ora Network Configuration File = (DESCRIPTION = (ADDRESS_LIST = (ADDRESS = (PROTOCOL = TCP)(HOST = )(PORT = <1521>)) ) (CONNECT_DATA = (SERVICE_NAME = ) ) ) -- --Bill Allen From matthew.nappi at stonybrook.edu Thu Dec 11 05:20:12 2014 From: matthew.nappi at stonybrook.edu (Matthew Nappi) Date: Wed, 10 Dec 2014 23:20:12 -0500 Subject: [Tutor] While Loop Help Message-ID: Hello All: I am working on the challenges from ?Python Programming for the Absolute Beginner? Chapter 3. I am asked to modify the original code pasted below to limit the number of guesses a player has to guess the number. I did so (code pasted below); however if a player guesses the right number they still receive an ending message indicating that they failed. How can I modify the code without using any advanced techniques to have a different message in the event of a successful guess? Thanks in advance! *Original Code:* # Guess My Number # # The computer picks a random number between 1 and 100 # The player tries to guess it and the computer lets # the player know if the guess is too high, too low # or right on the money import random print("\tWelcome to 'Guess My Number'!") print("\nI'm thinking of a number between 1 and 100.") print("Try to guess it in as few attempts as possible.\n") # 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 print("You guessed it! The number was", the_number) print("And it only took you", tries, "tries!\n") input("\n\nPress the enter key to exit.") *My Modified Code:* # Guess My Number # # The computer picks a random number between 1 and 100 # The player tries to guess it and the computer lets # the player know if the guess is too high, too low # or right on the money import random print("\tWelcome to 'Guess My Number'!") print("\nI'm thinking of a number between 1 and 100.") print("Try to guess it in as few attempts as possible.\n") # set the initial values the_number = random.randint(1, 100) guess = int(input("Take a guess: ")) tries = 1 # guessing loop while guess != the_number and tries < 10: if guess > the_number: print("Lower...") elif guess < the_number: print("Higher...") else: print("You win.") guess = int(input("Take a guess: ")) tries += 1 print("You fail! The number was", the_number) input("\n\nPress the enter key to exit.") From alan.gauld at btinternet.com Thu Dec 11 11:20:23 2014 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 11 Dec 2014 10:20:23 +0000 Subject: [Tutor] While Loop Help In-Reply-To: References: Message-ID: On 11/12/14 04:20, Matthew Nappi wrote: > (code pasted below); however if a player guesses the right number they > still receive an ending message indicating that they failed. How can I > modify the code without using any advanced techniques to have a different > message in the event of a successful guess? Thanks in advance! > import random > > print("\tWelcome to 'Guess My Number'!") > print("\nI'm thinking of a number between 1 and 100.") > print("Try to guess it in as few attempts as possible.\n") > > the_number = random.randint(1, 100) > guess = int(input("Take a guess: ")) > tries = 1 > > while guess != the_number and tries < 10: > if guess > the_number: > print("Lower...") > elif guess < the_number: > print("Higher...") > else: > print("You win.") > guess = int(input("Take a guess: ")) > tries += 1 So far so good, except that you probably don;t want the winner to have to input another number after being told he already won. You can avoid that by making the initial value for guess be something invalid, then move the input line to the top of the while loop: guess = 0 while guess != the_number and tries < 10: guess = int(input("Take a guess: ")) tries += 1 ... the if/else code here. > print("You fail! The number was", the_number) But you always print this regardless of the result. You need to put a test around it to check whether the guess equals the number and only print this if it is not. -- 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 From steve at pearwood.info Thu Dec 11 12:39:57 2014 From: steve at pearwood.info (Steven D'Aprano) Date: Thu, 11 Dec 2014 22:39:57 +1100 Subject: [Tutor] While Loop Help In-Reply-To: References: Message-ID: <20141211113957.GD20332@ando.pearwood.info> On Wed, Dec 10, 2014 at 11:20:12PM -0500, Matthew Nappi wrote: > I am working on the challenges from ?Python Programming for the Absolute > Beginner? Chapter 3. I am asked to modify the original code pasted below > to limit the number of guesses a player has to guess the number. I did so > (code pasted below); however if a player guesses the right number they > still receive an ending message indicating that they failed. How can I > modify the code without using any advanced techniques to have a different > message in the event of a successful guess? Thanks in advance! [...] > *My Modified Code:* > import random > print("\tWelcome to 'Guess My Number'!") > print("\nI'm thinking of a number between 1 and 100.") > print("Try to guess it in as few attempts as possible.\n") > > # set the initial values > the_number = random.randint(1, 100) > guess = int(input("Take a guess: ")) > tries = 1 > > # guessing loop > while guess != the_number and tries < 10: > if guess > the_number: > print("Lower...") > elif guess < the_number: > print("Higher...") > else: > print("You win.") > guess = int(input("Take a guess: ")) > tries += 1 Follow the code: start at the top of the while loop. The next thing that happens is that the computer checks whether guess > the number, otherwise whether guess < the number, otherwise they must be equal. Whichever one happens, a message is printed. What happens next? The next line executes, which says "take a guess". That isn't right, since that forces the player to guess even after they've won. There are a few ways to deal with that. One way would be to change the while loop to something like this: the_number = random.randint(1, 100) guess = -999999 # Guaranteed to not equal the_number. tries = 0 # Haven't guessed yet. while guess != the_number and and tries < 10: tries += 1 guess = int(input("Take a guess: ")) if guess < the_number: print("too low") elif guess > the_number: print("too high") else: print("you win!") Notice how this differs from the earlier version? Instead of asking the player to guess at the *end* of the loop, after checking whether the guess was right, you ask the player to guess at the *start* of the loop. That means you don't need an extra guess at the beginning, and it means you don't get an extra, unneeded guess even after you win. Now let's move on to the next line: > print("You fail! The number was", the_number) This line *always prints*, regardless of whether you have won or not. The easiest way to fix that is to just check whether or not the player guessed correctly: if guess != the_number: print("You fail! The number was", the_number) -- Steven From james at uplinkzero.com Thu Dec 11 12:42:38 2014 From: james at uplinkzero.com (James Chapman) Date: Thu, 11 Dec 2014 11:42:38 +0000 Subject: [Tutor] Does the user need to install Python, when we deploy our c++ products using python? In-Reply-To: References: Message-ID: Actually, after re-reading your original message I think I misunderstood and went off on a tangent. If you are embedding python into a C++ app, then you will need the dlls and all of the compiled python code. *.pyc. (Well most, not all). The exact location of these files in the final build I'm unsure of. -- James On 11 December 2014 at 11:39, James Chapman wrote: > > On 2 December 2014 at 20:28, gordon zhang > wrote: > >> >> >> I downloaded python 3.4.2 for c++ and create a vc++ project using python, >> but I have no idea what python dlls and other stuff needed to deploy the >> products. >> >> I know if we put Python34.dll and Python.dll in the folder of executable, >> it is not enough. What else do we need to put in the folder of >> executable?(the application does not run) >> >> If anyone knows please let me know. >> >> Thanks, Gordon >> > > Probably a little advanced for this list but the list is here to learn > right? So my own 2 pence worth... > > Are you referring to Python Tools for Visual Studio? > http://pytools.codeplex.com/ > > This allows you to build python projects in VS and then debug them using > the VS debugger, but you will need the debug files (.pdb) available on this > page: https://www.python.org/downloads/windows/ - This however is more > for extending python via C/C++ than building python apps or using python to > deploy apps. > > There are a number of tools out there, some already mentioned for bundling > python apps into exe's which then require the python dlls to be packaged in > an installer to be deployed with your newly built exe. I have done this in > the past and experience has taught me one thing. Don't do it! You end up > making your app way too complex, and it becomes very difficult to support. > Also, when you want to update the python environment you run into problems. > From someone who has been there, don't do it. Even if you have CI > infrastructure in place to make things easily repeatable, it still becomes > a nightmare. > > Rather find an automated way of deploying python independently and then > use an installer to install just your python code. That way all you support > is your code, you don't end up supporting 3rd party wrappers that don't > work properly. > > nullsoft scriptable installer is easy to use, has good documentation and > examples, and doesn't have a massively steep learning curve. > http://nsis.sourceforge.net/Main_Page > > > From steve at pearwood.info Thu Dec 11 12:43:44 2014 From: steve at pearwood.info (Steven D'Aprano) Date: Thu, 11 Dec 2014 22:43:44 +1100 Subject: [Tutor] cx_Oracle and Pyinstaller In-Reply-To: References: Message-ID: <20141211114343.GE20332@ando.pearwood.info> On Wed, Dec 10, 2014 at 06:42:38PM -0600, Bill Allen wrote: > I have had success with producing a single file executable from a Python > script that includes cx_Oracle. Here are the details. Hopefully this will > also help someone struggling to get this working. [...] Thanks Bill! This may be a little advanced for most beginners, but I'm sure it will come in handy for somebody. Do you have a blog where you can write it up? It may be easier for people to find on a blog or web page rather than just in an email archive. -- Steven From james at uplinkzero.com Thu Dec 11 12:39:36 2014 From: james at uplinkzero.com (James Chapman) Date: Thu, 11 Dec 2014 11:39:36 +0000 Subject: [Tutor] Does the user need to install Python, when we deploy our c++ products using python? In-Reply-To: References: Message-ID: On 2 December 2014 at 20:28, gordon zhang wrote: > > > I downloaded python 3.4.2 for c++ and create a vc++ project using python, > but I have no idea what python dlls and other stuff needed to deploy the > products. > > I know if we put Python34.dll and Python.dll in the folder of executable, > it is not enough. What else do we need to put in the folder of > executable?(the application does not run) > > If anyone knows please let me know. > > Thanks, Gordon > Probably a little advanced for this list but the list is here to learn right? So my own 2 pence worth... Are you referring to Python Tools for Visual Studio? http://pytools.codeplex.com/ This allows you to build python projects in VS and then debug them using the VS debugger, but you will need the debug files (.pdb) available on this page: https://www.python.org/downloads/windows/ - This however is more for extending python via C/C++ than building python apps or using python to deploy apps. There are a number of tools out there, some already mentioned for bundling python apps into exe's which then require the python dlls to be packaged in an installer to be deployed with your newly built exe. I have done this in the past and experience has taught me one thing. Don't do it! You end up making your app way too complex, and it becomes very difficult to support. Also, when you want to update the python environment you run into problems. >From someone who has been there, don't do it. Even if you have CI infrastructure in place to make things easily repeatable, it still becomes a nightmare. Rather find an automated way of deploying python independently and then use an installer to install just your python code. That way all you support is your code, you don't end up supporting 3rd party wrappers that don't work properly. nullsoft scriptable installer is easy to use, has good documentation and examples, and doesn't have a massively steep learning curve. http://nsis.sourceforge.net/Main_Page From james at uplinkzero.com Thu Dec 11 12:18:09 2014 From: james at uplinkzero.com (James Chapman) Date: Thu, 11 Dec 2014 11:18:09 +0000 Subject: [Tutor] While Loop Help In-Reply-To: References: Message-ID: While Alan has given you a far better solution, I feel someone should mention the break statement as you will likely come across it a lot, and it is quite an important flow control statement. You could add a break statement to the else which would break out of the while loop. https://docs.python.org/3.4/reference/simple_stmts.html#break Refactored to include a break -------------------------------------------------- ... the_number = random.randint(1, 100) win = false tries = 0 guess = int(input("Take a guess: ")) while tries < 10: guess = int(input("Take a guess: ")) tries += 1 if guess > the_number: print("Lower...") elif guess < the_number: print("Higher...") else: win = true break if win: print("You win") else: print("You fail! The number was {0}".format(the_number)) input("\n\nPress the enter key to exit.") -------------------------------------------------- From galen.seilis at gmail.com Thu Dec 11 21:25:53 2014 From: galen.seilis at gmail.com (Galen Seilis) Date: Thu, 11 Dec 2014 14:25:53 -0600 Subject: [Tutor] Parsing JSON with Python Message-ID: To whom it may concern, I am having difficulty interacting with JSON. The example below if a typical input and output: *import json* *array = json.load( { "name": "Joe", "address": "111 Street" } )* *Traceback (most recent call last): File "" , line 1, in File "C:\Python27\lib\json\__init__.py" , line 286, in load return loads(fp.read(), AttributeError: 'dict' object has no attribute 'read' >>>* I would appreciate assitance understanding why this doesn't work, and how I can get up-and-running with inputing JSON code into Python. -- Galen From ben+python at benfinney.id.au Fri Dec 12 00:15:54 2014 From: ben+python at benfinney.id.au (Ben Finney) Date: Fri, 12 Dec 2014 10:15:54 +1100 Subject: [Tutor] Parsing JSON with Python References: Message-ID: <85fvclg4lx.fsf@benfinney.id.au> Galen Seilis writes: > I am having difficulty interacting with JSON. The example below if a > typical input and output: Thank you for presenting a simple example and the resulting output. Unfortunately, your mail client has mangled it, inserting asterisks making syntax errors, and wrapping lines that should be separate. Please, in future, compose messages only in ?plain text? mode. Your text examples will survive much better that way. > *import json* > *array = json.load( { "name": "Joe", "address": "111 Street" } )* You are passing a Python dict value to the function. JSON is a serialisation format, and the input to ?json.load? must be a text string. A literal Python text string looks like this in the code:: "foo bar baz" A literal Python dict looks like this in the code:: { "name": "Joe", "address": "111 Street" } -- \ ?For fast acting relief, try slowing down.? ?Jane Wagner, via | `\ Lily Tomlin | _o__) | Ben Finney From alan.gauld at btinternet.com Fri Dec 12 00:19:30 2014 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 11 Dec 2014 23:19:30 +0000 Subject: [Tutor] Parsing JSON with Python In-Reply-To: References: Message-ID: On 11/12/14 20:25, Galen Seilis wrote: > To whom it may concern, > > I am having difficulty interacting with JSON. The example below if a > typical input and output: > > > *import json* > *array = json.load( { "name": "Joe", "address": "111 Street" } )* > > *Traceback (most recent call last): File "" , line 1, in > File "C:\Python27\lib\json\__init__.py" , line 286, in load return > loads(fp.read(), AttributeError: 'dict' object has no attribute 'read' >>>* The documentation for json.load() says: ###################### json.load(fp, cls=None, object_hook=None, parse_float=None, parse_int=None, parse_constant=None, object_pairs_hook=None, **kw) Deserialize fp (a .read()-supporting file-like object containing a JSON document) to a Python object using this conversion table. ... ##################### So it expects a file-like object as its first argument but you are passing a dictionary. It's not clear whether you are trying to convert your dictionary into a json data stream or whether you are trying to read a json string and convert it to a Python dictionary. Whichever way round you won't get an array back. dumps() will turn a Python data structure into a JSON string. loads() will turn a JSON string into a Python object. I'm guessing this is what you wanted? Just remember that the 's' at the end signifies string not a plural. And the non-s versions use files not strings. 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 From alan.gauld at btinternet.com Fri Dec 12 00:23:01 2014 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 11 Dec 2014 23:23:01 +0000 Subject: [Tutor] Parsing JSON with Python In-Reply-To: <85fvclg4lx.fsf@benfinney.id.au> References: <85fvclg4lx.fsf@benfinney.id.au> Message-ID: On 11/12/14 23:15, Ben Finney wrote: >> *array = json.load( { "name": "Joe", "address": "111 Street" } )* > > You are passing a Python dict value to the function. JSON is a > serialisation format, and the input to ?json.load? must be a text > string. Nope, its a file-like object. The input to loads() is a text string. The implementation of load() apparently reads the file object to produce a string which is passed to loads() -- 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 From martin at linux-ip.net Fri Dec 12 00:22:12 2014 From: martin at linux-ip.net (Martin A. Brown) Date: Thu, 11 Dec 2014 15:22:12 -0800 Subject: [Tutor] Parsing JSON with Python In-Reply-To: References: Message-ID: Hello there, > To whom it may concern, > > I am having difficulty interacting with JSON. The example below if a > typical input and output: > > > *import json* > *array = json.load( { "name": "Joe", "address": "111 Street" } )* > > *Traceback (most recent call last): File "" , line 1, in > File "C:\Python27\lib\json\__init__.py" , line 286, in load return > loads(fp.read(), AttributeError: 'dict' object has no attribute 'read' >>>* > > > I would appreciate assitance understanding why this doesn't work, > and how I can get up-and-running with inputing JSON code into > Python. Which version of Python? The following works with Python 3.x and Python 2.7, though: arr = json.loads('{ "name": "Joe", "address": "111 Street" }') arr.get('address') Here are some notes about why: # -- below is a Python dictionary, it is not actually JSON >>> { "name": "Joe", "address": "111 Street" } {'name': 'Joe', 'address': '111 Street'} # -- next is that Python dictionary turned into JSON (single quotes) >>> '{ "name": "Joe", "address": "111 Street" }' '{ "name": "Joe", "address": "111 Street" }' # -- now you have a JavaScript Object Notation string, which you # can manipulate; let's use the json.loads() call >>> arr = json.loads('{ "name": "Joe", "address": "111 Street" }') # -- You will notice I used a variable called 'arr' instead of # array, because there is a module called array, and I may # (one day) want to use it. >>> arr {'name': 'Joe', 'address': '111 Street'} # -- OK, but I'm lazy, I don't want to have to type all of my # JSON into strings. OK. So, don't. Have the JSON module # convert your object (a dictionary) into a string for you. >>> json.dumps(arr) '{"name": "Joe", "address": "111 Street"}' So, have some fun with the json.dumps() and json.loads() calls. Then, you can move on to json.dump() and json.load() to put your data into files. -Martin -- Martin A. Brown http://linux-ip.net/ From ben+python at benfinney.id.au Fri Dec 12 00:29:38 2014 From: ben+python at benfinney.id.au (Ben Finney) Date: Fri, 12 Dec 2014 10:29:38 +1100 Subject: [Tutor] Parsing JSON with Python References: <85fvclg4lx.fsf@benfinney.id.au> Message-ID: <85bnn9g3z1.fsf@benfinney.id.au> Alan Gauld writes: > On 11/12/14 23:15, Ben Finney wrote: > > >> *array = json.load( { "name": "Joe", "address": "111 Street" } )* > > > > You are passing a Python dict value to the function. JSON is a > > serialisation format, and the input to ?json.load? must be a text > > string. > > Nope, its a file-like object. Fair enough, I didn't check the ?json.load? documentation. Thank you for the correction. I suspect the OP wasn't aware they specified a Python dict, though, which is the main point. -- \ ?Never use a long word when there's a commensurate diminutive | `\ available.? ?Stan Kelly-Bootle | _o__) | Ben Finney From steve at pearwood.info Fri Dec 12 00:51:56 2014 From: steve at pearwood.info (Steven D'Aprano) Date: Fri, 12 Dec 2014 10:51:56 +1100 Subject: [Tutor] Parsing JSON with Python In-Reply-To: References: Message-ID: <20141211235156.GF20332@ando.pearwood.info> On Thu, Dec 11, 2014 at 02:25:53PM -0600, Galen Seilis wrote: > I would appreciate assitance understanding why this doesn't work, and how I > can get up-and-running with inputing JSON code into Python. Did you try reading the Fine Manual? It has many examples! For Python 2: https://docs.python.org/2/library/json.html or for Python 3: https://docs.python.org/3/library/json.html The four functions you are likely to care about are: json.load # read JSON input from a file, return objects json.loads # read JSON input from a string, return objects json.dump # dump JSON output to a file json.dumps # dump JSON output to a string Example: py> import json py> data = {23: None, 42: "Hello World!"} py> s = json.dumps(data) py> print(s) {"42": "Hello World!", "23": null} py> obj = json.loads(s) py> print(obj) {'23': None, '42': 'Hello World!'} -- Steven From alan.gauld at btinternet.com Fri Dec 12 00:56:10 2014 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 11 Dec 2014 23:56:10 +0000 Subject: [Tutor] Parsing JSON with Python In-Reply-To: References: Message-ID: On 11/12/14 23:22, Martin A. Brown wrote: > arr = json.loads('{ "name": "Joe", "address": "111 Street" }') > arr.get('address') > > Here are some notes about why: > # -- You will notice I used a variable called 'arr' instead of > # array, because there is a module called array, and I may > # (one day) want to use it. > > >>> arr > {'name': 'Joe', 'address': '111 Street'} But even arr is a bad name choice because it implies an array structure is being stored, which it isn't, it's a dictionary (which in the general case can be called an "associative array" but in Python-land that's extremely rare). arrays are a very specific type of data and using a variable name that sounds like array is liable to lead to false assumptions further down the line. Since this data stores a name and address use a name that reflects that, such as location, home, or even just address... Names should nearly always reflect their logical purpose not their data type. 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 From jagannath.ramanan at gmail.com Fri Dec 12 13:46:05 2014 From: jagannath.ramanan at gmail.com (Jagannath Ramanan) Date: Fri, 12 Dec 2014 07:46:05 -0500 Subject: [Tutor] Need help! Message-ID: Dear Sir / Madam, My name is jag. I need little bit of help understanding something. I have a vncserver running at the background in redhat. My client is lubuntu where im using python. For some reason the communication is only possible between them is to send custom TCP/IP messages. Im not a hardcore developers. I can do scripts and i have used gtk python for front ends etc. *The TCP /IP message length is:* TCP/IP: 37 bytes of message + 16 bytes of header = 53 bytes Raw Serial: 37 bytes message + 16 bytes of header + 2 bytes of trailer = 55 bytes I have no idea how i would code something like that in python to make it talk to the server. Any any help or guidance is sincerely appreciated. Thanks in advance!! Sincerely, Jagannath Ramanan, Software Tester From luis.sanmartin at unix.cl Fri Dec 12 15:20:51 2014 From: luis.sanmartin at unix.cl (Luis San Martin) Date: Fri, 12 Dec 2014 11:20:51 -0300 Subject: [Tutor] about multiprocessing performance Message-ID: Dear fellows, I'm learning about on multiprocessing module on python. So far I've enjoyed it though regarding performance I got some doubts. There is not that much difference[0] when running it on Mac OS X on the contrary to Linux. [0] http://codepad.org/lNDHNhof Kind regards From malaclypse2 at gmail.com Fri Dec 12 20:35:04 2014 From: malaclypse2 at gmail.com (Jerry Hill) Date: Fri, 12 Dec 2014 14:35:04 -0500 Subject: [Tutor] about multiprocessing performance In-Reply-To: References: Message-ID: On Fri, Dec 12, 2014 at 9:20 AM, Luis San Martin wrote: > I'm learning about on multiprocessing module on python. So far I've enjoyed > it though regarding performance I got some doubts. There is not that much > difference[0] when running it on Mac OS X on the contrary to Linux. > > [0] http://codepad.org/lNDHNhof Here's what I see from the link you provided: Linux: multiproc.py: 2.344s nomultiproc.py 8.873s Mac: multiproc.py: 2.469s nomultiproc.py: 8.775s That looks to me like it's working the same on both platforms. -- Jerry From danny.yoo at gmail.com Fri Dec 12 20:11:18 2014 From: danny.yoo at gmail.com (Danny Yoo) Date: Fri, 12 Dec 2014 11:11:18 -0800 Subject: [Tutor] Need help! In-Reply-To: References: Message-ID: On Dec 12, 2014 8:54 AM, "Jagannath Ramanan" wrote: > > Dear Sir / Madam, > > My name is jag. I need little bit of help understanding something. I have a > vncserver running at the background in redhat. My client is lubuntu where > im using python. > This question is out of scope for a beginner tutor forum. I don't think many of us can help you with low level network programming. We can point you to resources like the Socket HOWTO at https://docs.python.org/2/howto/sockets.html. But what you're asking sounds much more low level than that. You may want to check on python-list. https://mail.python.org/mailman/listinfo/python-list From oscar.j.benjamin at gmail.com Sat Dec 13 00:19:12 2014 From: oscar.j.benjamin at gmail.com (Oscar Benjamin) Date: Fri, 12 Dec 2014 23:19:12 +0000 Subject: [Tutor] Need help! In-Reply-To: References: Message-ID: On 12 December 2014 at 12:46, Jagannath Ramanan wrote: > Dear Sir / Madam, > > My name is jag. Hi Jag, > I need little bit of help understanding something. I have a > vncserver running at the background in redhat. My client is lubuntu where > im using python. > > For some reason the communication is only possible between them is to send > custom TCP/IP messages. Im not a hardcore developers. I can do scripts and > i have used gtk python for front ends etc. > > *The TCP /IP message length is:* > > TCP/IP: 37 bytes of message + 16 bytes of header = 53 bytes Raw Serial: 37 > bytes message + 16 bytes of header + 2 bytes of trailer = 55 bytes > I have no idea how i would code something like that in python to make it > talk to the server. > > Any any help or guidance is sincerely appreciated. > > Thanks in advance!! I'm don't really understand from your description what needs to be done so I can't offer any code that would do it. However I see that there is a module called vncdotool on PyPI here: https://pypi.python.org/pypi/vncdotool Apparently that module is made to speak to VNC servers. Perhaps you could give it a try. Oscar From alan.gauld at btinternet.com Sat Dec 13 00:23:28 2014 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 12 Dec 2014 23:23:28 +0000 Subject: [Tutor] Need help! In-Reply-To: References: Message-ID: On 12/12/14 12:46, Jagannath Ramanan wrote: > vncserver running at the background in redhat. My client is lubuntu where > im using python. > > For some reason the communication is only possible between them is to send > custom TCP/IP messages. What makes you think so? Is that something you have been told? Is it a technical requirement of your project? Have you tried communicating in any other way - eg. ping, ftp, ssh, http etc/ Also does it need to be TCP/IP? Could it be UDP over IP instead? If the messages are simple UDP can sometimes be easier to work with. > *The TCP /IP message length is:* > > TCP/IP: 37 bytes of message + 16 bytes of header = 53 bytes Raw Serial: 37 > bytes message + 16 bytes of header + 2 bytes of trailer = 55 bytes > I have no idea how i would code something like that in python to make it > talk to the server. It may be possible but it's well beyond the scope of learning Python and its library. You are probably better asking on the main python list. Assuming you really must go down this path of course. You might want to find a copy of "Foundations of Python Network Programming" by Goertzen. It's probably the best reference for networking on Python. But even he doesn't discuss creating bespoke packets which is what you seem to be asking about. The other classic text is Richard Steven's book(s) "Unix Network Programming: Sockets Networking API v.1" It's aimed at C programmers and very low level but for what you want it may be the best bet. -- 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 From alan.gauld at btinternet.com Sat Dec 13 00:27:04 2014 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 12 Dec 2014 23:27:04 +0000 Subject: [Tutor] about multiprocessing performance In-Reply-To: References: Message-ID: On 12/12/14 14:20, Luis San Martin wrote: > Dear fellows, > > I'm learning about on multiprocessing module on python. So far I've enjoyed > it though regarding performance I got some doubts. There is not that much > difference[0] when running it on Mac OS X on the contrary to Linux. They are both Unix based although different variants. Why would you expect much difference? Or are you just informing us of your findings? I'm not sure if you have a question? And if so what is it you want to know? -- 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 From cs at zip.com.au Sat Dec 13 04:25:46 2014 From: cs at zip.com.au (Cameron Simpson) Date: Sat, 13 Dec 2014 14:25:46 +1100 Subject: [Tutor] Need help! In-Reply-To: References: Message-ID: <20141213032546.GA61585@cskk.homeip.net> On 12Dec2014 07:46, Jagannath Ramanan wrote: >My name is jag. I need little bit of help understanding something. I have a >vncserver running at the background in redhat. My client is lubuntu where >im using python. > >For some reason the communication is only possible between them is to send >custom TCP/IP messages. Im not a hardcore developers. I can do scripts and >i have used gtk python for front ends etc. > >*The TCP /IP message length is:* > >TCP/IP: 37 bytes of message + 16 bytes of header = 53 bytes Raw Serial: 37 >bytes message + 16 bytes of header + 2 bytes of trailer = 55 bytes >I have no idea how i would code something like that in python to make it >talk to the server. I think you need to supply some more detail. The above looks like small snippet from a much larger document. It sounds to me like that is from a summary of some protocol which is slightly different over TCP from over a serial line. When you say "the communication is only possible between them is to send custom TCP/IP messages", what kind of communication to you have in mind? Normally a VNC service on your redhat box is simply a way of presenting a virtual display for remote interaction. It would be unusual for that to be your only choice unless you have a specific task in mind. Cheers, Cameron Simpson Sometimes the only solution is to find a new problem. From hanzer at riseup.net Sat Dec 13 21:10:07 2014 From: hanzer at riseup.net (Adam Jensen) Date: Sat, 13 Dec 2014 15:10:07 -0500 Subject: [Tutor] Need help! In-Reply-To: References: Message-ID: <20141213151007.2f0574947973dac92479fbb6@riseup.net> On Fri, 12 Dec 2014 07:46:05 -0500 Jagannath Ramanan wrote: > My name is jag. I need little bit of help understanding something. I have a > vncserver running at the background in redhat. My client is lubuntu where > im using python. > > For some reason the communication is only possible between them is to send > custom TCP/IP messages. Im not a hardcore developers. I can do scripts and > i have used gtk python for front ends etc. > > *The TCP /IP message length is:* > > TCP/IP: 37 bytes of message + 16 bytes of header = 53 bytes Raw Serial: 37 > bytes message + 16 bytes of header + 2 bytes of trailer = 55 bytes > I have no idea how i would code something like that in python to make it > talk to the server. When you hear hoofbeats, think of horses not zebras. It's possible you only need to open a TCP port in the RedHat machine's firewall: /sbin/iptables -I INPUT 1 -p tcp -d ${ip_of_lubuntu} --dport ${port} -j ACCEPT For experimentation and development, it might be best to select a port number within the range 49152?65535. http://en.wikipedia.org/wiki/List_of_TCP_and_UDP_port_numbers From cccccttttt at gmail.com Sun Dec 14 20:29:08 2014 From: cccccttttt at gmail.com (Pi Po) Date: Sun, 14 Dec 2014 11:29:08 -0800 Subject: [Tutor] looking for a Python feature for computer teaching Message-ID: As a teacher I find python simple and effective. However, appreciate feedback from anyone who knows of a Python version with this feature: Want each interpreted line of code to introduce as a cells on a spreadsheet window each new variable (or array) with its initialized value, and show the updated contents of each previously defined variable (or array). As a student types in a line of code they will see how that line impacts old data and introduces new data. This can now be done manually on a blackboard but is slow and tedious. Here are two simple spreadsheets that show how it might look for a student to step through their code: https://docs.google.com/spreadsheets/d/1FkyzsT4VcGf9APE4IgHEYl4f6EI3C_DdUi_oD9K9shU/edit?usp=sharing https://docs.google.com/spreadsheets/d/1mxIlScRBUa0Qtxg0G65Pw4FupeuDTDXQQbvpON7EH5M/edit?usp=sharing If anyone knows another language (assembler, forth, C, J, ...) which already has this feature, appreciate a link. But as syntax of Python is relatively clean and suited for instruction, much prefer something in Python. Cam Trenor secondary math/science From alan.gauld at btinternet.com Mon Dec 15 01:10:13 2014 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 15 Dec 2014 00:10:13 +0000 Subject: [Tutor] looking for a Python feature for computer teaching In-Reply-To: References: Message-ID: On 14/12/14 19:29, Pi Po wrote: > Want each interpreted line of code to introduce as a cells on > a spreadsheet window each new variable (or array) with its initialized > value, > and show the updated contents of each previously defined variable (or > array). I don;t know of any environment for any language that does it in a spreadsheet. The nearest thing is a debugger with a watch point set. You can use IDLE or Pythonwin or Eclipse or winpdb; they all support watch points. > As a student types in a line of code they will see how that > line impacts old data and introduces new data. Again that's not how the debugger approach works it takes a full program and steps through it showing how the variables get updated, but they don't allow dynamic typing of code during debugging. At least none that I've seen. Some allow minor edits to live code, but even that's fairly unusual. > This can now be done manually on a blackboard but is slow and tedious. Yes, but is very good discipline for students. Its how most programmers learn, and something I still do regularly when debugging a problem(on paper not a blackboard!) > If anyone knows another language (assembler, forth, C, J, ...) which > already has this feature, appreciate a link. > > But as syntax of Python is relatively clean and suited for instruction, > much prefer something in Python. Nope, I don't know of anything like that. Smalltalk might come closest with its Workspace concept and object browser. But it's certainly not a spreadsheet, although it does allow you to type and evaluate new lines of code as you go. The Squeak environment is designed for education use so might be worth a look. You could also try asking on the edu-sig mailing list which is for educators using Python (I haven't checked in there for years so I hope its still running!) -- 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 From steve at pearwood.info Mon Dec 15 01:12:04 2014 From: steve at pearwood.info (Steven D'Aprano) Date: Mon, 15 Dec 2014 11:12:04 +1100 Subject: [Tutor] looking for a Python feature for computer teaching In-Reply-To: References: Message-ID: <20141215001203.GS20332@ando.pearwood.info> On Sun, Dec 14, 2014 at 11:29:08AM -0800, Pi Po wrote: > Want each interpreted line of code to introduce as a cells on > a spreadsheet window each new variable (or array) with its initialized > value, > and show the updated contents of each previously defined variable (or > array). I haven't used any of these, but you can try them and see if they do what you want: http://manns.github.io/pyspread/ https://github.com/pythonanywhere/dirigible-spreadsheet There is also Resolver-One, but it is Windows only, and no longer available. But if you can find a copy somewhere, you could try it: http://code.google.com/p/resolver/ -- Steven From memilanuk at gmail.com Mon Dec 15 01:17:29 2014 From: memilanuk at gmail.com (memilanuk) Date: Sun, 14 Dec 2014 16:17:29 -0800 Subject: [Tutor] looking for a Python feature for computer teaching In-Reply-To: References: Message-ID: I believe that Spyder (lightweight IDE often included in scientific python builds like Anaconda, WinPython, python(x,y)) has a variable explorer pane... I'd guess you could 'step' thru the program in debugger mode and watch the variables change in the explorer window. https://code.google.com/p/spyderlib/ https://pythonhosted.org/spyder/variableexplorer.html -- Shiny! Let's be bad guys. Reach me @ memilanuk (at) gmail dot com From danny.yoo at gmail.com Mon Dec 15 05:57:17 2014 From: danny.yoo at gmail.com (Danny Yoo) Date: Sun, 14 Dec 2014 20:57:17 -0800 Subject: [Tutor] looking for a Python feature for computer teaching In-Reply-To: References: Message-ID: On Dec 14, 2014 3:35 PM, "Pi Po" wrote: > > As a teacher I find python simple and effective. > > However, appreciate feedback from anyone who knows > of a Python version with this feature: > > Want each interpreted line of code to introduce as a cells on > a spreadsheet window each new variable (or array) with its initialized > value, > and show the updated contents of each previously defined variable (or > array). > Have you seen the visualization provided by http://pythontutor.com/visualize.html#mode=edit From luis.sanmartin at unix.cl Mon Dec 15 15:13:30 2014 From: luis.sanmartin at unix.cl (Luis San Martin) Date: Mon, 15 Dec 2014 11:13:30 -0300 Subject: [Tutor] about multiprocessing performance In-Reply-To: References: Message-ID: I made a silly mistake as Jerry points its working above the same performance. Kind regards On Fri, Dec 12, 2014 at 8:27 PM, Alan Gauld wrote: > On 12/12/14 14:20, Luis San Martin wrote: >> >> Dear fellows, >> >> I'm learning about on multiprocessing module on python. So far I've >> enjoyed >> it though regarding performance I got some doubts. There is not that much >> difference[0] when running it on Mac OS X on the contrary to Linux. > > > They are both Unix based although different variants. > Why would you expect much difference? > Or are you just informing us of your findings? > > I'm not sure if you have a question? > And if so what is it you want to know? > > -- > 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 at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor From beachkidken at gmail.com Mon Dec 15 22:25:42 2014 From: beachkidken at gmail.com (Ken G.) Date: Mon, 15 Dec 2014 16:25:42 -0500 Subject: [Tutor] Is there an easily or shorter way? Message-ID: <548F51D6.8060903@gmail.com> I am sure there is a better way to refine the following lines. Letting x equal a number from 1 to 28, go through 28 separate 'if' statements to print a resulting value that equaled the value of x. For example: x = 8 if x = 1, print 'one' if x = 2, print 'two' ... ... if x = 8, print 'eight' ... ... if x = 28, print 'twenty eight' Would a single line using list or dictionary be shorter? Thanks, Ken From dyoo at hashcollision.org Mon Dec 15 22:38:14 2014 From: dyoo at hashcollision.org (Danny Yoo) Date: Mon, 15 Dec 2014 13:38:14 -0800 Subject: [Tutor] Is there an easily or shorter way? In-Reply-To: <548F51D6.8060903@gmail.com> References: <548F51D6.8060903@gmail.com> Message-ID: On Mon, Dec 15, 2014 at 1:25 PM, Ken G. wrote: > I am sure there is a better way to refine the following lines. > > Letting x equal a number from 1 to 28, go through 28 separate 'if' > statements to print a resulting value that equaled the value of x. Yes, the repetitive nature of those statements indicate that putting the varying part in a data structure, like a list or dictionary, would be greatly preferable. As a side note: if we were to talk about how we'd do this in a professional context, I think we'd recommend a library such as "humanize", which has functions to go from numbers to human-friendly string descriptions. https://pypi.python.org/pypi/humanize From dyoo at hashcollision.org Mon Dec 15 22:45:23 2014 From: dyoo at hashcollision.org (Danny Yoo) Date: Mon, 15 Dec 2014 13:45:23 -0800 Subject: [Tutor] Is there an easily or shorter way? In-Reply-To: References: <548F51D6.8060903@gmail.com> Message-ID: > As a side note: if we were to talk about how we'd do this in a > professional context, I think we'd recommend a library such as > "humanize", which has functions to go from numbers to human-friendly > string descriptions. > > https://pypi.python.org/pypi/humanize Whoops: wrong library. Humanize is a good one, but not exactly the one I was supposed to cite. I should have cited num2words, which is a cardinal number library: https://pypi.python.org/pypi/num2words From bodsda at googlemail.com Mon Dec 15 22:57:42 2014 From: bodsda at googlemail.com (Bod Soutar) Date: Mon, 15 Dec 2014 21:57:42 +0000 Subject: [Tutor] Is there an easily or shorter way? In-Reply-To: <548F51D6.8060903@gmail.com> References: <548F51D6.8060903@gmail.com> Message-ID: On 15 December 2014 at 21:25, Ken G. wrote: > I am sure there is a better way to refine the following lines. > > Letting x equal a number from 1 to 28, go through 28 separate 'if' > statements to print a resulting value that equaled the value of x. > > For example: > > x = 8 > > if x = 1, print 'one' > if x = 2, print 'two' > ... > ... > if x = 8, print 'eight' > ... > ... > if x = 28, print 'twenty eight' > > Would a single line using list or dictionary be shorter? > > Thanks, > > Ken > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor If you wanted to do this without additional libraries, consider how many *unique* words are actually required if you were to write them all out. You could use a dictionary to map the numbers to their words -- Bodsda From steve at pearwood.info Mon Dec 15 23:49:29 2014 From: steve at pearwood.info (Steven D'Aprano) Date: Tue, 16 Dec 2014 09:49:29 +1100 Subject: [Tutor] Is there an easily or shorter way? In-Reply-To: <548F51D6.8060903@gmail.com> References: <548F51D6.8060903@gmail.com> Message-ID: <20141215224928.GV20332@ando.pearwood.info> On Mon, Dec 15, 2014 at 04:25:42PM -0500, Ken G. wrote: > I am sure there is a better way to refine the following lines. > > Letting x equal a number from 1 to 28, go through 28 separate 'if' > statements to print a resulting value that equaled the value of x. Since you only care about the first 28 values, a list or dict is the way to go. The two look remarkably similar: # Using a dict. Replace the dots ... with the rest of the values. names = {1: "one", 2: "two", 3: "three", ... 28: "twenty-eight"} print(names[x]) # Using a list. Again, replace the dots. names = ["zero", "one", "two", "three", ... "twenty-eight"] print(names[x]) I stress that neither version *quite* works yet. You have to replace the dots ... with the rest of the values, which is tedious but not hard. In the case of the list version, the reason that I add an entry for zero is that lists are indexed from zero. That is, given the list: L = ['spam', 'eggs', 'cheese', 'toast'] the first entry is written L[0], the second entry L[1] and so forth. Although it takes a bit of getting used to, there actually are good reasons for that. One advantage of dicts over lists is that you can leave gaps while a list must have placeholders for every position: {2: "two", 4: "four", 8: "eight"} ["", "", "two", "", "four", "", "", "", "eight"] Of course, as Danny suggested, if you're going to be using this seriously for arbitrary numbers, you can't possibly list every single one in advance. What if somebody asks for the name of 9274810276523? In that case, we need a function that turns a number into an name digit by digit: nine trillion, two hundred and seventy-four billion, eight hundred and ten million, two hundred and seventy-six thousand, five hundred and twenty-three Doing this makes a nice little programming exercise, so I will leave it to you :-) -- Steven From davea at davea.name Mon Dec 15 23:59:11 2014 From: davea at davea.name (Dave Angel) Date: Mon, 15 Dec 2014 17:59:11 -0500 Subject: [Tutor] Is there an easily or shorter way? In-Reply-To: <548F51D6.8060903@gmail.com> References: <548F51D6.8060903@gmail.com> Message-ID: <548F67BF.8050500@davea.name> On 12/15/2014 04:25 PM, Ken G. wrote: > I am sure there is a better way to refine the following lines. > > Letting x equal a number from 1 to 28, go through 28 separate 'if' > statements to print a resulting value that equaled the value of x. > > For example: > > x = 8 > > if x = 1, print 'one' > if x = 2, print 'two' > ... > ... > if x = 8, print 'eight' > ... > ... > if x = 28, print 'twenty eight' > > Would a single line using list or dictionary be shorter? > If this is an assignment, and you quoted it correctly, then you're required to go through 28 if statements. On the other hand, if that paragraph is just a description of the way you solved it, then yes, it can be improved. Just making all but the first if statement an elif will make it faster, because once it finds a value, it won't continue checking the remaining ones. Still faster would be testing first for fourteen, and making a tree out of the if statements, using > and < comparisons instead of only == comparisons. Worst case would be about 5 tests. This would not be more compact, just quicker to execute. Faster yet, and somewhat more compact would be to make a tuple or list of 29 items (0 through 28), and just index into it. Slower, but more compact, would be to write the kind of library that Danny pointed you to, or the code that Ken/Bod alluded to. But the real question is what's your goal. Your original code isn't legal Python, so you're presumably in a learning mode. If so, you want to keep it simple, not use 3rd party libraries for something you could do yourself. And when you're given an assignment, you should do it exactly the way they want it, and only after that's correct (and running), do it also in other ways. Those other ways could be to improve performance, reduce size, make it more readable (or less, to enter it in obfuscation contests), to make it independent of any loaded libraries, to look like some sample in another language, ... My second suggestion, untested: if x < 14: if x < 7: if x < 3: if x == 1: print ("one") else: print ("two") elif x < 5: if x == 3: print ("three") else: print ("four") .... -- DaveA From steve at pearwood.info Tue Dec 16 00:03:08 2014 From: steve at pearwood.info (Steven D'Aprano) Date: Tue, 16 Dec 2014 10:03:08 +1100 Subject: [Tutor] looking for a Python feature for computer teaching In-Reply-To: <20141215001203.GS20332@ando.pearwood.info> References: <20141215001203.GS20332@ando.pearwood.info> Message-ID: <20141215230308.GW20332@ando.pearwood.info> On Mon, Dec 15, 2014 at 11:12:04AM +1100, Steven D'Aprano wrote: > On Sun, Dec 14, 2014 at 11:29:08AM -0800, Pi Po wrote: > > > Want each interpreted line of code to introduce as a cells on > > a spreadsheet window each new variable (or array) with its initialized > > value, > > and show the updated contents of each previously defined variable (or > > array). > > > I haven't used any of these, but you can try them and see if they do > what you want: > > http://manns.github.io/pyspread/ A better link to pyspread is here: https://pypi.python.org/pypi/pyspread Coincidentally a new release has just come out. -- Steve From davea at davea.name Tue Dec 16 00:04:17 2014 From: davea at davea.name (Dave Angel) Date: Mon, 15 Dec 2014 18:04:17 -0500 Subject: [Tutor] Is there an easily or shorter way? In-Reply-To: <20141215224928.GV20332@ando.pearwood.info> References: <548F51D6.8060903@gmail.com> <20141215224928.GV20332@ando.pearwood.info> Message-ID: <548F68F1.8080906@davea.name> On 12/15/2014 05:49 PM, Steven D'Aprano wrote: > On Mon, Dec 15, 2014 at 04:25:42PM -0500, Ken G. wrote: >> I am sure there is a better way to refine the following lines. >> >> Letting x equal a number from 1 to 28, go through 28 separate 'if' >> statements to print a resulting value that equaled the value of x. > > Of course, as Danny suggested, if you're going to be using this > seriously for arbitrary numbers, you can't possibly list every single > one in advance. What if somebody asks for the name of 9274810276523? In > that case, we need a function that turns a number into an name digit by > digit: > > nine trillion, two hundred and seventy-four billion, > eight hundred and ten million, two hundred and > seventy-six thousand, five hundred and twenty-three That's using the American interpretation for billion and trillion, not the British one. > > Doing this makes a nice little programming exercise, so I will leave it > to you :-) "one, two, three, many" We only need four values, in some societies... ;-) -- DaveA From steve at pearwood.info Tue Dec 16 00:39:08 2014 From: steve at pearwood.info (Steven D'Aprano) Date: Tue, 16 Dec 2014 10:39:08 +1100 Subject: [Tutor] Is there an easily or shorter way? In-Reply-To: <548F68F1.8080906@davea.name> References: <548F51D6.8060903@gmail.com> <20141215224928.GV20332@ando.pearwood.info> <548F68F1.8080906@davea.name> Message-ID: <20141215233908.GX20332@ando.pearwood.info> On Mon, Dec 15, 2014 at 06:04:17PM -0500, Dave Angel wrote: > On 12/15/2014 05:49 PM, Steven D'Aprano wrote: > > nine trillion, two hundred and seventy-four billion, > > eight hundred and ten million, two hundred and > > seventy-six thousand, five hundred and twenty-three > > That's using the American interpretation for billion and trillion, not > the British one. Even the British use the American interpretation of billion these days. Mostly. There are probably still a few hold-outs, but I expect that "X-ion" meaning powers of 1000 has pretty much won out. > >Doing this makes a nice little programming exercise, so I will leave it > >to you :-) > > "one, two, three, many" > > We only need four values, in some societies... ;-) Okay, I'm up to this challenge... 9274810276523 in base 4: "2,012,331,311,301,121,222,223" two sextilots, onemany-two quinlots, three manymany and threemany-one quadlots, three manymany and onemany-one trilots, three manymany and one bilots, one manymany and twomany-one milots, two manymany and twomany-two lots, two manymany and twomany-three -- Steve From beachkidken at gmail.com Tue Dec 16 01:43:02 2014 From: beachkidken at gmail.com (Ken G.) Date: Mon, 15 Dec 2014 19:43:02 -0500 Subject: [Tutor] Is there an easily or shorter way? In-Reply-To: References: <548F51D6.8060903@gmail.com> Message-ID: <548F8016.2090509@gmail.com> On 12/15/2014 04:45 PM, Danny Yoo wrote: >> As a side note: if we were to talk about how we'd do this in a >> professional context, I think we'd recommend a library such as >> "humanize", which has functions to go from numbers to human-friendly >> string descriptions. >> >> https://pypi.python.org/pypi/humanize > > Whoops: wrong library. Humanize is a good one, but not exactly the > one I was supposed to cite. I should have cited num2words, which is a > cardinal number library: > > https://pypi.python.org/pypi/num2words > . Thank you but actually whatever number I get from either 1 to 28, each number represent a property name such as "Reading Railroad", "Judy Avenue", "Pacific Gas and Electric", etc., etc. For example: if x = 1 then print "Mediterranean Avenue" if x = 2 then print "Baltic Avenue" ... ... if x = 28 then print "Boardwalk" Yes, I am using the property names from the game, Monopoly. I am using them in conjunction with of playing a lottery game and using Python to determine if I won anything from the numbers drawn and being compared with what numbers I purchased. Of course, the proper format in Python would be: if x == "01": print "Mediterranean Avenue" ... ... if x == 28: print "Boardwalk" Again, thanks for your input. Ken From beachkidken at gmail.com Tue Dec 16 01:46:07 2014 From: beachkidken at gmail.com (Ken G.) Date: Mon, 15 Dec 2014 19:46:07 -0500 Subject: [Tutor] Is there an easily or shorter way? In-Reply-To: <20141215224928.GV20332@ando.pearwood.info> References: <548F51D6.8060903@gmail.com> <20141215224928.GV20332@ando.pearwood.info> Message-ID: <548F80CF.1080400@gmail.com> On 12/15/2014 05:49 PM, Steven D'Aprano wrote: > On Mon, Dec 15, 2014 at 04:25:42PM -0500, Ken G. wrote: >> I am sure there is a better way to refine the following lines. >> >> Letting x equal a number from 1 to 28, go through 28 separate 'if' >> statements to print a resulting value that equaled the value of x. > Since you only care about the first 28 values, a list or dict is the way > to go. The two look remarkably similar: > > # Using a dict. Replace the dots ... with the rest of the values. > names = {1: "one", 2: "two", 3: "three", ... 28: "twenty-eight"} > print(names[x]) > > # Using a list. Again, replace the dots. > names = ["zero", "one", "two", "three", ... "twenty-eight"] > print(names[x]) > > > I stress that neither version *quite* works yet. You have to replace the > dots ... with the rest of the values, which is tedious but not hard. > > In the case of the list version, the reason that I add an entry for zero > is that lists are indexed from zero. That is, given the list: > > L = ['spam', 'eggs', 'cheese', 'toast'] > > the first entry is written L[0], the second entry L[1] and so forth. > Although it takes a bit of getting used to, there actually are good > reasons for that. One advantage of dicts over lists is that you can > leave gaps while a list must have placeholders for every position: > > {2: "two", 4: "four", 8: "eight"} > ["", "", "two", "", "four", "", "", "", "eight"] > > > Of course, as Danny suggested, if you're going to be using this > seriously for arbitrary numbers, you can't possibly list every single > one in advance. What if somebody asks for the name of 9274810276523? In > that case, we need a function that turns a number into an name digit by > digit: > > nine trillion, two hundred and seventy-four billion, > eight hundred and ten million, two hundred and > seventy-six thousand, five hundred and twenty-three > > Doing this makes a nice little programming exercise, so I will leave it > to you :-) > > Yes, Steven, it would be a 'nice' programming exercise. If I could just find the time...sighs. Thanks, Ken From dyoo at hashcollision.org Tue Dec 16 01:47:48 2014 From: dyoo at hashcollision.org (Danny Yoo) Date: Mon, 15 Dec 2014 16:47:48 -0800 Subject: [Tutor] Is there an easily or shorter way? In-Reply-To: <548F8016.2090509@gmail.com> References: <548F51D6.8060903@gmail.com> <548F8016.2090509@gmail.com> Message-ID: > > Thank you but actually whatever number I get from either 1 to 28, > each number represent a property name such as "Reading Railroad", > "Judy Avenue", "Pacific Gas and Electric", etc., etc. > > For example: > > if x = 1 then print "Mediterranean Avenue" > if x = 2 then print "Baltic Avenue" Ah, cool! Ok, then yes, definitely a list. There's a sequential-ness here that we should take advantage of. PLACES = ["Is-there-a-place-when-x-is-zero?", "Mediterranean Avenue", "Baltic Avenue", ] # and so on ... print PLACES[x] so that all the conditioning dissolves into a single list lookup. There might need to be a few more checks to make sure x is in bounds, but it's worth it here. From beachkidken at gmail.com Tue Dec 16 01:55:17 2014 From: beachkidken at gmail.com (Ken G.) Date: Mon, 15 Dec 2014 19:55:17 -0500 Subject: [Tutor] Is there an easily or shorter way? In-Reply-To: <548F67BF.8050500@davea.name> References: <548F51D6.8060903@gmail.com> <548F67BF.8050500@davea.name> Message-ID: <548F82F5.40402@gmail.com> On 12/15/2014 05:59 PM, Dave Angel wrote: > On 12/15/2014 04:25 PM, Ken G. wrote: >> I am sure there is a better way to refine the following lines. >> >> Letting x equal a number from 1 to 28, go through 28 separate 'if' >> statements to print a resulting value that equaled the value of x. >> >> For example: >> >> x = 8 >> >> if x = 1, print 'one' >> if x = 2, print 'two' >> ... >> ... >> if x = 8, print 'eight' >> ... >> ... >> if x = 28, print 'twenty eight' >> >> Would a single line using list or dictionary be shorter? >> > > If this is an assignment, and you quoted it correctly, then you're > required to go through 28 if statements. On the other hand, if that > paragraph is just a description of the way you solved it, then yes, it > can be improved. Just making all but the first if statement an elif > will make it faster, because once it finds a value, it won't continue > checking the remaining ones. > > Still faster would be testing first for fourteen, and making a tree > out of the if statements, using > and < comparisons instead of only == > comparisons. Worst case would be about 5 tests. This would not be > more compact, just quicker to execute. > > Faster yet, and somewhat more compact would be to make a tuple or list > of 29 items (0 through 28), and just index into it. > > Slower, but more compact, would be to write the kind of library that > Danny pointed you to, or the code that Ken/Bod alluded to. > > But the real question is what's your goal. Your original code isn't > legal Python, so you're presumably in a learning mode. If so, you > want to keep it simple, not use 3rd party libraries for something you > could do yourself. And when you're given an assignment, you should do > it exactly the way they want it, and only after that's correct (and > running), do it also in other ways. Those other ways could be to > improve performance, reduce size, make it more readable (or less, to > enter it in obfuscation contests), to make it independent of any > loaded libraries, to look like some sample in another language, ... > > > My second suggestion, untested: > if x < 14: > if x < 7: > if x < 3: > if x == 1: > print ("one") > else: > print ("two") > elif x < 5: > if x == 3: > print ("three") > else: > print ("four") > .... > > > Oh, it is not an assignment, Dave. It is an actual program I am using for my benefit. I had to figure out on a fly, what is the name of a piece of property that each number represent. I had to reckon something out within a limited amount of time I had. Giving the response given here so far, I could go with a list, dictionary or tuple. Thanks for your input. Ken From davea at davea.name Tue Dec 16 04:50:59 2014 From: davea at davea.name (Dave Angel) Date: Mon, 15 Dec 2014 22:50:59 -0500 Subject: [Tutor] Is there an easily or shorter way? In-Reply-To: <548F82F5.40402@gmail.com> References: <548F51D6.8060903@gmail.com> <548F67BF.8050500@davea.name> <548F82F5.40402@gmail.com> Message-ID: <548FAC23.1030205@davea.name> On 12/15/2014 07:55 PM, Ken G. wrote: > > Oh, it is not an assignment, Dave. It is an actual program I am using > for my benefit. I had to figure out on a fly, what is the name of a piece > of property that each number represent. I had to reckon something out > within a limited amount of time I had. Giving the response given here > so far, I could go with a list, dictionary or tuple. > Two other advantages with using a tuple, list or dictionary 1) is that you might someday need to do the reverse lookup, changing a string back into the integer. If you do it from the same data structure, you're more likely to get the transformation to be completely reversible (for valid values). 2) You might need to load this table from a file, or otherwise generate or check it on the fly. Tough to do that with separate function statements. -- DaveA From sbharuchi at gmail.com Tue Dec 16 05:06:06 2014 From: sbharuchi at gmail.com (Sunil Bharuchi) Date: Mon, 15 Dec 2014 23:06:06 -0500 Subject: [Tutor] program code for Python Programming for the Absolute Beginner, 3rd ed.? Message-ID: I went to the website (www.courseptr.com/downloads) to download the source code (py3e_source.zip). It's not there. Where can I get it the source code? -- Sunil Bharuchi sunilkumar.bharuchi.mil at mail.mil sbharuchi at gmail.com (C) 408.644.7626 From alan.gauld at btinternet.com Tue Dec 16 11:39:20 2014 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 16 Dec 2014 10:39:20 +0000 Subject: [Tutor] program code for Python Programming for the Absolute Beginner, 3rd ed.? In-Reply-To: References: Message-ID: On 16/12/14 04:06, Sunil Bharuchi wrote: > I went to the website (www.courseptr.com/downloads) to download the source > code (py3e_source.zip). It's not there. Where can I get it the source code? > Try using Google with python absolute beginners source code -- 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 From juan0christian at gmail.com Tue Dec 16 15:18:19 2014 From: juan0christian at gmail.com (Juan Christian) Date: Tue, 16 Dec 2014 14:18:19 +0000 Subject: [Tutor] Python 3.4.1 ImportError Linux Message-ID: Python 3.4.1 Fedora 21 Server My paths: ~/lorem ~/lorem/app ~/lorem/core I want to execute: ~/lorem/app/main.py Terminal (~/lorem/app): python3 main.py Traceback (most recent call last): File "app/main.py", line 5, in from core.backpack import BackpackThread ImportError: No module named 'core' Why am I getting this? From james at uplinkzero.com Tue Dec 16 15:45:41 2014 From: james at uplinkzero.com (James Chapman) Date: Tue, 16 Dec 2014 14:45:41 +0000 Subject: [Tutor] Python 3.4.1 ImportError Linux In-Reply-To: References: Message-ID: cd .. Terminal (~/lorem): python3 app/main.py import statement is relative to pwd. -- James On 16 December 2014 at 14:18, Juan Christian wrote: > > Python 3.4.1 > Fedora 21 Server > > My paths: > ~/lorem > ~/lorem/app > ~/lorem/core > > I want to execute: ~/lorem/app/main.py > > Terminal (~/lorem/app): python3 main.py > > Traceback (most recent call last): > File "app/main.py", line 5, in > from core.backpack import BackpackThread > ImportError: No module named 'core' > > > Why am I getting this? > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor > From beachkidken at gmail.com Tue Dec 16 16:17:09 2014 From: beachkidken at gmail.com (Ken G.) Date: Tue, 16 Dec 2014 10:17:09 -0500 Subject: [Tutor] RESOLVED: Re: Is there an easily or shorter way? In-Reply-To: References: <548F51D6.8060903@gmail.com> <548F8016.2090509@gmail.com> Message-ID: <54904CF5.6010307@gmail.com> On 12/15/2014 07:47 PM, Danny Yoo wrote: >> Thank you but actually whatever number I get from either 1 to 28, >> each number represent a property name such as "Reading Railroad", >> "Judy Avenue", "Pacific Gas and Electric", etc., etc. >> >> For example: >> >> if x = 1 then print "Mediterranean Avenue" >> if x = 2 then print "Baltic Avenue" > > Ah, cool! Ok, then yes, definitely a list. There's a sequential-ness > here that we should take advantage of. > > PLACES = ["Is-there-a-place-when-x-is-zero?", > "Mediterranean Avenue", > "Baltic Avenue", > ] # and so on ... > > print PLACES[x] > > > so that all the conditioning dissolves into a single list lookup. > There might need to be a few more checks to make sure x is in bounds, > but it's worth it here. Thank you, thank you. As I think it over through the night, I had a very faint idea of what you suggested. Again, thank. Ken From fomcl at yahoo.com Tue Dec 16 16:17:14 2014 From: fomcl at yahoo.com (Albert-Jan Roskam) Date: Tue, 16 Dec 2014 15:17:14 +0000 (UTC) Subject: [Tutor] Is there an easily or shorter way? In-Reply-To: References: Message-ID: <1740259301.206526.1418743034484.JavaMail.yahoo@jws10735.mail.gq1.yahoo.com> ----- Original Message ----- > From: Danny Yoo > To: Ken G. > Cc: Python Tutor Mailing List > Sent: Monday, December 15, 2014 10:45 PM > Subject: Re: [Tutor] Is there an easily or shorter way? > >> As a side note: if we were to talk about how we'd do this in a >> professional context, I think we'd recommend a library such as >> "humanize", which has functions to go from numbers to > human-friendly >> string descriptions. >> >> https://pypi.python.org/pypi/humanize > > > Whoops: wrong library. Humanize is a good one, but not exactly the > one I was supposed to cite. I should have cited num2words, which is a > cardinal number library: > > https://pypi.python.org/pypi/num2words Nice, useful. Humanize seems a better choice because it uses gettext. It is probably easier to add another language (like my own, which is not part of the package). From james at uplinkzero.com Tue Dec 16 16:14:17 2014 From: james at uplinkzero.com (James Chapman) Date: Tue, 16 Dec 2014 15:14:17 +0000 Subject: [Tutor] Python 3.4.1 ImportError Linux In-Reply-To: References: Message-ID: > Further to my last email, here's some reading regarding Python Paths > > http://www.stereoplex.com/blog/understanding-imports-and-pythonpath From jcgallaher78 at gmail.com Tue Dec 16 13:16:56 2014 From: jcgallaher78 at gmail.com (Jim Gallaher) Date: Tue, 16 Dec 2014 06:16:56 -0600 Subject: [Tutor] Tutor Digest, Vol 130, Issue 28 In-Reply-To: References: Message-ID: Sunil Bharuchi, I have that same book so I can answer this question. The code can be found at the author's site. programgames.com > On Dec 16, 2014, at 05:00, tutor-request at python.org wrote: > > Send Tutor mailing list submissions to > tutor at python.org > > To subscribe or unsubscribe via the World Wide Web, visit > https://mail.python.org/mailman/listinfo/tutor > or, via email, send a message with subject or body 'help' to > tutor-request at python.org > > You can reach the person managing the list at > tutor-owner at python.org > > When replying, please edit your Subject line so it is more specific > than "Re: Contents of Tutor digest..." > > > Today's Topics: > > 1. Re: Is there an easily or shorter way? (Dave Angel) > 2. Re: program code for Python Programming for the Absolute > Beginner, 3rd ed.? (Sunil Bharuchi) > 3. Re: program code for Python Programming for the Absolute > Beginner, 3rd ed.? (Alan Gauld) > > > ---------------------------------------------------------------------- > > Message: 1 > Date: Mon, 15 Dec 2014 22:50:59 -0500 > From: Dave Angel > To: tutor at python.org > Subject: Re: [Tutor] Is there an easily or shorter way? > Message-ID: <548FAC23.1030205 at davea.name> > Content-Type: text/plain; charset=ISO-8859-1; format=flowed > >> On 12/15/2014 07:55 PM, Ken G. wrote: >> >> Oh, it is not an assignment, Dave. It is an actual program I am using >> for my benefit. I had to figure out on a fly, what is the name of a piece >> of property that each number represent. I had to reckon something out >> within a limited amount of time I had. Giving the response given here >> so far, I could go with a list, dictionary or tuple. > > Two other advantages with using a tuple, list or dictionary > > 1) is that you might someday need to do the reverse lookup, changing a > string back into the integer. If you do it from the same data > structure, you're more likely to get the transformation to be completely > reversible (for valid values). > > 2) You might need to load this table from a file, or otherwise generate > or check it on the fly. Tough to do that with separate function statements. > > -- > DaveA > > > ------------------------------ > > Message: 2 > Date: Mon, 15 Dec 2014 23:06:06 -0500 > From: Sunil Bharuchi > To: tutor at python.org > Subject: Re: [Tutor] program code for Python Programming for the > Absolute Beginner, 3rd ed.? > Message-ID: > > Content-Type: text/plain; charset=UTF-8 > > I went to the website (www.courseptr.com/downloads) to download the source > code (py3e_source.zip). It's not there. Where can I get it the source code? > > -- > Sunil Bharuchi > sunilkumar.bharuchi.mil at mail.mil > sbharuchi at gmail.com > (C) 408.644.7626 > > > ------------------------------ > > Message: 3 > Date: Tue, 16 Dec 2014 10:39:20 +0000 > From: Alan Gauld > To: tutor at python.org > Subject: Re: [Tutor] program code for Python Programming for the > Absolute Beginner, 3rd ed.? > Message-ID: > Content-Type: text/plain; charset=windows-1252; format=flowed > >> On 16/12/14 04:06, Sunil Bharuchi wrote: >> I went to the website (www.courseptr.com/downloads) to download the source >> code (py3e_source.zip). It's not there. Where can I get it the source code? > > Try using Google with > > python absolute beginners source code > > -- > 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 > > > > > ------------------------------ > > Subject: Digest Footer > > _______________________________________________ > Tutor maillist - Tutor at python.org > https://mail.python.org/mailman/listinfo/tutor > > > ------------------------------ > > End of Tutor Digest, Vol 130, Issue 28 > ************************************** From alan.gauld at btinternet.com Wed Dec 17 00:50:02 2014 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 16 Dec 2014 23:50:02 +0000 Subject: [Tutor] Tutor Digest, Vol 130, Issue 28 In-Reply-To: References: Message-ID: On 16/12/14 12:16, Jim Gallaher wrote: > > Sunil Bharuchi, > > I have that same book so I can answer this question. The code can be found at the author's site. programgames.com Thanks for answering the question but please, in future, provide a meaningful subject line (for archive purposes) and also delete the contents of the digest that is not relevant. Some members pay by the byte for their internet access and others just dislike being sent stuff they have already seen as members of the list. Thankyou -- Alan G List moderator From AbdullahiFarah.Moham at claremont-high.org.uk Thu Dec 18 22:10:40 2014 From: AbdullahiFarah.Moham at claremont-high.org.uk (Abdullahi Farah Mohamud) Date: Thu, 18 Dec 2014 21:10:40 +0000 Subject: [Tutor] (no subject) Message-ID: hello i need help with a program and i dont understand what is wrong it is a lottery ticket generator. the problem is: when the computers asks the user if he would like to go again and the user says yes, it asks for the number of lines and then if the user clicks 3 it will only give me one line. here is the code appreciate if you could help import random abz = 0 lines = int(input('How many lines would you like?')) loop = lines if lines >7: print('Too many lines saaxib') exit() else: print() while lines != 0: line1 = random.randint (1,7) line2 = random.randint (8,14) line3 = random.randint (15,21) line4 = random.randint (22,28) line5 = random.randint (29,35) line6 = random.randint (36,42) line7 = random.randint (43,49) lines = lines - 1 print(line1, line2, line3, line4, line5, line6,line7) while abz == 0: again = input('Would you like to go again?') if again == 'yes': lines = int(input('How many lines would you like?')) line1 = random.randint (1,7) line2 = random.randint (8,14) line3 = random.randint (15,21) line4 = random.randint (22,28) line5 = random.randint (29,35) line6 = random.randint (36,42) line7 = random.randint (43,49) lines = lines - 1 print(line1, line2, line3, line4, line5, line6,line7) if again == 'no': print('Okay the program is finished saaxib') exit() From alan.gauld at btinternet.com Fri Dec 19 01:55:49 2014 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 19 Dec 2014 00:55:49 +0000 Subject: [Tutor] lottery problem (Was Re: (no subject)) In-Reply-To: References: Message-ID: On 18/12/14 21:10, Abdullahi Farah Mohamud wrote: > hello i need help with a program and i dont understand what is wrong Please always add a meaningful subject line. > when the computers asks the user if he would like to go again > and the user says yes, it asks for the number of lines > and then if the user clicks 3 it will only give > me one line. > import random > abz = 0 > lines = int(input('How many lines would you like?')) > loop = lines > if lines >7: You might want to check fpor negative numbers too or you will loop forever. > print('Too many lines saaxib') > exit() > else: > print() > while lines != 0: > line1 = random.randint (1,7) > line2 = random.randint (8,14) > line3 = random.randint (15,21) > line4 = random.randint (22,28) > line5 = random.randint (29,35) > line6 = random.randint (36,42) > line7 = random.randint (43,49) > lines = lines - 1 > print(line1, line2, line3, line4, line5, line6,line7) Down to here basically works. But... You could have used a list instead of all the individual variables line[0] = ... line[1] = ... But then you could get clever and use a loop: while lines != 0: start = 1 period = 7 for lineNum in range(7): line[lineNum] = random(start,period) start += period period += period print (*line) lines -=1 > while abz == 0: > again = input('Would you like to go again?') > if again == 'yes': > lines = int(input('How many lines would you like?')) > line1 = random.randint (1,7) Notice this is outside the if statement so will execute regardless of the answer. But unlike the equivalent section above it is NOT in a while loop so will only execute once per question. Which is what you were seeing. > line2 = random.randint (8,14) > line3 = random.randint (15,21) > line4 = random.randint (22,28) > line5 = random.randint (29,35) > line6 = random.randint (36,42) > line7 = random.randint (43,49) > lines = lines - 1 > print(line1, line2, line3, line4, line5, line6,line7) Since you are duplicating code you could put it in a function - have you seen functions yet? def getLine(start=1, period=7): line = [] for lineNum in range(7): line[lineNum] = random(start,period) start += period period += period return line then the while loop becomes: while lines != 0: line = getLine() print(*line) lines -= 1 > if again == 'no': > print('Okay the program is finished saaxib') > exit() 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 From steve at pearwood.info Fri Dec 19 02:03:35 2014 From: steve at pearwood.info (Steven D'Aprano) Date: Fri, 19 Dec 2014 12:03:35 +1100 Subject: [Tutor] (no subject) In-Reply-To: References: Message-ID: <20141219010335.GD20332@ando.pearwood.info> On Thu, Dec 18, 2014 at 09:10:40PM +0000, Abdullahi Farah Mohamud wrote: > hello i need help with a program and i dont understand what is wrong > it is a lottery ticket generator. > the problem is: > when the computers asks the user if he would like to go again and the user says yes, it asks for the number of lines and then if the user clicks 3 it will only give me one line. > here is the code > appreciate if you could help > > > import random > abz = 0 > lines = int(input('How many lines would you like?')) > loop = lines > if lines >7: > print('Too many lines saaxib') > exit() > else: > print() Here you loop over each lines. A "while loop" is not the best way to do this, a for loop would be much better. > while lines != 0: > line1 = random.randint (1,7) > line2 = random.randint (8,14) > line3 = random.randint (15,21) > line4 = random.randint (22,28) > line5 = random.randint (29,35) > line6 = random.randint (36,42) > line7 = random.randint (43,49) > lines = lines - 1 > print(line1, line2, line3, line4, line5, line6,line7) When you finish this while loop, you then start a brand new while loop: > while abz == 0: > again = input('Would you like to go again?') > if again == 'yes': > lines = int(input('How many lines would you like?')) All this does is repeatedly ask the user if they want to go again, over and over and over and over again, never stopping. It never stops because abz never gets changed: it starts with the value 0, and it stays with the value 0 forever. Here is how I would solve this problem in English. You can try translating it into Python code: start WHILE the user wants to play: ask how many numbers to pick FOR each of those numbers: print a random number print that number ask the user if they want to play again end Take note of the indentation: there is only one WHILE loop, and asking the user if they want to play again is *inside* that while loop, not outside it. Hope that this helps. Please try your best to change this to Python code, and ask for help if you need it. -- Steven From hanzer at riseup.net Fri Dec 19 02:27:03 2014 From: hanzer at riseup.net (Adam Jensen) Date: Thu, 18 Dec 2014 20:27:03 -0500 Subject: [Tutor] lottery problem (Was Re: (no subject)) In-Reply-To: References: Message-ID: <20141218202703.8f82ddd11cd43f68ba6577df@riseup.net> On Fri, 19 Dec 2014 00:55:49 +0000 Alan Gauld wrote: > You could have used a list instead of all the > individual variables > > line[0] = ... > line[1] = ... > > But then you could get clever and use a loop: > > while lines != 0: > start = 1 > period = 7 > for lineNum in range(7): > line[lineNum] = random(start,period) > start += period > period += period > print (*line) > lines -=1 > A list comprehension might be fun. https://docs.python.org/3.4/tutorial/datastructures.html#list-comprehensions For example: >>> [random.randint(x,x+6) for x in range(1,50,7)] [4, 9, 15, 27, 33, 36, 49] And to build the 'lines' list (although, this is getting rather ugly): >>> lines = [[random.randint(x,x+6) for x in range(1,50,7)] for i in range(7)] >>> lines [[2, 13, 18, 27, 35, 37, 47], [1, 11, 21, 24, 34, 37, 49], [7, 12, 16, 24, 29, 36, 44], [4, 9, 16, 22, 32, 37, 46], [2, 13, 20, 22, 29, 40, 46], [7, 14, 19, 26, 35, 42, 43], [4, 12, 16, 22, 34, 40, 46]] It might also be a good idea to execute random.seed() before calling randint() - https://docs.python.org/3.4/library/random.html#random.seed From hanzer at riseup.net Fri Dec 19 05:24:02 2014 From: hanzer at riseup.net (Adam Jensen) Date: Thu, 18 Dec 2014 23:24:02 -0500 Subject: [Tutor] lottery problem (Was Re: (no subject)) In-Reply-To: <20141218202703.8f82ddd11cd43f68ba6577df@riseup.net> References: <20141218202703.8f82ddd11cd43f68ba6577df@riseup.net> Message-ID: <20141218232402.68ca052ac62e8883c05d2c84@riseup.net> On Thu, 18 Dec 2014 20:27:03 -0500 Adam Jensen wrote: > And to build the 'lines' list (although, this is getting rather ugly): > > >>> lines = [[random.randint(x,x+6) for x in range(1,50,7)] for i in range(7)] Oops, in the context of the original program this might make more sense if written as: data = [[random.randint(x,x+6) for x in range(1,50,7)] for i in range(lines)] Side note: if one were to only import specific functions from a module, would the load time and memory consumption be smaller? Example, is: from random import randint, seed smaller and faster than: import random Side side note: since 'i' isn't being used, is there a way to loop (within the list comprehension) without the 'i'? For example, to generate three random numbers: [randint(1,10) for i in range(3)] # This works. [randint(1,10) for range(3)] # This does not work. From brandontdr at gmail.com Fri Dec 19 03:09:59 2014 From: brandontdr at gmail.com (Brandon Dorsey) Date: Thu, 18 Dec 2014 21:09:59 -0500 Subject: [Tutor] Learning to program, not code. Message-ID: Hello All, Programming has always been a passion of mine, however, I'm frequently frustrated at simple fact that I've been learning python for 8 months, and I have yet to start, and finish, a simple project. I find difficult to not only visualize the execution, but to figure out when and where to use data structure 'x'. Any suggestions on how to approach programming from a different angle? From __peter__ at web.de Fri Dec 19 10:32:15 2014 From: __peter__ at web.de (Peter Otten) Date: Fri, 19 Dec 2014 10:32:15 +0100 Subject: [Tutor] lottery problem (Was Re: (no subject)) References: <20141218202703.8f82ddd11cd43f68ba6577df@riseup.net> <20141218232402.68ca052ac62e8883c05d2c84@riseup.net> Message-ID: Adam Jensen wrote: > Side note: if one were to only import specific functions from a module, > would the load time and memory consumption be smaller? Example, is: > > from random import randint, seed > > smaller and faster than: > > import random Basically from random import randint, seed is equivalent to import random randint = random.randint seed = random.seed del random >From that you can deduce that the whole random module is loaded into memory in both cases. A small speed advantage may be caused when the attribute lookup is avoided in a tight loop $ python3 -m timeit -s 'import random' 'random.randint' 10000000 loops, best of 3: 0.0925 usec per loop $ python3 -m timeit -s 'from random import randint' 'randint' 10000000 loops, best of 3: 0.0356 usec per loop but the actual randint() function call is so "heavy" that this speedup is lost in the noise when you actually invoke the function: $ python3 -m timeit -s 'from random import randint' 'randint(0, 42)' 100000 loops, best of 3: 3.73 usec per loop $ python3 -m timeit -s 'import random' 'random.randint(0, 42)' 100000 loops, best of 3: 3.82 usec per loop > Side side note: since 'i' isn't being used, is there a way to loop (within > the list comprehension) without the 'i'? For example, to generate three > random numbers: > > [randint(1,10) for i in range(3)] # This works. > [randint(1,10) for range(3)] # This does not work. No, but in numpy you can express it directly numpy.random.randint(1, 10, 3) or -- if you go back to the original problem -- with some effort: >>> N = 3 >>> numpy.random.randint(1, 10, N) + numpy.arange(0, N*10, 10) array([ 5, 11, 27]) In return the latter is likely significantly more efficient for large N than the generic list comprehension. From joseph.lee22590 at gmail.com Fri Dec 19 10:44:56 2014 From: joseph.lee22590 at gmail.com (Joseph Lee) Date: Fri, 19 Dec 2014 01:44:56 -0800 Subject: [Tutor] FW: Learning to program, not code. References: Message-ID: <000101d01b70$734a2330$59de6990$@gmail.com> Oops, sent it to the original poster only. -----Original Message----- From: Joseph Lee [mailto:joseph.lee22590 at gmail.com] Sent: Friday, December 19, 2014 1:43 AM To: 'Brandon Dorsey' Subject: RE: [Tutor] Learning to program, not code. Hi Brandon, Answers are below. -----Original Message----- From: Tutor [mailto:tutor-bounces+joseph.lee22590=gmail.com at python.org] On Behalf Of Brandon Dorsey Sent: Thursday, December 18, 2014 6:10 PM To: tutor at python.org Subject: [Tutor] Learning to program, not code. Hello All, Programming has always been a passion of mine, however, I'm frequently frustrated at simple fact that I've been learning python for 8 months, and I have yet to start, and finish, a simple project. I find difficult to not only visualize the execution, but to figure out when and where to use data structure 'x'. Any suggestions on how to approach programming from a different angle? JL: A very good question. I come from C++ background and have been using Python since 2012. After speaking Python for a while, I realize that programming can be best described as writing a story or an essay. The English-like syntax of Python, coupled with use of indentation and good number of tools helped me appreciate how a program works (for me, from machine level mostly, as I'm working on a project that uses PyWin32 extensions and Win32 API a lot). Another way to approach programming a project is playing a musical piece or watching a play. When you play a song, you know when and how to play a given melody, or when watching a play, you get an idea as to how an actor portrays a particular character. For me, I sometimes view programming as writing a play (rather, a musical), with data structures being props and functions being actors (believe it or not, many geeks are good at arts, including myself - I use my fingers to type the latest screen reading algorithms in Python and play show tunes and video game themes on piano). Good luck. Cheers, Joseph _______________________________________________ Tutor maillist - Tutor at python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor From sarika1989.08 at gmail.com Fri Dec 19 10:38:52 2014 From: sarika1989.08 at gmail.com (Sarika Shrivastava) Date: Fri, 19 Dec 2014 15:08:52 +0530 Subject: [Tutor] Learning to program, not code. In-Reply-To: References: Message-ID: Hello All I am also facing write a code in python please help me for this i read all concepts of python but whem i will started this i am facing lot of problems . ---------- Forwarded message ---------- From: Brandon Dorsey Date: Fri, Dec 19, 2014 at 7:39 AM Subject: [Tutor] Learning to program, not code. To: tutor at python.org Hello All, Programming has always been a passion of mine, however, I'm frequently frustrated at simple fact that I've been learning python for 8 months, and I have yet to start, and finish, a simple project. I find difficult to not only visualize the execution, but to figure out when and where to use data structure 'x'. Any suggestions on how to approach programming from a different angle? _______________________________________________ Tutor maillist - Tutor at python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor -- From alan.gauld at btinternet.com Fri Dec 19 11:27:24 2014 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 19 Dec 2014 10:27:24 +0000 Subject: [Tutor] Learning to program, not code. In-Reply-To: References: Message-ID: On 19/12/14 02:09, Brandon Dorsey wrote: > simple fact that I've been learning python for 8 months, and I have yet to > start, and finish, a simple project. That's a pity because the detail involved in completing a project is often where you learn most. Maybe you should take time out from "learning" to concentrate on finishing one simple project. Make a start and when you get stuck, ask here. > I find difficult to not only visualize the execution, but to > figure out when and where to use data structure 'x'. The base data structures of list, tuple, set, dictionary all have fairly specific uses. - Sets are collections of unique values - Lists are numerically indexed, mutable collections of values - Tuples are numerically indexed, immutable collections of values - Dictionaries are keyed, mutable collections of values. Often you can use any one of list, tuple or dictionary... Use a tuple if it won't be changing. Use a dictionary if you have a natural key value Otherwise use a list Classes are a special case and are best discussed separately if that's where you are struggling. You don't need classes for most simple projects. > Any suggestions on how to approach programming > from a different angle? You could try designing the program before you start. Often jumping into code too soon leads to confusion. Do you have any method of structuring your code before you start? (For example using pdeudo-code or flow charts?) For a completely different approach to designing code (using Scheme but applicable to Python too) take a look at the web site/ebook "How to Design Programs" http://www.htdp.org/ This is particularly helpful if your problems tend to be algorithmic in nature rather than data store focused. 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 From alan.gauld at btinternet.com Fri Dec 19 11:46:41 2014 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 19 Dec 2014 10:46:41 +0000 Subject: [Tutor] Learning to program, not code. In-Reply-To: References: Message-ID: On 19/12/14 09:38, Sarika Shrivastava wrote: > I am also facing write a code in python please help me for > this i read all concepts of python > but whem i will started this i am facing lot of problems . Feel free to ask questions here. But please be specific. We need to know what kind of program you are writing; what its inputs and outputs should look like. If you get error messages you don't understand post the entire error message and at least some of the code from the place where it occurs. (If the code is short (less than 100 lines?) post all of it) Finally, tell us the OS and Python version. -- 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 From davea at davea.name Fri Dec 19 14:06:39 2014 From: davea at davea.name (Dave Angel) Date: Fri, 19 Dec 2014 08:06:39 -0500 Subject: [Tutor] Learning to program, not code. In-Reply-To: References: Message-ID: <549422DF.3050808@davea.name> On 12/18/2014 09:09 PM, Brandon Dorsey wrote: > Hello All, > > Programming has always been a passion of mine, A great start. Can you tell us a little more about yourself? Is Python the first language you've tried, or are you successful at other languages? Are you in school, at what level, do you already have some other career and this is a hobby? Do you have some hobbies that programming might synergize with? > however, I'm frequently > frustrated at > > simple fact that I've been learning python for 8 months, and I have yet to > start, and finish, a simple > > project. How are you learning python? Are you in a class, did you buy a book, download a tutorial, what? > I find difficult to not only visualize the execution, There are tools that may help with that, but it's not clear to me whether that would really help. If you want to play, you could look at: ttp://www.pythontutor.com/visualize.html#mode=edit > but to figure out when and where to > > use data structure 'x'. Alan gave some brief descriptions. You should realize that those are just the particular collections that are in the builtin section of python. There are many more in the standard library, MANY more out on the internet (eg. pypi), and many more in your head, just aching to come out. Any suggestions on how to approach programming > from a different angle? That's a great perspective. We're now drowning in a sea of riches, information on any topic. But in most cases, you have to be introduced to a topic systematically, with controlled flow, in order to understand what the fancier concepts are all about. When I "started" programming in 1966, it was with a borrowed Fortran book over spring break. I wrote a number of programs on sheets of paper, but had no machine to execute them on. (I also expect there were more errors than useful statements, but I didn't know anything about that either) I went on a field trip to the nearest computer, which was at Yale. I got to see the actual machinery through some large windows, but didn't have a chance to run anything till almost a year later, at my own college. Even then, freshmen weren't taught anything about them, and I had to learn from another student how to submit punched cards to the computer. And how to run jobs without having a legitimate account. Frequently when people develop an interest in programming now, it's in order to write a game, design a website, or to solve some fairly complex problem. If they then try to research the tools, they get overwhelmed with the possibilities. And without a narrower focus, they never get that satisfaction that comes with finishing a project. Without knowing anything at all about you really, I'd suggest you either take a course, or really *do* a tutorial. Many people just read a book (or site) about the subject, and don't actually try the exercises. In my case it was excusable, since I didn't have the several million dollars necessary to buy a computer, but the principle still holds. Start small, and systematically build up your abilities. If you're disciplined enough to do that on your own, there are many Python tutorials that you can download. And when you get stuck, you'll have a manageable problem that somebody can help with. If you've done all that, and you're still stuck, then be much more specific in your question here. Pick a project (or exercise, or assignment) that you've started working on, and describe the following: 1) python version and OS version 2) project description 3) code fragment that shows your present difficulty 4) what happens, and what you hoped would happen 5) any error messages (show the full stack trace) you get 6) meaningful subject line Python is a fabulous language for learning. You can get feedback a few seconds after you run the code, and you can make a change and try again in under a minute. I worked in one environment where the turnaround for a compile was about a day and a half. And in another where the compile of the complete application was done only once a week, and making it was a half-time job for the build-master. I've also worked in environments where I had to build my own programming tools, starting with a text editor. And in environments where we entered the code in hex. And generating the hex was a pencil/paper exercise. Looseleaf notebook was the source code. -- DaveA From hanzer at riseup.net Fri Dec 19 17:57:28 2014 From: hanzer at riseup.net (Adam Jensen) Date: Fri, 19 Dec 2014 11:57:28 -0500 Subject: [Tutor] lottery problem (Was Re: (no subject)) In-Reply-To: References: <20141218202703.8f82ddd11cd43f68ba6577df@riseup.net> <20141218232402.68ca052ac62e8883c05d2c84@riseup.net> Message-ID: <20141219115728.e1cb8358710fab0848f69dec@riseup.net> On Fri, 19 Dec 2014 10:32:15 +0100 Peter Otten <__peter__ at web.de> wrote: > Basically > > from random import randint, seed > > is equivalent to > > import random > randint = random.randint > seed = random.seed > del random > > From that you can deduce that the whole random module is loaded into memory > in both cases. A small speed advantage may be caused when the attribute > lookup is avoided in a tight loop Thanks for the clarification, that's really helpful. So I guess the import style is more about name space management than controlling the details of what gets loaded... > or -- if you go back to the original problem -- with some effort: > > >>> N = 3 > >>> numpy.random.randint(1, 10, N) + numpy.arange(0, N*10, 10) > array([ 5, 11, 27]) > > In return the latter is likely significantly more efficient for large N than > the generic list comprehension. Ha! That's fun. Seven seems to be a magic number in the original problem, so maybe a little tweak: import numpy as np N=7 (np.random.randint(1,N,N) + np.arange(0,N*N,N)).tolist() From robertvstepp at gmail.com Sat Dec 20 03:12:14 2014 From: robertvstepp at gmail.com (boB Stepp) Date: Fri, 19 Dec 2014 20:12:14 -0600 Subject: [Tutor] Learning to program, not code. [LONG RESPONSE!] Message-ID: On Thu, Dec 18, 2014 at 8:09 PM, Brandon Dorsey wrote: > > Hello All, > > Programming has always been a passion of mine, however, I'm frequently > frustrated at > > simple fact that I've been learning python for 8 months, and I have yet to > start, and finish, a simple > > project. I find difficult to not only visualize the execution, but to > figure out when and where to > > use data structure 'x'. Any suggestions on how to approach programming > from a different angle? I am going to take a stab at this. Perhaps the perspective from a non-professional in the world of computer programming might be of help. Like you I have had an ongoing fascination with computers and programming ever since I encountered punch cards, FORTRAN and an IBM mainframe in a computer science 101-like course in 1975. Ever since I've from time to time had encounters with programming, that have become more prevalent of late. Perhaps it might be helpful to view programming more simply as computer-aided problem solving, even though, at times, the computer seems to be a major stumbling block if not the outright problem itself. Thinking about it this way means that whatever techniques you know that have proven fruitful for solving other intellectual problems should be useful for programming conundrums as well. A major starting point is to make sure you understand the problem you are trying to tackle, or, at least have a useful overall appreciation of the task before you. As the problems get more challenging, your initial understanding may not be as deep as you would like, but you need to know enough to at least make some sort of start. Next, make sure the problem you chose is likely to be solvable in the domain you choose to approach it. An example of what I mean is that sending all of your program's output to a textual command line interface may not prove very fruitful if you are trying to write a graphical dungeons and dragon game. However, even here there might be possibilities. Some people use to do very interesting ASCII art and graphical like images with those non-alphanumeric ASCII characters. But more than likely you will not be pleased (at least nowadays) creating a final product that runs in the command line. But note that you could fully develop the logic of the adventure itself in this environment and once you had that done, design the GUI/graphical/audio elements. Next, when initially approaching the design of the program, don't get hung up on details! When I used to teach math and physics classes, even at the university level students would get so hung up on the details of the problem as stated, that they could not see the underlying important principles necessary for the problem's solution. Word problems of any kind is a classic example of this. I could window dress up problems that are all solvable using the simple formula distance equals speed multiplied by time, and students would get so confused by the details of the window dressing that they could not see that problems one through a gazillion and one were all solved using this same underlying formula. I think a similar thing happens with learning a programming language and the programming process. Especially in the area of technical vocabulary. Instead of focusing on what program statements, functions, whatever actually DO and cannot do, the student is awash in a sea of technical verbosity. Computer science people, in my personal experience, often have a difficult time saying things SIMPLY. When I was in college I mostly hung out with computer science types, and they were forever speaking in technical acronyms, technical slang, ..., and sometimes even technical profanity! But even though such things as subroutines, functions, methods, and perhaps other names may be precisely defined in somewhat different ways (and even might mean different things to a greater or lesser extent in different programming languages), what they all DO is usually quite similar. Perhaps more importantly when tackling a challenging problem it is easy to get lost in thinking about implementation details that you will have to eventually worry about. But save that sort of worry for later. I like to brainstorm on paper what my expectations are for a program, the overall functionality, what might be "nice" to do, what should be essential to do, ... I try to decompose the overall problem into obvious subunits and might even break these down as well. Then I consider what I already know how to do and how it relates to my brainstorming. An example from circa 1977: I was recently introduced to backgammon and was trying to get as good as possible at it. At the same time I found out about a new room in the computer science building called the software lab. I got permission to hang out there and noticed that they had a relatively new minicomputer that had an experimental monitor hooked up to it. Bear in mind that the most advanced visual display interaction I had had to date was with an IBM Selectric typewriter that was hooked up to a mainframe. You could type in your commands and the mainframe's response would type out on paper before your eyes. But this was even better! A large CRT that supposed had the ability to display free-form graphical images, albeit only in a single color. No one really knew how to use it to generate graphics, but it had a manual. After glancing through the manual I thought I would try to write a backgammon program. I felt sure I could display a suitable monocolor 2D backgammon board once I learned how to programmatically access the full functions of the monitor, but that was mostly studying the manual. However, I did not know how to make the program logic that would make the computer play a strong game of backgammon. So I delayed that part and started in on what I had an idea of how to do. Later, after reading plenty of backgammon books, I started to have ideas of how to do the actual game logic, especially some mathematically based ideas on proper use of the doubling cube. In the end I had a program that would consistently beat most of the people that played it. Disclaimer: Most of these people were poor backgammon players! So tackle that which you have some idea on how to proceed first. In general, when the going gets rough, work on the stuff you see a way of tackling and temporarily skip the stuff that has you scratching your head. Or if you are really stuck, work on a piece of a piece (... of a piece). For instance if you are working on something that will require a randomizer or some sort, work on that and expand on that seed as much as possible. Find another little piece. Solve that problem. As you do this you will often find that the stuff you learned from doing the small pieces gives you ideas for approaching the true head scratchers. And as you get more and more pieces solved, ways of assembling them into bigger parts of the developing program will occur to you. Some other ideas on approaching the small pieces: Say you know you will have to repeatedly do something. That should immediately suggest to you that you will need some type of looping or iteration structure even if you have, at this point, never heard of a while, for or whatever loop. Once you realize this need, investigate your chosen programming language to see if they have something similar to what you realize you need. Or you realize you need some way to retain the game's settings between playing sessions. That means you need to somehow store things in files. Ergo, read up on files! Even if you have no clue what you actually need to write to permanent storage, go ahead and design simple functions to read and write files. As you do this you will probably realize some little things that you can add to these functions that reflect what the game is shaping up to be like. And as you learn more about how to manipulate files, new pieces will start falling into place for this portion of your program. Have to make choices? Then what kind of structures does your language provide for doing this? If-then-elif-else? I don't know how you are, but I am like a dog gnawing on a bone until I finally crack it, a little piece at a time, until I get to the marrow. If you are doing all of the above you will generate errors, exceptions, whatever in profusion. Treat these as learning opportunities to really dig into the meat, and, finally, DETAILS of your chosen programming language. The smallest, itty bitty thing MATTERS! Computers are so stupid. They try to do EXACTLY what you type, however error ridden. As an example, yesterday I copied a snippet of someone's code that had the potential to be helpful on my current project at work. Even though I had what should have been a fully functional code snippet that for the life of me I could not see any reason why it shouldn't run, it continued to give me the same error message that made absolutely no sense to me. It gave me a syntax error at a pair of double quotes. But every time I typed in exactly the same code manually into the interpreter, it ran. I was about to pull out what remaining hair I had on top! Finally, I COPIED AND PASTED the code snippet into the interpreter. It failed with exactly the same error message! What the [insert profane word here]! I then got real close to my monitor and really looked at those quotes. They were pointing in slightly different directions! Once I replaced them with my keyboard's normal double quotes the problem vanished. So what to do when you can't eliminate the error message? First, believe (mostly) what it says. I say mostly because it may not pinpoint the actual location of the error. For instance you may have forgotten to close quotes, parentheses, etc. somewhere earlier in your code and the checker may not realize the actual point of the error. As many have said, try to isolate the location of the problem with judiciously inserted print statements. Print out whatever variable values that might help you understand what is going on. Comment out areas of code and see if you can isolate it that way. Maybe even get a non-programmer to read your code for obvious typos that you just are not seeing. You know, like in English class when you just cannot see the misspelled word? Don't forget the more insidious logic errors. If you understand what you are trying to do, then you should know what you should get for various inputs, situations, etc. Test these expectations! Finally (I am finally getting tired of typing! And supper is done!!) when you think you have it done and working, examine your ASSUMPTIONS. What if the user does something different from what you intended? What if that file you are expecting isn't actually there? Etc. I hope I did not waste your time with this long post. As I said, my programming skills are quite modest. But this is how I try to approach things. Keep at it! Persistence wins out in the end!1 Cheers! boB From davea at davea.name Sun Dec 21 03:30:47 2014 From: davea at davea.name (Dave Angel) Date: Sat, 20 Dec 2014 21:30:47 -0500 Subject: [Tutor] Learning to program, not code. In-Reply-To: References: <549422DF.3050808@davea.name> Message-ID: <549630D7.2050903@davea.name> On 12/20/2014 08:16 PM, Brandon Dorsey wrote: >> >> I'm 28 years old, currently unemployed and not in school until fall of >> 2015 as a junior. I picked up python a little under a year ago, with the >> hopes that I could make a career out of programming - when I finish school >> that is. So, as of right now you could say it's a hobby, however, I >> figured that I would jump the gun and learn it now, on my own, with widely >> available resources we have today. Currently, I have a solid foundation of >> how data structures and how OOP works, but the problem lies within having >> analysis paralysis. I have a tendency to over analyze everything, and with >> programming - as we all know - there are a million ways to accomplish the >> same task. >> Why do you quote your own remarks, instead of just writing them? And why were they at the beginning of the message instead of following the context you were actually quoting? Now that I've figured out which part of the message was yours, I can respond. You don't say what your major is, nor what you have been actually doing to develop your skill at Python. My guess is that you're picking too-ambitious tasks, and that you have not actually worked through the beginning problems of whatever tutorial you've worked on. There's a reason my college required homework to be done and turned in, in most classes, at the more elementary levels. It's easy to think you know more than you do, I don't say that to offend, but to try to help you get perspective. If you've been jumping ahead, perhaps that's the best way for you to learn, but it's not for everyone. Pick a simpler problem, and fully chase it down. Do NOT try to get the perfect algorithm, try to get a complete working implementation of the entire problem. Analysis is fine, but start by decomposing the problem into pieces you can solve exactly, then plug them together to make up a complete program. And if you've picked the right boundaries for the decomposition, you could then go back and optimize individual pieces, in various ways. But for many problems, maybe even most, it just doesn't matter. In real life, you'll find that there are just a few places where things have to be reworked for performance, and until you've got a lot of experience, you'll always guess wrong what those will be. Once you have a lot of experience, you'll merely usually guess wrong. That's why it's important to solve the whole problem before trying much to optimize any particular piece. If you think there are a million ways to solve a task, then the task is too big to consider as a whole. Decompose it into pieces small enough that there are only a dozen for any one of the subtasks. Then pick one of the dozen, and get it done. Do it in such a way that it can be described on its own, tested on its own, and maybe even shipped on its own. So enough for generalities. After you've picked a task, and divided it into subtasks, try to solve one of those subtasks, and show us what you're trying, what you've done, and what you don't like about it. You'll get lots of advice, some of it very good. Just remember that many of us love to prematurely optimize (it's fun),, and you're at the wrong stage to be doing that. So go ahead and write loops instead of list comprehensions. Worry more about whether the variable names make sense, whether the functions are trying to do too much, and whether you're making too many untested assumptions about the outside world. -- DaveA From ben+python at benfinney.id.au Sun Dec 21 04:01:19 2014 From: ben+python at benfinney.id.au (Ben Finney) Date: Sun, 21 Dec 2014 14:01:19 +1100 Subject: [Tutor] Posting and quoting style (was: Learning to program, not code.) References: <549422DF.3050808@davea.name> <549630D7.2050903@davea.name> Message-ID: <85y4q11zb4.fsf_-_@benfinney.id.au> Dave Angel writes: > Why do you quote your own remarks, instead of just writing them? And > why were they at the beginning of the message instead of following the > context you were actually quoting? As Dave alludes to, discussions are much clearer to follow when responses are composed in ?interleaved style?; please follow it . Your email client might make this conventional quoting and responding style difficult. If so, agitate with the vendor of that program to support the conventional style more easily; and, until then, switch to a better client program. -- \ ?To punish me for my contempt of authority, Fate has made me an | `\ authority myself.? ?Albert Einstein, 1930-09-18 | _o__) | Ben Finney From brandontdr at gmail.com Sun Dec 21 02:16:37 2014 From: brandontdr at gmail.com (Brandon Dorsey) Date: Sat, 20 Dec 2014 20:16:37 -0500 Subject: [Tutor] Learning to program, not code. In-Reply-To: <549422DF.3050808@davea.name> References: <549422DF.3050808@davea.name> Message-ID: > > I'm 28 years old, currently unemployed and not in school until fall of > 2015 as a junior. I picked up python a little under a year ago, with the > hopes that I could make a career out of programming - when I finish school > that is. So, as of right now you could say it's a hobby, however, I > figured that I would jump the gun and learn it now, on my own, with widely > available resources we have today. Currently, I have a solid foundation of > how data structures and how OOP works, but the problem lies within having > analysis paralysis. I have a tendency to over analyze everything, and with > programming - as we all know - there are a million ways to accomplish the > same task. > On Fri, Dec 19, 2014 at 8:06 AM, Dave Angel wrote: > On 12/18/2014 09:09 PM, Brandon Dorsey wrote: > >> Hello All, >> >> Programming has always been a passion of mine, >> > > A great start. Can you tell us a little more about yourself? Is Python > the first language you've tried, or are you successful at other languages? > Are you in school, at what level, do you already have some other career and > this is a hobby? Do you have some hobbies that programming might synergize > with? > > > however, I'm frequently > >> frustrated at >> >> simple fact that I've been learning python for 8 months, and I have yet to >> start, and finish, a simple >> >> project. >> > > How are you learning python? Are you in a class, did you buy a book, > download a tutorial, what? > > I find difficult to not only visualize the execution, >> > > There are tools that may help with that, but it's not clear to me whether > that would really help. If you want to play, you could look at: > > ttp://www.pythontutor.com/visualize.html#mode=edit > > but to figure out when and where to >> >> use data structure 'x'. >> > > Alan gave some brief descriptions. You should realize that those are just > the particular collections that are in the builtin section of python. > There are many more in the standard library, MANY more out on the internet > (eg. pypi), and many more in your head, just aching to come out. > > Any suggestions on how to approach programming > >> from a different angle? >> > > That's a great perspective. > > We're now drowning in a sea of riches, information on any topic. But in > most cases, you have to be introduced to a topic systematically, with > controlled flow, in order to understand what the fancier concepts are all > about. When I "started" programming in 1966, it was with a borrowed > Fortran book over spring break. I wrote a number of programs on sheets of > paper, but had no machine to execute them on. (I also expect there were > more errors than useful statements, but I didn't know anything about that > either) I went on a field trip to the nearest computer, which was at > Yale. I got to see the actual machinery through some large windows, but > didn't have a chance to run anything till almost a year later, at my own > college. Even then, freshmen weren't taught anything about them, and I had > to learn from another student how to submit punched cards to the computer. > And how to run jobs without having a legitimate account. > > Frequently when people develop an interest in programming now, it's in > order to write a game, design a website, or to solve some fairly complex > problem. If they then try to research the tools, they get overwhelmed with > the possibilities. And without a narrower focus, they never get that > satisfaction that comes with finishing a project. > > Without knowing anything at all about you really, I'd suggest you either > take a course, or really *do* a tutorial. Many people just read a book (or > site) about the subject, and don't actually try the exercises. In my case > it was excusable, since I didn't have the several million dollars necessary > to buy a computer, but the principle still holds. Start small, and > systematically build up your abilities. If you're disciplined enough to do > that on your own, there are many Python tutorials that you can download. > And when you get stuck, you'll have a manageable problem that somebody can > help with. > > If you've done all that, and you're still stuck, then be much more > specific in your question here. Pick a project (or exercise, or > assignment) that you've started working on, and describe the following: > > 1) python version and OS version > 2) project description > 3) code fragment that shows your present difficulty > 4) what happens, and what you hoped would happen > 5) any error messages (show the full stack trace) you get > 6) meaningful subject line > > Python is a fabulous language for learning. You can get feedback a few > seconds after you run the code, and you can make a change and try again in > under a minute. I worked in one environment where the turnaround for a > compile was about a day and a half. And in another where the compile of > the complete application was done only once a week, and making it was a > half-time job for the build-master. > > I've also worked in environments where I had to build my own programming > tools, starting with a text editor. And in environments where we entered > the code in hex. And generating the hex was a pencil/paper exercise. > Looseleaf notebook was the source code. > > > > -- > DaveA > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor > From fomcl at yahoo.com Sun Dec 21 10:21:47 2014 From: fomcl at yahoo.com (Albert-Jan Roskam) Date: Sun, 21 Dec 2014 01:21:47 -0800 Subject: [Tutor] Learning to program, not code. Message-ID: <1419153707.82808.BPMail_high_carrier@web163804.mail.gq1.yahoo.com> ---------------------------- On Sun, Dec 21, 2014 3:30 AM CET Dave Angel wrote: >On 12/20/2014 08:16 PM, Brandon Dorsey wrote: >> >> I'm 28 years old, currently unemployed and not in school until fall of >> 2015 as a junior. I picked up python a little under a year ago, with the >> hopes that I could make a career out of programming - when I finish school >> that is. So, as of right now you could say it's a hobby, however, I >> figured that I would jump the gun and learn it now, on my own, with widely >> available resources we have today. Currently, I have a solid foundation of >> how data structures and how OOP works, but the problem lies within having >> analysis paralysis. I have a tendency to over analyze everything, and with >> programming - as we all know - there are a million ways to accomplish the >> same task. >> > >Why do you quote your own remarks, instead of just writing them? And why were they at the beginning of the message instead of following the context you were actually quoting? > >Now that I've figured out which part of the message was yours, I can respond. > >You don't say what your major is, nor what you have been actually doing to develop your skill at Python. My guess is that you're picking too-ambitious tasks, and that you have not actually worked through the beginning problems of whatever tutorial you've worked on. There's a reason my college required homework to be done and turned in, in most classes, at the more elementary levels. > >It's easy to think you know more than you do, I don't say that to offend, but to try to help you get perspective. If you've been jumping ahead, perhaps that's the best way for you to learn, but it's not for everyone. > >Pick a simpler problem, and fully chase it down. Do NOT try to get the perfect algorithm, try to get a complete working implementation of the entire problem. Analysis is fine, but start by decomposing the problem into pieces you can solve exactly, then plug them together to make up a complete program. > >And if you've picked the right boundaries for the decomposition, you could then go back and optimize individual pieces, in various ways. But for many problems, maybe even most, it just doesn't matter. In real life, you'll find that there are just a few places where things have to be reworked for performance, and until you've got a lot of experience, you'll always guess wrong what those will be. Once you have a lot of experience, you'll merely usually guess wrong. That's why it's important to solve the whole problem before trying much to optimize any particular piece. > >If you think there are a million ways to solve a task, then the task is too big to consider as a whole. Decompose it into pieces small enough that there are only a dozen for any one of the subtasks. Then pick one of the dozen, and get it done. Do it in such a way that it can be described on its own, tested on its own, and maybe even shipped on its own. Don't postpone writing unittests (don't use doctest). They really give you focus and confidence (peace of mind!). If you also use version control, you can automatically run all tests before each commit. >So enough for generalities. After you've picked a task, and divided it into subtasks, try to solve one of those subtasks, and show us what you're trying, what you've done, and what you don't like about it. > >You'll get lots of advice, some of it very good. Just remember that many of us love to prematurely optimize (it's fun),, and you're at the wrong stage to be doing that. So go ahead and write loops instead of list comprehensions. Worry more about whether the variable names make sense, whether the functions are trying to do too much, and whether you're making too many untested assumptions about the outside world. > >-- DaveA >_______________________________________________ >Tutor maillist - Tutor at python.org >To unsubscribe or change subscription options: >https://mail.python.org/mailman/listinfo/tutor From ben+python at benfinney.id.au Sun Dec 21 11:15:43 2014 From: ben+python at benfinney.id.au (Ben Finney) Date: Sun, 21 Dec 2014 21:15:43 +1100 Subject: [Tutor] Learning to program, not code. References: <1419153707.82808.BPMail_high_carrier@web163804.mail.gq1.yahoo.com> Message-ID: <85tx0p1f74.fsf@benfinney.id.au> Albert-Jan Roskam writes: > Don't postpone writing unittests (don't use doctest). They really give > you focus and confidence (peace of mind!). Excellent advice. Write unit tests as a way of documenting what you want the function to do, and also to document what the function did wrong in that bug you just found :-) (Although, I'd modify the above to: do use doctest, but *not* for unit tests. Use doctest only for testing code examples you already have in your documentation, it's good for that.) > If you also use version control, you can automatically run all tests > before each commit. There's no ?if? there. Use a distributed version control system (Mercurial is good and is written in Python), and always make small easily-described commits while working. -- \ ?Visitors are expected to complain at the office between the | `\ hours of 9 and 11 a.m. daily.? ?hotel, Athens | _o__) | Ben Finney From hanzer at riseup.net Sun Dec 21 19:38:29 2014 From: hanzer at riseup.net (Adam Jensen) Date: Sun, 21 Dec 2014 13:38:29 -0500 Subject: [Tutor] Learning to program, not code. In-Reply-To: <85tx0p1f74.fsf@benfinney.id.au> References: <1419153707.82808.BPMail_high_carrier@web163804.mail.gq1.yahoo.com> <85tx0p1f74.fsf@benfinney.id.au> Message-ID: <20141221133829.7270dd2c72414a63d858aefb@riseup.net> On Sun, 21 Dec 2014 21:15:43 +1100 Ben Finney wrote: > Use a distributed version control system > (Mercurial is good and is written in Python) I'm beginning to really appreciate [fossil](http://fossil-scm.org/). Re: "Learning to program, not code". Is that like learning to think rather than (or before) learning to express your thoughts? Hmm, I'll have to think about that... From alan.gauld at btinternet.com Sun Dec 21 19:59:17 2014 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 21 Dec 2014 18:59:17 +0000 Subject: [Tutor] Learning to program, not code. In-Reply-To: <1419153707.82808.BPMail_high_carrier@web163804.mail.gq1.yahoo.com> References: <1419153707.82808.BPMail_high_carrier@web163804.mail.gq1.yahoo.com> Message-ID: On 21/12/14 09:21, Albert-Jan Roskam wrote: > Don't postpone writing unittests (don't use doctest). But do wait till you know what you will be testing. You can't write a unit test until you have a unit in mind. The OP seems to be struggling to figure out what units he needs. Once he has done that, unit testing can be included as part of the normal discipline of writing code. But you need to know the structure before you get to that stage. But even with system testing the first challenge is still to understand what it is you are trying to build. Until you understand the problem you can't deliver a solution nor can you test if the solution is correct. > They really give you focus and confidence (peace of mind!). Often misplaced! Remember that unit tests only test units, you also need system tests and very few unit testing frameworks are any good at that. And especially where GUI front ends are used. There are UI testing frameworks and they help, but the real challenges in testing any system are the test data build and the timing and synchronising of the tests. Of course, system testing should never, ideally, be done by the programmers who wrote the code, but "ideally" often isn't possible... > If you also use version control, you can automatically > run all tests before each commit. In theory yes, but if it's a big system that may not be practical. retesting 10,000+ files takes a long time even on modern computers. Now I doubt if many readers of this list are working on 10000 file codebases but you need to bear in mind that some day you may be and these *rules* don't always apply. I've worked on systems where running a full build/test cycle took 3 to 4 days. It was usually done over the weekend and Mondays and Tuesdays were reserved for bug fixing. The aim being to have a new working system every Wednesday morning. -- 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 From robertvstepp at gmail.com Mon Dec 22 03:00:57 2014 From: robertvstepp at gmail.com (boB Stepp) Date: Sun, 21 Dec 2014 20:00:57 -0600 Subject: [Tutor] Fwd: Re: Learning to program, not code. [LONG RESPONSE!] In-Reply-To: <20141222012520.GE2530@gmail.com> References: <20141222012520.GE2530@gmail.com> Message-ID: It appears that Michael only sent this to me when I think he meant to send it to the list... ---------- Forwarded message ---------- From: "Michael Shiloh" Date: Dec 21, 2014 7:25 PM Subject: Re: [Tutor] Learning to program, not code. [LONG RESPONSE!] To: "boB Stepp" Cc: > On Fri, Dec 19, 2014 at 08:12:14PM -0600, boB Stepp wrote: > > On Thu, Dec 18, 2014 at 8:09 PM, Brandon Dorsey wrote: > > > > > > Hello All, > > > > > > simple fact that I've been learning python for 8 months, and I have yet to > > > start, and finish, a simpleproject. I find difficult to not only visualize > > > the execution, but to figure out when and where to > > > use data structure 'x'. Any suggestions on how to approach programming > > > from a different angle? > > > > I am going to take a stab at this. Perhaps the perspective from a > > non-professional in the world of computer programming might be of > > help. > > Very interesting question, Brandon, and many excellent answers. I like the > comments that Bob made in particular. > > I have two modest suggestions: > > 1) Pretend you are explaining to someone else how to solve the problem (a pet > or stuffed animal would work as well). Pretend the person you're telling knows > very little so that you have to explain in great detail. I find this helps > sometimes, but not always. > > 2) Bob made the wonderful suggestion that if the entire problem seems > overwhelming, but you can see how to work on some small part of it, start with > that. I would add that if some small part of it interests you in particular, > start with that first. If you are excited or motivated, that will help you > push through the bumps in the road. > > I often do the part I'm most curious about first. > > > Good luck, > Michael From juan0christian at gmail.com Mon Dec 22 13:53:33 2014 From: juan0christian at gmail.com (Juan Christian) Date: Mon, 22 Dec 2014 12:53:33 +0000 Subject: [Tutor] How to change default path output of 'logging'? Message-ID: I have a 'logging' on my code using: import logging < ... > logging.basicConfig(filename="bumpr.log", level=logging.INFO) < ... > The thing is that the default location of this output when running via Windows Task Scheduler is 'C:/Windows/System32'. Is there a way to change the location of the output of this module? I want it to output where my 'main.py' is. From zachary.ware+pytut at gmail.com Mon Dec 22 16:20:21 2014 From: zachary.ware+pytut at gmail.com (Zachary Ware) Date: Mon, 22 Dec 2014 09:20:21 -0600 Subject: [Tutor] How to change default path output of 'logging'? In-Reply-To: References: Message-ID: On Monday, December 22, 2014, Juan Christian > wrote: > I have a 'logging' on my code using: > > import logging > < ... > > logging.basicConfig(filename="bumpr.log", level=logging.INFO) > < ... > > > The thing is that the default location of this output when running via > Windows Task Scheduler is 'C:/Windows/System32'. > > Is there a way to change the location of the output of this module? I want > it to output where my 'main.py' is. > That location is not a function of logging, it's a function of running via Windows Task Scheduler, which apparently starts the program with a current directory of C:\Windows\System32. The solution is to give logging an absolute path for the output file (which you can base of off __file__, something like """os.path.join(os.path.dirname(__file__), "bumpr.log")""") . Hope this helps, -- Zach -- Sent from Gmail Mobile From davea at davea.name Mon Dec 22 16:34:59 2014 From: davea at davea.name (Dave Angel) Date: Mon, 22 Dec 2014 10:34:59 -0500 Subject: [Tutor] How to change default path output of 'logging'? In-Reply-To: References: Message-ID: <54983A23.8040001@davea.name> On 12/22/2014 07:53 AM, Juan Christian wrote: > I have a 'logging' on my code using: > > import logging > < ... > > logging.basicConfig(filename="bumpr.log", level=logging.INFO) > < ... > > > The thing is that the default location of this output when running via > Windows Task Scheduler is 'C:/Windows/System32'. You want it in a different file, specify a different file. For example, logging.basicConfig(filename="F:/data/logging_info/bumpr.log", level=logging.INFO) > > Is there a way to change the location of the output of this module? I want > it to output where my 'main.py' is. No idea what part main.py plays to your code. If it's imported, then you could use main.__file__ to get the full pathname to it. Then use os.path.dirname() to get the directory. Then use os.path.join() to combine that with "bumpr.log". More likely, this is your script. So if you're trying to get the filename from the script, you just use __file__ And if that doesn't show up as an absolute path, use os.path.abspath. i couldn't test that part, since I don't use Windows, and can't play with the Windows Task Scheduler. -- DaveA From juan0christian at gmail.com Mon Dec 22 17:41:09 2014 From: juan0christian at gmail.com (Juan Christian) Date: Mon, 22 Dec 2014 16:41:09 +0000 Subject: [Tutor] How to change default path output of 'logging'? References: <54983A23.8040001@davea.name> Message-ID: On Mon Dec 22 2014 at 1:35:44 PM Dave Angel wrote: > > No idea what part main.py plays to your code. If it's imported, then > you could use main.__file__ to get the full pathname to it. Then use > os.path.dirname() to get the directory. Then use os.path.join() to > combine that with "bumpr.log". > > More likely, this is your script. So if you're trying to get the > filename from the script, you just use > __file__ > > And if that doesn't show up as an absolute path, use os.path.abspath. i > couldn't test that part, since I don't use Windows, and can't play with > the Windows Task Scheduler. > Thanks guys, it worked like a charm. str(os.path.abspath(__file__)).replace('main.py', '') So I get the full-path of my main dir where main.py is and all the other modules/packages too, no matter if I'm on OSX/Win/Linux. From davea at davea.name Mon Dec 22 17:57:00 2014 From: davea at davea.name (Dave Angel) Date: Mon, 22 Dec 2014 11:57:00 -0500 Subject: [Tutor] How to change default path output of 'logging'? In-Reply-To: References: <54983A23.8040001@davea.name> Message-ID: <54984D5C.7030900@davea.name> On 12/22/2014 11:41 AM, Juan Christian wrote: > > str(os.path.abspath(__file__)).replace('main.py', '') > > So I get the full-path of my main dir where main.py is and all the other > modules/packages too, no matter if I'm on OSX/Win/Linux. That's not the best way to get the directory path for a file. You should use os.path.dirname(). That way if the basename changes from main.py to something else (like main.pyc, or main.pyw, or usefulcode.py), it'll still work. It fixes other problems also, that are less likely to occur. os.path.dirname(os.path.abspath(__file__)) should do it for you. And that means that you want something like: filename=os.path.join(os.path.dirname(os.path.abspath(__file__)), "bumpr.log") (untested) -- DaveA From vishwas_pathak at persistent.com Mon Dec 22 12:27:01 2014 From: vishwas_pathak at persistent.com (Vishwas Pathak) Date: Mon, 22 Dec 2014 11:27:01 +0000 Subject: [Tutor] My Query - How to implement multi threading with remote execution capability in python to achieve parallel processing Message-ID: Hi, I am working building on developing an automation framework for my product . I need to implement multi-threading having a pool of thread where each thread will be executed different set of test cases on remote windows machines. Consider following example - Say I have two windows OS test machines and I want to execute test cases number 1 to 5 on test machine 1 and test cases number 6 to 10 on test machine 2. I will create a thread pool of 2 threads and thread 1 will connect to test machine 1 and execute the test cases 1 to 5 and thread 2 will connect to test machine 2 and execute the test cases 6 to 10. Also each thread will generate the log files separately printing execution details for respective test machine which is assigned to this particular thread. Please provide your inputs in designing this mechanism. Many Thanks !!!!!!!!!!!!!! Regards, Vishwas Pathak DISCLAIMER ========== This e-mail may contain privileged and confidential information which is the property of Persistent Systems Ltd. It is intended only for the use of the individual or entity to which it is addressed. If you are not the intended recipient, you are not authorized to read, retain, copy, print, distribute or use this message. If you have received this communication in error, please notify the sender and delete all copies of this message. Persistent Systems Ltd. does not accept any liability for virus infected mails. From dyoo at hashcollision.org Mon Dec 22 21:16:24 2014 From: dyoo at hashcollision.org (Danny Yoo) Date: Mon, 22 Dec 2014 12:16:24 -0800 Subject: [Tutor] My Query - How to implement multi threading with remote execution capability in python to achieve parallel processing In-Reply-To: References: Message-ID: On Dec 22, 2014 10:57 AM, "Vishwas Pathak" wrote: > > Hi, > > I am working building on developing an automation framework for my product . I need to implement multi-threading having a pool of thread where each thread will be executed different set of test cases on remote windows machines. Apologies, but this question is definitely out of bounds for Python-tutor. This mailing list is for beginners who are learning basic programming: your question would be more suited to an advanced forum, such as the main Python list. Try asking there instead. Good luck. From wolfrage8765 at gmail.com Mon Dec 22 21:36:55 2014 From: wolfrage8765 at gmail.com (wolfrage8765 at gmail.com) Date: Mon, 22 Dec 2014 15:36:55 -0500 Subject: [Tutor] My Query - How to implement multi threading with remote execution capability in python to achieve parallel processing In-Reply-To: References: Message-ID: On Mon, Dec 22, 2014 at 6:27 AM, Vishwas Pathak < vishwas_pathak at persistent.com> wrote: Your Disclaimer alone means that I can not respond to this question, or else it would apparently become the property of Persistent Systems Ltd. I prefer Open Source to closed source... good day. > > > DISCLAIMER > ========== > This e-mail may contain privileged and confidential information which is > the property of Persistent Systems Ltd. It is intended only for the use of > the individual or entity to which it is addressed. If you are not the > intended recipient, you are not authorized to read, retain, copy, print, > distribute or use this message. If you have received this communication in > error, please notify the sender and delete all copies of this message. > Persistent Systems Ltd. does not accept any liability for virus infected > mails. > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor > From akleider at sonic.net Tue Dec 23 03:58:16 2014 From: akleider at sonic.net (Alex Kleider) Date: Mon, 22 Dec 2014 18:58:16 -0800 Subject: [Tutor] My Query - How to implement multi threading with remote execution capability in python to achieve parallel processing Message-ID: <201412230258.sBN2wLZD018955@d.mail.sonic.net> On Dec 22, 2014 12:36 PM, wolfrage8765 at gmail.com wrote: > > On Mon, Dec 22, 2014 at 6:27 AM, Vishwas Pathak < > vishwas_pathak at persistent.com> wrote: > Your Disclaimer alone means that I can not respond to this question, or > else it would apparently become the property of Persistent Systems Ltd. I > prefer Open Source to closed source... good day. > Although I also find the disclaimer somewhat obnoxious and also prefer open source, I think you are mistaken in your conclusion about exactly what the disclaimer says. > > > > > > DISCLAIMER > > ========== > > This e-mail may contain privileged and confidential information which is > > the property of Persistent Systems Ltd. It is intended only for the use of > > the individual or entity to which it is addressed. If you are not the > > intended recipient, you are not authorized to read, retain, copy, print, > > distribute or use this message. If you have received this communication in > > error, please notify the sender and delete all copies of this message. > > Persistent Systems Ltd. does not accept any liability for virus infected > > mails. > > > > _______________________________________________ > > Tutor maillist? -? Tutor at python.org > > To unsubscribe or change subscription options: > > https://mail.python.org/mailman/listinfo/tutor > > > _______________________________________________ > Tutor maillist? -? Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor > From davea at davea.name Tue Dec 23 04:21:20 2014 From: davea at davea.name (Dave Angel) Date: Mon, 22 Dec 2014 22:21:20 -0500 Subject: [Tutor] My Query - How to implement multi threading with remote execution capability in python to achieve parallel processing In-Reply-To: <201412230258.sBN2wLZD018955@d.mail.sonic.net> References: <201412230258.sBN2wLZD018955@d.mail.sonic.net> Message-ID: <5498DFB0.6010903@davea.name> On 12/22/2014 09:58 PM, Alex Kleider wrote: > > On Dec 22, 2014 12:36 PM, wolfrage8765 at gmail.com wrote: >> >> On Mon, Dec 22, 2014 at 6:27 AM, Vishwas Pathak < >> vishwas_pathak at persistent.com> wrote: >> Your Disclaimer alone means that I can not respond to this question, or >> else it would apparently become the property of Persistent Systems Ltd. I >> prefer Open Source to closed source... good day. >> > > Although I also find the disclaimer somewhat obnoxious and also prefer open source, I think you are mistaken in your conclusion about exactly what the disclaimer says. > You're right that he's mistaken. it's even worse. The disclaimer claims I'm not permitted to read such messages, nor save them on my machine. So I'm considering writing a filter to try to comply by deleting them before they accidentally come before my eyes. -- DaveA From wolfrage8765 at gmail.com Tue Dec 23 04:55:18 2014 From: wolfrage8765 at gmail.com (wolfrage8765 at gmail.com) Date: Mon, 22 Dec 2014 22:55:18 -0500 Subject: [Tutor] My Query - How to implement multi threading with remote execution capability in python to achieve parallel processing In-Reply-To: <5498DFB0.6010903@davea.name> References: <201412230258.sBN2wLZD018955@d.mail.sonic.net> <5498DFB0.6010903@davea.name> Message-ID: On Mon, Dec 22, 2014 at 10:21 PM, Dave Angel wrote: > On 12/22/2014 09:58 PM, Alex Kleider wrote: > >> >> On Dec 22, 2014 12:36 PM, wolfrage8765 at gmail.com wrote: >> >>> >>> On Mon, Dec 22, 2014 at 6:27 AM, Vishwas Pathak < >>> vishwas_pathak at persistent.com> wrote: >>> Your Disclaimer alone means that I can not respond to this question, or >>> else it would apparently become the property of Persistent Systems Ltd. I >>> prefer Open Source to closed source... good day. >>> >>> >> Although I also find the disclaimer somewhat obnoxious and also prefer >> open source, I think you are mistaken in your conclusion about exactly what >> the disclaimer says. >> >> > You're right that he's mistaken. it's even worse. The disclaimer claims > I'm not permitted to read such messages, nor save them on my machine. So > I'm considering writing a filter to try to comply by deleting them before > they accidentally come before my eyes. > > I had sent this just to Alex, but since reading your reply (Dave) I figured I should just post it too. Sent to Alex: You are completely correct. I more so felt like the OP wanted us to help him with something that is clearly at a business level with the expectation that it would disappear into his company. But then again I am placing words into his mouth which clearly were not said. Although who is the authorized party to read and retain his emails, it seems ambiguous when he is sending it to a public mailing list? Sorry for over generalizing and being overly sarcastic. From alan.gauld at btinternet.com Tue Dec 23 10:53:36 2014 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 23 Dec 2014 09:53:36 +0000 Subject: [Tutor] My Query - How to implement multi threading with remote execution capability in python to achieve parallel processing In-Reply-To: <201412230258.sBN2wLZD018955@d.mail.sonic.net> References: <201412230258.sBN2wLZD018955@d.mail.sonic.net> Message-ID: On 23/12/14 02:58, Alex Kleider wrote: > > On Dec 22, 2014 12:36 PM, wolfrage8765 at gmail.com wrote: >> >> On Mon, Dec 22, 2014 at 6:27 AM, Vishwas Pathak < >> vishwas_pathak at persistent.com> wrote: >> Your Disclaimer alone means that I can not respond to this question, or >> else it would apparently become the property of Persistent Systems Ltd. I >> prefer Open Source to closed source... good day. I don't see where you get that from? The disclaimer follows a pretty standard corporate pattern that simply tries (usually unsuccessfully) to protect corporate IP. >>> DISCLAIMER >>> ========== >>> This e-mail may contain privileged and confidential information which is >>> the property of Persistent Systems Ltd. It may. It may not. This particular email apparently does not. Nothing unusual there. It's vague to the point of being useless but it does not claim ownership of anyone's IP but their own. >>> It is intended only for the use of the individual or entity to which >>> it is addressed. So in this case the mailing list is the entity. But the claim is true of most emails. We expect them to go to the entity to which we send them. We may not want them shared publicly or widely. >>> If you are not the >>> intended recipient, you are not authorized to read, retain, copy, print, >>> distribute or use this message. Again that's pretty general. You are not authorized by the sender to read the message. It doesn't prevent you from doing so but they aren't authorizing it and any action an unauthorized viewer takes can therefore be challenged in court. That's all it means, they have the option of challenging. It's akin to a copyright statement. But since the list members are part of the entity addressed it doesn't apply to us in this case. >>> If you have received this communication in >>> error, please notify the sender and delete all copies of this message. Again a reasonable request since it potentially implies a security issue for the corporation. >>> Persistent Systems Ltd. does not accept any liability for virus infected >>> mails. This is the only bit that is not reasonable. If Persistent Systems sends a virus infected email out it is there responsibility. If their systems are infected they are liable. But I don't see anything too outrageous about the disclaimer. The corporate banner we used to have was equally banal and said much the same stuff. -- 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 From hanzer at riseup.net Tue Dec 23 19:09:39 2014 From: hanzer at riseup.net (Adam Jensen) Date: Tue, 23 Dec 2014 13:09:39 -0500 Subject: [Tutor] My Query - How to implement multi threading with remote execution capability in python to achieve parallel processing In-Reply-To: References: Message-ID: <20141223130939.6f602641ef84774144ef5eb5@riseup.net> This thread is hilarious. Thanks for the chuckle. http://www.ignyte.ms/whitepapers/LayersOf%20HumanValuesInStrategy.pdf http://www.principiadiscordia.com/downloads/04%20Prometheus%20Rising.pdf On Mon, 22 Dec 2014 11:27:01 +0000 Vishwas Pathak wrote: > I am working building on developing an automation framework for my product . I need to implement multi-threading having a pool of thread where each thread will be executed different set of test cases on remote windows machines. Perhaps you could use, scavenge from, or find inspiration in one of these projects? [xdist: pytest distributed testing plugin](http://pytest.org/latest/xdist.html) [distributed-nose](https://pypi.python.org/pypi/distributed-nose/0.1.2) From scoobydoostu at hotmail.com Tue Dec 23 19:27:10 2014 From: scoobydoostu at hotmail.com (stuart kurutac) Date: Tue, 23 Dec 2014 18:27:10 +0000 Subject: [Tutor] print() invalid syntax error Message-ID: Hello all, I'm working my way through the Michael Dawson book "Python Programming for the Absolute Beginner" and I've come across an invalid syntax error on 2 occassoins now. For the life of me I can't see what's wrong. I've checked and re-checked I've typed in the code from the book correctly, I've ran the lines in IDLE and one works but the other doesn't. The first program is: #Pizza Slicer #Demonstrates string slicing word = "pizza" print( """ Slicing 'Cheat Sheet' 0 1 2 3 4 5 +---+---+---+---+---+ | P | i | z | z | a | +---+---+---+---+---+ -5 -4 -3 -2 -1 """ ) print("Enter the beginning and ending index for your slice of 'pizza'.") print("Press the enter key at 'Start' to exit.") start = None while start != "": start = (input("\nStart: ")) if start: start = int(start) finish = (int(input("Finish: ")) print("word[", start, ":", finish, "] is", end=" ") print(word[start:finish]) input("\n\nPress the enter key to exit.") When I run this through the terminal in linux using python3 I get the following: File "pizza_slicer.py", line 32 print("word[", start, ":", finish, "] is", end=" ") ^ SyntaxError: invalid syntax If I type the while loop into IDLE it doesn't produce the error but it doesn't return anything full stop. Now I get teh same sytax error for another program, the lines in question are below (I can include all the code if required): #display one item through an index index = (int(input("\nEnter the index number for an item in inventory: ")) print("At index", index, "is", inventory[index]) Once again, if Ii run this through the terminal I get the following: File "hero's_inventory2.py", line 26 print("At index", index, "is", inventory[index]) ^ SyntaxError: invalid syntax Is this something simple such as a difference with python version syntax? I tried running with version 3.2.3 and the native version (2.7.3) of python and got the same error message at the same point so I didn't think it could be this. I know it's probably something simple I just can't see it. Can anyone help? If you need any more info just let me know. From hanzer at riseup.net Tue Dec 23 21:47:00 2014 From: hanzer at riseup.net (Adam Jensen) Date: Tue, 23 Dec 2014 15:47:00 -0500 Subject: [Tutor] print() invalid syntax error In-Reply-To: References: Message-ID: <20141223154700.862049ff735a0b750382963d@riseup.net> On Tue, 23 Dec 2014 18:27:10 +0000 stuart kurutac wrote: > finish = (int(input("Finish: ")) The parenthesis aren't balanced. I would have written it as: finish = int(input("Finish: ")) but something like this should also work: finish = (int(input("Finish: "))) From alan.gauld at btinternet.com Wed Dec 24 01:16:37 2014 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 24 Dec 2014 00:16:37 +0000 Subject: [Tutor] print() invalid syntax error In-Reply-To: References: Message-ID: On 23/12/14 18:27, stuart kurutac wrote: > Hello all, > > I've come across an invalid syntax error on 2 occassoins now. > For the life of me I can't see what's wrong. > finish = (int(input("Finish: ")) > > > print("word[", start, ":", finish, "] is", end=" ") > When I run this through the terminal in linux using python3 I get the following: > > File "pizza_slicer.py", line 32 > print("word[", start, ":", finish, "] is", end=" ") > ^ > SyntaxError: invalid syntax Adam has told you what is wrong but, for reference, Python points to the "wrong" line because, with the missing parens, it sees your code as: finish = (int(input("Finish: ")) print("word[", .... And its illegal to have a print() immediately after an int() call. So it flags the print statement as illegal. The lesson is that when you get a syntax error thats not obvious check the line or two above as well. Unbalanced quotes or parens/brackets are often the cause. -- 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 From jcgallaher78 at gmail.com Wed Dec 24 14:44:07 2014 From: jcgallaher78 at gmail.com (Jim Gallaher) Date: Wed, 24 Dec 2014 07:44:07 -0600 Subject: [Tutor] print() invalid syntax (Jim Gallaher) In-Reply-To: References: Message-ID: <91CAB963-2084-4618-8E02-AF8B183062C3@gmail.com> > Message: 2 > Date: Tue, 23 Dec 2014 18:27:10 +0000 > From: stuart kurutac > To: "tutor at python.org" > Subject: [Tutor] print() invalid syntax error > Message-ID: > Content-Type: text/plain; charset="iso-8859-1" > > Hello all, > > I'm working my way through the Michael Dawson book "Python Programming for the Absolute Beginner..." > I tried running with version 3.2.3 and the native version (2.7.3) For his book he mentions he uses Python 3. Python 2 might work, but it's not guaranteed. Sincerely Jim Gallaher From wolfrage8765 at gmail.com Wed Dec 24 22:35:06 2014 From: wolfrage8765 at gmail.com (WolfRage) Date: Wed, 24 Dec 2014 16:35:06 -0500 Subject: [Tutor] Making Doubly Linked List with Less Lines of Code. Message-ID: <549B318A.8030909@gmail.com> I wrote some code recently to make a linked list of Nodes for a 2d graph, so it consists of rows and columns. Now I wanted to make the code support being doubly linked, forwards and backwards. The difficult part of this is that the links are per row and per column. But the code I think is overly bloated. I am currently working on reducing the complexity of it. If any one has the time to look at it, if you have ideas for how I can re-write it to be much smaller I would appreciate the information. If you need more code let me know, but I tried to condense it since this singular function is around 325 lines of code. Thank you. The function to make the linked list: def make_linked_lists(self): previous_row_node = None previous_col0_node = None previous_col1_node = None previous_col2_node = None previous_col3_node = None previous_col4_node = None previous_col5_node = None previous_col6_node = None previous_col7_node = None current_node = None self.tile_list = list() for row in range(0, self.rows): for col in range(0, self.cols): current_node = self.get_instance_of_id(str(col) + ',' + str(row)) self.tile_list.append(current_node) if row == 0: if col == 0: self.row0 = current_node self.col0 = current_node previous_col0_node = current_node elif col == 1: self.col1 = current_node previous_col1_node = current_node elif col == 2: self.col2 = current_node previous_col2_node = current_node elif col == 3: self.col3 = current_node previous_col3_node = current_node elif col == 4: self.col4 = current_node previous_col4_node = current_node elif col == 5: self.col5 = current_node previous_col5_node = current_node elif col == 6: self.col6 = current_node previous_col6_node = current_node elif col == 7: self.col7 = current_node previous_col7_node = current_node if previous_row_node is not None: previous_row_node.next_row_node = current_node current_node.prev_row_node = previous_row_node previous_row_node = current_node elif row == 1: if col == 0: self.row1 = current_node previous_row_node = None previous_col0_node.next_col_node = current_node current_node.prev_col_node = previous_col0_node previous_col0_node = current_node elif col == 1: previous_col1_node.next_col_node = current_node current_node.prev_col_node = previous_col1_node previous_col1_node = current_node elif col == 2: previous_col2_node.next_col_node = current_node current_node.prev_col_node = previous_col2_node previous_col2_node = current_node elif col == 3: previous_col3_node.next_col_node = current_node current_node.prev_col_node = previous_col3_node previous_col3_node = current_node elif col == 4: previous_col4_node.next_col_node = current_node current_node.prev_col_node = previous_col4_node previous_col4_node = current_node elif col == 5: previous_col5_node.next_col_node = current_node current_node.prev_col_node = previous_col5_node previous_col5_node = current_node elif col == 6: previous_col6_node.next_col_node = current_node current_node.prev_col_node = previous_col6_node previous_col6_node = current_node elif col == 7: previous_col7_node.next_col_node = current_node current_node.prev_col_node = previous_col7_node previous_col7_node = current_node if previous_row_node is not None: previous_row_node.next_row_node = current_node previous_row_node = current_node elif row == 2: if col == 0: self.row2 = current_node previous_row_node = None previous_col0_node.next_col_node = current_node previous_col0_node = current_node elif col == 1: previous_col1_node.next_col_node = current_node previous_col1_node = current_node elif col == 2: previous_col2_node.next_col_node = current_node previous_col2_node = current_node elif col == 3: previous_col3_node.next_col_node = current_node previous_col3_node = current_node elif col == 4: previous_col4_node.next_col_node = current_node previous_col4_node = current_node elif col == 5: previous_col5_node.next_col_node = current_node previous_col5_node = current_node elif col == 6: previous_col6_node.next_col_node = current_node previous_col6_node = current_node elif col == 7: previous_col7_node.next_col_node = current_node previous_col7_node = current_node if previous_row_node is not None: previous_row_node.next_row_node = current_node previous_row_node = current_node elif row == 3: if col == 0: self.row3 = current_node previous_row_node = None previous_col0_node.next_col_node = current_node previous_col0_node = current_node elif col == 1: previous_col1_node.next_col_node = current_node previous_col1_node = current_node elif col == 2: previous_col2_node.next_col_node = current_node previous_col2_node = current_node elif col == 3: previous_col3_node.next_col_node = current_node previous_col3_node = current_node elif col == 4: previous_col4_node.next_col_node = current_node previous_col4_node = current_node elif col == 5: previous_col5_node.next_col_node = current_node previous_col5_node = current_node elif col == 6: previous_col6_node.next_col_node = current_node previous_col6_node = current_node elif col == 7: previous_col7_node.next_col_node = current_node previous_col7_node = current_node if previous_row_node is not None: previous_row_node.next_row_node = current_node previous_row_node = current_node elif row == 4: if col == 0: self.row4 = current_node previous_row_node = None previous_col0_node.next_col_node = current_node previous_col0_node = current_node elif col == 1: previous_col1_node.next_col_node = current_node previous_col1_node = current_node elif col == 2: previous_col2_node.next_col_node = current_node previous_col2_node = current_node elif col == 3: previous_col3_node.next_col_node = current_node previous_col3_node = current_node elif col == 4: previous_col4_node.next_col_node = current_node previous_col4_node = current_node elif col == 5: previous_col5_node.next_col_node = current_node previous_col5_node = current_node elif col == 6: previous_col6_node.next_col_node = current_node previous_col6_node = current_node elif col == 7: previous_col7_node.next_col_node = current_node previous_col7_node = current_node if previous_row_node is not None: previous_row_node.next_row_node = current_node previous_row_node = current_node elif row == 5: if col == 0: self.row5 = current_node previous_row_node = None previous_col0_node.next_col_node = current_node previous_col0_node = current_node elif col == 1: previous_col1_node.next_col_node = current_node previous_col1_node = current_node elif col == 2: previous_col2_node.next_col_node = current_node previous_col2_node = current_node elif col == 3: previous_col3_node.next_col_node = current_node previous_col3_node = current_node elif col == 4: previous_col4_node.next_col_node = current_node previous_col4_node = current_node elif col == 5: previous_col5_node.next_col_node = current_node previous_col5_node = current_node elif col == 6: previous_col6_node.next_col_node = current_node previous_col6_node = current_node elif col == 7: previous_col7_node.next_col_node = current_node previous_col7_node = current_node if previous_row_node is not None: previous_row_node.next_row_node = current_node previous_row_node = current_node elif row == 6: if col == 0: self.row6 = current_node previous_row_node = None previous_col0_node.next_col_node = current_node previous_col0_node = current_node elif col == 1: previous_col1_node.next_col_node = current_node previous_col1_node = current_node elif col == 2: previous_col2_node.next_col_node = current_node previous_col2_node = current_node elif col == 3: previous_col3_node.next_col_node = current_node previous_col3_node = current_node elif col == 4: previous_col4_node.next_col_node = current_node previous_col4_node = current_node elif col == 5: previous_col5_node.next_col_node = current_node previous_col5_node = current_node elif col == 6: previous_col6_node.next_col_node = current_node previous_col6_node = current_node elif col == 7: previous_col7_node.next_col_node = current_node previous_col7_node = current_node if previous_row_node is not None: previous_row_node.next_row_node = current_node previous_row_node = current_node elif row == 7: if col == 0: self.row7 = current_node previous_row_node = None previous_col0_node.next_col_node = current_node previous_col0_node = current_node elif col == 1: previous_col1_node.next_col_node = current_node previous_col1_node = current_node elif col == 2: previous_col2_node.next_col_node = current_node previous_col2_node = current_node elif col == 3: previous_col3_node.next_col_node = current_node previous_col3_node = current_node elif col == 4: previous_col4_node.next_col_node = current_node previous_col4_node = current_node elif col == 5: previous_col5_node.next_col_node = current_node previous_col5_node = current_node elif col == 6: previous_col6_node.next_col_node = current_node previous_col6_node = current_node elif col == 7: previous_col7_node.next_col_node = current_node previous_col7_node = current_node if previous_row_node is not None: previous_row_node.next_row_node = current_node previous_row_node = current_node elif row == 8: if col == 0: self.row8 = current_node previous_row_node = None previous_col0_node.next_col_node = current_node previous_col0_node = current_node elif col == 1: previous_col1_node.next_col_node = current_node previous_col1_node = current_node elif col == 2: previous_col2_node.next_col_node = current_node previous_col2_node = current_node elif col == 3: previous_col3_node.next_col_node = current_node previous_col3_node = current_node elif col == 4: previous_col4_node.next_col_node = current_node previous_col4_node = current_node elif col == 5: previous_col5_node.next_col_node = current_node previous_col5_node = current_node elif col == 6: previous_col6_node.next_col_node = current_node previous_col6_node = current_node elif col == 7: previous_col7_node.next_col_node = current_node previous_col7_node = current_node if previous_row_node is not None: previous_row_node.next_row_node = current_node previous_row_node = current_node elif row == 9: if col == 0: self.row9 = current_node previous_row_node = None previous_col0_node.next_col_node = current_node previous_col0_node = current_node elif col == 1: previous_col1_node.next_col_node = current_node previous_col1_node = current_node elif col == 2: previous_col2_node.next_col_node = current_node previous_col2_node = current_node elif col == 3: previous_col3_node.next_col_node = current_node previous_col3_node = current_node elif col == 4: previous_col4_node.next_col_node = current_node previous_col4_node = current_node elif col == 5: previous_col5_node.next_col_node = current_node previous_col5_node = current_node elif col == 6: previous_col6_node.next_col_node = current_node previous_col6_node = current_node elif col == 7: previous_col7_node.next_col_node = current_node previous_col7_node = current_node if previous_row_node is not None: previous_row_node.next_row_node = current_node previous_row_node = current_node From steve at pearwood.info Wed Dec 24 22:56:05 2014 From: steve at pearwood.info (Steven D'Aprano) Date: Thu, 25 Dec 2014 08:56:05 +1100 Subject: [Tutor] Making Doubly Linked List with Less Lines of Code. In-Reply-To: <549B318A.8030909@gmail.com> References: <549B318A.8030909@gmail.com> Message-ID: <20141224215604.GB6580@ando.pearwood.info> On Wed, Dec 24, 2014 at 04:35:06PM -0500, WolfRage wrote: > I wrote some code recently to make a linked list of Nodes for a 2d > graph, so it consists of rows and columns. Now I wanted to make the code > support being doubly linked, forwards and backwards. The difficult part > of this is that the links are per row and per column. But the code I > think is overly bloated. I am currently working on reducing the > complexity of it. If any one has the time to look at it, if you have > ideas for how I can re-write it to be much smaller I would appreciate > the information. If you need more code let me know, but I tried to > condense it since this singular function is around 325 lines of code. Wow. It certainly is bloated. I don't have time to look at it in any detail right now, as it is Christmas Day here, but I'll give you a suggestion. Any time you find yourself writing more than two numbered variables, like this: > previous_col0_node = None > previous_col1_node = None > previous_col2_node = None > previous_col3_node = None > previous_col4_node = None > previous_col5_node = None > previous_col6_node = None > previous_col7_node = None you should instead think about writing a list: previous_col_nodes = [None]*8 Then, instead of code like this: > if col == 0: > self.col0 = current_node > previous_col0_node = current_node > elif col == 1: > self.col1 = current_node > previous_col1_node = current_node > elif col == 2: > self.col2 = current_node > previous_col2_node = current_node etc. you can just write: for col in range(number_of_columns): self.columns[col] = current_node previous_col_nodes[col] = current_node Look for the opportunity to write code like this instead of using range: for col, the_column in enumerate(self.columns): self.columns[col] = process(the_column) Any time you write more than a trivial amount of code twice, you should move it into a function. Then, instead of: if row == 0: if col == 0: a elif col == 1: b elif col == 2: c elif col == 3: d elif col == 4: e elif row == 1: if col == 0: a elif col == 1: b elif col == 2: c elif col == 3: d elif col == 4: e elif row == 3: # same again you can write a function: def process_cell(row, col): if col == 0: a elif col == 1: b elif col == 2: c elif col == 3: d elif col == 4: e # later on for row in rows: for col in cols: process_cell(row, col) Try those suggestions, and come back to us if you still need help. -- Steven From wolfrage8765 at gmail.com Wed Dec 24 23:02:03 2014 From: wolfrage8765 at gmail.com (WolfRage) Date: Wed, 24 Dec 2014 17:02:03 -0500 Subject: [Tutor] Making Doubly Linked List with Less Lines of Code. Message-ID: <549B37DB.1070300@gmail.com> Here is a condensed version of all of the applicable code but with out Linked List filled in, as I am preparing to re-write it. class GameTile(): def __init__(self, id, **kwargs): self.id = id class GameGrid(): def __init__(self, **kwargs): self.cols = 8 self.rows = 10 # Each variable below is a link to the head Node in the respective # row or column. self.row0 = None self.row1 = None self.row2 = None self.row3 = None self.row4 = None self.row5 = None self.row6 = None self.row7 = None self.row8 = None self.row9 = None self.col0 = None self.col1 = None self.col2 = None self.col3 = None self.col4 = None self.col5 = None self.col6 = None self.col7 = None self.skip_to_row = None self.skip_to_col = None self.tile_list = list() def make_linked_lists(self): prev_row_node = None prev_col0_node = None current_node = None for row in range(0, self.rows): for col in range(0, self.cols): for node in self.tile_list: if node.id == str(col) + ',' + str(row): current_node = node def update(self): for row in range(0, self.rows): element = None if row < 7: pass for column in range(0, self.cols): self.tile_list.append(GameTile(id=str(column) + ',' + str(row))) def print_lists(self): for node in self.tile_list: print(node.id) temp = GameGrid() temp.update() temp.make_linked_lists() temp.print_lists() From wolfrage8765 at gmail.com Wed Dec 24 23:05:17 2014 From: wolfrage8765 at gmail.com (WolfRage) Date: Wed, 24 Dec 2014 17:05:17 -0500 Subject: [Tutor] Making Doubly Linked List with Less Lines of Code. In-Reply-To: <20141224215604.GB6580@ando.pearwood.info> References: <549B318A.8030909@gmail.com> <20141224215604.GB6580@ando.pearwood.info> Message-ID: <549B389D.4080007@gmail.com> OK thanks for the rapid response, I will start rewriting the functions in this way now, and will come back with what I wind up with. Also Merry Christmas! On 12/24/2014 04:56 PM, Steven D'Aprano wrote: > On Wed, Dec 24, 2014 at 04:35:06PM -0500, WolfRage wrote: >> I wrote some code recently to make a linked list of Nodes for a 2d >> graph, so it consists of rows and columns. Now I wanted to make the code >> support being doubly linked, forwards and backwards. The difficult part >> of this is that the links are per row and per column. But the code I >> think is overly bloated. I am currently working on reducing the >> complexity of it. If any one has the time to look at it, if you have >> ideas for how I can re-write it to be much smaller I would appreciate >> the information. If you need more code let me know, but I tried to >> condense it since this singular function is around 325 lines of code. > Wow. It certainly is bloated. > > I don't have time to look at it in any detail right now, as it is > Christmas Day here, but I'll give you a suggestion. Any time you find > yourself writing more than two numbered variables, like this: > >> previous_col0_node = None >> previous_col1_node = None >> previous_col2_node = None >> previous_col3_node = None >> previous_col4_node = None >> previous_col5_node = None >> previous_col6_node = None >> previous_col7_node = None > you should instead think about writing a list: > > previous_col_nodes = [None]*8 > > Then, instead of code like this: > >> if col == 0: >> self.col0 = current_node >> previous_col0_node = current_node >> elif col == 1: >> self.col1 = current_node >> previous_col1_node = current_node >> elif col == 2: >> self.col2 = current_node >> previous_col2_node = current_node > etc. > > you can just write: > > for col in range(number_of_columns): > self.columns[col] = current_node > previous_col_nodes[col] = current_node > > > Look for the opportunity to write code like this instead of using range: > > for col, the_column in enumerate(self.columns): > self.columns[col] = process(the_column) > > > Any time you write more than a trivial amount of code twice, you should > move it into a function. Then, instead of: > > if row == 0: > if col == 0: a > elif col == 1: b > elif col == 2: c > elif col == 3: d > elif col == 4: e > elif row == 1: > if col == 0: a > elif col == 1: b > elif col == 2: c > elif col == 3: d > elif col == 4: e > elif row == 3: > # same again > > you can write a function: > > def process_cell(row, col): > if col == 0: a > elif col == 1: b > elif col == 2: c > elif col == 3: d > elif col == 4: e > > # later on > > for row in rows: > for col in cols: > process_cell(row, col) > > > > Try those suggestions, and come back to us if you still need help. > > > > From dyoo at hashcollision.org Thu Dec 25 06:15:25 2014 From: dyoo at hashcollision.org (Danny Yoo) Date: Wed, 24 Dec 2014 21:15:25 -0800 Subject: [Tutor] Making Doubly Linked List with Less Lines of Code. In-Reply-To: <549B37DB.1070300@gmail.com> References: <549B37DB.1070300@gmail.com> Message-ID: Quick comment: the structure of the code here catches my eye: > # Each variable below is a link to the head Node in the respective > # row or column. > self.row0 = None > self.row1 = None > self.row2 = None > self.row3 = None > self.row4 = None > self.row5 = None > self.row6 = None > self.row7 = None > self.row8 = None > self.row9 = None It seems highly regular; the code here is maintaining a collection of row variables. Because it's so regular, you might consider using a list to represent this collection. Concretely: self.rows = [None, None, None, None, None, None, None, None, None, None] We can express this more concisely in Python as: self.row = [None] * 10 Once we have this, then we can get at any particular row through its offset. So instead of: self.row0 we say: self.row[0] The big win with a list representation is that the offset can be computed. So if we need to do an operation on each row, we might say: for i in range(10): ## ... Do something with self.row[i] And if you see the full power of this, you'll realize that this allows us to express loops to do something to _all_ the rows, expressing that action just once. Or if we need to do something for every other row, that too is not too difficult to express: for i in range(0, 10, 2): ## ... Do something with self.row[i] In contrast, doing the same thing without using an explicit container representation means that doing container-wide actions is harder to do. This is the code smell that we saw at the beginning of this post, where we see repetitive code. From dyoo at hashcollision.org Thu Dec 25 06:31:06 2014 From: dyoo at hashcollision.org (Danny Yoo) Date: Wed, 24 Dec 2014 21:31:06 -0800 Subject: [Tutor] Making Doubly Linked List with Less Lines of Code. In-Reply-To: <549B318A.8030909@gmail.com> References: <549B318A.8030909@gmail.com> Message-ID: On Wed, Dec 24, 2014 at 1:35 PM, WolfRage wrote: > I wrote some code recently to make a linked list of Nodes for a 2d graph, so > it consists of rows and columns. Now I wanted to make the code support being > doubly linked, forwards and backwards. What are the _operations_ you want to support? Can you say more about this? Representations make certain operations easier or more difficult, and you're focusing on representations, which is fine. But I'm not quite sure what operations you need to support. You mention the concept of a 2d graph arranged in rows and columns. I am assuming you want at least two operations. * Given a row and column, add a Node at that position. * Given a row and column, get the Node (or nodes?) at that position. Conceptually, these are "insertion" and "lookup". But note that I am not sure what you want out of "lookup". I can't tell because it's not obvious, so you need to let us know. Does that sound reasonable? Let's put a stake on the ground and nail purpose first. And then figure out representation after that. From dyoo at hashcollision.org Thu Dec 25 06:17:15 2014 From: dyoo at hashcollision.org (Danny Yoo) Date: Wed, 24 Dec 2014 21:17:15 -0800 Subject: [Tutor] Making Doubly Linked List with Less Lines of Code. In-Reply-To: References: <549B37DB.1070300@gmail.com> Message-ID: > It seems highly regular; the code here is maintaining a collection of > row variables. Because it's so regular, you might consider using a > list to represent this collection. Concretely: > > self.rows = [None, None, None, None, None, None, None, None, None, None] Whoops. Apologies: I should have named the variable "row" to be consistent with the rest of the message: self.row = [None, None, None, None, None, None, None, None, None, None] That being said, still easier just to say: self.row = [None] * 10 From wolfrage8765 at gmail.com Thu Dec 25 18:09:19 2014 From: wolfrage8765 at gmail.com (WolfRage) Date: Thu, 25 Dec 2014 12:09:19 -0500 Subject: [Tutor] Making Doubly Linked List with Less Lines of Code. In-Reply-To: References: <549B37DB.1070300@gmail.com> Message-ID: <549C44BF.3050105@gmail.com> Thanks, definitely adding this concept into my code. And re-writing. I originally hard coded everything just to get it working... but obviously, it would have been more time efficient to have thought in these terms from the beginning. Hopefully I can learn to write code more like this to begin with, even when I just want to get something working. Reading the rest of your recommendations now. On 12/25/2014 12:15 AM, Danny Yoo wrote: > Quick comment: the structure of the code here catches my eye: > > >> # Each variable below is a link to the head Node in the respective >> # row or column. >> self.row0 = None >> self.row1 = None >> self.row2 = None >> self.row3 = None >> self.row4 = None >> self.row5 = None >> self.row6 = None >> self.row7 = None >> self.row8 = None >> self.row9 = None > It seems highly regular; the code here is maintaining a collection of > row variables. Because it's so regular, you might consider using a > list to represent this collection. Concretely: > > self.rows = [None, None, None, None, None, None, None, None, None, None] > > We can express this more concisely in Python as: > > self.row = [None] * 10 > > Once we have this, then we can get at any particular row through its > offset. So instead of: > > self.row0 > > we say: > > self.row[0] > > The big win with a list representation is that the offset can be > computed. So if we need to do an operation on each row, we might say: > > for i in range(10): > ## ... Do something with self.row[i] > > And if you see the full power of this, you'll realize that this allows > us to express loops to do something to _all_ the rows, expressing that > action just once. Or if we need to do something for every other row, > that too is not too difficult to express: > > for i in range(0, 10, 2): > ## ... Do something with self.row[i] > > > In contrast, doing the same thing without using an explicit container > representation means that doing container-wide actions is harder to > do. This is the code smell that we saw at the beginning of this post, > where we see repetitive code. From dmamyrivo at gmail.com Thu Dec 25 22:17:13 2014 From: dmamyrivo at gmail.com (Mamy Rivo DIANZINGA) Date: Thu, 25 Dec 2014 22:17:13 +0100 Subject: [Tutor] Python script Message-ID: Good morning Sir, merry Xmas. I have a question, please Sir if you do not mind. In this file E_vs_cutoff1.pdf, i represent the energy vs radial cutoff. And in the python script, i specified the limits of Y-axis as: pl.ylim(-5524.0,-5522.5). But as you can see the figure, there is -5522e-3 on left top and, the Energy values are between -2.0 and -0.5. It is as if the Energy values have been separated, despite the python instruction "pl.ylim(-5524.0,-5522.5)". So i was wondering, how can i fix it so that the figure shows indeed the Energy values from -5524.0 to -5522.5. How to set the Y-axis scale in that case? I hope you will understand my question. Thanks in advance and Merry Xmas again. Happy New year!!! From ben+python at benfinney.id.au Fri Dec 26 01:59:11 2014 From: ben+python at benfinney.id.au (Ben Finney) Date: Fri, 26 Dec 2014 11:59:11 +1100 Subject: [Tutor] Python script References: Message-ID: <85wq5fz0o0.fsf@benfinney.id.au> Mamy Rivo DIANZINGA writes: > Good morning Sir, merry Xmas. I have a question, please Sir if you do > not mind. Thank you for being so polite; we are usually quite informal here. > In this file E_vs_cutoff1.pdf, i represent the energy vs radial > cutoff. And in the python script, i specified the limits of Y-axis as: > pl.ylim(-5524.0,-5522.5). If you want to show us some Python code, you'll need to include it in the message. Please make sure to do the following to ensure your Python code is readable: * Make it *very* short, just enough to demonstrate the issue . This means do not present your entire program, but only a small one you have contrived to focus on the issue. * Compose your messages in plain text, without special formatting . This will be much more likely to preserve the Python code as you actually wrote it, without modification in transit. If you do both of these you are much more likely to get a good response from this Tutor group. > Thanks in advance and Merry Xmas again. Happy New year!!! And to you, and to everyone here good cheer. -- \ ?If consumers even know there's a DRM, what it is, and how it | `\ works, we've already failed.? ?Peter Lee, Disney corporation, | _o__) 2005 | Ben Finney From akleider at sonic.net Fri Dec 26 03:52:10 2014 From: akleider at sonic.net (Alex Kleider) Date: Thu, 25 Dec 2014 18:52:10 -0800 Subject: [Tutor] Python script In-Reply-To: <85wq5fz0o0.fsf@benfinney.id.au> References: <85wq5fz0o0.fsf@benfinney.id.au> Message-ID: <4cc6e7539b8085bac8cb1ef816b044ff@sonic.net> On 2014-12-25 16:59, Ben Finney wrote: > . It may be that this link will go away. http://www.coderanch.com/t/628405/Ranch-Office/SSCCE-org-document-disappearing From ben+python at benfinney.id.au Fri Dec 26 08:58:24 2014 From: ben+python at benfinney.id.au (Ben Finney) Date: Fri, 26 Dec 2014 18:58:24 +1100 Subject: [Tutor] Python script References: <85wq5fz0o0.fsf@benfinney.id.au> <4cc6e7539b8085bac8cb1ef816b044ff@sonic.net> Message-ID: <85fvc2zvtr.fsf@benfinney.id.au> Alex Kleider writes: > On 2014-12-25 16:59, Ben Finney wrote: > > > . > > It may be that this link will go away. > http://www.coderanch.com/t/628405/Ranch-Office/SSCCE-org-document-disappearing Almost certainly at some future time, but not because of that. As discussed in that thread (2014-02), the domain ?sscce.org? is now hosted by JavaRanch, leads to the ?SSCCE? document as normal, and is under no threat of disappearing. Nothing in that thread says otherwise, do you have more current information to the contrary? -- \ ?Geeks like to think that they can ignore politics. You can | `\ leave politics alone, but politics won't leave you alone.? | _o__) ?Richard M. Stallman, 2002-07-26 | Ben Finney From akleider at sonic.net Fri Dec 26 18:01:47 2014 From: akleider at sonic.net (Alex Kleider) Date: Fri, 26 Dec 2014 09:01:47 -0800 Subject: [Tutor] Python script In-Reply-To: <85fvc2zvtr.fsf@benfinney.id.au> References: <85wq5fz0o0.fsf@benfinney.id.au> <4cc6e7539b8085bac8cb1ef816b044ff@sonic.net> <85fvc2zvtr.fsf@benfinney.id.au> Message-ID: On 2014-12-25 23:58, Ben Finney wrote: > Nothing in that thread says otherwise, do you have more current > information to the contrary? I do not. From salismesalisme at hotmail.com Fri Dec 26 17:16:17 2014 From: salismesalisme at hotmail.com (salisme salisme) Date: Fri, 26 Dec 2014 16:16:17 +0000 Subject: [Tutor] Problem Message-ID: Hello I am having a big problem trying to open a url that I have created by concatenating a raw_input on to an already existing url. When I copy and paste the url in to the search bar it works fine but when I try to open it using urllib.request.urlopen(url) it givesme a 505 HTTP error. >From reading on the web I think the problem is the url I am using is not the full url, how do I get this full url from what I have, I tried to use geturl() but it wouldn't let me import it? Please help! import reimport urllibfrom urllib.request import urlparsefrom urllib.request import urlopenfrom urllib.request import urlretrievefrom bs4 import BeautifulSoup as bs choice = input("Choose artist and album name in following format : Artist 'x' album 'y'") baseurl = "http://www.ebay.co.uk/sch/Records-/176985/i.html?_nkw=" + choice + '&_pgn=1' then I get an error from the following: urllib.request.urlopen(baseurl) From joel.goldstick at gmail.com Sat Dec 27 00:55:45 2014 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Fri, 26 Dec 2014 18:55:45 -0500 Subject: [Tutor] Problem In-Reply-To: References: Message-ID: On Fri, Dec 26, 2014 at 11:16 AM, salisme salisme wrote: > Hello > I am having a big problem trying to open a url that I have created by concatenating a raw_input on to an already existing url. > When I copy and paste the url in to the search bar it works fine but when I try to open it using urllib.request.urlopen(url) it givesme a 505 HTTP error. > From reading on the web I think the problem is the url I am using is not the full url, how do I get this full url from what I have, I tried to use geturl() but it wouldn't let me import it? > Please help! > import reimport urllibfrom urllib.request import urlparsefrom urllib.request import urlopenfrom urllib.request import urlretrievefrom bs4 import BeautifulSoup as bs > choice = input("Choose artist and album name in following format : Artist 'x' album 'y'") > baseurl = "http://www.ebay.co.uk/sch/Records-/176985/i.html?_nkw=" + choice + '&_pgn=1' > then I get an error from the following: > urllib.request.urlopen(baseurl) > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor print baseurl -- Joel Goldstick http://joelgoldstick.com From alan.gauld at btinternet.com Sat Dec 27 02:15:49 2014 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 27 Dec 2014 01:15:49 +0000 Subject: [Tutor] Problem In-Reply-To: References: Message-ID: On 26/12/14 16:16, salisme salisme wrote: > I am having a big problem trying to open a url that > I have created by concatenating a raw_input > on to an already existing url. Thats not what your code says beloiw. Although its kind of hard to read since you didn't post in plain text... But you appear to be using input() not raw_input(). If its Python3 it should be input() but if its Python2 that will likely do something very different. > When I copy and paste the url in to the search bar it works Which url? Have you compared it with the baseurl value below? Did you cut n paste the baseurl value into the search bar? Or did you type what you thought it should be? > fine but when I try to open it using urllib.request.urlopen(url) > it givesme a 505 HTTP error. How do you see this error? Is it printed on screen? in a log file? Do you get any Python errors. Please show us a cut n' paste of the actual error text. > import reimport urllibfrom urllib.request import urlparsefrom urllib.request import urlopenfrom urllib.request import urlretrievefrom bs4 import BeautifulSoup as bs > choice = input("Choose artist and album name in following format : Artist 'x' album 'y'") > baseurl = "http://www.ebay.co.uk/sch/Records-/176985/i.html?_nkw=" + choice + '&_pgn=1' > then I get an error from the following: > urllib.request.urlopen(baseurl) What are you doing with the return value of urlopen()? Are you really thropwing it away? Please post, in plain text, the actual Python code that produces the error and the error message. And tell us which Python version and OS you are using. That way we might be able to help. -- 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 From steve at pearwood.info Sat Dec 27 03:27:42 2014 From: steve at pearwood.info (Steven D'Aprano) Date: Sat, 27 Dec 2014 13:27:42 +1100 Subject: [Tutor] Problem In-Reply-To: References: Message-ID: <20141227022742.GV6580@ando.pearwood.info> On Fri, Dec 26, 2014 at 04:16:17PM +0000, salisme salisme wrote: > Hello > I am having a big problem trying to open a url that I have created by > concatenating a raw_input on to an already existing url. When I copy > and paste the url in to the search bar it works fine but when I try to > open it using urllib.request.urlopen(url) it givesme a 505 HTTP error. 505 HTTP error means "version not supported". I would be very surprised if that is the error you receive. Please copy and paste (do not re-type from memory!) the *exact* error you get. > From reading on the web I think the problem is the url I am using is > not the full url, how do I get this full url from what I have, I tried > to use geturl() but it wouldn't let me import it? > Please help! > import reimport urllibfrom urllib.request import urlparsefrom > urllib.request import urlopenfrom urllib.request import > urlretrievefrom bs4 import BeautifulSoup as bs choice = input("Choose > artist and album name in following format : Artist 'x' album 'y'") > baseurl = "http://www.ebay.co.uk/sch/Records-/176985/i.html?_nkw=" + > choice + '&_pgn=1' All the formatting from your code is screwed up. Also you say above that you use "raw_input", but your code shown here actually uses "input", a different function. Please COPY and PASTE the **exact** code you are actually using, do not re-type it from memory, and please send as plain text so the formatting doesn't get screwed up. I also see you are trying to connect to Ebay. Ebay will try very, very, very hard to prohibit "bots" (i.e. programs like the one you are writing) from talking to the server. It will refuse to talk to anything it thinks is not a human being using a browser. That means it will take a lot of hard work to get this programming working: - you may need to set the user-agent to something that looks like a browser; - you may need to set the referrer to something from Ebay; - you may need to use cookies; - you may need to run Javascript to make things work correctly. All these things can be done, but it will require work and possibly third-party libraries. Start with showing us the actual code you use, the actual error given, and show us the actual URL used. Thank you, -- Steve From pscott_74 at yahoo.com Tue Dec 30 00:50:55 2014 From: pscott_74 at yahoo.com (Patti Scott) Date: Mon, 29 Dec 2014 15:50:55 -0800 Subject: [Tutor] [OT] Best Practices for Scientific Computing In-Reply-To: <1672096189.409752.1415985546744.JavaMail.yahoo@jws10777.mail.gq1.yahoo.com> Message-ID: <1419897055.60660.YahooMailBasic@web161804.mail.bf1.yahoo.com> Could someone clarify "Modularize code rather than copying and pasting?" thanks -------------------------------------------- On Fri, 11/14/14, Albert-Jan Roskam wrote: Subject: [Tutor] [OT] Best Practices for Scientific Computing To: "Python Mailing List" Date: Friday, November 14, 2014, 12:19 PM Hi, I thought this might be worth sharing, especially on a windy, rainy Friday evnening: http://www.plosbiology.org/article/info%3Adoi%2F10.1371%2Fjournal.pbio.1001745 Here are the best practices mentioned in the article: Write programs for people, not computers. A program should not require its readers to hold more than a handful of facts in memory at once. Make names consistent, distinctive, and meaningful. Make code style and formatting consistent. Let the computer do the work. Make the computer repeat tasks. Save recent commands in a file for re-use. Use a build tool to automate workflows. Make incremental changes. Work in small steps with frequent feedback and course correction. Use a version control system. Put everything that has been created manually in version control. Don't repeat yourself (or others). Every piece of data must have a single authoritative representation in the system. Modularize code rather than copying and pasting. Re-use code instead of rewriting it. Plan for mistakes. Add assertions to programs to check their operation. Use an off-the-shelf unit testing library. Turn bugs into test cases. Use a symbolic debugger. Optimize software only after it works correctly. Use a profiler to identify bottlenecks. Write code in the highest-level language possible. Document design and purpose, not mechanics. Document interfaces and reasons, not implementations. Refactor code in preference to explaining how it works. Embed the documentation for a piece of software in that software. Collaborate. Use pre-merge code reviews. Use pair programming when bringing someone new up to speed and when tackling particularly tricky problems. Use an issue tracking tool. Have a great weekend! Regards, Albert-Jan ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ All right, but apart from the sanitation, the medicine, education, wine, public order, irrigation, roads, a fresh water system, and public health, what have the Romans ever done for us? ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ _______________________________________________ Tutor maillist? -? Tutor at python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor From joel.goldstick at gmail.com Tue Dec 30 00:57:01 2014 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Mon, 29 Dec 2014 18:57:01 -0500 Subject: [Tutor] [OT] Best Practices for Scientific Computing In-Reply-To: <1419897055.60660.YahooMailBasic@web161804.mail.bf1.yahoo.com> References: <1672096189.409752.1415985546744.JavaMail.yahoo@jws10777.mail.gq1.yahoo.com> <1419897055.60660.YahooMailBasic@web161804.mail.bf1.yahoo.com> Message-ID: On Mon, Dec 29, 2014 at 6:50 PM, Patti Scott < pscott_74 at yahoo.com.dmarc.invalid> wrote: > Could someone clarify "Modularize code rather than copying and pasting?" > > thanks > Sure -- When you have nearly identical or identical pieces of code, make functions rather than cut and paste the same code. Call the function from various places. It makes it easier to bug fix later > -------------------------------------------- > On Fri, 11/14/14, Albert-Jan Roskam wrote: > > Subject: [Tutor] [OT] Best Practices for Scientific Computing > To: "Python Mailing List" > Date: Friday, November 14, 2014, 12:19 PM > > Hi, > > I thought this might be worth sharing, especially on a > windy, rainy Friday evnening: > http://www.plosbiology.org/article/info%3Adoi%2F10.1371%2Fjournal.pbio.1001745 > > > Here are the best practices mentioned in the article: > > Write programs for people, not computers. > A program should not require its readers to hold more than a > handful of facts in memory at once. > Make names consistent, distinctive, and meaningful. > Make code style and formatting consistent. > Let the computer do the work. > Make the computer repeat tasks. > Save recent commands in a file for re-use. > Use a build tool to automate workflows. > Make incremental changes. > Work in small steps with frequent feedback and course > correction. > Use a version control system. > Put everything that has been created manually in version > control. > Don't repeat yourself (or others). > Every piece of data must have a single authoritative > representation in the system. > Modularize code rather than copying and pasting. > Re-use code instead of rewriting it. > Plan for mistakes. > Add assertions to programs to check their operation. > Use an off-the-shelf unit testing library. > Turn bugs into test cases. > Use a symbolic debugger. > Optimize software only after it works correctly. > Use a profiler to identify bottlenecks. > Write code in the highest-level language possible. > Document design and purpose, not mechanics. > Document interfaces and reasons, not implementations. > Refactor code in preference to explaining how it works. > Embed the documentation for a piece of software in that > software. > Collaborate. > Use pre-merge code reviews. > Use pair programming when bringing someone new up to speed > and when tackling particularly tricky problems. > Use an issue tracking tool. > > > Have a great weekend! > > > Regards, > > Albert-Jan > > > > > > ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ > > All right, but apart from the sanitation, the medicine, > education, wine, public order, irrigation, roads, a > > fresh water system, and public health, what have the Romans > ever done for us? > > ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor > -- Joel Goldstick http://joelgoldstick.com From dyoo at hashcollision.org Tue Dec 30 02:51:49 2014 From: dyoo at hashcollision.org (Danny Yoo) Date: Mon, 29 Dec 2014 17:51:49 -0800 Subject: [Tutor] [OT] Best Practices for Scientific Computing In-Reply-To: References: <1672096189.409752.1415985546744.JavaMail.yahoo@jws10777.mail.gq1.yahoo.com> <1419897055.60660.YahooMailBasic@web161804.mail.bf1.yahoo.com> Message-ID: > When you have nearly identical or identical pieces of code, make functions > rather than cut and paste the same code. Call the function from various > places. It makes it easier to bug fix later We can make this more concrete. Let's say that we are writing a program to do all kinds of dice rolls. (I've been reading the 5th edition D&D Basic Rules lately, so that's been on my mind. :P) Say that we want to roll two 6-sided dice and print out the result of summing both dice rolls. We might imagine a program like this: ########################### import random dice1 = random.randint(1, 6) dice2 = random.randint(1, 6) print("2d6: %d" % (dice1 + dice2)) ########################### Later, we might want another similar program that rolls four dice and adds their result. Well, that's easy enough: we can just copy and paste. ######################################### import random dice1 = random.randint(1, 6) dice2 = random.randint(1, 6) dice3 = random.randint(1, 6) dice4 = random.randint(1, 6) print("4d6: %d" % (dice1 + dice2 + dice3 + dice4)) ######################################### Notice, though, that we needed to be a bit careful: we could just as easily mis-typed something: ######################################### import random dice1 = random.randint(1, 6) dice2 = random.randint(1, 6) dice3 = random.randint(1, 6) dice4 = random.randint(1, 6) print("4d6: %d" % (dice1 + dice2 + dice3 + dice3)) ######################################### Whooops. This is a contrived error, but several of the interesting bugs in real-world code originate from errors during copy-and-paste. We might also say that this code isn't that flexible because a "minor" change in the requirements (let's roll roll seven dice instead!) should be reflected as a minor change in the code, and at the moment, it isn't: we can see that we have to make multiple changes. So let's fix that. We can do so by generalizing the program, so that it can handle a multitude of dice roles in a general way. We can design a function to do this. Let's write a function, 'throwDice', that takes a number of dice we want to throw, and returns their sum. ######################################### import random def throwDice(n): """Returns the sum of n d6 dice.""" sum = 0 for i in range(n): sum += random.randint(1, 6) return sum ######################################### Once we have this function, now we can throw all sorts of dice, like: print("2d6: %d" % throwDice(2)) or print("4d6: %d" % throwDice(4)) Heck, we can start throwing dice like crazy: ######################################### for i in [1, 2, 3, 4, 5]: print("%dd6: %d" % (i, throwDice(i))) ######################################### (Visit http://repl.it/7Ix to see and run this program in your browser.) This is what it means to use functions to avoid copy-and-paste: if we find ourselves extending our program to do something more by copying and pasting, where it starts to feel repetitive, then we should stop and pause. We might be able to generalize what we're doing as a reusable function instead. And then the repetition won't be in the physical flow of our code, but rather that repetition will show up as separate uses of that general function. If you have more questions, please feel free to ask. From alan.gauld at btinternet.com Tue Dec 30 12:34:10 2014 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 30 Dec 2014 11:34:10 +0000 Subject: [Tutor] [OT] Best Practices for Scientific Computing In-Reply-To: <1419897055.60660.YahooMailBasic@web161804.mail.bf1.yahoo.com> References: <1672096189.409752.1415985546744.JavaMail.yahoo@jws10777.mail.gq1.yahoo.com> <1419897055.60660.YahooMailBasic@web161804.mail.bf1.yahoo.com> Message-ID: On 29/12/14 23:50, Patti Scott wrote: > Could someone clarify "Modularize code rather than copying and pasting?" Joel and Danny have given the basic answer in terms of putting loose code into functions. But it goes a little further too. You can be tempted to copy/paste functions because they almost do what you want but not quite (maybe the take a list of values and you want to use a dictionary). Its easy to copy the function and change all the numerical indexes into keys and use the dictionary. But it would be better to change the original function so that it can work with both, if possible. This usually involves representing the variations in behaviour as parameters in the function (usually with defaults to retain the original semantics). Another case might be where you have a bunch of functions that operate on a global data structure. Then you want to have a second similar data structure but you can't use the functions on it because they access the existing global. You could copy/paste the functions and change the data reference. But it would be better to either add the data structure reference to the functions as a parameter, or you create a class that has the data as an internal instance attribute. Finally, you might have some code in a program that you want to use in another program. But you can't just import the first program because it runs all sorts of other stuff you don't need. So you just copy out the functions you want. Or you could put the loose code into a function (main() usually) and call that within a if __name__ === "__main__": main() line in your original program, turning it into a reusable module which you can now safely import. So modularize can have several meanings, it applies to any mechanism used to bundle up code for reuse. The point being that reusing code, whether as a function, module or class, is more flexible and reliable than copy/pasting it. PS. Note that reuse is not universally a good thing, it does have negative aspects too, in test and maintenance costs and, often, in performance impact. But in the vast majority of cases the positives vastly outweigh the negatives. 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 From fomcl at yahoo.com Tue Dec 30 15:10:40 2014 From: fomcl at yahoo.com (Albert-Jan Roskam) Date: Tue, 30 Dec 2014 06:10:40 -0800 Subject: [Tutor] [OT] Best Practices for Scientific Computing Message-ID: <1419948640.7686.BPMail_high_carrier@web163802.mail.gq1.yahoo.com> ----------------------------- On Tue, Dec 30, 2014 12:34 PM CET Alan Gauld wrote: >On 29/12/14 23:50, Patti Scott wrote: >> Could someone clarify "Modularize code rather than copying and pasting?" > >Joel and Danny have given the basic answer in terms of putting >loose code into functions. But it goes a little further too. > >You can be tempted to copy/paste functions because they almost >do what you want but not quite (maybe the take a list of values >and you want to use a dictionary). Its easy to copy the function >and change all the numerical indexes into keys and use the >dictionary. But it would be better to change the original function >so that it can work with both, if possible. This usually involves >representing the variations in behaviour as parameters in the >function (usually with defaults to retain the original semantics). But isn't there a point where you break the 'law' that a function should have one and only one goal? At a certain point you end up with a big fat juicy function that not only takes dicts and lists, but also scratches your back, does the laundry,... >Another case might be where you have a bunch of functions that operate on a global data structure. Then you want to have a second similar data structure but you can't use the functions on it because they access >the existing global. You could copy/paste the functions and change the data reference. But it would be better to either add the data structure reference to the functions as a parameter, or you create a class that has the data as an internal instance attribute. > >Finally, you might have some code in a program that you want to use in another program. But you can't just import the first program because >it runs all sorts of other stuff you don't need. So you just copy >out the functions you want. Or you could put the loose code into a function (main() usually) and call that within a Say you have a file 'helpers.py' that contains functions that you might use across projects. How do you only display the functions that you actually used in your (Sphinx) documentation of a particular project? >if __name__ === "__main__": main() > >line in your original program, turning it into a reusable module >which you can now safely import. > >So modularize can have several meanings, it applies to any >mechanism used to bundle up code for reuse. The point being that reusing code, whether as a function, module or class, is more >flexible and reliable than copy/pasting it. > >PS. >Note that reuse is not universally a good thing, it does >have negative aspects too, in test and maintenance costs >and, often, in performance impact. I often use python for data analysis. I would be afraid that a modification to a generic function for project B would affect the results of project A (which may be long-running analysis). Hmmm, maybe 'git submodule' would be useful here. But in the vast majority >of cases the positives vastly outweigh the negatives. > >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 at python.org >To unsubscribe or change subscription options: >https://mail.python.org/mailman/listinfo/tutor From wolfrage8765 at gmail.com Tue Dec 30 19:47:49 2014 From: wolfrage8765 at gmail.com (WolfRage) Date: Tue, 30 Dec 2014 13:47:49 -0500 Subject: [Tutor] Making Doubly Linked List with Less Lines of Code. In-Reply-To: References: <549B318A.8030909@gmail.com> Message-ID: <54A2F355.9050607@gmail.com> This is my most recent rendition of the code. It still needs to be improved. Below I am answering some questions that were posed. Also I think my code is currently wrong because I think the print_by functions are both printing the list the same way. Tomorrow I will fix this and improve the code. Thank you guys for your help so far. class GameTile(): def __init__(self, id, **kwargs): self.id = id self.value = None self.next_node_in_row = None self.next_node_in_col = None self.prev_node_in_row = None self.prev_node_in_col = None class GameGrid(): def __init__(self, **kwargs): self.num_of_cols = 8 self.num_of_rows = 10 # Each variable below is a list of links to the head # node in the respective row or column. self.rows = [None] * self.num_of_rows self.cols = [None] * self.num_of_cols self.skip_to_row = None self.skip_to_col = None self.tile_list = list() def make_grid_nodes(self): for row in range(0, self.num_of_rows): for column in range(0, self.num_of_cols): tile = GameTile(id=str(column) + ',' + str(row)) self.tile_list.append(tile) if column == 0: # New Head of Row self.rows[row] = tile else: prev_row.next_node_in_row = tile tile.prev_node_in_row = prev_row prev_row = tile if row == 0: # New Head of Column self.cols[column] = tile else: prev_col.next_node_in_col = tile tile.prev_node_in_col = prev_col prev_col = tile def print_by_rows(self): for col, the_column in enumerate(self.cols): print(the_column.id) if the_column.next_node_in_row is not None: node = the_column.next_node_in_row while node.next_node_in_row is not None: print(node.id) node = node.next_node_in_row def print_by_row(self): for row in self.rows: print(row.id) if row.next_node_in_row is not None: node = row.next_node_in_row while node.next_node_in_row is not None: print(node.id) node = node.next_node_in_row def print_by_col(self): for col in self.cols: print(col.id) if col.next_node_in_col is not None: node = col.next_node_in_col while node.next_node_in_col is not None: print(node.id) node = node.next_node_in_col def draw_grid(self): import time sep = '?????????????????' f = '??' l = '??' row = sep + '\n?' last_col = None current_col = None val = None for node in self.tile_list: if node.value == None: val = l else: val = f current_col = node.id.split(',')[1] if last_col is None: row += val elif current_col == last_col: row += val else: row += '\n' + sep + '\n?' + val last_col = node.id.split(',')[1] row += '\n' + sep print(row) #time.sleep(1) temp = GameGrid() temp.make_grid_nodes() #temp.draw_grid() temp.print_by_row() print('BREAK Now COLUMNS') temp.print_by_col() On 12/25/2014 12:31 AM, Danny Yoo wrote: > What are the _operations_ you want to support? Can you say more about this? I need to support lookups, no insertions or deletions are required. This code will be used to quickly lookup nodes, and check for specific patterns by checking the nodes values in either a row or column. The code to perform the pattern matching was already written and is fast, but I will add it to the code once the creation On 12/24/2014 04:56 PM, Steven D'Aprano wrote: > Wow. It certainly is bloated. Agreed. > Look for the opportunity to write code like this instead of using range: > > for col, the_column in enumerate(self.columns): > self.columns[col] = process(the_column) This caught my eye, and I did try to implement it. But why use this instead of range? I am using Python3. I did find that enumerate is potentially faster but sometimes slower, as it depends on what is being done. Perhaps because it is considered more Pythonic? So what is your reason for this suggestion? > Any time you write more than a trivial amount of code twice, you should > move it into a function. Then, instead of: I agree, should have done, and need to look for these opportunities sooner. From dyoo at hashcollision.org Tue Dec 30 20:37:13 2014 From: dyoo at hashcollision.org (Danny Yoo) Date: Tue, 30 Dec 2014 11:37:13 -0800 Subject: [Tutor] Making Doubly Linked List with Less Lines of Code. In-Reply-To: <54A2F355.9050607@gmail.com> References: <549B318A.8030909@gmail.com> <54A2F355.9050607@gmail.com> Message-ID: >> What are the _operations_ you want to support? Can you say more about >> this? > > I need to support lookups, no insertions or deletions are required. This > code will be used to quickly lookup nodes, and check for specific patterns > by checking the nodes values in either a row or column. As it stands, I believe you want these operations: * Construct a game grid with a certain number of rows and columns * Find a tile within the grid, given its row and column. * Given a tile in the grid, find the neighboring tiles around it. If that's the case, then none of this requires linked list storage. Instead, we can represent this as a list of rows. Each row element would be itself a list of tiles. In short, a matrix. See: https://docs.python.org/2/faq/programming.html#how-do-i-create-a-multidimensional-list Its construction wouldn't be too bad. Something like: self.rows = [[None] * self.num_of_cols for i in range(self.num_of_rows)] Finding a tile (i, j) in such a structure would be direct list indexing. self.rows[i][j] And finding neighboring tiles also wouldn't be too bad: Given a tile at (i, j), we can find its neighbors through arithmetic (i plus or minus one, j plus or minus one). If the game grid were a lot more dynamic and non-squarish, then that might make it appropriate. Linked lists give us a flexible way to represent such a game board. But at the moment, I think it's overkill for the scenario you're showing us. Good luck! From wolfrage8765 at gmail.com Tue Dec 30 23:40:04 2014 From: wolfrage8765 at gmail.com (wolfrage8765 at gmail.com) Date: Tue, 30 Dec 2014 17:40:04 -0500 Subject: [Tutor] Making Doubly Linked List with Less Lines of Code. In-Reply-To: References: <549B318A.8030909@gmail.com> <54A2F355.9050607@gmail.com> Message-ID: On Tue, Dec 30, 2014 at 2:37 PM, Danny Yoo wrote: > If that's the case, then none of this requires linked list storage. > > Instead, we can represent this as a list of rows. Each row element > would be itself a list of tiles. In short, a matrix. See: > https://docs.python.org/2/faq/programming.html#how-do-i-create-a-multidimensional-list True, I could use a multidimensional list. And originally I was using a 2D list. But I wanted the ability to quickly search across a row or up and down a column and so the added benefit of the linked list was that it simply requires me to access the next node reference. > > And finding neighboring tiles also wouldn't be too bad: Given a tile > at (i, j), we can find its neighbors through arithmetic (i plus or > minus one, j plus or minus one). From a coding perspective the linked list seemed simplier, because my other 2D list implementation required me to have a function that could map from any position to North, South, East, & West, plus it needed to perform bounds checking. Of course having the list now be doubly linked has added complexity. > > If the game grid were a lot more dynamic and non-squarish, then that > might make it appropriate. Linked lists give us a flexible way to > represent such a game board. But at the moment, I think it's overkill > for the scenario you're showing us. That may be True. I would like to know, if you know, would this doubly linked list be more or less memory efficient than the 2D list method and which one would provide faster look-ups? I do know that the doubly linked list has an initial speed cost in constructing it, which is obviously more than the 2D list. The overall application to which this code will be applied is a Kivy App that will be deployed to mobile devices, that is why I have these questions, although I realize this is pre-optimizing which is the root of evil... From akleider at sonic.net Wed Dec 31 06:41:33 2014 From: akleider at sonic.net (Alex Kleider) Date: Tue, 30 Dec 2014 21:41:33 -0800 Subject: [Tutor] Making Doubly Linked List with Less Lines of Code. In-Reply-To: References: <549B318A.8030909@gmail.com> <54A2F355.9050607@gmail.com> Message-ID: On 2014-12-30 14:40, wolfrage8765 at gmail.com wrote: > > True, I could use a multidimensional list. And originally I was using > I wanted the ability to quickly search across a row or > up and down a column and so the added benefit of the linked list was > that it simply requires me to access the next node reference. This problem interested me right from when it was first posted a few days ago so I tried to code up a solution to what I perceived it (the problem) to be. In the process of doing so I discovered that list multiplication does not at all behave the way I expected (as demonstrated by the 'bad_flip_2_D' function.) Code follows; comments appreciated. (Since the issue now is list multiplication, should this fork into a new subject?) # script begins here: #!/usr/bin/env python3 # file: 'two_D_list.py' """ OP: But I wanted the ability to quickly search across a row or up and down a column and so the added benefit of the linked list was that it simply requires me to access the next node reference. My interpretation/comments: Required are methods to access/search along column or row. Assume 2D list already exists. Can we further assume that all rows are the same length? Using a class might be the preferable way to go but leave that for later refactoring. Assume everyone assumes 0 based numbering. """ two_D = [ [0, 1, 2, 3], [4, 5, 6, 7], [8, 9, 10, 11] ] # For testing purposes. def get_n_rows(array): """Returns length of the array == number of rows.""" return len(array) def get_n_columns(two_D_array): """Returns the length of the first (zero'th) row. We assume all rows are the same length.""" return len(two_D_array[0]) def search_row(two_D_array, row_num, item): """Returns None if not there, else it returns the indices of the first instance of item found in the row specified. Not tested.""" try: col_num = two_D_array[row_num].index(item) return (row_num, col_num) except ValueError: return None def show_array(array): for row in range(len(array)): for col in range(len(array[row])): entry = array[row][col] if not entry: entry = 0 print("{:>3}".format(entry), end='') print() print() def flip_2_D(two_D_array): """Flips a two dimensional array so columns become rows and the rows become columns.""" ret = [] for i in range(get_n_columns(two_D_array)): ret.append([]) for j in range(get_n_rows(two_D_array)): ret[i].append([]) for i in range(get_n_rows(two_D_array)): for j in range(get_n_columns(two_D_array)): temp = two_D_array[i][j] # print("putting {} into ({}, {})." # .format(temp, j, i)) ret[j][i] = temp # show_array(ret) # For debugging purposes. return ret def bad_flip_2_D(two_D_array): """Flips a two dimensional array so columns become rows and the rows become columns. Demonstrates unexpected (by me) results of array multiplication.""" ret = [[[0]] * get_n_rows(two_D_array)] * get_n_columns(two_D_array) for i in range(get_n_rows(two_D_array)): for j in range(get_n_columns(two_D_array)): temp = two_D_array[i][j] print("putting {} into ({}, {})." .format(temp, j, i)) ret[j][i] = temp show_array(ret) # For debugging purposes. return ret def search_col(two_D_array, col_num, item): """Returns None if not there, else it returns the indices of the first instance of item found in the column specified. Simply reconstruct the array and then use search_row.""" flipped = flip_2_D(two_D_array) return search_row(flipped, col_num, item) if __name__ == "__main__": print("Running Python3 script: 'two_D_list.py'.......") print(get_n_rows(two_D), get_n_columns(two_D)) print show_array(two_D) show_array(flip_2_D(two_D)) # end of script Other possibly required info: alex at x301:~/Python/Tutor$ uname -a Linux x301 3.13.0-43-generic #72-Ubuntu SMP Mon Dec 8 19:35:44 UTC 2014 i686 i686 i686 GNU/Linux cheers, Alex From coolshwetu at gmail.com Wed Dec 31 11:08:05 2014 From: coolshwetu at gmail.com (shweta kaushik) Date: Wed, 31 Dec 2014 15:38:05 +0530 Subject: [Tutor] Convert string to bytes Message-ID: Hi all, I need help on this problem. I have one message packet in form of string s = '0xFE, 0x01, 0x01, 0x22, 0xFE, 0x02'. I have to send this data to MSP430 microcontroller, but it is not taking data if it is string. If I am passing this as hardcoded value s1 = 0xFE, 0x01, 0x01, 0x22, 0xFE, 0x02 then board is responding. I want to convert s as s1 using python. Please help me out to convert string in normal format for microcontroller to respond. Thanks in advance. Regards, Shweta From tgmiller5 at hotmail.com Wed Dec 31 14:49:17 2014 From: tgmiller5 at hotmail.com (Tammy Miller) Date: Wed, 31 Dec 2014 08:49:17 -0500 Subject: [Tutor] Help on Python drop-down list options Message-ID: 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 From wolfrage8765 at gmail.com Wed Dec 31 17:31:14 2014 From: wolfrage8765 at gmail.com (WolfRage) Date: Wed, 31 Dec 2014 11:31:14 -0500 Subject: [Tutor] Help on Python drop-down list options In-Reply-To: References: Message-ID: <54A424D2.20709@gmail.com> 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 at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor From wolfrage8765 at gmail.com Wed Dec 31 17:34:35 2014 From: wolfrage8765 at gmail.com (WolfRage) Date: Wed, 31 Dec 2014 11:34:35 -0500 Subject: [Tutor] Convert string to bytes In-Reply-To: References: Message-ID: <54A4259B.2000005@gmail.com> I wrote a program to help me break out hex strings awhile ago. It was written to communicate with a Atmega 168. This is written for Python 3. Here is a snippet, see if this helps you. s4 = "28 40 7A 7C 05 00 00 34" hex_array = bytearray.fromhex(s4) print(s4) print(list(hex_array)) print(hex_array) for byte in list(hex_array): print(hex(byte)) print(bytes([byte])) On 12/31/2014 05:08 AM, shweta kaushik wrote: > Hi all, > > I need help on this problem. > > I have one message packet in form of string s = '0xFE, 0x01, 0x01, 0x22, > 0xFE, 0x02'. I have to send this data to MSP430 microcontroller, but it is > not taking data if it is string. If I am passing this as hardcoded value s1 > = 0xFE, 0x01, 0x01, 0x22, 0xFE, 0x02 then board is responding. I want to > convert s as s1 using python. > > Please help me out to convert string in normal format for microcontroller > to respond. > > Thanks in advance. > > Regards, > Shweta > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor From alan.gauld at btinternet.com Wed Dec 31 18:51:25 2014 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 31 Dec 2014 17:51:25 +0000 Subject: [Tutor] Help on Python drop-down list options In-Reply-To: References: Message-ID: 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 From alan.gauld at btinternet.com Wed Dec 31 18:57:33 2014 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 31 Dec 2014 17:57:33 +0000 Subject: [Tutor] Convert string to bytes In-Reply-To: References: Message-ID: On 31/12/14 10:08, shweta kaushik wrote: > I have one message packet in form of string s = '0xFE, 0x01, 0x01, 0x22, > 0xFE, 0x02'. I have to send this data to MSP430 microcontroller, but it is > not taking data if it is string. If I am passing this as hardcoded value s1 > = 0xFE, 0x01, 0x01, 0x22, 0xFE, 0x02 then board is responding. I want to > convert s as s1 using python. I'm pretty sure you don;t need that, you only need the integer values of the hex strings. You can then write those integers directly to your controller. Assuming I'm right this should work (Python v2.7): >>> s = '0xFE, 0x01, 0x01, 0x22, 0xFE, 0x02' >>> [int(h,16) for h in s.split(',')] [254, 1, 1, 34, 254, 2] >>> 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 From alan.gauld at btinternet.com Wed Dec 31 19:53:25 2014 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 31 Dec 2014 18:53:25 +0000 Subject: [Tutor] Convert string to bytes In-Reply-To: References: Message-ID: <54A44625.3070707@btinternet.com> On 31/12/14 18:03, shweta kaushik wrote: > I also did the same thing and its working... but i dint use this. I > just did this and it is similar to what you said. > > >>> s = '0xFE, 0x01, 0x01, 0x22, 0xFE, 0x02' > >>> packet = eval(s) > (254, 1, 1, 34, 254, 2) > >>> > this is tuple, which my microcontroller is able to recognize and > respond back. It works with a fixed string input but using eval() is a big security risk, especially if you read the input from a file or network or even a user. You could potentially find your hard disk being formatted or similar damage. An explicit conversion using int() is much safer. -- 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 From coolshwetu at gmail.com Wed Dec 31 19:03:36 2014 From: coolshwetu at gmail.com (shweta kaushik) Date: Wed, 31 Dec 2014 23:33:36 +0530 Subject: [Tutor] Convert string to bytes In-Reply-To: References: Message-ID: Hi Alan, Thank you.. I also did the same thing and its working... but i dint use this. I just did this and it is similar to what you said. >>> s = '0xFE, 0x01, 0x01, 0x22, 0xFE, 0x02' >>> packet = eval(s) (254, 1, 1, 34, 254, 2) >>> this is tuple, which my microcontroller is able to recognize and respond back. Regards, Shweta On Wed, Dec 31, 2014 at 11:27 PM, Alan Gauld wrote: > On 31/12/14 10:08, shweta kaushik wrote: > > I have one message packet in form of string s = '0xFE, 0x01, 0x01, 0x22, >> 0xFE, 0x02'. I have to send this data to MSP430 microcontroller, but it is >> not taking data if it is string. If I am passing this as hardcoded value >> s1 >> = 0xFE, 0x01, 0x01, 0x22, 0xFE, 0x02 then board is responding. I want to >> convert s as s1 using python. >> > > I'm pretty sure you don;t need that, you only need the integer values of > the hex strings. You can then write those integers directly to your > controller. Assuming I'm right this should work (Python v2.7): > > >>> s = '0xFE, 0x01, 0x01, 0x22, 0xFE, 0x02' > >>> [int(h,16) for h in s.split(',')] > [254, 1, 1, 34, 254, 2] > >>> > > 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 at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor >