Converting long to int in python

How convert long to int in python

If your program is on Python 2.x where int and long difference matters, and you are sure you are not using large integers, you could have just been fine with using to provide the key as well. Solution: Python has two different kinds of integers.

Why can’t a long integer be converted to an integer when inside a Python list?

Python has two different kinds of integers. The int type is used for those that fit into 32 bits, or -0x80000000 to 0x7fffffff. The long type is for anything outside that range, as all your examples are. The difference is marked with the L appended to the number, but only when you use repr(n) as is done automatically when the number is part of a list.

In Python 3 they realized that this difference was arbitrary and unnecessary. Any int can be as large as you want, and long is no longer a type. You won’t see repr put the trailing L on any numbers no matter how large, and adding it yourself on a constant is a syntax error.

Читайте также:  Add kotlin to gradle

Convert Double to Integer in Java, Math.round() accepts a double value and converts it into the nearest long value by adding 0.5 to the value and trimming its decimal points. The

Converting string to long in python

long can only take string convertibles which can end in a base 10 numeral. So, the decimal is causing the harm. What you can do is, float the value before calling the long . If your program is on Python 2.x where int and long difference matters, and you are sure you are not using large integers, you could have just been fine with using int to provide the key as well.

So, the answer is long(float(‘234.89’)) or it could just be int(float(‘234.89’)) if you are not using large integers. Also note that this difference does not arise in Python 3, because int is upgraded to long by default. All integers are long in python3 and call to covert is just int

Well, longs can’t hold anything but integers.

One option is to use a float: float(‘234.89’)

The other option is to truncate or round. Converting from a float to a long will truncate for you: long(float(‘234.89’))

>>> long(float('1.1')) 1L >>> long(float('1.9')) 1L >>> long(round(float('1.1'))) 1L >>> long(round(float('1.9'))) 2L 

Converting list of long ints to ints, Why do you want to convert the longs to integers? The list should work the same whether it contains integers or longs. Or are you just doing

Convert string to respective data type ie. int or long (python3)

As opposed to Python 2, Python 3 doesn’t distinguish between int and long ( long is gone from Python 3). It’s just an integer which can be even longer than 64-bit.

From Python 3 documentation

Integers have unlimited precision.

Convert string to respective data type ie. int or long (python3), As opposed to Python 2, Python 3 doesn’t distinguish between int and long ( long is gone from Python 3). It’s just an integer which can be

Is it possible to convert a really large int to a string quickly in python

You wrote in the comments that you want to get the length of the integer in decimal format. You don’t need to convert this integer to a string, you can use «common logarithm» instead:

import math math.ceil(math.log(a, 10)) 

Moreover, if you know that:

then math.log(a, 10) is equal to math.log(plaintextOrd, 10) * bigNumber , which shouldn’t take more than a few milliseconds to calculate:

>>> plaintextOrd = 12345 >>> bigNumber = 67890 >>> a = plaintextOrd**bigNumber >>> len(str(a)) 277772 >>> import math >>> math.ceil(math.log(a, 10)) 277772 >>> math.ceil(math.log(plaintextOrd, 10) * bigNumber) 277772 

It should work even if a wouldn’t fit on your hard drive:

>>> math.ceil(math.log(123456789, 10) * 123456789012345678901234567890) 998952457326621672529828249600 

As mentioned by @kaya3, Python standard floats aren’t precise enough to describe the exact length of such a large number.

You could use mpmath (arbitrary-precision floating-point arithmetic) to get results with the desired precision:

>>> from mpmath import mp >>> mp.dps = 1000 >>> mp.ceil(mp.log(123456789, 10) * mp.mpf('123456789012345678901234567890')) mpf('998952457326621684655868656199.0') 

Some quick notes on the «I need it for this function».

 new = [] for i in range(parts): new.append(string[a*i:a*(i+1)]) 

or just new = [string[a*i:a*(i+1)] for i in range(parts)] .

Note that you have silently discarded the last len(string) % parts characters.

