I didn't feel like memorizing the basic grammar without an interesting sample program, so I decided to create a sample program for each basic grammar.
By the way, the definition of interesting is difficult, It's just interesting on my scale, so I'll make a funny sample program (maybe a little surreal), and there may be calculations like this one.
As a premise, I am a super beginner. I'm learning Python for the server side of web applications, and I'll be learning Django after finishing the basic grammar.
Create a program that calculates the number of divisors for integers from 1 to 100. Create two patterns, one is to calculate while extracting the elements of the list with for, and the other is to calculate with map.
x = range(1,100)
y = []
cnt = 0
for i in x:
cnt = 0
j = 1
#Divide by the number less than or equal to x
while j <= i:
#If it is divisible, it is a divisor, so count up
if x[i-1] % j == 0 :
cnt += 1
j += 1
y.append(cnt)
print(x)
print(y)
def yakusucalc(x1):
cnt = 0
j = 1
Try dividing by a number less than # x1
while j <= x1:
#If it is divisible, it is a divisor, so count up
if x1 % j == 0 :
cnt += 1
j += 1
return cnt
x = range(1,100)
y = list(map(yakusucalc, x))
print(x)
print(y)
By the way, when the graph is displayed, it looks like this.
The code to display the graph is as follows.
# This line is required when running on Jupyter Notebook
%matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
import math
x = range(1,100)
# Calculate the number of divisors.
def yakusucalc(x1):
cnt = 0
j = 1
Try dividing by a number less than # x1
while j <= x1:
#If it is divisible, it is a divisor, so count up
if x1 % j == 0 :
cnt += 1
j += 1
return cnt
y = list(map(yakusucalc, x))
print(x)
print(y)
plt.plot(x, y)
plt.show
By using map, the code has been simplified.
Postscript (2020/1/26) yakusucalc can be written in one line as follows. (Thank you for your comment)
def yakusucalc(value):
return sum(value % yakusu == 0 for yakusu in range(1, value + 1))
Recommended Posts