Number of Packages in the "cheeseshop"

2009-03-05 Thread Michael Rudolf
Hi, I just wondered how many Packages are in the Python Package Index.

I could not find any counter, but I found that there is a category
overview on http://pypi.python.org/pypi?%3Aaction=browse .

A quick look at the HTML told me that the number of Packages per
Category is listed surrounded by parentheses, at most one per line.

So I counted them:

import urllib
sum=0
for t in urllib.urlopen('http://pypi.python.org/pypi?%3Aaction=browse'):
t=t.split('(')[-1].split(')')[0]
try:
sum += int(t)
except ValueError:
pass # print "OMG cannot convert %s to int" % t
print "sum is: %s" % sum 

Which yields: sum is: 31670

That would be around half the weight of CPAN, which would be a
not-so-bad result ;)

My Questions: 
a) Are there package listed in multiple Categories, which would breaking
my counting?
b) Did I make some other mistake(s)?
c) is there a counter which yields the current number of PyPI-Packages?

PS: Please excuse my bad english, I am not a native speaker.

THX, Michael
--
http://mail.python.org/mailman/listinfo/python-list


Re: Number of Packages in the "cheeseshop"

2009-03-05 Thread Michael Rudolf
Am Thu, 5 Mar 2009 05:38:58 -0800 (PST)
schrieb John Machin :

> Main page (http://pypi.python.org/pypi), right at the top:
> """
> The Python Package Index is a repository of software for the Python
> programming language. There are currently 5883 packages here.
> """

Ooops... totally missed that... must have been blind, sorry.
Thank you.

> > for t in \
> > urllib.urlopen('http://pypi.python.org/pypi?%3Aaction=browse'):
> > t=t.split('(')[-1].split(')')[0]
> That statement is a thing of beauty and a joy forever. I wonder what
> it does.
extracts everything between parentheses per line, as long as there is
exactly one '(' and one ')' in it (true for that site).

Didnt want to parse the HTML or write a regex for that simple Job.

Anyways, sorry for that stupid post and thanks for pointing out that
there actually *is* a counter.
Next time I will readjust my caffeine-in-blood-level before posting. ;)

Michael
--
http://mail.python.org/mailman/listinfo/python-list


Signature-based Function Overloading in Python

2010-02-23 Thread Michael Rudolf
Just a quick question about what would be the most pythonic approach in 
this.


In Java, Method Overloading is my best friend, but this won't work in 
Python:


>>> def a():
pass
>>> def a(x):
pass
>>> a()
Traceback (most recent call last):
  File "", line 1, in 
a()
TypeError: a() takes exactly 1 argument (0 given)

So - What would be the most pythonic way to emulate this?
Is there any better Idom than:

>>> def a(x=None):
if x is None:
pass
else:
pass

?

Thanks,
Michael
--
http://mail.python.org/mailman/listinfo/python-list


Re: Signature-based Function Overloading in Python

2010-02-24 Thread Michael Rudolf

First: Thanks for all the replies so far, they really helped me.

Am 24.02.2010 11:28, schrieb Jean-Michel Pichavant:

>>> def a(x=None):
if x is None:
pass
else:
pass


This is the way to do it python, and it has its advantages: 1 docstring,
1 way do do it, 1 interface.


Yes, I see. Actually I do now realize that even in Java I use method 
overloading mostly to implement optional arguments anyway, like:


void constructor(){this.foo='foo'; this.initotherstuff();}
void constructor(int x) {this.x=x; this.constructor();}

and so on.

So most of the time the idiom above is exactly what I need, as the 
versions of the function share code anyway.


But there are also cases where they do something completely different - 
in these cases I might use one of the other solutions provided here or 
simply make two or three functions and name them appropiately.


I do now see that the pythonic approach is the "best" for most cases, 
but I really loved to see that you *can* do overloading in a convenient 
way if you really want to :D Those decorators just rock :D


Thanks again,
Michael
--
http://mail.python.org/mailman/listinfo/python-list


Re: Is this secure?

2010-02-24 Thread Michael Rudolf

Am 24.02.2010 18:23, schrieb mk:

