Wednesday 22 May 2024

Python Coding challenge - Day 212 | What is the output of the following Python Code?

 

let's break down and explain each part of this code:

my_dict = {1: 0, 0: [], True: False}

result = all(my_dict)

print(result)

Step-by-Step Explanation

Dictionary Creation:

my_dict = {1: 0, 0: [], True: False}

This line creates a dictionary my_dict with the following key-value pairs:

1: 0 - The key is 1 and the value is 0.

0: [] - The key is 0 (or (0) in another form) and the value is an empty list [].

True: False - The key is True and the value is False.

Note that in Python dictionaries, keys must be unique. If you try to define multiple key-value pairs with the same key, the last assignment will overwrite any previous ones. However, in this dictionary, the keys are unique even though 1 and True can be considered equivalent (True is essentially 1 in a boolean context).

Using the all Function:

result = all(my_dict)

The all function in Python checks if all elements in an iterable are True. When all is applied to a dictionary, it checks the truthiness of the dictionary's keys (not the values).

In this dictionary, the keys are 1, 0, and True.

The truthiness of the keys is evaluated as follows:

1 is True.

0 is False.

True is True.

Since one of the keys (0) is False, the all function will return False.

Printing the Result:

print(result)

This line prints the result of the all function. Given that the dictionary contains a False key (0), the output will be False.

Summary

Putting it all together, the code creates a dictionary and uses the all function to check if all the keys are true. Since one of the keys is 0 (which is False), the all function returns False, which is then printed.

So, when you run this code, the output will be:

False

Tuesday 21 May 2024

Pdf To Audio using Python

 


# Importing necessary libraries

import PyPDF2

import pyttsx3

# Prompt user for the PDF file name

pdf_filename = input("Enter the PDF file name (including extension): ").strip()

# Open the PDF file

try:

    with open(pdf_filename, 'rb') as pdf_file:

        # Create a PdfFileReader object

        pdf_reader = PyPDF2.PdfReader(pdf_file)

        

        # Get an engine instance for the speech synthesis

        speak = pyttsx3.init()        

        # Iterate through each page and read the text

        for page_num in range(len(pdf_reader.pages)):

            page = pdf_reader.pages[page_num]

            text = page.extract_text()

            if text:

                speak.say(text)

                speak.runAndWait()       

        # Stop the speech engine

        speak.stop()      

        print("Audiobook creation completed.")

except FileNotFoundError:

    print("The specified file was not found.")

except Exception as e:

    print(f"An error occurred: {e}")

#clcoding.com


Explanation:

This script segment accomplishes several tasks:

Importing Necessary Libraries:

PyPDF2: This library is used to work with PDF files, allowing us to read the content of PDF documents.
pyttsx3: This library is used for text-to-speech conversion, enabling us to convert the text extracted from the PDF into spoken words.
Prompting User for PDF File Name:

The input() function is used to prompt the user to enter the name of the PDF file, including its extension (e.g., example.pdf).
The entered file name is stored in the variable pdf_filename.
Opening the PDF File:

The open() function is used to open the PDF file specified by the user. The file is opened in binary read mode ('rb').
This operation is wrapped in a try block to handle possible exceptions, such as the file not being found (FileNotFoundError) or other unexpected errors (Exception).
Reading PDF Content and Converting to Speech:

If the PDF file is successfully opened, a PdfReader object named pdf_reader is created using PyPDF2. This object is used to read the content of the PDF document.
An instance of the text-to-speech engine (speak) is initialized using pyttsx3.init().
The script iterates through each page of the PDF using a for loop and the range(len(pdf_reader.pages)) construct. For each page:
The text content is extracted from the page using page.extract_text().
If the extracted text is not empty, it is passed to the text-to-speech engine to be spoken aloud using speak.say(text) and speak.runAndWait().
After processing all pages, the text-to-speech engine is stopped using speak.stop().
Error Handling:

If the specified PDF file is not found (FileNotFoundError), the script prints a message indicating that the file was not found.
If any other unexpected error occurs during the execution of the script (Exception), the error message is printed.
Completion Message:

If the script executes successfully without encountering any errors, a message indicating the completion of audiobook creation is printed.
Overall, this script segment enables the user to specify a PDF file, reads its content, converts the text to speech, and creates an audiobook from the PDF content.

Python Coding challenge - Day 211 | What is the output of the following Python Code?

 

Code:

explain c = '13\t14' 

print(c.index('\t'))

Solution and Explanation:

Let's break down the code c = '13\t14' and print(c.index('\t')) to understand what it does:

