Featured Post

SQL Query: 3 Methods for Calculating Cumulative SUM

Image
SQL provides various constructs for calculating cumulative sums, offering flexibility and efficiency in data analysis. In this article, we explore three distinct SQL queries that facilitate the computation of cumulative sums. Each query leverages different SQL constructs to achieve the desired outcome, catering to diverse analytical needs and preferences. Using Window Functions (e.g., PostgreSQL, SQL Server, Oracle) SELECT id, value, SUM(value) OVER (ORDER BY id) AS cumulative_sum  FROM your_table; This query uses the SUM() window function with the OVER clause to calculate the cumulative sum of the value column ordered by the id column. Using Subqueries (e.g., MySQL, SQLite): SELECT t1.id, t1.value, SUM(t2.value) AS cumulative_sum FROM your_table t1 JOIN your_table t2 ON t1.id >= t2.id GROUP BY t1.id, t1.value ORDER BY t1.id; This query uses a self-join to calculate the cumulative sum. It joins the table with itself, matching rows where the id in the first table is greater than or

10 Exclusive Python Projects for Interviews

Here are ten Python projects along with code and possible solutions for your practice.


10 top projects



01. Palindrome Checker:


Description: Write a function that checks if a given string is a palindrome (reads the same backward as forward).


def is_palindrome(s):
    s = s.lower().replace(" ", "")
    return s == s[::-1]

# Test the function
print(is_palindrome("radar"))  # Output: True
print(is_palindrome("hello"))  # Output: False


02. Word Frequency Counter:


Description: Create a program that takes a text file as input and counts the frequency of each word in the file.


def word_frequency(file_path):
    with open(file_path, 'r') as file:
        text = file.read().lower()
        words = text.split()
        word_count = {}
        for word in words:
            word_count[word] = word_count.get(word, 0) + 1
    return word_count

# Test the function
file_path = 'sample.txt'
word_count = word_frequency(file_path)
print(word_count)


03. Guess the Number Game:


Description: Develop a simple game where the computer randomly generates a number, and the user tries to guess it.

import random

def guess_the_number():
    target_number = random.randint(1, 100)
    attempts = 0
    while True:
        guess = int(input("Guess the number (1-100): "))
        attempts += 1
        if guess == target_number:
            print(f"Congratulations! You guessed the number in {attempts} attempts.")
            break
        elif guess < target_number:
            print("Try a higher number.")
        else:
            print("Try a lower number.")

# Test the game
guess_the_number()


04. Contact Book:


Description: Build a contact management application that allows users to add, view, search, and delete contacts.


class ContactBook:
    def __init__(self):
        self.contacts = {}
    
    def add_contact(self, name, phone):
        self.contacts[name] = phone
    
    def view_contacts(self):
        for name, phone in self.contacts.items():
            print(f"{name}: {phone}")
    
    def search_contact(self, name):
        if name in self.contacts:
            return self.contacts[name]
        else:
            return "Contact not found."
    
    def delete_contact(self, name):
        if name in self.contacts:
            del self.contacts[name]
            print(f"{name} has been deleted from contacts.")
        else:
            print(f"{name} not found in contacts.")

# Test the ContactBook class
contacts = ContactBook()
contacts.add_contact("John", "1234567890")
contacts.add_contact("Alice", "9876543210")
contacts.view_contacts()
print(contacts.search_contact("John"))
contacts.delete_contact("Alice")
contacts.view_contacts()


05. File Encryption/Decryption:


Description: Create a program that encrypts and decrypts a file using a simple encryption algorithm.


def encrypt_file(file_path):
    with open(file_path, 'r') as file:
        text = file.read()
        encrypted_text = ''.join(chr(ord(c) + 1) for c in text)
    with open(f'{file_path}.enc', 'w') as encrypted_file:
        encrypted_file.write(encrypted_text)

def decrypt_file(encrypted_file_path):
    with open(encrypted_file_path, 'r') as encrypted_file:
        encrypted_text = encrypted_file.read()
        decrypted_text = ''.join(chr(ord(c) - 1) for c in encrypted_text)
    with open(f'{encrypted_file_path[:-4]}.dec', 'w') as decrypted_file:
        decrypted_file.write(decrypted_text)

