Sunday 7 April 2024

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

 

Code: 

def sum(num):
    if num == 1:
        return 1
    return num + sum(num-1)
print(sum(4))

Solution and Explanantion: 

This is a recursive Python function named sum. It calculates the sum of integers from 1 to a given number (num). Let's break it down:

def sum(num)::

This line defines a function named sum that takes one argument, num.

if num == 1::

This is a base case for the recursion. It checks if the input num is equal to 1.

return 1:

If num is indeed 1, it returns 1. This is the base case of the recursion where the sum of integers from 1 to 1 is 1.

return num + sum(num-1):

If num is not equal to 1, it returns the sum of num and the result of calling sum recursively with num-1. This line adds the current value of num to the sum of all integers from 1 to num-1.

print(sum(4)):

This line calls the sum function with the argument 4, meaning it will calculate the sum of integers from 1 to 4.

Let's trace how this works with sum(4):

sum(4) calls sum(3)

sum(3) calls sum(2)

sum(2) calls sum(1)

sum(1) returns 1 (base case)

sum(2) returns 2 + 1 = 3

sum(3) returns 3 + 3 = 6

sum(4) returns 4 + 6 = 10

So, print(sum(4)) will output 10.

Saturday 6 April 2024

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

 

Code: 

my_dict = {'a': 1, 'b': 2, 'c': 3}

value = my_dict.get('d', None)

print(value)

Solution and Explanation:

Let's break down each line of the code:

my_dict = {'a': 1, 'b': 2, 'c': 3}: This line creates a dictionary called my_dict with three key-value pairs. Each key represents a letter ('a', 'b', 'c') and each corresponding value is an integer (1, 2, 3).

value = my_dict.get('d', None): This line retrieves the value associated with the key 'd' from the dictionary my_dict using the .get() method. If the key 'd' exists in the dictionary, it returns the associated value. If the key doesn't exist, it returns the default value provided, which in this case is None.

print(value): This line prints the value stored in the variable value. If the key 'd' exists in the dictionary, it will print the corresponding value. If the key doesn't exist, it will print None, as that is the default value provided.