c = '13\t14'

Here, we are assigning a string to the variable c.

The string '13\t14' contains the characters 1, 3, a tab character (\t), 1, and 4.

The \t is an escape sequence that represents a tab character.

print(c.index('\t'))

The index method is called on the string c.

c.index('\t') searches the string c for the first occurrence of the tab character (\t).

The index method returns the index (position) of the first occurrence of the specified value.

If the specified value is not found, it raises a ValueError.

Let's put it all together:

The string c is '13\t14'. Visually, it can be represented as:

13<TAB>14

where <TAB> is a single tab character.

When we call c.index('\t'), we are looking for the index of the tab character in the string c.

In the string '13\t14', the tab character is located at index 2 (considering zero-based indexing):

'1' is at index 0

'3' is at index 1

'\t' (tab) is at index 2

'1' is at index 3

'4' is at index 4

Therefore, the statement print(c.index('\t')) will output 2 because the tab character is found at index 2 in the string c.


Monday 20 May 2024

Box and Whisker plot using Python Libraries

Step 1: Install Necessary Libraries

First, make sure you have matplotlib and seaborn installed. You can install them using pip:

pip install matplotlib seaborn

#clcoding.com

Step 2: Import Libraries

Next, import the necessary libraries in your Python script or notebook.

import matplotlib.pyplot as plt
import seaborn as sns
import numpy as np

Step 3: Create Sample Data

Create some sample data to plot. This can be any dataset you have, but for demonstration purposes, we will create a simple dataset using NumPy.

# Generate sample data
np.random.seed(10)
data = [np.random.normal(0, std, 100) for std in range(1, 5)]

Step 4: Create the Box and Whisker Plot

Using matplotlib and seaborn, you can create a basic Box and Whisker plot.

# Create a boxplot
plt.figure(figsize=(10, 6))
plt.boxplot(data, patch_artist=True)

# Add title and labels
plt.title('Box and Whisker Plot')
plt.xlabel('Category')
plt.ylabel('Values')

# Show plot
plt.show()

Step 5: Enhance the Plot with Seaborn

For more advanced styling, you can use seaborn, which provides more aesthetic options.

# Set the style of the visualization

sns.set(style="whitegrid")

# Create a boxplot with seaborn

plt.figure(figsize=(10, 6))

sns.boxplot(data=data)

# Add title and labels

plt.title('Box and Whisker Plot')

plt.xlabel('Category')

plt.ylabel('Values')

# Show plot

plt.show()

Python Coding challenge - Day 210 | What is the output of the following Python Code?

 



Code:

lst = ['P', 20, 'Q', 4.50]

item = iter(lst)

print(next(item))

Solution and Explanation: 

 Let's break down the code and explain each part in detail:

lst = ['P', 20, 'Q', 4.50]
item = iter(lst)
print(next(item))

Explanation

Creating the List:

lst = ['P', 20, 'Q', 4.50]
This line defines a list named lst with four elements:
A string 'P'
An integer 20
Another string 'Q'
A float 4.50

Creating an Iterator:

item = iter(lst)
The iter() function is called with the list lst as an argument.
This converts the list into an iterator object. An iterator is an object that allows you to traverse through all the elements of a collection (in this case, the list lst).
The iterator item is now ready to iterate over the elements of the list one by one.

Accessing the First Element Using next():

print(next(item))
The next() function is called on the iterator item.
The next() function retrieves the next element from the iterator. Since this is the first call to next(item), it returns the first element of the list lst, which is 'P'.
After retrieving the element, the iterator advances to the next element in the list.
The print() function then prints this retrieved element ('P') to the console.

Output

When you run the code, the output will be: P

This is because 'P' is the first element in the list lst. The next(item) function call retrieves and returns this first element, which is then printed by the print() function.


Sunday 19 May 2024

Python List Comprehensions

List comprehensions in Python provide a powerful and concise way to create lists. They are an essential part of any Python programmer's toolkit. Ready to make your code more Pythonic? Let's dive in!

What is a List Comprehension?

A list comprehension is a compact way to process all or part of the elements in a sequence and return a list with the results. The syntax is simple yet powerful:

[expression for item in iterable if condition]

Basic Example

Let's start with a basic example. Suppose we want a list of squares for numbers from 0 to 9. With list comprehensions, it's a one-liner:

squares = [x**2 for x in range(10)]

print(squares)

Output:

