[Tutor] Question about a python finction
Hello, Is there a function that allows you to grab the numbers between two numbers? Eg. If you input the numbers 1 and 4 To make a list like this [1,2,3,4] Thank you for you’re time Sent from my iPhone ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] The game of nim in python
Python to Jython. Can you help me with a Jython code for the Nim game? Removing 1-4 sticks out of 13, last player who picks up the last stick wins Player 1 vs player2(Computer) player1=str(input("Enter your name. ")) player2="Computer" howMany=0 gameover=False strawsNumber=random.randint(10,20) if (strawsNumber%4)==1: strawsNumber+=1 def removingStrawsComputer(): removedNumber=random.randint(1,3) global strawsNumber while removedNumber>strawsNumber: removedNumber=random.randint(1,3) strawsNumber-=removedNumber return strawsNumber def removingStrawsHuman(): global strawsNumber strawsNumber-=howMany return strawsNumber def humanLegalMove(): global howMany legalMove=False while not legalMove: print("It's your turn, ",player1) howMany=int(input("How many straws do you want to remove?(from 1 to 3) ")) if howMany>3 or howMany<1: print("Enter a number between 1 and 3.") else: legalMove=True while howMany>strawsNumber: print("The entered number is greater than a number of straws remained.") howMany=int(input("How many straws do you want to remove?")) return howMany def checkWinner(player): if strawsNumber==0: print(player," wins.") global gameover gameover=True return gameover def resetGameover(): global gameover gameover=False return gameover def game(): while gameover==False: print("It's ",player2,"turn. The number of straws left: ",removingStrawsComputer()) checkWinner(player1) if gameover==True: break humanLegalMove() print("The number of straws left: ",removingStrawsHuman()) checkWinner(player2) game() ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
[Tutor] (no subject)
Hi, Total beginner to python and am working my way through Michael Dawsons 'Absolute beginner' book. Just got stuck on the last bit of the challenges from chapter 3. Essentially need to create a game where the user picks a number between 1 and 100 and the computer has to guess, program should indicate to the computer if the guess need to be higher or lower, it should also count the number of attempts and call a halt to the game if a set number of attempts is reached. The highlighted bit is where I think I'm going wrong but I just can't think how to make the computer remember the previously closest highest and lowest guesses, not sure if you have all read Micheal Dawsons book but I've not covered a whole lot by chapter 3 and so any hints/solutions need to be pretty basic as I don't want to get ahead of myself. Thanks, Kevin #numbers game again but... #user picks number between 1 and 100 #and computer guesses import random user_number = int(input(Pick a number between 1 and 100: )) computer_guess = random.randint(1, 100) guesses = 1 while computer_guess != user_number: print(The computers guess is, computer_guess) if computer_guess user_number: print(Lower...) else: print(Higher...) if guesses == 10: print(You lose computer!) break if computer_guess user_number: computer_guess = random.randrange(1, (computer_guess-1)) else: computer_guess = random.randint((computer_guess + 1), 100) guesses += 1 if computer_guess == user_number: print(Well done you guessed the number was, user_number) print(It took you, guesses, tries) input(Press the enter key to exit.) ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Tutor Digest, Vol 123, Issue 27
Alan and Steven, Many thanks for both your help. *Alan* Although I understand that the method you described is the most efficient way of guessing a random number, I was trying so that my program would have the computer making repeated random guesses between a decreasing range of its last two closest guesses. That is if the user chooses 55 as the number and the computers first guess is 98 then its next guess would be between 1 and 97, if the 2nd guess was 23 the 3rd guess would between 24 and 97, if the 4th guess was 50 then the 5th guess would be between 51 and 98, the 6th guess being 60 then the 7th guess would be between 51 and 59, etc etc. I was hoping that this may mean the computer won't get it every time in 10 guesses and be a bit more as a human might guess (at least the first few times they played before they cottoned on to the method you described). And thank you for the bug spot! Also yes there is a typo in that I didn't mean to have have that random.randrange in there ( was meant to be a randint) *Steven* Thank you for the info re highlighting! Yes I think your example below describes what I was trying to do, E.g. suppose you pick the number 50, and the computer guesses 25. Since this is the first guess, it's automatically the closest. Then the computer guesses 60. Since 60-50 = 10 is smaller than 50-25 = 25, 60 is the closest. Then the computer guesses 30. Since 50-30 = 20 is greater than 10, 60 remains the closest. Am I on the right track? Assuming I am, how might I program this? The first thing is to have a variable that holds the closest value: closest = ... what? Here's a trick. Since we know that the guesses are always between 1 and 100, if we set the first closest to something greater than 100, the first guess will always count as closer! So: closest = Then, as you check each guess: if abs(computer_guess - user_number) abs(closest - user_number): # this guess is closer than the previous closest closest = computer_guess But (just to clarify) as I put the simple example you gave through the code you supplied I get a little confused as it doesn't seem to save the closest? For example this is how i worked it: if (25 - 50) ( - 50) closest = 25 if (60-50) (25 - 50) closest = 25? As you stated for yor example a guess of 60 would be closer than the guess of 25. As I said I really am a beginner and I apologise if my questions are frustrating but I do appreciate any help offered. Thanks again. Kevin On Thu, May 8, 2014 at 2:02 PM, tutor-requ...@python.org wrote: Send Tutor mailing list submissions to tutor@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-requ...@python.org You can reach the person managing the list at tutor-ow...@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: Final review (Steven D'Aprano) 2. Re: (no subject) (Alan Gauld) 3. Re: (no subject) (Steven D'Aprano) 4. Re: How inefficient is this code? (Neil D. Cerutti) 5. Re: PyCountry currency formatting woes (Sithembewena Lloyd Dube) -- Message: 1 Date: Thu, 8 May 2014 23:30:49 +1000 From: Steven D'Aprano st...@pearwood.info To: tutor@python.org Subject: Re: [Tutor] Final review Message-ID: 20140508133048.GF4273@ando Content-Type: text/plain; charset=utf-8 On Wed, May 07, 2014 at 08:49:11PM -0700, Scott W Dunning wrote: [...] greeting [len(greeting)] It is trying to access the character at the position 11, where the string Hello world doesn't contain any value in the index 11 and the maximum index is 10. So it throws the following error. I think this is where I am getting confused. I guess I don?t understand why/how it?s trying to access the character at the index 11? The value of greeting is Hello world. So let's write it out, showing the index of each character. Remember that Python starts counting from zero, not one: Index 0: H Index 1: e Index 2: l Index 3: l Index 4: o Index 5: space Index 6: w Index 7: o Index 8: r Index 9: l Index 10: d So the indexes start from 0, and go up to 10. How many characters are there? Count them, and you get 11. Which makes sense: one character per index, there are at least ten indexes (1 through 10), plus one extra (index 0) makes 11. So the length of the string is 11, but the highest index is 10. So greeting[0] gives H, greeting[1] gives e, greeting[2] gives l, and so on, until you get to greeting[10] which gives d, and greeting[len(greeting)] = greeting[11] which is an error. -- Steven -- Message: 2 Date: Thu, 08 May 2014 14:46:10 +0100 From: Alan Gauld alan.ga...@btinternet.com
[Tutor] cx_freeze windows 7 python 3.3
I am new to this site so please forgive me if I am forwarding this question to the wrong person. I am trying to use cx_freeze on windows 7 with python 3.3. I can create a build folder and a dist folder using the command line without any problems. When I click on the created .exe file I receive the following error:- Cannot import traceback module. Exception:cannot import name MAXREPEAT Original Exception:cannot import name MAXREPEAT I have looked for a solution but cannot find one. Can anyone please help. Thanks Kevin___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
[Tutor] Please help with beautifulsoup and web scraping
http://stackoverflow.com/q/18974172/2390312 ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] How to make a python script run on startup
anybody know how to do this on linux? On 4/9/13, eryksun eryk...@gmail.com wrote: On Tue, Apr 9, 2013 at 5:54 AM, Alexander Mark rhettna...@gmail.com wrote: There is a startup folder, usually on the start menu, you can add the script to. current user: %USERPROFILE%\Start Menu\Programs\Startup all users: %ALLUSERSPROFILE%\Start Menu\Programs\Startup Updating the latter will probably require elevation, which you do via ShellExecute with the runas verb, using either pywin32 or ctypes. If you don't want a console use the .pyw extension. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] Matplotlib Slider Widget and changing colorbar threshold
I am currently trying to work on a program that will allow the user to display their dataset in the form of a colormap and through the use of sliders, it will also allow the user to adjust the threshold of the colormap and thus update the colormap accordingly. The best to describe this would be through the use of a picture: [1]: http://i.stack.imgur.com/1T9Qp.png This image shows how the colorbar should look before (the image on the left) and after (the image on the right) the adjustment. As the threshold values of the colrobar are changed, the colormap would be updated accordingly. Now I am mainly using matplotlib and I found that matplotlib does support some widgets, such as a slider. However the area I need help in is devising a piece of code which will update the colorbar and colormap (like the way shown in the picture above) when the slider is adjusted. I was wondering if anyone has done this before and might have a piece of code they would be willing to share and might have pointers as to how this can be achieved. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] help, complete beginner please!
Hi all! I'm trying to write a basic text adventure game to start learning python (just for fun). I've gone through the first four chapters of a learn python game programming book and I'm having trouble with the exercise on writing a text adventure. I've been piecing together what is in the book with some examples I found online. My goal with this question is not to necessarily make the code I've written work, but to gain a fundamental understanding of the concepts. Can someone show me how to organize a text-based game with these things kept in mind: 1)Each room will be a function 2)Direction(N,S,E,W) 3)Look at 4)Pick Up 5)Quit 6)Accumulated Gold Coins 7) Find all the Gold 8)Win/Lose I'm looking for the simplest version of this as possible, because I'm having trouble with the concepts. I'm only showing my code to give you an idea where I'm at. However, I would really like someone to lay out a little code structure for me. I'm using Python 2.6.5 on a Mac Version 10.4.11 and don't consider myself computer literate, so bear with my ignorance please. Also, don't feel like you have to correct my code...please just create your own example of code structure to get me on the right track. Here is the start of my game: FirstGame.py First try at creating a text-based adventure game. Trying to learn the basics of creating functions and using if and loops. kevin: 8/27/10 keepGoing = True while keepGoing == True: global gold gold = 0 def RoomOne(): print You find yourself in a large room. Above you is a massive crystal print chandelier. In front of you is round stone fountain, spewing water print from it's center. On the walls hang green satin drapery. The ceiling print is comprised of three ornate arches. There is an arch in front of you print and to your right and left. A staircase leads up from under the arch print in front of you. Under the arches to your left and right are large wooden print doors, each with an iron handle. Enter 'Help' for a full list of commands. RoomOne() Command = raw_input(Please enter a command. ) Command = Command.upper() if Command == N: RoomFour() elif Command == S: print You ditched the creepy castle and headed for the road. keepGoing == False elif Command == E: RoomTwo() elif Command == HELP: print List of Commands: 'Help',then enter for this list. print 'N', then enter = Door to the North. print 'S', then enter = Door to the South. print 'E', then enter = Door to the East. print 'W', then enter = Door to the West. print 'Look at', then 'objects name', then enter = Looks at an object. print 'Pick Up', then 'objects name', then enter = Picks up an object. print 'Q', then enter = Quit Game. elif Command == W: RoomSix() elif Command == LOOK AT FOUNTAIN: print There appears to be 4 gold coins in it. elif Command == PICK UP 4 GOLD COINS: gold = gold + 4 print Current Gold = , gold elif Command == Q: keepGoing = False else: print That doesn't work. def RoomTwo(): print Current Gold = , gold print In the middle of the room is a large Gargoyle with fiery red eyes. print He's holding a cup. In the southeast corner of the room you see a broom print with dust and cob-webs on it. Next to the broom is a dead rat. print To the north is another door. In front of the door is an overturned basket. promptTwo = raw_input(What are you going to do? ) promptTwo = promptTwo.upper() if promptTwo == N: RoomThree() elif promptTwo == S: print There is no door there. elif promptTwo == W: RoomOne() elif promptTwo == E: print There is only a wall there. elif promptTwo == Q: keepGoing = False elif promptTwo == PICK UP BASKET: print You pick up the basket, revealing 2 gold pieces. RoomTwo() elif promptTwo == PICK UP 2 GOLD COINS: gold = gold + 2 print Current Gold = , gold RoomTwo() elif promptTwo == LOOK AT GARGOYLE: print Looking at the Gargoyle you notice he's really mean, and really still. RoomTwo() elif promptTwo == LOOK AT BROOM: print Looking at the broom, you notice it's unnecessarity dirty. elif promptTwo == PICK UP BROOM: print You pick up the broom. But you don't notice anything special, so you print set it back down where it was. elif promptTwo == LOOK AT CUP: print You look at the cup, and find nothing of interest. elif promptTwo == LOOK AT DEAD RAT: print You look at the dead rat and find it utterly disgusting. elif promptTwo == HELP: print
Re: [Tutor] Running .py files in shell
I am running Mac OSX v10.6.4 Snow Leopard I am running Python 2.6.1 In general get the MacPython distributions of Python etc, they usually install easier (ie from the GUI) than the Unix based versions. Okay, thanks. I will look into that. 1. How do I execute .py files in the command line shell? I have my files in /Users/Kevin/python-exercises/ and am opening python in shell from that directory There are numerous ways, especially in MacOS. The simplest way is to put a shebang line at the top of your script and then make them executable: $ cat myscript.py What is the significance of this and how do I use it? I guess this is a command to add in to Shell, however when I use this I get the following error: cat tryme1.py Traceback (most recent call last): File stdin, line 1, in module NameError: name 'cat' is not defined #! /bin/env python With my configuration, I am guessing I need to change this snippet to: #! /opt/local/Library/Frameworks/Python.framework/Versions/2.6/bin python # the above line must be the first line in your file and tells the # shell where to find python # rest of your code follows. Then use chmod +x to make it executable $ chmod +x myscript.py When I try to run this with one of my files I get the following error: chmod +x tryme1.py File stdin, line 1 chmod +x tryme1.py ^ SyntaxError: invalid syntax Now you can run it: $ myscript.py Alternatively you can just call python explicitly: $ python myscript.py I get a syntax error doing this too: python tryme1.py File stdin, line 1 python tryme1.py ^ SyntaxError: invalid syntax ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] Running .py files in shell
Hello all, I am new to programming and have opted to learn Python as I hear it is a good first language. I am currently going through the exercises in 'How to Think Like a Computer Scientist: Learning with Python 2nd Edition'. I am running Mac OSX v10.6.4 Snow Leopard I am running Python 2.6.1 I have a couple of questions: 1. How do I execute .py files in the command line shell? I have my files in /Users/Kevin/python-exercises/ and am opening python in shell from that directory 2. How do I install GASP which is referenced in chapter 4? The instructions in this book are not complete. I have researched and found a reference on Stack Overflow which is contributed to by GASP programmers http://stackoverflow.com/questions/1024862/how-do-i-install-gasp-for-python-2-6-2-on-a-mac I have MacPorts installed and have attempted to install PyObjC, which is referenced as a prerequisite to PyGame and GASP. I get the following error when attempting to install PyObjC: sudo port install py-pyobjc Password: --- Computing dependencies for py-pyobjc --- Fetching py-pyobjc Error: Target org.macports.fetch returned: PyObjC 1.4 is for Mac OS X 10.4 and lower. On 10.5, use py-pyobjc2 instead. Log for py-pyobjc is at: /opt/local/var/macports/logs/_opt_local_var_macports_sources_rsync.macports.org_release_ports_python_py-pyobjc/main.log Error: Status 1 encountered during processing. It says to use py-objc2 instead, so I do so and get this error: sudo port install py-pyobjc2 Error: Target org.macports.activate returned: Image error: /opt/local/lib/python2.4/site-packages/modulegraph/__init__.py is being used by the active py-modulegraph port. Please deactivate this port first, or use 'port -f activate py-modulegraph-devel' to force the activation. Log for py-modulegraph-devel is at: /opt/local/var/macports/logs/_opt_local_var_macports_sources_rsync.macports.org_release_ports_python_py-modulegraph-devel/main.log Error: The following dependencies failed to build: py-py2app-devel py-modulegraph-devel Error: Status 1 encountered during processing. To report a bug, see http://guide.macports.org/#project.tickets I attempted to correct the issue by entering the following: port -f activate py-modulegraph-devel But it returned this error: Warning: Failed to open Portfile from registry for py-modulegraph-devel @0.7.2_0 --- Activating py-modulegraph-devel Error: port activate failed: sqlite error: attempt to write a readonly database (8) This is as far as I have got with resolving this issue so far. All help and guidance will be greatly appreciated. Kevin Rapley ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] Any
Hi all, I was just wondering if anyone here can recommend any freeware program that has been written in python and for which the source code is available. Basically I just want to see a program that does something relatively simple and straightforward, but something that is real world, I mean something that people actually use, hopefully something that comes with it's own installer and GUI. I'd like to try out using the program as an ordinary user and then I want to look at the source code to see how it's been achieved. Any ideas or suggestions? Kevin Kirton Australia ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Any
Christian Witts wrote: Maybe look through projects at Freshmeat [1]. [1] http://freshmeat.net/tags/python That's exactly what I was looking for. I've already selected a few small programs and now I plan on installing them, seeing how they operate from a user's perspective, then I'll take a look at the source code and see what I can work out. Thanks very much. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Any
Alan Gauld wrote: But if thats not enough try both sourceforge and the PyGame web sites. On sourceforge search for projects using python... DIA is one that springs to mind(a Visio type drawing program) PyGame has lots of Python games you can download, several with source. PyGame looks promising (very distracting too). DIA in itself looks quite useful and interesting, so I might learn that as a user then see if I can look through its code. Thanks for your help. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] automatic output file naming scheme
okay. I got the subprocess bit to work and i have os walk doing its walk. But now for something i did not think about until i started to think about how to fit these two bits to work together. os walk is going to traverse my dirs from some given starting point and process files that it finds that fit my criteria. So i my case it will look for all sound files in a given directly structure and then call sox and do a conversion. This part i can already probably do just by combining the working code that i have … but now i need to have some kind of automagic naming scheme that creates an output file name that is based on the input name but is unique, either adding a number or suffix before the file extension, or even a time stamp. Since we want to create file names that are unique and not clobber existing files, but also will tells us something meaningful about how the file was created so that finding: foo01.aif or foo.1.aif would yield something like foo-out01.aif or foo01-out.aif or something similar. How can you do such a thing in python? is there some elegant way to take the input file name and combine it with some other string to create the output file name? -kp ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] subprocess
I tried readings some toots and tried reading alan's thing. I just still can't grok how to use subprocess. I am trying to call sox (fun fact: an early contributer to sox was none other than Guido van Rossum) In the old days you would just use os i guess, like: import os os.system('sox -V3 -D -S St.01.aif -b16 Stout-01.aif rate -s -v 44100') to call a unix executable that you would ordinarily run from the terminal. what would the equivalent of this in python's new subprocess be? perhaps if i saw an example it would click.. additionally.. sox is a sound conversion tool. I plan to batch process a bunch of files. Will subprocess start all the jobs as it finds the files? or will it process one job and que the next? If it opened a thread and started a bunch of jobs it would likely bog down the system no? anyway I have the os walk and other stuff that i am working on and i was hoping to get some help on subprocess. There are a few pages on subprocess but they all might just as well be in chinese and none of them, none that i can see are equivalent to what i am trying to do (they all seem to be doing os-y things) An example might help. Not sure why i am finding this so hard to get my head around. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] Self-intro and two short newbie questions
Hi all, I've committed myself to learning Python and have started reading Learning Python (Mark Lutz) and looking through various online resources. My career so far has involved a little high school teaching and about 10 years of translating Japanese to English, but no programming or coding. I've also joined this list today and this is my first post. My aim is to be able to create Python programs, specifically activities that work on the OLPC's XO laptops and SoaS (Sugar on a Stick). My questions are: how long would you estimate it to take and how complicated would it be to create the following as Python programs? (I know it varies depending on the person, but for example, how long would it take _you_?) (i) a simple guitar tuning program involving an image of a guitar and the playing of each of the standard strings of a guitar (E, A, D, G, B, E) upon key input by the user (something similar to this: http://www.gieson.com/Library/projects/utilities/tuner/ (page is 782kb to open)) and (ii) a very basic turtle art program with an intentionally limited set of commands and on-screen display words (say, a total of 30 to 50 specific strings), wherein the entire set of strings is offered to the user (perhaps at first use of the program) in a format that enables easy and full localization of the program so long as each of the strings is translated appropriately and inputted to the program. I know of turtle.py and xturtle.py, but I'm thinking of starting something from scratch. It's the easy localization I'm interested in. Hope these questions are appropriate. I'm grateful to be able to ask them here. Kevin (in Australia) ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Self-intro and two short newbie questions
Thanks very much for the responses. I feel encouraged now to try to create the guitar tuner program by myself first, and then the simple turtle art program after that. It's kind of both exhilarating and daunting that I don't know exactly where to start at the moment, but that's the fun of learning I guess. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] batch file processing w/ python using cmd line executable?
hi I am new territory here and not even sure where to start poking around other than the os module some. Essentially i need to do something like a shell script for batch processing gobs of files. I am trying to use a command line tool (sox, an open source sound file converter that runs from the unix command line) and I don't want to edit the command line, run the job, edit the command line, etc over and over again for hundreds of small files. I wonder if it is possible to use python to call sox and have it do os.mkdir, process all the input files in a particular directory and put the converted files into the directory it made with mkdir... so if i had kp/flute/ST kp8/flute/ST/foo01.aif kp8/flute/ST/foo02.aif kp8/flute/ST/foo03.aif kp8/flute/ST/foo04.aif kp8/flute/ST/foo05.aif The script would call sox repeatedly and create a new dir with a converted file for each found in the original folder. like so: kp/flute/STout/ kp/flute/STout/foo01.wav kp/flute/STout/foo02.wav kp/flute/STout/foo03.wav kp/flute/STout/foo04.wav kp/flute/STout/foo05.wav what makes this especially hairy is that sox is a monster an typically needs a crazy number of arguments, though these would be the same for the whole batch. A typical command line call i need to make to, say, batch convert files from one sample rate and bit depth to another would look like so: % sox -V3 -D -S St.01.aif -b16 kp/flute/STout/St.01.wav rate -s -v 44100 Is there away to do this in python, by just pointing it to a whole dir of files and say do it to all of these? cheers, kevin ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] Automaton/transitional grammar query
I posted about this a couple weeks back, but then got horribly ill and dropped the ball so i was hoping to revisit. I am not sure if this is and example of Finite Automaton or a Finite State Machine or perhaps it is related to a transition table or markov process. I think some one here told me it is called a transitional grammar? I am not sure. I am not a math person but i would love to know exactly what this is. I googled around and got lots of super complicated gobbledegoo all with knotty regex stuff, but what i want to do is much more simple. I am trying to use a table to define a bunch of moves like so: 1 -- 2 5 2 -- 1 4 3 -- 3 4 -- 1 5 -- 4 3 so that i can generate a sequence that, given an initial value, that will continue to grow according to these rules. Starting with 1 we then go to 2 5, 2 leads us too 1 4, the 5 leads us to 4 3, then we iterate over 1 4 4 and 3 to get 2 5 1 1 and 3 Like so: 1 2 5 1 4 4 3 2 5 1 1 3 1 4 4 3 2 5 2 5 3 . etc. Essentially, iterating over the last added items to the list, applying the table, appending those new items to the list, applying the table again... etc, until the sequence reaches some predetermined number of iterations and quits. [ [1], [2, 5], [1, 4] , [4, 3], [2, 5], [1], [1], [3], [1, 4], [4, 3], [2, 5], [2, 5], [3] ] First, as i mentioned I would like to know what, precisely, this kind of process is called so that i can look it up. Second, i would l like to add to what i have, which seems to work. But first here is the code, where we left off below: #!/usr/bin/env python rules = {1: (2, 5), 2: (1, 4), 3: (3,), 4: (1,), 5: (4, 3)} def apply_rules(sequence): for element in sequence: # look it up in the global rules values = rules[element] # yield each of those in turn for value in values: yield value def flatten(l, ltypes=(list, tuple)): ltype = type(l) l = list(l) i = 0 while i len(l): while isinstance(l[i], ltypes): if not l[i]: l.pop(i) i -= 1 break else: l[i:i + 1] = l[i] i += 1 return ltype(l) def test(): data = [1] outlist = [] for i in range(10): outlist.append(data) gen = apply_rules(data) data = list(gen) outlist.append(data) # one more to get the final result print '\n\n', outlist, '\n\n' flat = flatten(outlist) count = 0 for item in flat: print count, ',', item, ';' count += 1 print '\n\n' if __name__ == __main__: test() This all appears to work. I am not sure if this is the best way to do it, but for the size lists i have been generating it seems zippy. So what? You are asking a question you already know the answer to? Well now I would like to have this set of rules contain some probabilistic branching. Instead of having my go to rules or grammar hard wired it would be good if some steps could also have weighted choices. So that maybe 1 -- 2 5 70% of the time but maybe it goes 1 -- 2 4 every once in a while (as in 30%). So i am not sure how to do that... also, it occurs to me that i could define a grammar that got stuck in an infinite loop if not careful. I wonder if i should add some mechanism to check the dictionary defined rules before execution or if that is just too hard to do and i should just be careful. Meanwhile I have my trusty old weighted random func all ready to go: import random def windex(lst): '''an attempt to make a random.choose() function that makes weighted choices accepts a list of tuples with the item and probability as a pair''' wtotal = sum([x[1] for x in lst]) n = random.uniform(0, wtotal) for item, weight in lst: if n lt; weight: break n = n - weight return item My question is how to apply this since i am setting up my rules in a dictionary, so I am confused as to how all these pieces, which work in isolation, would fit together. Lastly, if i add the probabilities... is this just a super roundabout way to make a quasi markov table? i dunno. But it seems like a cool way to make patterns. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Automaton/transitional grammar query
You might be interested in Steven Wolfram's book, A New Kind of Science and the many examples on his web site: http://www.wolframscience.com/ See Wikipedia as well. This is a very rich area. Thanks. That was just the kind of reference I was looking for. Fantastic. I am sure i wont be able to grok the math bits but maybe i can begin to understand thsese ideas on a conceptual level. I will look for this in the book store. When you introduce the random element you are generating Markov chains. That's what i thought. I would be interested in playing with some simple, 1st and 2nd order markov chains too, but i just want to define the transition tables with the elements and their probabilities and generate. Most of the Markov stuff i see out there is big and knotty and way more than i need. I don't understand why you want to flatten outlist; when I run your program I get one number per line, not one generation per line as you show above. That's odd. Anyway in my program I am printing the list twice. The first time outlist is printed it is nested one level deep. That is just scaffolding. Then i pick through it one item per line having flattened it and print it in a format that my other program can read. I been using that flatten function since 1970. Prolly pilfered from Tim Peters or Effbot. Remember them guys? Awesome dudes. I wonder if they even use python anymore. Anyway that is from way before itertools was even a glimmer. Additionally, your flatten function doesn't work for me actually. I get: NameError: global name 'chain' is not defined enumerate() is simpler: Thanks. enumerate is also still somewhat new to me. I don't think you will get an infinite loop. You may have a grammar that generates a stable or repeating pattern but I don't think you will be able to detect that without trying it. Yeah i don't mean an infinite loop, but more like a perpetual dance back and forth between to items that point to each other. I think I need to be careful when i define the rules that i don't get something like that... say if 1 goes to 4 but 4's rule is go to 1, for example. our rules, instead of being just a list of numbers, become a list of probability mappings. I think you want to apply the probabilities to the whole sequence, so a single rule might be (using your example) 1: [ ((2. 5), .7), ((2. 4), .3) ] Then change the apply_rules function to choose one of the possibilites using your windex() function. I'll roll this around in my pea sized brain and see if i can put this suggestion to work. Thanks Kent! Hopefully I will get this going and my psudo-markov thingy happening too. These things are fun for making patterns. I like these powerful little pea shooters. -kevin ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Automaton/transitional grammar query
On Oct 12, 2009, at 8:02 PM, Dave Angel wrote: Often, when a combination of existing stdlib collection types gets too confusing, it's time to consider classes and objects. Not necessarily to make the program object oriented, but to make the program data structure understandable. That's sage advice I just dislike and resist OO. But i do eventually need to make steps in that direction. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] need help with conditionals
On Sep 26, 2009, at 11:42 PM, Alan Gauld wrote: Kent Johnson ken...@tds.net wrote It appears to be http://openbookproject.net/thinkCSpy/ch04.html So it is, Thats a shame CSpy is one of my favourite competitors :-) Pity it's apparently encouraging the use of eval like this with no caveat. But to the OP, keep with it, its not a bad tutorial, shame about this exercise! Perhaps worth alerting the author? He's a nice guy and i e-mailed him many moons ago when i was working through that book with some concerns i had. He was really receptive and grateful to get feed back and was quick to make changes if he thought they would improv the text. A super good dude and it seems, a top notch educator. He tends to credit *everyone* who sends in a suggestion, no matter how minor. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] What is this an example of (and how can i use it?)
On Sep 21, 2009, at 9:52 AM, Kent Johnson wrote: Calling a generator function gives you something that can be iterated. You can create a list out of it (by passing it to the list() function) or you can iterate the items in it directly with a for loop. Using the example above, you could say for item in roundrobin('abc', [], range(4), (True,False)): print item I kinda understand conceptually what iterators and generators do and why they are a honking good idea (why create 100 of x when we just want the 100th, etc.) what i don't get is the syntax and how they are used in real life. How generator and iterators behave in the wild. It's really not that bad. They are just a generalization of what you have already been doing with lists. Even the Lutz is too terse and generally poor on these two complex and relatively new constructs. They are a dark and obscure magic. No, really they are not difficult. Read my essay and ask questions if you don't understand. Thanks. I have some time today and will read up on what you sent me and revisit the lutz and other docs. It appears it is not so impenetrable as i initially though. Well iterators aren't maybe, but generator do look tricky. So interators iterate over lists, tuples, strings, dictionaries and any data type that is iterable, and generators are ways to make new iterables? Anyway, i will brew some coffee and hit those links. Thanks, -kevin ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] What is this an example of (and how can i use it?)
I am afraid that in the long layoff in python has meant some new constructs have passed me by. In googling around I found some nice little code I want to use, but i don't quite understand it, how it is called, and what it is an example of. I guess there are generators and iterators now and it seems this might be an example of one of those new constructs. Can anyone explain what it is i am looking at, how it is called, and what it is an example of so that I can look it up: def roundrobin(*iterables): roundrobin('ABC', 'D', 'EF') -- A D E B F C # Recipe credited to George Sakkis pending = len(iterables) nexts = cycle(iter(it).next for it in iterables) while pending: try: for next in nexts: yield next() except StopIteration: pending -= 1 nexts = cycle(islice(nexts, pending)) ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] What is this an example of (and how can i use it?)
On Sep 21, 2009, at 1:32 AM, Alan Gauld wrote: kevin parks wrote: called, and what it is an example of. I guess there are generators and iterators now and it seems this might be an example of one of those new This is a generator expression. That's unfortunate news for me. It is like a list comprehension (you know about those right?) Yes. I know and use and love them daily. Even if there were implemented backwards :) [for x in range(10) x**2] would have been easier than: [x**2 for x in range(10)] But i am used to it now. except it doesn't create the list it just returns each item on demand. You could think of a list as a list constructed using a generator expression. def roundrobin(*iterables): roundrobin('ABC', 'D', 'EF') -- A D E B F C # Recipe credited to George Sakkis pending = len(iterables) nexts = cycle(iter(it).next for it in iterables) note this is storing the next methods not the results of them. while pending: try: for next in nexts: yield next() So the yield calls the stored method and returns the result. So... then to call (by call i mean use/execute/doit) i would do, what? foo.next() I kinda understand conceptually what iterators and generators do and why they are a honking good idea (why create 100 of x when we just want the 100th, etc.) what i don't get is the syntax and how they are used in real life. How generator and iterators behave in the wild. I am also bummed since generators have methods, which means they are OO which means i am i'd be in for 16 years of computer science study and super arcane, obscure and opaque concepts like what to do with __self__ and all that junk before i can use them. Anyway i needed a pea shooter that does a round robin. This one does it, but i don't know how to use it. I read up on gennies and itties and see if i can get my head around it. They are really poorly addressed nearly everywhere i look. They are explained so that really smart folks who know a lot of CS and are fluent in 15 computer languages can understand them, but not us mortals. Even the Lutz is too terse and generally poor on these two complex and relatively new constructs. They are a dark and obscure magic. I'll try the links Kent pointed me to first and see how that goes. thanks, -kp-- ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] working with multiple sets
This discussion is making my brain melt. It is also showing how clever Bob was to do it the way he did... I found a solution that i think works, and think has not yet been suggested. I quarantined Bob's code into a black box ... and then cast the output as a plain old fashioned python built in dictionary on output. So now instead of printing the code Bob gave the collection is returned by the func. Then i can cast it as a dict and pick over that dictionary as i wish. Here (as a bonus) I can transverse a range of keys that is inclusive of all my keys and also use python's get() dict method to also indicate index points (keys) that are empty.. which by default returns 'None', which is also useful in this case to show me what is missing. But I also have to do some type testing tomfoolery since missing keys return None, which is a special type (and not a list like the others)... I wanted the value list sorted so... i did if type(item) == type(foo): not sure if there is a betterererer way. Anyway, this woiks. -- #!/usr/bin/env python import collections def pscape(): lookup = collections.defaultdict(list) k1 = [34, 39, 41, 42, 43, 44, 46, 48, 49, 50, 51, 54, 55, 56, 58, 60, 61, 62, 63, 65, 66, 67, 68] k2 = [51, 56, 58, 63, 65, 68, 70, 72, 75, 77, 80, 82] y1 = [51, 53, 54, 56, 58, 60, 61, 63, 65, 66, 68, 70, 72, 73, 70, 72, 73, 75, 77, 79, 80] sets = {'k1': set(k1), 'k2': set(k2), 'y1': set(y1)} for key, value in sets.items(): for element in value: lookup[element].append(key) return lookup def test(): gamut = dict(pscape()) # -- scaffolding #print \n\n, type(gamut), \n\n, gamut, \n\n, gamut.keys() print \n\n foo = [1, 2, 3] for x in range(30, 85): item = gamut.get(x) if type(item) == type(foo): item.sort() print x, item print \n\n if __name__ == __main__: test() ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] mapping/filtering a sequence
Prolly good to post final solutions for future goog'lerz (like when i forget) or anyone who was following along. Here's where i ended up with this... shows both ways. -- #!/usr/bin/env python my_map = { 38:34, 40:39, 45:44, 47:46, 52:51, 59:58, 55:56 } def filter_item(item): return my_map.get(item, item) # you can do it old skool with map() def filter_test1(): foo = range(60) mappedfoo = map(filter_item, foo) for item in foo: print foo[item], mappedfoo[item] # you can also do it with a list comp def filter_test2(): foo = range(60) mappedfoo = [filter_item(n) for n in foo] for item in foo: print foo[item], mappedfoo[item] if __name__ == __main__: filter_test1() print \n,-- * 8, \n filter_test2() #--EOF-- ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] working with multiple sets
I also notice that if i do: def foo(): lookup = collections.defaultdict(list) x = range(10) y = range(5, 15) z = range(8, 22) sets = {'x': set(x), 'y': set(y), 'z': set(z)} for key, value in sets.items(): for element in value: lookup[element].append(key) for x in lookup: print x, lookup[x] print in oder to print more clearly what I want to see, the sets (as usual for a mapping type) are not always in order. Note that from 5 to 7 for example 'y' is listed in front of 'x' and 8 9 have 'y', 'x', 'z' and not 'x', 'y', 'z' ... I am not clear on how to sort that as the dictionary method lookup.sort() either doesn't work or i have tried it in all the wrong places. 0 ['x'] 1 ['x'] 2 ['x'] 3 ['x'] 4 ['x'] 5 ['y', 'x'] 6 ['y', 'x'] 7 ['y', 'x'] 8 ['y', 'x', 'z'] 9 ['y', 'x', 'z'] 10 ['y', 'z'] 11 ['y', 'z'] 12 ['y', 'z'] 13 ['y', 'z'] 14 ['y', 'z'] 15 ['z'] 16 ['z'] 17 ['z'] 18 ['z'] 19 ['z'] 20 ['z'] 21 ['z'] On Sep 8, 2009, at 10:52 PM, bob gailer wrote: kevin parks wrote: I am looking at this and wondering: Why does this use collections.defaultdict ? In fact i guess since collections.defaultdict is new to me i am not even sure why it exists and why someone would use this as opposed to using Python's built- in dictionary? and why was it used in this instance? It simplifies coding, as it takes care of initializing each new entry to a list. On Sep 6, 2009, at 3:06 AM, bob gailer wrote: I want to be able to look at a number/item and see which lists it is in so that i could maybe have a master list of all the data, a superset, and then an indication of which lists that data was in, as some items will only be in one list, some will appear in two lists (x y, or x z or y z) and a small handful will be in all three lists. I think you mean set rather than list To enable processing of an arbitrary number of sets, put them in a collection (list or dictionary). Use a list if it is sufficient to identify sets by number, else use a dictionary. Use a dictionary to relate items to their set(s). import collections lookup = collections.defaultdict(list) sets = {'x': set((1,2,3)), 'y': set((2,3))} for key, value in sets.items(): for element in value: lookup[element].append(key) print lookup -- Bob Gailer Chapel Hill NC 919-636-4239 ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] working with multiple sets
Actually, This seems like it works: lookup[x].sort() in like so: def foo(): lookup = collections.defaultdict(list) x = range(10) y = range(5, 15) z = range(8, 22) sets = {'x': set(x), 'y': set(y), 'z': set(z)} for key, value in sets.items(): for element in value: lookup[element].append(key) print print lookup, \n\n for x in lookup: lookup[x].sort() print x, lookup[x] #print type(lookup) print #print sets I realized that i was trying to apply the standard: k = lookup.keys() k.sort() in the wrong way and in the wrong place (i accidentally cut it out in my message when i removed the scaffolding) I might try the tuple things to for educational purposes. I am somewhat nervous about using something other than a built in type as i am not familiar with collections and it isn't well covered in beginner books or the docs. On Sep 9, 2009, at 12:44 AM, Kent Johnson wrote: On Tue, Sep 8, 2009 at 10:07 AM, kevin parksk...@me.com wrote: I also notice that if i do: def foo(): lookup = collections.defaultdict(list) x = range(10) y = range(5, 15) z = range(8, 22) sets = {'x': set(x), 'y': set(y), 'z': set(z)} for key, value in sets.items(): for element in value: lookup[element].append(key) for x in lookup: print x, lookup[x] print in oder to print more clearly what I want to see, the sets (as usual for a mapping type) are not always in order. Note that from 5 to 7 for example 'y' is listed in front of 'x' and 8 9 have 'y', 'x', 'z' and not 'x', 'y', 'z' Dictionaries and sets are not ordered. The order of items in sets.items() is an implementation detail, not something you can depend on. ... I am not clear on how to sort that as the dictionary method lookup.sort() either doesn't work or i have tried it in all the wrong places. lookup can't be sorted directly as it is a (default)dict. Anyway it is lookup[x] that you want to sort. Try print x, sorted(lookup[x]) or for x in lookup: lookup[x].sort() # list.sort() sorts the list in place and does not return a value. print x, lookup[x] Another alternative would be to use a list of tuples instead of a dict for sets, then the lookup values would be created in the desired order, e.g. sets = [ (x', set(x)), ('y', set(y)), ('z', set(z)) ] for key, value in sets: # etc Kent ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] working with multiple sets
I guess what i honestly want to asks, but am hesitant to since it makes me look like a dork is: What would this look like if i want to use a straight up built-in dictionary type and not the collections.defaultdict. import collections def foo(): lookup = collections.defaultdict(list) x = range(10) y = range(5, 15) z = range(8, 22) sets = {'x': set(x), 'y': set(y), 'z': set(z)} for key, value in sets.items(): for element in value: lookup[element].append(key) print \n, lookup, \n\n for x in lookup: lookup[x].sort() print x, lookup[x] print \n ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] mapping/filtering a sequence
I actually find the map biz easier to get my head around than the list comp. I guess this makes it another good reason for me to be happy that map is apparently staying in after nearly being depreciated. I generally prefer list comp in every instance, but the idea of an if else construct within the conditional of a list comp really hurts my brain, but it is nice to see that, had map(), filter() and reduce() all gotten the boot, there is a way to do it with a list comp, opaque as it is. Thanks to all who responded this. -kp-- On Sep 6, 2009, at 5:29 AM, Mark Tolonen wrote: Douglas Philips d...@mac.com wrote in message news:9ee00578-6af7-4c6c-9968-af5f25a00...@mac.com ... On 2009 Sep 5, at 12:22 PM, Mark Tolonen wrote: As a list comp: L=range(30,41) [{38:34,40:39}.get(n,n) for n in L] [30, 31, 32, 33, 34, 35, 36, 37, 34, 39, 39] True, that is terse, but IMHO has maintainability issues. The mapping data structure and the method of transformation (.get()) are tangled in with the transformation itself. Again, IMHO, unless this is a very short script, the maintenance should outweigh raw terseness. This *was* a very short script. My point was using a list comp. If you want to nitpick, don't use lower-case L for variables either :^) my_map = { 38: 34, 40: 39 } def filter_item(item): return my_map.get(item, item) L = [filteritem(n) for n in L] Happy? -Mark ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] mapping/filtering a sequence
I am doing some data massage, minor mapping and filtering really and i find that i have a lot of this kind of kludgy code: # -- - def filt_seq(inseq): out_list = [] for item in inseq: # 38 needs to be mapped on to 34 as we don't have a 38 in our grid if item == 38: item = item - 4 out_list.append(item) # We also don't have a 40, but we do have a 39. Map that sucka elif item == 40: item = item - 1 out_list.append(item) # if we get values that fall in good places, just pass them on to the out seq else: out_list.append(item) return out_list # -- - To do some basic jiggering of some out of range off grid data. There has to be a better, more elegant, more flexible less brute force more pythonic way to do this kind of mapping no? cheers, -kp-- ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] working with multiple sets
I am doing some simple things with sets and so far have had a lot of success with python's built-in sets, which is such a great new(ish) batteries included type python data type. [snip] [snip] -- [snip] [snip] -- #!/usr/bin/env python def test(): x = range(10) y = range(5, 15) z = range(8, 22) setx = set(x) sety = set(y) setz = set(z) print \n, x = , x, \n, y = , y, \n, z = , z, \n * 2 overlap1 = setx.intersection(sety) overlap1 = sorted(list(overlap1)) print overlap of x and y:, overlap1 # overlap2 = sety.intersection(setz) overlap2 = sorted(list(overlap2)) print overlap of y and z:, overlap2 # overlap3 = setx.intersection(setz) overlap3 = sorted(list(overlap3)) print overlap of x and z:, overlap3 if __name__ == __main__: test() [snip] [snip] -- [snip] [snip] -- so silly stuff like that works fine. But i want to do a little more than that. I want to be able to look at a number/item and see which lists it is in so that i could maybe have a master list of all the data, a superset, and then an indication of which lists that data was in, as some items will only be in one list, some will appear in two lists (x y, or x z or y z) and a small handful will be in all three lists. 0 - x 1 - x 2 - x 3 - x 4 - x 5 - x, y 6 - x, y 7 - x, y 8 - x, y, z 9 - x, y, z 10 - y, x etc. Of course the whole point of this is that the sets will be more complicated than 0-9, 5-14, and 8-21 and additionally, the sets may not be a list of numbers but eventually a list of strings. So the steps would be to create the superset then test for membership for each list? I kinda get it, the thing that warps my brain is the idea that there are more than 2 lists now to test against eventually my script needs to accommodate 4, 5, 6 sets.. but i would just like to see if i can get 3 sets to work first. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Help deciding between python and ruby
1. go to the book store 2. pull a copy of learning ruby by Michael Fitzgerald (ora.com) 3. pull a copy of learning python by Mark Lutz (ora.com) 4. read chapter 1 of each 5. make a decision 6. get to work Alternately check comp.lang.python where this question comes up over and over and over and over and worry your head some more. And while i am all for python advocacy. I: 1. Could not do better than the first 20 pages of the Lutz. 2. I am (and i am sure i will be over-ruled and shouted down for this), not entirely sure the tutor list is the appropriate place for this query. Places like comp.lang.python better serve this purpose. The tutor list is primarily a list (cribbing from http://mail.python.org/mailman/listinfo/tutor) for folks who want to ask questions regarding how to learn computer programming with the Python language. I am not entirely sure i want to hear a long drawn out thought experiment on what one person thinks upon adopting a new programming language. I joined this list to learn the specifics of programming in python and to get help and learn from the questions and answers posted by others. If this place too gets clogged with python -v- perl, python-v-ruby, phython -v- php navelgazing it is going to ruin the tutor list which has a pretty clear mission and has served that purpose very very well over the years i have been on it. I think we should redirect this query and avoid mission creep All IMO, YMMV, etc. co. If you think i am just being a jerk, at least take my initial advice. The ora books BOTH have great overviews of each language. A cup of coffee and reading the first 20 pages of each will tell you great overviews of Python v Ruby. -kevin On Sep 4, 2009, at 11:46 PM, Dan King wrote: I think you will get at the least a slight bias toward Python. However, I think you should do your own research and reach your own conclusions. Simply to get you started I put the following into Google: 'Python or Ruby: Which to learn' and got more than 1M hits. Best of luck. Robert Well, the slight (at the very least) bias toward Python is expected as this is a python mailing list. I have already done research on python and ruby via Google. I've found that python is described as more 'explicit,' used in multiple situations, has better libraries, and has unique 'spacing underscore' syntax requirements; and ruby on the other is more 'implicit,' used more in web-apps (via ROR), emphasizes code-readability/beauty, and is more flexible (i.e. has more than one way of doing something). While the preceding information is nice, the information hasn't helped me decide which one to learn - that's the reason for my post. I want to sift through the hype for each language. I want to understand the perspectives of people who use python - why they like/ dislike it, if/why the would recommend learning it, and what experiences they've had with python in professional contexts. To put my programming knowledge in context, I have experience with php and java; I enjoy php's ease and the syntax of java (everything is apparent from the code, although it can be a bit verbose). Look forward to the responses. Thanks. -Dan ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] mapping/filtering a sequence
Yeah the list seems flaky at the moment. Additionally, my query is an incredibly stupid one. But what you have works and represents an improvement over the unreadable kludge I was doing. Thanks to all who responded. cheers, k On Sep 6, 2009, at 12:26 AM, Douglas Philips wrote: On or about 2009 Sep 5, at 10:45 AM, Martin A. Brown indited: I must have missed a message or two, because I don't understand why math is being done on constants like that. Given my misunderstanding, I'd go with: my_map = { 38: 34, 40: 39 } def filter_item(item): return my_map.get(item, item) l = [ ... ] l = map(filter_item, l) -Doug ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] packing a list of lists
Back to python after a long long layoff. So i am running into some beginner's confusion... I am trying to plot a list of numbers in gnuplot.py. To do that I am trying to pack the list with an index by iterating over the list so i can get something like: foo = [12, 11, 9, 6, 2, 9, 3, 8, 12, 3, 5, 6] [ [1, 12], [2, 11], [3, 9], [4, 6], [5, 2], [6, 9], [7, 3], [8, 8] ... ] So that i have x, y pairs to plot. When i print in my func i get the right thing, for each item (note scaffolding) yet when i reurn the whole list i just get the last pair repeated over and over. I am not sure why this is. def pack(in_seq): out_list=[] x = 1 ll=[1, 1] for each in in_seq: ll[0] = x ll[1] = each out_list.append(ll) #print ll x = x + 1 print out_list # function declarations would go here def test(): test function - say what this does here and skip a line Keyword arguments: none print foo = minus(200) plot_me = pack(foo) #print foo print print plot_me if __name__ == __main__: test() ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] packing a list of lists
Thanks for the replies. Though the list comprehension does not work: TypeError: enumerate() takes exactly 1 argument (2 given) On Aug 29, 2009, at 12:20 AM, vince spicer wrote: #print foohough I didn't test your code, I think what you are trying to accomplish can be done using enumerate cleaner def pack(foo): out = [] for x,y in enumerate(foo, 1): out.append((x,y)) return out Or even cleaner with list comprehension def pack(foo): return [x for x in enumerate(foo, 1)] ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] packing a list of lists
I think this is b/c I am running 2.5. I also have 2.6 but i am using 2.5 for gnupoly and an older audio lib i have. I ran the listcom below on 2.6 and it worked, so i just have to figure out how that can be written for 2.5. I guess 2.6 has an update to enumerate. -k On Aug 29, 2009, at 2:21 AM, afit...@gmail.com wrote: Enumerate() is returning a tuple, I haven't tested this code but try: [[x[0],x[1]] for x in enumerate(blah,1)] --Original Message-- Sender: tutor-bounces+afith13+python=gmail@python.org To: tutor@python.org Subject: Re: [Tutor] packing a list of lists Sent: Aug 28, 2009 9:49 AM Thanks for the replies. Though the list comprehension does not work: TypeError: enumerate() takes exactly 1 argument (2 given) On Aug 29, 2009, at 12:20 AM, vince spicer wrote: #print foohough I didn't test your code, I think what you are trying to accomplish can be done using enumerate cleaner def pack(foo): out = [] for x,y in enumerate(foo, 1): out.append((x,y)) return out Or even cleaner with list comprehension def pack(foo): return [x for x in enumerate(foo, 1)] ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] packing a list of lists
Interestingly changing: out_list.append(ll) to out_list.append(list(ll)) seems to work. The part of my brain that understood why that is must have sleeping. -k On Aug 28, 2009, at 11:05 PM, i wrote: Back to python after a long long layoff. So i am running into some beginner's confusion... I am trying to plot a list of numbers in gnuplot.py. To do that I am trying to pack the list with an index by iterating over the list so i can get something like: foo = [12, 11, 9, 6, 2, 9, 3, 8, 12, 3, 5, 6] [ [1, 12], [2, 11], [3, 9], [4, 6], [5, 2], [6, 9], [7, 3], [8, 8] ... ] So that i have x, y pairs to plot. When i print in my func i get the right thing, for each item (note scaffolding) yet when i reurn the whole list i just get the last pair repeated over and over. I am not sure why this is. def pack(in_seq): out_list=[] x = 1 ll=[1, 1] for each in in_seq: ll[0] = x ll[1] = each out_list.append(ll) #print ll x = x + 1 print out_list # function declarations would go here def test(): test function - say what this does here and skip a line Keyword arguments: none print foo = minus(200) plot_me = pack(foo) #print foo print print plot_me if __name__ == __main__: test() ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] packing a list of lists
On Aug 29, 2009, at 12:23 AM, Michael M Mason wrote: i wrote: def pack(in_seq): out_list=[] x = 1 ll=[1, 1] for each in in_seq: ll[0] = x ll[1] = each out_list.append(ll) #print ll x = x + 1 print out_list Variable out_list consists of list ll repeated however many times. Each time you change ll you're changing it everywhere it appears in out_list. That is, what's being appended to out_list isn't a copy of ll, it's a pointer to ll. You need something like:- out_list.append([ll[0],ll[1]]) Right... ugh.. Totally forgot about that. Python 101. I don't know why my brain resists that idea. Every time i let python alone a while and come back to it i get bit by this. And you need to add a return at the end of the function, otherwise it returns None: return out_list That, of course, i know... I was messing around debugging of course. Thanks for the response. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Checking Syntax
I am teaching myslef Python from a GIS tutorial 'Writing_Geoprocessing_Scripts.pdf'. I have typed everything exactly like it is in the tutorial and when I go to run a check on the sytax (before I try running the program) it places a cursor like so: outFeatureClas|s = outWorkspace + / + GP.ValidateTableName(fc,outWorkspace) I have checked the tutorial and I can't see what is wrong. I can't get past this until it is corrected. I have attached the script. Any advice would be greatly appreciated. Thanks, Kevin #Import standard library modules #imports system, operating system Windows 32 modules #sys refers to Python system, os refers to acess to operating system import win32com.client, sys, os #Create the Geoprocessor object GP = win32com.client.Dispatch(esriGeoprocessing.GpDispatch.1) #Set the input workspace #argv = argument value #argv[1] is the name of the script GP.workspace = sys.argv[1] #Set the clip featureclass clipFeatures = sys.argv[2] #Set the output workspace outWorkspace = sys.argv[3] #Set the cluster tolerance clusterTolerance = sys.argv[4] #try statement defines the beginning of a block of code that will be #handled by its associated exception handler, or except statement #try/except statements are used to handle unexpected errors #this defines that the program should do when an exception happens try: #Get a list of the featureclasses in the input folder fcs = GP.ListFeatureClasses() #Loop through the list of feature classes #always reset a list so the first item is extracted #so you can be sure you get the first item in the list fcs.Reset() fc = fcs.Next() while fc: #Validate the new feature class name for the output workspace. #ValidateTableName ensures output name is valid for output #workspace, it returns unique name so no existing data is overwritten. outFeatureClass = outWorkspace + / + GP.ValidateTableName(fc, outWorkspace) #Clip each feature class in list with the clip feature class. #Do not clip the clipFeatures, it may be in the same workspace. if str(fc) != str(os.path.split(clipFeatures)[1]): GP.Clip(fc, clipFeatures, outFeatureClass, clusterTolerance) fc = fcs.Next() except: #except statement is required by the earlier try statement #if an error occurs during execution the code in the except #block will run GP.AddMessage(GP.GetMessages(2)) print GP.GetMessages(2) ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Efficiency of Doxygen on Python vs C++?
Stephen McInerney wrote: My friend said the runtime efficiency of Doxygen on his build was much worse on the Python code than the C++ code, i.e. it took ages to parse the Python code. It's not the efficiency of doxygen that's the question. The problem is that you can add fields to objects as you go in Python so you need to do a deep analysis of the code to determine the class structure which you don't have to do with C++ (or Java). Kev. Anyone agree/disagree, or have any efficiency tips on how to structure things for decent Doxygen performance? (I haven't used Doxygen myself and I don't have access to the build in question). Regards, Stephen _ Learn.Laugh.Share. Reallivemoms is right place! http://www.reallivemoms.com?ocid=TXT_TAGHMloc=us -- http://www.grfx.com mailto:[EMAIL PROTECTED] ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Module imports
With sincere apologies for such a basic question, and one i will admit that i asked once before, moons ago. But even after googling around a bit i don't understand what the right answer is, or if i once did, can't recall it now.. I have a script, let's call it foo.py This script loads several modules from the standard library and a home brewed module that has a bunch code that i often reuse in it. For example it might have: # -- foo.py -- # -- batteries included import random import sys import time # -- homebrewed import kp [... code here ..] That is fine and in this script i will call and use various things from the random, sys, and time modules. but my kp module also uses happens to call on certain things from the random, time, and sys modules and so kp.py also has import random import sys import time Now so far this seems to be working fine and without error (as far as i can tell). However, shouldn't i only be importing random, sys and time once? and if so, where? in foo.py or kp.py? It was explained to me that it is fine to import random, sys and time in both, and that only the first import uses up memory, and subsequent attempts to import the same module don't really cost anything and just add a reference in the namespace. but isn't loading it in both modules confusing and bad additionally in this case which import is actually being used (or does this not even matter?) the one in kp.py or in foo.py? For some reason i feel like i should understand how and why this works a little better in order to avoid overlap and conflict in what is becoming a bit more involved intermingling of modules and scripts. or alternately you all can chime in and say dude, get over it, multiple and overlapping imports are not a big deal in python, you are worrying about nothing, and making a problem where there is none! Get on with your life. haha best, kevin ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] time(duration) formats basic time math query
I have been handed a huge number of documents which have hundreds of pages of times and durations, all calculated and notated by several different people over the course of many years. Sadly, no made any guidelines at all about how this work would proceed and all the documenters had their own ideas about how times/durations would be specified so the doc are a mess. Furthermore the person i work for changes her mind every 15 minutes so i have no idea what she will want at any given moment. This sounds to me like a job for Python hee hee Essentially, I am trying to do 2 things: move fluidly between different duration formats (take any, specify and display any). Such as: pure miliseconds seconds. msec mm:ss.msec hh:mm:ss.msec So the input doc would be grepped for times and i could just uncomment the line i need and get he format my boss wants at this particular moment. So a recording that is 71 minutes and 33 seconds could be printed as: 4293 seconds 71:33. 01:11.33. or whatever also i need to be able to adjust start times, durations, and end times which means doing a little time math. Like if a recording is 71 minute and 33 seconds.. but there are several sonic events in that recording and i need to specify the duration, or start time etc of those individual events... then i need to subtract... Additionally i know that i will need to subtract pure minutes from an hh:mm format I having a real hard time getting my head round the labyrinthian datetime module in the docs (i am guessing that this is what i should use). I wonder if anyone could give me a hand and point me in the right direction. cheers, kevin ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] cycle w/ shuffle
Thanks Kent. That is what i did the first time around but it didn't work ... but that was do to something else that was not working in the script hehe of course, this just shuffles the saved copy of the list which is egg-zactly what i needed duh ... sorry... gosh... red face=on -kevin-- On Apr 27, 2006, at 6:00 AM, [EMAIL PROTECTED] wrote: kevin parks wrote: it seems to me that i need something like itertools cycle, except that i need to keep track of when i have exhausted my list and then call random.shuffle() on my sequence. def cycle(iterable): saved = [] for element in iterable: yield element saved.append(element) while saved: random.shuffle(saved) ### for element in saved: yield element Kent ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] how to *really* copy a list
John, Thanks. Your message was very helpful. I will tattoo it to my forehead. hehe... i notice that the learning python book also explains so of this and i shall study that as well cheers, kevin On Apr 27, 2006, at 10:14 PM, [EMAIL PROTECTED] wrote: On 28/04/06, kevin parks [EMAIL PROTECTED] wrote: In most case you are fine operating on the list in place and altering the existing list. In some cases you want your code to stop molesting your poor mutables and really honestly sincerly copy the dang thing. In this case i am making a function that does odd smmetry mirroring. But i want my orginal list to remain intact def mirror(seq): odd symmetry mirroring [1, 2, 3, 4] -- [1, 2, 3, 4, 3, 2, 1] foo=seq[:-1]# copy list, excluding last element for odd symetry foo.reverse() # flip it seq.extend(foo) return seq Hi Kevin, Your problem is this line: seq.extend(foo) ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] how to *really* copy a list
Ed, I should have realized that the nesting would create the problem, but i didn't have that in mind... i always thought that the difference between extend and append was that extend did not yield a nested list. I really need to revisit this issue and get it right in my mind. It is a 'gotcha' that i remember reading about often but, now that it has bit me a few times hehe so much to know... -kevin-- On Apr 29, 2006, at 6:00 AM, [EMAIL PROTECTED] wrote: Hi Kevin, Your problem is this line: seq.extend(foo) This is the line that mutates your original list. There are a few ways you could procede here. One way is to make a copy of the argument, like this: def mirror(seq): start = list(seq) end = seq[:-1] end.reverse() start.extend(end) return start Notice that we've not calling any methods on seq, so seq won't be changed. The first line, start = list(seq), instructs python to build a new list out of the elements of seq. You could also write start = seq[:] here --- I'm not sure which is the preferred way. A little 'gotcha' with this is that if you have nested lists, these methods don't copy the nested lists, only the outer list (which makes sense, but can be surprising the first time you encounter it). If for some reason you want to copy nested lists, look into deepcopy(), otherwise you'll be fine. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] how to *really* copy a list
I know there is an answer to this somewhere. it is prolly the biggest stumbling block to all python n00bs, but it hasn't been an issue for me in a while. Suddenly i am getting bit by it and can't for the life of me keep straight the two way of opperating on lists. In most case you are fine operating on the list in place and altering the existing list. In some cases you want your code to stop molesting your poor mutables and really honestly sincerly copy the dang thing. In this case i am making a function that does odd smmetry mirroring. But i want my orginal list to remain intact a = [1, 2, 3, 4] mirror(a) [1, 2, 3, 4, 3, 2, 1] a [1, 2, 3, 4, 3, 2, 1] clearly this is not happening. believe it or not i googled around figuring the answer would be posted someplace... but if it is i haven't found it. Every thing i land on says copy a list by [:] slicing like i have below... how to i really (not kidding) copy a list? I swear i used to know this, but i haven't had to do it in a long long long time. # === dumb code: def mirror(seq): odd symmetry mirroring [1, 2, 3, 4] -- [1, 2, 3, 4, 3, 2, 1] foo=seq[:-1]# copy list, excluding last element for odd symetry foo.reverse() # flip it seq.extend(foo) return seq ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] seq looping
Bob ... i used my kludge which defines some bounds and tests for it... but your idea of stuffing that into a seperate black box as golden in that it made me think of the problem as input -- doit -- result. and made my loops simpler and easier to read... and i use that same gap making typing thing in several loops, so encapsulating that meant that i could make it general purpose, and re-usable and i can add to it later more easily. Thanks for that suggestion. I ended up with this: # if the flag (random float) is lower than our percentage of rest, we pick # a rest duration and add that to our start time creating a gap between events. def make_rest(event, lowerbound, upperbound, start, rest_percent): restflag = random.random() if (restflag rest_percent): # This kludge makes sure our last event does not get a rest, and we can # prevent the first few events from getting rests as well to insure # our transitions between sections are seamless sufficiently busy # NOTE LOWER bound is included if event = lowerbound and event upperbound: rest_dur = windex(rest) print \n, - * 8, [ rest : , rest_dur, ], - * 8, \n start = start + rest_dur else: print [bang] # debug return start then in the master bedroom i just call it: startime = foo.make_rest(event, 1, upperbound, startime, rest_percent) cheers, kevin On Apr 25, 2006, at 11:27 PM, Bob Gailer wrote: How about separating the body into 2 functions, calling both for all but the last list element, then calling just the first for the last element: : def step1(sample): global incr splt = os.path.split(sample) rtinput(sample) loc = random.random() dur = DUR() STEREO(startime, inskip, dur, amp, loc) print event no. %d @ %.2f (dur: %.2f, end: %.2f) -- sf: %s : [flag: %.2f] % (event, startime, dur, startime+dur, splt[1], dry) incr = (dur * duty_factor) + kptools.windex(kptools.durations) startime = startime + incr def rest(): global event restflag = random.random() if (restflag rest_percent): rest = kptools.windex(kptools.rest) print \n, - * 8, [ rest : , rest, ], - * 8, \n startime = startime + rest event = event + 1 for sample in smpl_lst[:-1]: step1(sample) rest() step1(smpl_lst[-1]) so what i am trying to do its skip that if (restflag rest_percent): biz on the last item if we are on our last sequence item. The rests (which are random) is for padding between events and since we have just played our last event, we don't want any extra padding so that our next call of the loop starts at the proper time (just at the last event of this loop is over). The loop function will calculate the next start time, and return it so that we can use it as the start time argument for our next call of the loop. so if i want to play 7 items i might get something like: loop_call_01: item_1 item_2 rest item_3 rest item_4 item_5 item_6 rest item_7 (but we don't want any rest here ever! cause we might want our next loop to start w/o any pause) ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] cycle w/ shuffle
I am trying to write a loop that iterates over a sequence and do something x number of times. But sometimes i will need more events (larger number x) than i have have items in the sequence, so if i need more events that i have stuff in my sequence i would like to have the loop reload and shuffle the deck and start all over again, reloading as many times as necessary to get the number of events needed. I suppose i could go around cyclically modulo the list size but i would want to shuffle the deck before doing that again... it seems to me that i need something like itertools cycle, except that i need to keep track of when i have exhausted my list and then call random.shuffle() on my sequence. def cycle(iterable): saved = [] for element in iterable: yield element saved.append(element) while saved: for element in saved: yield element def test(): seq = ('one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'ten') loop = cycle(seq) count = 1 for item in range(25): print count, loop.next() count = count + 1 if __name__ == '__main__': test() here i have gone through my list 2.5 times .. and somewhere after the second and third(tho incomplete) rounds i need to shuffle... but i am not sure how to fix that. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] cycle w/ shuffle
I am trying to write a loop that iterates over a sequence and do something x number of times. But sometimes i will need more events (larger number x) than i have have items in the sequence, so if i need more events that i have stuff in my sequence i would like to have the loop reload and shuffle the deck and start all over again, reloading as many times as necessary to get the number of events needed. I suppose i could go around cyclically modulo the list size but i would want to shuffle the deck before doing that again... it seems to me that i need something like itertools cycle, except that i need to keep track of when i have exhausted my list and then call random.shuffle() on my sequence. def cycle(iterable): saved = [] for element in iterable: yield element saved.append(element) while saved: for element in saved: yield element def test(): seq = ('one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'ten') loop = cycle(seq) count = 1 for item in range(25): print count, loop.next() count = count + 1 if __name__ == '__main__': test() here i have gone through my list 2.5 times .. and somewhere after the second and third(tho incomplete) rounds i need to shuffle... but i am not sure how to fix that. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] seq looping
I have a loop that process each item in a sequence and after each item some updating is done to some variables. However i don't what these variable updated if we are processing the last item in the list. i could put in a conditional and test if the list is now empty after popping items from the list... but testing for an empty list and the bookkeeping of maintaining the popped list seems horribly inefficient and this is for a real time multimedia playback type situation so learning a more efficient idiom for this seems worth while: You won't have all the dependancies... including the player (STEREO) and some tables of durations.. but you get the gist: def playall(startime, amp, wet_percent, rest_percent, duty_factor, smpl_lst): ''' a play-loop that plays all samples in a directory, just once with some temporal padding and also returns the end of the last duration so that the begining of the next section can be determined''' event = 1; inskip = 0; inchan = 0; incr = 0 for sample in smpl_lst: splt = os.path.split(sample) rtinput(sample) loc = random.random() dur = DUR() STEREO(startime, inskip, dur, amp, loc) print event no. %d @ %.2f (dur: %.2f, end: %.2f) -- sf: %s : [flag: %.2f] % (event, startime, dur, startime+dur, splt[1], dry) incr = (dur * duty_factor) + kptools.windex(kptools.durations) startime = startime + incr restflag = random.random() if (restflag rest_percent): rest = kptools.windex(kptools.rest) print \n, - * 8, [ rest : , rest, ], - * 8, \n startime = startime + rest event = event + 1 print '\n', 'Next start = ', startime, '\n\n' so what i am trying to do its skip that if (restflag rest_percent): biz on the last item if we are on our last sequence item. The rests (which are random) is for padding between events and since we have just played our last event, we don't want any extra padding so that our next call of the loop starts at the proper time (just at the last event of this loop is over). The loop function will calculate the next start time, and return it so that we can use it as the start time argument for our next call of the loop. so if i want to play 7 items i might get something like: loop_call_01: item_1 item_2 rest item_3 rest item_4 item_5 item_6 rest item_7 (but we don't want any rest here ever! cause we might want our next loop to start w/o any pause) gosh.. i hope this is clear anyway that's my query .. hehe ... cheers, kevin ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Alternating patterns
I have a set that i iterate over... but each time through it i would like to alternate between the original set and a variation of the set that has one of the members of the set altered (by + or - 1) So if my original set is: [0, 2, 4, 5, 7, 9, 11] I would use that the first pass but on the second pass i might like the third member (4,) to become 3, (-1) resulting in : [0, 2, 3, 5, 7, 9, 11] But then back again to the original on the next pass (+1 back to 4,): [0, 2, 4, 5, 7, 9, 11] and then back: [0, 2, 3, 5, 7, 9, 11] again, etc. in other words i would like to alternate members of the set back and forth. Usually only 1 (or sometimes 2,) member at time. i could also imagine a needing(alter one, alter another, undo that, undo the first back to the original set): [0, 2, 4, 5, 7, 9, 11] -- [0, 2, 3, 5, 7, 9, 11] -- [0, 2, 3, 5, 7, 8, 10] -- [0, 2, 3, 5, 7, 9, 11] -- [0, 2, 4, 5, 7, 9, 11] or: original -- [0, 2, 4, 5, 7, 9, 11] altered -- [0, 2, 3, 5, 7, 9, 11] now back to 4, but change something else (like 11, is now 10): [0, 2, 4, 5, 7, 9, 10] etc... How can one make such alternating patterns? -kp-- ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Alternating patterns
-- Message: 10 Date: Tue, 28 Mar 2006 22:43:38 -0500 From: Kent Johnson [EMAIL PROTECTED] Subject: Re: [Tutor] Alternating patterns Cc: tutor@python.org Message-ID: [EMAIL PROTECTED] Content-Type: text/plain; charset=ISO-8859-1; format=flowed kevin parks wrote: I have a set that i iterate over... but each time through it i would like to alternate between the original set and a variation of the set that has one of the members of the set altered (by + or - 1) So if my original set is: [0, 2, 4, 5, 7, 9, 11] I would use that the first pass but on the second pass i might like the third member (4,) to become 3, (-1) resulting in : [0, 2, 3, 5, 7, 9, 11] But then back again to the original on the next pass (+1 back to 4,): [0, 2, 4, 5, 7, 9, 11] and then back: [0, 2, 3, 5, 7, 9, 11] again, etc. How can one make such alternating patterns? itertools.cycle() will repeat a sequence indefinitely: In [2]: from itertools import cycle In [3]: i=cycle([1,2]) In [5]: for j in range(6): ...: print i.next() ...: ...: 1 2 1 2 1 2 For non-repeating sequences I would look at writing a generator function for the sequences. Kent okay.. i am painfully unaware of generators, iterators, sets, genexes and a lot of the new stuff post 2.3 2.4 stuffs... my problem is that i find the online docs kind of terse and few of the Python books yet cover these newer constructs in detail itertools looks very cool are there any toots on the above and on Sets itertools? It really seems like it would help to know these for my work... That liddo bit right up there with itertools.cycle already has me a drooling... (so helpful that would be!) -kp-- ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] scaling values
i have various functions (that i didn't write) that put out data in lists of various types. But some functions (which i didn't write) that expect the data to be scaled, sometimes 0-1 sometimes 1-2, sometimes 0-127..., sometimes 0 - 32768... gosh you name it. In other words i have a bunch of black boxes that don't speak the same language is there a scaling function in python (or numeric or scipy) that can scale a list of values to a high precision? x = [13, 71, 120, 88, 82, 100, 10, 65, 101, 45, 26] foo = scale(x, 0, 1.0) and get that list scaled 0 to 1, or if i had: x = [.12789, .982779, .19798198, .266796, .656527, .257877091] foo = scale(x, 0, 127) cheers, -kp-- ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] scaling values
hi, Seems my post added much confusion. Sorry... I was hoping not to have to post my code since it is really wrong and slightly embarrassing.. what i am trying to do is map an input range of values to output range. I was hoping to make it a bit of an all purpose utility that would map pretty much any input range to an output range, also do inverted mapping... and also handle negative numbers and perhaps even a flag for exponential mapping. import random def scaleX(in_seq, low, hi): range1 = max(in_seq) - min(in_seq) #range2 = max(out_seq) - min(outseq) range2 = hi - low ratio = range1/range2 return [(x * ratio) for x in in_seq] def test(): # Create a list of 15 random integers in the range 0 to 127 # see if we can map it to 0 - 1 inseq = random.sample(xrange(128), 25) print print scaleX(inseq, 0.0, 1.0) print if __name__ == __main__: test() ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] scaling values
Thanks to Kent Johnson, David Heiser and everyone else. Looks like i was most of the way there...hehe... David Heiser gets special bonus points for actually understanding my initial mysterious query. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] weighted choices from among many lists
On Mar 11, 2006, at 3:24 PM, [EMAIL PROTECTED] wrote: Message: 1 Date: Sat, 11 Mar 2006 08:34:49 -0500 From: Kent Johnson [EMAIL PROTECTED] Subject: Re: [Tutor] weighted choices from among many lists Cc: tutor@python.org Message-ID: [EMAIL PROTECTED] Content-Type: text/plain; charset=ISO-8859-1; format=flowed kevin parks wrote: I have several lists... and i would like to some times chose from one list and for a while choose from a different list, etc. You don't say what isn't working but I have a guess. The actual windex() function looks OK to me. yes, that part always worked fine... not the most robust thing, but it works. def test(): lst_a = [ 'red', 'green', 'blue', 'orange', 'violet', 'yellow', 'black', 'white' ] lst_b = ['Rottweiler', 'Beagle', 'Sheepdog', 'Collie', 'Boxer', 'Terrier', 'Bulldog', 'Chihuahua', 'Retriever', 'Collie', 'Dachshund', 'Doberman', 'Greyhound', 'Pug', 'Spaniel'] lst_c = ['Ale', 'Lager', 'Pilsner', 'Bock', 'Porter', 'Stout'] lst_d = ['fender', 'gibson', 'rickenbacker', 'guild', 'danelectro', 'gretsch', 'martin', 'ibanez'] x = [('lst_a', .50), ('lst_b', .25), ('lst_c', .10),('lst_d', .15)] x is list containing the *names* of the other lists. You need to keep references to the lists so you can pick from them. x = [(lst_a, .50), (lst_b, .25), (lst_c, .10),(lst_d, .15)] i am an idiot... someone shoot me.. i guess i got so carried away with typing the single quotes for the above lists that when i went to pack those up for windex i didn't realize that i had needlessly typed 'lst_a', etc. Sometimes you just need a fresh pair of eyes to pick up on that type of thing i = 1 while i 100: lst = windex(x) print i, lst, with the change above this will print the list, not its name pick = random.choice(lst) but this will work. If you want to be able to print the name of the list then you could include both the name and the actual list in x: x = [(('lst_a', lst_a), .50), etc...] That produces: ('lst_c', ['Ale', 'Lager', 'Pilsner', 'Bock', 'Porter', 'Stout']) ['Ale', 'Lager', 'Pilsner', 'Bock', 'Porter', 'Stout'] i am actually trying to get name of list, the choice like so: lst_c Bock ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] weighted choices from among many lists
Yes, you need to unpack the result of calling windex(). You so ably demonstrated unpacking the list in your for loop I thought you would figure it out :-) Try lst_name, lst = windex(x) then random.choice() and print. Thanks Kent i got it, just another brain-fart on my side... I was already doing something like: lst_name, lst = windex(x) pick = random.choice(lst) But instead of: print i, lst_name, pick I was idiotically still printing: print i, lst, pick now matter how you unpack it all... you are still gonna get lst if that is what is in your print statement... grrr of course the another way i would be a use a dictionary and us the list name as a key... the list as a value... Thanks, kevin ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] weighted choices from among many lists
I have several lists... and i would like to some times chose from one list and for a while choose from a different list, etc... so i cooked this up and it almost works so that i can get colors 50% of the time, doggies 25%, beer 10%, and guitars 100% (if i was real smart i would make my index thingy check to make sure my wieghets added up to 100% or scaled them to be. ) ... meanwhile, as you can see i am 90% of the way there, can anyone figure out what i got wrong or suggest improvements to the code... best, -kevin-- #!/usr/bin/env python import random def windex(lst): '''a random.choose() function that makes weighted choices accepts a list of tuples with the item and probability as a pair like: x = [('one', 0.25), ('two', 0.25), ('three', 0.5)] y=windex(x)''' n = random.uniform(0, 1) for item, weight in lst: if n weight: break n = n - weight return item def test(): lst_a = [ 'red', 'green', 'blue', 'orange', 'violet', 'yellow', 'black', 'white' ] lst_b = ['Rottweiler', 'Beagle', 'Sheepdog', 'Collie', 'Boxer', 'Terrier', 'Bulldog', 'Chihuahua', 'Retriever', 'Collie', 'Dachshund', 'Doberman', 'Greyhound', 'Pug', 'Spaniel'] lst_c = ['Ale', 'Lager', 'Pilsner', 'Bock', 'Porter', 'Stout'] lst_d = ['fender', 'gibson', 'rickenbacker', 'guild', 'danelectro', 'gretsch', 'martin', 'ibanez'] x = [('lst_a', .50), ('lst_b', .25), ('lst_c', .10),('lst_d', .15)] i = 1 while i 100: lst = windex(x) print i, lst, pick = random.choice(lst) print pick i = i + 1 if __name__ == __main__: test() ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] activestate
I noticed a couple days ago that the active state archive seems to have ceased. Is it going away? cheers, kevin ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] module imports
On Mar 8, 2006, at 7:09 PM, Bob Gailer wrote: kevin parks wrote: i have a module called foo.py foo.py imports random kp.py imports foo.py ... but in kp.py i also need to use stuff from random... so kp.py also imports random but i prolly shouldn't do that right? Wrong. so it is okay to do that? Cause now, haven't i needlessly copied the same names/attributes/methods/functions to 2 namespaces... The first import of a module runs its top level code, and creates a module object. Subsequent imports simply place a reference to that object in the current namespace. I get very confused about imports... and accessing names from other spaces and such... and efficiency. i have 2 or more modules all of which need to access a given function or method, what is the best way to do that. Put the function in a module and import it as needed. but i mean a function from a standard module. i am so cornfused Apparently. Even your spell checker is addled. [that was a joke] so let's say i have a script called foo.py. foo.py uses some things from the random module and therefore has import random import kp import sys import time etc. co. in it but foo.py also imports a module kp which also happens to import random. Should i only be importing random once or are you saying it is just fine to import a module that imports another module that you actually have already imported. -kp-- ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] list packing
howdy, I am using the os module to do some of my heavy lifting for me. I am tried of building lists by hand so i decided that i would get python to look in a bunch of directories and stuff all the things it find there into a list depending on it's extension. Works great ... one problem sometimes i need just the filenames and that is fine, but more often i need to feed the full path to my other functions yet i don't see *any* documentation on os.listdir() at all. I don't know how to give me the full path ... snd = [f for f in os.listdir('/Users/kevin/snd/') if f.endswith('.aif')] cheers, kevin ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Gaussian integer values
hi all. I am working with a list and would like to choose from the list randomly but not uniformly. I am interested in several distributions but the first one i looked at is Gaussian. which you call like so: random.gauss(mean, dev) You can try this code courtesy of effbot (http://effbot.org/ librarybook/random.htm) # File: random-example-3.py import random histogram = [0] * 20 # calculate histogram for gaussian # noise, using average=5, stddev=1 for i in range(1000): i = int(random.gauss(5, 1) * 2) histogram[i] = histogram[i] + 1 # print the histogram m = max(histogram) for v in histogram: print * * (v * 50 / m) fine this works and works well... one problem with this... if you are using this to create an index to a list you might be in trouble as each time you run it you get a slightly different min and max value. so... how does one safely pick from a list of say 15 elements with a large bias towards the center values without over or under-running the bounds of your list? cheers, kevin ps. what would be the opposite of the Gaussian distro the scoop like one, the one where the outer elements are favored. Is that in the python standard lib? (or numpy?) ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] soundfile picker rating system
I am a little bit stuck I want to play a bunch of soundfiles randomly, but i want to give each soundfile a rating (say 0-100) and have the likelihood that the file be chosen be tied to its rating so that the higher the rating the more likely a file is to be chosen. Then i need some additional flags for repetition, and some other business. I am guessing a dictionary would be a great way to do this, with the key being the soundfile name and the values being my ratings and other flags associated data. #soundfile name : [rating, %chance it will repeat/loop] sfiles = { (sf001) : [85, 15], (sf002) : [25, 75], (sf003) : [95, 45], (sf004) : [35, 95] } But i am stuck on how to do a random chooser that works according to my idea of choosing according to rating system. It seems to me to be a bit different that just choosing a weighted choice like so: def windex(lst): '''an attempt to make a random.choose() function that makes weighted choices accepts a list of tuples with the item and probability as a pair like: x = [('one', 0.25), ('two', 0.25), ('three', 0.5)] y=windex(x)''' n = random.uniform(0, 1) for item, weight in lst: if n weight: break n = n - weight return item And i am not sure i want to have to go through what will be hundreds of sound files and scale their ratings by hand so that they all add up to 100%. I just want to have a long list that i can add too whenever i want, and assign it a grade/rating according to my whims! cheers, kevin ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] printing the random seed?
hi. I am having some fun with python and making multiple runs on an algorhythm and sometimes getting some fun stuff that i would like to be able to reproduce, but there are some random elements in it. I wonder is there a way to see the random seed, and make note of it so that you could then set the seed for a subsequent run to get the same (initially) random results? cheers, kevin (Hi Danny, if you are still here!) ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] printing the random seed?
Danny (hope you are good!) co, I see that biz about random.seed()... but in the absence of setting that ... does it just grab a value from the system clock? Is there a way to just let it generate it's usual, known seed... but then observe what that is in case you get an especially good run of data? like i clearly can't just go: zeed = random.seed() print zeed = , zeed hmm... cheers, -[kp]-- ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] help
how do i use python, do i download it? how do i use it . kevin.Don't just Search. Find! The new MSN Search: Fast. Clear. Easy. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Reversing
I was asked to make a program that reverses the text that a user would input. I have tried what I thought would work which is phrase.reverse(). phrase = the raw_input. Help! Thank you, Kevin Bixler ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Single Underscore
What's the significance of naming a variable with a single underscore as its first character? For example, I'm looking at find.py in the standard library and it has variables named _debug and _prune. Kevin ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Single Underscore
Thanks for the info. I'll look into the links provided. http://jaynes.colorado.edu/PythonGuidelines.html http://www.python.org/peps/pep-0008.html Kevin ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] fileinput problem
On Sat, 25 Jun 2005 06:41:01 -0400 Kent Johnson [EMAIL PROTECTED] wrote: You named your program fileinput.py, so when you import fileinput you are getting your own program again instead of the library module. Change the name of your program and try again. Doh! I do remember reading that somewhere before. Lesson learnt. Kevin ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Calling a function
I'm having trouble with this code which is meant to run a time comparison between two similar functions. The first module is makezeros.py def lots_of_appends(): zeros = [] for i in range(1): zeros.append(0) def one_multiply(): zeros = [0] * 1 The second module is timings.py. import time, makezeros def do_timing(num_times, *funcs): totals = {} for func in funcs: totals[func] = 0.0 for x in range(num_times): for func in funcs: starttime = time.time() apply(func) stoptime = time.time() elapsed = stoptime-starttime totals[func] = totals[func] + elapsed for func in funcs: print Running %s %d times took %.3f seconds % (func.__name__, num_times, totals[func]) do_timing(100, (makezeros.lots_of_appends, makezeros.one_multiply)) Here's the outcome I get: $ python ./Python/timings.py Traceback (most recent call last): File ./Python/timings.py, line 17, in ? do_timing(100, (lots_of_appends, one_multiply)) File ./Python/timings.py, line 10, in do_timing apply(func) TypeError: 'tuple' object is not callable BTW, the code is taken straight out of Learning Python, but I've been banging my head on it for awhile. Any ideas?? Kevin ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Calling a function
Ewald John, thanks for the help. i'll work on it some more with your ideas in mind (after getting some sleep). Kevin ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] re: IDLE
Is there a way to get line numbers to show in python IDLE? I looked at all the preferances but nothing? Thanks Kevin ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Re: Help with classes
Well this OOP stuff is realy hard for me as I have never even programmed it took me a while just to understand defs. However I am determined to learn how to do it. My biggest problem is with __init__ I still don't understand how to use it. Though I did try somthing different with my code rather then having the dict of commands in the main part of the code, I put it in th __init__ of class Comands like so: class Command: def __init__(self): self.command_list = {} self.command_list['get'] = 'get' self.command_list['look'] = 'look' self.command_list['kill'] = 'kill' def UserCMD_get(self): print Not in yet def UserCMD_look(self): print Not in yet def UserCMD_kill(self): print Not in yet test = Command() while 1: prompt = raw_input(: ) if prompt not in test.command_list: print That is not a command if prompt in test.command_list: exec 'test.UserCMD_' + prompt + '()' though doing it like this to me the only real difference is the dict of commands is in the __init__ of class. But why do I feel that this is still the wrong way to do this. I was trying to look at other examples but they are hard to fallow with no comments of any kind. what my ultimate goal for right now is make it so that at the prompt wich is : When a player type is get sword it will add a sword to there inventory. Wich I'm not sure if I am going about this the right way. thanks Kevin On Apr 8, 2005 3:01 AM, Andrei [EMAIL PROTECTED] wrote: Bob Gailer bgailer at alum.rpi.edu writes: At 12:22 PM 4/7/2005, Andrei wrote: Kevin python.programming at gmail.com writes: I am fooling around with classes and I was trying to create a very small one player text adventure. I made a class called commands here snip I don't think you're making proper use of classes. IMHO there is no proper use of classes. Perhaps I didn't phrase that quite the way I intended. What I meant is that there are places where classes are obviously beneficial and there are places where a different solution is the easier one. Python is fortunately flexible enough to allow all kinds of approaches. In Python a class is whatever one creates using the class statement. In As it is in all languages. Which is not to say that any class the language allows you to make is actually useful or the best way to do the job. Python has with its tuples, lists, dicts and sets a whole bunch of collection types readily available, which look like collections and are instantly recognized by any programmer as collections (unlike a class, which I for one would expect to be used as more than a collection when reading code). snip Kent's proposal makes IMHO excellent use of the class mechanism. One may also access the class __dict__ directly in lieu of using getattr. Yep, hence my statement that a class in this use case is just a confusing way of using a dict :). I read (perhaps misread) Kevin's post as a question from someone who is new to OOP and wants to learn about it, rather than a request on info regarding the manipulation of class internals. The Commands class is merely a collection of unrelated methods. But they are related. Each represents a game command; the class is the container for the commands. And it might be that as the program expands that there would be multiple instances representing players or saved games or ??? And class properties would keep track of the player's status. Guessing at Kevin's intentions is quite difficult by other means than reading the posted code. A class called Commands that only contains methods implementing actions as results to commands given by the human player, can't reasonably be interpreted as something that will at some point hold a character's status. Yours, Andrei ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Help with classes
I am fooling around with classes and I was trying to create a very small one player text adventure. I made a class called commands here it is: class Commands: def __init__(self): pass def quiting(self): sys.exit() def look(self): print \nNot working yet!\n def get(self): print \nNot working yet!\n def take(self): print \nNot working yet!\n def kill(self): print \nNot working yet!\n def drink(self): print \nNot working yet!\n def eat(self): print \nNot working yet!\n def eq(self): print \nNot working yet!\n def helpsys(self,response): answer = None i = ['look','get','take','kill','drink','eat','eq','help'] while not answer in i: answer = raw_input(response) #Help files will go here return answer there is nothing special about it yet. But in the main code wich is: while 1: com = Commands() a = ['look', 'get', 'take', 'kill', 'drink', 'eat', 'eq', 'help', 'quit'] commandl = raw_input(: ) if commandl not in a: print \nI don't understand that command?\n I want to beable to type in a command from the list at the prompt and have it call one of the functions from the class. I was looking for a shorter way to write it but the only way I can think of is with an if statment for each command. Is there a better way or shorter way to do this? Thanks Kevin ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Operator Overloading
On Mon, 04 Apr 2005 21:14:21 +1200 John Fouhy [EMAIL PROTECTED] wrote: Are you sure you've giving us all the code? No, I was trying to keep it simple. Anyway, here it is, class MyList: def __init__(self, start): self.wrapped = [ ] for x in start: self.wrapped.append(x) def __add__(self, other): return MyList(self.wrapped + other) def __mul__(self, time): return MyList(self.wrapped * time) def __getitem__(self, offset): return self.wrapped[offset] def __len__(self): return len(self.wrapped) def __getslice__(self, low, high): return MyList(self.wrapped[low:high]) def __setitem__(self, index, value): self.wrapped[index] = value print self.wrapped def __getattr__(self, name): return getattr(self.wrapped, name) def __repr__(self): return `self.wrapped` = from mylist import MyList class MyListSub(MyList): calls = 0 def __init__(self, start): self.adds = 0 MyList.__init__(self, start) def __add__(self, other): MyListSub.calls = MyListSub.calls + 1 self.adds = self.adds + 1 return MyList.__add__(self, other) def __mul__(self, time): MyListSub.calls = MyListSub.calls + 1 self.adds = self.adds + 1 return MyList.__mul__(self, time) def __getitem__(self, offset): MyListSub.calls = MyListSub.calls + 1 self.adds = self.adds + 1 return MyList.__getitem__(self, offset) def __len__(self): MyListSub.calls = MyListSub.calls + 1 self.adds = self.adds + 1 return MyList.__len__(self) def __getslice__(self, low, high): MyListSub.calls = MyListSub.calls + 1 self.adds = self.adds + 1 return MyList.__getslice__(self, low, high) def __setitem__(self, index, value): MyListSub.calls = MyListSub.calls + 1 self.adds = self.adds + 1 return MyList.__setitem__(self, index, value) def __getattr__(self, name): MyListSub.calls = MyListSub.calls + 1 self.adds = self.adds + 1 return MyList.__getattr__(self, name) def __sub__(self, index): MyListSub.calls = MyListSub.calls + 1 self.adds = self.adds + 1 return MyList.__sub__(self, index) def __and__(self, value): MyListSub.calls = MyListSub.calls + 1 self.adds = self.adds + 1 MyList.__and__(self, value) def stats(self): return self.calls, self.adds ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Operator Overloading
Following an example from a book, I'm getting an unexpected outcome. The point of exercise is to extend operator overloading methods from a superclass and track the method calls. Here's the code, class MyList: def __init__(self, start): self.wrapped = [ ] for x in start: self.wrapped.append(x) def __add__(self, other): return MyList(self.wrapped + other) def __len__(self): return len(self.wrapped) = from module import MyList class MyListSub(MyList): calls = 0 def __init__(self, start): self.adds = 0 MyList.__init__(self, start) def __add__(self, other): MyListSub.calls = MyListSub.calls + 1 self.adds = self.adds + 1 return MyList.__add__(self, other) def __len__(self): MyListSub.calls = MyListSub.calls + 1 self.adds = self.adds + 1 return MyList.__len__(self) def stats(self): return self.calls, self.adds This is not my code but is taken from the book I'm working with. My problem is that whenever I call to the __add__ method the counters increase by 2 while calls the __len__ method increase the counters by 1 as expected. What I've concluded is that the method which overloads and arithmetic operations executes the counter statements twice while the method which overloads a sequencing operation executes the counter statements only once. Otherwise, I can see no difference between the two methods. Here's an example, A = MyListSub([1, 2, 3]) A.stats() (0, 0) len(A) 3 A.stats() (1, 1) A + [4, 5, 6] [1, 2, 3, 4, 5, 6] A.stats() (3, 3) I'm stumped and and would appreciate any help. Kevin ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] A simple question about creating a program
I was wondering, can you make a program the uses alot of classes do the exact same thing with out useing classes? ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Class and methods?
I am sorta starting to get it. So you could use __init__ to ask for a file name to see if there is one in a folder or not if there is then open that file and conitue where that file left off. If its not there create a new file with that name, then start the program? Or do I have that all wrong? Thanks Kevin On Wed, 30 Mar 2005 21:46:36 +0100, Alan Gauld [EMAIL PROTECTED] wrote: In a class is every def called a method Strictly speaking only those that have a 'self' parameter(or equivalent) The others are unbound functions and pretty useless, usually being the result of programmer errors!... and the def __init__(self) is called the constructor method? Usually. I don't have a problem writting a def I am still not clear on how to use a constructor. Use the constructor to initialise the attributes of your new instance. When you create an instance by calling a class: instance = Class(a,b,c) what happens is that Python creates a blank instance of Class then calls the __init__ method of the new instance passing in the arguments you gave to the class, in our case a,b,c. [ If your class inherits from a superclass then its usually a good idea to call the superclass init method inside your init just to make sure the superclass attributes are all set up properly too. ] Is there a site that explains the constructor in great detail? Well I try... But it depends on how great a detail you want. Great detail implies not easy to understand, in which case the definitive site is the Python documentation! Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] An attribute error problem
Well I think I am going to learn how to create small little server the will just send and recive a message from a client. I just want to know is it easier to use twistedmatrix or just plain socket to create servers? Thanks Kevin On Tue, 29 Mar 2005 06:11:46 -0500, Kent Johnson [EMAIL PROTECTED] wrote: Kevin wrote: Well I just noticed somthing about the entire sServer.py file. All the code under each def is not indented sServer.py mixes tabs and spaces for indentation. If you view it in an editor that indents 8 spaces for a tab it is fine. You might be interested in the reindent.py and untabify.py scripts in the Python/Tools/Scripts directory. Kent ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] An attribute error problem
Hi, I fond this game on the internet I was able to fix most of the errors that it was giving and it will now start up ok. However when you try to enter a name to login to the game it will crash and give this: in sServer.py line 42, in removeConnection self._descriptors.remove(conn._fd) AttributeError: 'tuple' object has no attribute '_fd' How would I go about fixing this. I have uploaded to entire game to http://lotheria.com/mudmaker.zp if anyone would care to take a look at it. Thanks Kevin ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Re: An attribute error problem
Sorry http://www.lotheria.com/mudmaker.zip On Mon, 28 Mar 2005 13:35:20 -0500, Kevin [EMAIL PROTECTED] wrote: Hi, I fond this game on the internet I was able to fix most of the errors that it was giving and it will now start up ok. However when you try to enter a name to login to the game it will crash and give this: in sServer.py line 42, in removeConnection self._descriptors.remove(conn._fd) AttributeError: 'tuple' object has no attribute '_fd' How would I go about fixing this. I have uploaded to entire game to http://lotheria.com/mudmaker.zp if anyone would care to take a look at it. Thanks Kevin ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] An attribute error problem
Nope it will still give the same Attribute error. On Mon, 28 Mar 2005 13:50:07 -0500, Kent Johnson [EMAIL PROTECTED] wrote: Kevin wrote: Hi, I fond this game on the internet I was able to fix most of the errors that it was giving and it will now start up ok. However when you try to enter a name to login to the game it will crash and give this: in sServer.py line 42, in removeConnection self._descriptors.remove(conn._fd) AttributeError: 'tuple' object has no attribute '_fd' How would I go about fixing this. This error is because the caller is passing the wrong kind of argument to removeConnection. It seems to expect a connection object but it is getting a tuple instead. My guess is the error is the line self.closeConnection((self, f)) in checkConnections(). The argument is (self, f) which is a tuple. Maybe it should be self.closeConnection(self._connections[f]) ?? I have uploaded to entire game to http://lotheria.com/mudmaker.zp if anyone would care to take a look at it. That should be http://lotheria.com/mudmaker.zip Kent ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] An attribute error problem
Here is the entire error message: Traceback (most recent call last): File C:\Documents and Settings\Kevin\Desktop\New Folder\mudmaker\mmaker.py, line 55, in ? server.checkConnections(0.1) File C:\Documents and Settings\Kevin\Desktop\New Folder\mudmaker\sServer.py, line 73, in checkConnections self.closeConnection((self, f)) File C:\Documents and Settings\Kevin\Desktop\New Folder\mudmaker\sServer.py, line 49, in closeConnection self.removeConnection((self, conn)) File C:\Documents and Settings\Kevin\Desktop\New Folder\mudmaker\sServer.py, line 42, in removeConnection self._descriptors.remove(conn._fd) AttributeError: 'tuple' object has no attribute '_fd' On Mon, 28 Mar 2005 14:06:49 -0500, Kent Johnson [EMAIL PROTECTED] wrote: Kevin wrote: Nope it will still give the same Attribute error. Please post the entire error including the stack trace and the whole error message. Copy and paste the whole thing, don't transcribe it. Kent On Mon, 28 Mar 2005 13:50:07 -0500, Kent Johnson [EMAIL PROTECTED] wrote: Kevin wrote: Hi, I fond this game on the internet I was able to fix most of the errors that it was giving and it will now start up ok. However when you try to enter a name to login to the game it will crash and give this: in sServer.py line 42, in removeConnection self._descriptors.remove(conn._fd) AttributeError: 'tuple' object has no attribute '_fd' How would I go about fixing this. This error is because the caller is passing the wrong kind of argument to removeConnection. It seems to expect a connection object but it is getting a tuple instead. My guess is the error is the line self.closeConnection((self, f)) in checkConnections(). The argument is (self, f) which is a tuple. Maybe it should be self.closeConnection(self._connections[f]) ?? I have uploaded to entire game to http://lotheria.com/mudmaker.zp if anyone would care to take a look at it. That should be http://lotheria.com/mudmaker.zip Kent ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] An attribute error problem
Well I just noticed somthing about the entire sServer.py file. All the code under each def is not indented, after I fixed all the indentation I got a host of other errors when I try to log in. I posted the files on my site if you want to take a look at it. There are to many problems with it right now. I only wanted to look at how it ran under a linux box and windows to see how a mud server would run. Thanks for the help Kevin On Mon, 28 Mar 2005 20:25:38 -0500, Kent Johnson [EMAIL PROTECTED] wrote: Kevin wrote: Here is the entire error message: Traceback (most recent call last): File C:\Documents and Settings\Kevin\Desktop\New Folder\mudmaker\mmaker.py, line 55, in ? server.checkConnections(0.1) File C:\Documents and Settings\Kevin\Desktop\New Folder\mudmaker\sServer.py, line 73, in checkConnections self.closeConnection((self, f)) The line above is exactly the line I suggested you change (see below). It doesn't look like you did. Did you understand my suggestion? Are you able to change the file? Kent File C:\Documents and Settings\Kevin\Desktop\New Folder\mudmaker\sServer.py, line 49, in closeConnection self.removeConnection((self, conn)) File C:\Documents and Settings\Kevin\Desktop\New Folder\mudmaker\sServer.py, line 42, in removeConnection self._descriptors.remove(conn._fd) AttributeError: 'tuple' object has no attribute '_fd' On Mon, 28 Mar 2005 14:06:49 -0500, Kent Johnson [EMAIL PROTECTED] wrote: Kevin wrote: Nope it will still give the same Attribute error. Please post the entire error including the stack trace and the whole error message. Copy and paste the whole thing, don't transcribe it. Kent On Mon, 28 Mar 2005 13:50:07 -0500, Kent Johnson [EMAIL PROTECTED] wrote: Kevin wrote: Hi, I fond this game on the internet I was able to fix most of the errors that it was giving and it will now start up ok. However when you try to enter a name to login to the game it will crash and give this: in sServer.py line 42, in removeConnection self._descriptors.remove(conn._fd) AttributeError: 'tuple' object has no attribute '_fd' How would I go about fixing this. This error is because the caller is passing the wrong kind of argument to removeConnection. It seems to expect a connection object but it is getting a tuple instead. My guess is the error is the line self.closeConnection((self, f)) in checkConnections(). The argument is (self, f) which is a tuple. Maybe it should be self.closeConnection(self._connections[f]) ?? I have uploaded to entire game to http://lotheria.com/mudmaker.zp if anyone would care to take a look at it. That should be http://lotheria.com/mudmaker.zip Kent ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] How and where to use pass and continue
I am having lot of trouble learning where and when to use pass and continue. The two books that I use don't explian these very good. Is there a website the explains these is great detail? I have also looked at the python tutorial as well. Thanks Kevin ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] How and where to use pass and continue
That was a great help I understand now what they do and how to use them. Thanks alot for all your help. On Sun, 27 Mar 2005 21:43:45 -0500, Bill Mill [EMAIL PROTECTED] wrote: On Sun, 27 Mar 2005 20:37:02 -0500, Kevin [EMAIL PROTECTED] wrote: I am having lot of trouble learning where and when to use pass and continue. The two books that I use don't explian these very good. Is there a website the explains these is great detail? I have also looked at the python tutorial as well. Kevin, I'll try to help you out - pass and continue are pretty simple concepts. Consider the following code snippet which I will try to use to explain both: command = None while command != '3': command = raw_input(Press 1 to pass, 2 to continue, or 3 to exit ) if command == '1': print passing pass elif command == '2': print continuing continue else: print othering print end of loop reached print exiting PASS The 'pass' statement simply means 'do nothing'. In the example above, when the python interpreter encounters the pass statement, it simply continues with its execution as it normally would. It is usually used as the only statement in the body of an if statement to denote explicitly that nothing is to be done. I will often use it as a placeholder so that a program compiles correctly, like: if 'a': do_something() elif 'b': #TODO: implement do_something_else() pass elif 'c': quit_foo() Without the pass statement, there are no statements in the second block, and python will raise a SyntaxError. In the first example above, Python sees the pass, exits the series of 'If...elif... conditions, advances to the final statement of the while loop, prints end of loop reached, and resumes execution at the top of the loop. CONTINUE The continue statement means what it says - continue with the loop, but resume execution at the top of the loop. In the case of a while loop, the exit condition will be evaluated again, and execution resumes from the top. In the case of a for loop, the item being iterated over will move to its next element. Thus, for i in (1,2): print i continue print we never get here Will print 1, hit the continue, update i to the value 2, print 2, hit the continue, and exit because there are no more iterations for i. In the first example I gave, after python reaches the continue, 'command' is again evaluated to see if its value is 3, then the loop proceeds from the top down. If you run the example, you should be able to figure out what's going on. There are a couple more wrinkles - for example, continue only works on the innermost loop in its execution context - but generally, they work as you expect. The longer you work with python, the more you'll find this to be the case, but I'm biased. Hope this helps, and feel free to ask questions about what you don't understand. Peace Bill Mill bill.mill at gmail.com Thanks Kevin ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] How and where to use pass and continue
Ok I have another question now I noticed that at the tope of a while loop there will be somthing like this: test = None while test != enter: test = raw_input(Type a word: ) if test == enter: break what is the purpose of test = None ? Thanks Kevin On Sun, 27 Mar 2005 22:13:45 -0500, Kevin [EMAIL PROTECTED] wrote: That was a great help I understand now what they do and how to use them. Thanks alot for all your help. On Sun, 27 Mar 2005 21:43:45 -0500, Bill Mill [EMAIL PROTECTED] wrote: On Sun, 27 Mar 2005 20:37:02 -0500, Kevin [EMAIL PROTECTED] wrote: I am having lot of trouble learning where and when to use pass and continue. The two books that I use don't explian these very good. Is there a website the explains these is great detail? I have also looked at the python tutorial as well. Kevin, I'll try to help you out - pass and continue are pretty simple concepts. Consider the following code snippet which I will try to use to explain both: command = None while command != '3': command = raw_input(Press 1 to pass, 2 to continue, or 3 to exit ) if command == '1': print passing pass elif command == '2': print continuing continue else: print othering print end of loop reached print exiting PASS The 'pass' statement simply means 'do nothing'. In the example above, when the python interpreter encounters the pass statement, it simply continues with its execution as it normally would. It is usually used as the only statement in the body of an if statement to denote explicitly that nothing is to be done. I will often use it as a placeholder so that a program compiles correctly, like: if 'a': do_something() elif 'b': #TODO: implement do_something_else() pass elif 'c': quit_foo() Without the pass statement, there are no statements in the second block, and python will raise a SyntaxError. In the first example above, Python sees the pass, exits the series of 'If...elif... conditions, advances to the final statement of the while loop, prints end of loop reached, and resumes execution at the top of the loop. CONTINUE The continue statement means what it says - continue with the loop, but resume execution at the top of the loop. In the case of a while loop, the exit condition will be evaluated again, and execution resumes from the top. In the case of a for loop, the item being iterated over will move to its next element. Thus, for i in (1,2): print i continue print we never get here Will print 1, hit the continue, update i to the value 2, print 2, hit the continue, and exit because there are no more iterations for i. In the first example I gave, after python reaches the continue, 'command' is again evaluated to see if its value is 3, then the loop proceeds from the top down. If you run the example, you should be able to figure out what's going on. There are a couple more wrinkles - for example, continue only works on the innermost loop in its execution context - but generally, they work as you expect. The longer you work with python, the more you'll find this to be the case, but I'm biased. Hope this helps, and feel free to ask questions about what you don't understand. Peace Bill Mill bill.mill at gmail.com Thanks Kevin ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] cyclically rotate a seq
Hi folks, I am trying to cyclically rotate a seq until it reached the beginning stage again. I would like to be able to rotate in both directions and using any arbitrary interval. I think that I have this correct, but would be happy for someone to check it and also i am interested in any improvements or enhancements. It is important that this work correctly or the whole rest of my code will be in barf *^-^* hee hee. So any help would be appreciated. #!/usr/bin/env python import sys import random # cyclically rotate a sequence # -- # should work on any sequence type # should work with any hop(n) interval # should also work in both directions (left or right) # -- def rotate(seq, n=1): if len(seq) == 0: return seq # Normalize n, using modulo - even works for negative n n = n % len(seq) return seq[n:] + seq[:n] def test(): start = 1 x = [7, 2, 1, 0, 11, 6, 5, 4] print; print x; print '--' * 8 for i in range(len(x)): out = rotate(x, start) print out start = start + 1 if __name__ == __main__: test() # EOF ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] (no subject)
Hello all. I have just completed my very first python program just a simple number guessing. I would like for someone to try it out if they could and let me know how I did with it and where I could have improved apon it. There are t files main.py and defs.py Thanks ## #!/usr/bin/python #main.py ### from defs import * import sys ### choice() #Lets call the main menu up for the user #This is used to ask if you would like to keep playing# while 1: play = raw_input(What is your choice? ) #Aks use to enter a choice from the menu if play == '3': #If user picks 3 print \nHave a nice day!\n #Tell them to have a nice day sys.exit() #Then exit the entire thing elif play == '2': #If user picks 2 instruct() #Then lets call the instructions function elif play == '1': #If user picks 1 game() #Then lets call the game function for the user to play elif play == '': #This is used is the menu leaves the screen so the user can get it back choice() #Bring back the menu else: print \nYou need to pick 1, 2 or 3 or hit enter to see choices\n #Let the user know that they can only pick 1, 2, 3 or just hit enter and nothing else. ### #defs.py # import random import sys ### #This is not used in the game yet def yesno(question): Asks the use a yes or no question answer = None while answer not in ('y','ye','yes','n','no'): answer = raw_input(question).lower() if answer not in ('y','ye','yes','n','no'): print Please enter Y or N return answer #This is the guessing game# def game(): This is the main part of the guessing game tries = 5 #Set the number of tries to 5 guess = random.randrange(2)+1 #Computer picks a number from 1 to 20 while 1: try: answer = int(raw_input(What is your guess? )) #Ask the user to guess the number if answer != guess: #Check to see if answer is not equal to guessed number tries -= 1 #if answer is wrong reduce the number of tries by 1 print Thats not it, you only have %d tries left %tries #Tell user not right answer if tries == 0: #Check to see if user has run out of tries print \nYou lost this round! #If no tries left let the user know raw_input(\n[Hit Enter to Continue]\n) #Wait for user to go back to main menu choice() #Show main menu for user break #Then break out of the loop if answer == guess: #If the answer is equal to the guessed number print \nCongrats you just Won this round!! #Tell the user he just one in so many tries raw_input([Hit Enter to Continue]) #Wait for user to go back to main menu choice() #Show main menu for user break #Break out of the loop except ValueError: #Lets make sure that the user is only typeing in numbers and nothing else print \nYou can only use numbers\n #Let user know they can only use numbers #This is the main menu for the game def choice(): The main menu of the game print # # # NUMBER GUESSING GAME# # # # - Created by Kevin J # # - [EMAIL PROTECTED] # # # # 1 - Play # # 2 - instructions # # 3 - Quit # \n #This is the instuctions on how to play the game that can be called from the main menu def instruct(): Instructions on how to play the guessing game print\n HOW TO PLAY THE NUMBER GUESSING GAME # To play this game all you need to do is guess a number from 1 to 20. # # You will only have 5 tries to beat the game. Once you have beat the # # game or you have used up all of your 5 tries you will be sent back # # to the main screen were you can quit or start over again
[Tutor] printing out a box of O's
I just started getting in to python and for taking a look at the for loop. I want to print out a box of O's 10o chars long by 10 lines long this is what I came up with. Is there a better way to do this: j = 'O' for i in j*10: print i * 100 Thanks Kevin ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] (no subject)
Hello I'm very new to python but need to write a script to update a single geodatabase table in arcview9 from several dbf files. If I can do this I can then use windows scheduled tasks to up date the tables automatically. The field names in the dbs files are or can be slightly different from those in the geodatabase table and the information already contained within the geodatabase table must be kept.in the ge___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] permutations, patterns, and probability
Greetings, I am working on a program to produce patterns. What would like is for it to exhaustively produce all possible permutations of a sequence of items but for each permutation produce variations, and also a sort of stutter based on probability / weighted randomess. Let us say we have tiles of four primary colors: ['Red', 'Blue', 'Green', 'Yellow']. Now we also have 4 alternatives or substitutes for each color ['Maroon', 'Navy_Blue', 'Forest_Green', 'Dark_Brown'] We pick a unique permutation, say: ['Red', 'Blue', 'Yellow', 'Green'] Now I would like to pick the primary colors substitute (say 30% chance for each element) so instead of our plain ['Red', 'Blue', 'Yellow', 'Green'] we might end up with: ['Red', 'Navy_Blue', 'Yellow', 'Forest_Green'] or ['Maroon', 'Navy_Blue', 'Yellow', 'Green'] Whatever... The main point is that sometimes the original color is retained and sometimes the dark color is substituted. Now I want to take this list and sometimes stutter an element so that there is, let us say a 50% chance for each element, that it is stuttered, and it may be repeated 1 (34%), 2(66%), or 3(33%) times. So that we could get: ['Maroon','Maroon','Navy_Blue', 'Yellow','Yellow','Yellow','Yellow', 'Green'] The program would quit when all 24 (in the case of 4 elements) was exhausted. I have code that makes weighted randomness. I have code that makes permutations, but I am having trouble putting this all together... While i work on it though that i might ask for help... I'd like for the code to be reusable and am building a library of functions for patterns. cheers, kevin ### This is not mine, it is from a python book... I believe the Lutz book def permute(list): if not list:# shuffle any sequence return [list] # empty sequence else: res = [] for i in range(len(list)): rest = list[:i] + list[i+1:]# delete current node for x in permute(rest): # permute the others res.append(list[i:i+1] + x) # add node at front return res mport random ### This this is mine, but seems to work anyway hee hee def windex(lst): '''an attempt to make a random.choose() function that makes weighted choices accepts a list of tuples with the item and probability as a pair like: x = [('one', 0.25), ('two', 0.25), ('three', 0.5)] y=windex(x)''' n = random.uniform(0, 1) for item, weight in lst: if n weight: break n = n - weight return item ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] permutations, patterns, and probability
Tremendously helpful One question though. How can i pluck a unique item from my exhaustive list of permutations without repeats making sure that each one is used once? Like filling a bag, shaking it, and then picking from the bag and removing that item from the bag so it isn't used again -k On Feb 1, 2005, at 8:58 PM, [EMAIL PROTECTED] wrote: f you had a randomizeList function and a stutterList function then your top-level function would look like this: permutations = permute(['Red', 'Blue', 'Yellow', 'Green']) permutations = [ randomizeList(list) for list in permutations ] permutations = [ stutterList(list) for list in permutations ] In other words you start with the basic permutations, then apply the randomize function to each permutation, then apply the stutter function. The randomizeList function should walk through the list, find the right randomize list for that list element (a dict could help with that - look up the list element and get the randomize list), and build a new list with the randomized values. The stutterList function walks through the list building a new list with possibly repeated elements. HTH, Kent ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] How would python messure up in performance?
How well would a multi user texed based game created in just Python run if there were over 300 - 400 players (Just a hypathetical question) Would python be to slow to handle that amount of traffic? Thanks Kevin ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] How would python messure up in performance?
Well not sure how to answer that but I will try. For file I/O you would have a seperat file for each character that would store HP/MANA/MOVE points, store items that the character would have on. Areas would be loaded from there own files with all the creatures and items for that area in the same file. Spells would probably have there own seperate file to load from. As far as unning the game it would be run on a redhat linux server. On Sun, 23 Jan 2005 13:06:47 +, Max Noel [EMAIL PROTECTED] wrote: On Jan 23, 2005, at 12:55, Kevin wrote: How well would a multi user texed based game created in just Python run if there were over 300 - 400 players (Just a hypathetical question) Would python be to slow to handle that amount of traffic? It depends... What would be happening in said game? What would it involve, calculation-wise? What would you be running it on? In that kind of program, the core programming itself is rarely a bottleneck (IOW, Python should work just fine). The true elements on which your game's performance depend are: 1) Connection bandwidth and latency 2) Database access (especially if the DB is not on a remote server) 3) File I/O, if any Could you give us a few more specs? -- Max maxnoel_fr at yahoo dot fr -- ICQ #85274019 Look at you hacker... A pathetic creature of meat and bone, panting and sweating as you run through my corridors... How can you challenge a perfect, immortal machine? ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] How would python messure up in performance?
Thanks for the advise. I am no ware near ready to do this as i am just learning to use python. I just thought it would be interesting to see a mud made in python rather then always in C or C++. So for now I am only going to start out making small programs to learn with. So thanks for answering the question. On Mon, 24 Jan 2005 00:04:25 +, Max Noel [EMAIL PROTECTED] wrote: On Jan 23, 2005, at 23:57, Kevin wrote: Well not sure how to answer that but I will try. For file I/O you would have a seperat file for each character that would store HP/MANA/MOVE points, store items that the character would have on. Areas would be loaded from there own files with all the creatures and items for that area in the same file. Spells would probably have there own seperate file to load from. As far as unning the game it would be run on a redhat linux server. That's a bizarre design choice (for the characters, I mean), this just screams Database, especially since you may find yourself with concurrent write accesses on some files (e.g. a player attacks another while the other is moving). Anyway. This looks like you'll be doing lots of file I/O, with a few calculations inbetween, right? Then unless your server is really shitty, Python should handle this just fine. -- Max maxnoel_fr at yahoo dot fr -- ICQ #85274019 Look at you hacker... A pathetic creature of meat and bone, panting and sweating as you run through my corridors... How can you challenge a perfect, immortal machine? ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor