Home
Problem
Status
Contest
Workbook
User
Group
Forum
Register
Login
{"managingGroups":{},"author":"FolkN","updateTime":1713251770000,"title":"day 1 notes datatypes, operators, conditions, loop, map ,input format","dislikeCnt":0,"content":"\n\n### 1. Python Data Types\nPython variables can store data of different types. The major types include:\n\n- **Integers (`int`)**: Whole numbers such as 1, -3, 42.\n- **Floating point (`float`)**: Numbers with a decimal point or in exponential form; e.g., 3.14, -0.001, 2e10.\n- **Strings (`str`)**: Sequence of Unicode characters; e.g., \"Hello\", \"1234\".\n- **Boolean (`bool`)**: Represents truth values; either `True` or `False`.\n- **Lists (`list`)**: Ordered and mutable collection of items; e.g., `[1, 2.5, \u0027Python\u0027]`.\n- **Tuples (`tuple`)**: Ordered and immutable collection of items; e.g., `(1, 2.5, \u0027Python\u0027)`.\n- **Sets (`set`)**: Unordered collection of unique items; e.g., `{1, 2, 3}`.\n- **Dictionaries (`dict`)**: Key-value pairs, unordered, mutable, and indexed by unique keys; e.g., `{\u0027name\u0027: \u0027Alice\u0027, \u0027age\u0027: 25}`.\n\n### 2. Input Types and Formatting\n\n- **Input Type**:\n - Use `input()` function to receive input from the user, which returns data as a string.\n - Convert input strings to appropriate types using `int()`, `float()`, or similar functions as needed.\n ```python\n age \u003d int(input(\"Enter your age: \"))\n salary \u003d float(input(\"Enter your salary: \"))\n ```\n\n- **String Formatting**:\n - **Old style** - using `%`:\n ```python\n name \u003d \"John\"\n \"Hello, %s!\" % name\n ```\n - **`str.format()` method**:\n ```python\n age \u003d 20\n \"He is {} years old\".format(age)\n ```\n - **Formatted String Literals (f-strings)** - Python 3.6+:\n ```python\n name \u003d \"John\"\n age \u003d 20\n f\"{name} is {age} years old\"\n ```\n\n### 3. Conditional Statements\nPython uses conditional statements to execute code based on one or more conditions.\n\n- **`if` statement**:\n ```python\n if condition:\n # code to execute if condition is True\n ```\n\n- **`if-else` statement**:\n ```python\n if condition:\n # code to execute if condition is True\n else:\n # code to execute if condition is False\n ```\n\n- **`if-elif-else` statement**:\n ```python\n if condition1:\n # execute if condition1 is True\n elif condition2:\n # execute if condition2 is True\n else:\n # execute if all above conditions are False\n ```\n\n- **Nested conditions**:\n ```python\n if condition1:\n if condition2:\n # execute if both condition1 and condition2 are True\n ```\n\n### 4. Loops\nPython provides two types of loops to iterate over data or execute repetitive tasks.\n\n- **`for` loop** - Iterates over a sequence (like a list, tuple, string, etc.) or other iterable objects:\n ```python\n for item in iterable:\n # execute code\n ```\n\n- **`while` loop** - Continues executing as long as a condition remains true:\n ```python\n while condition:\n # execute code\n ```\n\n- **Loop control statements**:\n - `break`: Exits the loop immediately.\n - `continue`: Skips the rest of the code inside the loop for the current iteration and moves to the next iteration.\n - `else`: Executes after the loop completes normally (did not end by a `break`).\n\n### Examples\n\nHere are a few examples combining these concepts:\n\n```python\n# Using conditional statements and loops together\nnumbers \u003d [1, 2, 3, 4, 5]\nfor num in numbers:\n if num % 2 \u003d\u003d 0:\n print(f\"{num} is even\")\n else:\n print(f\"{num} is odd\")\n\n# Using input and string formatting\nname \u003d input(\"What is your name? \")\nage \u003d int(input(\"How old are you? \"))\nprint(f\"Hello, {name}! Next year, you will be {age+1} years old.\")\n```\nThe `map()` function in Python is another fundamental concept often used for transforming and processing collections of data. It\u0027s particularly useful when you want to apply a single function to all the elements in an iterable (like a list or tuple) efficiently.\n\n### Map Function\n\n- **Purpose**: Applies a given function to each item of an iterable (list, tuple, etc.) and returns a map object (an iterator) of the results.\n- **Syntax**:\n ```python\n map(function, iterable, ...)\n ```\n- **Parameters**:\n - `function`: A function to which map passes each element from the given iterable(s).\n - `iterable`: An iterable like list, tuple, etc., whose items are processed by the function.\n\n- **Return Value**: Returns a map object (an iterator) which can be converted into other iterables like lists, tuples, etc.\n\n### Example Usage of `map()`\n\nLet\u0027s look at some examples to illustrate the use of `map()`:\n\n#### Example 1: Applying a Simple Function\nSuppose we have a list of numbers and we want to square each number:\n\n```python\ndef square(number):\n return number ** 2\n\nnumbers \u003d [1, 2, 3, 4, 5]\nsquared_numbers \u003d map(square, numbers)\nprint(list(squared_numbers)) # Output: [1, 4, 9, 16, 25]\n```\n\n#### Example 2: Using `map()` with a Lambda Function\n`map()` is often used with lambda functions to apply simple operations. Let\u0027s convert a list of numbers to strings:\n\n```python\nnumbers \u003d [1, 2, 3, 4, 5]\nstr_numbers \u003d map(lambda x: str(x), numbers)\nprint(list(str_numbers)) # Output: [\u00271\u0027, \u00272\u0027, \u00273\u0027, \u00274\u0027, \u00275\u0027]\n```\n\n#### Example 3: Multiple Iterables\n`map()` can also be used with more than one iterable. The iterables are passed to the function in parallel. With multiple iterables, the function must take as many arguments as there are iterables. Let\u0027s add elements from two lists:\n\n```python\ndef add(a, b):\n return a + b\n\nlist1 \u003d [1, 2, 3]\nlist2 \u003d [4, 5, 6]\nresult \u003d map(add, list1, list2)\nprint(list(result)) # Output: [5, 7, 9]\n```\n\n### Advantages of `map()`\n\n1. **Efficiency**: It’s generally more succinct and faster than manually iterating through the iterables and applying the function.\n2. **Convenience**: Especially with lambda functions, it allows for concise expression of transformations of data.\n3. **Memory Efficient**: Returns an iterator, which means that not all results need to be stored in memory at once.\n\n### Converting `map` Results\n\nSince `map()` returns an iterator, you often need to convert it to a list or other types to see the results or use them further:\n\n```python\nresult \u003d map(square, numbers)\nprint(list(result)) # Converts the result into a list\n```\n\nUnderstanding how to effectively use the `map()` function can significantly streamline data processing tasks, making code cleaner and often more efficient.\nWhen you need to take single-line input of integers and convert them into a list using the `map()` function in Python, you generally deal with input that contains multiple numbers separated by spaces. Here’s how you can do it in a compact and efficient way:\n\n### Reading and Processing a Single Line of Integer Inputs\n\nYou can use the `input()` function to get user input as a string, then split the string into components using `str.split()`, and finally convert each component to an integer using `map()`. Here\u0027s the standard approach condensed into a single line:\n\n```python\nnumbers \u003d list(map(int, input(\"Enter numbers separated by spaces: \").split()))\n```\n\nLet\u0027s break down each part of this line:\n\n1. **`input(\"Enter numbers separated by spaces: \")`**: This prompts the user to enter a line of text, which should be numbers separated by spaces.\n \n2. **`.split()`**: This method splits the string received from `input()` by any whitespace by default (spaces, in this case), resulting in a list of substrings. For example, `\"1 2 3\".split()` would result in `[\u00271\u0027, \u00272\u0027, \u00273\u0027]`.\n\n3. **`map(int, ...)`**: This applies the `int` function to each element in the list of strings. `map()` then returns an iterator that produces the integers.\n\n4. **`list(...)`**: Finally, the `list()` constructor is used to convert the iterator returned by `map()` into a list of integers.\n\n### Example Use in a Program\n\nHere’s a small example program that takes a line of integers as input, converts them into a list of integers, and then prints the list and the sum of its elements:\n\n```python\n# Prompt user for input and convert the input into a list of integers\nnumbers \u003d list(map(int, input(\"Enter numbers separated by spaces: \").split()))\n\n# Output the list of numbers\nprint(\"List of numbers:\", numbers)\n\n# Output the sum of the numbers\nprint(\"Sum of numbers:\", sum(numbers))\n```\n\n### Execution Example\n\nAssuming the user inputs `10 20 30 40`, the output would be:\n\n```\nEnter numbers separated by spaces: 10 20 30 40\nList of numbers: [10, 20, 30, 40]\nSum of numbers: 100\n```\n\nThis technique is particularly useful in competitive programming, data processing, and situations where quick and efficient input parsing is required. It neatly handles the conversion of input into usable data types in just a single line.","threadId":189815,"likeCnt":6,"createTime":1713251770000,"isWorkbook":false,"viewCnt":208,"openness":2,"fav":false,"id":4888,"trustable":false}