Re: [Tutor] List to dictionary
Dick Moores wrote: > At 09:53 PM 12/6/2006, Luke Paireepinart wrote: >> # Remove duplicates from a list: >> >>> L = [1,2,2,3,3,3] >> >>> [x for x in L if x not in locals()['_[1]'].__self__] >> [1,2,3] > > Why not > >>> L = [1,2,2,3,3,3] > >>> list(set(L)) > [1, 2, 3] Because the other methods (via set or dict keys) don't preserve order, and the list comprehension version does. The others may have preserved order in this case, but won't always. -Luke ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] subprocess & pyw conflict ?
On Thursday 07 December 2006 00:31, Luke Paireepinart wrote: > Dave S wrote: > > Hi all, > > > > I thought I had my solution with subprocess ... my test code ... > > > > > > > > #!/usr/bin/env python > > # -*- coding: iso8859_1 -*- > > > > import subprocess > > > > a = subprocess.Popen('tasklist.exe', bufsize=0, stdout=subprocess.PIPE, > > universal_newlines=True) > > op = a.stdout.readlines() > > > > for i in op: > > if i.split(' ')[0] == 'gmanager.exe': > > f = open('E:\Documents and Settings\All > > Users\Desktop\gsr_running', 'w') > > f.close() > > > > > > > > works a treat when I run it as proc.py detects the process I am looking > > for & writes a dummy file to the desktop. :) but I get a black windows > > terminal flash up. > > > > The code will eventually run in an app.pyw so to check it would be OK I > > renamed my working proc.py to proc.pyw - it fails :(, No window (as > > expected), no dummy file (not expected) - the process gmanager.exe is > > running. > > > > So there seems to be a problem with subprocess & pyw > > > > Googling I found ... > > https://sourceforge.net/tracker/?func=detail&atid=105470&aid=1358527&grou > >p_id=5470 So I tried the suggested workaround with proc.pyw ... > > > > > > > > #!/usr/bin/env python > > # -*- coding: iso8859_1 -*- > > > > import subprocess > > > > a = subprocess.Popen('tasklist.exe', bufsize=0, stdin=subprocess.PIPE, > > stdout=subprocess.PIPE, universal_newlines=True) > > op = a.stdout.readlines() > > a.stdin.close() > > > > for i in op: > > if i.split(' ')[0] == 'gmanager.exe': > > f = open('E:\Documents and Settings\All > > Users\Desktop\gsr_running', 'w') > > f.close() > > > > > > Still zip, and because there is no terminal, I cannot view any errors ! > > > > Any suggestions welcome :) > > Well, because I'm batting 0 on this thread so far, I think I'll just go > ahead and suggest another bad solution! > You could try redirecting the output of sys.stderr to a file, and you > might be able to see the error message! :D > > If you hadn't said 'any suggestions welcome' I might've kept this to > myself :P Ahhh .. 'any suggestions' is an SOS call - all any any ideas are warmly greeted :) > > >>> import sys > >>> class TestClass(object): > > def __init__(self): > self.data = [] > def write(self,item): > self.data.append(item) > > >>> a = TestClass() > >>> sys.stderr = a > >>> salfjdsljfka321423 > >>> print a.data > > ['\nTraceback (most recent call last):', '\n', ' File "", > line 1, in -toplevel-\n', 'salfjdsljfka321423\n', "NameError: name > 'salfjdsljfka321423' is not defined\n"] > > Except instead of a file-like class, you could just use a real file. > But then it would only leave the last line intact. > So you'd probably want to make a class that wraps a file object, where > the write method just appends to an internal list, > and it writes it all out to the file when you call the Class.close() or > whatever. > Actually, I guess the program stops executing on an exception... > Hmm, not really sure what you'd do exactly. > > > Sure, there are better solutions, and this doesn't really help you with > your original problem, but it at least lets you see your error message! > HTH, > -Luke Thanks for that - I will give it a go & post back :) > > > ___ > > 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] ***SPAM*** List to dictionary
Bill Campbell wrote: > The way I usually do this is something like: > > outDict = dict(map(lambda x: (x, 1), inList)) > names = outDict.keys() > names.sort() This is a really old approach. Since Python 2.3 you can say outDict = dict.fromkeys(inList) or dict.fromkeys(inList, 1) if you cared about the value. Since Python 2.4 you can use a set instead of a dict as shown in other replies. Kent ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] List to dictionary
Luke Paireepinart wrote: > How about this :D > > # Remove duplicates from a list: L = [1,2,2,3,3,3] [x for x in L if x not in locals()['_[1]'].__self__] > [1,2,3] > > [accessed at > http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/204297 ] The problems with this are, it is not portable, even across versions of CPython (try the above in Python 2.4) and it will have poor performance for lists with many unique entries because it searches the entire list for each addition. These recipes are interesting, particularly the discussion for the first one: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52560 http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/438599 Raymond Hettinger (who should know, he is a Python performance guru) said in 2002 that this is the fastest order-preserving method: def uniq(alist)# Fastest order preserving set = {} return [set.setdefault(e,e) for e in alist if e not in set] Perhaps there is now a faster method using a real set, but maybe not because set doesn't have a method that adds to the set and returns the value. Kent ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Is there any good turtorial about numeric python for beginners?
Dave Kuhlman wrote: > On Wed, Dec 06, 2006 at 05:49:22PM -0800, linda.s wrote: >> Is there any good tutorial about numeric python for beginners? >> I have googled around and many of them are either too old or aims at >> experienced users... > > Look here: > > http://new.scipy.org/Wiki/Documentation Particularly the "Documentation from NumPy's predecessor" link which AFAIK is the best available free documentation for NumPy. Alternately you can buy the current docs. Kent ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] How to center teh window using Tkinter
Hi folks, I want to center the window. I am using Tkinter and want to center the window as per the screen size. The size of the window is not fixed, I mean the height is not fixed, so I cannot use fixed parameters that can be passed to geometry() method. IF the height is more, the window should be positioned at the top.. I hope I am clear about my question. Thanks in anticipation. Best Regards, Asrarahmed Kadri -- To HIM you shall return. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] ***SPAM*** List to dictionary
> -Original Message- > From: [EMAIL PROTECTED] > [mailto:[EMAIL PROTECTED] On Behalf Of Luke Paireepinart > Sent: Wednesday, December 06, 2006 10:54 PM > To: tutor@python.org > Subject: Re: [Tutor] ***SPAM*** List to dictionary > > Also, why is there now a **SPAM* in the subject heading? > > Wonderingly, > -Luke > Maybe Bill was labeling it SPAM since it was posted twice to the list? Wed Dec 6 17:00:18 CET 2006 Thu Dec 7 04:31:55 CET 2006 Also, I tried to explain in my reply yesterday. "The next statement (temp[i] = 0) is where I get confused. Can someone please explain what is happening here. " I'm confused. %) - NOTICE: This e-mail transmission and any documents or files attached to it contain information for the sole use of the above-identified individual or entity. Its contents may be privileged, confidential, and exempt from disclosure under the law. Any dissemination, distribution, or copying of this communication is strictly prohibited. Please notify the sender immediately if you are not the intended recipient. FGNS ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] __init__.py for running a file from commandline?
On 11/27/06, Michael P. Reilly <[EMAIL PROTECTED]> wrote: When you type something from the command-line, you are at the whims of the WinXP command shell. You have to follow its rules, not Python's. It would need to have "python" in %PATH%, and then it would need to have to run "python C:\path\to\pyroot\utils\commands\mygrep.py". The arguments are determined before Python is even started, and they are parsed by the WinXP DOS-a-like shell. (Also why you cannot have ".", only Python understands dots). Doesn't python receive the command line argument, path-to-script in this case, for its own use and parsing? It seems like the solution I really seek is a command line switch that tells python that I am using namespace conventions, and that it should begin searching in the directory that PYTHONPATH points to. For example, c:> python -namespace utils.commands.mygrep.py Do either of you know of such a convenience? I suppose I could write a batch file, python.bat, that could implement this wrapping logic. Kent mentioned issues with importing modules, and those would still hold true since those are after Python starts. Also, the WinXP shell, does handle forward slashs, but you were probably not in the proper directory for the shell to find the file using "utils/commands/mygrep.py" pathname. Good spot-- forward slashes work, simply as relative path specifiers, so you have to be in the correct directory. I was not. Thus the problem. Also: it appears forward slashes only work as relative path specifiers (e.g., cd /temp), but fail if with a drive letter (e.g., c:/temp). Thanks guys. Marcus ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] subprocess & pyw conflict ?
On Thursday 07 December 2006 10:25, Dave S wrote: > On Thursday 07 December 2006 00:31, Luke Paireepinart wrote: > > Dave S wrote: > > > Hi all, > > > > > > I thought I had my solution with subprocess ... my test code ... > > > > > > > > > > > > #!/usr/bin/env python > > > # -*- coding: iso8859_1 -*- > > > > > > import subprocess > > > > > > a = subprocess.Popen('tasklist.exe', bufsize=0, stdout=subprocess.PIPE, > > > universal_newlines=True) > > > op = a.stdout.readlines() > > > > > > for i in op: > > > if i.split(' ')[0] == 'gmanager.exe': > > > f = open('E:\Documents and Settings\All > > > Users\Desktop\gsr_running', 'w') > > > f.close() > > > > > > > > > > > > works a treat when I run it as proc.py detects the process I am looking > > > for & writes a dummy file to the desktop. :) but I get a black windows > > > terminal flash up. > > > > > > The code will eventually run in an app.pyw so to check it would be OK I > > > renamed my working proc.py to proc.pyw - it fails :(, No window (as > > > expected), no dummy file (not expected) - the process gmanager.exe is > > > running. > > > > > > So there seems to be a problem with subprocess & pyw > > > > > > Googling I found ... > > > https://sourceforge.net/tracker/?func=detail&atid=105470&aid=1358527&gr > > >ou p_id=5470 So I tried the suggested workaround with proc.pyw ... > > > > > > > > > > > > #!/usr/bin/env python > > > # -*- coding: iso8859_1 -*- > > > > > > import subprocess > > > > > > a = subprocess.Popen('tasklist.exe', bufsize=0, stdin=subprocess.PIPE, > > > stdout=subprocess.PIPE, universal_newlines=True) > > > op = a.stdout.readlines() > > > a.stdin.close() > > > > > > for i in op: > > > if i.split(' ')[0] == 'gmanager.exe': > > > f = open('E:\Documents and Settings\All > > > Users\Desktop\gsr_running', 'w') > > > f.close() > > > > > > > > > Still zip, and because there is no terminal, I cannot view any errors ! > > > > > > Any suggestions welcome :) > > > > Well, because I'm batting 0 on this thread so far, I think I'll just go > > ahead and suggest another bad solution! > > You could try redirecting the output of sys.stderr to a file, and you > > might be able to see the error message! :D > > > > If you hadn't said 'any suggestions welcome' I might've kept this to > > myself :P > > Ahhh .. 'any suggestions' is an SOS call - all any any ideas are warmly > greeted :) > > > >>> import sys > > >>> class TestClass(object): > > > > def __init__(self): > > self.data = [] > > def write(self,item): > > self.data.append(item) > > > > >>> a = TestClass() > > >>> sys.stderr = a > > >>> salfjdsljfka321423 > > >>> print a.data > > > > ['\nTraceback (most recent call last):', '\n', ' File "", > > line 1, in -toplevel-\n', 'salfjdsljfka321423\n', "NameError: name > > 'salfjdsljfka321423' is not defined\n"] > > > > Except instead of a file-like class, you could just use a real file. > > But then it would only leave the last line intact. > > So you'd probably want to make a class that wraps a file object, where > > the write method just appends to an internal list, > > and it writes it all out to the file when you call the Class.close() or > > whatever. > > Actually, I guess the program stops executing on an exception... > > Hmm, not really sure what you'd do exactly. > > > > > > Sure, there are better solutions, and this doesn't really help you with > > your original problem, but it at least lets you see your error message! > > HTH, > > -Luke > > Thanks for that - I will give it a go & post back :) > Oh my head OK after much tinkering I got the following to work with .pyw # scan windows task list to see if GSR is running f = os.popen('tasklist.exe', 'r') plist = f.readlines() f.close gsr_running = False # scan for GSR program for line in plist: if line.split(' ')[0] == 'gmanager.exe': gsr_running = True A Dave can relax, chill, project finished ... all works ... god .. (homer simpson moment !) > > > ___ > > > 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] OT GPL project finished, presentation looming
OK this is an OT question I have just finished a Python QT project for work, written in my own free time over the last several months (and with a lot of help from you guys :). Its 5500 lines of python over several modules (for me that huge) and a CSV 'rules' file of 500 lines, all GPL'd We use a commercial program that connects to remote intruder alarm systems and downloads their configs. Up to 80,000 software attributes per site. My python QT app scans the database files (.dbf), decodes them, scans them against a CSV list of rules and throws any anomaly's out to a GUI. It essentially audits the site programming checking for incorrect programming, configuration errors etc. In addition it generates audited PDF certificates, engineer summary's PDFs and user manuals PDFs for each specific site. Sometime in January I have to give a presentation and I know one of the questions will be. "Its what we want but you are not a company, what if you leave ?" I need an answer,.. What am I asking ... If need be are any of you for hire ? Dave PS it looks great, would love to post some pngs but it would violate the list rules :( ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Newbie question: random.sample illusion?
Hi everybody, I'm in the process of learning Python and working my way through O'Reilly's "Learning Python". As an excercise I wrote (some copy/paste as well) a small lottery program just to learn how to work with lists and dictionarys etc. The user has to enter 6 numbers from a range(1-45). The numbers are stored in a list(num_list). Then the program asks the user how many times(vDraws) he wants to play the lottery with his numbers. After entering the program draws the lottery the desired number of times and compares the winning numbers with the users numbers. Now, by accident I stumbled upon the following; if the user enters the numbers 1 to 6 as his lottery numbers he always wins! So somewhere I must have made a mistake. Could somebody have a look at the code please and tell me where I took a wrong turn? winnings=0 right2=1 right3=4 right4=15 right5=450 right6=100 user_nums=[] # empty List for numbers print "Kies je nummers tussen 0 en 46" print whereat=1 listindex=0 # when 7th number is inputted loop breaks while whereat <= 6: num=raw_input("Voer "+str(whereat)+". Lotto nummer in: ") # check that user inputted value is not smaller than 1 or bigger than 45 # and that it is not already in user_nums if num != "" and len(num) != 0: if int(num) >= 1 and int(num) <= 45 and num not in user_nums: user_nums.append(num) whereat+=1 listindex+=1 # if above statement if false just pass and ask for the number again! else: pass print '1 trekking kost U 1 euro inzet' print vDraws = input("Hoe vaak wil je in de lotto spelen met deze nummers? :>") # Create dictionary for statiscal purposes later on :-) d={1:0, 2:0, 3:0, 4:0, 5:0, 6:0, 7:0, 8:0, 9:0, 10:0, 11:0, 12:0, 13:0, 14:0, 15:0, 16:0, 17:0, 18:0, 19:0, 20:0, 21:0, 22:0, 23:0, 24:0, 25:0, 26:0, 27:0, 28:0, 29:0, 30:0, 31:0, 32:0, 33:0, 34:0, 35:0, 36:0, 37:0, 38:0, 39:0, 40:0, 41:0, 42:0, 43:0, 44:0, 45:0} match=0 count=0 inzet=vDraws * 1 while vDraws > 0: x=random.sample(range(1,46), 6)# draws lottery from given range for i in x: y=int(i) d[y] = int(d[y])+ 1 #stores values in lottonumbers dictionary for p in user_nums: count+=1 y=str(y) if p in y: match+=1 # increase matching variable by one if its right number # caculating winnings if match ==2: winnings+=right2 match=0 elif match ==3: winnings+=right3 match=0 elif match == 4: winnings+=right4 match=0 elif match == 5: winnings+=right5 match=0 elif match == 6: winnings+=right6 match=0 vDraws = vDraws - 1 # sorting dictionary by its values items=d.items() backitems=[ [v[1],v[0]] for v in items] backitems.sort() sortedlist=[ backitems[i][1] for i in range(0,len(backitems))] print print print saldo=winnings-inzet print print print '-' * 80 if saldo > 0: print 'U heeft', saldo, 'euro winst gemaakt!' else: print 'U heeft', saldo, ' euro verlies geleden!' print 'U heeft in totaal gewonnen', winnings, 'euro.' print 'Uw inzet was', inzet, 'euro' print 'De 6 meest gevallen getallen waren:', for x in sortedlist[0:6]: print x, #prints the 6 most drawn numbers _ Veilig & gerust mailen met de verbeterde antivirusscan van Live Mail! http://imagine-windowslive.com/mail/launch/default.aspx?Locale=nl-nl ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] ***SPAM*** List to dictionary
On Thu, 2006-12-07 at 08:22 -0700, Mike Hansen wrote: > > > -Original Message- > > From: [EMAIL PROTECTED] > > [mailto:[EMAIL PROTECTED] On Behalf Of Luke Paireepinart > > Sent: Wednesday, December 06, 2006 10:54 PM > > To: tutor@python.org > > Subject: Re: [Tutor] ***SPAM*** List to dictionary > > > > Also, why is there now a **SPAM* in the subject heading? > > > > Wonderingly, > > -Luke > > > > Maybe Bill was labeling it SPAM since it was posted twice to the list? > > Wed Dec 6 17:00:18 CET 2006 > Thu Dec 7 04:31:55 CET 2006 > > Also, I tried to explain in my reply yesterday. "The next statement > (temp[i] = 0) is where I get confused. temp is a dictionary. ## earlier code was temp = {} i is a name from a list called names. temp[i] is a reference into the dictionary using i as a key. temp[i] = 0 binds that reference to 0. Any previous value for temp[i] is discarded. temp is simply being used to track distinct names. Any name from names will have one and only one occurrence in the list of dictionary keys. So temp.keys() will contain each name exactly once. As covered in a recent thread, the ordering of the names will probably be different from the original names list. > Can someone please explain what is happening here. " > > I'm confused. %) > - > > NOTICE: This e-mail transmission and any documents or files attached to > it contain information for the sole use of the above-identified individual > or entity. > > Its contents may be privileged, confidential, and exempt from disclosure > under the law. > Any dissemination, distribution, or copying of this communication is > strictly prohibited. > > Please notify the sender immediately if you are not the intended recipient. > > FGNS > ___ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor -- Lloyd Kvam Venix Corp ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] OT GPL project finished, presentation looming
Dave S wrote: > [snip explanation of program] Sounds really cool! > > Sometime in January I have to give a presentation and I know one of the > questions will be. "Its what we want but you are not a company, what if you > leave ?" I need an answer,.. > My understanding is that if it's GPL'ed, they can use it whether you work there or not. Is that not true? > What am I asking ... If need be are any of you for hire ? > Why would hiring someone else help in this situation? > Dave > > PS it looks great, would love to post some pngs but it would violate the list > rules :( > You can just upload the PNGs to a free webhost and link us to them, like Photobucket or Imageshack. I imagine people just don't want big attachments in their e-mail. If you give them a link to the picture then they only have to download it if they really want to see what it is. HTH, -Luke ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] OT GPL project finished, presentation looming
On Thursday 07 December 2006 17:54, Luke Paireepinart wrote: > Dave S wrote: > > [snip explanation of program] > > Sounds really cool! Its a bit niche - but cool > > > Sometime in January I have to give a presentation and I know one of the > > questions will be. "Its what we want but you are not a company, what if > > you leave ?" I need an answer,.. > > My understanding is that if it's GPL'ed, they can use it whether you > work there or not. > Is that not true? Sorry I did not mean that, the GPL thing is AOK > > > What am I asking ... If need be are any of you for hire ? > > Why would hiring someone else help in this situation? I work for national company, they are very interested in what I am doing, there is nothing else in the marketplace that does this, but they are used to dealing with large software company's. They will be concerned about using my app because I am one person. What if I get hit by a bus ! what if I leave ? what happens when a new version of controller comes out & new CSV rules need to be written - what would they do ? Its all GPL so no secrets, my guess is that if $$ was offered to the Python community someone would be willing to maintain the code but I am unsure of how it would actually work ? Is it a case of "hello, python programmer for hire ?" or is there an 'official' procedure that I can include in my presentation ? I would guess this is a common problem for GPL software being introduced into commercial settings (the whole support thing). (It appears that none of the company's IT professionals can program !) > > Dave > > > > PS it looks great, would love to post some pngs but it would violate the > > list rules :( > > You can just upload the PNGs to a free webhost and link us to them, like > Photobucket or Imageshack. > > I imagine people just don't want big attachments in their e-mail. If > you give them a link to the picture > then they only have to download it if they really want to see what it is. OK I will do my presentation then do that as a kind of thank you for all your help :) > > HTH, > -Luke ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Newbie question: random.sample illusion?
Moedeloos Overste wrote: > Hi everybody, > > I'm in the process of learning Python and working my way through O'Reilly's > "Learning Python". As an excercise I wrote (some copy/paste as well) a small > lottery program just to learn how to work with lists and dictionarys etc. > > The user has to enter 6 numbers from a range(1-45). The numbers are stored > in a list(num_list). Then the program asks the user how many times(vDraws) > he wants to play the lottery with his numbers. After entering the program > draws the lottery the desired number of times and compares the winning > numbers with the users numbers. > > Now, by accident I stumbled upon the following; if the user enters the > numbers 1 to 6 as his lottery numbers he always wins! So somewhere I must > have made a mistake. Could somebody have a look at the code please and tell > me where I took a wrong turn? > > > > winnings=0 > right2=1 > right3=4 > right4=15 > right5=450 > right6=100 > it might be clearer to do prizes = [0,0,1,4,15,450,100] > user_nums=[] # empty List for numbers > print "Kies je nummers tussen 0 en 46" > print > whereat=1 > listindex=0 > What is the point of having two variables here? You never use listindex. You should start whereat at 0. > # when 7th number is inputted loop breaks > while whereat <= 6: > And loop until whereat is less than 6. That's the general consensus on looping in Computer Science. Starting at 0. > num=raw_input("Voer "+str(whereat)+". Lotto nummer in: ") > And just change this line to str(whereat+1) instead. > # check that user inputted value is not smaller than 1 or bigger than 45 > # and that it is not already in user_nums > if num != "" and len(num) != 0: > If they enter 'a' your program will crash. A better solution would be to use a try except block. eg. try: tmp = int(num) if tmp >= 1 and tmp <= 45 and tmp not in user_nums: user_nums.append(tmp) whereat += 1 except ValueError: pass > if int(num) >= 1 and int(num) <= 45 and num not in user_nums: > user_nums.append(num) > Also note here that you're using the integer representation of num to compare it to 1 and 45, but then you're storing the string representation of it in user_nums. This may be part of why you're having a problem. > whereat+=1 > listindex+=1 > # if above statement if false just pass and ask for the number > again! > else: > pass > print '1 trekking kost U 1 euro inzet' > print > vDraws = input("Hoe vaak wil je in de lotto spelen met deze nummers? :>") > > # Create dictionary for statiscal purposes later on :-) > d={1:0, 2:0, 3:0, 4:0, 5:0, 6:0, 7:0, 8:0, 9:0, 10:0, 11:0, 12:0, 13:0, > 14:0, 15:0, > 16:0, 17:0, 18:0, 19:0, 20:0, 21:0, 22:0, 23:0, 24:0, 25:0, 26:0, 27:0, > 28:0, > 29:0, 30:0, 31:0, 32:0, 33:0, 34:0, 35:0, 36:0, 37:0, 38:0, 39:0, 40:0, > 41:0, 42:0, > 43:0, 44:0, 45:0} > This could be: d = {} for x in range(1,46): d[x] = 0 Or several varations of this, using lambda & map, and such. > match=0 > count=0 > You don't use count in your program anywhere. > inzet=vDraws * 1 > There's absolutely no reason to multiply something by 1. > while vDraws > 0: > x=random.sample(range(1,46), 6)# draws lottery from given range > for i in x: > y=int(i) > This line is unnecessary, 'i' is already an integer. > d[y] = int(d[y])+ 1 #stores values in lottonumbers dictionary > Can be shortened to d[y] += 1 > for p in user_nums: >count+=1 > no reason to do this because the for loop will end when it runs out of variables. >y=str(y) > Again, if you leave the original items as integers you don't have to do all this conversion. >if p in y: > I would change this to 'if p == y', because I'm not sure what 'in' is doing here. > match+=1 # increase matching variable by one if its right > number > > # caculating winnings > if match ==2: > winnings+=right2 > match=0 > elif match ==3: > winnings+=right3 > match=0 > elif match == 4: > winnings+=right4 > match=0 > elif match == 5: > winnings+=right5 > match=0 > elif match == 6: > winnings+=right6 > match=0 > Using that prizes list, this can be shortened to winnings += prizes[match] match = 0 > vDraws = vDraws - 1 > Or vDraws -= 1 > # sorting dictionary by its values > items=d.items() > backitems=[ [v[1],v[0]] for v in items] > backitems.sort() > sortedlist=[ backitems[i][1] for i in range(0,len(backitems))] > > print > print > print > saldo=winnings-inzet > print > print > print '-' * 80 > if saldo > 0: > print 'U heeft', saldo, 'euro winst gemaakt!' > else: > print 'U heeft', saldo, ' euro verlies geleden!' > > > print 'U
Re: [Tutor] Newbie question: random.sample illusion?
Moedeloos Overste wrote: > Hi everybody, > > I'm in the process of learning Python and working my way through O'Reilly's > "Learning Python". As an excercise I wrote (some copy/paste as well) a small > lottery program just to learn how to work with lists and dictionarys etc. > > The user has to enter 6 numbers from a range(1-45). The numbers are stored > in a list(num_list). Then the program asks the user how many times(vDraws) > he wants to play the lottery with his numbers. After entering the program > draws the lottery the desired number of times and compares the winning > numbers with the users numbers. > > Now, by accident I stumbled upon the following; if the user enters the > numbers 1 to 6 as his lottery numbers he always wins! So somewhere I must > have made a mistake. Could somebody have a look at the code please and tell > me where I took a wrong turn? > > Ooops, I accidentally hit 'send' on that other e-mail before I was done with it. I was just going to say that you forgot to include 'random'. Also, here is the code with the changes I suggested. I ran it on 1,2,3,4,5,6 for 80 tries and didn't win every time. #code begins here. import random winnings=0 prizes = [0,0,1,4,15,450,100] user_nums=[] # empty List for numbers print "Kies je nummers tussen 0 en 46" print whereat=0 # when 6th number is inputted loop breaks while whereat < 6: num=raw_input("Voer "+str(whereat+1)+". Lotto nummer in: ") # check that user inputted value is not smaller than 1 or bigger than 45 # and that it is not already in user_nums try: tmp = int(num) if tmp >= 1 and tmp <= 45 and tmp not in user_nums: user_nums.append(tmp) whereat += 1 except ValueError: pass print '1 trekking kost U 1 euro inzet' print vDraws = input("Hoe vaak wil je in de lotto spelen met deze nummers? :>") # Create dictionary for statiscal purposes later on :-) d = {} for x in range(1,46): d[x] = 0 match=0 count=0 inzet=vDraws while vDraws > 0: x=random.sample(range(1,46), 6)# draws lottery from given range for i in x: d[i] += 1 #stores values in lottonumbers dictionary for p in user_nums: if p == i: match+=1 # increase matching variable by one if its right number winnings += prizes[match] match = 0 vDraws -= 1 # sorting dictionary by its values items=d.items() backitems=[ [v[1],v[0]] for v in items] backitems.sort() sortedlist=[ backitems[i][1] for i in range(0,len(backitems))] print '\n\n' saldo=winnings-inzet print '\n' print '-' * 80 if saldo > 0: print 'U heeft', saldo, 'euro winst gemaakt!' else: print 'U heeft', saldo, ' euro verlies geleden!' print 'U heeft in totaal gewonnen', winnings, 'euro.' print 'Uw inzet was', inzet, 'euro' print 'De 6 meest gevallen getallen waren:', for x in sortedlist[0:6]: print x, #prints the 6 most drawn numbers ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Newbie question: random.sample illusion?
Dear Luke, Wow, thank you for all the input.You really made an effort .It's always nice when someone is willing to share his knowledge with you. You really opened my eyes on some things. I guess it's gonna be a long night for me. But I'm really enjoying myself though :-) Regards, Robert >From: Luke Paireepinart <[EMAIL PROTECTED]> >To: Moedeloos Overste <[EMAIL PROTECTED]> >CC: tutor@python.org >Subject: Re: [Tutor] Newbie question: random.sample illusion? >Date: Thu, 07 Dec 2006 12:17:23 -0600 > >Moedeloos Overste wrote: >>Hi everybody, >> >>I'm in the process of learning Python and working my way through >>O'Reilly's "Learning Python". As an excercise I wrote (some copy/paste as >>well) a small lottery program just to learn how to work with lists and >>dictionarys etc. >> >>The user has to enter 6 numbers from a range(1-45). The numbers are stored >>in a list(num_list). Then the program asks the user how many times(vDraws) >>he wants to play the lottery with his numbers. After entering the program >>draws the lottery the desired number of times and compares the winning >>numbers with the users numbers. >> >>Now, by accident I stumbled upon the following; if the user enters the >>numbers 1 to 6 as his lottery numbers he always wins! So somewhere I must >>have made a mistake. Could somebody have a look at the code please and >>tell me where I took a wrong turn? >> >> >> >>winnings=0 >>right2=1 >>right3=4 >>right4=15 >>right5=450 >>right6=100 >> >it might be clearer to do >prizes = [0,0,1,4,15,450,100] >>user_nums=[] # empty List for numbers >>print "Kies je nummers tussen 0 en 46" >>print >>whereat=1 >>listindex=0 >> >What is the point of having two variables here? >You never use listindex. >You should start whereat at 0. >># when 7th number is inputted loop breaks >>while whereat <= 6: >> >And loop until whereat is less than 6. >That's the general consensus on looping in Computer Science. Starting at >0. >> num=raw_input("Voer "+str(whereat)+". Lotto nummer in: ") >> >And just change this line to str(whereat+1) instead. >> # check that user inputted value is not smaller than 1 or bigger than >>45 >> # and that it is not already in user_nums >> if num != "" and len(num) != 0: >> >If they enter 'a' your program will crash. >A better solution would be to use a try except block. >eg. try: > tmp = int(num) > if tmp >= 1 and tmp <= 45 and tmp not in user_nums: > user_nums.append(tmp) > whereat += 1 >except ValueError: >pass >> if int(num) >= 1 and int(num) <= 45 and num not in user_nums: >> user_nums.append(num) >> >Also note here that you're using the integer representation of num to >compare it to 1 and 45, >but then you're storing the string representation of it in user_nums. >This may be part of why you're having a problem. >> whereat+=1 >> listindex+=1 >> # if above statement if false just pass and ask for the >>number again! >> else: >> pass >>print '1 trekking kost U 1 euro inzet' >>print >>vDraws = input("Hoe vaak wil je in de lotto spelen met deze nummers? :>") >> >># Create dictionary for statiscal purposes later on :-) >>d={1:0, 2:0, 3:0, 4:0, 5:0, 6:0, 7:0, 8:0, 9:0, 10:0, 11:0, 12:0, 13:0, >>14:0, 15:0, >> 16:0, 17:0, 18:0, 19:0, 20:0, 21:0, 22:0, 23:0, 24:0, 25:0, 26:0, >>27:0, 28:0, >> 29:0, 30:0, 31:0, 32:0, 33:0, 34:0, 35:0, 36:0, 37:0, 38:0, 39:0, >>40:0, 41:0, 42:0, >> 43:0, 44:0, 45:0} >> >This could be: >d = {} >for x in range(1,46): >d[x] = 0 >Or several varations of this, using lambda & map, and such. >>match=0 >>count=0 >> >You don't use count in your program anywhere. >>inzet=vDraws * 1 >> >There's absolutely no reason to multiply something by 1. >>while vDraws > 0: >> x=random.sample(range(1,46), 6)# draws lottery from given range >> for i in x: >> y=int(i) >> >This line is unnecessary, 'i' is already an integer. >> d[y] = int(d[y])+ 1 #stores values in lottonumbers dictionary >> >Can be shortened to d[y] += 1 >> for p in user_nums: >>count+=1 >> >no reason to do this because the for loop will end when it runs out of >variables. >>y=str(y) >> >Again, if you leave the original items as integers you don't have to do all >this conversion. >>if p in y: >> >I would change this to 'if p == y', because I'm not sure what 'in' is doing >here. >> match+=1 # increase matching variable by one if its right >>number >> >> # caculating winnings >> if match ==2: >> winnings+=right2 >> match=0 >> elif match ==3: >> winnings+=right3 >> match=0 >> elif match == 4: >> winnings+=right4 >> match=0 >> elif match == 5: >> winnings+=right5 >> match=0 >> elif match == 6: >> winnings+=right6 >>
Re: [Tutor] OT GPL project finished, presentation looming
"Dave S" <[EMAIL PROTECTED]> wrote > They will be concerned about using my app because I am one person. > What if I > get hit by a bus ! what if I leave ? This is a common problem in big companies including my own. For years they wouldn't even use the GNU software because it was "unsupported". I even had to buy a commercial version of emacs for about $300... Eventually cygnus started offering support (for $5K per year) and they allowed us to use emacs, gcc etc Eventually even X windows. Now they are more relaxed and we use Linux to run our internal DHCP and DNS, even some web servers... > ...(It appears that none of the > company's IT professionals can program !) That's also not unusual. In fact our company appears to be slowly heading that way. We used to have 11,000 IT professionals of which around 5000 were developers. Now we have 13,000 IT professionals of whom about 1000 still write code. The coding is mainly offshored to India and Eastern Europe. Our internal people are being retrained on "higher value" roles like business analysis, design/architecture, deployment/integration and project management. So I now program in python as and when I can and call it prototyping... They call it progress. Alan G. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] function and module
I am reading a sample code and want to figure out where a function (for instance, abc) is from. There are many lines such as from XXX import * Is there a way not going through all these imported modules to find where the abc is from (by the way, the abc function is not in the current module)? Thanks, Linda ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] mlab and numeric
can anyone tell me the relationship between MLab and Numeric? Especially MLab, there is very little information about it. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor