Ask Your Question
0

Converting a list of integers into a single integer

asked 2021-05-27 03:31:50 +0200

nooniensoong97 gravatar image

Hi,

So here's what I have to convert an interger into a list of integers. pie = pi.n(digits = 10) pies = list(pie.str()) pies.remove('.') pies = [int(i) for i in pies]

output: [3,1,4,1,5,9,2,6,5,3]

So after manipulating this list of integers I would like to then reverse the process to create a new integer. The only way I can think of is to take each item, and multiply them by the factor. ie. zero term wouldn't need to be multiplied, but the first term in list would be multiplied by 0.1, second would be multiplied by 0.01, and then add them all up. Is there an easier way of converting back to an integer?

edit retag flag offensive close merge delete

Comments

What do you mean when you say "integer"?

John Palmieri gravatar imageJohn Palmieri ( 2021-05-27 05:26:37 +0200 )edit

1 Answer

Sort by ยป oldest newest most voted
2

answered 2021-05-27 05:36:33 +0200

updated 2021-05-27 18:05:22 +0200

Sage integers have a digits method which returns the list of digits, with units digit last, preceded by 10's digit, etc.:

sage: a = 31415
sage: a.digits()
[5, 1, 4, 1, 3]

So you could do:

sage: pie = pi.n(digits = 10)
sage: pied = (pie * 10**10).trunc() # get an integer
sage: pied
31415926535
sage: pi_digits = pied.digits()
sage: pi_digits
[5, 3, 5, 6, 2, 9, 5, 1, 4, 1, 3]
sage: sum(10**index * digit for (index, digit) in enumerate(pi_digits))
31415926535
edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account.

Add Answer

Question Tools

1 follower

Stats

Asked: 2021-05-27 03:31:50 +0200

Seen: 37 times

Last updated: May 27