What can one line of Python code do?

Since I came into contact with Python in 2008, I can’t put it down. Gradually, I can’t bear to alienate Perl and Shell programming, because of the elegance of python? Not all, mainly because it can be developed efficiently.

What can that line of code do?

Interesting

My child’s English name is Andy. Maybe when I taught him to write a program, if I showed this line of code first, it might arouse his interest in the code.

>>> print'\
'.join([''.join([('AndyLove'[(x-y)%8]if((x*0.05)**2 + (y*0.1)** 2-1)**3-(x*0.05)**2*(y*0.1)**3<=0 else' ')for x in range(-30,30)])for y in range(15 ,-15,-1)])

Executing it in python will output a heart shape spelled out by one character.

Character graphics are still very interesting, 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 those who have learned complex numbers in high school should still have an impression. Each position is represented by the parameter N, which is the square root of x*x + y*y. If this value is greater than or equal to 2, the position value corresponding to 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 this new N value again. The image given by wikipedia is like this:

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

>>> print'\
'.join([''.join(['*'if abs((lambda a:lambda z,c,n:a(a,z,c,n))( lambda s,z,c,n:z if n==0 else s(s,z*z + c,c,n-1))(0,0.02*x + 0.05j*y,40))2 else' 'for x in range(-80,20)])for y in range(-20,20)])

Efficient

For handy gadgets, it is even more of Python’s forte.

One line of code prints the ninety-nine multiplication table:

print '\
'.join([' '.join(['%s*%s=%-2s' % (y,x,x*y) for y in range(1,x + 1) ]) for x in range(1,10)])

output:

One line of code calculates prime numbers between 1-1000

print(*(i for i in range(2, 1000) if all(tuple(i%j for j in range(2, int(i**.5))))))

One line of code can output the value of the first 100 Fibonacci numbers:

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 with interaction:

>>> reduce ( lambda x,y:x*y, range(1,input() + 1))
10
3628800

One line of code implements the conversion between Celsius and Fahrenheit:

>>> print((lambda i:i not in [1,2] and "Invalid input!" or i==1 and (lambda f:f<-459.67 and "Invalid input!" or f)( float(input("Please input a Celsius temperature:"))*1.8 + 32) or i==2 and (lambda c:c<-273.15 and "Invalid input!" or c)((float(input("Please input a Fahrenheit temperature:"))-32)/1.8))(int(input("1,Celsius to Fahrenheit\
2,Fahrenheit to Celsius\
Please input 1 or 2\
"))))
1,Celsius to Fahrenheit
2, Fahrenheit to Celsius
Please input 1 or 2
1
Please input a Celsius temperature: 28
82.4
>>>

As for string sorting and quick sorting, it is even easier to handle.

"".join((lambda x:(x.sort(),x)[1])(list('string')))

qsort = lambda arr: len(arr) > 1 and qsort(filter(lambda x: x<=arr[0], arr[1:] )) + arr[0:1] + qsort(filter(lambda x:x >arr[0], arr[1:] )) or arr

Connotation

Take a look at the following line of python code, you may be dizzy:

This is the original code to stimulate children’s interest in programming and let them practice. Its real appearance is roughly like this:

def guess_my_number(n):
while True:
user_input = raw_input("Enter a positive integer to guess: ")
if len(user_input)==0 or not user_input.isdigit():
print "Not a positive integer!"
else:
user_input = int(user_input)
if user_input > n:
print "Too big ! Try again!"
elif user_input < n:
print "Too small ! Try again!"
else:
print "You win!"
return True
guess_my_number(42)

In fact, as long as you understand functional programming, use the magical Lambda, cooperate with list comprehension and more complex judgment statements, any python code can be converted into a line of code.

For example, to take a random number from a list

import random as rnd
print rnd.choice([2,3,5,7,11,13,17])

Converted to Lambda can be:

print (lambda rnd: rnd. choice([1, 2, 3, 10]))(__import__('random'))

These codes are fun, mainly because they can help us understand some small details of Python, especially the magical usage of Lambda.

Extended

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

import antigravity

It opens the browser, showing the comic and related content on the site:

We can package python files into a library form, and then import them in, which is a line of code that secretly changes the concept and premise. For example, in order to transfer files with windows, set up a temporary ftp on Mac:

$ python -m pyftpdlib

Of course, this depends on the library pyftpdlib, which is not available on the machine, just pip install pyftpdlib.

If semicolons are allowed in a line of code, it is just sacrificing readability, and it is basically omnipotent.

On the premise of being connected to the Internet, obtain the public network IP address

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

You can easily write a small game with one line of code to simulate a golf shot.

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

Input the angle and strength such as (0.8,80), and you can get a parabola drawn by characters.

Add while and other statements to draw an endless

python -c "while 1:import random; print(random.choice('╥╲'), end='')"

Finally, one line of code ends with the philosophy of python.

$ python -c "import this"
The Zen of Python, by Tim Peters

Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one--and preferably only one--obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!

About Python technology reserves

Learning Python well is good whether it is employment or sideline business to make money, but to learn Python, you still need to have a study plan. Finally, everyone will share a full set of Python learning materials to help those who want to learn Python!

For beginners with 0 basics:

If you are a zero-based novice, you can consider getting started with Python quickly.

On the one hand, the learning time is relatively short, and the learning content is more comprehensive and concentrated.
On the other hand, you can find a learning plan that suits you

Including: Python activation code + installation package, Python web development, Python crawler, Python data analysis, artificial intelligence, machine learning and other tutorials. Take you to learn Python systematically from zero foundation!

Introduction to zero-based Python learning resources

Python learning route summary

The technical points in all directions of Python are sorted out to form a summary of knowledge points in various fields. Its usefulness lies in that you can find corresponding learning resources according to the above knowledge points to ensure that you can learn more comprehensively. (Get the full set of tutorials at the end of the article)

Python essential development tools

Reminder: The space is limited, the folder has been packed, and the way to obtain it is at the end of the article

Python learning video 600 collection

Watching the zero-based learning video is the fastest and most effective way to learn. Following the teacher’s ideas in the video, it is still very easy to get started from the basics to the in-depth.

Actual case

Optical theory is useless, you have to learn to follow along, and you have to do it yourself, so that you can apply what you have learned to practice. At this time, you can learn from some actual combat cases.

100 Python exercises

Check the learning results.

Interview questions

This full version of the full set of Python learning materials has been uploaded to CSDN. If you need it, you can scan the QR code of CSDN official certification below on WeChat to get it for free [guaranteed 100% free]