Even then I'm not getting completely uniform distribution for some reason:
d 39411
l 39376
f 39288
a 39275
s 39225
r 39172
p 39159
t 39073
k 39071
u 39064
e 39005
o 39005
n 38995
j 38993
h 38975
q 38958
c 38938
b 38906
g 38894
i 38847
m 38819
v 38712
z 35321
y 35228
w 35189
x 35075

Code:

import operator

def gen_rand_word(n):
with open('/dev/urandom') as f:
return ''.join([chr(ord('a') + ord(x) % 26) for x in f.read(n)])


The reason is 256 % 26 != 0
256 mod 26 equals 22, thus your code is hitting a-v about 10% (256/26 is 
approx. 10) more often than w-z. You might want to skip the values 0-22 
to achieve a truly uniform distribution.


FYI: Electronic Cash PINs in europe (dont know about the rest of the 
world) were computed the same way (random hexdigit and just mod it when 
it's too large) leading to a high probability that your first digit was 
a 1 :)


Regards,
Michael
--
http://mail.python.org/mailman/listinfo/python-list


Re: Is this secure?

2010-02-24 Thread Michael Rudolf

Am 24.02.2010 19:35, schrieb mk:

On 2010-02-24 18:56, Michael Rudolf wrote:


The reason is 256 % 26 != 0
256 mod 26 equals 22, thus your code is hitting a-v about 10% (256/26 is
approx. 10) more often than w-z.


writing secure code is hard...


So true. That's why one should stick to standard libs when it comes to 
crypto or security in general. It's just to easy to mess it up. Just ask 
Debian about whether touching OpenSSL was a good idea ;)




You might want to skip the values 0-22
to achieve a truly uniform distribution.

Hmm perhaps you meant to skip values over 256 - 22 ?


That's the same thing as x mod y equals x+N*y mod y for every natural N.


def gen_rand_word(n):
with open('/dev/urandom') as f:
return ''.join([chr(ord('a') + ord(x) % 26) for x in f.read(n) if ord(x)
 > 22])


Off-by-one-error: you're skipping len(range(22))==23 hits.
OK, I just see that I wrote misleading 0-22 while I meant range(22).



While with this:
def gen_rand_word(n):
with open('/dev/urandom') as f:
return ''.join([chr(ord('a') + ord(x) % 26) for x in f.read(n) if ord(x)
< 235])


Same off-by-one.


FYI: Electronic Cash PINs in europe (dont know about the rest of the
world) were computed the same way (random hexdigit and just mod it when
it's too large) leading to a high probability that your first digit was
a 1 :)

Schadenfreude is deriving joy from others' misfortunes; what is the
German word, if any, for deriving solace from others' misfortunes? ;-)


Well - "Schadenfreude" *is* in fact a german word :)
"Schaden" is the event or result of misfortune, "Freude" is joy.


Well, I really think that you should use repeated Random.choice on an 
alphabet.

Or Random.Systemrandom.choice if you don't trust the PRNG.

Regards,
Michael
--
http://mail.python.org/mailman/listinfo/python-list


Re: Is this secure?

2010-02-24 Thread Michael Rudolf

Am 24.02.2010 21:06, schrieb mk:


I just posted a comparison with calculating std deviations for various
methods - using os.urandom, SystemRandom.choice with seeding and without
seeding.


I saw them


They all seem to have slightly different distributions.


No they don't. Just run those tests again and you will see that you 
cannot put them in any order or behaviour. They are all correct now, 
except that you cannot seed SystemRandom, as it is *not* a PRNG (at 
least here, it is a wrapper for /dev/random)


Regards,
Michael
--
http://mail.python.org/mailman/listinfo/python-list


Re: How to make an empty generator?

2010-02-24 Thread Michael Rudolf

Am 24.02.2010 23:58, schrieb Aahz:

(abbreviated "gen iter" or "geniter").


lol I don't know why, but this sounds like a sex toy to me ;)

Regards,
Michael
--
http://mail.python.org/mailman/listinfo/python-list


Re: Signature-based Function Overloading in Python

2010-02-25 Thread Michael Rudolf

Am 25.02.2010 11:58, schrieb Jean-Michel Pichavant:

You said it yourself: "simply make two or three functions and name
them appropiately" :-)

When 2 methods of a class were to have the same name for doing
completely different things like you said, there's a design flaw to my
opinion.

JM

I wonder if I've just written that my opinion is flawed... It surely is,
but that's not why I meant :-)


:D

Well, there might be cases when someone wants to do this. consider: 
(pseudocode - this is *not* python ;)


class Machines (Object):
@classmethod
def shutdown(cls, Machine, emergency=False):
   try:
if Machine is instanceof(Fileservers):
if not emergency:
Machine.unmount_raid_first()
...
Machine.halt()
if Machine is instanceof(Router):
if not emergency:
cls.shutdown(Machine.attachedmachines)
...
...
finally:
if emergency and Machine has powerswitch:
Machine.powerswitch.Off()
@classmethod
def emergency(cls):
for machine in cls.instances:
cls.shutdown(machine, 1)

Other design patterns might me good too, but I like the idea of having 
emergency protocols in *one* place here. But without method overloading, 
there are many many nested 'if's.


One could say that the machines have to know how to shut down itself, 
but there might be dependencies they do not know about, and as said, it 
clutters the emergency protocol all over the modules.


One could define normal_shutdown() and emergency_shutdown(), but I do 
not like this eighter, and there are still many 'if's to seperate the types.


There are cases where *no* solution is perfect, and those are the cases 
where "2 methods of a class were to have the same name for doing 
completely different things" or other messy things like this are IMO 
*NOT* a design flaw.


Regards,
Michael
--
http://mail.python.org/mailman/listinfo/python-list


Re: What's the word on using """ to comment-out?

2010-02-25 Thread Michael Rudolf

Am 25.02.2010 16:07, schrieb Grant Edwards:

On 2010-02-25, Paul Rudin  wrote:

No idea, but it would be nice to have some multiline comment syntax
(other than # at the beginning of each line). Particularly one that can
be nested.


if 0:

Seriously, that's what I generally do: mark the block of code,
indent it 1 level, add an if 0: at the top.



I really hate it when I see something like this in other's code.
The fact that my IDE (vim) still displays this like valid code ready to 
be executed can cause extreme frustration while trying to spot a bug.


This is almost as bad as "commenting out" (parts of) a for loop by 
adding a continue.


I once saw this in production code and wanted to kill the original 
developer, as commenting out the parts of the code with the continue (it 
was a *bg* for-loop) for debugging purposes actually would have 
*enabled* the code below, thus rendering the whole database useless.


Lucky me that I a) had backups b) set up a sandbox and c) actually saw 
this before it was too late.


Regards,
Michael
--
http://mail.python.org/mailman/listinfo/python-list


Re: round() function

2010-02-25 Thread Michael Rudolf

Am 25.02.2010 16:39, schrieb Tracubik:

hi all, i've this sample code:


n = 4.499
str(round(n,2))

'4.5'

that's right, but what i want is '4.50' to be displayed instead of '4.5'.
Off course i know that 4.5 = 4.50, still i'ld like to have 4.50.

How can I solve this?

Thanks in advance
Nico


This has nothing to do with round().
round() returns a float, and float(4.50) is 4.5.

You can *print* it as 4.50 using format strings, but the float will 
always be 4.5



>>> n = 4.499
>>> x=round(n,2)
>>> x
4.5
>>> print "%.2f" % x
4.50
>>> s="%.2f" % round(n,2)
>>> s
'4.50'
>>>
--
http://mail.python.org/mailman/listinfo/python-list


Re: What's the word on using """ to comment-out?

2010-02-26 Thread Michael Rudolf

Am 25.02.2010 17:39, schrieb Grant Edwards:

IMO, any sort of "commented out" code left in a program is a
big mistake.  If the code is soething that does need to stay
for optional use, then it needs to be properly integrated along
with logic to control when it's used.


OK, then we are perfectly fine and of course for personal use everyone 
can "comment out" code as they wish.


I'd just hate to see something like "if False" in production level code.
--
http://mail.python.org/mailman/listinfo/python-list


Re: What's the word on using """ to comment-out?

2010-02-26 Thread Michael Rudolf

Am 26.02.2010 12:47, schrieb Michael Rudolf:

I'd just hate to see something like "if False" in production level code.


And yeah, I've seen it. And worse.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Signature-based Function Overloading in Python

2010-02-27 Thread Michael Rudolf

Am 27.02.2010 10:00, schrieb alex23:

Michael Rudolf  wrote:

In Java, Method Overloading is my best friend


Guido wrote a nice article[1] on "multimethods" using decorators,
which Ian Bicking followed up on[2] with a non-global approach.

1: http://www.artima.com/weblogs/viewpost.jsp?thread=101605
2: http://blog.ianbicking.org/more-on-multimethods.html



Nice!
I really liked 
http://bob.pythonmac.org/archives/2005/03/30/five-minute-multimethods-in-python-using-dispatch/

--
http://mail.python.org/mailman/listinfo/python-list


Method / Functions - What are the differences?

2010-02-28 Thread Michael Rudolf

Out of curiosity I tried this and it actually worked as expected:

>>> class T(object):
x=[]
foo=x.append
def f(self):
return self.x


>>> t=T()
>>> t.f()
[]
>>> T.foo(1)
>>> t.f()
[1]
>>>

At first I thought "hehe, always fun to play around with python. Might 
be useful sometimes" - but then It really confused me what I did. I 
mean: f is what we call a method, right? But was is foo? It is not a 
method and not a classmethod as it accepts no self and no cls.
So that leaves staticmethod? OK, fair, as x is "static" here anyway this 
reflects what it does. But then consider this:


>>> class T(object):
def __init__(self):
self.x=[]
self.foo=self.x.append
def f(self):
return self.x


>>> y=T()
>>> y.x
[]
>>> y.foo(1)
>>> y.x
[1]
>>> a=T()
>>> a.x
[]
>>> a.foo(2)
>>> a.x
[2]
>>>

Note that all I did was moving the list and foo into the instance. Still 
no self and no cls, but also no static behaviour any more.


So is foo just nothing of the above and really only a class/instance 
attribute which happens to be callable?


Perhaps this all does not matter, but now I am really confused about the 
terminology. So: what makes a method a method? And of what type?


Regards,
Michael
--
http://mail.python.org/mailman/listinfo/python-list


Re: Method / Functions - What are the differences?

2010-02-28 Thread Michael Rudolf

Am 28.02.2010 15:08, schrieb Alf P. Steinbach:

 >>> "Hello".upper

 >>> f = "Hello".upper
 >>> f

 >>> f()
   'HELLO'
 >>>
 >>>
 >>>
 >>> f.__self__
   'Hello'


Holy hand grenade.
You have no Idea how enlightened I feel right now :D

Thank you, "bound method" was the term I forgot and your example... 
...totally revealed the internals behind this to me. Especially the last 
line I quoted.

I mean, I always knew *that* this works, but I never knew *why*.

Regards,
Michael
--
http://mail.python.org/mailman/listinfo/python-list


Re: Re Interest check in some delicious syntactic sugar for "except:pass"

2010-03-03 Thread Michael Rudolf

Am 03.03.2010 12:47, schrieb Oren Elrad:

""" code involving somefile """
try:
os.remove(somefile)
except:
...pass # The bloody search indexer has got the file and I
can't delete it. Nothing to be done.


You don't know that what you stated in your comment is true.
All you know is that there was an exception. To find the reason, you 
have to inspect the exception.

You escpecially do NOT know whether the file is removed or not.

OK, os.remove() might be a CPython builtin (not sure ATM), but in 
general all sort of crazy things can happen here, like ImportError 
raised by code in the lib or so.
And of course: a bare except: also catches ^C or SystemExit. That is 
almost certainly *not* what you want, right?


To your first question about a "silenced" keyword: you could emulate 
this with context managers I guess.


Something like (untested, just a quick mockup how it could look):



class silenced:
def __init__(self, *silenced):
self.exceptions=tuple(silenced) #just to be explicit
def __enter__(self):
return self #dito1
def __exit__(self, type, value, traceback):
for ex in self.exceptions:
if isinstance(value, ex):
return True #supresses exception


