Critique of first python code
Hi all. I'm just starting to pick up python. I wanted to play with nested lists so first I wrote a little bit of code to create arbitrarily nested lists (grow). Then I wrote a breadth first search. I'm putting this small snippet up asking for criticism. Was there a more elegant way to do what I'm doing? Anything that goes against convention? Anything that fingers me as a c++ programmer? Are there standard modules that do these kind of things? Thanks for any feedback. ## from random import randint Val = 0 def grow(L,depth): '''grows L by appending integers and arbitrarily nested lists with a maximum depth. Returns L.''' global Val if depth == 0: return L else: choice = randint(1,2) if 1 == choice: # add a numerical literal Val += 1 L.append(Val) return grow(L,depth-1) elif 2 == choice: # add a list L.append( grow([],depth-1) ) return grow(L,depth-1) def traverse(L, count=0): '''Prints the non iterable object of L in breadth first order. Returns count + the number of non iterables in L.''' if L == []: return count n = [] for e in L: if not hasattr(e,'__iter__'): print e, count += 1 else: n[:] += e print '\n' return traverse(n,count) L = grow([],10) C = traverse(L) ## -- Zack -- http://mail.python.org/mailman/listinfo/python-list
Re: Critique of first python code
On Feb 8, 4:32 pm, George Sakkis <[EMAIL PROTECTED]> wrote:
> On Feb 8, 3:40 pm, Arnaud Delobelle <[EMAIL PROTECTED]> wrote:
>
>
>
> > How about:
>
> > from itertools import count
> > from random import randrange
>
> > def grow(L, depth, counter=count()):
> >'''grow L by appending integers and arbitrarily nested lists with a
> >maximum depth. Returns L.'''
> >if depth == 0:
> > return L
> >else:
> > L.append(counter.next() if randrange(2) else grow([], depth-1))
> > return grow(L, depth-1)
>
> Or you may write a more flexible generator version of the above. If
> you're not familiar with generators, think of them as lazy sequences
> that generate successive elements only when needed:
>
> import random
> from itertools import count
>
> def igrow(depth, next=count(1).next, nest=list, random=random.random):
> '''Generate integers and arbitrarily nested iterables with a
> maximum depth.'''
> if depth:
> depth -= 1
> yield next() if random()<0.5 else
> nest(igrow(depth,next,nest,random))
> for e in igrow(depth,next,nest,random):
> yield e
>
> With this you can just as easily generate nested tuples (or other
> containers) instead of lists:
>
> nested = tuple(igrow(10, nest=tuple))
>
> You may even avoid allocating nested containers altogether:
>
> from types import GeneratorType
>
> for x in igrow(10, nest=iter):
> if isinstance(x, GeneratorType):
> # process nested generator
> else:
> # x is an 'atom'
>
> HTH,
> George
The generators you show here are interesting, and it prodded me on how
to add tuples but at the moment (I'm a python newbie) the generator
seems less readable to me than the alternative. After some input from
Scott David Daniels I changed some of the unnecessary recursion to
while loops. I completely over thought my problem. I've fetched pylint
and I'll be sure to keep it in my toolkit. What does everyone think of
the code below? Are generator functions a more pythonic (preferred?)
way of doing things or will my while loops escape mocking? Thanks for
the feedback this has been a great exercise for me.
import random
from itertools import count
_Val = count(1)
def grow(seq, depth):
'''
Grows seq with arbitrarily appended integers, lists and tuples.
At least depth elements will be added to seq and seq will not grow
more than depth levels deep.
Returns seq.
'''
while depth > 0:
choice = random.random()
if choice < .5:
seq.append(_Val.next())
elif choice < .75:
seq.append(list(grow([], depth-1)))
else:
seq.append(tuple(grow([], depth-1)))
depth -= 1
return seq
def traverse(seq):
'''
Breadth first traversal of seq.
Prints the non iterable objects of seq in breadth first order.
Returns the number of atoms (non iterables) in seq.
'''
counter = 0
while seq:
below = []
for item in seq:
if hasattr(item, '__iter__'):
below.extend(item)
else:
print item,
counter += 1
#intentional blank line to distinguish long lines that wrap
print '\n'
seq = below
return counter
L = grow([],10)
C = traverse(L)
--
Zack
--
http://mail.python.org/mailman/listinfo/python-list
class static variables and __dict__
If I have a class static variable it doesn't show up in the __dict__ of
an instance of that class.
class C:
n = 4
x = C()
print C.__dict__
{'__module__': '__main__', '__doc__': None, 'n': 4}
print x.__dict__
{}
This behavior makes sense to me as n is not encapsulated in x's
namespace but what method can you use on x to find all available
attributes for that class?
--
Zack
--
http://mail.python.org/mailman/listinfo/python-list
Re: class static variables and __dict__
Diez B. Roggisch wrote:
> Zack schrieb:
>> If I have a class static variable it doesn't show up in the __dict__
>> of an instance of that class.
>>
>> class C:
>>n = 4
>>
>> x = C()
>> print C.__dict__
>> {'__module__': '__main__', '__doc__': None, 'n': 4}
>> print x.__dict__
>> {}
>>
>> This behavior makes sense to me as n is not encapsulated in x's
>> namespace but what method can you use on x to find all available
>> attributes for that class?
>
> x.__class__.__dict__
>
> Diez
>
This would leave out any attributes of base classes. Not that I asked
for that functionality in my original post but is there a way to get all
attributes qualified by x. ? I see that I could walk the dict of x,
x.__class__ and x.__class__.__bases__ until I exhaust the tree. But is
there a built in method for doing this?
--
Zack
--
http://mail.python.org/mailman/listinfo/python-list
Re: class static variables and __dict__
Zack wrote:
> Diez B. Roggisch wrote:
>> Zack schrieb:
>>> If I have a class static variable it doesn't show up in the __dict__
>>> of an instance of that class.
>>>
>>> class C:
>>>n = 4
>>>
>>> x = C()
>>> print C.__dict__
>>> {'__module__': '__main__', '__doc__': None, 'n': 4}
>>> print x.__dict__
>>> {}
>>>
>>> This behavior makes sense to me as n is not encapsulated in x's
>>> namespace but what method can you use on x to find all available
>>> attributes for that class?
>>
>> x.__class__.__dict__
>>
>> Diez
>>
>
> This would leave out any attributes of base classes. Not that I asked
> for that functionality in my original post but is there a way to get all
> attributes qualified by x. ? I see that I could walk the dict of x,
> x.__class__ and x.__class__.__bases__ until I exhaust the tree. But is
> there a built in method for doing this?
>
I believe this accomplishes what I'm looking for. I'm not positive it is
correct or if there are cases I've missed. It would be nice if there is
a simple python builtin for finding the fully qualified dict.
def fullDict(obj):
'''
Returns a dict with all attributes qualified by obj.
obj is an instance of a class
'''
d = obj.__dict__
# update existing items into new items to preserve inheritance
tmpD = obj.__class__.__dict__
tmpD.update(d)
d = tmpD
supers = list(obj.__class__.__bases__)
for c in supers:
tmpD = c.__dict__
tmpD.update(d)
d = tmpD
supers.extend(c.__bases__)
return d
--
Zack
--
http://mail.python.org/mailman/listinfo/python-list
Re: class static variables and __dict__
Dustan wrote: > On Feb 16, 4:40 pm, Zack <[EMAIL PROTECTED]> wrote: >> what method can you use on x to find all available >> attributes for that class? > >>>> class Foo(object): > bar = "hello, world!" > def __init__(self, baz): > self.baz = baz > >>>> x = Foo(42) > >>>> x.__dict__.keys() # Does not include bar > ['baz'] > >>>> dir(x) # Includes bar plus some methods > ['__class__', '__delattr__', '__dict__', '__doc__', > '__getattribute__', '__hash__', '__init__', '__module__', '__new__', > '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__str__', > '__weakref__', 'bar', 'baz'] I knew there was something simple I was forgetting. Thanks -- Zack -- http://mail.python.org/mailman/listinfo/python-list
Re: class static variables and __dict__
Dustan wrote:
> On Feb 16, 5:59 pm, Zack <[EMAIL PROTECTED]> wrote:
>> Zack wrote:
>>> Diez B. Roggisch wrote:
>>>> Zack schrieb:
>>>>> If I have a class static variable it doesn't show up in the __dict__
>>>>> of an instance of that class.
>>>>> class C:
>>>>>n = 4
>>>>> x = C()
>>>>> print C.__dict__
>>>>> {'__module__': '__main__', '__doc__': None, 'n': 4}
>>>>> print x.__dict__
>>>>> {}
>>>>> This behavior makes sense to me as n is not encapsulated in x's
>>>>> namespace but what method can you use on x to find all available
>>>>> attributes for that class?
>>>> x.__class__.__dict__
>>>> Diez
>>> This would leave out any attributes of base classes. Not that I asked
>>> for that functionality in my original post but is there a way to get all
>>> attributes qualified by x. ? I see that I could walk the dict of x,
>>> x.__class__ and x.__class__.__bases__ until I exhaust the tree. But is
>>> there a built in method for doing this?
>> I believe this accomplishes what I'm looking for. I'm not positive it is
>> correct or if there are cases I've missed. It would be nice if there is
>> a simple python builtin for finding the fully qualified dict.
>>
>> def fullDict(obj):
>> '''
>> Returns a dict with all attributes qualified by obj.
>>
>> obj is an instance of a class
>>
>> '''
>> d = obj.__dict__
>> # update existing items into new items to preserve inheritance
>> tmpD = obj.__class__.__dict__
>> tmpD.update(d)
>> d = tmpD
>> supers = list(obj.__class__.__bases__)
>> for c in supers:
>>tmpD = c.__dict__
>> tmpD.update(d)
>>d = tmpD
>>supers.extend(c.__bases__)
>> return d
>
> I know you're probably dumping this for dir(), but I should still warn
> you: This function modifies the class dictionary, which might not have
> been what you intended.
I'm not actually do anything with this, or dir, just messing around
learning python (I would use dir instead of this if I had a need
though). I had completely missed that I wasn't copying the dicts. Thanks
for that catch.
--
Zack
--
http://mail.python.org/mailman/listinfo/python-list
Accumulating values in dictionary
Given a bunch of objects that all have a certain property, I'd like to
accumulate the totals of how many of the objects property is a certain
value. Here's a more intelligible example:
Users all have one favorite food. Let's create a dictionary of
favorite foods as the keys and how many people have that food as their
favorite as the value.
d = {}
for person in People:
fav_food = person.fav_food
if d.has_key(fav_food):
d[fav_food] = d[fav_food] + 1
else:
d[fav_food] = 1
d ends up being something like: {'pie': 400, 'pizza': 200, 'burgers':
100} if 400 people like pie, 200 like pizza and 100 like burgers.
There's nothing wrong (that I know of) by doing it as I have up there,
but is there a simpler, easier way? Looking forward to hearing about
how much of a n00b I am. Thanks in advance!
--
http://mail.python.org/mailman/listinfo/python-list
Re: Accumulating values in dictionary
On May 20, 12:26 pm, Zack <[EMAIL PROTECTED]> wrote:
> Given a bunch of objects that all have a certain property, I'd like to
> accumulate the totals of how many of the objects property is a certain
> value. Here's a more intelligible example:
>
> Users all have one favorite food. Let's create a dictionary of
> favorite foods as the keys and how many people have that food as their
> favorite as the value.
>
> d = {}
> for person in People:
> fav_food = person.fav_food
> if d.has_key(fav_food):
> d[fav_food] = d[fav_food] + 1
> else:
> d[fav_food] = 1
>
> d ends up being something like: {'pie': 400, 'pizza': 200, 'burgers':
> 100} if 400 people like pie, 200 like pizza and 100 like burgers.
>
> There's nothing wrong (that I know of) by doing it as I have up there,
> but is there a simpler, easier way? Looking forward to hearing about
> how much of a n00b I am. Thanks in advance!
Er. OK so I realize now that I could have just done this:
d = {}
for person in people:
fav_food = person.fav_food
d[fav_food] = d.get(fav_food, 0) + 1
--
http://mail.python.org/mailman/listinfo/python-list
Re: Accumulating values in dictionary
On May 20, 10:38 am, Thomas Bellman <[EMAIL PROTECTED]> wrote: > Arnaud Delobelle <[EMAIL PROTECTED]> wrote: > > from collections import defaultdict > > d = defaultdict(int) # That means the default value will be 0 > > for person in people: > > d[person.fav_food] += 1 > > Ah! I didn't think of using int as the factory function. If you > use this, then I believe the warning I gave about performance > does not apply; my understanding is that calling built-in functions > (like the int constructor) is fast. > > -- > Thomas Bellman, Lysator Computer Club, Linköping University, Sweden > "Beware of bugs in the above code; I have! bellman @ lysator.liu.se > only proved it correct, not tried it." ! Make Love -- Nicht Wahr! Arnaud, that is so badass re: int -- http://mail.python.org/mailman/listinfo/python-list
Os.fork() replacement for windows.
Title: Os.fork() replacement for windows. Ok ladies and gentlemen, I'm attemtping to port a unix based app written in python over to windows. However this app relies on the os.fork() to achieve parallelism for sending and receiving network packets. I need to 'fork' the code to send a series of packets and parse them on return. I have been looking into twisted to attempt to achieve capability but it looks like I'd have to rewrite the app from the ground up to deal with asynchronous operations and attempting to make it all re-entrant which is a huge task and something I'd prefer to avoid if there is a better solution available. Any ideas? Thanks so much, Zack Payton -- http://mail.python.org/mailman/listinfo/python-list
RE: Build spoofed IP packets
See scapy.py I've completed windows support at this time and am currently testing it, working out some bugs. If you want a copy just ask. I need some testers. It can do almost any packet transmissions you want. (google it) Z -- http://mail.python.org/mailman/listinfo/python-list
how do I put the python on my desktop or even access it
Sent from Windows Mail -- https://mail.python.org/mailman/listinfo/python-list
exec within function
hi,
I'm not sure how I can use exec within a function correctly
here is the code i'm using:
def a():
exec('b=1')
print(b)
a()
this will raise an error, but I would like to see it outputting 1
thanks
smk
--
http://mail.python.org/mailman/listinfo/python-list
