Fun python 3.2 one-liner

R

Raymond Hettinger

from collections import Counter
from itertools import product

print('\n'.join('*'*(c//2000) for _,c in sorted(Counter(map(sum,
product(range(6), repeat=8))).items())))


almost-normally-yours,

Raymond
 
R

Raymond Hettinger

print('\n'.join('*'*(c//2000) for _,c in sorted(Counter(map(sum, product(range(6), repeat=8))).items())))








*
***
*****
********
************
******************
*************************
********************************
*****************************************
*************************************************
********************************************************
**************************************************************
******************************************************************
*******************************************************************
******************************************************************
**************************************************************
********************************************************
*************************************************
*****************************************
********************************
*************************
******************
************
********
*****
***
*



Re-posting (forgot to attach the output).
Besides the interesting output, other
interesting virtues include very low
memory usage and that the inner-loop
pipeline runs entirely in C.


Raymond
 
G

geremy condra

*
***
*****
********
************
******************
*************************
********************************
*****************************************
*************************************************
********************************************************
**************************************************************
******************************************************************
*******************************************************************
******************************************************************
**************************************************************
********************************************************
*************************************************
*****************************************
********************************
*************************
******************
************
********
*****
***
*



Re-posting (forgot to attach the output).
Besides the interesting output, other
interesting virtues include very low
memory usage and that the inner-loop
pipeline runs entirely in C.

Another (related) 3.2 one liner:

from math import erf, sqrt

def normal_cdf(x, mu=0, sigma=1): return (1/2) * (1 +
erf((x-mu)/(sigma*sqrt(2))))

approximates the cumulative distribution function of the normal distribution.

Geremy Condra
 
H

harrismh777

Raymond said:
almost-normally-yours,

Raymond

thanks ... interesting

Seriously, these little one liners teach me more about the python
language in less time than *all* of the books I'm trying to digest right
now. The toughest part of learning python is learning about what's
available so as not to reinvent the proverbial wheel...

thanks again... fun.
 
T

Terry Reedy

from collections import Counter
from itertools import product

print('\n'.join('*'*(c//2000) for _,c in sorted(Counter(map(sum,
product(range(6), repeat=8))).items())))

The line break makes that hard to read; the axis is not labeled (and
labels help understand the code). So my suggested revision is:

from collections import Counter
from itertools import product

print('\n'.join('{:2d}: {}'.format(i, '*'*(c//2000)) for i,c in sorted(
Counter(map(sum,product(range(6), repeat=8))).items() )))

0:
1:
2:
3:
4:
5:
6:
7: *
8: ***
9: *****
10: ********
11: ************
12: ******************
13: *************************
14: ********************************
15: *****************************************
16: *************************************************
17: ********************************************************
18: **************************************************************
19: ******************************************************************
20: *******************************************************************
21: ******************************************************************
22: **************************************************************
23: ********************************************************
24: *************************************************
25: *****************************************
26: ********************************
27: *************************
28: ******************
29: ************
30: ********
31: *****
32: ***
33: *
34:
35:
36:
37:
38:
39:
40:
 
M

Martin De Kauwe

what is the character limit on a one liner :p. Very interesting
jesting apart, any more?
 
C

Chris Angelico

what is the character limit on a one liner :p. Very interesting
jesting apart, any more?

Not sure if this can be redone as a one-liner; currently it's two.


for i in range(3):
print '\n\t"'+("minor","medium","major")+'
":({\n\t\t'+"\n\t\t".join([q[0]+',"'+" ".join(q[1:])+'",' for q in
[q.split("\x96")[-1].split(" ") for q in "\n".join([q.split("
",3)+" "+q.split(" ",3)[3] for q in
a.split("\n")]).replace("\x92","'").split("\n")] if
q[0]!="\x97"])+'\n\t}),'

That's the code I used in IDLE to translate this:

Minor Medium Major Ring Market Price
01–18 — — Protection +1 2,000 gp
19–28 — — Feather falling 2,200 gp
61–70 01–05 — Counterspells 4,000 gp
71–75 06–08 — Mind shielding 8,000 gp
86–90 24–28 — Ram 8,600 gp
— 29–34 — Climbing, improved 10,000 gp
— 35–40 — Jumping, improved 10,000 gp
— 41–46 — Swimming, improved 10,000 gp
91–93 47–51 — Animal friendship 10,800 gp
94–96 50–56 01–02 Energy resistance, minor 12,000 gp
99–100 62–66 — Water walking 15,000 gp
— 94–97 29–32 Blinking 27,000 gp
— 98–100 33–39 Energy resistance, major 28,000 gp
— — 40–49 Protection +4 32,000 gp
— — 98 Elemental command (fire) 200,000 gp
— — 99 Elemental command (water) 200,000 gp
— — 100 Spell storing, major 200,000 gp

into something that my dice-roller can use. (In the interests of
brevity I've chopped a whole lot of the table out, but each column
contains every possible value from 01 to 100.)

Not as "cool" as the previous one, but it sure was handy!

In case you're wondering: Yes, that is Dungeons and Dragons. I run an
online D&D server. Nerd? Only slightly.....

Chris Angelico
 
R

Raymond Hettinger

what is the character limit on a one liner :p. Very interesting
jesting apart, any more?

Sure, here are three one-liners using itertools.groupby() to emulate
some Unix pipelines:

sort letters | uniq # list unique values
sort letters | uniq -c # count unique values
sort letters | uniq -d # find duplicates
from itertools import groupby
[k for k, g in groupby(sorted('abracadabra'))]
['a', 'b', 'c', 'd', 'r']
[(k, len(list(g))) for k, g in groupby(sorted('abracadabra'))]
[('a', 5), ('b', 2), ('c', 1), ('d', 1), ('r', 2)]
[k for k, g in groupby(sorted('abracadabra')) if len(list(g)) > 1]
['a', 'b', 'r']


Raymond


P.S. Of course, there are many ways to do this.
['a', 'b', 'c', 'd', 'r']
[('a', 5), ('b', 2), ('c', 1), ('d', 1), ('r', 2)]
['a', 'b', 'r']
 
G

gb

harrismh777 said:
Seriously, these little one liners teach me more about the python
language in less time than [...]

def f(x,n,w): return x if n==1 else\
(lambda x0=f(x[::2],n/2,w[::2]),\
x1=f(x[1::2],n/2,w[::2]): reduce(lambda a,b: a+b ,\
zip(*[(x0[k]+w[k]*x1[k],\
x0[k]-w[k]*x1[k])\
for k in range(n/2)])))()

it was a joke of sort played on it.comp.lang.python

[thanks to marco (zip(*...)) and antonio (lambda with default
arguments)]
 
C

Chris Angelico

harrismh777 said:
Seriously, these little one liners teach me more about the python
language in less time than [...]

def f(x,n,w): return x if n==1 else\
   (lambda x0=f(x[::2],n/2,w[::2]),\
           x1=f(x[1::2],n/2,w[::2]): reduce(lambda a,b: a+b,\
                                     zip(*[(x0[k]+w[k]*x1[k],\
                                            x0[k]-w[k]*x1[k])\
                                            for k in range(n/2)])))()

it was a joke of sort played on it.comp.lang.python

(Remind me how it is that Python code is more readable than line noise
or Perl code?)

What sort of parameters does this take? So far all I can figure out is
that n is an integer and x and w are sliceables, but I'm not sure
whether x and w should be strings or arrays.

ChrisA
 
G

Gregory Ewing

Chris said:
(Remind me how it is that Python code is more readable than line noise
or Perl code?)

Crazy thought: I wonder if Perl programmers have "multi
line Perl" competitions where they laugh their heads off
at how readable the code is, and how nobody in their
right mind would ever write Perl code that way?-)
 