So:

with silenced(os.Error):
os.remove(somefile)

Would translate to:

try:
os.remove(somefile)
except os.Error:
pass

One nice thing about this approach would be that you can alias a set of 
exceptions with this:


idontcareabouttheseerrors=silenced(TypeError, ValueError, PEBCAKError, 
SyntaxError, EndOfWorldError, 1D10T_Error)


with idontcareabouttheseerrors:
do_stuff()

Regards,
Michael
--
http://mail.python.org/mailman/listinfo/python-list


Re: Is this secure?

2010-03-03 Thread Michael Rudolf

Am 03.03.2010 04:51, schrieb Lie Ryan:

import itertools
def gen():
 valid_chars = 'abcdefghijklmnopqrstuvwxyz'
 for char in itertools.repeat(valid_chars):
 yield char

gen = gen()
def gen_rand_string(length):
 chars = (next(gen) for i in range(length))
 return ''.join(chars)

since it gives me a perfect distribution of letters,


It does not. Only if not (length(valid_chars) % length)

Regards,
Michael
--
http://mail.python.org/mailman/listinfo/python-list


Re: case do problem

2010-03-04 Thread Michael Rudolf

Am 03.03.2010 18:38, schrieb Tracubik:

Il Wed, 03 Mar 2010 09:39:54 +0100, Peter Otten ha scritto:



def loop():
 count = 0
 m = 0
 lookup = {1: 1, 2: 10, 3: 100}
 for iterations in range(20): # off by one
 # ...
 print "%2d %1d %3d" % (iterations, count, m) # ...
 if generic_condition():
 count += 1
 # ...
 m = lookup.get(count, m)
 if count == 4:
 break

if __name__ == "__main__":
 loop()
 print "That's all, folks"

Something must be wrong with me today because I find the Pascal code
/more/ readable..


i was think the same, Pascal seem to generate a great more readable code.
I'm a newbie, so my opinion is probably wrong, but i still think that
don't have CASE OF and REPEAT UNTIL code block return in difficult-to-
read code.


That is probably a side-effect of literal code translation.

No one would write something like you did when he writes in python the 
first place.



>> Tracubik wrote:
>>
>>> hi, i've to convert from Pascal this code:
>>
>> program loop;
>>
>> function generic_condition: boolean;
>> begin
>> generic_condition := random>  0.7
>> end;
>>
>> procedure loop;
>> var
>> iterations, count, m: integer;
>> begin
>> iterations := 0;
>> count := 0;
>> m := 0;
>> repeat
>>iterations := iterations+1;
>>(*...*)
>>writeln(iterations:2, count:2, m:4);
>>(*...*)
>>if generic_condition then
>>inc(count);
>>(*...*)
>>case count of
>>1: m := 1;
>>2: m := 10;
>>3: m := 100
>>end
>> until (count = 4) or (iterations = 20)
>> end;
>>
>> begin
>> loop;
>> writeln("That's all, folks")
>> end.

Hmmm lets see...
We have somewhat obscure and complicated logic.

If we cannot get rid of it, lets hide it:

class Loop:
def __init__(self, maxiterations=0, maxcount=1, m=0):
assert generic_condition.__call__
self.maxiterations = maxiterations
self.maxcount = maxcount
self.m=m
self.count=0
self.iterations=0

def __iter__(self):
while True:
yield self.next()

def next(self):
self.iterations+=1
if self.iterations > self.maxiterations:
raise StopIteration
if generic_condition():
self.count += 1
if self.count >= self.maxcount:
raise StopIteration
self.m = (None,1,10,100)[self.count]
return self, self.m

# So we have:

#from complicatedlogic import Loop
from random import random

def generic_condition():
return random() > 0.7

if __name__ == '__main__':
for loop, m in Loop(maxiterations=20, maxcount=4):
print("%2d %1d %3d" % (loop.iterations, loop.count, m))
print("That's all, folks")


better? worse? I honestly do not know.

Note that while this is valid py3 and runs as intended, there might be 
some off-by-one or something left.


Also, this is of course not production level code ;)

Regards,
Michael
--
http://mail.python.org/mailman/listinfo/python-list


