+ 1

Slice in python

Is it possible to slice an int for example, a = 12345 is it possible to slice it so every number becomes their own and is it possible to add them?

18th Jan 2019, 10:27 PM
Warrior422
Warrior422 - avatar
10 odpowiedzi
+ 5
The easiest way I know is to convert it to a string b=str(a) and to sum them just use sum(int(i) for i in b) So to sum it all in one line: sum( int(i) for i in str(a))
18th Jan 2019, 10:46 PM
Mohamed Ali ZORGATI
Mohamed Ali ZORGATI - avatar
+ 5
Then there is the old-school way of using modulo: x = 0 while number: x += number%10 number //= 10 I have just made a performance comparison in case you're interested: https://code.sololearn.com/c3zFM5oVLiaQ/?ref=app
19th Jan 2019, 12:31 AM
HonFu
HonFu - avatar
+ 4
I modified HonFu 's code to show the effect of length on time. After about 40, the str method is consistantly quicker. https://code.sololearn.com/cEF931LPWCyf/?ref=app
19th Jan 2019, 6:26 AM
Louis
Louis - avatar
+ 3
Yes, first turn it into a string, slice it like a string and turn back to int
19th Jan 2019, 12:27 AM
Andrej Zrnic
Andrej Zrnic - avatar
+ 3
Interesting. Why is this difference? Because 'big nums' in Python are internally different to let's say a 'long long'? (I wonder how their superlarge ints work anyway.)
19th Jan 2019, 9:27 AM
HonFu
HonFu - avatar
+ 3
HonFu Louis I suspected that the part running slow was the division and shift in the C method. So i changed it from base 10 (native human) to base 16 (native binary) with following change to Louis code: while n: s += n&15 n = n>>4 and, surprise: both methods are equivalent in speed (run it many times and see the spread of performance of Sololearn server). So it has to do with the difficulty to "just" extract the last digit of a big number and "just" dislocate a comma in base 10, what in base 16 is a very fast calculation.
13th Feb 2019, 11:52 AM
Edward
Edward - avatar
+ 2
HonFu it is not the same thing. I'm doing the last digit sum in Hexadecimal and not in decimal. so results will never match, unless you do s += n%16 n = n//16
13th Feb 2019, 1:44 PM
Edward
Edward - avatar
+ 2
HonFu kinda, yes. My intention was only try to guess were the code gets much slower using long integers, not compare results one to one. if you wish to compare one to one in hex base you need to transform the decimal in hex before summing the digits, and the sum must also be in hex.
13th Feb 2019, 8:51 PM
Edward
Edward - avatar
0
Edward, I am not so competent in bit operations so sorry if I'm wrong, but I just tried this here and to me it looks like your loop isn't doing the same thing. Can you tell me what I'm missing? for i in (123, 77, 3566): n = i s = 0 while n: s += n&15 n = n>>4 print(s) n = i s = 0 while n: s += n%10 n = n//10 print(s) print()
13th Feb 2019, 12:08 PM
HonFu
HonFu - avatar
0
Edward, but aren't we comparing apples and oranges then?
13th Feb 2019, 2:22 PM
HonFu
HonFu - avatar