Add tech_docs/python/type_casting.md
This commit is contained in:
99
tech_docs/python/type_casting.md
Normal file
99
tech_docs/python/type_casting.md
Normal file
@@ -0,0 +1,99 @@
|
|||||||
|
Certainly! I'd be happy to help you create a list of challenging Python type casting questions for a "stump the chump" game. This is a great way to test and improve Python knowledge. Let's start with a list of increasingly difficult questions. I'll provide the questions without answers, but I can explain any of them if you'd like.
|
||||||
|
|
||||||
|
1. What's the result of `int("3.14")`?
|
||||||
|
|
||||||
|
2. How would you convert the string "123" to a float?
|
||||||
|
|
||||||
|
3. What happens when you try to cast a complex number to an integer, like `int(3+4j)`?
|
||||||
|
|
||||||
|
4. What's the output of `bool("False")`?
|
||||||
|
|
||||||
|
5. How do you convert a list of strings to a list of integers in one line?
|
||||||
|
|
||||||
|
6. What's the result of `list(range(5))`?
|
||||||
|
|
||||||
|
7. How would you convert a set of tuples to a dictionary?
|
||||||
|
|
||||||
|
8. What happens when you try `float("inf")`?
|
||||||
|
|
||||||
|
9. How do you convert a binary string to an integer?
|
||||||
|
|
||||||
|
10. What's the output of `str(b"hello", "utf-8")`?
|
||||||
|
|
||||||
|
11. How would you convert a list of ASCII values to a string?
|
||||||
|
|
||||||
|
12. What's the result of `tuple({"a": 1, "b": 2}.items())`?
|
||||||
|
|
||||||
|
13. How do you convert a string of comma-separated values to a list of floats?
|
||||||
|
|
||||||
|
14. What happens when you try `int("1_000_000")`?
|
||||||
|
|
||||||
|
15. How would you convert a dictionary to a list of tuples, sorted by keys?
|
||||||
|
|
||||||
|
These questions cover various aspects of Python type casting, from basic conversions to more complex scenarios involving built-in functions and methods. Would you like me to explain any of these questions or add more to the list?
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
You're absolutely right. I apologize for not providing more context and explanations initially. Let's enhance this list with more valuable information, context, and explanations for each question:
|
||||||
|
|
||||||
|
1. Q: What's the result of `int("3.14")`?
|
||||||
|
A: This raises a ValueError.
|
||||||
|
Explanation: The `int()` function can't directly convert a string with a decimal point to an integer. It expects a string representation of a whole number. To convert this to an integer, you'd first need to convert it to a float and then to an integer: `int(float("3.14"))`.
|
||||||
|
|
||||||
|
2. Q: How would you convert the string "123" to a float?
|
||||||
|
A: Use `float("123")`. This returns 123.0.
|
||||||
|
Explanation: The `float()` function can convert strings representing both integers and floating-point numbers to float objects. Even though "123" doesn't have a decimal point, `float()` will add it, resulting in 123.0.
|
||||||
|
|
||||||
|
3. Q: What happens when you try to cast a complex number to an integer, like `int(3+4j)`?
|
||||||
|
A: This raises a TypeError.
|
||||||
|
Explanation: Complex numbers in Python consist of a real and an imaginary part. There's no standard way to convert this two-dimensional number to a one-dimensional integer, so Python doesn't allow this conversion. If you need the integer part, you could use `int((3+4j).real)`.
|
||||||
|
|
||||||
|
4. Q: What's the output of `bool("False")`?
|
||||||
|
A: True
|
||||||
|
Explanation: When converting strings to booleans, Python considers any non-empty string as True, regardless of its content. Only an empty string `""` would evaluate to False. This can be counterintuitive, especially with strings like "False" or "0".
|
||||||
|
|
||||||
|
5. Q: How do you convert a list of strings to a list of integers in one line?
|
||||||
|
A: Use a list comprehension: `[int(x) for x in string_list]`
|
||||||
|
Explanation: This creates a new list by applying the `int()` function to each element `x` in `string_list`. It's a concise way to perform the conversion, combining iteration and the `int()` function in a single expression.
|
||||||
|
|
||||||
|
6. Q: What's the result of `list(range(5))`?
|
||||||
|
A: [0, 1, 2, 3, 4]
|
||||||
|
Explanation: `range(5)` creates a sequence of numbers from 0 to 4. The `list()` function then converts this range object into a list. This is often used to create a list of consecutive integers.
|
||||||
|
|
||||||
|
7. Q: How would you convert a set of tuples to a dictionary?
|
||||||
|
A: Use the `dict()` function: `dict({('a', 1), ('b', 2)})`
|
||||||
|
Explanation: The `dict()` constructor can create a dictionary from a collection of key-value pairs. Each tuple in the set becomes a key-value pair in the resulting dictionary. This is useful for converting data between different collection types.
|
||||||
|
|
||||||
|
8. Q: What happens when you try `float("inf")`?
|
||||||
|
A: It returns float('inf'), which represents positive infinity.
|
||||||
|
Explanation: Python's float type includes special values for infinity. This is useful in mathematical operations or when you need to represent a value larger than any finite number. You can also use `float("-inf")` for negative infinity.
|
||||||
|
|
||||||
|
9. Q: How do you convert a binary string to an integer?
|
||||||
|
A: Use `int()` with base 2: `int('1010', 2)` returns 10.
|
||||||
|
Explanation: The `int()` function can take an optional second argument specifying the base of the number in the string. For binary (base 2), you use 2 as the second argument. This is handy for converting between different number representations.
|
||||||
|
|
||||||
|
10. Q: What's the output of `str(b"hello", "utf-8")`?
|
||||||
|
A: 'hello'
|
||||||
|
Explanation: This converts a bytes object to a string using UTF-8 encoding. The `str()` function, when given a bytes object and an encoding, decodes the bytes into a string. This is crucial when working with data from files or network sources that might be in bytes format.
|
||||||
|
|
||||||
|
11. Q: How would you convert a list of ASCII values to a string?
|
||||||
|
A: Use `chr()` in a list comprehension and join: `''.join([chr(x) for x in ascii_list])`
|
||||||
|
Explanation: This two-step process first converts each ASCII value to its corresponding character using `chr()`, then joins all characters into a single string. It's useful when working with data that represents text as numeric ASCII values.
|
||||||
|
|
||||||
|
12. Q: What's the result of `tuple({"a": 1, "b": 2}.items())`?
|
||||||
|
A: (('a', 1), ('b', 2)) or (('b', 2), ('a', 1)) (order may vary)
|
||||||
|
Explanation: The `items()` method returns a view of the dictionary's key-value pairs. Converting this to a tuple creates a tuple of tuples, each inner tuple being a key-value pair. The order isn't guaranteed unless you're using Python 3.7+ with a regular dict.
|
||||||
|
|
||||||
|
13. Q: How do you convert a string of comma-separated values to a list of floats?
|
||||||
|
A: `[float(x) for x in "1.5,2.3,3.7".split(',')]`
|
||||||
|
Explanation: This combines string splitting, a list comprehension, and float conversion. It first splits the string by commas, then converts each resulting substring to a float. This is commonly used when processing CSV-like data.
|
||||||
|
|
||||||
|
14. Q: What happens when you try `int("1_000_000")`?
|
||||||
|
A: It returns 1000000.
|
||||||
|
Explanation: Python 3.6+ allows underscores in numeric literals to improve readability of long numbers. The `int()` function is aware of this and ignores the underscores when converting the string to an integer. This feature helps in writing more readable code when dealing with large numbers.
|
||||||
|
|
||||||
|
15. Q: How would you convert a dictionary to a list of tuples, sorted by keys?
|
||||||
|
A: `sorted(my_dict.items())`
|
||||||
|
Explanation: The `items()` method returns a view of the dictionary's key-value pairs. The `sorted()` function then sorts these pairs based on the keys. This is useful when you need to process dictionary items in a specific order, as dictionaries themselves are unordered (prior to Python 3.7).
|
||||||
|
|
||||||
|
These explanations provide context on why each conversion works the way it does, potential use cases, and some of the underlying concepts in Python's type system. This kind of detailed understanding is crucial for writing robust, efficient Python code and for debugging complex type-related issues.
|
||||||
Reference in New Issue
Block a user