C

Chris Angelico

Chris Angelico wrote:

Crazy thought: I wonder if Perl programmers have "multi
line Perl" competitions where they laugh their heads off
at how readable the code is, and how nobody in their
right mind would ever write Perl code that way?-)

Ha!! Okay, now I have to explain to my fellow bus passengers what it
is that I just cracked up laughing at...

You know what? I don't think I can.

I do like readable code, but quite a few of my favorite language
features are the ones commonly (ab)used to make unreadable code. C's
?: operator, Pike's interpretation of || for defaults, Python's lambda
functions... all great ways to shorten your code, but so easily used
for evil.

I think I like things that can be used for evil.

ChrisA
 
E

Emile van Sebille

(Remind me how it is that Python code is more readable than line noise
or Perl code?)

Crazy thought: I wonder if Perl programmers have "multi
line Perl" competitions where they laugh their heads off
at how readable the code is, and how nobody in their
right mind would ever write Perl code that way?-)
[/QUOTE]

I don't know if I should be laughing or nodding in agreement... :)

Emile
 
G

Giacomo Boffi

Chris Angelico said:
def f(x,n,w): return x if n==1 else\
   (lambda x0=f(x[::2],n/2,w[::2]),\
           x1=f(x[1::2],n/2,w[::2]): reduce(lambda a,b: a+b ,\
                                     zip(*[(x0[k]+w[k]*x1[k],\
                                            x0[k]-w[k]*x1[k])\
                                            for k in range(n/2)])))()
