티스토리 뷰

python lecture/algorism

[edu] Kaprekar series

burningrizen 2018. 10. 14. 23:47

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 k digits.

Kaprekar series

The Kaprekar series for a number n is represented as a list whose first element is n. The next number is calculated as the difference K(n)=nn between the number n that exists of the digits of n sorted in increasing order, and the number n that exists of the digits of n 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 nN. The function must return the Kaprekar series for the given number n.

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
댓글