Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>You should think of the following number split into 3-sized chunks:</p> <pre><code>1000005 -&gt; 100 000 5 </code></pre> <p>You have two problems. The first is that if you put those <em>integers</em> back together, you'll get:</p> <pre><code>100 0 5 -&gt; 100005 </code></pre> <p>(i.e., the middle one is 0, not 000) which is not what you started with. Second problem is that you're not sure what size the last part should be.</p> <p>I would ensure that you're first using a string whose length is an exact multiple of the part size so you know <em>exactly</em> how big each part should be:</p> <pre><code>def split_number (num, part_size): string = str(num) string_size = len(string) while string_size % part_size != 0: string = "0%s"%(string) string_size = string_size + 1 arr = [] pointer = 0 while pointer &lt; string_size: e = pointer + part_size arr.append(int(string[pointer:e])) pointer += part_size return arr </code></pre> <p>Secondly, make sure that you put the parts back together with the right length for each part (ensuring you don't put leading zeros on the first part of course):</p> <pre><code>def join_number(arr, part_size): fmt_str = "%%s%%0%dd"%(part_size) num = arr[0] for x in arr[1:]: num = fmt_str%(num,int(x)) return int(num) </code></pre> <p>Tying it all together, the following complete program:</p> <pre><code>#!/usr/bin/python def split_number (num, part_size): string = str(num) string_size = len(string) while string_size % part_size != 0: string = "0%s"%(string) string_size = string_size + 1 arr = [] pointer = 0 while pointer &lt; string_size: e = pointer + part_size arr.append(int(string[pointer:e])) pointer += part_size return arr def join_number(arr, part_size): fmt_str = "%%s%%0%dd"%(part_size) num = arr[0] for x in arr[1:]: num = fmt_str%(num,int(x)) return int(num) x = 1000005 print x y = split_number(x,3) print y z = join_number(y,3) print z </code></pre> <p>produces the output:</p> <pre><code>1000005 [1, 0, 5] 1000005 </code></pre> <p>which shows that it goes back together.</p> <p>Just keep in mind I haven't done Python for a few years. There's almost certainly a more "Pythonic" way to do it with those new-fangled lambdas and things (or whatever Python calls them) but, since your code was of the basic form, I just answered with the minimal changes required to get it working. Oh yeah, and be wary of negative numbers :-)</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload