[Tutor] Issue with Python 2.7.2 - beginner needing help
Hello! I am just beginning to learn Python from the book Starting Out With Python - 2nd Edition. I have read and completed exercises up to page 45. I am currently learning how to display multiple items with one call to the print function. ex: 1 # This program demonstrates a variable. 2 room = 503 3 print('I am staying in room number', room) Program Output: I am staying in room number 503 However, when I type this out exactly as shown, my program output looks very similar to line 3. My program output should look like: I am staying in room number 503 BUT, it looks like this: ('I am staying in room number', 503) How can this be fixed? I need help and can't find any information when I search the web. I don't know if this is a problem that can be fixed or if it is a problem at all. I know I have a limited Python vocabulary and it may be hard to understand my question. I tried to explain as clearly as possible. If you can understand my issue and have the time to answer my question, I would greatly appreciate it. I would rather not continue my lessons until this is resolved. Sincerely, Tonyelle Evans ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] Issue with Python 2.7.2 - beginner needing help
Hi Tonyelle Your code doesn't work as expected due to your 2nd edition book uses Python 3x, see page xi, 'Changes in this edition'. This would work for your version of Python... room = 503 print 'I am staying in room number', room If you're new, Python 2.7.2 is (IMO) a better choice, many more tutorials, books etc available as resources, including Gaddis's 1st edition 'Starting Out with Python' which uses Python 2x. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] Python problem
Hello, I send you a mail at 29.12.2011. about problem with my IDLE (Python GUI) and I didnt recive any ansfer; Instead, I am receiving correspondence between other members of forum; Honestly, I don't want to receive all this conversation's. Thank you. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Python problem
To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor On Tue, Jan 10, 2012 at 11:04 AM, Bojan Antonijevic wrote: > Hello, > > I send you a mail at 29.12.2011. about problem with my IDLE (Python GUI) and > I didnt recive any ansfer; Instead, I am receiving correspondence between > other members of forum; Honestly, I don't want to receive all this > conversation's. > Thank you. > > ___ > 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] a question about MySQLdb in python
hi, all: python's version: 2.6. MySQLdb version: 1.2.3. I once encounter with a question like this: File "/usr/local/lib/python2.6/dist-packages/MySQL_python-1.2.3-py2.6-linux-x86_64.egg/MySQLdb/connections.py", line 36, in defaulterrorhandler raise errorclass, errorvalue OperationalError: (2006, 'MySQL server has gone away') and i try to find the exception is how to perform to us in the source code. when i read the source code, some questions puzzled me! question 1: how to find the words "2006, 'MySQL server has gone away" in sourced code? question 2: in MySQLdb/cursors.py , the method errorhandler() just receive two parameters such as exc,value when it's be invoked. however, in MySQLdb/connection.py, we define it as one receives 4 parameters such connection, cursor, erorclass, errorvalue a method should accepts 4 parameters is invoked by 2 parameters. how to explain it? question 3: in MySQLdb/connection.py, the module cursors is been imported. while, In MySQLdb/cursors.py, some methods such as errorhandler in MySQLdb/connection.py is been invoked. the two module, which one is execute first? which one is added to mem first? some important codes are shown as follows. any response will be welcome! -- Jia Xiaolei --- source code about MySQLdb -- # MySQLdb/connections.py import cursors def defaulterrorhandler(connection, cursor, errorclass, errorvalue): """ If cursor is not None, (errorclass, errorvalue) is appended to cursor.messages; otherwise it is appended to connection.messages. Then errorclass is raised with errorvalue as the value. You can override this with your own error handler by assigning it to the instance. """ error = errorclass, errorvalue if cursor: cursor.messages.append(error) else: connection.messages.append(error) del cursor del connection raise errorclass, errorvalue class Connection(_mysql.connection): """MySQL Database Connection Object""" default_cursor = cursors.Cursor errorhandler = defaulterrorhandler def __init__(self, *args, **kwargs): # some codes self.cursorclass = kwargs2.pop('cursorclass', self.default_cursor) charset = kwargs2.pop('charset', '') def cursor(self, cursorclass=None): """ Create a cursor on which queries may be performed. The optional cursorclass parameter is used to create the Cursor. By default, self.cursorclass=cursors.Cursor is used. """ return (cursorclass or self.cursorclass)(self) def xx(yy): # some codes # MySQLdb/cursors.py class BaseCursor(object): def __init__(self, connection): from weakref import proxy self.connection = proxy(connection) self.description = None self.description_flags = None self.rowcount = -1 self.arraysize = 1 self._executed = None self.lastrowid = None self.messages = [] self.errorhandler = connection.errorhandler self._result = None self._warnings = 0 self._info = None self.rownumber = None def execute(self, query, args=None): """Execute a query. query -- string, query to execute on server args -- optional sequence or mapping, parameters to use with query. Note: If args is a sequence, then %s must be used as the parameter placeholder in the query. If a mapping is used, %(key)s must be used as the placeholder. Returns long integer rows affected, if any """ from types import ListType, TupleType from sys import exc_info del self.messages[:] db = self._get_db() charset = db.character_set_name() if isinstance(query, unicode): query = query.encode(charset) if args is not None: query = query % db.literal(args) try: r = self._query(query) except TypeError, m: if m.args[0] in ("not enough arguments for format string", "not all arguments converted"): self.messages.append((ProgrammingError, m.args[0])) self.errorhandler(self, ProgrammingError, m.args[0]) else: self.messages.append((TypeError, m)) self.errorhandler(self, TypeError, m) except: exc, value, tb = exc_info() del tb self.messages.append((exc, value)) self.errorhandler(self, exc, value) self._executed = query if not self._defer_warnings: self._warning_check() return r class Cursor(CursorStoreResultMixIn, CursorTupleRowsMixIn, BaseCursor): ___ Tuto
[Tutor] Testing dymamically created methods
Hi all, I would like to use some existing tool like py.test or nose to run my tests, but I failed to do so. The problem is as follow. I have tests: ### test_methods.py ### def test_one(): assert 1 == 1 def test_two(): assert 1 == 1 # I have abstraction layer that keeps information about this test, like method name. It's simple JSON file. Then I have the test runner: ### test_runner.py ### def read_test_definition(): """read the JSON file and returns dict with test details""" def test_run(): my_test_data = read_test_definition() import test_methods for testid in my_test_data: my_method = my_test_data[testid] # here the 'my_method' is equal 'test_one' or 'test_two', hope it's clear.. test_method = getattr(test_methods, my_method) test_method() ### This code works without py.test or nosetests. For example if I use print instead of 'assert'. Both py.test and nosetests failed to execute this correctly. Or maybe they do execute it correctly, I just don't understand it..:) They both report only single test was executed. I would like to see test report for each method executed in 'for' loop. Is it possible? PS. Sorry for my ignorance, I just started to learn Python last week. Thanks, Thomas ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Testing dymamically created methods
Hi, On 10 January 2012 12:15, Thomas Maier wrote: > This code works without py.test or nosetests. For example if I use print > instead of 'assert'. > Both py.test and nosetests failed to execute this correctly. > Or maybe they do execute it correctly, I just don't understand it..:) > They both report only single test was executed. > I would like to see test report for each method executed in 'for' loop. > Is it possible? For nose, I *think* you can basically achieve what you want by turning test_run() into a generator (by essentially replacing the call to the test_method() with a suitable "yield" statement. See here: http://readthedocs.org/docs/nose/en/latest/writing_tests.html#test-generators Additionally you might also look at the TestLoader functionality for taking further control over how and where your tests are loaded, e.g. see for example nose.loader.loadTestsFromGenerator() or nose.loader.loadTestsFromGeneratorMethod() (or indeed all the other methods) here: http://readthedocs.org/docs/nose/en/latest/api/loader.html HTH, my $0.02 worth, Walter ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Primitive Chess Clock Program Question
>> I assume you want to display something like this: >> >> Enter your next move: 0:30 SNIP > Assuming Steven has guessed right then I think you need to use one of the > non blocking input mechanisms like kbhit() or getch() or somesuch. > > Those methods are notioriously unreliable and OS specific. For example you > may need to use curses or the Microsoft runtime module msvcrt. I would recommend termios for unix over curses, because curses pretty much takes over. Something like this: http://code.activestate.com/recipes/577977-get-single-keypress/ SNIP > label while awaiting user input is almost trivial > (for a GUI). I agree with Alan, a GUI toolkit makes this trivial because it can run using events and timers. For a terminal I would recommend you use a couple of threads. One that checks for input on getchar() and the other thread, the main thread, that can update the display of the prompt. You can use Queue to pass the key(s) recieved to the main thread. Also to reduce or eliminate flicker I would also recommend you look at sending the backspace characters to the terminal and then replace the correct time. Something like this: import sys sys.stdout.write('\b') sys.stdout.flush() Of course that is assuming that your terminal will support \b . On Wed, Jan 4, 2012 at 2:22 AM, Alan Gauld wrote: > On 03/01/12 21:28, Steven D'Aprano wrote: > >> I assume you want to display something like this: >> >> Enter your next move: 0:30 >> >> where the "0:30" is the time remaining, and is constantly updating. When >> it hits zero, the function returns whether the user has typed anything >> or not. > > > Assuming Steven has guessed right then I think you need to use one of the > non blocking input mechanisms like kbhit() or getch() or somesuch. > > Those methods are notioriously unreliable and OS specific. For example you > may need to use curses or the Microsoft runtime module msvcrt. > > The general code will look like > > Display prompt > while no key hit > sleep briefly > update time in prompt > (using ctrl characters to delete/overwrire previouis entry) > #when key hit > process input. > > It is a non trivial problem and the details will depend on whether you use > curses or the microsoft route. > > It is one of those few cases that is actually much easier to do > in a GUI. GUIs generally make life more complex but in this case updating a > label while awaiting user input is almost trivial > (for a GUI). > > -- > Alan G > Author of the Learn to Program web site > http://www.alan-g.me.uk/ > > > ___ > 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] Python problem
On 01/10/2012 05:04 AM, Bojan Antonijevic wrote: Hello, I send you a mail at 29.12.2011. about problem with my IDLE (Python GUI) and I didnt recive any ansfer; Instead, I am receiving correspondence between other members of forum; Honestly, I don't want to receive all this conversation's. Thank you. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor I don't see any other message from you (at least not in the last 6 months), so I can't address your IDLE question. Either you didn't send it correctly, or you used some other name. As for getting emails between various members, that's exactly what a mailing list is about. Everybody who joins gets all the traffic, and answers what he can. You might be surprised how much you can learn by reading other's questions and the replies they get. And you also might be surprised how much you can learn trying to help others. If you don't want to be bothered, then instructions for unsubscribing are in every message, including this one. -- DaveA ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Testing dymamically created methods
On Tue, Jan 10, 2012 at 3:31 PM, Walter Prins wrote: > Hi, > > On 10 January 2012 12:15, Thomas Maier wrote: >> This code works without py.test or nosetests. For example if I use print >> instead of 'assert'. >> Both py.test and nosetests failed to execute this correctly. >> Or maybe they do execute it correctly, I just don't understand it..:) >> They both report only single test was executed. >> I would like to see test report for each method executed in 'for' loop. >> Is it possible? > > For nose, I *think* you can basically achieve what you want by turning > test_run() into a generator (by essentially replacing the call to the > test_method() with a suitable "yield" statement. See here: > http://readthedocs.org/docs/nose/en/latest/writing_tests.html#test-generators Works perfect. > Additionally you might also look at the TestLoader functionality for > taking further control over how and where your tests are loaded, e.g. > see for example nose.loader.loadTestsFromGenerator() or > nose.loader.loadTestsFromGeneratorMethod() (or indeed all the other > methods) here: > http://readthedocs.org/docs/nose/en/latest/api/loader.html Will try later. > HTH, my $0.02 worth, > > Walter Thank you very much! Thomas ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] a question about MySQLdb in python
贾晓磊 wrote: > hi, all: > > python's version: 2.6. > MySQLdb version: 1.2.3. > > I once encounter with a question like this: > File > "/usr/local/lib/python2.6/dist-packages/MySQL_python-1.2.3-py2.6-linux- x86_64.egg/MySQLdb/connections.py", > > line 36, in defaulterrorhandler > raise errorclass, errorvalue > OperationalError: (2006, 'MySQL server has gone away') > > and i try to find the exception is how to perform to us in the source > code. > > when i read the source code, some questions puzzled me! > > question 1: how to find the words "2006, 'MySQL server has gone away" in > sourced code? The 'MySQL server has gone away' message is probably in the client part of MySQL's C code. If you don't want to download that wholesale you can use a search engine like www.koders.com to look at some candidate files. > question 2: in MySQLdb/cursors.py , the method errorhandler() just > receive two parameters such as exc,value when it's be invoked. however, in > MySQLdb/connection.py, we define it as one receives 4 parameters such > connection, cursor, erorclass, errorvalue > a method should accepts 4 parameters is invoked by 2 > parameters. how to explain it? Consider: def defaulterrorhandler(four, three, two, one): ... class Connection: errorhandler = defaulterrorhandler connection = Connection() At this point connection.errorhandler is a "bound method", i. e. argument "four" is the connection instance. The method expects only three more arguments. Now after class Cursor: def __init__(self, connection): self.errorhandler = connection.errorhandler cursor = Cursor(connection) cursor.errorhandler can be called with three arguments and looking at the quoted code that indeed happens, e. g. in the following line: > self.errorhandler(self, ProgrammingError, m.args[0]) You are probably conditioned to disregard the first argument, self, because of its name, but it counts just as well. The Cursor instance isn't added automatically as the binding mechanism only kicks in when a function is found in the class __dict__, but errorhandler is put into the __dict__ of the instance. >>> class A: ... pass ... >>> def f(*args): print args ... >>> a = A() >>> a.f = f >>> a.f() () >>> A.g = f >>> a.g() (<__main__.A instance at 0x7f8d50e765f0>,) > question 3: in MySQLdb/connection.py, the module cursors is been > imported. > while, In MySQLdb/cursors.py, some methods such as errorhandler in > MySQLdb/connection.py is been invoked. > the two module, which one is execute first? which one is > added to mem first? When a module is imported the code to create its functions, classes, and other values is executed. The code inside the functions and methods is not run until a function is explicitly invoked or a class is instantiated. For this reason (and because of the module cache) it is even possible (though strongly discouraged) to have two modules import each other: $ cat one.py print "importing one" import two def f(n): print "one.f(%s)" % n if n: two.f(n-1) $ cat two.py print "importing two" import one def f(n): print "two.f(%s)" % n if n: one.f(n-1) $ python -c 'import one; one.f(5)' importing one importing two one.f(5) two.f(4) one.f(3) two.f(2) one.f(1) two.f(0) ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Help with lag
On Wed, Jan 4, 2012 at 9:45 PM, Nate Lastname wrote: > Hello! > > The attached file 'cameramovement.py' is very laggy. Could someone help me > out by telling me what part of this is slowing it down so much? I've > checked the whole file through, and I can't see why it's so slow. You'll > have to place the pngs and bmps in the folder data/test, and the other pys > in the same folder with cameramovement. Thanks! > > Thanks > -Defenestrator. > > > P.S. - I know that the load time is long. That is not the problem I have. > The game runs at a solid 62.5 fps on my computer (well, I assume that's what the number in the top right means anyway). I experience zero lag or choppy movement whatsoever. Sounds to me like you're computer might simply be too slow to run it? For the record, my system specs: 64bit Windows 7, i5-2500k @ 3.3 GHz, 8GB RAM, GeForce GTX 560 Ti. Python 2.7.2, pygame 1.9.2pre Hugo ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Removing certain sequences from a string list elements
On Sat, Jan 7, 2012 at 2:08 AM, Varsha Purohit wrote: > Hello, > > I have a simple python program where I am comparing two log files and I am > storing the differences in a list. I am programming in python after a long > time so may be I might have not written something very efficient. Please let > me know what alternate solution I can apply for my program. > > I am reading each line in the file individually and storing them in a list. > After that i am comparing the two lists and printing out the differences. > But I wanted to know how can I iter through each string in the list and > remove certain sequences like \n and ',' comma. I want to basically printout > a column where it has each element of the list in each row. It should also > avoid priting the time stamp since they will be different anyway. i want the > program as simple as it looks right now. > > Input file contains something like this in each line. I have not included > the complete log file. > > MegaMon> mfc > MFC data: > vendorId/deviceId=1000/005b, subVendorId/subDeviceId=1000/9285, OEM=1, > SubOem=1, isRaidKeySecondary=0 > MFCF: disableSAS=0, maxDisks=0, enableRaid6=1, disableWideCache=0 > disableRaid5=0, enableSecurity=0, enableReducedFeatureSet=0 > enableCTIO=0 enableSnapshot=1 enableSSC=1 enableCacheOffload=0 > maxHANodes=2 > > > here is the program > > def readList1(): > f1 = open('mfc_node1.txt',"r") > lines = f1.read().split(" ") > q = [] > for line in lines: > if not line in q: > q.append(line) > f1.close() > return q > > def readList2(): > f = open('mfc_node2.txt',"r") > lines = f.read().split(" ") > p = [] > for line in lines: > if not line in p: > p.append(line) > f.close() > return p > > These two functions should be one function that takes a filename as argument. They are exactly the same. For removing commas and newlines, you should google the str.strip() method. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] x%2
On Tue, Jan 10, 2012 at 6:24 PM, emin wrote: > answers = ["yes","no"] > reaction = ["OK.I GOT IT.But why symbol of percent % not symbol of division > / ?","PLEASE EXPLAIN MORE"] > > print "1st SORRY FOR BAD ENGLISH & DISTURBING:((i am beginner)" > print "So you want to say it doesnt mean 2 percent of x and it means x > divisible by 2?" > print "Yes" > print "or" > print "No" > answerChoise = raw_input("Type here: ") > > if answerChoise == "yes" or answerChoise == "Yes": > print reaction[0] > > elif answerChoise == "no" or answerChoise == "No": > print reaction[1] Urm, yeah, while this is cute and all, it's not a great way of asking a question. I'm not totally sure what you mean, so I'm just going to say - a / b is the division operator. It divides things. It returns a divided by b. a % b is the remainder operator. It returns what's "left" after dividing a by b. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] x%2
On Tue, Jan 10, 2012 at 1:47 PM, Noah Hall wrote: > On Tue, Jan 10, 2012 at 6:24 PM, emin wrote: >> answers = ["yes","no"] >> reaction = ["OK.I GOT IT.But why symbol of percent % not symbol of division >> / ?","PLEASE EXPLAIN MORE"] >> >> print "1st SORRY FOR BAD ENGLISH & DISTURBING:((i am beginner)" >> print "So you want to say it doesnt mean 2 percent of x and it means x >> divisible by 2?" >> print "Yes" >> print "or" >> print "No" >> answerChoise = raw_input("Type here: ") >> >> if answerChoise == "yes" or answerChoise == "Yes": >> print reaction[0] >> >> elif answerChoise == "no" or answerChoise == "No": >> print reaction[1] > > Urm, yeah, while this is cute and all, it's not a great way of asking > a question. > > I'm not totally sure what you mean, so I'm just going to say - > > a / b is the division operator. It divides things. It returns a divided by b. > a % b is the remainder operator. It returns what's "left" after dividing a by > b. > ___ > Tutor maillist - Tutor@python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor -- The / operator signifies division. The % signifies modulo. see this: http://en.wikipedia.org/wiki/Modulo_operation and see this: http://docs.python.org/reference/expressions.html#index-998 Joel Goldstick ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] generating unique set of dicts from a list of dicts
trying to figure out how to generate a unique set of dicts from a json/list of dicts. initial list ::: [{"pStart1a": {"termVal":"1122","termMenu":"CLASS_SRCH_WRK2_STRM","instVal":"OSUSI", "instMenu":"CLASS_SRCH_WRK2_INSTITUTION","goBtn":"CLASS_SRCH_WRK2_SSR_PB_SRCH", "pagechk":"CLASS_SRCH_WRK2_SSR_PB_SRCH","nPage":"CLASS_SRCH_WRK2_SSR_PB_CLASS_SRCH"}, "pSearch1a": {"chk":"CLASS_SRCH_WRK2_MON","srchbtn":"DERIVED_CLSRCH_SSR_EXPAND_COLLAPS"}}, {"pStart1":""}, {"pStart1a":{"termVal":"1122","termMenu":"CLASS_SRCH_WRK2_STRM","instVal":"OSUSI", "instMenu":"CLASS_SRCH_WRK2_INSTITUTION","goBtn":"CLASS_SRCH_WRK2_SSR_PB_SRCH", "pagechk":"CLASS_SRCH_WRK2_SSR_PB_SRCH","nPage":"CLASS_SRCH_WRK2_SSR_PB_CLASS_SRCH"}, "pSearch1a": {"chk":"CLASS_SRCH_WRK2_MON","srchbtn":"DERIVED_CLSRCH_SSR_EXPAND_COLLAPS"}}, {"pStart1":""}] As an exmple, the following is the test list: [{"pStart1a": {"termVal":"1122","termMenu":"CLASS_SRCH_WRK2_STRM","instVal":"OSUSI", "instMenu":"CLASS_SRCH_WRK2_INSTITUTION","goBtn":"CLASS_SRCH_WRK2_SSR_PB_SRCH", "pagechk":"CLASS_SRCH_WRK2_SSR_PB_SRCH","nPage":"CLASS_SRCH_WRK2_SSR_PB_CLASS_SRCH"}, "pSearch1a": {"chk":"CLASS_SRCH_WRK2_MON","srchbtn":"DERIVED_CLSRCH_SSR_EXPAND_COLLAPS"}}, {"pStart1":""}, {"pStart1a":{"termVal":"1122","termMenu":"CLASS_SRCH_WRK2_STRM","instVal":"OSUSI", "instMenu":"CLASS_SRCH_WRK2_INSTITUTION","goBtn":"CLASS_SRCH_WRK2_SSR_PB_SRCH", "pagechk":"CLASS_SRCH_WRK2_SSR_PB_SRCH","nPage":"CLASS_SRCH_WRK2_SSR_PB_CLASS_SRCH"}, "pSearch1a": {"chk":"CLASS_SRCH_WRK2_MON","srchbtn":"DERIVED_CLSRCH_SSR_EXPAND_COLLAPS"}}, {"pStart1":""}] Trying to get the following, list of unique dicts, so there aren't duplicate dicts. Searched various sites/SO.. and still have a mental block. [ {"pStart1a": {"termVal":"1122","termMenu":"CLASS_SRCH_WRK2_STRM","instVal":"OSUSI", "instMenu":"CLASS_SRCH_WRK2_INSTITUTION","goBtn":"CLASS_SRCH_WRK2_SSR_PB_SRCH", pagechk":"CLASS_SRCH_WRK2_SSR_PB_SRCH","nPage":"CLASS_SRCH_WRK2_SSR_PB_CLASS_SRCH"}, "pSearch1a": {"chk":"CLASS_SRCH_WRK2_MON","srchbtn":"DERIVED_CLSRCH_SSR_EXPAND_COLLAPS"}}, {"pStart1":""}] I was considering iterating through the initial list, copying each dict into a new list, and doing a basic comparison, adding the next dict if it's not in the new list.. is there another/better way? posted this to StackOverflow as well. http://stackoverflow.com/questions/8808286/simplifying-a-json-list-to-the-unique-dict-items <<< There was a potential soln that I couldn't understand. - The simplest approach -- using list(set(your_list_of_dicts)) won't work because Python dictionaries are mutable and not hashable (that is, they don't implement __hash__). This is because Python can't guarantee that the hash of a dictionary won't change after you insert it into a set or dict. However, in your case, since you (don't seem to be) modifying the data at all, you can compute your own hash, and use this along with a dictionary to relatively easily find the unique JSON objects without having to do a full recursive comparison of each dictionary to the others. First, we need a function to compute a hash of the dictionary. Rather than trying to build our own hash function, let's use one of the built-in ones from hashlib: def dict_hash(d): out = hashlib.md5() for key, value in d.iteritems(): out.update(unicode(key)) out.update(unicode(value)) return out.hexdigest() (Note that this relies on unicode(...) for each of your values returning something unique -- if you have custom classes in the dictionaries whose __unicode__ returns something like "MyClass instance", this will fail or will require modification. Also, in your example, your dictionaries are flat, but I'll leave it as an exercise to the reader how to expand this solution to work with dictionaries that contain other dicts or lists.) Since dict_hash returns a string, which is immutable, you can now use a dictionary to find the unique elements: uniques_map = {} for d in list_of_dicts: uniques[dict_hash(d)] = d unique_dicts = uniques_map.values() *** not sure what the "uniqes" is, or what/how it should be defined thoughts/comments are welcome thanks ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] generating unique set of dicts from a list of dicts
On 01/10/2012 03:24 PM, bruce wrote: Since dict_hash returns a string, which is immutable, you can now use a dictionary to find the unique elements: uniques_map = {} for d in list_of_dicts: uniques[dict_hash(d)] = d unique_dicts = uniques_map.values() *** not sure what the "uniqes" is, or what/how it should be defined Don't know about the rest of the message, but I think there's a typo in the above fragment. On the third line, it should be uniques_map, not uniques that you're adding an item to. And unless you have a really long (and strong) hash, you still have to check for actually equal. In otherwords, the above solution will throw out a dict that happens to have the same hash as one already in the uniques_map. Do you trust the "equals" method for your dicts ? If not, that's your first problem. If you do, then you can simply do unique_dicts = [] for d in list_of_dicts: if d not in unique_dicts: unique_dicts.append(d) Do it, then decide if performance is inadequate. Only then should you worry about faster methods, especially if the faster method is broken. -- DaveA ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] x%2
On 1/10/2012 1:47 PM, Noah Hall wrote: a % b is the remainder operator. It returns what's "left" after dividing a by b. Not to beat a dead horse- but % is the modulo operator. It returns the residue class of the 2 operands. When a is positive this is the same as remainder, but not so for negative a. >>> 5%3 2 >>> -5%3 1 >>> FWIW the Python documentation (at least as of 2.7.2 has this wrong!) -- Bob Gailer 919-636-4239 Chapel Hill NC ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] Defining a File path
Hi guys, I know that if i dont include any path information, python looks in the current directory for the file. My question is how do i specify a file path to open a file saved on my desktop for example. Thanks all Adrian Sent from my iPad ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] generating unique set of dicts from a list of dicts
[NN] >> uniques_map = {} >> for d in list_of_dicts: >> uniques[dict_hash(d)] = d >> unique_dicts = uniques_map.values() [Dave Angel] > unique_dicts = [] > for d in list_of_dicts: > if d not in unique_dicts: > unique_dicts.append(d) > > Do it, then decide if performance is inadequate. Only then should you > worry about faster methods, especially if the faster method is broken. Another variant: # keys and values in the dictionaries must be hashable list_of_dicts = ... unique_dicts_map = {} for d in list_of_dicts: key = frozenset(d.items()) unique_dicts_map[key] = d unique_dicts = unique_dicts_map.values() I'm using a frozenset because it is hashable. It should be easy to see that two dicts are equal if and only if they comprise a set of equal key-value pairs. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Defining a File path
On 1/10/2012 11:31 AM Adrian said... Hi guys, I know that if i dont include any path information, python looks in the current directory for the file. My question is how do i > specify a file path to open a file saved on my desktop for example. There's lots of ways that depend on your platform and specific needs. Google python path search for some ideas, and ask with more specifics. Emile ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Defining a File path
On Tue, Jan 10, 2012 at 8:31 PM, Adrian wrote: > Hi guys, > I know that if i dont include any path information, python looks in the > current directory for the file. My question is how do i specify a file path > to open a file saved on my desktop for example. > > Thanks all > > Adrian > Just write the path like you would anywhere else, there is nothing special about how python handles this. # this is where my desktop is located on my windows 7 machine, but it differs per operating system of course f = open("C:\Users\hugo\Desktop\file.txt", 'r') # you can also use relative paths, like "two directories up from the current and then into the media directory" # forward slashes here, that's what they use on essentially everything that isn't windows f = open("../../media/file.txt", 'r') if you want to be cross-platform, you should take a look at the os.path module. HTH, Hugo ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] x%2
bob gailer wrote: On 1/10/2012 1:47 PM, Noah Hall wrote: a % b is the remainder operator. It returns what's "left" after dividing a by b. Not to beat a dead horse- but % is the modulo operator. That depends on how you define "remainder" and "modulo". There is no definition agreed on by all people, and so we get into terminology disputes. To a mathematician, "modulo operator" is meaningless. Modulo is a modifier to a statement, not an operator, and is written "mod" as in: 1 = 5*3 mod 7 It returns the residue class of the 2 operands. When a is positive this is the same as remainder, but not so for negative a. "Remainder" is ambiguous for negative values. -7/5 could be given as -1 with -2 remainder, or as -2 with 3 remainder. One might define a remainder operation as returning a result: - which is always positive - with the sign of the divisor - with the sign of the dividend - which is closest to zero - which is furthest away from zero The last two require further variations, depending on how you resolve ties. One might also define i%0 to be i, or as undefined. So by my count, there are at least 18 consistent ways to define a remainder/modulo operator. A very few languages define two operators, or functions, e.g. Ada defines a rem operator which returns the remainder with the sign of the dividend and a mod operator which returns the remainder with the sign of the operator. -- Steven ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Defining a File path
On 01/10/2012 04:53 PM, Hugo Arts wrote: On Tue, Jan 10, 2012 at 8:31 PM, Adrian wrote: Hi guys, I know that if i dont include any path information, python looks in the current directory for the file. My question is how do i specify a file path to open a file saved on my desktop for example. Thanks all Adrian Just write the path like you would anywhere else, there is nothing special about how python handles this. # this is where my desktop is located on my windows 7 machine, but it differs per operating system of course f = open("C:\Users\hugo\Desktop\file.txt", 'r') You'd want to do one of three things there: 1) use forward slashes "C:/Users/hugo/Desktop/file.txt" which Windows will use happily for nearly every purpose. 2) use raw strings r"C:\Users\hugo\Desktop\file.txt" 3) or escape the backslashes: "C:\\Users\\hugo\\Desktop\\file.txt" # you can also use relative paths, like "two directories up from the current and then into the media directory" # forward slashes here, that's what they use on essentially everything that isn't windows f = open("../../media/file.txt", 'r') if you want to be cross-platform, you should take a look at the os.path module. HTH, Hugo ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor -- DaveA ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] Extremely simple question
Hi there, I am *new* (I cannot put enough emphasis on that!) to Python programming, and to programming in general. I am trying to write out a statement that will protect a file on my computer from being run unless I enter the right specifications; your_weight = int(raw_input("Please enter your weight: ")) > if your_weight < 0: > print 'You're not Chris!' > elif your_weight == 170: > print 'You might be Chris! But...' > your_height = int(raw_input("Please enter your height: ")) > if your_height < 180: > print 'You're not Chris! > elif your_height == 180: > print 'You're Chris!' > your_name = int(raw_input("What is your name? ")) > elif your_height > 180: > print 'You're not Chris!" > elif x > 170: > print 'You're not Chris!' When I open it, the program says I have a syntax error. Praytell, where did I go wrong? ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Extremely simple question
On Wed, Jan 11, 2012 at 7:14 AM, Chris Johnson wrote: > Hi there, > > I am *new* (I cannot put enough emphasis on that!) to Python programming, > and to programming in general. I am trying to write out a statement that > will protect a file on my computer from being run unless I enter the right > specifications; > >> your_weight = int(raw_input("Please enter your weight: ")) >> if your_weight < 0: >> print 'You're not Chris!' >> elif your_weight == 170: >> print 'You might be Chris! But...' >> your_height = int(raw_input("Please enter your height: ")) >> if your_height < 180: >> print 'You're not Chris! >> elif your_height == 180: >> print 'You're Chris!' >> your_name = int(raw_input("What is your name? ")) >> elif your_height > 180: >> print 'You're not Chris!" >> elif x > 170: >> print 'You're not Chris!' > > > When I open it, the program says I have a syntax error. Praytell, where did > I go wrong? When you have a problem like this, you should copy and paste the *whole* traceback here. Anyway, just from quickly looking, I think your error lines in the the line elif x > 170: I'm sure you can work out why. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor