python(programming skill)
python(programming skill)
A **2D numeric array** is an array that stores values in a matrix form with rows
and columns. Each element of the array can be accessed using two indices: one for
the row and the other for the column.
```python
# Creating a 2D numeric array (3 rows and 2 columns)
array_2d = [
[1, 2],
[3, 4],
[5, 6]
]
# Accessing elements
print(array_2d[0][1]) # Output: 2 (element at row 0, column 1)
print(array_2d[2][0]) # Output: 5 (element at row 2, column 0)
```
To access an element, you provide two indices: the row index and the column index.
For example, `array_2d[0][1]` accesses the element at row 0, column 1, which is
`2`.
```python
# Creating a 2D character array (3 rows and 4 columns)
char_array_2d = [
['a', 'b', 'c', 'd'],
['e', 'f', 'g', 'h'],
['i', 'j', 'k', 'l']
]
# Accessing elements
print(char_array_2d[1][2]) # Output: 'g' (element at row 1, column 2)
print(char_array_2d[2][0]) # Output: 'i' (element at row 2, column 0)
```
To access an element, the process is the same as in the numeric array, where you
use the row and column indices to get the character value at that position.
Q2. Explain need of structure with example and write difference between structure
and union.
The need for a structure arises when you want to group together different types of
data (which are logically related) into a single unit, rather than managing them
individually. It helps in organizing complex data efficiently and makes the code
more readable and manageable.
Suppose we are designing a system to store information about students. Each student
has:
- Name (string)
- Age (integer)
- Grade (float)
```c
#include <stdio.h>
int main() {
// Declaring a structure variable
struct Student student1;
// Assigning values to structure members
strcpy(student1.name, "Alice");
student1.age = 20;
student1.grade = 88.5;
return 0;
}
```
| **Aspect** | **Structure**
| **Union** |
|------------------------|---------------------------------------------------------
---|-------------------------------------------------------------|
| **Memory allocation** | In a structure, memory is allocated for each member.
| In a union, memory is allocated for the largest member only. |
| **Memory usage** | The total memory size of a structure is the sum of the
memory required for all its members. | The memory size of a union is equal to the
size of its largest member. |
| **Accessing members** | All members can be accessed independently.
| Only one member can be accessed at a time. |
| **Data type** | Members can have different data types and hold
different values simultaneously. | All members share the same memory location and
hold one value at a time. |
| **Use case** | Used when you need to store multiple pieces of data
that are logically related and accessed at the same time. | Used when you need to
store different types of data in the same location but not simultaneously. |
| **Memory example** | If a structure has an integer, float, and char array,
memory is allocated for all three. | If a union has an integer, float, and char
array, memory is allocated for the largest data type among them. |
```c
#include <stdio.h>
int main() {
// Declaring a union variable
union Data data1;
return 0;
}
```
In the above union example, only one of the members can hold a value at any given
time, and each member shares the same memory space.
Structures are ideal when you need to store multiple attributes that will be used
together, while unions are more efficient when you only need to store one of
several possible types of data at a time, saving memory.
**Syntax**:
```c
return_type function_name() {
// Code to perform action
}
```
**Example**:
```c
#include <stdio.h>
int main() {
greet(); // Calling the function
return 0;
}
```
In this example:
- The `greet` function does not take any arguments nor return any value, but it
prints a greeting message.
**Syntax**:
```c
return_type function_name(type arg1, type arg2, ...) {
// Code using arguments
}
```
**Example**:
```c
#include <stdio.h>
int main() {
addNumbers(10, 20); // Calling the function with arguments
return 0;
}
```
In this example:
- The `addNumbers` function takes two arguments (integers), performs addition,
and prints the result. It does not return any value.
**Syntax**:
```c
return_type function_name() {
// Code to compute and return a value
}
```
**Example**:
```c
#include <stdio.h>
int main() {
int num = getNumber(); // Calling the function and storing the return value
printf("The number is: %d\n", num);
return 0;
}
```
In this example:
- The `getNumber` function does not take any arguments, but it returns the
integer value `42`.
**Syntax**:
```c
return_type function_name(type arg1, type arg2, ...) {
// Code to compute a value and return it
}
```
**Example**:
```c
#include <stdio.h>
int main() {
int result = multiply(5, 10); // Calling the function with arguments
printf("The result of multiplication is: %d\n", result);
return 0;
}
```
In this example:
- The `multiply` function accepts two integer arguments, multiplies them, and
returns the result. The return value is then printed.
### Conclusion:
- **User-Defined Functions (UDFs)** are powerful tools for making code more
modular, reusable, and organized. Functions can be categorized based on whether
they accept arguments and whether they return values, as shown in the examples
above.
ans. In Python, strings are sequences of characters, and there are various built-in
methods that allow you to manipulate and work with strings effectively. Here are
some commonly used **string methods** in Python, along with examples:
### 1. **`upper()`**
- Converts all characters of the string to uppercase.
**Syntax**:
```python
string.upper()
```
**Example**:
```python
text = "hello"
print(text.upper()) # Output: "HELLO"
```
### 2. **`lower()`**
- Converts all characters of the string to lowercase.
**Syntax**:
```python
string.lower()
```
**Example**:
```python
text = "HELLO"
print(text.lower()) # Output: "hello"
```
### 3. **`capitalize()`**
- Capitalizes the first character of the string and makes all other characters
lowercase.
**Syntax**:
```python
string.capitalize()
```
**Example**:
```python
text = "hello world"
print(text.capitalize()) # Output: "Hello world"
```
### 4. **`title()`**
- Converts the first character of each word to uppercase and the remaining
characters to lowercase.
**Syntax**:
```python
string.title()
```
**Example**:
```python
text = "hello world"
print(text.title()) # Output: "Hello World"
```
### 5. **`strip()`**
- Removes any leading (spaces at the beginning) and trailing (spaces at the end)
characters (by default, it removes spaces).
**Syntax**:
```python
string.strip()
```
**Example**:
```python
text = " hello "
print(text.strip()) # Output: "hello"
```
**Syntax**:
```python
string.replace(old, new)
```
**Example**:
```python
text = "I love programming"
print(text.replace("love", "enjoy")) # Output: "I enjoy programming"
```
### 7. **`split(delimiter)`**
- Splits the string into a list where each word is a list item. The `delimiter`
specifies where to split (by default, it splits by spaces).
**Syntax**:
```python
string.split(delimiter)
```
**Example**:
```python
text = "apple,banana,cherry"
print(text.split(',')) # Output: ['apple', 'banana', 'cherry']
```
### 8. **`join(iterable)`**
- Joins the elements of an iterable (such as a list) into a string, with the
string acting as a separator between the elements.
**Syntax**:
```python
string.join(iterable)
```
**Example**:
```python
words = ['apple', 'banana', 'cherry']
print(', '.join(words)) # Output: "apple, banana, cherry"
```
### 9. **`find(substring)`**
- Returns the lowest index where the substring is found in the string. If not
found, it returns `-1`.
**Syntax**:
```python
string.find(substring)
```
**Example**:
```python
text = "hello world"
print(text.find("world")) # Output: 6
print(text.find("python")) # Output: -1 (substring not found)
```
**Syntax**:
```python
string.startswith(prefix)
```
**Example**:
```python
text = "hello world"
print(text.startswith("hello")) # Output: True
print(text.startswith("world")) # Output: False
```
**Syntax**:
```python
string.endswith(suffix)
```
**Example**:
```python
text = "hello world"
print(text.endswith("world")) # Output: True
print(text.endswith("hello")) # Output: False
```
**Syntax**:
```python
string.isdigit()
```
**Example**:
```python
text = "12345"
print(text.isdigit()) # Output: True
text2 = "hello"
print(text2.isdigit()) # Output: False
```
**Syntax**:
```python
string.isspace()
```
**Example**:
```python
text = " "
print(text.isspace()) # Output: True
text2 = "hello"
print(text2.isspace()) # Output: False
```
**Syntax**:
```python
len(string)
```
**Example**:
```python
text = "hello"
print(len(text)) # Output: 5
```
### 15. **`isalpha()`**
- Returns `True` if all characters in the string are alphabetic (letters only),
otherwise returns `False`.
**Syntax**:
```python
string.isalpha()
```
**Example**:
```python
text = "hello"
print(text.isalpha()) # Output: True
text2 = "hello123"
print(text2.isalpha()) # Output: False
```
---
### Conclusion:
Python provides a rich set of string methods that make string manipulation easier
and more efficient. These methods help you modify, search, and analyze strings in
various ways, making it simpler to handle text data in your programs.
You can create a list by placing comma-separated values inside square brackets
`[]`.
**Example:**
```python
# Creating a list with mixed data types
my_list = [1, "apple", 3.14, True]
print(my_list)
```
**Output:**
```
[1, "apple", 3.14, True]
```
You can access individual elements of the list using **indexing**. Python uses
**zero-based indexing**, meaning the first element has index `0`, the second
element has index `1`, and so on.
**Example:**
```python
my_list = [1, "apple", 3.14, True]
print(my_list[1]) # Output: "apple"
print(my_list[2]) # Output: 3.14
```
You can also use **negative indexing** to access elements from the end of the list.
The last element has index `-1`, the second-last has index `-2`, etc.
**Example:**
```python
print(my_list[-1]) # Output: True (last element)
print(my_list[-2]) # Output: 3.14 (second-last element)
```
Here are some of the most commonly used **list methods** in Python:
---
### 1. **`append(item)`**
- Adds an item to the end of the list.
**Syntax**:
```python
list.append(item)
```
**Example**:
```python
my_list = [1, 2, 3]
my_list.append(4)
print(my_list) # Output: [1, 2, 3, 4]
```
---
### 2. **`extend(iterable)`**
- Extends the list by appending all elements from the provided iterable (another
list, tuple, etc.) to the end of the list.
**Syntax**:
```python
list.extend(iterable)
```
**Example**:
```python
my_list = [1, 2, 3]
my_list.extend([4, 5])
print(my_list) # Output: [1, 2, 3, 4, 5]
```
---
**Syntax**:
```python
list.insert(index, item)
```
**Example**:
```python
my_list = [1, 2, 3]
my_list.insert(1, "apple")
print(my_list) # Output: [1, "apple", 2, 3]
```
---
### 4. **`remove(item)`**
- Removes the first occurrence of the specified item from the list. If the item
is not found, it raises a `ValueError`.
**Syntax**:
```python
list.remove(item)
```
**Example**:
```python
my_list = [1, 2, 3, 2, 4]
my_list.remove(2)
print(my_list) # Output: [1, 3, 2, 4]
```
---
### 5. **`pop(index)`**
- Removes and returns the element at the specified index. If no index is
provided, it removes and returns the last element.
**Syntax**:
```python
list.pop(index)
```
**Example**:
```python
my_list = [1, 2, 3, 4]
popped_item = my_list.pop(1)
print(popped_item) # Output: 2
print(my_list) # Output: [1, 3, 4]
```
---
### 6. **`index(item)`**
- Returns the index of the first occurrence of the specified item in the list.
If the item is not found, it raises a `ValueError`.
**Syntax**:
```python
list.index(item)
```
**Example**:
```python
my_list = [1, 2, 3, 4]
print(my_list.index(3)) # Output: 2
```
---
### 7. **`count(item)`**
- Returns the number of times the specified item appears in the list.
**Syntax**:
```python
list.count(item)
```
**Example**:
```python
my_list = [1, 2, 2, 3, 2]
print(my_list.count(2)) # Output: 3
```
---
### 8. **`sort()`**
- Sorts the elements of the list in ascending order by default. You can also
sort in descending order by passing `reverse=True`.
**Syntax**:
```python
list.sort(reverse=False)
```
**Example**:
```python
my_list = [3, 1, 4, 2]
my_list.sort()
print(my_list) # Output: [1, 2, 3, 4]
```
**Descending Order**:
```python
my_list.sort(reverse=True)
print(my_list) # Output: [4, 3, 2, 1]
```
---
### 9. **`reverse()`**
- Reverses the elements of the list in place.
**Syntax**:
```python
list.reverse()
```
**Example**:
```python
my_list = [1, 2, 3, 4]
my_list.reverse()
print(my_list) # Output: [4, 3, 2, 1]
```
---
**Syntax**:
```python
list.clear()
```
**Example**:
```python
my_list = [1, 2, 3]
my_list.clear()
print(my_list) # Output: []
```
---
**Syntax**:
```python
list.copy()
```
**Example**:
```python
my_list = [1, 2, 3]
new_list = my_list.copy()
print(new_list) # Output: [1, 2, 3]
```
---
**Syntax**:
```python
list(iterable)
```
**Example**:
```python
my_tuple = (1, 2, 3)
new_list = list(my_tuple)
print(new_list) # Output: [1, 2, 3]
```
---
---
### Conclusion:
Lists in Python are a powerful and flexible data structure, supporting many methods
for adding, removing, searching, and modifying elements. Understanding these
methods allows you to efficiently work with lists in Python for a wide range of
applications.
**Example**:
```python
from collections import namedtuple
**Example**:
```python
from collections import deque
# Create a deque
d = deque([1, 2, 3])
**Example**:
```python
from collections import Counter
**Example**:
```python
from collections import OrderedDict
# Create an OrderedDict
od = OrderedDict([('apple', 2), ('banana', 3), ('cherry', 1)])
**Example**:
```python
from collections import defaultdict
d['apple'] += 1
d['banana'] += 2
---
### **Summary**
```python
import numpy as np
# Basic statistics
mean_value = np.mean(arr)
print("Mean of arr:", mean_value)
```
**Output:**
```
1D Array: [1 2 3 4]
2D Matrix:
[[1 2]
[3 4]
[5 6]]
Element-wise addition: [ 6 8 10 12]
Array multiplied by 2: [2 4 6 8]
Mean of arr: 2.5
```
---
### **Pandas**
```python
import pandas as pd
# Accessing a column
print("\nAccessing the 'Name' column:")
print(df['Name'])
# Basic operations
df['Age'] = df['Age'] + 1 # Incrementing age by 1
print("\nDataFrame after incrementing age by 1:")
print(df)
**Output:**
```
Pandas Series:
0 10
1 20
2 30
3 40
dtype: int64
Pandas DataFrame:
Name Age City
0 Alice 25 New York
1 Bob 30 Los Angeles
2 Charlie 35 Chicago
---
---
### **Conclusion:**
Both libraries are crucial in the data science ecosystem and are often used
together for various data processing and analysis tasks.