10/7/24, 10:46 AM Gu_lab.
ipynb - Colab
# Accept user input for name and age
name = input("Enter your name: ")
age = input("Enter your age: ")
# Display the output
print(f"Hello, {name}! You are {age} years old.")
Enter your name: Ranvijay
Enter your age: 23
Hello, Ranvijay! You are 23 years old.
# Define a function to calculate factorial
def factorial(n):
if n == 0 or n == 1:
return 1
else:
return n * factorial(n - 1)
# Call the function to calculate factorial of 10
result = factorial(10)
# Display the result
print(f"The factorial of 10 is: {result}")
The factorial of 10 is: 3628800
# Function to calculate total profit
def calculate_profit(cost_price, sales_price, units_sold):
return (sales_price - cost_price) * units_sold
# Request input from the user
cost_price = float(input("Enter the cost price of a single unit: "))
sales_price = float(input("Enter the sales price of a single unit: "))
units_sold = int(input("Enter the number of units sold: "))
# Calculate the profit
total_profit = calculate_profit(cost_price, sales_price, units_sold)
# Display the result
print(f"The total profit is: ${total_profit:.2f}")
Enter the cost price of a single unit: 450
Enter the sales price of a single unit: 475
Enter the number of units sold: 10
The total profit is: $250.00
# Function to compute income tax
def compute_income_tax(gross_income, num_dependents):
# Constants
tax_rate = 0.20
standard_deduction = 10000
dependent_deduction = 3000
# Calculate taxable income
taxable_income = gross_income - standard_deduction - (dependent_deduction * num_dependents)
# Ensure taxable income isn't negative
taxable_income = max(taxable_income, 0)
# Calculate income tax
income_tax = taxable_income * tax_rate
return income_tax
# Request input from the user
gross_income = float(input("Enter your gross income (to the nearest paisa): "))
num_dependents = int(input("Enter the number of dependents: "))
# Calculate the income tax
income_tax = compute_income_tax(gross_income, num_dependents)
# Display the result
print(f"Your income tax is: ₹{income_tax:.2f}")
Enter your gross income (to the nearest paisa): 3200000
Enter the number of dependents: 2
[Link] 1/7
10/7/24, 10:46 AM Gu_lab.ipynb - Colab
Your income tax is: ₹636800.00
# Function to calculate present value (PV)
def calculate_present_value(future_value, rate, years):
present_value = future_value / ((1 + rate) ** years)
return present_value
# Test case 1: future_value = 2000, rate = 0.035, years = 5
fv1 = 2000
rate1 = 0.035
years1 = 5
pv1 = calculate_present_value(fv1, rate1, years1)
print(f"Test Case 1 - Present Value: ₹{pv1:.2f}")
# Test case 2: future_value = 350, rate = 0.01, years = 10
fv2 = 350
rate2 = 0.01
years2 = 10
pv2 = calculate_present_value(fv2, rate2, years2)
print(f"Test Case 2 - Present Value: ₹{pv2:.2f}")
Test Case 1 - Present Value: ₹1683.95
Test Case 2 - Present Value: ₹316.85
# Function to convert Fahrenheit to Celsius
def fahrenheit_to_celsius(deg_fahrenheit=0):
deg_celsius = (deg_fahrenheit - 32) / (9.0 / 5.0)
return round(deg_celsius, 2)
# Test case 1: Fahrenheit = 20
fahrenheit1 = 20
celsius1 = fahrenheit_to_celsius(deg_fahrenheit=fahrenheit1)
print(f"Test Case 1 - {fahrenheit1}°F is {celsius1}°C")
# Test case 2: Fahrenheit = 100
fahrenheit2 = 100
celsius2 = fahrenheit_to_celsius(deg_fahrenheit=fahrenheit2)
print(f"Test Case 2 - {fahrenheit2}°F is {celsius2}°C")
Test Case 1 - 20°F is -6.67°C
Test Case 2 - 100°F is 37.78°C
# Function to display animal noises
def animal_call(animal='mouse'):
if animal == 'mouse':
print('squeak')
elif animal == 'cat':
print('meow')
elif animal == 'dog':
print('woof')
elif animal == 'cow':
print('moo')
else:
print('Sorry, I do not know what noise that animal makes.')
# Test cases
animal_call() # Default animal (mouse)
animal_call(animal='cat') # Test for cat
animal_call(animal='dog') # Test for dog
animal_call(animal='cow') # Test for cow
animal_call(animal='lion')# Test for unknown animal
squeak
meow
woof
moo
Sorry, I do not know what noise that animal makes.
# Function to check if a number is a multiple of 3, 5, or both
def fizz_buzz(number):
if number % 3 == 0 and number % 5 == 0:
return "FIZZBUZZ"
elif number % 3 == 0:
return "FIZZ"
elif number % 5 == 0:
return "BUZZ"
else:
[Link] 2/7
10/7/24, 10:46 AM Gu_lab.ipynb - Colab
return number
# Test cases
test_numbers = [1, 3, 5, 15, 23]
# Loop through test numbers and print results
for num in test_numbers:
result = fizz_buzz(num)
print(result)
1
FIZZ
BUZZ
FIZZBUZZ
23
# Function to find the maximum value in a list
def find_maximum(to_search):
if not to_search: # Check if the list is empty
return None # Return None if the list is empty
return max(to_search)
# Input list
to_search = [0, 1000, 2, 999, 5, 100, 54]
# Find and print the maximum value
max_value = find_maximum(to_search)
print(f"The maximum value in the list is: {max_value}")
The maximum value in the list is: 1000
import pandas as pd
# Function to handle missing data
def handle_missing_data(file_path):
# Step 1: Read the data file into a DataFrame
df = pd.read_csv(file_path)
# Step 2: Identify missing values in the whole DataFrame
print("Missing values in the DataFrame before cleaning:")
print([Link]().sum()) # Shows the count of missing values per column
# Step 3: Delete all rows with missing values
df_cleaned = [Link]()
# Step 4: Check for missing values after deleting rows
print("\nMissing values in the DataFrame after cleaning:")
print(df_cleaned.isnull().sum())
return df_cleaned
# Provide the path to your data file (replace 'your_file.csv' with your actual file path)
file_path = "D:\[Link]"
# Call the function and process the dataset
cleaned_df = handle_missing_data(file_path)
# Display the cleaned DataFrame
print("\nCleaned DataFrame:")
print(cleaned_df)
Missing values in the DataFrame before cleaning:
Code 0
Symbol 0
Name 0
dtype: int64
Missing values in the DataFrame after cleaning:
Code 0
Symbol 0
Name 0
dtype: int64
Cleaned DataFrame:
Code Symbol Name
0 AED إ.د United Arab Emirates d
1 AFN ؋ Afghan afghani
2 ALL L Albanian lek
3 AMD AMD Armenian dram
4 ANG ƒ Netherlands Antillean gu
[Link] 3/7
10/7/24, 10:46 AM Gu_lab.ipynb - Colab
.. ... ... ...
158 XOF CFA West African CFA franc
159 XPF Fr CFP franc
160 YER ﷼ Yemeni rial
161 ZAR R South African rand
162 ZMW ZK Zambian kwacha
[163 rows x 3 columns]
<>:22: SyntaxWarning: invalid escape sequence '\c'
<>:22: SyntaxWarning: invalid escape sequence '\c'
C:\Users\Ranvijay\AppData\Local\Temp\ipykernel_13864\[Link]: SyntaxWarning: invalid escape sequence '\c'
file_path = "D:\[Link]"
import pandas as pd
# Function to group data based on a given column and extract a specific group
def split_data_into_groups(file_path, group_column, group_value):
# Step 1: Read data into a DataFrame
df = pd.read_csv(file_path)
# Step 2: Group the data by the specified column
grouped_data = [Link](group_column)
# Step 3: Extract the desired group using get_group
try:
group = grouped_data.get_group(group_value)
print(f"Group for '{group_value}' in column '{group_column}':")
print(group)
except KeyError:
print(f"No group found for value '{group_value}' in column '{group_column}'")
return grouped_data
# Example usage
file_path = "D:\grouped_data.csv" # Replace with your actual file path
group_column = 'Category' # Column to group by (e.g., 'Category')
group_value = 'A' # Group to extract (e.g., value 'A')
# Call the function to split the data into groups and retrieve the desired group
grouped_data = split_data_into_groups(file_path, group_column, group_value)
Group for 'A' in column 'Category':
Category Item Quantity
0 A Item1 10
2 A Item3 8
<>:22: SyntaxWarning: invalid escape sequence '\g'
<>:22: SyntaxWarning: invalid escape sequence '\g'
C:\Users\Ranvijay\AppData\Local\Temp\ipykernel_13864\[Link]: SyntaxWarning: invalid escape sequence '\g'
file_path = "D:\grouped_data.csv" # Replace with your actual file path
import pandas as pd
# Function to compute basic statistics
def compute_statistics(file_path):
# Step 1: Read the dataset into a DataFrame
df = pd.read_csv(file_path)
# Step 2: Compute statistics
statistics = {
'Sum': [Link](numeric_only=True), # Sum of all numeric columns
'Min': [Link](numeric_only=True), # Minimum value of all numeric columns
'Max': [Link](numeric_only=True), # Maximum value of all numeric columns
'Mean': [Link](numeric_only=True), # Mean of all numeric columns
'Standard Deviation': [Link](numeric_only=True) # Standard deviation of all numeric columns
}
# Step 3: Output the results suitably labeled
for stat_name, stat_values in [Link]():
print(f"\n{stat_name} of the dataset:")
print(stat_values)
# Example usage
file_path = "D:\statistics_data.csv" # Replace with your actual file path
compute_statistics(file_path)
Sum of the dataset:
Quantity 37
dtype: int64
Min of the dataset:
[Link] 4/7
10/7/24, 10:46 AM Gu_lab.ipynb - Colab
Quantity 2
dtype: int64
Max of the dataset:
Quantity 12
dtype: int64
Mean of the dataset:
Quantity 7.4
dtype: float64
Standard Deviation of the dataset:
Quantity 3.974921
dtype: float64
<>:23: SyntaxWarning: invalid escape sequence '\s'
<>:23: SyntaxWarning: invalid escape sequence '\s'
C:\Users\Ranvijay\AppData\Local\Temp\ipykernel_13864\[Link]: SyntaxWarning: invalid escape sequence '\s'
file_path = "D:\statistics_data.csv" # Replace with your actual file path
import pandas as pd
import [Link] as plt
# Function to visualize data using scatter plot and bar plot
def data_visualization(file_path, x_col, y_col):
# Step 1: Read the dataset into a DataFrame
df = pd.read_csv(file_path)
# Step 2: Plot a scatter plot using two columns
[Link](figsize=(10, 5))
# Scatter plot
[Link](1, 2, 1) # Create a subplot (1 row, 2 columns, 1st plot)
[Link](df[x_col], df[y_col], color='blue', marker='o')
[Link](f'Scatter Plot of {x_col} vs {y_col}')
[Link](x_col)
[Link](y_col)
# Step 3: Plot a bar plot using the second column's values
[Link](1, 2, 2) # 2nd plot in the same figure
[Link](df[x_col], df[y_col], color='green')
[Link](f'Bar Plot of {x_col} vs {y_col}')
[Link](x_col)
[Link](y_col)
# Show the plots
plt.tight_layout()
[Link]()
# Example usage
file_path = "D:\statistics_data (1).csv" # Replace with your actual file path or use the provided CSV
x_col = 'Item' # Column for X-axis (replace with your column name)
y_col = 'Quantity' # Column for Y-axis (replace with your column name)
# Call the function to plot the scatter plot and bar plot
data_visualization(file_path, x_col, y_col)
[Link] 5/7
10/7/24, 10:46 AM Gu_lab.ipynb - Colab
<>:31: SyntaxWarning: invalid escape sequence '\s'
<>:31: SyntaxWarning: invalid escape sequence '\s'
C:\Users\Ranvijay\AppData\Local\Temp\ipykernel_13864\[Link]: SyntaxWarning: invalid escape sequence '\s'
file_path = "D:\statistics_data (1).csv" # Replace with your actual file path or use the provided CSV
import pandas as pd
import numpy as np
import [Link] as sm
import [Link] as plt
# Sample data creation (you can replace this with your own dataset)
data = {
'X': [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
'Y': [2.3, 2.9, 3.7, 4.5, 5.1, 5.8, 6.9, 7.1, 8.2, 9.0]
}
df = [Link](data)
# Define variables
X = df['X'] # independent variable
Y = df['Y'] # dependent variable
# Add constant term for intercept
X = sm.add_constant(X)
# Perform linear regression
model = [Link](Y, X).fit()
# Print the summary of the regression
print([Link]())
# Predict values
predictions = [Link](X)
# Plotting the results
[Link](df['X'], df['Y'], color='blue', label='Data Points')
[Link](df['X'], predictions, color='red', label='Regression Line')
[Link]('Linear Regression Example')
[Link]('Independent Variable (X)')
[Link]('Dependent Variable (Y)')
[Link]()
[Link]()
[Link] 6/7
10/7/24, 10:46 AM Gu_lab.ipynb - Colab
OLS Regression Results
==============================================================================
Dep. Variable: Y R-squared: 0.996
Model: OLS Adj. R-squared: 0.995
Method: Least Squares F-statistic: 1814.
Date: Sun, 22 Sep 2024 Prob (F-statistic): 1.02e-10
Time: [Link] Log-Likelihood: 5.3738
No. Observations: 10 AIC: -6.748
Df Residuals: 8 BIC: -6.142
Df Model: 1
Covariance Type: nonrobust
==============================================================================
coef std err t P>|t| [0.025 0.975]
------------------------------------------------------------------------------
const 1.4733 0.108 13.645 0.000 1.224 1.722
X 0.7412 0.017 42.592 0.000 0.701 0.781
==============================================================================
Omnibus: 1.634 Durbin-Watson: 3.013
Prob(Omnibus): 0.442 Jarque-Bera (JB): 0.422
Skew: -0.503 Prob(JB): 0.810
Kurtosis: 3.044 Cond. No. 13.7
==============================================================================
Notes:
[1] Standard Errors assume that the covariance matrix of the errors is correctly specified.
C:\Users\Ranvijay\anaconda3\Lib\site-packages\scipy\stats\_axis_nan_policy.py:531: UserWarning: kurtosistest only valid for n>=20 .
res = hypotest_fun_out(*samples, **kwds)
from [Link] import linprog
# Coefficients for the objective function (minimize total cost)
c = [500, 600] # Cost for X and Y
# Coefficients for the inequality constraints (Ax <= b)
A = [
[-1/4, -1/2], # For Product A
[-1/4, -1/10], # For Product B
[-1/12, -1/12] # For Product C
]
b = [-4, -2, -1] # Right-hand side of the inequalities
# Bounds for x and y (non-negativity)
x_bounds = (0, None) # x >= 0
y_bounds = (0, None) # y >= 0
# Solve the linear programming problem
result = linprog(c, A_ub=A, b_ub=b, bounds=[x_bounds, y_bounds], method='highs')
# Check if the solution was found
if [Link]:
print("Optimal solution found:")
print(f"Kilograms of raw material X to use: {result.x[0]:.2f} kg")
print(f"Kilograms of raw material Y to use: {result.x[1]:.2f} kg")
print(f"Minimum total cost: {[Link]:.2f} rupees")
else:
print("No optimal solution found.")
[Link] 7/7