What sort of parameters does this take? So far all I can figure out
is that n is an integer and x and w are sliceables, but I'm not sure
whether x and w should be strings or arrays.

def direct_fft(x,n):
return f(x,n,[exp(-2*pi*1j*k/n) for k in range(n/2)])
def inverse_fft(x,n):
return [x/n for x in f(x,n,[exp(+2*pi*1j*k/n) for k in range(n/2)])]
 
D

Daniel Fetchinson

what is the character limit on a one liner :p.
For PEP 8 compliance, 80 characters. :)

Yeah, but we don't live in the 80's or 90's anymore and our screens
can support xterms (or let alone IDE widows) much wider than 80
characters. I'm using 140 for python these days. Seriously, who would
want to limit him/herself to 80 characters in 2011?

Cheers,
Daniel
 
T

Tim Wintle

Yeah, but we don't live in the 80's or 90's anymore and our screens
can support xterms (or let alone IDE widows) much wider than 80
characters. I'm using 140 for python these days. Seriously, who would
want to limit him/herself to 80 characters in 2011?

I'd rather have two files open with 80 columns in them than a single
file with 160 columns and have to switch between files.

Tim Wintle
 
S

Steven D'Aprano

Yeah, but we don't live in the 80's or 90's anymore and our screens can
support xterms (or let alone IDE widows) much wider than 80 characters.
I'm using 140 for python these days. Seriously, who would want to limit
him/herself to 80 characters in 2011?

Seriously, or is that a rhetorical question?

People who like to have two source files side-by-side on a standard
sized monitor, or three on a wide-screen monitor.

People who need to read or edit source code on a virtual terminal rather
than in a GUI console app.

People who print out source code to read later.

People with poor vision who need to use a significantly larger sized
characters, and therefore can't fit as many on a line.

People who might want to email code snippets without having them
inconveniently wrapped by the mail client.

People who don't like reading really long, overly complex, lines, and
prefer to keep lines short for readability.

And most importantly... people who want to have their code accepted into
the Python standard library.


Personally, I find that the discipline of keeping to 80 characters is
good for me. It reduces the temptation of writing obfuscated Python one-
liners when two lines would be better. The *only* time it is a burden is
when I write doc strings, and even then, only a small one.
 
C

Chris Angelico

Seriously, or is that a rhetorical question?

People who like to have two source files side-by-side on a standard
sized monitor, or three on a wide-screen monitor.

And most importantly... people who want to have their code accepted into
the Python standard library.

Is that 80 including indentation, or excluding? And if including, does
that put a hard limit of 20 indentation levels for standard library
code?

Only partly tongue-in-cheek. I have code that quite legitimately has
gone to ten tabs in, and stayed there, and has on occasion gone as far
as 12-16. Generally I just scroll my display horizontally and ignore
the preceding tab levels. And sometimes I cheat a bit, in C or Pike,
and don't indent at some level; if it's a loop (or more likely a
switch) that surrounds the entire function, I might do:

void functionname(parameters) {while (cond)
{
//code at one indent, not two
}}

Can't do that in Python - for better or for worse.

Chris Angelico
 
S

Steven D'Aprano

Is that 80 including indentation, or excluding? And if including, does
that put a hard limit of 20 indentation levels for standard library
code?

Including.

As for the hard limit, pretty much.

Only partly tongue-in-cheek. I have code that quite legitimately has
gone to ten tabs in, and stayed there,

"Legitimately"? I very much doubt it. (Only half joking.)

and has on occasion gone as far as 12-16.

I would consider anything more than four indents a code smell. That is,
four is unexceptional; five would make me look over the code to see if it
could be refactored; six would make me look at it *carefully*; eight
would have me questioning my own sanity. I wouldn't give a hard limit
beyond which I would "never" go beyond, but I find it difficult to
imagine what drugs I'd need to be on to go beyond eight.

*wink*
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top