Ask Your Question
0

Converting a list of integers into a single integer

asked 3 years ago

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?

Preview: (hide)

Comments

What do you mean when you say "integer"?

John Palmieri gravatar imageJohn Palmieri ( 3 years ago )

1 Answer

Sort by » oldest newest most voted
2

answered 3 years ago

updated 3 years ago

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
Preview: (hide)
link

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 ( 3 years ago )

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

John Palmieri gravatar imageJohn Palmieri ( 3 years ago )

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 ( 3 years ago )

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 ( 3 years ago )

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: 3 years ago

Seen: 1,618 times

Last updated: May 27 '21