Re: How to login https sever with inputing account name and password?

2010-03-04 Thread Michael Rudolf

Am 04.03.2010 11:38, schrieb Karen Wang:

Hi all,

I want to use python to access to https server, like
"https://212.218.229.10/chinatest/";

If open it from IE, will see the pop-up login windows like this



I tried several ways but always only get page for" HTTP Error 401.2 -
Unauthorized" error. ( myusername and mypassword are all correct)

Below is my code:

import urllib2

values = {

 'user' : "myusername",

"pass' : "mypassword" }

data = urllib2.urlencode(values)

t = urllib2.urlopen('https://212.218.229.10/chinatest/',data)

print t.read()

where I am wrong ?


AFAIR does urlopen() expect the password to be Base64-encoded, not 
urlencoded.


You might also need to add an AUTH-Line. But this all does not matter, 
as there is more than one AUTH-Method you'd have to implement them all, 
but fortunately urllib2.HTTPBasicAuthHandler and 
urllib2.HTTPBasicAuthHandler exist.


So use them:

import urllib2
passman = urllib2.HTTPPasswordMgrWithDefaultRealm()
passman.add_password(None, theurl, username, password)
authhandler = urllib2.HTTPBasicAuthHandler(passman)
opener = urllib2.build_opener(authhandler)
urllib2.install_opener(opener)
pagehandle = urllib2.urlopen(theurl)

(taken from 
http://www.voidspace.org.uk/python/articles/authentication.shtml )


Further reference:
http://www.python.org/doc/2.5.2/lib/module-urllib2.html
http://www.python.org/doc/2.5.2/lib/urllib2-examples.html

HTH,
Michael
--
http://mail.python.org/mailman/listinfo/python-list


Re: A "scopeguard" for Python

2010-03-04 Thread Michael Rudolf

Am 04.03.2010 17:32, schrieb Jean-Michel Pichavant:

It looks like to me that 'with' statements are like decorators: overrated.


Oh no, you just insulted my favourite two python features, followed 
immediately by generators, iterators and list comprehensions / generator 
expressions :p


No, really: they *are* great ;D

Regards,
Michael
--
http://mail.python.org/mailman/listinfo/python-list


Re: A "scopeguard" for Python

2010-03-04 Thread Michael Rudolf

Am 04.03.2010 18:20, schrieb Robert Kern:


What I'm trying to explain is that the with: statement has a use even if
Cleanup doesn't. Arguing that Cleanup doesn't improve on try: finally:
does not mean that the with: statement doesn't improve on try: finally:.


Yes, the with-statement rocks :)

I suggested such a thing a few days ago in another thread, where OP 
wanted a "silent" keyword like:


silent:
do_stuff()

would be equivalent to:
try: do_stuff() except: pass

Of course catching *all* exceptions was a bad idea, so I came up with 
the code below and now I actually like it and use it myself :)


-snip-
To your first question about a "silenced" keyword: you could emulate 
this with context managers I guess.


Something like (untested, just a quick mockup how it could look):



class silenced:
def __init__(self, *silenced):
self.exceptions=tuple(silenced) #just to be explicit
def __enter__(self):
return self#dito
def __exit__(self, type, value, traceback):
for ex in self.exceptions:
if isinstance(value, ex):
return True #supresses exception


So:

with silenced(os.Error):
os.remove(somefile)

Would translate to:

try:
os.remove(somefile)
except os.Error:
pass

One nice thing about this approach would be that you can alias a set of 
exceptions with this:


idontcareabouttheseerrors=silenced(TypeError, ValueError, PEBCAKError, 
SyntaxError, EndOfWorldError, 1D10T_Error)


with idontcareabouttheseerrors:
do_stuff()

Regards,
Michael
--
http://mail.python.org/mailman/listinfo/python-list


Re: related lists mean value (golfed)

2010-03-09 Thread Michael Rudolf

Am 09.03.2010 13:02, schrieb Peter Otten:

[sum(a for a,b in zip(x,y) if b==c)/y.count(c)for c in y]

[1.5, 1.5, 8.0, 4.0, 4.0, 4.0]
Peter


... pwned.
Should be the fastest and shortest way to do it.

