astype converts an array to another type. Model the conversions to int and to bool, and count what was lost.
What to build
A program that converts floats with astype(int) and astype(bool).
Requirements
- Print the values after
astype(int)(truncation toward zero), then afterastype(bool)(Falsefor 0,Trueotherwise), each line as Python prints a list. - Then print
changed by astype(int): K, the number of values whose integer differs from the original value.
Input
One line of numbers.
Output
Three lines.
Constraints
1 to 30 numbers; |x| ≤ 10^6.
Example
Input:
3.7 -1.2 0 5
Output:
[3, -1, 0, 5]
[True, True, False, True]
changed by astype(int): 2
Why it works
Converting to int keeps only the whole part toward zero, so every value with a fraction changes; converting to bool keeps only whether the value is zero.
Examples
Example 1 · Input
3.7 -1.2 0 5
Expected output
[3, -1, 0, 5] [True, True, False, True] changed by astype(int): 2
Example 2 · Input
2.9 -2.9
Expected output
[2, -2] [True, True] changed by astype(int): 2
Prompts inside input() are ignored when checking, so input("n: ") is fine.
Hints
Hint 1
int() in Python truncates toward zero, as astype(int) does.
Hint 2
Only 0 becomes False when converting to bool; -0.5 is True.
Solution
Show one correct solution (try it yourself first)
values = [float(x) for x in input().split()]
as_int = [int(v) for v in values]
as_bool = [v != 0 for v in values]
print(as_int)
print(as_bool)
print("changed by astype(int):", sum(1 for v, i in zip(values, as_int) if v != i))