반응형
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
반응형
'<개인공부> - IT > [Python]' 카테고리의 다른 글
What does if __name__ == “__main__”: do? (0) | 2018.09.15 |
---|---|
Python Multiple return values (Tuple, Dict) (0) | 2018.08.23 |
Python Dictionary 자료형 사용해보기 (0) | 2018.08.20 |
Number of Things Challenge 함수 만들기 (0) | 2018.08.20 |
Commafy 함수 만들기 (0) | 2018.08.20 |