[Tutor] Dictionary to variable copy
*Can i copy the content if a dictionary in to another variable, with out any link between the dictionary the variable? if so, please teach. * ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Dictionary to variable copy
Op 08-12-11 10:03, sunil tech schreef: /Can i copy the content if a dictionary in to another variable, with out any link between the dictionary the variable? / Have a look at the copy module [1], or use the builtin dict.copy() method. Cheers, Timo [1] http://docs.python.org/library/copy.html#module-copy / if so, please teach. / ___ 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] how to calculate program compile time?
I'm doing puzzles where we need to write code that works as fast a possible So, how can I check the compile time of my program ?... ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] unable to use find(), index()
I am using the following code astr = foobarstr1 =fooastr.find(str1, beg=0, end=3) This is showing the following error Traceback (most recent call last): File interactive input, line 1, in moduleTypeError: find() takes no keyword arguments I even tried by importing string module, but it isn't working. This same problem with find() Could you please help me! ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] unable to use find(), index()
Hi Surya, On 8 December 2011 11:19, surya k sur...@live.com wrote: astr.find(str1, beg=0, end=3) This is showing the following error Traceback (most recent call last): File interactive input, line 1, in moduleTypeError: find() takes no keyword arguments See the documentation for the str.find() method here: http://docs.python.org/release/2.5.2/lib/string-methods.html The error says that find() does not take any keyword arguments, and you've supplied 2, (namely, beg and end.) So, try calling find() without trying to specify beg and end as keyword (e.g. named as you've done) arguments. Also read up on keyword arguments (and arguments in general): http://docs.python.org/release/1.5.1p1/tut/keywordArgs.html Walter ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] how to calculate program compile time?
On 2011/12/08 12:59 PM, surya k wrote: I'm doing puzzles where we need to write code that works as fast a possible So, how can I check the compile time of my program ?... ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor You can use the `timeit` [1] module or outside of Python if you're using Linux you can use `time`. That will give you your total execution time. You can also look at further performance tips [2] if needed. [1] http://docs.python.org/library/timeit.html [2] http://wiki.python.org/moin/PythonSpeed/PerformanceTips -- Christian Witts Python Developer // ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] unable to use find(), index()
On 2011/12/08 01:19 PM, surya k wrote: I am using the following code astr = foobarstr1 =fooastr.find(str1, beg=0, end=3) This is showing the following error Traceback (most recent call last): File interactive input, line 1, inmoduleTypeError: find() takes no keyword arguments I even tried by importing string module, but it isn't working. This same problem with find() Could you please help me! ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor Your traceback message gives you the reason it's not working, `find() takes no keyword arguments`. The function only takes positional arguments so if you just write `astr.find(str1, 0, 3)` it will work as you expect it to. help(''.find) Help on built-in function find: find(...) S.find(sub [,start [,end]]) - int Return the lowest index in S where substring sub is found, such that sub is contained within s[start:end]. Optional arguments start and end are interpreted as in slice notation. Return -1 on failure. -- Christian Witts Python Developer // ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] unable to use find(), index()
surya k wrote: I am using the following code astr = foobarstr1 =fooastr.find(str1, beg=0, end=3) You have mangled the code in your email and lost line breaks. Fortunately this is simple enough to fix: astr = foobar str1 =foo astr.find(str1, beg=0, end=3) Please take more care to post code in PLAIN TEXT, not html rich text, which may mangle line breaks and break the code. This is showing the following error Traceback (most recent call last): File interactive input, line 1, in moduleTypeError: find() takes no keyword arguments I even tried by importing string module, but it isn't working. This same problem with find() Could you please help me! Did you read the error message? find() takes no keyword arguments This means just what it says: the find method does not take keyword arguments. Do you understand what keyword arguments are? # Wrong, will not work: astr.find(str1, begin=23, end=42) # Right, will work: astr.find(str1, 23, 42) -- Steven ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] how to use int and split() simultaneously
This is something I am trying to do.. Say, we are entering a string 1 2 3 4 5.so, I want to assign the numbers directly as numbers. how can I do it? I could put that numbers as string but not as number.. strNum = raw_input('enter:').split() I can convert the list into numbers by doing this... for i in range(len(strNum)): strNum[i] = int(strNum[i]). but I feel, its a long process. How can I do it in the shortest possible way?? ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] how to use int and split() simultaneously
oh, yes, no top posting. See below. On Thu, Dec 8, 2011 at 1:33 PM, surya k sur...@live.com wrote: This is something I am trying to do.. Say, we are entering a string 1 2 3 4 5.so, I want to assign the numbers directly as numbers. how can I do it? I could put that numbers as string but not as number.. strNum = raw_input('enter:').split() I can convert the list into numbers by doing this... for i in range(len(strNum)): strNum[i] = int(strNum[i]). but I feel, its a long process. How can I do it in the shortest possible way?? Using a list comprehension is one example of a compact way of doing it: strNum = raw_input(enter numbers, separated by space: ).split() strNum = [int(x) for x in strNum] You would have to assume that the entire string consists of tokens that can be type cast into integers. If not you get an error: strNum = raw_input(enter numbers, separated by space: ).split() enter numbers, separated by space: 1 2 3 4 5 66 asd strNum = [int(x) for x in strNum] Traceback (most recent call last): File stdin, line 1, in ? ValueError: invalid literal for int(): asd In that case a for loop with a try-except would better: strNum = raw_input(enter numbers, separated by space: ).split() num_list = [] for token in strNum: try: num_list.append(int(token)) except ValueError: # Do nothing, fetch the next token continue print repr(num_list) This code gives this result: enter numbers, separated by space: 1 2 3 4 5 66 [1, 2, 3, 4, 5, 66] enter numbers, separated by space: 1 2 3 4 5 66 asd 77 [1, 2, 3, 4, 5, 66, 77] Strictly speaking the continue in the except clause is not necessary in this simple example. Hope this helps! /dario ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] print method name
i created a class and in some instances when i use it call some of its methods i need to print a method name. the online search did produce some results but none of them seem to work for me. for example one of them said just to use __name__ or func_name but it didn't work for me. i'm using python 3.1.1 any help is appreciated. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] print method name
On Thu, Dec 8, 2011 at 9:49 AM, rail shafigulin rail.shafigu...@gmail.comwrote: i created a class and in some instances when i use it call some of its methods i need to print a method name. the online search did produce some results but none of them seem to work for me. for example one of them said just to use __name__ or func_name but it didn't work for me. i'm using python 3.1.1 any help is appreciated. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor Can you show the code? This works for me: class A(object): def __init__(self): pass def addr(self,a,b): return a + b a = A() print a.addr.__name__ addr ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] print method name
On Thu, Dec 8, 2011 at 9:49 AM, rail shafigulin rail.shafigu...@gmail.comwrote: i created a class and in some instances when i use it call some of its methods i need to print a method name. the online search did produce some results but none of them seem to work for me. for example one of them said just to use __name__ or func_name but it didn't work for me. i'm using python 3.1.1 any help is appreciated. It would be better if you send us the code you tried. I'm not sure what you are looking to do. When you invoke the method, do you want it to print its own name? class A(object): ... def first(self): ... pass ... a = A() a.first.__name__ 'first' ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor -- Joel Goldstick ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] how to find index of list with its value
Well, we all know to know the value when we have the index of a list. But how can we find it in the reverse way... say a listl=[1,2,3,4] l[0]=1.but how can I find its address with its value 1 ?? ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] how to find index of list with its value
On Thu, Dec 8, 2011 at 10:28 AM, surya k sur...@live.com wrote: Well, we all know to know the value when we have the index of a list. But how can we find it in the reverse way... say a listl=[1,2,3,4] l[0]=1.but how can I find its address with its value 1 ?? ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor l.index(1) This will find the index of the first element with the value of 1 -- Joel Goldstick ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] how to find index of list with its value
On 08/12/2011 15:28, surya k wrote: Well, we all know to know the value when we have the index of a list. But how can we find it in the reverse way... say a listl=[1,2,3,4] l[0]=1.but how can I find its address with its value 1 ?? help ([]) ... index(...) L.index(value, [start, [stop]]) - integer -- return first index of value. Raises ValueError if the value is not present. TJG ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] how to find index of list with its value
mylist = [1,2,3,4,1] mylist.index(1) 0 But note that this only shows the index for the first occurrence of the item. Bodsda Sent from my BlackBerry® wireless device -Original Message- From: surya k sur...@live.com Sender: tutor-bounces+bodsda=googlemail@python.org Date: Thu, 8 Dec 2011 20:58:37 To: Python Tutortutor@python.org Subject: [Tutor] how to find index of list with its value Well, we all know to know the value when we have the index of a list. But how can we find it in the reverse way... say a listl=[1,2,3,4] l[0]=1.but how can I find its address with its value 1 ?? ___ 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] print method name
On 12/09/2011 01:49 AM, rail shafigulin wrote: i created a class and in some instances when i use it call some of its methods i need to print a method name. the online search did produce some results but none of them seem to work for me. for example one of them said just to use __name__ or func_name but it didn't work for me. i'm using python 3.1.1 I'm guessing that you're doing something like def foo(): ... print foo().__name__ foo() would call the foo() function, so you'd be asking the .__name__ of the object returned by foo not the __name__ of foo. Instead you'd need to use the the function object itself, IOW don't call foo just do: print foo.__name__ This should work for both python 2 and python 3, and for both class methods or regular functions. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] print method name
On Thu, Dec 8, 2011 at 10:17 AM, Joel Goldstick joel.goldst...@gmail.comwrote: On Thu, Dec 8, 2011 at 9:49 AM, rail shafigulin rail.shafigu...@gmail.com wrote: i created a class and in some instances when i use it call some of its methods i need to print a method name. the online search did produce some results but none of them seem to work for me. for example one of them said just to use __name__ or func_name but it didn't work for me. i'm using python 3.1.1 any help is appreciated. It would be better if you send us the code you tried. I'm not sure what you are looking to do. When you invoke the method, do you want it to print its own name? class A(object): ... def first(self): ... pass ... a = A() a.first.__name__ 'first' ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor -- Joel Goldstick folks, never mind. i'm not sure what went wrong when i ran my code and got an error. i ran it again and it is working fine. my sincere apologies. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] print method name
On Thu, Dec 8, 2011 at 10:40 AM, Lie Ryan lie.1...@gmail.com wrote: On 12/09/2011 01:49 AM, rail shafigulin wrote: i created a class and in some instances when i use it call some of its methods i need to print a method name. the online search did produce some results but none of them seem to work for me. for example one of them said just to use __name__ or func_name but it didn't work for me. i'm using python 3.1.1 I'm guessing that you're doing something like def foo(): ... print foo().__name__ foo() would call the foo() function, so you'd be asking the .__name__ of the object returned by foo not the __name__ of foo. Instead you'd need to use the the function object itself, IOW don't call foo just do: print foo.__name__ This should work for both python 2 and python 3, and for both class methods or regular functions. __**_ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/**mailman/listinfo/tutorhttp://mail.python.org/mailman/listinfo/tutor as a matter of apology i found another way of getting a method name without actually knowing the name of the method: import inspect class MyClass(object): def __init__(self): pass def mymethod(self): print(inspect.getframeinfo(inspect.currentframe()).function) def main(): a = MyClass() a.mymethod() if __name__ == '__main__': main() ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] how to calculate program compile time?
On 08/12/11 10:59, surya k wrote: I'm doing puzzles where we need to write code that works as fast a possible So, how can I check the compile time of my program ?... Why would that be helpful? The code is only compiled the first time you use it so any second run will use the compiled code for imported modules. Put your program in a module and then write a driver file that imports the main program... If you want to improve performance check the timings with the Python profiler. Tune the bits that need tuning. If thats still not enough look at rewriting the critical parts in Cython. Or if that fails use C. But that should be a last resort. -- 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
Re: [Tutor] how to use int and split() simultaneously
On Thu, Dec 8, 2011 at 7:43 AM, Dario Lopez-Kästen cl2dl...@gmail.comwrote: snip In that case a for loop with a try-except would better: strNum = raw_input(enter numbers, separated by space: ).split() num_list = [] for token in strNum: try: num_list.append(int(token)) except ValueError: # Do nothing, fetch the next token continue print repr(num_list) snip Strictly speaking the continue in the except clause is not necessary in this simple example. Though you do have to have *something* or you'll get a syntax error because you can't have an empty block. The keyword `pass` works well in cases like this. HTH, Wayne ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] print method name
On 08/12/11 14:49, rail shafigulin wrote: i created a class and in some instances when i use it call some of its methods i need to print a method name. I'm curious why you need this? In most cases if you call a method you know its name... myObj = MyClass() myObj.spam() print Just called MyClass.spam() This would only be useful if you were creating references to methods dynamically or using callbacks from asynchronous messages or something? Just wondering what you are doing that requires this? -- 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
Re: [Tutor] Dictionary to variable copy
On 08/12/11 09:03, sunil tech wrote: /Can i copy the content if a dictionary in to another variable, with out any link between the dictionary the variable? if so, please teach. Yes, but they will both refer to the same object. But the two references will be entirely independant: D = {1:2,3:4} d = D[1] # both d and D[1] reference 2 D[1] = 42 # d still refers to 2 del(D) # d still refers to 2 Is that what you mean? Or do you wantbto make a clone of the value so that you can change it without changing the original? In that case you can use several techniques depending on object type. Generically use copy or deepcopy. HTH -- 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
Re: [Tutor] how to link GUI app to the code
self.Bind(wx.EVT_BUTTON, self.OnSubmit, self.button_submit) How do you decide when it is appropriate to bind to a panel/frame and when to bind to the widget itself? I understand that certain events do not propagate up the widget stack, but what about for events that do? Is there a guideline of which is appropriate when? Ramit P.S. Yes, I should probably ask the wxPython mailing list...but I don't care enough (yet) to subscribe to a new list. :) Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology 712 Main Street | Houston, TX 77002 work phone: 713 - 216 - 5423 -- This email is confidential and subject to important disclaimers and conditions including on offers for the purchase or sale of securities, accuracy and completeness of information, viruses, confidentiality, legal privilege, and legal entity disclaimers, available at http://www.jpmorgan.com/pages/disclosures/email. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] how to link GUI app to the code
The general rule with GUIs is to bind at the lowest practical level, usually the widget itself. The exception is usually for things like global accelerators. For example launching a help browser might be at window level. Alan Gauld Author of the Learn To Program website http://www.alan-g.me.uk/ From: Prasad, Ramit ramit.pra...@jpmorgan.com To: Alan Gauld alan.ga...@btinternet.com; tutor@python.org tutor@python.org Sent: Thursday, 8 December 2011, 19:07 Subject: RE: [Tutor] how to link GUI app to the code self.Bind(wx.EVT_BUTTON, self.OnSubmit, self.button_submit) How do you decide when it is appropriate to bind to a panel/frame and when to bind to the widget itself? I understand that certain events do not propagate up the widget stack, but what about for events that do? Is there a guideline of which is appropriate when? Ramit P.S. Yes, I should probably ask the wxPython mailing list...but I don't care enough (yet) to subscribe to a new list. :) Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology 712 Main Street | Houston, TX 77002 work phone: 713 - 216 - 5423 -- This email is confidential and subject to important disclaimers and conditions including on offers for the purchase or sale of securities, accuracy and completeness of information, viruses, confidentiality, legal privilege, and legal entity disclaimers, available at http://www.jpmorgan.com/pages/disclosures/email. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] how to use int and split() simultaneously
On 08-Dec-2011, at 7:13 PM, Dario Lopez-Kästen wrote: oh, yes, no top posting. See below. On Thu, Dec 8, 2011 at 1:33 PM, surya k sur...@live.com wrote: This is something I am trying to do.. Say, we are entering a string 1 2 3 4 5.so, I want to assign the numbers directly as numbers. how can I do it? I could put that numbers as string but not as number.. strNum = raw_input('enter:').split() I can convert the list into numbers by doing this... for i in range(len(strNum)): strNum[i] = int(strNum[i]). but I feel, its a long process. How can I do it in the shortest possible way?? Using a list comprehension is one example of a compact way of doing it: strNum = raw_input(enter numbers, separated by space: ).split() strNum = [int(x) for x in strNum] You would have to assume that the entire string consists of tokens that can be type cast into integers. If not you get an error: strNum = raw_input(enter numbers, separated by space: ).split() enter numbers, separated by space: 1 2 3 4 5 66 asd strNum = [int(x) for x in strNum] Traceback (most recent call last): File stdin, line 1, in ? ValueError: invalid literal for int(): asd In that case a for loop with a try-except would better: strNum = raw_input(enter numbers, separated by space: ).split() num_list = [] for token in strNum: try: num_list.append(int(token)) except ValueError: # Do nothing, fetch the next token continue print repr(num_list) This code gives this result: enter numbers, separated by space: 1 2 3 4 5 66 [1, 2, 3, 4, 5, 66] enter numbers, separated by space: 1 2 3 4 5 66 asd 77 [1, 2, 3, 4, 5, 66, 77] Strictly speaking the continue in the except clause is not necessary in this simple example. Hope this helps! /dario Using re module: === import re strNum = raw_input(enter numbers, separated by space: ) if re.search('[^\d ]', strNum): print('Invalid input') else: data = [int(x) for x in strNum.split()] print(data) ===___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] list.index() question
Hi, Assuming a list similar to this: l1=[['a',1],['b',2],['c',3]] and I want to get the index of 'c'. A one dimensional list is extremely easy; val = list.index(value). But how do I get it for a list similar to l1. I have tried ind = l1[0].index('c') and that tells me 'c' is not in list. Either my syntax is way off or I am missing the viable solution. I am reasonably certain I could iterate over l1 until I find either the value or do not find the value. If that is the only way to go, could someone share an example of workable code to do that task reasonably well. Thank you for your assistance. Robert ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] list.index() question
On 12/8/11, Robert Berman berma...@cfl.rr.com wrote: Hi, Assuming a list similar to this: l1=[['a',1],['b',2],['c',3]] and I want to get the index of 'c'. A one dimensional list is extremely easy; val = list.index(value). But how do I get it for a list similar to l1. I have tried ind = l1[0].index('c') and that tells me 'c' is not in list. That's right, 'c' is in l1[2], not l1[0]. Are you trying to search all lists inside l1 for 'c' instead of a specific list inside l1? Either my syntax is way off or I am missing the viable solution. I am reasonably certain I could iterate over l1 until I find either the value or do not find the value. If that is the only way to go, could someone share an example of workable code to do that task reasonably well. Maybe: def contains(lst, val): for i in lst: if isinstance(i, list): return contains(i, val) elif val==i: return True return False Thank you for your assistance. Robert -- Have a great day, Alex (msg sent from GMail website) mehg...@gmail.com; http://www.facebook.com/mehgcap ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] list.index() question
That won't work because l1[0] is ['a', 1] What happens if you don't change the code? l1.index('c') Bodsda Sent from my BlackBerry® wireless device -Original Message- From: Robert Berman berma...@cfl.rr.com Sender: tutor-bounces+bodsda=googlemail@python.org Date: Thu, 08 Dec 2011 16:13:32 To: tutortutor@python.org Subject: [Tutor] list.index() question ___ 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] list.index() question
On 12/08/2011 04:27 PM, bod...@googlemail.com wrote: That won't work because l1[0] is ['a', 1] What happens if you don't change the code? l1.index('c') Bodsda Sent from my BlackBerry® wireless device -Original Message- From: Robert Bermanberma...@cfl.rr.com Sender: tutor-bounces+bodsda=googlemail@python.org Date: Thu, 08 Dec 2011 16:13:32 To: tutortutor@python.orgIn [1]: l1=[['a',1],['b',2],['c',3]] In [2]: l1 Out[2]: [['a', 1], ['b', 2], ['c', 3]] In [3]: l1.index('c') --- ValueErrorTraceback (most recent call last) /home/bermanrl/ipython console inmodule() ValueError: 'c' is not in list Subject: [Tutor] list.index() question ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor Bodsa et al, What happens is as follows: In [1]: l1=[['a',1],['b',2],['c',3]] In [2]: l1 Out[2]: [['a', 1], ['b', 2], ['c', 3]] In [3]: l1.index('c') --- ValueErrorTraceback (most recent call last) /home/bermanrl/ipython console in module() ValueError: 'c' is not in list I really appreciate the help I am getting. Eventually I am certain there is a relatively easy solution I simply do not have the expertise to see it. Robert ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] list.index() question
Robert Berman wrote: Hi, Assuming a list similar to this: l1=[['a',1],['b',2],['c',3]] and I want to get the index of 'c'. You will need to explain what you mean by the index of 'c'. Do you mean 0, because 'c' is in position 0 of the sub-list ['c', 3]? Or do you mean 2, because 'c' is in the sub-list at position 2? What happens if there is a sub-list ['d', 'c']? Should that also count? What about sub-sub-lists, should they be checked too? Here is a version which checks each sub-list in turn, and returns the index of any 'c' it finds of the first such sub-list. def inner_find(list_of_lists): for sublist in list_of_lists: try: return sublist.index('c') except ValueError: pass # go to the next one # If not found at all: raise ValueError('not found') Here's a version which finds the index of the first sub-list that begins with 'c' as the zeroth element: def match_sublist(list_of_lists): for i, sublist in enumerate(list_of_lists): if sublist and sublist[0] == 'c': return i raise ValueError('not found') Other variations on these two techniques are left for you to experiment with. -- Steven ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] how to use int and split() simultaneously
शंतनू wrote: Using re module: === import re strNum = raw_input(enter numbers, separated by space: ) if re.search('[^\d ]', strNum): print('Invalid input') else: data = [int(x) for x in strNum.split()] print(data) This is not Perl, where everything is a nail that needs to be hammered with a regex. Especially not a regex which is wrong: your regex is too strict. It disallows using tabs as separators, while str.split() will happily consume tabs for you. In general, in Python, the way to check of an error condition is to try it, and if it fails, catch the exception. This doesn't always apply, but it does apply most of the time. data = [int(x) for x in strNum.split()] will print a perfectly good error message if it hits invalid input. There's no need to check the input first with a regex. If you want to recover from errors, it is easy by taking the conversion out of a list comprehension and into an explicit for loop: data = [] for s in strNum.split(): try: data.append(int(s)) except ValueError: data.append(42) # Or some other default value. If you don't care about recovering from individual errors, but only care whether the entire conversion succeeds or fails: try: data = [int(s) for s in strNum.split()] except ValueError: data = [] -- Steven ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] list.index() question
On Thu, Dec 8, 2011 at 5:03 PM, Steven D'Aprano st...@pearwood.info wrote: Robert Berman wrote: Hi, Assuming a list similar to this: l1=[['a',1],['b',2],['c',3]] and I want to get the index of 'c'. You will need to explain what you mean by the index of 'c'. Do you mean 0, because 'c' is in position 0 of the sub-list ['c', 3]? Or do you mean 2, because 'c' is in the sub-list at position 2? What happens if there is a sub-list ['d', 'c']? Should that also count? What about sub-sub-lists, should they be checked too? Here is a version which checks each sub-list in turn, and returns the index of any 'c' it finds of the first such sub-list. def inner_find(list_of_lists): for sublist in list_of_lists: try: return sublist.index('c') except ValueError: pass # go to the next one # If not found at all: raise ValueError('not found') Here's a version which finds the index of the first sub-list that begins with 'c' as the zeroth element: def match_sublist(list_of_lists): for i, sublist in enumerate(list_of_lists): if sublist and sublist[0] == 'c': return i raise ValueError('not found') Other variations on these two techniques are left for you to experiment with. -- Steven __**_ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/**mailman/listinfo/tutorhttp://mail.python.org/mailman/listinfo/tutor l1=[['a',1],['b',2],['c',3]] r = [s for s in l1 if s[0] == 'c'] r [['c', 3]] This doesn't get you all the way, but maybe its a start. If you had more than one sublist like ['c', 8] is would include that too -- Joel Goldstick ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] list.index() question
On 12/08/2011 05:03 PM, Steven D'Aprano wrote: Robert Berman wrote: Hi, Assuming a list similar to this: l1=[['a',1],['b',2],['c',3]] and I want to get the index of 'c'. You will need to explain what you mean by the index of 'c'. Do you mean 0, because 'c' is in position 0 of the sub-list ['c', 3]? Or do you mean 2, because 'c' is in the sub-list at position 2? What happens if there is a sub-list ['d', 'c']? Should that also count? What about sub-sub-lists, should they be checked too? Here is a version which checks each sub-list in turn, and returns the index of any 'c' it finds of the first such sub-list. def inner_find(list_of_lists): for sublist in list_of_lists: try: return sublist.index('c') except ValueError: pass # go to the next one # If not found at all: raise ValueError('not found') Here's a version which finds the index of the first sub-list that begins with 'c' as the zeroth element: def match_sublist(list_of_lists): for i, sublist in enumerate(list_of_lists): if sublist and sublist[0] == 'c': return i raise ValueError('not found') Other variations on these two techniques are left for you to experiment with. Thank you Steven and Joel. You have given me information to experiment with which is most appreciated. Robert ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Super In tkinter class inheritance
class ChooseDestinationWindow(Frame): def __init__(self,master): super(ChooseDestinationWindow,self).__init_ _(master) What exactly does this super method since I have seen it numerous times before and as far as I can see it is not anything the user created himself in the class? This has to do a lot with inheritance in object-oriented programming. If you are not aware of this, you might want to read some basics on that. The gist of the reason to call super is that the TKinter (or whatever base class) does some work in the background to create a Frame type, so if you are inheriting from the Frame class, you still (normally) want the Frame class to behave normally with very specific deviations. For instance, you may want to setup the Frame but (like an Office-type application) have it ask the user to save when the app tries to close. You use super in a function to call the behavior of the base class so that you do not need to duplicate the code. It is a fairly language-agnostic OOP idea. Ramit Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology 712 Main Street | Houston, TX 77002 work phone: 713 - 216 - 5423 -- This email is confidential and subject to important disclaimers and conditions including on offers for the purchase or sale of securities, accuracy and completeness of information, viruses, confidentiality, legal privilege, and legal entity disclaimers, available at http://www.jpmorgan.com/pages/disclosures/email. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor