Looking at this article, I was impressed if Tetris could be made in just seven lines. But I can't javascript at all, so I don't understand the meaning. (I mean, I understand the syntax, but I don't know what I'm doing) However, I realized that short coating would be cool, and I thought that Python might be able to do that, so I will introduce it. Also, I don't have vocabulary, so please forgive me even if the sentence is strange.
First, try building a primality test program normally. (Execution speed is not considered)
JudgeNum=int(input("number?"))
prime=True
for i in range(2,JudgeNum):
if JudgeNum%i==0:
prime=False
print(prime)
Execution result
number?5
True
This is the usual answer. Even if you show this to other people, it is a reaction like "Hmm". Let's shorten this a little for the time being
First
int(input("number?"))#Is
int(input())#Replace with
JudgeNum#Is
n#Replace with
Then use the comprehension notation.
prime=True
for i in range(2,n):
if n%i==0:
prime=False
This guy
prime=not[i for i in range(2,n) if n%2==0]
Is almost the same as In this comprehension, the number of cracks is added to the list.
In python, an empty list is evaluated as False, so by flipping it with not, the empty list (which means that it was not divisible by all numbers) is a prime number. (vocabulary) (I tried to flip it with ~ instead of not for a moment, but I couldn't because the flip is a list.)
Then you don't need the variable prime. So
print(not[i for i in range(2,n) if n%2==0])
Can be shortened with. Eventually
n=int(input())
print(not[i for i in range(2,n) if n%2==0])
I was able to shorten it to two lines.
If you've come this far, I'd like to have one line. But when you declare a variable, you have to start a new line. Is it necessary to have at least two lines because the primality test algorithm is almost impossible without using variables? I wish I could do it with commas like function arguments ... . . . ! Should I use a function! However, it is impossible with ordinary functions. So I decided to use an anonymous function (lambda). Just take n as an argument
(lambda n:print(not[i for i in range(2,n)if n%i==0]))(int(input()))
Now you can compress it to one line. Eh? Do you know that two lines have fewer characters?
This is a short coating that I worked hard on. If you have a code shorter than this, please let me know.
Recommended Posts