컴퓨터 못만지는거/야금야금 Python

파이썬으로 등차수열 출력하기 등차수열의 합 구하기

김무명01 2020. 1. 11.

* 파이썬으로 등차수열 만들기

* 파이썬으로 등차수열의 합 구하기

* list의 크기, size 구하기

* list 안의 숫자들 다 더하기

 

 

list 명령어를 이용하면 일정한 간격으로 증가, 감소하는 숫자의 집합(등차수열)을 만들 수 있다.

 

1
2
3
4
5
6
7
8
9
10
11
12
print('This is the program for printing out numbers in an arithmetic sequence.\n')
a0 = input('The first number: \n') #첫번째 숫자
= input('The difference: \n') #증가, 감소폭
ax = input('The last number: \n') #마지막 숫자, 혹은 이 규칙을 만족하는 이것보다 작은 수
a0 = int(a0)
= int(d)
ax = int(ax)
 
#수열 출력하기
= list(range(a0, ax+1, d));
#a0부터 d만큼 증가/감소하여 마지막 숫자는 ax보다 작은 수 집합을 a에 저장해라.
 
print(a)
 
cs

 

1부터 10씩 증가하여 100보다 작은 수의 집합을 list 명령어로 생성하였다.

The first number:
1
The difference:
10
The last number:
100
[1, 11, 21, 31, 41, 51, 61, 71, 81, 91]

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
print('This is the program for printing out numbers in an arithmetic sequence.\n')
print('And then, we are going to get the sum of the numbers in the list.\n')
a0 = input('The first number: \n')
= input('The difference: \n')
ax = input('The last number: \n')
a0 = int(a0)
= int(d)
ax = int(ax)
 
= list(range(a0, ax+1, d));
 
print(a)
 
print(len(a))
 
= 0
for i in range(0len(a)):
  s = s + a[i]; 
print('sum of the numbers: %d' %(s))
cs

len(a)를 통해 리스트 a의 크기 (=리스트 a가 가지고 있는 숫자의 개수)를 구할 수 있다.

 

s에 리스트에 저장된 a[i]를 구한다.

list(a)에 저장된 첫번째 숫자는 print(a[0])을 입력하면 호출할 수 있다.

첫번째 저장된 숫자는 [0], 두번째 저장된 숫자는 [1], ...

0부터 시작한다. => for 루프 안에서 i의 범위는 0부터 시작한다.

 

 

 

1, 3, 5, 7 (간격은 2) 수열의 합을 구해본다.

This is the program for printing out numbers in an arithmetic sequence.

And then, we are going to get the sum of the numbers in the list.

The first number:
1
The difference:
2
The last number:
7
[1, 3, 5, 7] #생성된 list(a)
4 #list(a)가 가지고 있는 원소의 개수
sum of the numbers: 16 # 1+3+5+7=16

 

 

 

 

댓글