본문 바로가기
<개인공부> - IT/[Python]

List 자료형의 Join함수 사용하기

by Aggies '19 2018. 8. 21.
반응형

Question:

Write a program which will find all such numbers which are divisible by 7 but are not a multiple of 5,
between 2000 and 3200 (both included).
The numbers obtained should be printed in a comma-separated sequence on a single line.

def divisibleSevenNotDivisibleFive():
listOfNumber = ""

# Range: 2000 ~ 3200
for i in range(2000, 3201):
if((i % 7 == 0) and (i % 5 != 0)):
listOfNumber = listOfNumber + str(i) + ", "
return listOfNumber

print (divisibleSevenNotDivisibleFive())

위와 같이 프로그래밍을 하게되면 마지막 3199, 하고 comma를 찍게된다.
if문에 해당되면 그 숫자와 함께 comma를 문자열에 덮어씌우니까 말이다.

그러나 아래와 같이 join 함수를 이용하면 해결할 수 있다.

def divisibleSevenNotDivisibleFive():

# Convert data type from string to list
listOfNumber = []

# Range: 2000 ~ 3200
for i in range(2000, 3201):
if((i % 7 == 0) and (i % 5 != 0)):

# Append data by list's built-in "append" function
listOfNumber.append(str(i))
return listOfNumber

print (", ".join(divisibleSevenNotDivisibleFive()))

Reference site : 

https://github.com/zhiwehu/Python-programming-exercises/blob/master/100%2B%20Python%20challenging%20programming%20exercises.txt

반응형