티스토리 뷰
The algorithm for constructing a Kaprekar series was discovered in 1949 by the Indian mathematical Dattaraya Ramachandra Kaprekar. It was originally described for numbers with four digits, but can be easily generalized for numbers with digits.
The Kaprekar series for a number is represented as a list whose first element is . The next number is calculated as the difference between the number that exists of the digits of sorted in increasing order, and the number that exists of the digits of sorted in decreasing order. This next number is appended to the end of the list.
We keep on repeating this procedure with the last number in the list, until the difference is 0, is equal to the previous number or already occurs in the list. If the procedure results in a number that already occurs in the list, this number must not be appended to the list.
Assignment
Write a function kaprekarSeries that takes a number . The function must return the Kaprekar series for the given number .
Example
>>> kaprekarSeries(677)
[677, 99, 0]
>>> kaprekarSeries(9876)
[9876, 3087, 8352, 6174]
>>> kaprekarSeries(55500)
[55500, 54945, 50985, 92961, 86922, 75933, 63954, 61974, 82962]
def int_to_array(num):
nums_str = str(num)
nums_int = list()
for num_str in nums_str:
nums_int.append(int(num_str))
return nums_int
def get_sort(nums, reverse):
order_nums = nums[:]
order_nums.sort(reverse=reverse)
return order_nums
def list_to_int(nums):
sum = 0
decimal = len(nums) - 1
for i, num in enumerate(nums):
base = 1
for _ in range(decimal - i):
base *= 10
sum += num * base
return sum
def get_diff(inc, dec):
return list_to_int(dec) - list_to_int(inc)
def kaprekarSeries(num):
result = list()
result.append(num)
while True:
nums = int_to_array(num)
inc = get_sort(nums, False)
dec = get_sort(nums, True)
diff = get_diff(inc, dec)
if diff in result:
break
result.append(diff)
num = diff
return result
print(kaprekarSeries(677))
'python lecture > algorism' 카테고리의 다른 글
[eud] bubble sorting (0) | 2018.10.15 |
---|---|
[edu] Zigzag (0) | 2018.10.15 |
[edu] Transitions and transversions (0) | 2018.10.08 |
[edu] Word sums (0) | 2018.10.08 |
[edu] Penney Ante (0) | 2018.10.06 |
- Total
- Today
- Yesterday
- django chatbot
- 엑셀 비교
- 파이썬 강좌
- 파이썬 입문
- 모바일 스킨 적용
- chatbot
- django
- PuTTYGen
- 문서 비교
- 파이썬
- 모바일 테마 적용
- gitlab
- admin.py
- 면접정답
- gitignore
- wsgi
- virtualenv
- 장고 플러스친구 자동응답
- 문과 코딩
- GIT
- 이미지 비교
- 장고
- 면접답변
- 파이썬 프로그래밍
- 플러스친구 자동응답
- pycrypto
- Python
- Tistory
- 장고 카톡 자동응답
- 파이썬 독학
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | 5 | 6 | 7 |
8 | 9 | 10 | 11 | 12 | 13 | 14 |
15 | 16 | 17 | 18 | 19 | 20 | 21 |
22 | 23 | 24 | 25 | 26 | 27 | 28 |
29 | 30 | 31 |