8 Respuestas
+ 3
I'm not sure how many other ways there are, but one way would be to use the floor function in the math module:
>>> import math
>>> math.floor(123.0)
123
Then again it uses another built-in function.
---------------------------
I think using fewer built-in functions or methods does help you understand how things work in python, but according to me you can give certain fundamental functions a free pass, for example:
- print()
- data type functions (int, float, str, etc.)
- type()
- range()
- input(), etc.
---------------------------
However, there are functions and methods that you could avoid using, such as
- sorted()
- min() and max()
- sum()
- string methods like .center(), .swapcase(), .replace(), etc
But they do make life a lot easier, at least to write code efficiently.
---------------------------
There isn't much point in reinventing the wheel is there? :)
+ 1
That won't work @Louis, the output will still be 123.0
+ 1
Just A Rather Ridiculously Long Username
Thanks. Those are really good points.
+ 1
I have come up with a idea like this:
from itertools import count
num=123.0
def toInt(num):
for j in count(0):
if j==num:
return j
elif j>10000:
#just in case of potential infinite loop due to typos.
break
integer=toInt(num)
However, this method is really inefficient, since it iterate over 0 to num.
+ 1
Yes, I know that using count() from itertools is a bad idea, but count() can be replaced by other infinite generator object easily.
e.g.
def count(n):
while True:
yield n
n += 1
The example above is just for better understanding.
+ 1
Just A Rather Ridiculously Long Username
range() will returns a range object which can be converted to other data structures such as list by list() readily, but range() can only returns a object with finite length (you have to declare the up-limit beforehand)
count(n) returns a itertools.count object which can be used as an infinite generator object (start from n, and no end), so you should never try list(count(0)) which implies a infinite loop and using infinite memory. However, this kind of object with no ending can be useful during iteration.
+ 1
Right, I wasn't familiar with itertools.count and I don't really know how I missed the first line.
But once again, you're using another built-in method that generates 122 unnecessary int() objects before the one that you need (which could have been done in the first place using int(123.0)).
Still, good solution nonetheless.
0
That is a valid solution 李立威, but assuming by count() you mean range(), aren't you using another built-in function that uses the built-in class 'int' several times? ;)