In your second loop, you shadow i with for i in i , which happens to work but is awkward and dangerous. It can also be replaced with string2 = ».join(new) , which means you can just do string2 = string[:-(len(string) % parts)] .

You then see if the strings are the same length, and then add the extra letters to the end of the last list. This is a little surprising, e.g. you would have

>>> divideStringIntoParts(3, '0123456789a') ['012', '345', '6789a'] 

When most algorithms would produce something that favors even distributions, and earlier elements, e.g.:

>>> divideStringIntoParts(3, '0123456789a') ['0124', '4567', '89a'] 

Regardless of this, we see that you don’t really care about the value of the string at all here, just how many digits it has. Thus you could rewrite your function as follows.

def divide_number_into_parts(number, parts): ''' >>> divide_number_into_parts(12345678901, 3) [123, 456, 78901] ''' total_digits = math.ceil(math.log(number + 1, 10)) part_digits = total_digits // parts extra_digits = total_digits % parts remaining = number results = [] for i in range(parts): to_take = part_digits if i == 0: to_take += extra_digits digits, remaining = take_digits(remaining, to_take) results.append(digits) # Reverse results, since we go from the end to the beginning return results[::-1] def take_digits(number, digits): ''' Removes the last digits from number. Returns those digits along with the remainder, e.g.: >>> take_digits(12345, 2) (45, 123) ''' mod = 10 ** digits return number % mod, number // mod 

This should be very fast, since it avoids strings altogether. You can change it to strings at the end if you’d like, which may or may not benefit from the other answers here, depending on your chunk sizes.

Faster than function str conversion of int to str is provided by GMPY2

import time from gmpy2 import mpz # Test number (Large) x = 123456789**12345 # int to str using Python str() start = time.time() python_str = str(x) end = time.time() print('str conversion time seconds'.format(end - start)) # int to str using GMPY2 module start = time.time() r = mpz(x) gmpy2_str = r.digits() end = time.time() print('GMPY2 conversion time seconds'.format(end - start)) print('Length of 123456789**12345 is: '.format(len(python_str))) print('str result == GMPY2 result <>'.format(python_str==gmpy2_str)) 

Results (GMPY2 was 12 times faster in test)

str conversion time 0.3820 seconds GMPY2 conversion time 0.0310 seconds Length of 123456789**12345 is: 99,890 str result == GMPY2 result True 

Python int to binary string?, Go straight to the format() function: format(n, ‘b’) . There is no need to parse out the placeholder and match it to an argument, go straight for the value

Источник

Data Type Conversion in Python

Sometimes, you may need to perform conversions between the built-in types. To convert between types, you simply use the type name as a function.

There are several built-in functions to perform conversion from one data type to another. These functions return a new object representing the converted value.

Sr.No. Function & Description
1 int(x [,base])
Converts x to an integer. base specifies the base if x is a string.
2 long(x [,base] )
Converts x to a long integer. base specifies the base if x is a string.
3 float(x)
Converts x to a floating-point number.
4 complex(real [,imag])
Creates a complex number.
5 str(x)
Converts object x to a string representation.
6 repr(x)
Converts object x to an expression string.
7 eval(str)
Evaluates a string and returns an object.
8 tuple(s)
Converts s to a tuple.
9 list(s)
Converts s to a list.
10 set(s)
Converts s to a set.
11 dict(d)
Creates a dictionary. d must be a sequence of (key,value) tuples.
12 frozenset(s)
Converts s to a frozen set.
13 chr(x)
Converts an integer to a character.
14 unichr(x)
Converts an integer to a Unicode character.
15 ord(x)
Converts a single character to its integer value.
16 hex(x)
Converts an integer to a hexadecimal string.
17 oct(x)
Converts an integer to an octal string.

Источник

Python 3 — Numbers

Number data types store numeric values. They are immutable data types. This means, changing the value of a number data type results in a newly allocated object.

Number objects are created when you assign a value to them. For example −

