What is the purpose of using 'int' in the following code? - python

What is the purpose of using int in the following code?
sum = sum + int(n % 10)

If n is an int, it does absolutely nothing, but if n is a float, it will make sure that the result of the modulo is always an integer.
Example:
>>> n = 3.14
>>> n % 10
3.14
>>> int(n % 10)
3
The actual reason why this was used and if it was necessary cannot be determined from only that one line in your question. But since that line also overrides the built-in sum and doesn't use the += compound assignment, it smells like a poor coder, so probably the usage of int() is just an unnecessary oversight.
It's also possible that n is an instance of some other class that implements __mod__ in a weird way, but that's quite inlikely.

Related

Should I use float literals to represent integer numbers as floats in Python?

Consider a function that is to return a half of a float argument. Should it better be the first or the second?
def half_a(x: float) -> float:
return x / 2
def half_b(x: float) -> float:
return x / 2.0
Is there any performance difference or is there a style convention that would say one of these is better than the other?
Clearly half_a looks better and a more complex piece of code may get more readable written this way but in some other languages it is either necessary or preferable to use the half_b version to avoid run-time type conversion.
It's hard to know if there's a performance difference (and if there is, it's definitely negligible). Regarding style, there is also no common convention. However, I would choose the first one, if you are on python 3+. Python 3 has a different operator for integer division. See below
x = 2
print(type(x)) # int
print(type(x / 2)) # float
print(type(x // 2)) # int
On the other hand, if you are on python 2, you should probably choose the second one, because if your argument happens to be an int
print(2/5) # 0
float divided by float is slightly faster than float divided by int:
>>> timeit.timeit('n/2', 'n=123456.789')
0.04134701284306175
>>> timeit.timeit('n/2.0', 'n=123456.789')
0.03455621766488548
>>> timeit.timeit('[n/2 for n in r]', 'r = [n*5/1.1 for n in range(1, 10001)]', number=10000)
5.177127423787169
>>> timeit.timeit('[n/2.0 for n in r]', 'r = [n*5/1.1 for n in range(1, 10001)]', number=10000)
4.067747102254316

Python basic equation error

When running this code it is giving me this error:
x = p((1/2) - (2/q)) TypeError: 'int' object is not callable
p = 0
q = 0
while (p==0):
p = int(input("Enter an integer for p: "))
while (q==0):
q = int(input("Enter an integer for q: "))
x = p((1/2) - (2/q))
print(x)
You didn't use *, the multiplication operator:
x = p * ((1/2) - (2/q))
------^ here
In math equations, the multiplication operator is often left out. E.g. a(b-2) means "a times the quantity b-2).
In programming however, you must explicitly include the multiplication operator. E.g. a*(b-2).
In Python (and most other languages), when a token is followed by open/close parenthesis, it implies that a function is being called. This is why you received the 'int' object is not callable error; because p is an int, and it looked like you were trying to call it.
You have another problem in your translation from "equation" to Python. In Python 2, integer division is used (when both operands are integers, of course). Which means that this term:
x = p * ((1/2) - (2/q))
^^^^^
is going to equal zero.
In Python 3, this is not the case. Division (with a single /) is always floating point.
Since this is probably not desired, you should do one of the following:
Convert one of the terms to float, e.g. float(1)/2
from __future__ import division which enables the Python 3 behavior
Just replace the term with 0.5
Because you are trying to do something like this:
p()
but p is variable.

Python memory error for integer and math

When I run my code below I get Memory Error
import math
X = 600851475143
halfX = math.trunc(int(X / 2))
countFactors = 0
for i in range(halfX):
if i >0 and X % i:
countFactors += 1
print countFactors
I understand because of math calcs here but I do not know how to correct it.
I'm going to guess you're using Python 2.7 (or 2.x, at any rate).
If that's the case, you should use xrange instead of range.
In python 3.x, range creates an iterator that only uses a few bytes of memory regardless of how large it is. In python 2.x, range always creates a list containing numbers counting up (or down) over the specified range. Calling range(some_large_number) can cause you to run out of memory in 2.x.
Therefore, Python 2.x has xrange which creates an iterator identical to range in 3.x.
Also, you can simplify your math somewhat. For example:
x = 600851475143
half_x = x // 2
count_factors = 0
for i in xrange(half_x):
if i > 0 and x % i == 0:
count_factors += 1
print count_factors
However, there are much more efficient ways to do this.
As a simple example, if the number is divisible by two, you can iterative over every other number, cutting the number of tests in half. Similarly, if it's divisible by 3, 5, etc.
I'll leave it to you to figure out the generalization. It's a fun problem :)

applying for loop such that counters are multiplied rather than being added in python

hello I am relatively new to python! Is there a way to do this using for loops in python?
This is a java implementation of something i want to do in python
for (i=1;i<20; i*= 2)
{System.out.println(i);}
Solution in while loop in python`
while i<20:
print i
i*=2
I cannot figure out a way to do this using for loops. Implemented it using while loop obviously, but still curious to know whether there is a method to do so or not
There are lots of ways to do this, e.g.
for i in range(5):
i = 2 ** i
print i
or using generators
from itertools import count, takewhile
def powers_of_two():
for i in count():
yield 2 ** i
for i in takewhile(lambda x: x < 20, powers_of_two()):
print i
But in the end, it depends on your use case what version gives the clearest and most readbale code. In most cases, you would probably just use a while-loop, since it's simple and does the job.
You think of for loops like they would be in other languages, like C, C++, Java, JavaScript etc.
Python for loops are different; they work on iterables, and you always have to read them like:
for element in iterable
instead of the C'ish
for(start_condition; continue_condition; step_statement)
Hence, you would need iterable to generate your products.
I like readability, so here's how I'd do it:
for a in (2**i for i in range(20)):
print a
But that mainly works because we mathematically know that the i'th element of your sequence is going to be 2**i.
There is not a real way to do this in Python. If you wanted to mimic the logic of that for loop exactly, then a manual while loop would definitely be the way to go.
Otherwise, in Python, you would try to find a generator or generator expression that produces the values of i. Depending on the complexity of your post loop expression, this may require an actual function.
In your case, it’s a bit simpler because the numbers you are looking for are the following:
1 = 2 ** 0
2 = 2 ** 1
4 = 2 ** 2
8 = 2 ** 3
...
So you can generate the numbers using a generator expression (2 ** k for k in range(x)). The problem here is that you would need to specify a value x which happens to be math.floor(math.log2(20)) + 1 (because you are looking for the largest number k for which 2 ** k < 20 is true).
So the full expression would be this:
for i in (2 ** k for k in range(math.floor(math.log2(20)) + 1)):
print(i)
… which is a bit messy, so if you don’t necessarily need the i to be those values, you could move it inside the loop body:
for k in range(math.floor(math.log2(20)) + 1):
i = 2 ** k
print(i)
But this still only fits your purpose. If you wanted a “real” C-for loop expression, you could write a generator function:
def classicForLoop (init, stop, step):
i = init
while i < stop:
yield i
i = step(i)
Used like this:
for i in classicForLoop(1, 20, lambda x: x * 2):
print(i)
Of course, you could also modify the generator function to take lambdas as the first and second parameter, but it’s a bit simpler like this.
Use range() function to define iteration length.You can directly use print() than system.out.println
Alexander mentioned it and re-iterating
for i in range(1,20):print(i*2)
You can also consider while loop here-
i=0
while (i<20):
print(2**i)
i=i+1
Remember indentation in python

What's actually happening when I convert an int to a string?

I understand it's easy to convert an int to a string by using the built-in method str(). However, what's actually happening? I understand it may point to the
__str__ method of the int object but how does it then compute the “informal” string representation? Tried looking at the source and didn't find a lead; any help appreciated.
Python repeatedly divides the int by 10 and uses % 10 to get the decimal digits one by one.
Just to make sure we're looking at the right code, here's the function Python 2.7 uses to convert ints to strings:
static PyObject *
int_to_decimal_string(PyIntObject *v) {
char buf[sizeof(long)*CHAR_BIT/3+6], *p, *bufend;
long n = v->ob_ival;
unsigned long absn;
p = bufend = buf + sizeof(buf);
absn = n < 0 ? 0UL - n : n;
do {
*--p = '0' + (char)(absn % 10);
absn /= 10;
} while (absn);
if (n < 0)
*--p = '-';
return PyString_FromStringAndSize(p, bufend - p);
}
This allocates enough space to store the characters of the string, then fills the digits in one by one, starting at the end. When it's done with the digits, it sticks a - sign on the front if the number is negative and constructs a Python string object from the characters. Translating that into Python, we get the following:
def int_to_decimal_string(n):
chars = [None] * enough # enough room for any int's string representation
abs_n = abs(n)
i = 0
while True:
i += 1
chars[-i] = str(abs_n % 10) # chr(ord('0') + abs_n % 10) is more accurate
abs_n //= 10
if not abs_n:
break
if n < 0:
i += 1
chars[-i] = '-'
return ''.join(chars[-i:])
Internally the Int object is stored as 2's complement representation like in C (well, this is true if range value allow it, python can automagically convert it to some other representation if it does not fit any more).
Now to get the string representation you have to change that to a string (and a string merely some unmutable list of chars). The algorithm is simple mathematical computing: divide the number by 10 (integer division) and keep the remainder, add that to character code '0'. You get the unit digit. Go on with the result of the division until the result of the division is zero. It's as simple as that.
This approach works with any integer representation but of course it will be more efficient to call the ltoa C library function or equivalent C code to do that if possible than code it in python.
When you call str() on an object it calls it's classes __ str__ magic method.
for example
class NewThing:
def __init__(self, name):
self.name = name
def __str__(self):
return self.name
From there you can use the str() method on the object, or use it directly in strings.
>> thing = NewThing("poop")
>> print thing
>> poop
More info on magic methods here
Not sure if this is what you wanted, but I can't comment yet to ask clarifying questions.

Categories