# Test the encryption and decryption functions
file_path = 'data.txt'
encrypt_file(file_path)
decrypt_file(f'{file_path}.enc')


06. Web Scraping and Data Visualization:


Description: Write a script that scrapes data from a website and creates visualizations using libraries like Matplotlib.
(Note: This project may require you to select a specific website for scraping and installing necessary libraries.)


# Example web scraping with BeautifulSoup:
import requests
from bs4 import BeautifulSoup

url = 'https://example.com'
response = requests.get(url)
soup = BeautifulSoup(response.text, 'html.parser')
# ... extract data from the website and create visualizations with Matplotlib or other libraries.


07. Rock, Paper, Scissors Game:



Description: Develop a command-line game where the user plays against the computer in the classic rock-paper-scissors.


import random

def rock_paper_scissors():
    choices = ["rock", "paper", "scissors"]
    computer_choice = random.choice(choices)
    user_choice = input("Enter your choice (rock/paper/scissors): ").lower()
    if user_choice not in choices:
        print("Invalid choice.")
    else:
        print(f"Computer chose: {computer_choice}")
        if user_choice == computer_choice:
            print("It's a tie!")
        elif (
            (user_choice == "rock" and computer_choice == "scissors") or
            (user_choice == "paper" and computer_choice == "rock") or
            (user_choice == "scissors" and computer_choice == "paper")
        ):
            print("You win!")
        else:
            print("Computer wins!")

# Test the game
rock_paper_scissors()


08. Weather Forecast Telegram Bot:


Description: Build a Telegram bot that provides weather forecasts for a given location using an API.
(Note: This project may require you to create a Telegram bot and obtain an API key for weather data.)


# Example Telegram bot using the 'python-telegram-bot' library:
from telegram import Update
from telegram.ext import Updater, CommandHandler

def start(update: Update, _) -> None:
    update.message.reply_text("Hello! I am your Weather Forecast Bot.")

def weather(update: Update, _) -> None:
    location = update.message.text.split()[1]
    # Fetch weather data using API and send the forecast back to the user.
    update.message.reply_text(f"Weather forecast for {location}: ...")

# Set up the bot and handlers
updater = Updater("YOUR_TELEGRAM_BOT_TOKEN", use_context=True)
dispatcher = updater.dispatcher
dispatcher.add_handler(CommandHandler("start", start))
dispatcher.add_handler(CommandHandler("weather", weather))

# Start the bot
updater.start_polling()
updater.idle()


09. URL Status Checker:

Description: Create a script that checks the status codes of a list of URLs to identify broken or inaccessible links.


import requests

def check_url_status(url_list):
    for url in url_list:
        try:
            response = requests.head(url)
            status_code = response.status_code
            if status_code == 200:
                print(f"{url} is accessible.")
            else:
                print(f"{url} is not accessible. Status code: {status_code}")
        except requests.exceptions.RequestException:
            print(f"{url} is not accessible.")

# Test the function
urls = ["https://example.com", "https://google.com", "https://nonexistent.com"]
check_url_status(urls)


10. Currency Exchange Rate Calculator:


Description: Write a program that fetches exchange rates from an API and calculates currency conversions.
(Note: This project may require you to choose a specific currency exchange rate API.)

import requests

def get_exchange_rate(base_currency, target_currency):
    url = f'https://api.example.com/rates?base={base_currency}&symbols={target_currency}'
    response = requests.get(url)
    data = response.json()
    return data['rates'][target_currency]

def currency_converter(amount, base_currency, target_currency):
    exchange_rate = get_exchange_rate(base_currency, target_currency)
    converted_amount = amount * exchange_rate
    return converted_amount

# Test the currency_converter function
amount = 100
base_currency = 'USD'
target_currency = 'EUR'
converted_amount = currency_converter(amount, base_currency, target_currency)
print(f"{amount} {base_currency} is equal to {converted_amount:.2f} {target_currency}")


Remember to install any required libraries (e.g., BeautifulSoup, python-telegram-bot) using pip before running the scripts. Happy coding!

Comments

Popular posts from this blog

How to Fix datetime Import Error in Python Quickly

Explained Ideal Structure of Python Class

How to Check Kafka Available Brokers