You can also delete the reference to a number object by using the del statement. The syntax of the del statement is −

You can delete a single object or multiple objects by using the del statement. For example −

Python supports different numerical types −

  • int (signed integers) − They are often called just integers or ints. They are positive or negative whole numbers with no decimal point. Integers in Python 3 are of unlimited size. Python 2 has two integer types — int and long. There is no ‘long integer‘ in Python 3 anymore.
  • float (floating point real values) − Also called floats, they represent real numbers and are written with a decimal point dividing the integer and the fractional parts. Floats may also be in scientific notation, with E or e indicating the power of 10 (2.5e2 = 2.5 x 10 2 = 250).
  • complex (complex numbers) − are of the form a + bJ, where a and b are floats and J (or j) represents the square root of -1 (which is an imaginary number). The real part of the number is a, and the imaginary part is b. Complex numbers are not used much in Python programming.

It is possible to represent an integer in hexa-decimal or octal form

>>> number = 0xA0F #Hexa-decimal >>> number 2575 >>> number = 0o37 #Octal >>> number 31

Examples

Here are some examples of numbers.

int float complex
10 0.0 3.14j
100 15.20 45.j
-786 -21.9 9.322e-36j
080 32.3+e18 .876j
-0490 -90. -.6545+0J
-0×260 -32.54e100 3e+26J
0×69 70.2-E12 4.53e-7j

A complex number consists of an ordered pair of real floating-point numbers denoted by a + bj, where a is the real part and b is the imaginary part of the complex number.

Number Type Conversion

Python converts numbers internally in an expression containing mixed types to a common type for evaluation. Sometimes, you need to coerce a number explicitly from one type to another to satisfy the requirements of an operator or function parameter.

  • Type int(x) to convert x to a plain integer.
  • Type long(x) to convert x to a long integer.
  • Type float(x) to convert x to a floating-point number.
  • Type complex(x) to convert x to a complex number with real part x and imaginary part zero.
  • Type complex(x, y) to convert x and y to a complex number with real part x and imaginary part y. x and y are numeric expressions

Mathematical Functions

Python includes the following functions that perform mathematical calculations.

The absolute value of x: the (positive) distance between x and zero.

The ceiling of x: the smallest integer not less than x.

-1 if x < y, 0 if x == y, or 1 if x >y. Deprecated in Python 3. Instead use return (x>y)-(x.

The floor of x: the largest integer not greater than x.

The natural logarithm of x, for x > 0.

The base-10 logarithm of x for x > 0.

The largest of its arguments: the value closest to positive infinity

The smallest of its arguments: the value closest to negative infinity.

The fractional and integer parts of x in a two-item tuple. Both parts have the same sign as x. The integer part is returned as a float.

x rounded to n digits from the decimal point. Python rounds away from zero as a tie-breaker: round(0.5) is 1.0 and round(-0.5) is -1.0.

The square root of x for x > 0.

Random Number Functions

Random numbers are used for games, simulations, testing, security, and privacy applications. Python includes the following functions that are commonly used.

A random item from a list, tuple, or string.

A randomly selected element from range(start, stop, step).

A random float r, such that 0 is less than or equal to r and r is less than 1

Sets the integer starting value used in generating random numbers. Call this function before calling any other random module function. Returns None.

Randomizes the items of a list in place. Returns None.

A random float r, such that x is less than or equal to r and r is less than y.

Trigonometric Functions

Python includes the following functions that perform trigonometric calculations.

Return the arc cosine of x, in radians.

Return the arc sine of x, in radians.

Return the arc tangent of x, in radians.

Return atan(y / x), in radians.

Return the cosine of x radians.

Return the Euclidean norm, sqrt(x*x + y*y).

Return the sine of x radians.

Return the tangent of x radians.

Converts angle x from radians to degrees.

Converts angle x from degrees to radians.

Mathematical Constants

The module also defines two mathematical constants −

The mathematical constant pi.

The mathematical constant e.

Источник

Оцените статью