I tried to do something like this, but my brain hurt while trying to 
visualize list comprehension evaluation orders ;)


Regards,
Michael
--
http://mail.python.org/mailman/listinfo/python-list


Re: related lists mean value

2010-03-09 Thread Michael Rudolf

Am 08.03.2010 23:34, schrieb dimitri pater - serpia:

Hi,

I have two related lists:
x = [1 ,2, 8, 5, 0, 7]
y = ['a', 'a', 'b', 'c', 'c', 'c' ]

what I need is a list representing the mean value of 'a', 'b' and 'c'
while maintaining the number of items (len):
w = [1.5, 1.5, 8, 4, 4, 4]


This kinda looks like you used the wrong data structure.
Maybe you should have used a dict, like:
{'a': [1, 2], 'c': [5, 0, 7], 'b': [8]} ?


I have looked at iter(tools) and next(), but that did not help me. I'm
a bit stuck here, so your help is appreciated!


As said, I'd have used a dict in the first place, so lets transform this 
straight forward into one:


x = [1 ,2, 8, 5, 0, 7]
y = ['a', 'a', 'b', 'c', 'c', 'c' ]

# initialize dict
d={}
for idx in set(y):
d[idx]=[]

#collect values
for i, idx in enumerate(y):
d[idx].append(x[i])

print("d is now a dict of lists: %s" % d)

#calculate average
for key, values in d.items():
d[key]=sum(values)/len(values)

print("d is now a dict of averages: %s" % d)

# build the final list
w = [ d[key] for key in y ]

print("w is now the list of averages, corresponding with y:\n \
\n x: %s \n y: %s \n w: %s \n" % (x, y, w))


Output is:
d is now a dict of lists: {'a': [1, 2], 'c': [5, 0, 7], 'b': [8]}
d is now a dict of averages: {'a': 1.5, 'c': 4.0, 'b': 8.0}
w is now the list of averages, corresponding with y:

 x: [1, 2, 8, 5, 0, 7]
 y: ['a', 'a', 'b', 'c', 'c', 'c']
 w: [1.5, 1.5, 8.0, 4.0, 4.0, 4.0]

Could have used a defaultdict to avoid dict initialisation, though.
Or write a custom class:

x = [1 ,2, 8, 5, 0, 7]
y = ['a', 'a', 'b', 'c', 'c', 'c' ]

class A:
def __init__(self):
self.store={}
def add(self, key, number):
if key in self.store:
self.store[key].append(number)
else:
self.store[key] = [number]
a=A()

# collect data
for idx, val in zip(y,x):
a.add(idx, val)

# build the final list:
w = [ sum(a.store[key])/len(a.store[key]) for key in y ]

print("w is now the list of averages, corresponding with y:\n \
\n x: %s \n y: %s \n w: %s \n" % (x, y, w))

Produces same output, of course.

Note that those solutions are both not very efficient, but who cares ;)


thanks!


No Problem,

Michael
--
http://mail.python.org/mailman/listinfo/python-list


Re: related lists mean value (golfed)

2010-03-09 Thread Michael Rudolf

OK, I golfed it :D
Go ahead and kill me ;)

x = [1 ,2, 8, 5, 0, 7]
y = ['a', 'a', 'b', 'c', 'c', 'c' ]

def f(a,b,v={}):
try: v[a].append(b)
except: v[a]=[b]
def g(a): return sum(v[a])/len(v[a])
return g
w = [g(i) for g,i in [(f(i,v),i) for i,v in zip(y,x)]]

print("w is now the list of averages, corresponding with y:\n \
\n x: %s \n y: %s \n w: %s \n" % (x, y, w))

Output:
w is now the list of averages, corresponding with y:

 x: [1, 2, 8, 5, 0, 7]
 y: ['a', 'a', 'b', 'c', 'c', 'c']
 w: [1.5, 1.5, 8.0, 4.0, 4.0, 4.0]

Regards,
Michael
--
http://mail.python.org/mailman/listinfo/python-list


Re: Unicode characters in btye-strings

2010-03-12 Thread Michael Rudolf

Am 12.03.2010 21:56, schrieb Martin v. Loewis:

