One line of Python code

Source: Internet
Author: User

Life was short, just use Python.

Since the 08 touch python, there is a feeling of love, gradually, some can not bear to alienate the Perl and shell programming, because of the elegance of Python? Not all, the main is to effectively develop it.

What do you do with that line of code?

Interesting

My child's English name is Andy, perhaps when he first taught him to write a program, if you show this line of code, it might be more to arouse his interest in the code.

>>>Print' \ n '.Join(["'.Join([(' Andylove '[(x-y)%8]if((x*0. to)**2+(y*0.1)**2-1)**3-(x*0. to)**2*(y*0.1)**3<=0 Else"') for xIn Range (- -, -)]) for yIn range ( the,- the,-1)])

Executing it in Python will output a heart shape that is spelled out by a character.

Character graphics are still interesting and there is a famous image called Mandelbrot. Each position in the Mandelbrot image corresponds to a complex number in the formula N=x+y*i, and the senior high school plural should also have an impression. Each location is represented by the parameter n, which is the square root of the x*x+y*y. If the value is greater than or equal to 2, the position value for this number is 0. If the value of parameter n is less than 2, change the value of N to n*n-
N (n= (x*x-y*y-x) + (2*x*y-y) *i), and test the new N value again. The image given by the Wiki encyclopedia is this:

Let's draw a Mandelbrot with one line of code:

>>>Print' \ n '. Join (["'. Join ([' * 'ifABS ((LambdaA:LambdaZ,c,n:a (A,z,c,n)) (LambdaS,z,c,n:zifn==0ElseS (s,z*z+c,c,n-1))(0,0.02*x+0.05j*y, +)) <2 Else"' forXinchRange (- the, -)]) forYinchRange (- -, -)])

Efficient

Python's forte is also a tool for handy gadgets.

A line of code prints 99 multiplication tables:

‘\n‘.join([‘ ‘.join([‘%s*%s=%-2s‘forin range(1,x+1forin range(1,10)])

Output:

A line of code calculates the prime number between 1-1000

forinrange(21000ifallforinrange(2, int(i**.5))))))  

One line of code can output the values of the first 100 Fibonacci sequences:

print [x[0] for x in [  (a[i][0], a.append((a[i][1], a[i][0]+a[i][1]))) for a in ([[1,1]], ) for i in xrange(100) ]]

One line of code implements factorial, and it also interacts with:

>>> lambda x,y:x*y,  range(1,input()+1))103628800

A line of code to achieve a converter between degrees Celsius and Fahrenheit:

>>>Print (LambdaI:i not inch[1,2] and "Invalid input!" ori==1  and(Lambdaf:f<-459.67  and "Invalid input!" orf) (Float (Input ("Please input a Celsius temperature:"))*1.8+ +)ori==2  and(Lambdac:c<-273.15  and "Invalid input!" orc) ((Float (input ("Please input a Fahrenheit temperature:"))- +)/1.8)) (Int (Input ("1,celsius to Fahrenheit\n2,fahrenheit to celsius\nplease input 1 or 2\n"))))1, Celsius to Fahrenheit2, Fahrenheit to celsiusplease input1 or 21Please input a Celsius temperature: -82.4>>>

As for string sorting and quick sorting, it is extremely easy.

"".join((lambda x:(x.sort(),x)[1])(list(‘stringlen1and  qsort(filter(lambda x: x<=arr[0], arr[1:] )) + arr[0:1] + qsort(filter(lambda x: x>arr[0], arr[1or arr
Connotation

Take a look at the following line of Python code, and you might faint:

This is the original code to stimulate the child's programming interest, let the child practice, its real face is roughly this:

 def guess_my_number(n):     while True: User_input = Raw_input ("Enter a positive integer to guess:")ifLen (user_input) = =0 or  notUser_input.isdigit ():Print "Not a positive integer!"        Else: user_input = Int (user_input)ifUser_input > N:Print "Too Big!" Try again! "            elifUser_input < n:Print "Too Small!" Try again! "            Else:Print "You win!"                return TrueGuess_my_number ( the)

In fact, any Python code can be converted to a single line of code, as long as it understands functional programming, uses magical lambda, fits list derivation, and complex judgment statements.

For example, take a random number from a list

importas rndprint rnd.choice([2,35,711,13,17])

The conversion to a lambda can be:

print (lambda rnd: rnd.choice([12310]))(__import__(‘random‘))

The code is fun, and it's helpful to understand some of the python's vulture-like notes, especially the magical lambda usage .

Extend

Of course, there are other interesting places, enter the following line

import antigravity

It opens the browser to show the comics and related content on the website:

We can package the Python file into the form of a library and import it into a line of code that is a concept and a precondition. For example, to transfer files with Windows, and then temporarily set up FTP on Mac:

$ python -m pyftpdlib

Of course it depends on pyftpdlib this library, not on the machine, pip install pyftpdlib it can be.

If a semicolon is allowed to exist in a line of code, it is simply a sacrifice of readability, which is essentially omnipotent.

Access to the public IP address on the premise of a network

python"import socket; sock=socket.create_connection((‘ns1.dnspod.net‘,6666)); print sock.recv(16); sock.close()"

A line of code can easily write a small game, to simulate the golf shot.

"import math as m;a,v=eval(input());[print(‘%03d‘%x+‘ ‘*m.floor(0.5+x*m.tan(a)-x*x/(v*m.cos(a)))+‘o‘) for x in range(102)]"

Input angle and force size (0.8,80), you can get a character to paint the parabola.
Add upper while and other statements, draw an endless python -c "while 1:import random;print(random.choice(‘╱╲‘), end=‘‘)" .

Finally, a line of code ends with a python philosophy.

$ python-c"Import This"The Zen ofPython byTim petersbeautiful isBetter than ugly. Explicit isBetter than implicit. Simple isBetter than Complex.complex isBetter than complicated. Flat isBetter than nested. Sparse isBetter than dense. Readability counts. Special cases aren ' t special enough toBreak theRules. Although practicality beats purity. Errors should never pass silently. Unless explicitly silenced. Inch theFace ofAmbiguity, refuse theTemptation toGuess. There should be one--and preferably only one--obvious it.Although thatMay notBe obvious at  FirstUnless you ' re Dutch.now isBetter than never. Although never isOften better than *right* now. If theImplementation isHard toExplainit' s a bad idea. If theImplementation isEasy toExplainitMay is a good idea. Namespaces is one honking great idea- Let's do more of those!

Resources:
http://www.zhihu.com/question/37046157
https://onelinepy.herokuapp.com/
Https://github.com/csvoss/onelinerizer

One line of Python code

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.