Re: [Tutor] super.__init__() arguments
On 09/27/10 09:45, Jojo Mwebaze wrote: > Hey Tutor, > > Seems a small issue but this has been playing for a while now, what am i > doing wrong here? > super() without argument only works for Python 3. In Python 2.x, you have to pass to super your class name and your class instance, i.e.: Class Circle(Point): def __init__(self, radius=0, x=0, y=0): super(Point, self).__init__(x, y) self.radius = radius ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] class method problem
Hello, Fine that you are in a arque But can we come back to my problem. How can I take care that test2 can be initialized. Roelof ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] super.__init__() arguments
In addition it only works for new style classes. -wayne On 9/27/10, Lie Ryan wrote: > On 09/27/10 09:45, Jojo Mwebaze wrote: >> Hey Tutor, >> >> Seems a small issue but this has been playing for a while now, what am i >> doing wrong here? >> > > super() without argument only works for Python 3. In Python 2.x, you > have to pass to super your class name and your class instance, i.e.: > > Class Circle(Point): > def __init__(self, radius=0, x=0, y=0): > super(Point, self).__init__(x, y) > self.radius = radius > > ___ > Tutor maillist - Tutor@python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > -- Sent from my mobile device ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] class method problem
On 2:59 PM, Roelof Wobben wrote: Hello, Fine that you are in a arque But can we come back to my problem. How can I take care that test2 can be initialized. Roelof You had this code, and got the following error: class zoeken() : pass def __len__(self): return 0 def __str__(self): return test2 def find(self, strng, ch, start, stop): index = start while index< len(strng) and index< stop: if strng[index] == ch: return index index += 1 return -1 test = zoeken() test.woord = "tamara" test2 = zoeken.find(test, "a", 1,5) print test(test2) But now I get this message : Traceback (most recent call last): File "C:\Users\wobben\workspace\oefeningen\src\test.py", line 20, in test2 = zoeken.find(test, "a", 1,5) TypeError: find() takes exactly 5 arguments (4 given) The immediate answer is that 1) you are calling the find method with the class as the first argument, while it was declared with 'self'. 2) you never pass a string to be searched, so there's nothing useful to be passed to strng. It's the second problem that causes the error, but the first one is tied with it. You can fix the immediate syntax error by passing the string explicitly. test2 = test.find("tamara", "a", 1, 5) The real problem though is one of design, or intent. You're assigning that "tamara" to an attribute of a particular instance of zoeken(). So did you mean that find() would look there for it? If that were the case, the find declaration should change to: def find(self, ch, start, stop): and naturally, the reference to strng[index] should change to self.woord[index] There are several things wrong with the find() method, and with the __str__() method, but the first question that needs answering is What does a zoeken (please capitalize it, to follow Python conventions) object represent? What are its data attributes going to mean? Since it's not English, I don't get a clue from the name, but normally I'd get one from the __init__() method, which you omitted. My convention is to initialize all attributes in the __init__() method, even if they're not always used. But if that's undesirable for some reason, then at least comment on them there. DaveA ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] class method problem
I looked up the word zoeken -- it means find in English. I looked up the chapter and exercise in the online text "How to think like a computer scientist" Its a good tutorial. I think the OP seems to get confused on basic concepts. Here is my stab at the exercise: #!/usr/bin/env python """This exercise is to take the find function, alter it so that it can specify an end point for the search. It is problem 2 at the end of this chapter: http://openbookproject.net/thinkcs/python/english2e/ch15.html The author notes that end should default to len(str), but it can't since default parameters are initialized when the function is defined and not when it is invoked. """ # this is from the author's text def find(str, ch, start=0): index = start while index < len(str): if str[index] == ch: return index index = index + 1 return -1 # this I believe is the concept the author was looking to get the reader to understand def find2(str, ch, start=0, end = None): if end == None: end = len(str) index = start while index < end: if str[index] == ch: return index index = index + 1 return -1 -- Joel Goldstick ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] super.__init__() arguments
Thanks Guys! Works perfect cheers On Mon, Sep 27, 2010 at 1:01 PM, Wayne Werner wrote: > In addition it only works for new style classes. > > -wayne > > On 9/27/10, Lie Ryan wrote: > > On 09/27/10 09:45, Jojo Mwebaze wrote: > >> Hey Tutor, > >> > >> Seems a small issue but this has been playing for a while now, what am i > >> doing wrong here? > >> > > > > super() without argument only works for Python 3. In Python 2.x, you > > have to pass to super your class name and your class instance, i.e.: > > > > Class Circle(Point): > > def __init__(self, radius=0, x=0, y=0): > > super(Point, self).__init__(x, y) > > self.radius = radius > > > > ___ > > Tutor maillist - Tutor@python.org > > To unsubscribe or change subscription options: > > http://mail.python.org/mailman/listinfo/tutor > > > > -- > Sent from my mobile device > ___ > 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] super.__init__() arguments
Thanks Guys! Works perfect cheers On Mon, Sep 27, 2010 at 1:01 PM, Wayne Werner wrote: > In addition it only works for new style classes. > > -wayne > > On 9/27/10, Lie Ryan wrote: > > On 09/27/10 09:45, Jojo Mwebaze wrote: > >> Hey Tutor, > >> > >> Seems a small issue but this has been playing for a while now, what am i > >> doing wrong here? > >> > > > > super() without argument only works for Python 3. In Python 2.x, you > > have to pass to super your class name and your class instance, i.e.: > > > > Class Circle(Point): > > def __init__(self, radius=0, x=0, y=0): > > super(Point, self).__init__(x, y) > > self.radius = radius > > > > ___ > > Tutor maillist - Tutor@python.org > > To unsubscribe or change subscription options: > > http://mail.python.org/mailman/listinfo/tutor > > > > -- > Sent from my mobile device > ___ > 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] function with multiple checks
I've got a small function that I'm using to check whether a password is of a certain length and contains mixed case, numbers and punctuation. Originally I was using multiple "if re.search" for the patterns but it looked terrible so I've read up on list comprehensions and it's slightly improved. I just can't escape the feeling that there's a more elegant way to do this that I'm missing. I've been looking through all the python stuff that I thought might be relevant (lambda, map, filter, set, frozenset, etc) but nothing has come together. Just wondering if anyone has suggested reading material for alternate ways they'd handle this code. CODE: from string import ascii_lowercase, ascii_uppercase, digits, punctuation def complex_password(password): """Checks password for sufficient complexity.""" if len(password) < 12: return False if len([c for c in password if c in punctuation]) == 0: return False if len([c for c in password if c in digits]) == 0: return False if len([c for c in password if c in ascii_uppercase]) == 0: return False if len([c for c in password if c in ascii_lowercase]) == 0: return False return True ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] dynamic arrays?
Hi all, One thing I have never much liked about Python is its need for specifically sized arrays and lack of a dynamic, array-like data structure. For example, the following fails with a "list assignment index out of range" error: a=[] i=0 for l in open("file.txt", "r"): a[i]=l i+=1 Is there something in Python I am missing that would let the above work? I am hoping that my annoyance at the apparent lack of such a thing is unfounded. BTW, I know why the above throws that exception. TIA. -- 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] dynamic arrays?
On Mon, Sep 27, 2010 at 11:32 AM, Alex Hall wrote: > Hi all, > One thing I have never much liked about Python is its need for > specifically sized arrays and lack of a dynamic, array-like data > structure. For example, the following fails with a "list assignment > index out of range" error: > > a=[] > i=0 > for l in open("file.txt", "r"): > a[i]=l > i+=1 > Is there some reason to use this construct rather than the list object's 'append' method? for i in open('file.txt', 'r'): a.append(l) brian > > Is there something in Python I am missing that would let the above > work? I am hoping that my annoyance at the apparent lack of such a > thing is unfounded. BTW, I know why the above throws that exception. > TIA. > > -- > 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 > -- Brian K. Jones My Blog http://www.protocolostomy.com Follow me http://twitter.com/bkjones ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] dynamic arrays?
> One thing I have never much liked about Python is its need for > specifically sized arrays and lack of a dynamic, array-like data > structure. For example, the following fails with a "list assignment > index out of range" error: > > a=[] > i=0 > for l in open("file.txt", "r"): > a[i]=l > i+=1 Hmm, what's wrong with append()? a = [] for l in open("file.txt"): a.append(l) Can't answer on the why, ie, why use append instead of a[i]. Then again, if you want that option, use a dictionary (probably bad idea here, but it works): a = {} i = 0 for l in open("file.txt"): a[i] = l i += 1 Cheers, Evert > Is there something in Python I am missing that would let the above > work? I am hoping that my annoyance at the apparent lack of such a > thing is unfounded. BTW, I know why the above throws that exception. > TIA. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] dynamic arrays?
On 9/27/10, Brian Jones wrote: > On Mon, Sep 27, 2010 at 11:32 AM, Alex Hall wrote: > >> Hi all, >> One thing I have never much liked about Python is its need for >> specifically sized arrays and lack of a dynamic, array-like data >> structure. For example, the following fails with a "list assignment >> index out of range" error: >> >> a=[] >> i=0 >> for l in open("file.txt", "r"): >> a[i]=l >> i+=1 >> > > Is there some reason to use this construct rather than the list object's > 'append' method? > > for i in open('file.txt', 'r'): > a.append(l) Ah, good thought. So exactly what are the functional differences between a list and an array in Python, or are they so close that it makes no difference which you use? It seems like you can index into both with the bracket notation. Are lists limited in any way that makes them not as desirable as arrays? > > brian > >> >> Is there something in Python I am missing that would let the above >> work? I am hoping that my annoyance at the apparent lack of such a >> thing is unfounded. BTW, I know why the above throws that exception. >> TIA. >> >> -- >> 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 >> > > > > -- > Brian K. Jones > My Blog http://www.protocolostomy.com > Follow me http://twitter.com/bkjones > -- 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] function with multiple checks
On Mon, Sep 27, 2010 at 11:09 AM, Tim Miller wrote: > I've got a small function that I'm using to check whether a password is of > a certain length and contains mixed case, numbers and punctuation. > > Originally I was using multiple "if re.search" for the patterns but it > looked terrible so I've read up on list comprehensions and it's slightly > improved. I just can't escape the feeling that there's a more elegant way to > do this that I'm missing. > > I've been looking through all the python stuff that I thought might be > relevant (lambda, map, filter, set, frozenset, etc) but nothing has come > together. Just wondering if anyone has suggested reading material for > alternate ways they'd handle this code. > > CODE: > > from string import ascii_lowercase, ascii_uppercase, digits, punctuation > > > def complex_password(password): >"""Checks password for sufficient complexity.""" >if len(password) < 12: >return False >if len([c for c in password if c in punctuation]) == 0: >return False >if len([c for c in password if c in digits]) == 0: >return False >if len([c for c in password if c in ascii_uppercase]) == 0: >return False >if len([c for c in password if c in ascii_lowercase]) == 0: >return False >return True > You can probably make other optimizations, but just to start, you can get rid of 'len' and '== 0': if not [c for c in password if c in ascii_lowercase]: return False will return False if there are no lowercase characters. An empty list evaluates to False. With that in mind, you could just 'return [c for c in password if c in ascii_lowercase]' if the calling code is written to handle it. > ___ > Tutor maillist - Tutor@python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > -- Brian K. Jones My Blog http://www.protocolostomy.com Follow me http://twitter.com/bkjones ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] dynamic arrays?
On Mon, Sep 27, 2010 at 9:32 AM, Alex Hall wrote: > Hi all, > One thing I have never much liked about Python is its need for > specifically sized arrays and lack of a dynamic, array-like data > structure. For example, the following fails with a "list assignment > index out of range" error: > > a=[] > i=0 > for l in open("file.txt", "r"): > a[i]=l > i+=1 > > Is there something in Python I am missing that would let the above > work? I am hoping that my annoyance at the apparent lack of such a > thing is unfounded. BTW, I know why the above throws that exception. > TIA. > > -- > 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 > Your method works ok for dictionaries but when working with lists you can append data. #method 1: works with any iterator data=[] for line in open("file.txt", "r"): data.append(line) #method 2: this will convert a file into an array data = open("file.txt", "r").readlines() #method 3: if you had to know the line number a = [] for i, line in enumerate(open('flie.txt')): print i, line a.append(line) Hope this helps -- Vince Spicer Lead Developer - MCE Computing -- Sent from Ubuntu ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] function with multiple checks
On Mon, Sep 27, 2010 at 11:09 AM, Tim Miller wrote: > I've got a small function that I'm using to check whether a password is of a > certain length and contains mixed case, numbers and punctuation. > > Originally I was using multiple "if re.search" for the patterns but it > looked terrible so I've read up on list comprehensions and it's slightly > improved. I just can't escape the feeling that there's a more elegant way to > do this that I'm missing. > > I've been looking through all the python stuff that I thought might be > relevant (lambda, map, filter, set, frozenset, etc) but nothing has come > together. Just wondering if anyone has suggested reading material for > alternate ways they'd handle this code. The way you've written it obviously works fine. That being said, I'd probably do something like this: from string import ascii_lowercase, ascii_uppercase, digits, punctuation def complex_password(password): '''Checks to make sure a password is complex''' checks = [ lambda p: len(p) > 12, lambda p: any(c in punctuation for c in p), lambda p: any(c in digits for c in p), lambda p: any(c in ascii_uppercase for c in p), lambda p: any(c in ascii_lowercase for c in p), ] return all(check(password) for check in checks) if __name__ == '__main__': passwords = ['password', 'Password1234567', 'Password1.234567'] for password in passwords: print password, complex_password(password) In the complex_password function, I create a list of tests, each of which is a function that returns either true or false. In this case I used lambdas to create the function objects, since all the tests easily fit on a single line, but it would be fine to define a function elsewhere and use it in the list if you had more complicated checks to do. all() is a built in function that returns True if all of the elements in an iterable are true (or the iterable is empty), and otherwise returns False. That seems like an ideal way to execute a bunch of tests and return True if all of them pass, and otherwise return false. In this case, the iterable is a generator expression that evaluates each of the rules with the supplied password. any() is similar, but it returns True if any member of the iterable is True. Looking back at it, I probably should have used longer variable names in my rules, which would have made them a bit easier to read. When I was writing them, I was worried about the lines getting too long with longer names. It didn't turn out to be a problem though. -- Jerry ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] dynamic arrays?
On Mon, Sep 27, 2010 at 11:39 AM, Alex Hall wrote: > On 9/27/10, Brian Jones wrote: > > On Mon, Sep 27, 2010 at 11:32 AM, Alex Hall wrote: > > > >> Hi all, > >> One thing I have never much liked about Python is its need for > >> specifically sized arrays and lack of a dynamic, array-like data > >> structure. For example, the following fails with a "list assignment > >> index out of range" error: > >> > >> a=[] > >> i=0 > >> for l in open("file.txt", "r"): > >> a[i]=l > >> i+=1 > >> > > > > Is there some reason to use this construct rather than the list object's > > 'append' method? > > > > for i in open('file.txt', 'r'): > > a.append(l) > > Ah, good thought. So exactly what are the functional differences > between a list and an array in Python, or are they so close that it > makes no difference which you use? It seems like you can index into > both with the bracket notation. Are lists limited in any way that > makes them not as desirable as arrays? > A python list and a python array are one and the same to my knowledge. Do you mean a list and a dict? A dict is an unordered collection of key-value pairs, and the keys are more or less arbitrary values of your own creation (I believe the single limitation is the key must be a hashable type). A list is a 'flat' array, although you can use enumerate(l) to get index->value pairs from a list 'l'. hth. > > > > brian > > > >> > >> Is there something in Python I am missing that would let the above > >> work? I am hoping that my annoyance at the apparent lack of such a > >> thing is unfounded. BTW, I know why the above throws that exception. > >> TIA. > >> > >> -- > >> 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 > >> > > > > > > > > -- > > Brian K. Jones > > My Blog http://www.protocolostomy.com > > Follow me http://twitter.com/bkjones > > > > > -- > Have a great day, > Alex (msg sent from GMail website) > mehg...@gmail.com; http://www.facebook.com/mehgcap > -- Brian K. Jones My Blog http://www.protocolostomy.com Follow me http://twitter.com/bkjones ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] function with multiple checks
On Mon, Sep 27, 2010 at 11:43 AM, Brian Jones wrote: > > > On Mon, Sep 27, 2010 at 11:09 AM, Tim Miller wrote: > >> I've got a small function that I'm using to check whether a password is of >> a certain length and contains mixed case, numbers and punctuation. >> >> Originally I was using multiple "if re.search" for the patterns but it >> looked terrible so I've read up on list comprehensions and it's slightly >> improved. I just can't escape the feeling that there's a more elegant way to >> do this that I'm missing. >> >> I've been looking through all the python stuff that I thought might be >> relevant (lambda, map, filter, set, frozenset, etc) but nothing has come >> together. Just wondering if anyone has suggested reading material for >> alternate ways they'd handle this code. >> >> CODE: >> >> from string import ascii_lowercase, ascii_uppercase, digits, punctuation >> >> >> def complex_password(password): >>"""Checks password for sufficient complexity.""" >>if len(password) < 12: >>return False >>if len([c for c in password if c in punctuation]) == 0: >>return False >>if len([c for c in password if c in digits]) == 0: >>return False >>if len([c for c in password if c in ascii_uppercase]) == 0: >>return False >>if len([c for c in password if c in ascii_lowercase]) == 0: >>return False >>return True >> > How about this: d = [digits, punctuation, ascii_uppercase, ascii_lowercase] s = 'asdf1234A' for c in d: if not [x for x in s if x in c]: print x, ' not in ', c Just a quick hack, but you get the idea. It breaks when you want different numbers of characters from the different lists in the password. > > > You can probably make other optimizations, but just to start, you can get > rid of 'len' and '== 0': > > if not [c for c in password if c in ascii_lowercase]: >return False > > will return False if there are no lowercase characters. An empty list > evaluates to False. With that in mind, you could just 'return [c for c in > password if c in ascii_lowercase]' if the calling code is written to handle > it. > > > > >> ___ >> Tutor maillist - Tutor@python.org >> To unsubscribe or change subscription options: >> http://mail.python.org/mailman/listinfo/tutor >> > > > > -- > Brian K. Jones > My Blog http://www.protocolostomy.com > Follow me http://twitter.com/bkjones > -- Brian K. Jones My Blog http://www.protocolostomy.com Follow me http://twitter.com/bkjones ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] function with multiple checks
> I've got a small function that I'm using to check whether a password is of a > certain length and contains mixed case, numbers and punctuation. > > Originally I was using multiple "if re.search" for the patterns but it looked > terrible so I've read up on list comprehensions and it's slightly improved. I > just can't escape the feeling that there's a more elegant way to do this that > I'm missing. > > I've been looking through all the python stuff that I thought might be > relevant (lambda, map, filter, set, frozenset, etc) but nothing has come > together. Just wondering if anyone has suggested reading material for > alternate ways they'd handle this code. set does seem to have what you want: isdisjoint() could do the trick. Eg: if set(punctuation).isdisjoint(password) or set(digits).isdisjoint(password) or set(ascii_uppercase).isdisjoint(password) or set(ascii_lowercase).isdisjoint(password): return False return True You could even confuse yourself and put it all on one line: return not any(set(chars).isdisjoint(password) for chars in [punctuation, digits, ascii_uppercase, ascii_lowercase]) but I wouldn't recomended it. I guess this can even shortened further. (note: the 'not' operator is needed, because isdisjoint returns True for what you probably prefer as False.) Evert > CODE: > > from string import ascii_lowercase, ascii_uppercase, digits, punctuation > > > def complex_password(password): >"""Checks password for sufficient complexity.""" >if len(password) < 12: >return False >if len([c for c in password if c in punctuation]) == 0: >return False >if len([c for c in password if c in digits]) == 0: >return False >if len([c for c in password if c in ascii_uppercase]) == 0: >return False >if len([c for c in password if c in ascii_lowercase]) == 0: >return False >return True > ___ > 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] dynamic arrays?
On 9/27/10, Brian Jones wrote: > On Mon, Sep 27, 2010 at 11:39 AM, Alex Hall wrote: > >> On 9/27/10, Brian Jones wrote: >> > On Mon, Sep 27, 2010 at 11:32 AM, Alex Hall wrote: >> > >> >> Hi all, >> >> One thing I have never much liked about Python is its need for >> >> specifically sized arrays and lack of a dynamic, array-like data >> >> structure. For example, the following fails with a "list assignment >> >> index out of range" error: >> >> >> >> a=[] >> >> i=0 >> >> for l in open("file.txt", "r"): >> >> a[i]=l >> >> i+=1 >> >> >> > >> > Is there some reason to use this construct rather than the list object's >> > 'append' method? >> > >> > for i in open('file.txt', 'r'): >> > a.append(l) >> >> Ah, good thought. So exactly what are the functional differences >> between a list and an array in Python, or are they so close that it >> makes no difference which you use? It seems like you can index into >> both with the bracket notation. Are lists limited in any way that >> makes them not as desirable as arrays? >> > > A python list and a python array are one and the same to my knowledge. Do > you mean a list and a dict? A dict is an unordered collection of key-value > pairs, and the keys are more or less arbitrary values of your own creation > (I believe the single limitation is the key must be a hashable type). A list > is a 'flat' array, although you can use enumerate(l) to get index->value > pairs from a list 'l'. Oh. Somehow I never made the connection that arrays and lists are the same. :) No, I was not thinking of a dictionary in this case, though I will have to look into that enumerate function. Thanks for clearing this up. > > hth. > > > >> > >> > brian >> > >> >> >> >> Is there something in Python I am missing that would let the above >> >> work? I am hoping that my annoyance at the apparent lack of such a >> >> thing is unfounded. BTW, I know why the above throws that exception. >> >> TIA. >> >> >> >> -- >> >> 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 >> >> >> > >> > >> > >> > -- >> > Brian K. Jones >> > My Blog http://www.protocolostomy.com >> > Follow me http://twitter.com/bkjones >> > >> >> >> -- >> Have a great day, >> Alex (msg sent from GMail website) >> mehg...@gmail.com; http://www.facebook.com/mehgcap >> > > > > -- > Brian K. Jones > My Blog http://www.protocolostomy.com > Follow me http://twitter.com/bkjones > -- 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] dynamic arrays?
On 2:59 PM, Alex Hall wrote: On 9/27/10, Brian Jones wrote: On Mon, Sep 27, 2010 at 11:32 AM, Alex Hall wrote: Hi all, One thing I have never much liked about Python is its need for specifically sized arrays and lack of a dynamic, array-like data structure. For example, the following fails with a "list assignment index out of range" error: a=[] i=0 for l in open("file.txt", "r"): a[i]=l i+=1 Is there some reason to use this construct rather than the list object's 'append' method? for i in open('file.txt', 'r'): a.append(l) Ah, good thought. So exactly what are the functional differences between a list and an array in Python, or are they so close that it makes no difference which you use? It seems like you can index into both with the bracket notation. Are lists limited in any way that makes them not as desirable as arrays? an array is of homogeneous type, so it takes much less space. On the other hand, if you ever want to have some elements different from others, you need to use list., Similarly, if the type of data isn't one of the dozen or so defined array types, you need to use list. DaveA ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] dynamic arrays?
> Hi all, >> >> One thing I have never much liked about Python is its need for >> >> specifically sized arrays and lack of a dynamic, array-like data >> >> structure. For example, the following fails with a "list assignment >> >> index out of range" error: a=[] i=0 for l in open("file.txt", "r"): a[i]=l i+=1 >> >> > A python list and a python array are one and the same to my knowledge. Actually I looked it up, there is an array module. I've never used it. Lists are built in data type that act like what people mean when they say arrays -- an ordered list of values accessible by a positional index. The reason you get the exception is that you are trying to put something in a[0], and you defined a as empty, so it has no a[0] yet. len(a) == 0 initially. When you append a value to a, your first value is stored, in a[0], etc. Read about slices. They're fun, and informative to understand indexing concepts in python -- Joel Goldstick ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] function with multiple checks
set does seem to have what you want: isdisjoint() could do the trick. Eg: if set(punctuation).isdisjoint(password) or set(digits).isdisjoint(password) or set(ascii_uppercase).isdisjoint(password) or set(ascii_lowercase).isdisjoint(password): return False return True You could even confuse yourself and put it all on one line: return not any(set(chars).isdisjoint(password) for chars in [punctuation, digits, ascii_uppercase, ascii_lowercase]) but I wouldn't recomended it. I guess this can even shortened further. (note: the 'not' operator is needed, because isdisjoint returns True for what you probably prefer as False.) Here I was thinking I'd read through set types thoroughly and now that you've pointed out isdisjoint it really jumps out describing exactly the usage I was looking for. isdisjoint(other)¶ Return True if the set has no elements in common with other. Sets are disjoint if and only if their intersection is the empty set. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] function with multiple checks
On 28/09/10 01:46, Jerry Hill wrote: The way you've written it obviously works fine. That being said, I'd probably do something like this: from string import ascii_lowercase, ascii_uppercase, digits, punctuation def complex_password(password): '''Checks to make sure a password is complex''' checks = [ lambda p: len(p)> 12, lambda p: any(c in punctuation for c in p), lambda p: any(c in digits for c in p), lambda p: any(c in ascii_uppercase for c in p), lambda p: any(c in ascii_lowercase for c in p), ] return all(check(password) for check in checks) if __name__ == '__main__': passwords = ['password', 'Password1234567', 'Password1.234567'] for password in passwords: print password, complex_password(password) In the complex_password function, I create a list of tests, each of which is a function that returns either true or false. In this case I used lambdas to create the function objects, since all the tests easily fit on a single line, but it would be fine to define a function elsewhere and use it in the list if you had more complicated checks to do. all() is a built in function that returns True if all of the elements in an iterable are true (or the iterable is empty), and otherwise returns False. That seems like an ideal way to execute a bunch of tests and return True if all of them pass, and otherwise return false. In this case, the iterable is a generator expression that evaluates each of the rules with the supplied password. any() is similar, but it returns True if any member of the iterable is True. Looking back at it, I probably should have used longer variable names in my rules, which would have made them a bit easier to read. When I was writing them, I was worried about the lines getting too long with longer names. It didn't turn out to be a problem though. After doing a bit more reading and trying out some of the very useful suggestions people have made in this thread, I've decided to rework that section based on your example. I was trying to use lambdas to solve this earlier but it's new territory for me and I couldn't figure out how to string them together as you've done above. The explanation is especially invaluable, thanks. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] function with multiple checks
On 28/09/10 01:50, Brian Jones wrote: On Mon, Sep 27, 2010 at 11:43 AM, Brian Jones mailto:bkjo...@gmail.com>> wrote: How about this: d = [digits, punctuation, ascii_uppercase, ascii_lowercase] s = 'asdf1234A' for c in d: if not [x for x in s if x in c]: print x, ' not in ', c Just a quick hack, but you get the idea. It breaks when you want different numbers of characters from the different lists in the password. You can probably make other optimizations, but just to start, you can get rid of 'len' and '== 0': if not [c for c in password if c in ascii_lowercase]: return False will return False if there are no lowercase characters. An empty list evaluates to False. With that in mind, you could just 'return [c for c in password if c in ascii_lowercase]' if the calling code is written to handle it. I've rewritten that section of code using the lambda example from this thread since to me it just looks very clean. Thanks for the pointers on list comprehensions though, I've managed to go through and simplify quite a few bits of code based on that. I'm a little embarrased about all the len() now. :) ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] function with multiple checks
On Tue, 28 Sep 2010 01:09:54 am Tim Miller wrote: > def complex_password(password): > """Checks password for sufficient complexity.""" > if len(password) < 12: > return False > if len([c for c in password if c in punctuation]) == 0: > return False > if len([c for c in password if c in digits]) == 0: > return False > if len([c for c in password if c in ascii_uppercase]) == 0: > return False > if len([c for c in password if c in ascii_lowercase]) == 0: > return False > return True def complex_password(password): return ( len(password) >= 12 and any(c in punctuation for c in password) and any(c in digits for c in password) and any(c in ascii_uppercase for c in password) and any(c in ascii_lowercase for c in password) ) -- Steven D'Aprano ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] dynamic arrays?
On Tue, 28 Sep 2010 01:45:56 am Brian Jones wrote: > A python list and a python array are one and the same to my > knowledge. Close, but not quite. Python has an array type. It is almost identical to lists, except the type of data it will hold is constrained to a specific type: >>> import array >>> a = array.array('i') >>> a.append(42) >>> a array('i', [42]) >>> a.append("spam") Traceback (most recent call last): File "", line 1, in TypeError: an integer is required -- Steven D'Aprano ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] dynamic arrays?
On Tue, 28 Sep 2010 02:12:55 am Joel Goldstick wrote: > a=[] > i=0 > for l in open("file.txt", "r"): > a[i]=l > i+=1 Did you try it before posting? -- Steven D'Aprano ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] filling 2d array with zeros
Hi again everyone, I have a 2d array (I guess it is technically a list) which I want to fill with zeros. Later I will change some values, but any I do not change have to be zeros. I have two complex for loops, but I tried to scale things down to a couple list comprehensions and I broke things. What is wrong with the following line? self.am=[[(a,b) for a in range(len(self.lines)) a=0] for b in range(len(self.lines)) b=0] self.lines is another array that tells self.am how big to get, but no matter the size, all created cells of the self.am 2d array should end up with a value of 0. I barely understand list comprehensions as it is so am not sure what I did wrong here. I adapted this from a working example that fills a 2d array with numbers. -- 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] dynamic arrays?
On Tue, 28 Sep 2010 01:32:32 am Alex Hall wrote: > Hi all, > One thing I have never much liked about Python is its need for > specifically sized arrays and lack of a dynamic, array-like data > structure. Python lists are dynamically sized. If you compare Python to languages with fixed-size arrays, like Pascal, you will see the difference: fixed arrays are, well, fixed. You declare their size, and then they can never change, either increase or decrease. Python lists can do both. You can increase their size using: * the append method * the extend method * the insert method * slice assignment or you can decrease their size using: * the del statement * slice assignment -- Steven D'Aprano ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] function error
hello, i have the following error when i call this function: 20 def outOfBounds(): ---> 21 if abs(turtle.position()[0]) > turtle.window_height()/2 or abs(turtle.position()[1]) > turtle.window_width()/2: 22 return "true" 23 else: TypeError: 'function' object is unsubscriptable but i can't really figure out where is the problem with this function 'unsubscriptable'; i know it may be something regarding turtle.position returning a list can you help me with some hint ? thank you -- roberto ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] unittest testing order...
List, When using the unittest module, tests are run in alphanumeric order. What's the suggested way of specifying a test order? Any code examples would be great! Thanks -Modulok- ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] dynamic arrays?
On Mon, Sep 27, 2010 at 1:52 PM, Steven D'Aprano wrote: > On Tue, 28 Sep 2010 02:12:55 am Joel Goldstick wrote: > >> a=[] >> i=0 >> for l in open("file.txt", "r"): >> a[i]=l >> i+=1 > > Did you try it before posting? > That is a copy of the OP post. and it shows what didn't work I deleted in my post, then realized I needed it for example, so cut and pasted. But, to answer your question, that code gives and exception Joel Goldstick > > -- > Steven D'Aprano > ___ > Tutor maillist - tu...@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
Re: [Tutor] filling 2d array with zeros
On Mon, Sep 27, 2010 at 1:54 PM, Alex Hall wrote: > Hi again everyone, > I have a 2d array (I guess it is technically a list) which I want to > fill with zeros. Later I will change some values, but any I do not > change have to be zeros. I have two complex for loops, but I tried to > scale things down to a couple list comprehensions and I broke things. > What is wrong with the following line? > self.am=[[(a,b) for a in range(len(self.lines)) a=0] for b in > range(len(self.lines)) b=0] > > self.lines is another array that tells self.am how big to get, but no > matter the size, all created cells of the self.am 2d array should end > up with a value of 0. I barely understand list comprehensions as it is > so am not sure what I did wrong here. I adapted this from a working > example that fills a 2d array with numbers. > > -- > Have a great day, > Alex (msg sent from GMail website) > mehg...@gmail.com; http://www.facebook.com/mehgcap > ___ > Tutor maillist - tu...@python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > I don't know how you are figuring out your size, but if you note below, you can create a list with one element value 0, then multiply it by length you need and result is than length of array filled with 0s x = [0] * 4 >>> x [0, 0, 0, 0] -- Joel Goldstick ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] filling 2d array with zeros
On Tue, 28 Sep 2010 03:54:55 am Alex Hall wrote: > Hi again everyone, > I have a 2d array (I guess it is technically a list) which I want to > fill with zeros. Later I will change some values, but any I do not > change have to be zeros. I have two complex for loops, but I tried to > scale things down to a couple list comprehensions and I broke things. > What is wrong with the following line? > self.am=[[(a,b) for a in range(len(self.lines)) a=0] for b in > range(len(self.lines)) b=0] Start with a single row, of n columns: [0 for i in range(n)] # the loop variable i is not used Now all you need is to set n appropriately: n = len(self.lines) [0 for i in range(n)] Is there an easier way? Yes, you don't even need a list comp: [0]*n Now make m rows of the same: [ [0]*n for i in range(m) ] And you are done. You might be tempted to take a short-cut: [ [0]*n ]*m but this doesn't work as you expect. This is one of the rare Python gotchas -- it looks like it should work, but it doesn't behave like you might expect. Try it and see: >>> a = [[0]*3]*4 >>> a [[0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0]] >>> a[0][1] = 2 >>> a [[0, 2, 0], [0, 2, 0], [0, 2, 0], [0, 2, 0]] What's going on here? It's a little complicated, so let's start with a simpler situation: >>> b = [0, 0, 0] >>> c = b # c is an alias to the same list as b >>> d = b # so is d >>> e = c # and e >>> b[0] = 3 >>> e [3, 0, 0] Because both b and e refer to the same list (not copies!) any change to b *must* also change e. It's like if Barack Obama gets a haircut, so does the current President of the USA, because they're the same person. Now stick them in a list: >>> a = [b, c, d, e] >>> a [[3, 0, 0], [3, 0, 0], [3, 0, 0], [3, 0, 0]] >>> a[0][1] = 4 >>> a [[3, 4, 0], [3, 4, 0], [3, 4, 0], [3, 4, 0]] Modify one, modify them all, because in fact they are actually all the same list. [ [0]*3 ]*4 behaves the same way. There's no problem in the inner list, but the outer list doesn't make four copies of [0,0,0], it has *one* list repeated four times. Modify one, modify them all. -- Steven D'Aprano ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] unittest testing order...
On Tue, 28 Sep 2010 04:03:17 am Modulok wrote: > List, > > When using the unittest module, tests are run in alphanumeric order. > What's the suggested way of specifying a test order? There isn't one. It shouldn't matter what order the tests run, no test should *rely* on another test. (Although of course, if one test fails, any tests which assume the missing functionality will also fail.) -- Steven D'Aprano ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] dynamic arrays?
I'm guessing you are also using numpy and that you want arrays (or matrices) for the sake of either (a) matrix and array functions or (b) much greater processing speed. Add from numpy import * Then hat you can do is go back and forth: Build what you intend to be an array, but build it as a list using append. then ar=array(list) converts it. If you want to change its size again, convert it back to a list, change it, convert it back to an array. The functions you need are list(), array(), and possibly matrix() from numpy import * a=[1,2,3] type(a) ar=array(a) ar array([1, 2, 3]) matrix(ar) matrix([[1, 2, 3]]) type(ar) ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] filling 2d array with zeros
On 9/27/2010 10:54 AM Alex Hall said... What is wrong with the following line? self.am=[[(a,b) for a in range(len(self.lines)) a=0] for b in range(len(self.lines)) b=0] The a=0 and b=0 -- what do you think they're doing? Emile ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] unittest testing order...
>> List, >> >> When using the unittest module, tests are run in alphanumeric order. >> What's the suggested way of specifying a test order? > > There isn't one. It shouldn't matter what order the tests run, no test > should *rely* on another test. > > (Although of course, if one test fails, any tests which assume the > missing functionality will also fail.) Steven is right that unittests should be independent. I did once, however, come across an option to order the tests. Scanning through the unittest docs, I found "sortTestMethodsUsing": "Function to be used to compare method names when sorting them in getTestCaseNames() and all the loadTestsFrom*() methods. The default value is the built-in cmp() function; the attribute can also be set to None to disable the sort." Perhaps that does what you want. But I would indeed not recommend it. Evert ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] filling 2d array with zeros
Am 27.09.2010 20:29, schrieb Steven D'Aprano: On Tue, 28 Sep 2010 03:54:55 am Alex Hall wrote: Hi again everyone, I have a 2d array (I guess it is technically a list) which I want to fill with zeros. Later I will change some values, but any I do not change have to be zeros. I have two complex for loops, but I tried to scale things down to a couple list comprehensions and I broke things. What is wrong with the following line? self.am=[[(a,b) for a in range(len(self.lines)) a=0] for b in range(len(self.lines)) b=0] Start with a single row, of n columns: [0 for i in range(n)] # the loop variable i is not used Now all you need is to set n appropriately: n = len(self.lines) [0 for i in range(n)] Is there an easier way? Yes, you don't even need a list comp: [0]*n Now make m rows of the same: [ [0]*n for i in range(m) ] And you are done. You might be tempted to take a short-cut: [ [0]*n ]*m but this doesn't work as you expect. This is one of the rare Python gotchas -- it looks like it should work, but it doesn't behave like you might expect. Try it and see: a = [[0]*3]*4 a [[0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0]] a[0][1] = 2 a [[0, 2, 0], [0, 2, 0], [0, 2, 0], [0, 2, 0]] What's going on here? It's a little complicated, so let's start with a simpler situation: b = [0, 0, 0] c = b # c is an alias to the same list as b d = b # so is d e = c # and e b[0] = 3 e [3, 0, 0] Because both b and e refer to the same list (not copies!) any change to b *must* also change e. It's like if Barack Obama gets a haircut, so does the current President of the USA, because they're the same person. Now stick them in a list: a = [b, c, d, e] a [[3, 0, 0], [3, 0, 0], [3, 0, 0], [3, 0, 0]] a[0][1] = 4 a [[3, 4, 0], [3, 4, 0], [3, 4, 0], [3, 4, 0]] Modify one, modify them all, because in fact they are actually all the same list. [ [0]*3 ]*4 behaves the same way. There's no problem in the inner list, but the outer list doesn't make four copies of [0,0,0], it has *one* list repeated four times. Modify one, modify them all. Another extremly helpful explanation for every learner watching the mailing list. Steven, you really deserve the golden tutor medal of honor! Cheers, Jan P.S.: You other guys are awesome as well. Amazing mailing list... ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] filling 2d array with zeros
On 9/27/10, Steven D'Aprano wrote: > On Tue, 28 Sep 2010 03:54:55 am Alex Hall wrote: >> Hi again everyone, >> I have a 2d array (I guess it is technically a list) which I want to >> fill with zeros. Later I will change some values, but any I do not >> change have to be zeros. I have two complex for loops, but I tried to >> scale things down to a couple list comprehensions and I broke things. >> What is wrong with the following line? >> self.am=[[(a,b) for a in range(len(self.lines)) a=0] for b in >> range(len(self.lines)) b=0] > > > Start with a single row, of n columns: > > [0 for i in range(n)] # the loop variable i is not used > > Now all you need is to set n appropriately: > > n = len(self.lines) > [0 for i in range(n)] > > > Is there an easier way? Yes, you don't even need a list comp: > > [0]*n > > Now make m rows of the same: > > [ [0]*n for i in range(m) ] That worked, and I think I see what is going on. > > And you are done. > > > You might be tempted to take a short-cut: > > [ [0]*n ]*m > > but this doesn't work as you expect. This is one of the rare Python > gotchas -- it looks like it should work, but it doesn't behave like you > might expect. Try it and see: > a = [[0]*3]*4 a > [[0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0]] a[0][1] = 2 a > [[0, 2, 0], [0, 2, 0], [0, 2, 0], [0, 2, 0]] > > What's going on here? It's a little complicated, so let's start with a > simpler situation: > b = [0, 0, 0] c = b # c is an alias to the same list as b d = b # so is d e = c # and e b[0] = 3 e > [3, 0, 0] > > Because both b and e refer to the same list (not copies!) any change to > b *must* also change e. It's like if Barack Obama gets a haircut, so > does the current President of the USA, because they're the same person. > > Now stick them in a list: > a = [b, c, d, e] a > [[3, 0, 0], [3, 0, 0], [3, 0, 0], [3, 0, 0]] a[0][1] = 4 a > [[3, 4, 0], [3, 4, 0], [3, 4, 0], [3, 4, 0]] > > Modify one, modify them all, because in fact they are actually all the > same list. > > [ [0]*3 ]*4 behaves the same way. There's no problem in the inner list, > but the outer list doesn't make four copies of [0,0,0], it has *one* > list repeated four times. Modify one, modify them all. That makes sense. Basically, the * operator in this case acts as a copying command. For simple data types this is fine, but throw in a complex type, in this case a list (though I expect that any object would do this) and you are just doing what Python does to copy objects: copying the memory location, not making a deep copy and getting a duplicate object. I never would have thought of that. Thanks again for the great explanation! > > > -- > Steven D'Aprano > ___ > Tutor maillist - Tutor@python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > -- 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
[Tutor] if value in list of dictionaries
hello, i have a list which is generated from a csv file: options = [ {'industry': 'travel', 'name': 'owner-director','value': MSG(u"Owner/Director")}, {'industry': 'travel', 'name': 'manager','value': MSG(u"Manager")}, {'industry': 'travel', 'name': 'assistant-manager','value': MSG(u"Assistant Manager")}, {'industry': 'travel', 'name': 'travel-consultant','value': MSG(u"Travel Consultant")}, {'industry': 'travel', 'name': 'managing-director','value': MSG(u"Managing Director")}, {'industry': 'travel', 'name': 'sales-director','value': MSG(u"Sales Director")}, {'industry': 'travel', 'name': 'marketing-director','value': MSG(u"Marketing Director")}, {'industry': 'travel', 'name': 'marketing-manager','value': MSG(u"Marketing Manager")}, {'industry': 'travel', 'name': 'marketing-assistant','value': MSG(u"Marketing Assistant")}, {'industry': 'travel', 'name': 'product-manager','value': MSG(u"Product Manager")}, {'industry': 'travel', 'name': 'reservation-staff','value': MSG(u"Reservation Staff")}, {'industry': 'travel', 'name': 'student','value': MSG(u"Student")}, {'industry': 'travel', 'name': 'other','value': MSG(u"Other")}] what is the correct way to ensure that {'industry': 'travel', 'name': 'other','value': MSG(u"Other")} is always added to the end of this list after all the items have been sorted? here is the code which returns this list: http://pastie.org/1185024 thanks -- ˙uʍop ǝpısdn p,uɹnʇ pןɹoʍ ǝɥʇ ǝǝs noʎ 'ʇuǝɯɐן sǝɯıʇ ǝɥʇ puɐ 'ʇuǝʇuoɔ ǝq s,ʇǝן ʇǝʎ %>>> "".join( [ {'*':'@','^':'.'}.get(c,None) or chr(97+(ord(c)-83)%26) for c in ",adym,*)&uzq^zqf" ] ) ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] filling 2d array with zeros
On 27 September 2010 22:00, Alex Hall wrote: > That makes sense. Basically, the * operator in this case acts as a > copying command. For simple data types this is fine, but throw in a > complex type, in this case a list (though I expect that any object > would do this) and you are just doing what Python does to copy > objects: copying the memory location, not making a deep copy and > getting a duplicate object. It does not copy the object it makes multiple _references_ to the *same* object. So let's say you have a list [1,2,3] with variable a which is a list object containing 3 integer objects. Following Steven´s example you basically create a new list with 3 references to the first list with variable a. You could just as well have written it as [a,a,a] which is the same as [a] * 3. >>> a = [1,2,3] >>> b = [a,a,a] >>> b [[1, 2, 3], [1, 2, 3], [1, 2, 3]] >>> a[0] = 10 >>> a [10, 2, 3] >>> b [[10, 2, 3], [10, 2, 3], [10, 2, 3]] The next step is how do we create a real copy of the object instead of a new reference to the same object. There are multiple methods to create a copy. The easiest is using a slice. A slice returns (in this example) a *new* list with all the values. >>> b = [a[:],a[:],a[:]] >>> b [[1, 2, 3], [1, 2, 3], [1, 2, 3]] >>> a[0] = 10 >>> a [10, 2, 3] >>> b [[1, 2, 3], [1, 2, 3], [1, 2, 3]] >>> b[0][0] = 10 >>> b [[10, 2, 3], [1, 2, 3], [1, 2, 3]] Or use the copy modules to do the same, see help(copy) for more info. >>> import copy >>> a = [1,2,3] >>> b = [copy.copy(a), copy.copy(a), copy.copy(a)] >>> b [[1, 2, 3], [1, 2, 3], [1, 2, 3]] >>> a[0] = 10 >>> a [10, 2, 3] >>> b [[1, 2, 3], [1, 2, 3], [1, 2, 3]] >>> b[0][0] = 10 >>> b [[10, 2, 3], [1, 2, 3], [1, 2, 3]] copy.copy(a) is what we call a shallow copy. It only make a copy of the list object a. But what if list object a again contained 3 list objects? You then run into the same problem as before. >>> a = [[1,2],[3,4],[5,6]] >>> b = [copy.copy(a), copy.copy(a), copy.copy(a)] >>> b [[[1, 2], [3, 4], [5, 6]], [[1, 2], [3, 4], [5, 6]], [[1, 2], [3, 4], [5, 6]]] >>> a[0][0] = 10 >>> b [[[10, 2], [3, 4], [5, 6]], [[10, 2], [3, 4], [5, 6]], [[10, 2], [3, 4], [5, 6]]] For this you can use copy.deepcopy() which make sure you create a copy of each object (in this case lists). I found this was one of the most weird things I needed to understand about python. Hope this helps. Greets Sander ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] filling 2d array with zeros
On 27 September 2010 23:15, Sander Sweers wrote: >> objects: copying the memory location, not making a deep copy and >> getting a duplicate object. > > It does not copy the object it makes multiple _references_ to the *same* > object. Oops, You already got the idea and I should have read better. Ow well, maybe the copy module was of interest to you. Greets Sander ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] if value in list of dictionaries
On 9/27/2010 1:22 PM Norman Khine said... what is the correct way to ensure that {'industry': 'travel', 'name': 'other','value': MSG(u"Other")} is always added to the end of this list after all the items have been sorted? here is the code which returns this list: options.sort(key=itemgetter('name')) return options So, to answer the question you ask above, you can do: options.sort(key=itemgetter('name')) options.append({'industry':'travel', 'name':'other','value':MSG(u"Other")} return options But I don't think that's the question you're looking to get answered. I think you want "other" to be found only at the end and not elsewhere. Then you might try excluding other from options allowing the above to append it to the end: for index, row in enumerate(topics.get_rows()): if row[0] != 'other': options.append({'name': row[0], 'value': MSG(row[1])}) HTH, Emile ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] unittest testing order...
On 9/27/10, Steven D'Aprano wrote: > On Tue, 28 Sep 2010 04:03:17 am Modulok wrote: >> List, >> >> When using the unittest module, tests are run in alphanumeric order. >> What's the suggested way of specifying a test order? > > There isn't one. It shouldn't matter what order the tests run, no test > should *rely* on another test. > > (Although of course, if one test fails, any tests which assume the > missing functionality will also fail.) In an ideal world, I agree. This is possible for pure functional programming where state is avoided. However, when dealing with object oriented, imperative programming, state changes cannot be avoided. Thus if a method requires an object be passed to it, I'd like to verify that object is being constructed correctly by the object factory, before verifying that the method which uses said object, is correct. Or is there some other way of doing this? I'm new to unittesting. Thanks! -Modulok- ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] unittest testing order...
On 27-Sep-10 15:07, Modulok wrote: In an ideal world, I agree. This is possible for pure functional programming where state is avoided. However, when dealing with object oriented, imperative programming, state changes cannot be avoided. Generally, a unit test should test a single aspect of a single unit of your program. This is used all the time in object oriented programming. You set up an object (or collection of them), set up an initial state, test the behavior, and tear it down again. The state should not affect the assumptions of any other unit test. Thus if a method requires an object be passed to it, I'd like to verify that object is being constructed correctly by the object factory, before verifying that the method which uses said object, is correct. No problem. The object's constructor will have a number of unit tests of its own to ensure objects are constructed correctly, and the method has unit tests for them which test various cases about their behavior, etc. I suggest picking up a good book or two about unit testing so you get off to the right foot about how this is usually done. I'm not sure you're seeing the complete point of this. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] generating independent random numbers
Hi, I'm writing a program that's testing speed calculation of calendar dates from any date spanning 1600-3000. I want it to generate a random date and then prompt the user to indicate the correct day of the week using Zeller's formula. Included below is just some of the code to show what I'm having trouble with. The variables that need to be randomly called each time (in this case, 5 times) are c, y, month, and k (I use these inputs to get the value and assign the date with Zeller's formula, not included below). Problem I'm having is that on each while loop, those variables stay constant. I'm not sure how to make the class independently random. How can I change this with random so that on each while loop c, y, month, and k also have different values? Thanks --- import random, calendar class Date: c = random.randint(16,30) y = random.randint(0,99) month = random.randint(1,12) apr = [4,6,9,11] feb = [2] if month in feb: if y%4 == 0: k = random.randint(1,29) else: k = random.randint(1,28) elif month in apr: k = random.randint(1,30) else: k = random.randint(1,31) n = 0 while n < 5: Date() year = Date.c*100 + Date.y print '\n',calendar.month_name[Date.month], Date.k,',', year,'=', answer = raw_input() n+=1 ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] filling 2d array with zeros
On 9/27/10, Sander Sweers wrote: > On 27 September 2010 23:15, Sander Sweers wrote: >>> objects: copying the memory location, not making a deep copy and >>> getting a duplicate object. >> >> It does not copy the object it makes multiple _references_ to the *same* >> object. > > Oops, You already got the idea and I should have read better. Ow well, > maybe the copy module was of interest to you. Yes, very much. I never even knew such a module existed, and I had wondered, through all of this, what would happen when a deep copy was required. Now I know. :) > > Greets > Sander > -- 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
[Tutor] IPython: trouble setting an editor
64-bit Vista Python 2.6 for IPython 0.10 I also have Python 2.7 and 3.1 I'd like to use the version of IDLE that comes with Python 2.6. However, if I have the line ipy_editors.idle() in my ipy_user_conf.py, And enter edit, What opens is the IDLE for Python 3.1. So, in imitation of this line in ipy_user_conf.py: #ipy_editors.scite('c:/opt/scite/scite.exe') , I swapped out the above line for ipy_editors.idle("c:/Python26/Lib/idlelib/idle.pyw") and now when I enter ed fact.py, or just ed , (fact.py is a script of mine that I copied to C:Python26/Scripts) the IDLE for Python 3.1 opens, all set to edit the SCRIPT c:/Python26/Lib/idlelib/idle.pyw ! What's going on here? What do I have to do to use the Python 2.6 version of IDLE with IPython? BTW entering run fact.pyat the IPython prompt runs fact.py just fine. Thanks, Dick Moores ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] generating independent random numbers
On Tue, 28 Sep 2010 08:55:36 am Carter Danforth wrote: > class Date: > c = random.randint(16,30) > y = random.randint(0,99) > month = random.randint(1,12) Here's your problem: you are creating a class where all the attributes (called "members" in some other languages) belong to the class and are shared by all instances. Python classes are themselves objects, and the code inside the class body gets executed *once*, when the class is created. So in this case, the Date class chooses a single random month, *once*, and all instances share this attribute Date.month. To get the behaviour you are after, you need to use instance attributes, which means referring to self. The usual place to do this is in the __init__ method, which is called when the instance is being initialised: class Date: def __init__(self): self.month = random.randint(1,12) # etc. By the way, why do you calculate a century and year separately, then add c+y to get the year? It would be easier to just say: year = random.randint(1600, 3099) -- Steven D'Aprano ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] filling 2d array with zeros
On Tue, 28 Sep 2010 06:00:41 am Alex Hall wrote: > > [ [0]*3 ]*4 behaves the same way. There's no problem in the inner > > list, but the outer list doesn't make four copies of [0,0,0], it > > has *one* list repeated four times. Modify one, modify them all. > > That makes sense. Basically, the * operator in this case acts as a > copying command. For simple data types this is fine, but throw in a > complex type, in this case a list (though I expect that any object > would do this) and you are just doing what Python does to copy > objects: copying the memory location, not making a deep copy and > getting a duplicate object. I never would have thought of that. > Thanks again for the great explanation! No, be careful about your terminology. I get that you understand what is going on, but you're saying it wrong. The * operator doesn't make copies. I know it's tempting to say it does, sometimes I catch myself saying so myself, but what Python is doing is making multiple references to the same object. The object is not copied. It may be easier if you think about the underlying C implementation (under the hood, in the engine) rather than the Python level. At the Python level, objects can be in multiple places at once. Objects like lists can even be inside themselves: >>> L = [] >>> L.append(L) If you've watched Doctor Who as a child, and seen his TARDIS (which of course is bigger on the inside than the outside) land inside itself, such strange loops won't hold any fear for you at all :) But at the C level, Python doesn't make copies of any object unless necessary. The *name* L is a pointer to the list object. When you execute: L = [] Python creates a name L which then points ("refers to") to a list object. When you next do this: L.append(L) Python doesn't move the list object into itself -- that would be a good trick. Besides, objects are big, complex chunks of memory and moving them around would be slow, so Python leaves the list where it is and simply places a pointer to L into the appropriate list position. (But don't forget that Python is not necessarily written in C. There's Jython, written in Java, and CLPython written in Lisp, and many others. How they implement objects may be different. What happens under the hood isn't important, so long as the behaviour at the Python level remains the same.) So at the Python level, there is never any copying of objects unless you specifically ask for it, and the * operator doesn't make any copies at all. It repeats the one object multiple times. -- Steven D'Aprano ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] unittest testing order...
On Tue, 28 Sep 2010 08:07:30 am Modulok wrote: > On 9/27/10, Steven D'Aprano wrote: > > On Tue, 28 Sep 2010 04:03:17 am Modulok wrote: > >> List, > >> > >> When using the unittest module, tests are run in alphanumeric > >> order. What's the suggested way of specifying a test order? > > > > There isn't one. It shouldn't matter what order the tests run, no > > test should *rely* on another test. > > > > (Although of course, if one test fails, any tests which assume the > > missing functionality will also fail.) > > In an ideal world, I agree. This is possible for pure functional > programming where state is avoided. However, when dealing with object > oriented, imperative programming, state changes cannot be avoided. > Thus if a method requires an object be passed to it, I'd like to > verify that object is being constructed correctly by the object > factory, before verifying that the method which uses said object, is > correct. It is reasonable to write two tests: test_construction # verify object is constructed correctly test_method # verify object is used correctly But you shouldn't rely on the tests being *executed* in any specific order, just as you shouldn't rely on them being *written* in any specific order. You should be able to go back at any time and add an extra test: test_special_construction even though test_method already exists. Likewise because every test is independent, it doesn't matter whether test_construction executes before or after test_method, or even simultaneously! (An advanced testing infrastructure might execute each test in its own thread.) Tests can have their own setup and teardown code. You should not put the setup code to test_method in test_construction -- they should be independent. -- Steven D'Aprano ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] generating independent random numbers
You might try fixing up the following. I did not match the scale to what you are looking for. But the trick is to take advantage of the time module's association of numbers with dates: import time import random """ Sample output Wed Apr 29 14:35:58 1992 Thu Jun 24 12:04:15 1971 Fri Oct 7 01:29:28 1994 Wed Mar 23 10:33:14 1994 Sun Apr 12 12:17:56 1998 Wed May 12 06:41:33 1971 Mon Jun 15 09:15:31 1998 Fri Sep 14 18:26:22 1979 Fri Apr 28 00:55:57 1972 Fri Mar 26 00:43:12 2010 """ def re_scale(): now=float(time.time()) early=100. rang=(now-early) return time.ctime((random.random())*rang+early) for i in range(10): print re_scale() ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] filling 2d array with zeros
On 9/27/10, Steven D'Aprano wrote: > On Tue, 28 Sep 2010 06:00:41 am Alex Hall wrote: >> > [ [0]*3 ]*4 behaves the same way. There's no problem in the inner >> > list, but the outer list doesn't make four copies of [0,0,0], it >> > has *one* list repeated four times. Modify one, modify them all. >> >> That makes sense. Basically, the * operator in this case acts as a >> copying command. For simple data types this is fine, but throw in a >> complex type, in this case a list (though I expect that any object >> would do this) and you are just doing what Python does to copy >> objects: copying the memory location, not making a deep copy and >> getting a duplicate object. I never would have thought of that. >> Thanks again for the great explanation! > > No, be careful about your terminology. I get that you understand what is > going on, but you're saying it wrong. The * operator doesn't make > copies. I know it's tempting to say it does, sometimes I catch myself > saying so myself, but what Python is doing is making multiple > references to the same object. The object is not copied. Yes; the object stays put, the object's memory location (pointer) is copied. I have just enough c++ and theory to get this, and enough to be scared of it and very thankful that Python deals with it for me instead of me needing all those ampersand and star operators in front of variables... That was a nightmare, and I came running back to my high-level languages in a hurry. :) > > It may be easier if you think about the underlying C implementation > (under the hood, in the engine) rather than the Python level. At the > Python level, objects can be in multiple places at once. Objects like > lists can even be inside themselves: > L = [] L.append(L) > > If you've watched Doctor Who as a child, and seen his TARDIS (which of > course is bigger on the inside than the outside) land inside itself, > such strange loops won't hold any fear for you at all :) > > But at the C level, Python doesn't make copies of any object unless > necessary. The *name* L is a pointer to the list object. When you > execute: > > L = [] > > Python creates a name L which then points ("refers to") to a list > object. When you next do this: > > L.append(L) > > Python doesn't move the list object into itself -- that would be a good > trick. Besides, objects are big, complex chunks of memory and moving > them around would be slow, so Python leaves the list where it is and > simply places a pointer to L into the appropriate list position. Makes sense, but I never thought of this as being possible, let alone legal. Still, though I cannot imagine a situation where it would be necessary, I am sure someone has used it somewhere. A very interesting thing to think about; a single-element list holding... itself. Yep, very interesting! Now I wish I were more of a sci fi buff. :) > > (But don't forget that Python is not necessarily written in C. There's > Jython, written in Java, and CLPython written in Lisp, and many others. > How they implement objects may be different. What happens under the > hood isn't important, so long as the behaviour at the Python level > remains the same.) Really? Neat! I wonder what the advantage of doing that is, since the end result, as you say, should be the same once you start writing Python code? > > So at the Python level, there is never any copying of objects unless you > specifically ask for it, and the * operator doesn't make any copies at > all. It repeats the one object multiple times. > > > -- > Steven D'Aprano > ___ > Tutor maillist - Tutor@python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > -- 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] generating independent random numbers
On 2:59 PM, Steven D'Aprano wrote: On Tue, 28 Sep 2010 08:55:36 am Carter Danforth wrote: class Date: c = random.randint(16,30) y = random.randint(0,99) month = random.randint(1,12) Here's your problem: you are creating a class where all the attributes (called "members" in some other languages) belong to the class and are shared by all instances. Python classes are themselves objects, and the code inside the class body gets executed *once*, when the class is created. So in this case, the Date class chooses a single random month, *once*, and all instances share this attribute Date.month. To get the behaviour you are after, you need to use instance attributes, which means referring to self. The usual place to do this is in the __init__ method, which is called when the instance is being initialised: class Date: def __init__(self): self.month = random.randint(1,12) # etc. By the way, why do you calculate a century and year separately, then add c+y to get the year? It would be easier to just say: year = random.randint(1600, 3099) That's the big problem, although it's also worth pointing out that you'll need a new instance each time through the loop. It's not enough to call Date(), you also have to bind it to a name, and use that name for attribute lookup.So something like mydate = Date() year = mydate.y + But there are at least a few subtle problems left. One is that many of the years are divisible by four but do not have 29 days in February. For example, 1800, 1900, 2100 are not leap years. Next problem is that the dates are not evenly distributed over the entire range of years. The 14th of February will be more likely to be chosen than the sixth of July. You can decide that this is deliberate, but it is a consideration. Third, the program doesn't do anything to check the user's answer. For that matter, there's no timing going on either. Depending on the learning goals of this project, I'd consider using the datetime module, and method: mydate = date.fromordinal(/ordinal/) Now you can make a single randint() call, once you precalculate the starting and ending dates desired. And this module also gives you other things you need, such as the weekday() method. DaveA ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] list comprehension, efficiency?
I have seen list comprehensions used, but have not quite got the hang of it yet. So, I was writing a bit of code to do some work with file directories and decided to give it a try as follows: list_c = os.listdir("c:") #first code written in the way I usually would. dirs = [] for x in list_c: if os.path.isdir(x): dirs.append(x) #replaced the above code with the following list comprehension, it worked as expected: dirs = [x for x in list_c if os.path.isdir(x)] I can now see that quite a bit of the code I write dealing with lists can be done with list comprehensions. My question is this, is the list comprehension styled code generally more efficient at runtime? If so, why? --Bill ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] Python Help
I'm having a hard time finding the count of divisors that are even. Help anybody? Here's my code. The output is suppose to count the number of even divisors the range has. def evenCount(b) : for n in range(x, y+1) : count = 0 if n % 2 == 0 : count += n/3 count % n == 1 return n ### main x = input("Enter a starting value: ") y = input("Enter a stopping value: ") count = evenCount(x) for n in range(x, y+1) : count = 0 if n % 2 == 0 : count += n/3 print "%2d: " %n, "has%2d" %count, "even divisors", else : print "%2d: " %n, "has 0 even divisors", print ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Python Help
On Tue, Sep 28, 2010 at 12:15 AM, masawudu bature wrote: > I'm having a hard time finding the count of divisors that are even. Help > anybody? > > Here's my code. > > The output is suppose to count the number of even divisors the range has. > > def evenCount(b) : > for n in range(x, y+1) : > count = 0 > if n % 2 == 0 : > count += n/3 > count % n == 1 > return n > > > ### main > > x = input("Enter a starting value: ") > y = input("Enter a stopping value: ") > > count = evenCount(x) > > for n in range(x, y+1) : > count = 0 > if n % 2 == 0 : > count += n/3 > print "%2d: " %n, "has%2d" %count, "even divisors", > else : > print "%2d: " %n, "has 0 even divisors", > print > > > > ___ > Tutor maillist - tu...@python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > #You start with your range variables x = input("Enter a starting value: ") y = input("Enter a stopping value: ") #You set a for loop for range for num in range(x, y): #If that number divided by 2 has a remainder of 0, it's of course even. if num % 2 == 0: #print the number print num And various other ways as well. David ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] list comprehension, efficiency?
On 09/28/10 13:57, Bill Allen wrote: > I can now see that quite a bit of the code I write dealing with lists > can be done with list > comprehensions. My question is this, is the list comprehension styled > code generally > more efficient at runtime? If so, why? Yes, because the looping in list comprehension is done in C instead of a python construct. However, they are the type of efficiency that you shouldn't bother yourself with unless you're microoptimizing. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Python Help
Thanks David, But the loop was suppose to produce the count of even divisors an integer has. Like, 6 has 2 "even" divisors, which is 2 and 6, itself. 8 = 3 even divisors, which is 2, 4 ,and 8 10 = 2 even divisors, which is 2, and 10 12 = 4 even divisors, which is 2, 4, 6, and 12 sorry, I just don't know how to write a code to count the number of divisors From: David Hutto To: masawudu bature Cc: tutor@python.org Sent: Mon, September 27, 2010 11:36:05 PM Subject: Re: [Tutor] Python Help On Tue, Sep 28, 2010 at 12:15 AM, masawudu bature wrote: > I'm having a hard time finding the count of divisors that are even. Help > anybody? > > Here's my code. > > The output is suppose to count the number of even divisors the range has. > > def evenCount(b) : > for n in range(x, y+1) : > count = 0 > if n % 2 == 0 : > count += n/3 > count % n == 1 > return n > > > ### main > > x = input("Enter a starting value: ") > y = input("Enter a stopping value: ") > > count = evenCount(x) > > for n in range(x, y+1) : > count = 0 > if n % 2 == 0 : > count += n/3 > print "%2d: " %n, "has%2d" %count, "even divisors", > else : > print "%2d: " %n, "has 0 even divisors", > print > > > > ___ > Tutor maillist - Tutor@python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > #You start with your range variables x = input("Enter a starting value: ") y = input("Enter a stopping value: ") #You set a for loop for range for num in range(x, y): #If that number divided by 2 has a remainder of 0, it's of course even. if num % 2 == 0: #print the number print num And various other ways as well. David ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] Pythonic nested lists
Hi all, I've been trying to write a programme that solves sudoku problems for a while now. I'm getting close, but would like to ask a few questions about the most pythonic way of doing some things. I've decided to create nested lists (row order, column order and square order) which correspond with dictionary keys - the values of which are the numbers given in the puzzle - so I can loop through the dict in different orders. I think the first two are OK, but the square order list seems extremely messy and I would love some pointers. What I have is as follows: roworder = [[str(j)+str(i) for i in range(9)] for j in range(9)] colorder = zip(*roworder) #here comes the problem! start, index = 0,0 sqorder = [] for i in range(9): sqorder.append([]) for j in range(start, start+3): sqorder[i].extend(roworder[j][index:index+3]) if index == 6: index = 0 else: index += 3 if i == 2 or i == 5: start += 3 Any comments at all would be gratefully received. Thanks in advance Colin ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor