Let's do various things using Python's list comprehension notation

1.First of all

This is my first time writing an article about Python. Recently, I've been fond of a minor language called nim, but since it's really minor, I'm studying Python in parallel, and I spend my days teaching my friends "nim is good, George ...". .. Well, I'm off the topic, but this time I'll write an article about how to get used to list comprehensions while solving various problems with Python list comprehensions.

2. How to express list comprehension (lambda expression, if statement, etc.)

First from the basics

I want to make a list with the same value for all elements.

python


a=[0 for i in range(10)]
#[0,0,0,0,0,0,0,0,0,0]

I want to make a list that has values that follow a certain rule as elements.

For example, arithmetic progression of intersection 1

python


a=[i for i in range(10)]
#[0,1,2,3,4,5,6,7,8,9]

Using the function f (x)

python


def f(x):
  return x**2
a=[f(i) for i in range(10)]
#[0,1,4,9,16,25,36,49,64,81]

#Or even like this
b=[i**2 for i in range(10)]
#[0,1,4,9,16,25,36,49,64,81]

Let's use a lambda expression

python


a=[(lambda price,tax:price + (price * tax))(100*i,0.08) for i in range(10)]
#[0.0,108.0,216.0,324.0,432.0,540.0,648.0,756.0,864.0,972.0]

I want to make a list with only the elements that meet the conditions using the if statement.

When using only if

python


a=[i for i in range(10) if i%2==0]
#[0,2,4,6,8]

When using if-else

python


a=[x if x%2==1 else 0 for x in range(10)]
#[0,1,0,3,0,5,0,7,0,9]

3. Try to solve various problems

Both sides of the coin

100 coins are lined up in a row with the front side up. Turn over the multiple of 2. Turn over the multiple of 3. Turn over the multiple of 4. What is the number of coins on the front when you do that in order?

python


#Table is 1,The back is 0
#For the second and above, the odds and odds of the divisor determine whether it is the front or the back.
#For example, when it is 2, it turns over only once ⇒"If the number of divisors is even, the coin is back"
[print([k+1 for k,j in enumerate([0 if len([i for i in range(2,int(y/2)+1) if y%i==0])%2==0 
       else 1 for y in range(1,101)]) if j==1])]
#[4, 9, 16, 25, 36, 49, 64, 81, 100]
#I noticed when I tried this, but x**The answer is the number that can be represented by 2....(x**Because the divisor x of 2 overlaps)

#Another solution
import math
[print([i**2 for i in range(2,int(math.sqrt(100))+1)])]
#[4, 9, 16, 25, 36, 49, 64, 81, 100]

#It seems that you can also import the library, so I will try it
[print([i**2 for i in range(2,int([math.sqrt(100) for math in [__import__('math')]][0])+1)])]
#[4, 9, 16, 25, 36, 49, 64, 81, 100]

No, I'm going crazy

Perfect number up to 1000

python


[print([j for j in range(1,1001) if sum([i for i in range(1,int(j/2)+1) if j%i==0])==j])]
#[6,28,496]

Somehow sorting from random numbers

python


[print(sorted([int(rd.uniform(0,100)) for rd in [__import__('random')] for i in range(100)]))]

Prime numbers up to 1000

python


[print([i for i in range(2,1000) if 0 not in 
       [i%j for j in range(2,int([math.sqrt(i) for math in [__import__('math')]][0])+1)]])]
"""
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 
113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229, 233, 239, 241, 
251, 257, 263, 269, 271, 277, 281, 283, 293, 307, 311, 313, 317, 331, 337, 347, 349, 353, 359, 367, 373, 379, 383, 389, 
397, 401, 409, 419, 421, 431, 433, 439, 443, 449, 457, 461, 463, 467, 479, 487, 491, 499, 503, 509, 521, 523, 541, 547, 
557, 563, 569, 571, 577, 587, 593, 599, 601, 607, 613, 617, 619, 631, 641, 643, 647, 653, 659, 661, 673, 677, 683, 691, 
701, 709, 719, 727, 733, 739, 743, 751, 757, 761, 769, 773, 787, 797, 809, 811, 821, 823, 827, 829, 839, 853, 857, 859, 
863, 877, 881, 883, 887, 907, 911, 919, 929, 937, 941, 947, 953, 967, 971, 977, 983, 991, 997]
"""

Try to solve a ternary linear equation

For example, "There are 40, 60, 30 500-yen coins, 100-yen coins, and 10-yen coins, respectively. How many coins should I use to make a total of 9000 yen using them? It can be used when there is a problem like.

python


[ns 
 for ns in [dict()] if not(
        ns.update({"A":40}) or
        ns.update({"B":60}) or
        ns.update({"C":30}) or
        ns.update({"x":9000}) or
        print([[a,b,c] 
        for a in range(A+1) 
        for b in range(B+1) 
        for c in range(C+1) 
        if 500*a+100*b+10*c==x]))]

#[[14, 19, 10], [14, 20, 0], [15, 14, 10], [15, 15, 0], [16, 9, 10], [16, 10, 0], [17, 4, 10], [17, 5, 0], [18, 0, 0]]

The "if not" part on the second line can be "if". Like the if of [i for i in range (10) if i% 2 == 0], if it is True, it will be an element of the list and it must not be False, so when printing the entire list, [{'A' : 40,'B': 60,'C': 30,'x': 9000}] or [].

4. Finally

As an aside (or rather, as a personal memorandum), I will write about the above or frequent list. In python, the ~~ boolean value of print () seems to be False ~~ (the return value was None as shown below), for example, you can do this.

python


if print(5)==True:
    print("fxxk")
elif print(5)==None:
    print("brain fxxk")
else:
    print("brain")
#brain fxxk

In addition, in python, when A is True, "A or B" is obviously True, so B is not evaluated. (Same for "A and B" when A is False)

python


[print(5) or print(3) and print(4)]
#5
#3
#4 is not printed

I will add it when I can do something new again. The list comprehension seems to be Turing complete ...

Recommended Posts

Let's do various things using Python's list comprehension notation
Python basic operation 1st: List comprehension notation
List comprehension
Comprehension notation
List comprehension
Comprehension notation
[Python] List Comprehension Various ways to create a list
[Introduction to Udemy Python3 + Application] 60. List comprehension notation