(*) If a source encoding was given, the source is actually recoded to
UTF-8, parsed, and then re-encoded back into the original encoding.


Why is that? So "unicode"-strings (as in u"string") are not really 
unicode-, but utf8-strings?


Need citation plz.

Thx,
Michael
--
http://mail.python.org/mailman/listinfo/python-list


Re: I passed a fizzbuzz test but failed at recursion.

2010-03-14 Thread Michael Rudolf

Am 10.03.2010 16:55, schrieb Bill:

def fizzbuzz(num):
 if num:
 if num % 15 is 0: return fizzbuzz(num-1) + 'fizzbuzz \n'
 elif num % 5 is 0: return fizzbuzz(num-1) + 'buzz \n'
 elif num % 3 is 0: return fizzbuzz(num-1) + 'fizz \n'
 else : return fizzbuzz(num-1) + ('%d \n' % num)
 return ''
print fizzbuzz(100)


While I do understand that this is not a Perl group, and this probably 
won't help the OP, I just could not resist:


for i in range(1,101):print('','fizz')[not i%3]+('','buzz')[not i%5]or i

> However, when I try to decipher the logic of the function I imagine
> the solution reversed as "buzz fizz 98 97 ...etc... 4 fizz 2 1".

No, the function creates the string from right to left.
See:
fizzbuzz(100) = fizzbuzz(99) + "buzz \n"
= fizzbuzz(98) + "fizz \n" + "buzz \n"

...

= fizzbuzz(1) + "2 \n" + "fizz \n" + "4 \n" + "buzz\n " + "fizz \n" + 
 + "97 \n" + "98 \n" + "fizz \n" + "buzz \n"


= fizzbuzz(0) + "1 \n" + "2 \n" + "fizz \n" + "4 \n" + "buzz\n " + "fizz 
\n" +  + "97 \n" + "98 \n" + "fizz \n" + "buzz \n"


= " " + "1 \n" + "2 \n" + "fizz \n" + "4 \n" + "buzz\n " + "fizz \n" + 
 + "97 \n" + "98 \n" + "fizz \n" + "buzz \n"


Regards,
Michael
--
http://mail.python.org/mailman/listinfo/python-list


Re: "Breaking" the __main__ script

2010-03-14 Thread Michael Rudolf

Am 14.03.2010 12:53, schrieb Mark Lawrence:

vsoler wrote:

I sometimes want to stop the script at a certain point,
with something like stop, break, end or something similar.
What statement can I use?

Something like
import sys
sys.exit()?


Or just "raise SystemExit", "raise SyntaxError" or any other Exception.
But you won't have to: If you use IDLE, you can just set breakpoints in 
your code: enable the debugger in debug-debugger and set breakpoints via 
right click in your source file.


Or you could use a real debugger, like pdb
http://docs.python.org/library/pdb.html

HTH,
Michael
--
http://mail.python.org/mailman/listinfo/python-list


Re: "Breaking" the __main__ script

2010-03-14 Thread Michael Rudolf

Am 14.03.2010 16:03, schrieb pyt...@bdurham.com:

Any reason you prefer PDB over WinPDB?
http://winpdb.org/


Yes. I don't have Windows except one one PC :P
--
http://mail.python.org/mailman/listinfo/python-list


Re: "Breaking" the __main__ script

2010-03-14 Thread Michael Rudolf

Am 14.03.2010 21:08, schrieb pyt...@bdurham.com:

Any reason you prefer PDB over WinPDB?
http://winpdb.org/

Yes. I don't have Windows except one one PC :P

WinPDB runs on non-Windows platforms :)

Uh, OK.
Then the name mislead me ;)

But yeah, I prefer a console based debugger.
--
http://mail.python.org/mailman/listinfo/python-list


Re: import antigravity

2010-03-16 Thread Michael Rudolf

Am 16.03.2010 21:44, schrieb Mark Lawrence:

Who actually *IS* running the time machine?  Are there any bugs??


My is. And as I'm a lazy hacker: sure. there are bugs. lets just call 
them features and move on. nothing to see here ;)

--
http://mail.python.org/mailman/listinfo/python-list