Ask Your Question
0

Converting a list of integers into a single integer

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

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 +0100 )edit

1 Answer

Sort by ยป oldest newest most voted
2

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

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

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

Comments

Thanks. However, sage truncates the value down to 14 digits after trying to multiple to get the sum back down to 3.141.... I am working on something other then pi, and I would like to try and keep the nth digits in the numbers I am working with.

nooniensoong97 gravatar imagenooniensoong97 ( 2021-06-17 04:23:20 +0100 )edit

What is n in your case? How many digits are you trying to keep?

John Palmieri gravatar imageJohn Palmieri ( 2021-06-17 07:39:45 +0100 )edit

n will increase by one each iteration. I am not sure how far I will run the program right now I am just in the debug phase.

nooniensoong97 gravatar imagenooniensoong97 ( 2021-06-26 16:07:38 +0100 )edit

What have you tried, what part of my suggestion isn't working? Can you just replace "10" in my suggestion with "m" and then increase m each time? If you want more help, you need to provide more details about what you're trying to accomplish.

John Palmieri gravatar imageJohn Palmieri ( 2021-06-27 00:27:13 +0100 )edit

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 +0100

Seen: 1,225 times

Last updated: May 27 '21