Gekitsuu
Gekitsuu

Reputation: 87

In python how can I iterate through a string splitting it at different spots as I go?

I'm trying to write a quick solve for Kaprekar number's to show a friend of mine how easy it is to implement something like this in Python. I know how to do all the steps except for iterating through the squared number as a string. For example 45 is a Kaprekar number because

45 ** 2 = 2025 and 20 + 25 = 45

What I'm trying to write is code that would take the result of 45 ** 2 = 2025 and let me iterate over the combinations like

['2', '025']

['20', '25']

['202', '5']

Upvotes: 2

Views: 247

Answers (2)

unmounted
unmounted

Reputation: 34388

I will spend a couple of extra days in purgatory for answering a math question already answered by Ignacio, but you may also experiment with some variant of:

>>> a = 2025
>>> for i in range(1,4):
...     print a / 10**i, a % 10**i
... 
202 5
20 25
2 25

Upvotes: 1

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 798606

>>> s = '2025'
>>> for i in range(1, len(s)):
...   print s[:i], s[i:]
... 
2 025
20 25
202 5

Upvotes: 7

Related Questions