So, in summary, the code first creates a dictionary my_dict, then it attempts to retrieve the value associated with the key 'd' from this dictionary. Finally, it prints the retrieved value (or None if the key doesn't exist in the dictionary).

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

 

Code:

my_dict = {'a': 1, 'b': 2, 'c': 3}

value = my_dict.pop('d', 0)

print(value)

Solution and Explanation:

Let's break down the code step by step:

my_dict = {'a': 1, 'b': 2, 'c': 3}: This line initializes a dictionary named my_dict with three key-value pairs. The keys are 'a', 'b', and 'c', and their corresponding values are 1, 2, and 3 respectively.

value = my_dict.pop('d', 0): The pop() method in Python is used to remove and return the value associated with a specified key. In this line, 'd' is the key being looked up in the dictionary. However, since 'd' is not a key in my_dict, the default value 0 is returned instead of raising a KeyError.

If the key 'd' exists in the dictionary, its corresponding value would be returned and removed from the dictionary.

If the key 'd' does not exist in the dictionary, the second argument of pop() (which is 0 in this case) is returned without modifying the dictionary.

Therefore, value will be assigned the value returned by pop(), which is 0.

print(value): This line prints the value stored in the variable value. Since value holds 0 (the default value returned by pop()), the output of this line will be 0.

So, the output of the code will be:

0

Python Advanced Programming: The Guide to Learn Python Programming. Reference with Exercises and Samples About Dynamical Programming, Multithreading, Multiprocessing, Debugging, Testing and More

 


If you want to learn the most modern programming language in the world, then keep reading.

Python is an high-level programming language. It's a modern language, easy to learn and understand but very powerful.

It's a versatile programming language that is now being used on a lot of different projects, from world-class internet companies to small hobbyists, Python is extremely flexible and can be useful in a lot of different fields.

With Python, you can develop apps, games and any kind of software.

In fact, Python is one of the highest-demand skill for professional developers.

Python Advanced Programming approaches this programming language in a very practical method to make sure you can learn everything you need to start working with Python as soon as possible and to handle advanced feature of this unique language.

You will learn...

▸ Advanced procedural programming techniques

▸ What is Dynamic Code Execution

▸ Advanced OOP functions most developers are not aware of

▸ Functional-style programming with Python

▸ How to debug, test and profile your software

▸ How to handle multiple processes

▸ The best techniques to spread the workload on different threads

Paper Back : Python Advanced Programming: The Guide to Learn Python Programming. Reference with Exercises and Samples About Dynamical Programming, Multithreading, Multiprocessing, Debugging, Testing and More

PDF: Python Advanced Programming: The Guide to Learn Python Programming. Reference with Exercises and Samples About Dynamical Programming, Multithreading, Multiprocessing, Debugging, Testing and More

Friday 5 April 2024

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

 



Code:

set1 = {1, 2, 3}

set2 = {3, 4, 5}

print(set1 - set2)

Solution and Explanation:

The code snippet set1 = {1, 2, 3} and set2 = {3, 4, 5} initializes two sets: set1 containing elements {1, 2, 3} and set2 containing elements {3, 4, 5}.

When you perform the operation set1 - set2, you're using the set difference operator -, which returns a new set containing elements that are present in set1 but not in set2. In other words, it returns the elements that are unique to set1.

So, in this case, the output will be {1, 2} because the elements 1 and 2 are present in set1 but not in set2. The element 3 is common to both sets, so it is not included in the result.







Thursday 4 April 2024

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

 

Let's break down the code:

my_list = [1, 2, 3, 4, 5]  # Define a list named my_list with elements 1, 2, 3, 4, and 5

my_list.remove(3)          # Remove the element with the value 3 from my_list

print(my_list)             # Print the modified my_list

Explanation:

my_list = [1, 2, 3, 4, 5]: This line initializes a list named my_list containing the integers 1, 2, 3, 4, and 5.

my_list.remove(3): The remove() method is called on my_list with the argument 3. This method removes the first occurrence of the specified value from the list. In this case, it removes the element with the value 3 from my_list.

print(my_list): This line prints the modified my_list after the element with the value 3 has been removed. So, the output will be:

[1, 2, 4, 5]

After executing the code, my_list will contain the elements [1, 2, 4, 5], with the element 3 removed from it.

Wednesday 3 April 2024

Convert PDF files using Python


from gtts import gTTS
from PyPDF2 import PdfReader

def pdf_to_text(pdf_file):
    text = ""
    with open(pdf_file, 'rb') as f:
        reader = PdfReader(f)
        for page_num in range(len(reader.pages)):
            page = reader.pages[page_num]
            text += page.extract_text()
    return text

def text_to_audio(text, output_file):
    tts = gTTS(text)
    tts.save(output_file)

# Example usage:
pdf_file = "clcoding.pdf"
output_audio_file = "clcoding_audio.mp3"

text = pdf_to_text(pdf_file)
text_to_audio(text, output_audio_file)

#clcoding.com

Explanation: 

This code snippet is a Python script that converts text from a PDF file to an audio file using the Google Text-to-Speech (gTTS) library (gTTS) and the PyPDF2 library (PdfReader).

Here's a breakdown of what each part of the code does:

Importing Required Libraries:

from gtts import gTTS: This imports the gTTS class from the gtts module, which allows us to convert text to speech using Google Text-to-Speech.
from PyPDF2 import PdfReader: This imports the PdfReader class from the PyPDF2 library, which is used to read PDF files.
pdf_to_text(pdf_file) Function:

This function takes a PDF file path (pdf_file) as input.
It opens the PDF file in binary mode and creates a PdfReader object to read the content of the PDF.
It iterates through each page of the PDF (reader.pages) and extracts text from each page using the extract_text() method.
It concatenates all the extracted text from each page into a single string (text).
Finally, it returns the concatenated text.
text_to_audio(text, output_file) Function:

This function takes two arguments: the text to convert to audio (text) and the file path where the audio will be saved (output_file).
It creates a gTTS object (tts) by passing the input text.
It saves the generated audio file to the specified output file path.
Example Usage:

It defines the input PDF file (pdf_file) as "clcoding.pdf".
It defines the output audio file path (output_audio_file) as "clcoding_audio.mp3".
It calls the pdf_to_text() function to extract text from the PDF file.
It calls the text_to_audio() function to convert the extracted text to audio and save it to the specified output file.
The comment #clcoding.com is unrelated to the code and appears to be a note or reference to a website.

This script essentially converts the text content of a PDF file into audio, which could be useful for tasks such as creating audiobooks, generating voiceovers, or assisting users with reading disabilities.

import os
from PyPDF2 import PdfReader
from pdf2image import convert_from_path

def pdf_to_images(pdf_file, output_dir):
    images = []
    with open(pdf_file, 'rb') as f:
        reader = PdfReader(f)
        for page_num, _ in enumerate(reader.pages):
            # Convert each PDF page to image
            img_path = os.path.join(output_dir, f"page_{page_num}.png")
            images.append(img_path)
    return images

# Example usage:
pdf_file = "clcoding.pdf"
output_dir = "output_images"

if not os.path.exists(output_dir):
    os.makedirs(output_dir)

pdf_to_images(pdf_file, output_dir)

#clcoding.com

Explanation: 

This Python script converts each page of a PDF file into an image format (PNG) using the PyPDF2 library to read the PDF and the pdf2image library to perform the conversion.

Here's a breakdown of each part of the code:

Importing Required Libraries:

import os: This imports the os module, which provides functions for interacting with the operating system, such as creating directories.
from PyPDF2 import PdfReader: This imports the PdfReader class from the PyPDF2 library, which is used to read PDF files.
from pdf2image import convert_from_path: This imports the convert_from_path function from the pdf2image library, which is used to convert PDF pages to images.
pdf_to_images(pdf_file, output_dir) Function:

This function takes two arguments: the path to the input PDF file (pdf_file) and the directory where the output images will be saved (output_dir).
It initializes an empty list called images to store the file paths of the converted images.
It opens the PDF file in binary mode ('rb') using a context manager (with open(...) as f) and creates a PdfReader object (reader) to read the content of the PDF.
It iterates through each page of the PDF (reader.pages) using enumerate to get both the page number and the page object.
For each page, it generates a file path for the corresponding image in the output directory (output_dir) using os.path.join and appends it to the images list.
Finally, it returns the list of image file paths.
Example Usage:

It defines the input PDF file (pdf_file) as "clcoding.pdf".
It defines the output directory (output_dir) as "output_images".
It checks if the output directory does not exist (if not os.path.exists(output_dir)), and if not, it creates the directory using os.makedirs(output_dir).
It calls the pdf_to_images() function to convert the PDF pages to images and stores the list of image file paths.
The comment #clcoding.com is unrelated to the code and appears to be a note or reference to a website.

This script can be useful for tasks such as converting PDF pages to images for further processing or display, such as in document management systems, image processing pipelines, or for creating thumbnails of PDF documents.

import os
from PyPDF2 import PdfReader
import docx

def pdf_to_text():
    pdf_file = "clcoding.pdf"
    text = ""
    with open(pdf_file, 'rb') as f:
        reader = PdfReader(f)
        for page_num in range(len(reader.pages)):
            page_text = reader.pages[page_num].extract_text()
            text += page_text
    return text

def pdf_to_docx(output_file):
    text = pdf_to_text()
    doc = docx.Document()
    doc.add_paragraph(text)
    doc.save(output_file)

# Example usage:
output_docx_file = "output_docx.docx"

pdf_to_docx(output_docx_file)

#clcoding.com

Explanation:

This Python script converts the text content of a PDF file ("clcoding.pdf") into a Microsoft Word document (.docx) using the PyPDF2 library to extract text from the PDF and the python-docx library to create and save the Word document.

Here's a breakdown of each part of the code:

Importing Required Libraries:

import os: This imports the os module, which provides functions for interacting with the operating system, such as creating directories or checking file paths.
from PyPDF2 import PdfReader: This imports the PdfReader class from the PyPDF2 library, which is used to read PDF files.
import docx: This imports the docx module, which is part of the python-docx library, used for creating and manipulating Word documents.
pdf_to_text() Function:

This function reads the text content of the PDF file ("clcoding.pdf").
It initializes an empty string called text to store the extracted text.
It opens the PDF file in binary mode ('rb') using a context manager (with open(...) as f) and creates a PdfReader object (reader) to read the content of the PDF.
It iterates through each page of the PDF (reader.pages) using range(len(reader.pages)) to get the page number.
For each page, it extracts the text using the extract_text() method of the page object and appends it to the text string.
Finally, it returns the concatenated text.
pdf_to_docx(output_file) Function:

This function converts the extracted text from the PDF to a Word document.
It calls the pdf_to_text() function to get the text content of the PDF.
It creates a new docx.Document() object (doc) to represent the Word document.
It adds a paragraph containing the extracted text to the document using the add_paragraph() method.
It saves the document to the specified output file path using the save() method.
Example Usage:

It defines the output Word document file path (output_docx_file) as "output_docx.docx".
It calls the pdf_to_docx() function to convert the PDF text content to a Word document and save it to the specified output file.
The comment #clcoding.com is unrelated to the code and appears to be a note or reference to a website.

This script is useful for converting the text content of a PDF file to a Word document, which can be helpful for further editing or formatting. Make sure you have the necessary libraries installed (PyPDF2 and python-docx).

 import os
from PyPDF2 import PdfReader
import pandas as pd

def pdf_to_text():
    pdf_file = "clcoding.pdf"
    text = ""
    with open(pdf_file, 'rb') as f:
        reader = PdfReader(f)
        for page_num in range(len(reader.pages)):
            page_text = reader.pages[page_num].extract_text()
            text += page_text
    return text

def pdf_to_excel(output_file):
    text = pdf_to_text()
    lines = text.split('\n')
    df = pd.DataFrame(lines)
    df.to_excel(output_file, index=False, header=False)

# Example usage:
output_excel_file = "output_excel.xlsx"

pdf_to_excel(output_excel_file)

#clcoding.com

Explanation:

This Python script reads the text content of a PDF file ("clcoding.pdf") and then converts it into an Excel file (.xlsx) using the Pandas library. Here's a breakdown of each part of the code:

Importing Required Libraries:

import os: This imports the os module, which provides functions for interacting with the operating system, such as creating directories or checking file paths.
from PyPDF2 import PdfReader: This imports the PdfReader class from the PyPDF2 library, which is used to read PDF files.
import pandas as pd: This imports the Pandas library, often used for data manipulation and analysis.
pdf_to_text() Function:

This function reads the text content of the PDF file ("clcoding.pdf").
It initializes an empty string called text to store the extracted text.
It opens the PDF file in binary mode ('rb') using a context manager (with open(...) as f) and creates a PdfReader object (reader) to read the content of the PDF.
It iterates through each page of the PDF (reader.pages) using range(len(reader.pages)) to get the page number.
For each page, it extracts the text using the extract_text() method of the page object and appends it to the text string.
Finally, it returns the concatenated text.
pdf_to_excel(output_file) Function:

This function converts the extracted text from the PDF to an Excel file.
It calls the pdf_to_text() function to get the text content of the PDF.
It splits the text into lines using the newline character ('\n') and creates a list of lines.
It creates a Pandas DataFrame (df) from the list of lines.
It saves the DataFrame to an Excel file specified by the output_file parameter using the to_excel() method, without including the index or header.
Example Usage:

It defines the output Excel file path (output_excel_file) as "output_excel.xlsx".
It calls the pdf_to_excel() function to convert the PDF text content to an Excel file and save it to the specified output file.
The comment #clcoding.com is unrelated to the code and appears to be a note or reference to a website.

This script can be useful for extracting text data from PDF files and converting it into a structured format like an Excel spreadsheet for further analysis or manipulation. Make sure you have the necessary libraries installed (PyPDF2 and pandas).



import os
from PyPDF2 import PdfReader
from pptx import Presentation

def pdf_to_text():
    pdf_file = "clcoding.pdf"  # Using "clcoding.pdf"
    text = ""
    with open(pdf_file, 'rb') as f:
        reader = PdfReader(f)
        for page_num in range(len(reader.pages)):
            page_text = reader.pages[page_num].extract_text()
            text += page_text
    return text

def pdf_to_ppt(output_file):
    text = pdf_to_text()
    prs = Presentation()
    slides = text.split('\n\n')
    for slide_content in slides:
        slide = prs.slides.add_slide(prs.slide_layouts[1])
        slide.shapes.title.text = slide_content
    prs.save(output_file)

# Example usage:
output_ppt_file = "output_ppt.pptx"

pdf_to_ppt(output_ppt_file)

#clcoding.com

Explanation:

This Python script converts the text content of a PDF file ("clcoding.pdf") into a PowerPoint presentation (.pptx) using the PyPDF2 library to extract text from the PDF and the python-pptx library to create and save the PowerPoint presentation.

Here's a breakdown of each part of the code:

Importing Required Libraries:

import os: This imports the os module, which provides functions for interacting with the operating system, such as creating directories or checking file paths.
from PyPDF2 import PdfReader: This imports the PdfReader class from the PyPDF2 library, which is used to read PDF files.
from pptx import Presentation: This imports the Presentation class from the pptx module, which is part of the python-pptx library used for creating and manipulating PowerPoint presentations.
pdf_to_text() Function:

This function reads the text content of the PDF file ("clcoding.pdf").
It initializes an empty string called text to store the extracted text.
It opens the PDF file in binary mode ('rb') using a context manager (with open(...) as f) and creates a PdfReader object (reader) to read the content of the PDF.
It iterates through each page of the PDF (reader.pages) using range(len(reader.pages)) to get the page number.
For each page, it extracts the text using the extract_text() method of the page object and appends it to the text string.
Finally, it returns the concatenated text.
pdf_to_ppt(output_file) Function:

This function converts the extracted text from the PDF to a PowerPoint presentation.
It calls the pdf_to_text() function to get the text content of the PDF.
It creates a new Presentation() object (prs) to represent the PowerPoint presentation.
It splits the text into slides based on double newline characters ('\n\n').
For each slide content, it adds a new slide to the presentation using the add_slide() method, specifying the layout of the slide.
It sets the title of each slide to the slide content using the shapes.title.text property.
Finally, it saves the presentation to the specified output file path using the save() method.
Example Usage:

It defines the output PowerPoint file path (output_ppt_file) as "output_ppt.pptx".
It calls the pdf_to_ppt() function to convert the PDF text content to a PowerPoint presentation and save it to the specified output file.
The comment #clcoding.com is unrelated to the code and appears to be a note or reference to a website.

This script can be useful for converting the text content of a PDF file into a structured format like a PowerPoint presentation, which can be helpful for presentations or sharing information in a visually appealing format. Make sure you have the necessary libraries installed (PyPDF2 and python-pptx).

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

 

Code: 

g = [1, 2, 3, 4]
g.clear()
print(g)

Solution and Explanation:

Let's break down the code step by step:

g = [1, 2, 3, 4]: This line initializes a list named g with four elements: 1, 2, 3, and 4.

g.clear(): This line calls the clear() method on the list g. The clear() method removes all the elements from the list, effectively making it empty.

print(g): Finally, this line prints the contents of the list g after it has been cleared. Since the clear() method removed all elements from g, the output will be an empty list [].

So, the code essentially clears all the elements from the list g and then prints an empty list [].

Tuesday 2 April 2024

Doughnut Plot using Python

 

import plotly.graph_objects as go


# Sample data

labels = ['A', 'B', 'C', 'D']

values = [20, 30, 40, 10]

colors = ['#FFA07A', '#FFD700', '#6495ED', '#ADFF2F']


# Create doughnut plot

fig = go.Figure(data=[go.Pie(labels=labels, values=values, hole=.5, marker=dict(colors=colors))])

fig.update_traces(textinfo='percent+label', textfont_size=14, hoverinfo='label+percent')

fig.update_layout(title_text="Customized Doughnut Plot", showlegend=False)


# Show plot

fig.show()


#clcoding.com


import matplotlib.pyplot as plt


# Sample data

labels = ['Category A', 'Category B', 'Category C', 'Category D']

sizes = [20, 30, 40, 10]

explode = (0, 0.1, 0, 0)  # "explode" the 2nd slice


# Create doughnut plot

fig, ax = plt.subplots()

ax.pie(sizes, explode=explode, labels=labels, autopct='%1.1f%%', startangle=90, shadow=True, colors=plt.cm.tab20.colors)

ax.axis('equal')  # Equal aspect ratio ensures that pie is drawn as a circle


# Draw a white circle at the center to create a doughnut plot

centre_circle = plt.Circle((0, 0), 0.7, color='white', fc='white', linewidth=1.25)

fig.gca().add_artist(centre_circle)


# Add a title

plt.title('Doughnut Plot with Exploded Segment and Shadow Effect')


# Show plot

plt.show()


#clcoding.com



import plotly.graph_objects as go


# Sample data

labels = ['A', 'B', 'C', 'D']

values = [20, 30, 40, 10]


# Create doughnut plot

fig = go.Figure(data=[go.Pie(labels=labels, values=values, hole=.5)])

fig.update_layout(title_text="Doughnut Plot")


# Show plot

fig.show()


#clcoding.com



import matplotlib.pyplot as plt


# Sample data

labels = ['Category A', 'Category B', 'Category C', 'Category D']

sizes = [20, 30, 40, 10]


# Create doughnut plot

fig, ax = plt.subplots()

ax.pie(sizes, labels=labels, autopct='%1.1f%%', startangle=90, colors=plt.cm.tab20.colors)

ax.axis('equal')  # Equal aspect ratio ensures that pie is drawn as a circle


# Draw a white circle at the center to create a doughnut plot

centre_circle = plt.Circle((0, 0), 0.7, color='white', fc='white', linewidth=1.25)

fig.gca().add_artist(centre_circle)


# Add a title

plt.title('Doughnut Plot')


# Show plot

plt.show()


#clcoding.com

Monday 1 April 2024

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

 


Let's break down each line of code:

d = [1, 2]: This line initializes a list d with elements [1, 2].

e = (1, 2): This line initializes a tuple e with elements (1, 2).

print(tuple(d) + e): This line converts the list d into a tuple using the tuple() function, resulting in (1, 2), and then concatenates it with tuple e. This concatenation combines the elements of both tuples. Since tuples are immutable, a new tuple is created as the result of this operation. The output of this line will be (1, 2, 1, 2).

print(d + list(e)): This line converts the tuple e into a list using the list() function, resulting in [1, 2], and then concatenates it with list d. This concatenation combines the elements of both lists. Since lists are mutable, a new list is created as the result of this operation. The output of this line will be [1, 2, 1, 2].

So, the output of the entire code will be:

(1, 2, 1, 2)

[1, 2, 1, 2]

Sunday 31 March 2024

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

 

let's break down the code:

a = 5: This line assigns the integer value 5 to the variable a.

b = "10": This line assigns the string "10" to the variable b.

print(a + int(b)): Here, int(b) converts the string "10" to an integer, resulting in 10. Then a + int(b) adds the integer value of b (which is 10) to the value of a (which is 5), resulting in 15. So, this line will print 15.

print(str(a) + b): Here, str(a) converts the integer a into a string, resulting in "5". Then "5" + b concatenates the string "5" with the string "10", resulting in "510". So, this line will print "510".

So, the output of the code will be:

15

510

Happy Easter wishes using Python

 


import pyfiglet

from termcolor import colored


def wish_happy_easter():

    # Creating a colorful Happy Easter message using pyfiglet and termcolor

    easter_message = pyfiglet.figlet_format("Happy Easter!")

    colored_message = colored(easter_message, color='yellow', attrs=['bold'])

    

    # Additional colorful text

    additional_text = colored("\nWishing you a joyful and blessed Easter !")

    

    print(colored_message + additional_text)


wish_happy_easter()


#clcoding.com

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

 

Code: 

def fibonacci(n):

    if n <= 1:

        return n

    else:

        return fibonacci(n-1) + fibonacci(n-2)

print(fibonacci(6))

Solution and Explanation:

The provided code defines a Python function fibonacci(n) that computes the nth Fibonacci number recursively, and then prints the 6th Fibonacci number.

Here's how it works:

The fibonacci function takes an integer n as input.

It starts with a base case: if n is 0 or 1, it returns n itself. This is because the Fibonacci sequence starts with 0 and 1, and from there each subsequent number is the sum of the two preceding ones.

If n is greater than 1, it recursively calls the fibonacci function for n-1 and n-2, and returns the sum of these two calls.

The function keeps recursively calling itself until it reaches one of the base cases, where it directly returns a value.

Finally, it prints the 6th Fibonacci number by calling fibonacci(6) and prints the result.

Let's walk through fibonacci(6):

fibonacci(6) calls fibonacci(5) and fibonacci(4).

fibonacci(5) further calls fibonacci(4) and fibonacci(3).

fibonacci(4) calls fibonacci(3) and fibonacci(2).

This process continues until it reaches the base cases (n <= 1).

Eventually, it computes the Fibonacci numbers for n=2, n=3, n=4, n=5, and n=6 and sums them up to get the 6th Fibonacci number.

So, when you run print(fibonacci(6)), it will output the 6th Fibonacci number, which is 8.

Saturday 30 March 2024

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

 

Let's break down the code snippet step by step:

class MyClass:

    def __init__(self):

        self.__x = 10

Here, we define a class named MyClass. It has a constructor method __init__ which initializes an instance variable __x with the value 10. The __x variable is prefixed with double underscores, making it a private variable.

obj = MyClass()

We then create an instance of the MyClass class called obj. This invokes the constructor method __init__() of the MyClass class, setting the __x attribute to 10.

obj.__x = 20

Here, we try to assign a value of 20 to the __x attribute of the obj instance. However, Python is dynamically typed, so this line actually creates a new attribute __x in the obj instance, distinct from the __x attribute defined in the class. Since the attribute in the class is private, it cannot be accessed or modified directly from outside the class.

print(obj.__x)

This line tries to print the value of the __x attribute of the obj instance. However, due to the previous line, there are now two __x attributes associated with the obj instance: one created in the class and another created directly in the instance. So, obj.__x refers to the newly created attribute __x in the instance, not the one defined in the class. Therefore, it prints 20.

In summary, even though the class MyClass has a private attribute __x, the code snippet demonstrates how Python's dynamic nature allows the creation of a new instance attribute with the same name, leading to confusion about which attribute is being accessed or modified.


Thursday 28 March 2024

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

 


Code: 

def bar(a, b=2, c=3):

    print(a, b, c)

bar(1)

bar(1, 4)

bar(1, c=5)

Solution and Explanation: 

let's go through each function call:

bar(1):

Here, only one argument a is passed, so a takes the value 1.

Since b and c have default values specified in the function definition (b=2 and c=3), they will take those values.

So, the output will be 1 2 3.

bar(1, 4):

Here, two arguments a and b are passed, so a takes the value 1 and b takes the value 4.

Since c has a default value specified, it will take that default value.

So, the output will be 1 4 3.

bar(1, c=5):

Here, two arguments a and c are passed, so a takes the value 1 and c takes the value 5.

Since b has a default value specified, it will take that default value.

So, the output will be 1 2 5.

In Python, when calling a function, arguments are assigned based on their position, unless you explicitly specify the name of the parameter (as in the third call). In that case, the argument is matched to the parameter name regardless of position. If a parameter has a default value, it can be omitted in the function call, and the default value will be used.

pytube library for downloading YouTube videos

 

# Get a specific stream
stream = yt.streams.get_by_itag(22)  # Example: iTAG for 720p MP4

# Download the stream
stream.download()

#clcoding.com 

# Get the best audio stream
audio_stream = yt.streams.get_audio_only()

# Download the audio
audio_stream.download()

#clcoding.com 





# Get streams with only audio
audio_streams = yt.streams.filter(only_audio=True)

# Get streams with only video
video_streams = yt.streams.filter(only_video=True)

# Get streams with a specific resolution
hd_streams = yt.streams.filter(res="720p")

#clcoding.com 

# Get all available streams

streams = yt.streams.all()


# Print available streams

for stream in streams:

    print(stream)


#clcoding.com 

# Get streams with only audio

audio_streams = yt.streams.filter(only_audio=True)


# Get streams with only video

video_streams = yt.streams.filter(only_video=True)


# Get streams with a specific resolution

hd_streams = yt.streams.filter(res="720p")


#clcoding.com 



# Title of the video

print("Title:", yt.title)


# Description of the video

print("Description:", yt.description)


# Thumbnail URL of the video

print("Thumbnail URL:", yt.thumbnail_url)


# Video length in seconds

print("Length (seconds):", yt.length)


# Number of views

print("Views:", yt.views)


#clcoding.com 




from pytube import YouTube


# YouTube video URL

video_url = 'https://www.youtube.com/watch?v=qMNKy_4opeE'


# Initialize a YouTube object with the video URL

yt = YouTube(video_url)


# Get the highest resolution stream

stream = yt.streams.get_highest_resolution()


# Download the video

stream.download()


print("Download completed!")


#clcoding.com 

Tuesday 26 March 2024

Python pattern challenge - Day 9

 


def print_pattern():

    num = 1

    for i in range(1, 6):

        if i % 2 != 0:

            print(f"* {num} * {num + 1} *")

            num += 2

        else:

            print(f"{num} * {num + 1} * {num + 2}")

            num += 3


print_pattern()


Explanation: 

Let's break down the print_pattern() function step by step:

Initialization:

num = 1: This variable is initialized to 1. It will be used to generate the numbers in the pattern.
Looping:

for i in range(1, 6):: This loop iterates from 1 to 5 (inclusive). It controls the number of rows in the pattern.
Conditional Printing:

if i % 2 != 0:: This condition checks if the current row number i is odd.
If the row number is odd:
print(f"* {num} * {num + 1} *"): It prints a pattern where an asterisk ('*') is followed by num, then another asterisk, then num + 1, and finally an asterisk. This is repeated for each odd row.
num += 2: num is incremented by 2 because each number is two units apart in odd rows.
If the row number is even:
print(f"{num} * {num + 1} * {num + 2}"): It prints a pattern where num is followed by an asterisk, then num + 1, then an asterisk, and finally num + 2. This is repeated for each even row.
num += 3: num is incremented by 3 because each number is three units apart in even rows.
Output:

The function print_pattern() is called, resulting in the specified pattern being printed to the console.
Overall, this function generates and prints a pattern consisting of alternating rows with different structures: odd rows have asterisks surrounding consecutive numbers, while even rows have numbers separated by asterisks.

Python pattern challenge - Day 8

 

def gen_tri(size):

    for i in range(0, size//2 + 1):

        yield ' ' * i + '*' * (size - 2*i) + ' ' * i

def print_heart(size):

    size = 2*size + 1

    for i in reversed(list(gen_tri(size//2))):

        print(i, i)

    for i in gen_tri(size):

        print(i)

print_heart(4)


Explanation: 

This Python code defines two functions: gen_tri(size) and print_heart(size), and then it calls print_heart(4).

Here's what each part does:

gen_tri(size) Function:

This function generates lines for a triangle pattern.
It takes one parameter size, which represents the width of the base of the triangle.
It uses a loop to iterate over the range from 0 to size//2 + 1. This ensures that the triangle will have a height equal to half of the base plus one.
For each iteration, it yields a string consisting of spaces and asterisks (' ' and '*') to form the triangle shape. The number of spaces (' ') before and after the asterisks decreases as i increases, and the number of asterisks increases accordingly.
print_heart(size) Function:

This function prints a heart shape composed of two triangles.
It takes one parameter size, which represents the size of the heart.
Inside this function, size is modified to ensure symmetry and compatibility with the gen_tri function.
It first prints the upper triangle of the heart by iterating in reverse over the lines generated by gen_tri for half of the specified size.
Then, it prints the lower triangle of the heart by iterating over the lines generated by gen_tri for the other half of the specified size.
print_heart(4) Call:

This line calls the print_heart function with size equal to 4.
It will print a heart shape where the base of the triangle in each half has a width of 4 characters.
Overall, this code generates and prints a heart shape made up of two triangles, with a specified size.

How to install modules without pip ?

 Installing Python modules without using pip can be done manually by downloading the module's source code or distribution package and then installing it using Python's setup tools. Here's a basic guide on how to do it:

Download the module: Go to the official website or repository of the module you want to install and download the source code or distribution package (usually in a .tar.gz or .zip format).

Extract the package: Extract the downloaded package to a directory on your computer.

Navigate to the package directory: Open a terminal or command prompt and navigate to the directory where you extracted the package.

Install the module: Run the following command to install the module using Python's setup tools:

python setup.py install

If you have multiple versions of Python installed, you may need to specify the Python version explicitly, for example:

python3 setup.py install

This command will compile and install the module into your Python environment.

Verify installation: After installation, you can verify if the module is installed correctly by trying to import it in a Python script or interpreter.

Keep in mind that installing modules manually without pip may require additional dependencies and manual handling of version compatibility. It's generally recommended to use pip whenever possible, as it handles dependency resolution and installation automatically. However, manual installation can be useful in cases where pip is not available or suitable for some reason.







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

 

This code defines a function foo that takes a single argument x. The argument x is initialized with a default value of an empty list [].

def foo(x=[]):

    x.append(1)

    return x

Here's what happens when you call foo() multiple times:

First Call (print(foo())):

foo() is called without any argument, so x defaults to an empty list [].

Inside the function, 1 is appended to the list x, modifying it to [1].

The modified list [1] is returned and printed.

Second Call (print(foo())):


Since the default argument x retains its value between calls, it still holds the modified list [1] from the previous call.

1 is appended to the existing list x, resulting in [1, 1].

The modified list [1, 1] is returned and printed.

Third Call (print(foo())):


Similar to the second call, the default argument x still holds the modified list [1, 1].

Another 1 is appended to the list x, making it [1, 1, 1].

The modified list [1, 1, 1] is returned and printed.

So, the output of the three function calls will be:

[1]

[1, 1]

[1, 1, 1]

It's important to note that the default argument x=[] is evaluated only once when the function foo is defined. This means that every time you call foo() without passing an argument explicitly, the same list object (which was created when the function was defined) is used. This can lead to unexpected behavior if you're not careful, especially when dealing with mutable default arguments like lists or dictionaries.

Monday 25 March 2024

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

 

#Code:

explain def foo(x):
    return x + 1
result = map(foo, [1, 2, 3, 4])
print(list(result))

Solution and Explanations: 

This Python code demonstrates the use of the map() function. Let's break it down step by step:

def foo(x): - This line defines a function named foo that takes a single argument x.

return x + 1 - Inside the foo function, it simply returns the value of x incremented by 1.

result = map(foo, [1, 2, 3, 4]) - Here, the map() function is used. It takes two arguments: a function (foo in this case) and an iterable ([1, 2, 3, 4] in this case). What map() does is it applies the function (foo) to each item in the iterable ([1, 2, 3, 4]), producing a new iterable containing the results. So, map(foo, [1, 2, 3, 4]) will apply foo to each element of the list [1, 2, 3, 4], resulting in [2, 3, 4, 5].

print(list(result)) - The map() function returns an iterator, so we need to convert it into a list to see the results. This line converts the result iterator into a list and prints it. The output will be [2, 3, 4, 5], which are the values obtained by applying the foo function to each element in the list [1, 2, 3, 4], incrementing each by 1.

Python pattern challenge - Day 7

 


a=[]

for i in range(7):

    a.append([])

    for j in range(7):

        if i==0 or i==6 or i+j==6 or i==j:

            a[i].append("*")

        else:

            a[i].append(" ")


for i in range(7):

    print(*a[i])


Explanation: 

 Let's break down the code step by step:

a = []: This line initializes an empty list named a. This list will eventually hold the elements of the 2D array or matrix.

The outer loop: for i in range(7):

This loop iterates over values from 0 to 6 (inclusive).

For each value of i, a new empty list is appended to the list a. This effectively initializes a new row in the matrix.

The inner loop: for j in range(7):

This loop iterates over values from 0 to 6 (inclusive), representing columns within each row.

For each cell in the matrix (each combination of i and j), the following condition is checked:

The if condition:

If i is 0 or 6 (first or last row), or if the sum of i and j equals 6 (indicating the anti-diagonal), or if i equals j (indicating the main diagonal), then a star (*) is appended to the current row (a[i]). Otherwise, a space is appended.

After completing the inner loop for each i, a contains a 2D list representing a matrix where stars (*) are placed along the main diagonal, anti-diagonal, and the first and last rows.

The final loop: for i in range(7):

This loop iterates over the rows of the matrix.

For each row, the print(*a[i]) statement prints the elements of that row separated by spaces.

Overall, this code generates a 7x7 matrix filled with spaces and stars according to the conditions specified, and then prints the matrix row by row.

Sunday 24 March 2024

Happy Holi wishes using Python

 



from colorama import Fore

import pyfiglet

font = pyfiglet.figlet_format('Happy  Holi')

print(Fore.MAGENTA+font)


#clcoding.com




import pyfiglet

from termcolor import colored


def wish_happy_holi():

    # Happy Holi message using pyfiglet and termcolor

    holi_message = pyfiglet.figlet_format("Happy Holi!")

    colored_message = colored(holi_message, color='red')

    print(colored_message)


wish_happy_holi()

Python pattern challenge - Day 6

 

# Function to print swastika

def swastika(row,col):

for i in range(row):

for j in range(col): 

# checking if i < row/2

if(i < row // 2): 

# checking if j<col/2

if (j < col // 2): 

# print '*' if j=0

if (j == 0):

print("*", end = "")

# else print space

else:

print(" ", end = " ")

# check if j=col/2 

elif (j == col // 2):

print(" *", end = "")

else:

# if i=0 then first row will have '*'

if (i == 0):

print(" *", end = "")

elif (i == row // 2):

print("* ", end = "")

else: 

# middle column and last column will 

# have '*' after i > row/2

if (j == col // 2 or j == col - 1):

print("* ", end = "")

# last row

elif (i == row - 1): 

# last row will be have '*' if 

# j <= col/2 or if it is last column

if (j <= col // 2 or j == col - 1):

print("* ", end = "")

else:

print(" ", end = " ")

else:

print(" ", end = " ")

print()

# Driver code


# odd number of row and column

# to get perfect swastika

row = 7; col = 7


# Function calling

swastika(row, col)


#clcoding.com


*     * * * *
*     *
*     *
* * * * * * * 
      *     * 
      *     * 
* * * *     * 

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

 

Code:

def outer_function(x):

    def inner_function(y):

        return x + y

    return inner_function

result = outer_function(5)(3)

print(result)


Solution and Explanation: 

This code defines a Python function outer_function that takes a parameter x. Inside outer_function, there's another function defined called inner_function, which takes a parameter y.

inner_function simply returns the sum of x and y.

outer_function itself returns inner_function, effectively creating a closure where inner_function retains access to the x value passed to outer_function.

The last three lines of the code demonstrate how to use this function.

outer_function(5) is called, which returns inner_function where x is now set to 5.

Then, (3) is passed to this returned inner_function, effectively adding 3 to the x value set previously (5), resulting in 8.

Finally, the result, 8, is printed.

So, the output of this code would be: 8

Saturday 23 March 2024

GeoPy Library in Python

 

from geopy.geocoders import Nominatim

# Initialize Nominatim geocoder
geolocator = Nominatim(user_agent="my_geocoder")

# Geocode an address
location = geolocator.geocode("Mumbai, India")

print("Latitude:", location.latitude)
print("Longitude:", location.longitude)

#clcoding.com 


from geopy.geocoders import Nominatim

# Initialize Nominatim geocoder
geolocator = Nominatim(user_agent="my_geocoder")

# Reverse geocode coordinates
location = geolocator.reverse((26.4219999, 71.0840575))

print("Address:", location.address)

#clcoding.com


from geopy.distance import geodesic

# Coordinates of two locations
location1 = (18.521428, 73.8544541)  # Pune
location2 = (19.0785451, 72.878176)  # Mumbai

# Calculate distance between locations
distance = geodesic(location1, location2).kilometers

print("Distance betwen City :", distance, "km")

#clcoding.com



from geopy.geocoders import ArcGIS

# Initialize ArcGIS geocoder
geolocator = ArcGIS()

# Geocode an address using ArcGIS
location = geolocator.geocode("Pune, India")

print("Latitude:", location.latitude)
print("Longitude:", location.longitude)

#clcoding.com

Popular Posts

Categories

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

Followers

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