[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

Adding a Condition

What if we want only even squares? Just add an if condition at the end:

even_squares = [x**2 for x in range(10) if x % 2 == 0]

print(even_squares)

Output:

[0, 4, 16, 36, 64]

Nested Comprehensions

You can also nest comprehensions for multidimensional lists. Here’s an example to flatten a 2D list:

matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

flattened = [num for row in matrix for num in row]

print(flattened)

Output:

[1, 2, 3, 4, 5, 6, 7, 8, 9]

Dictionary Comprehensions

List comprehensions aren’t just for lists. You can create dictionaries too!

squares_dict = {x: x**2 for x in range(10)}

print(squares_dict)

Output:

{0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64, 9: 81}

Set Comprehensions

And even sets! This creates a set of unique squares:

unique_squares = {x**2 for x in range(10)}

print(unique_squares)

Output:

{0, 1, 4, 9, 16, 25, 36, 49, 64, 81}

Advanced Use - Function Application

You can apply functions within comprehensions. Here’s an example using str.upper():

words = ["hello", "world", "python"]

upper_words = [word.upper() for word in words]

print(upper_words)

Output:

['HELLO', 'WORLD', 'PYTHON']

Comprehensions with Multiple Conditions

You can add multiple conditions. Let’s filter numbers divisible by 2 and 3:

filtered = [x for x in range(20) if x % 2 == 0 if x % 3 == 0]

print(filtered)

Output:

[0, 6, 12, 18]

In Conclusion

List comprehensions make your code cleaner and more readable. They’re efficient and Pythonic. Practice and integrate them into your projects to see the magic!

Introduction to Modern Statistics free pdf

 

Introduction to Modern Statistics is a re-imagining of a previous title, Introduction to Statistics with Randomization and Simulation. The new book puts a heavy emphasis on exploratory data analysis (specifically exploring multivariate relationships using visualization, summarization, and descriptive models) and provides a thorough discussion of simulation-based inference using randomization and bootstrapping, followed by a presentation of the related Central Limit Theorem based approaches. Other highlights include:

Web native book. The online book is available in HTML, which offers easy navigation and searchability in the browser. The book is built with the bookdown package and the source code to reproduce the book can be found on GitHub. Along with the bookdown site, this book is also available as a PDF and in paperback.

Tutorials. While the main text of the book is agnostic to statistical software and computing language, each part features 4-8 interactive R tutorials (for a total of 32 tutorials) that walk you through the implementation of the part content in R with the tidyverse for data wrangling and visualisation and the tidyverse-friendly infer package for inference. The self-paced and interactive R tutorials were developed using the learnr R package, and only an internet browser is needed to complete them.

Labs. Each part also features 1-2 R based labs. The labs consist of data analysis case studies and they also make heavy use of the tidyverse and infer packages.

Datasets. Datasets used in the book are marked with a link to where you can find the raw data. The majority of these point to the openintro package. You can install the openintro package from CRAN or get the development version on GitHub.

Hard Copy: Introduction to Modern Statistics

Free PDF: Introduction to Modern Statistics




Python Coding challenge - Day 209 | What is the output of the following Python Code?

 

Code:

h = [5, 6, 7, 8]

h.pop()

h.pop(0)

print(h)

Solution and Explanation: 

Let's break down the given Python code and explain what each line does:

h = [5, 6, 7, 8]

This line creates a list h with the elements 5, 6, 7, and 8.

h = [5, 6, 7, 8]
h.pop()

The pop() method removes and returns the last item from the list. Since no argument is provided, it removes the last element, which is 8.

Before h.pop():

h = [5, 6, 7, 8]
After h.pop():

h = [5, 6, 7]
h.pop(0)

The pop(0) method removes and returns the item at index 0 from the list. This means it removes the first element, which is 5.

Before h.pop(0):

h = [5, 6, 7]
After h.pop(0):

h = [6, 7]
print(h)

This line prints the current state of the list h to the console.

print(h)
The output will be:

[6, 7]
Summary
Initially, the list h is [5, 6, 7, 8].
The first h.pop() removes the last element, resulting in [5, 6, 7].
The second h.pop(0) removes the first element, resulting in [6, 7].
Finally, print(h) outputs [6, 7].
So the final state of the list h after these operations is [6, 7].

Common Python Errors and How to Fix Them

 

ZeroDivisionError: division by zero

This happens when you try to divide a number by zero. Always check the divisor before dividing.

# Correct way

result = 10 / 2

# Incorrect way

result = 10 / 0  # ZeroDivisionError

#clcoding.com 

IndentationError: unexpected indent

Python uses indentation to define code blocks. This error occurs when there’s a misalignment in the indentation.

# Correct way

if True:

    print("Hello")

# Incorrect way

if True:

  print("Hello")  # IndentationError

#clcoding.com 

ImportError: No module named 'module'

This error means Python can’t find the module you’re trying to import. Check if the module is installed and the name is correct.

# Install the module first
# pip install requests

import requests  # Correct way

import non_existent_module  # ImportError

#clcoding.com 

ValueError: invalid literal for int() with base 10: 'text'

This occurs when you try to convert a string that doesn’t represent a number to an integer. Ensure the string is numeric.

# Correct way
number = int("123")

# Incorrect way
number = int("abc")  # ValueError

#clcoding.com 

AttributeError: 'object' has no attribute 'attribute'

This happens when you try to use an attribute or method that doesn’t exist for an object. Ensure you are calling the correct method or attribute.

class MyClass:
    def __init__(self):
        self.value = 10

obj = MyClass()

# Correct way
print(obj.value)

# Incorrect way
print(obj.price)  # AttributeError

#clcoding.com 

KeyError: 'key'

This error occurs when you try to access a dictionary key that doesn’t exist. Use .get() method or check if the key exists.

my_dict = {"name": "Alice"}

# Correct way
print(my_dict.get("age", "Not Found"))

# Incorrect way
print(my_dict["age"])  # KeyError

#clcoding.com 

IndexError: list index out of range

This occurs when you try to access an index that doesn't exist in a list. Always check the list length before accessing an index.

my_list = [1, 2, 3]

# Correct way
print(my_list[2])  # Prints 3

# Incorrect way
print(my_list[5])  # IndexError

#clcoding.com 

TypeError: unsupported operand type(s)

This happens when you perform an operation on incompatible types. Check the data types of your variables.

# Correct way
result = 5 + 3

# Incorrect way
result = 5 + "3"  # Can't add integer and string

#clcoding.com 

NameError: name 'variable' is not defined

This occurs when you try to use a variable or function before it's declared. Ensure that all variables and functions are defined before use.

# Correct way
name = "Alice"
print(name)

# Incorrect way
print(name)
name = "Alice"

#clcoding.com 

SyntaxError: invalid syntax

This usually means there's a typo or a mistake in the code structure. Check for missing colons, parentheses, or indentation errors. Example:

print("Hello World")
# Missing parenthesis can cause SyntaxError
print "Hello World"

#clcoding.com 

Friday 17 May 2024

Python Coding challenge - Day 208 | What is the output of the following Python Code?

 

Code:

g = [1, 2, 3]

h = [1, 2, 3]

print(g is h)  

print(g == h) 

Solution and Explanation:

In Python, the expressions g = [1, 2, 3] and h = [1, 2, 3] create two separate list objects that contain the same elements. When we use print(g is h) and print(g == h), we are comparing these two lists in different ways.

g is h
The is operator checks for object identity. It returns True if both operands refer to the exact same object in memory.

g = [1, 2, 3]
h = [1, 2, 3]
print(g is h)
In this case, g and h are two different objects that happen to have the same contents. Since they are distinct objects, g is h will return False.

g == h
The == operator checks for value equality. It returns True if the operands have the same value, which for lists means that they have the same elements in the same order.

g = [1, 2, 3]
h = [1, 2, 3]
print(g == h)
Here, g and h have the same elements in the same order, so g == h will return True.

Summary
g is h: Checks if g and h are the same object in memory (identity). Result: False.
g == h: Checks if g and h have the same contents (equality). Result: True.
Thus, the output will be:

False
True

Python Coding challenge - Day 207 | What is the output of the following Python Code?

 

Code:

str_a = "hello"

str_b = "hello"

print(str_a is str_b)

print(str_a == str_b)

Solution and Explanation:  

In Python, the statements str_a = "hello" and str_b = "hello" both create string objects that contain the same sequence of characters. Let's break down what happens when you use the is and == operators to compare these two strings.

is Operator
The is operator checks for object identity. It returns True if both operands refer to the same object in memory.

== Operator
The == operator checks for value equality. It returns True if the values of the operands are equal, regardless of whether they are the same object in memory.

Now, let's analyze the code:

str_a = "hello"
str_b = "hello"
print(str_a is str_b)  # This checks if str_a and str_b are the same object
print(str_a == str_b)  # This checks if the values of str_a and str_b are equal
str_a is str_b
In Python, small strings and some other immutable objects are sometimes interned for efficiency. String interning means that identical strings may refer to the same object in memory. Because "hello" is a short, commonly used string, Python often interns it. As a result, str_a and str_b will likely refer to the same interned string object. Therefore, str_a is str_b will typically return True because they are the same object in memory.

str_a == str_b
The == operator compares the values of str_a and str_b. Since both strings contain the same sequence of characters "hello", str_a == str_b will return True regardless of whether they are the same object in memory.

Summary
str_a is str_b checks if str_a and str_b refer to the exact same object. In this case, it will likely be True due to string interning.
str_a == str_b checks if str_a and str_b have the same value. This will be True because both strings contain "hello".
So, the output of the code will be:

True
True
This illustrates both object identity and value equality for these string variables in Python.






Thursday 16 May 2024

Interesting facts about Dictionaries

 Dictionary Methods

Dictionaries come with several handy methods such as setdefault, update, pop, popitem, and clear.

my_dict = {'name': 'Alice', 'age': 25}

# setdefault
my_dict.setdefault('city', 'Unknown')
print(my_dict)  

# update
my_dict.update({'age': 26, 'city': 'New York'})
print(my_dict)  

# pop
age = my_dict.pop('age')
print(age)  # Output: 26
print(my_dict)  

# popitem
item = my_dict.popitem()
print(item) 
print(my_dict)  

# clear
my_dict.clear()
print(my_dict)  

#clcoding.com
{'name': 'Alice', 'age': 25, 'city': 'Unknown'}
{'name': 'Alice', 'age': 26, 'city': 'New York'}
26
{'name': 'Alice', 'city': 'New York'}
('city', 'New York')
{'name': 'Alice'}
{}

Ordered Dictionaries

As of Python 3.7, dictionaries maintain insertion order by default. The OrderedDict from the collections module was used for this purpose in earlier versions.

my_dict = {'first': 1, 'second': 2, 'third': 3}
print(my_dict)  

#clcoding.com
{'first': 1, 'second': 2, 'third': 3}

Merging Dictionaries

Starting with Python 3.9, you can use the | operator to merge dictionaries.

dict1 = {'a': 1, 'b': 2}
dict2 = {'b': 3, 'c': 4}
merged_dict = dict1 | dict2
print(merged_dict)  

#clcoding.com
{'a': 1, 'b': 3, 'c': 4}
Dictionary Views
The keys, values, and items methods return dictionary view objects, which are dynamic and reflect changes in the dictionary.

my_dict = {'name': 'Alice', 'age': 25}
keys_view = my_dict.keys()
print(keys_view)  
my_dict['city'] = 'New York'
print(keys_view) 

#clcoding.com
dict_keys(['name', 'age'])
dict_keys(['name', 'age', 'city'])

Default Values with get and defaultdict

Using the get method, you can provide a default value if the key is not found.

my_dict = {'name': 'Alice'}
print(my_dict.get('age', 'Not Found'))  
Not Found
With defaultdict from the collections module, you can provide default values for missing keys.

from collections import defaultdict

dd = defaultdict(int)
dd['a'] += 1
print(dd)  

#clcoding.com
defaultdict(<class 'int'>, {'a': 1})


Dictionary Comprehensions

Just like list comprehensions, you can create dictionaries using dictionary comprehensions.

squares = {x: x*x for x in range(6)}
print(squares)  

#clcoding.com
{0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25}

Iterating Through Dictionaries

You can iterate through keys, values, or key-value pairs in a dictionary.

my_dict = {'name': 'Alice', 'age': 25}
for key in my_dict:
    print(key)  

for value in my_dict.values():
    print(value)  

for key, value in my_dict.items():
    print(key, value)  

#clcoding.com
name
age
Alice
25
name Alice
age 25

Keys Must Be Immutable and Unique

The keys in a dictionary must be immutable types (like strings, numbers, or tuples) and must be unique.

my_dict = {(1, 2): 'tuple key', 'name': 'Alice', 3.14: 'pi'}
print(my_dict)  

#clcoding.com
{(1, 2): 'tuple key', 'name': 'Alice', 3.14: 'pi'}

Efficient Lookup Time

Dictionaries have average O(1) time complexity for lookups, insertions, and deletions due to their underlying hash table implementation.

my_dict = {'a': 1, 'b': 2, 'c': 3}
print(my_dict['b'])  

#clcoding.com
2


Dynamic and Mutable

Dictionaries are mutable, which means you can change their content without changing their identity.

my_dict = {'name': 'Alice', 'age': 25}
my_dict['age'] = 26
my_dict['city'] = 'New York'
print(my_dict)  

#clcoding.com
{'name': 'Alice', 'age': 26, 'city': 'New York'}

Python Coding challenge - Day 206 | What is the output of the following Python Code?

 

Code:

dict_a = {"a": 1, "b": 2}

dict_b = {"a": 1, "b": 2}

print(dict_a is dict_b)

print(dict_a == dict_b)

Solution and Explanation: 

This code creates two dictionaries, dict_a and dict_b, with identical key-value pairs. Then it prints the results of two different comparisons:

print(dict_a is dict_b): This checks whether dict_a and dict_b refer to the same object in memory. In this case, they are two separate dictionary objects, so the output will be False.

print(dict_a == dict_b): This checks whether the contents of dict_a and dict_b are the same. Since they have the same key-value pairs, the output will be True.

Tuesday 14 May 2024

Python Coding challenge - Day 205 | What is the output of the following Python Code?

 

Code: 

num = [5, 6]

*midd, lst = num, num[-1]  

print(midd, lst)

Solution and Explanation: 

Let's break down the code step by step:

num = [5, 6]: This line creates a list called num containing two integers, 5 and 6.

*midd, lst = num, num[-1]: Here, we're using extended iterable unpacking. Let's dissect this line:

*midd: The * operator is used to gather any remaining items in the iterable (in this case, the list num) into a list. So, midd will contain all elements of num except the last one.

, lst: This part assigns the last item of the num list to the variable lst. In this case, it's assigning 6 to lst.

Therefore, after this line executes, midd will be [5] and lst will be 6.

print(midd, lst): This line prints the variables midd and lst. So, it will output [5] 6.

So, overall, the code snippet initializes a list num with two elements [5, 6], then it unpacks this list into two variables: midd, which contains all elements of num except the last one ([5]), and lst, which contains the last element of num (6). Finally, it prints the values of midd and lst.



Monday 13 May 2024

Python Coding challenge - Day 204 | What is the output of the following Python Code?

 


Code:

num = [7, 8, 9]

*mid, last = num[:-1]  

print(mid, last)

Solution and Explanation:

let's break down the code:

num = [7, 8, 9]
*mid, last = num[:-1]  
print(mid, last)
num = [7, 8, 9]: This line creates a list called num containing the elements 7, 8, and 9.

*mid, last = num[:-1]: This line is a bit more complex. It's using extended unpacking and slicing. Let's break it down:

num[:-1]: This slices the list num from the beginning to the second-to-last element. So, it creates a new list [7, 8].

*mid, last: Here, the *mid notation is used to capture multiple items from the sliced list except the last one, and last captures the last item. So, mid will contain [7, 8], and last will contain 9.

print(mid, last): This line prints the values of mid and last.

So, when you run this code, it will print:

[7, 8] 9
This demonstrates how you can use extended unpacking along with slicing to split a list into multiple variables in Python.



Python Libraries for Financial Analysis and Portfolio Management

 



import statsmodels.api as sm
import numpy as np

# Generate some sample data
x = np.random.rand(100)
y = 2 * x + np.random.randn(100)

# Fit a linear regression model
model = sm.OLS(y, sm.add_constant(x)).fit()

print("Regression coefficients:", model.params)
print("R-squared:", model.rsquared)

#clcoding.com 
import pandas as pd

# Create a simple DataFrame
data = {'Name': ['Alice', 'Bob', 'Charlie'],
        'Age': [25, 30, 35],
        'Salary': [50000, 60000, 70000]}
df = pd.DataFrame(data)

# Perform data analysis
print("DataFrame head:")
print(df.head())
print("\nAverage salary:", df['Salary'].mean())

#clcoding.com 
import numpy as np

# Create a simple array
arr = np.array([1, 2, 3, 4, 5])

# Perform numerical operations
print("Sum:", np.sum(arr))
print("Mean:", np.mean(arr))
print("Standard deviation:", np.std(arr))

#clcoding.com 
from ibapi.client import EClient
from ibapi.wrapper import EWrapper

class MyWrapper(EWrapper):
    def __init__(self):
        super().__init__()

class MyClient(EClient):
    def __init__(self, wrapper):
        EClient.__init__(self, wrapper)

app = MyClient(MyWrapper())
app.connect("127.0.0.1", 7497, clientId=1)

app.run()

#clcoding.com 
import numpy as np
from scipy import optimize

# Define a simple objective function
def objective(x):
    return x**2 + 10*np.sin(x)

# Optimize the objective function
result = optimize.minimize(objective, x0=0)

print("Minimum value found at:", result.x)
print("Objective function value at minimum:", result.fun)

#clcoding.com 
from riskfolio.Portfolio import Portfolio

# Create a simple portfolio
data = {'Asset1': [0.05, 0.1, 0.15],
        'Asset2': [0.08, 0.12, 0.18],
        'Asset3': [0.06, 0.11, 0.14]}
portfolio = Portfolio(returns=data)

# Perform portfolio optimization
portfolio.optimize()

print("Optimal weights:", portfolio.w)
print("Expected return:", portfolio.mu)
print("Volatility:", portfolio.sigma)

#clcoding.com 

Sunday 12 May 2024

Python Coding challenge - Day 203 | What is the output of the following Python Code?

 

Code:

num = [1, 2, 3]

*middle, last = num

print(middle, last)

Solution and Explanation:

Let's break down the code step by step:

num = [1, 2, 3]: This line initializes a list called num with three elements: 1, 2, and 3.

*middle, last = num: This line uses a feature called "extended iterable unpacking". Here, *middle is used to capture all elements except the last one from the list num, and last captures the last element of the list.

*middle: This syntax with the * operator before a variable name is used to capture multiple elements from an iterable (like a list) into a new list. In this case, it captures the first two elements [1, 2] into the variable middle.

last: This variable captures the last element of the list, which is 3, and assigns it to the variable last.

print(middle, last): This line prints out the values of the variables middle and last.

Putting it all together, if we execute this code, it will print:

[1, 2] 3
This is because middle contains the first two elements [1, 2] from the list num, and last contains the last element 3 from the list num.

Saturday 11 May 2024

Happy Mother's Day!

 


Code:

import pyfiglet

from termcolor import colored

import random

def get_random_font_style():

    # List of available Figlet font styles

    font_styles = pyfiglet.FigletFont.getFonts() 

    # Choose a random font style from the list

    return random.choice(font_styles)

def get_random_color():

    # List of available colors

    colors = ['red', 'green', 'yellow', 'blue', 'magenta', 'cyan', 'white']

    # Choose a random color from the list

    return random.choice(colors)

def wish_mothers_day():

    # Get a random font style and color

    random_font_style = get_random_font_style()

    random_color = get_random_color()

    # Create a Figlet font object with the random style

    font = pyfiglet.Figlet(font=random_font_style)

    # Print the decorative greeting in the chosen color

    print(colored(font.renderText("Happy Mother's Day!"), random_color))

wish_mothers_day()

#clcoding.com

Solution and Explanation:

This code generates a Mother's Day wish with a randomly selected font style and color using the pyfiglet and termcolor libraries in Python. Here's a breakdown of what each part of the code does:

import pyfiglet: Imports the pyfiglet library, which is used to create ASCII art text.

from termcolor import colored: Imports the colored function from the termcolor library, which is used to add color to text in the terminal.

import random: Imports the random module, which is used to generate random font styles and colors.

get_random_font_style(): Defines a function that returns a random font style chosen from the available Figlet font styles provided by pyfiglet.

get_random_color(): Defines a function that returns a random color chosen from a predefined list of colors.

wish_mothers_day(): Defines the main function responsible for printing the Mother's Day wish. Inside this function:

random_font_style is assigned a random font style using get_random_font_style().
random_color is assigned a random color using get_random_color().
A Figlet font object is created using the random font style.
The text "Happy Mother's Day!" is rendered using the chosen font style and colored with the chosen color using the colored function.
The rendered text is printed to the console.
wish_mothers_day(): Finally, the wish_mothers_day() function is called to generate and print the Mother's Day wish with a random font style and color.

This code allows you to produce colorful and decorative Mother's Day wishes each time it's run, adding a touch of randomness and visual appeal to the message.


Type Hints in Python

 Type hints in Python are an excellent tool for improving code quality and maintainability, especially in larger projects. 

from typing import Optional

class TreeNode:

    def __init__(self, value: int) -> None:

        self.value = value

        self.left: Optional['TreeNode'] = None

        self.right: Optional['TreeNode'] = None

#clcoding.com

class LinkedListNode:

    def __init__(self, value: int, next_node: 'LinkedListNode' = None) -> None:

        self.value = value

        self.next = next_node

#clcoding.com

from typing import Optional

class TreeNode:

    def __init__(self, value: int) -> None:

        self.value = value

        self.left: Optional['TreeNode'] = None

        self.right: Optional['TreeNode'] = None

#clcoding.com

from typing import TypeVar

class Animal:

    def speak(self) -> str:

        raise NotImplementedError

class Dog(Animal):

    def speak(self) -> str:

        return "Woof!"

T = TypeVar('T', bound=Animal)

def make_sound(animal: T) -> str:

    return animal.speak()

#clcoding.com

from typing import Callable

def apply_func(func: Callable[[int, int], int], a: int, b: int) -> int:

    return func(a, b)

#clcoding.com

from typing import Iterable, TypeVar

T = TypeVar('T')

def process_items(items: Iterable[T]) -> None:

    for item in items:

        # Process each item

        pass

#clcoding.com

from typing import TypeVar, Iterable

T = TypeVar('T')

def first_element(items: Iterable[T]) -> T:

    return next(iter(items))

#clcoding.com

from typing import List, Tuple

Point = Tuple[int, int]

Polygon = List[Point]

def area(polygon: Polygon) -> float:

    # Calculate area of polygon

    pass

#clcoding.com

from typing import Union
def square_root(num: Union[int, float]) -> Union[int, float]:
    return num ** 0.5

#clcoding.com
from typing import Optional

def greet(name: Optional[str]) -> str:
    if name:
        return f"Hello, {name}!"
    else:
        return "Hello, anonymous!"

#clcoding.com

Automating File Compression with gzip

 

Code:

import gzip

import shutil


def compress_file(input_file, output_file):

    with open(input_file, 'rb') as f_in:

        with gzip.open(output_file, 'wb') as f_out:

            shutil.copyfileobj(f_in, f_out)


# Example usage

input_filename = 'clcoding.txt'

output_filename = 'clcoding.txt.gz'

compress_file(input_filename, output_filename)

#clcoding.com 

Explanation:

Let's break down the code step by step:

import gzip: This line imports the gzip module, which provides functionalities for working with gzip-compressed files in Python. The gzip module allows you to create, read, and write gzip-compressed files.

import shutil: This line imports the shutil module, which provides a higher-level interface for file operations. In this script, shutil is used to copy the contents of one file to another efficiently.

def compress_file(input_file, output_file):: This line defines a function named compress_file that takes two parameters: input_file (the path to the file to be compressed) and output_file (the path where the compressed file will be saved).

with open(input_file, 'rb') as f_in:: This line opens the input file (input_file) in binary read mode ('rb') using the open() function. It uses a context manager (with statement) to automatically close the file when the block is exited. The file object is assigned to the variable f_in.

with gzip.open(output_file, 'wb') as f_out:: This line opens the output file (output_file) in gzip-compressed write mode ('wb') using gzip.open(). Similar to the previous with statement, it also uses a context manager to automatically close the file when the block is exited. The compressed file object is assigned to the variable f_out.

shutil.copyfileobj(f_in, f_out): This line copies the contents of the input file (f_in) to the gzip-compressed output file (f_out). It efficiently copies data between file objects without loading the entire file into memory.

input_filename = 'clcoding.txt': This line defines a variable input_filename and assigns it the name of the input file (clcoding.txt). This file will be compressed.

output_filename = 'clcoding.txt.gz': This line defines a variable output_filename and assigns it the name of the output file (clcoding.txt.gz). This file will store the compressed data.

compress_file(input_filename, output_filename): This line calls the compress_file function with the input and output filenames as arguments, which compresses the input file and saves the compressed data to the output file.

#clcoding.com: This line appears to be a comment, possibly indicating the source of the file (clcoding.com). Comments in Python are preceded by the # symbol and are ignored by the interpreter.

This script takes a file (clcoding.txt), compresses it using gzip, and saves the compressed data to a new file (clcoding.txt.gz).


Popular Posts

Categories

AI (29) Android (24) AngularJS (1) Assembly Language (2) aws (17) Azure (7) BI (10) book (4) Books (124) C (77) C# (12) C++ (82) Course (67) Coursera (195) Cybersecurity (24) data management (11) Data Science (100) Data Strucures (7) Deep Learning (11) Django (14) Downloads (3) edx (2) Engineering (14) Excel (13) Factorial (1) Finance (6) flask (3) flutter (1) FPL (17) Google (19) Hadoop (3) HTML&CSS (46) IBM (25) IoT (1) IS (25) Java (93) Leet Code (4) Machine Learning (46) Meta (18) MICHIGAN (5) microsoft (4) Pandas (3) PHP (20) Projects (29) Python (845) Python Coding Challenge (279) Questions (2) R (70) React (6) Scripting (1) security (3) Selenium Webdriver (2) Software (17) SQL (41) UX Research (1) web application (8)

Followers

Person climbing a staircase. Learn Data Science from Scratch: online program with 21 courses