The function method chechbirthday returnd an integer 1 if it is her birthday else 0
Answers
Answer:
Step-by-step explanation:
26
2
This question already has an answer here:
How to check if a float value is a whole number 13 answers
How to make python print 1 as opposed to 1.0 3 answers
In Python is there a way to turn 1.0 into a integer 1 while the same function ignores 1.5 and leaves it as a float?
Right now, int() will turn 1.0 into 1 but it will also round 1.5 down to 1, which is not what I want.
python floating-point integer
shareimprove this question
edited Apr 24 at 2:42
U10-Forward
28.6k55 gold badges2424 silver badges5050 bronze badges
asked Apr 4 at 7:46
Raymond Shen
18522 silver badges44 bronze badges
marked as duplicate by Martijn Pieters♦ python Apr 23 at 10:32
This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.
4
one way could be to check the float using is_integer() if that passes, convert it to int? – DirtyBit Apr 4 at 7:47
7
Floats are approximations, 1.0 could actually be 1.00000000000001 or 0.999999999999. – Barmar Apr 4 at 7:49
6
Note that because of duck typing, this passage you want to achieve is probably out of place or useless, depending on context. – Federico S Apr 4 at 7:52
13
Please specify your exact requirements in words/rules rather than just with a single example! – Lightness Races in Orbit Apr 4 at 10:35
5
def f(x): if x == 1.0: return 1 else return 1.5 – Bakuriu Apr 4 at 20:26
show 6 more comments
10 Answers
activeoldestvotes
79
Continuing from the comments above:
Using is_integer():
Example from the docs:
>>> (1.5).is_integer()
False
>>> (1.0).is_integer()
True
>>> (1.4142135623730951).is_integer()
False
>>> (-2.0).is_integer()
True
>>> (3.2).is_integer()
False
INPUT:
s = [1.5, 1.0, 2.5, 3.54, 1.0, 4.4, 2.0]
Hence:
print([int(x) if x.is_integer() else x for x in s])
Wrapped in a function:
def func(s):
return [int(x) if x.is_integer() else x for x in s]
print(func(s))
If you do not want any import:
def func(s):
return [int(x) if x == int(x) else x for x in s]
print(func(s))
Using map() with lambda function and the iter s:
print(list(map(lambda x: int(x) if x.is_integer() else x, s)))
OR
print(list(map(lambda x: int(x) if int(x) == x else x, s)))
OUTPUT: