Solve Problems by Coding Solutions - A Complete solution for python programming
Python is TIOBE's programming language of the year 2024!
Pomodoro Timer
import tkinter as tk
from tkinter import messagebox
import time
# Constants
WORK_MIN = 25 # Work duration in minutes
SHORT_BREAK_MIN = 5 # Short break duration in minutes
LONG_BREAK_MIN = 15 # Long break duration in minutes
CYCLES = 4 # Number of work sessions before a long break
class PomodoroTimer:
def __init__(self):
self.root = tk.Tk()
self.root.title("Pomodoro Timer")
self.timer_running = False
self.current_cycle = 0
self.time_left = 0
# UI Setup
self.label = tk.Label(self.root, text="Pomodoro Timer", font=("Arial", 20))
self.label.pack(pady=10)
self.time_label = tk.Label(self.root, text="00:00", font=("Arial", 40))
self.time_label.pack(pady=10)
self.start_button = tk.Button(self.root, text="Start", font=("Arial", 15), command=self.start_timer)
self.start_button.pack(side="left", padx=10)
self.reset_button = tk.Button(self.root, text="Reset", font=("Arial", 15), command=self.reset_timer)
self.reset_button.pack(side="right", padx=10)
def start_timer(self):
if not self.timer_running:
self.current_cycle += 1
if self.current_cycle % (CYCLES + 1) == 0:
self.time_left = LONG_BREAK_MIN * 60
self.label.config(text="Long Break", fg="blue")
elif self.current_cycle % 2 == 0:
self.time_left = SHORT_BREAK_MIN * 60
self.label.config(text="Short Break", fg="green")
else:
self.time_left = WORK_MIN * 60
self.label.config(text="Work", fg="red")
self.timer_running = True
self.countdown()
def countdown(self):
if self.time_left > 0:
mins, secs = divmod(self.time_left, 60)
self.time_label.config(text=f"{mins:02}:{secs:02}")
self.time_left -= 1
self.root.after(1000, self.countdown)
else:
self.timer_running = False
self.time_label.config(text="00:00")
if self.current_cycle % 2 != 0:
messagebox.showinfo("Time's up!", "Time for a break!")
else:
messagebox.showinfo("Time's up!", "Time to work!")
def reset_timer(self):
self.timer_running = False
self.current_cycle = 0
self.time_left = 0
self.label.config(text="Pomodoro Timer", fg="black")
self.time_label.config(text="00:00")
def run(self):
self.root.mainloop()
# Run the Pomodoro Timer
if __name__ == "__main__":
PomodoroTimer().run()
News Aggregator
your_newsapi_key in the code with your actual API key.
import requests
API_KEY = "your_newsapi_key" # Replace with your NewsAPI key
BASE_URL = "https://newsapi.org/v2/"
def fetch_top_headlines(country="us", category="general", page_size=5):
"""
Fetch top news headlines from NewsAPI.
Args:
country (str): Country code for news (default is 'us').
category (str): Category of news (default is 'general').
page_size (int): Number of headlines to fetch (default is 5).
Returns:
list: A list of dictionaries containing news headlines and details.
"""
url = f"{BASE_URL}top-headlines"
params = {
"apiKey": API_KEY,
"country": country,
"category": category,
"pageSize": page_size,
}
try:
response = requests.get(url, params=params)
response.raise_for_status()
data = response.json()
return data.get("articles", [])
except requests.exceptions.RequestException as e:
print(f"Error fetching news: {e}")
return []
def display_headlines(articles):
"""
Display news headlines in a user-friendly format.
Args:
articles (list): List of news articles.
"""
if not articles:
print("No news articles found.")
return
print("\n--- Latest News Headlines ---")
for idx, article in enumerate(articles, 1):
print(f"\n{idx}. {article['title']}")
print(f" Source: {article['source']['name']}")
print(f" URL: {article['url']}")
def main():
print("Welcome to the News Aggregator!")
country = input("Enter the country code for news (e.g., 'us' for USA, 'in' for India): ").strip()
category = input("Enter the category of news (e.g., 'business', 'entertainment', 'sports'): ").strip()
num_articles = input("How many articles would you like to fetch? (default is 5): ").strip()
# Default values if input is empty
country = country if country else "us"
category = category if category else "general"
num_articles = int(num_articles) if num_articles.isdigit() else 5
print("\nFetching top headlines...")
articles = fetch_top_headlines(country=country, category=category, page_size=num_articles)
display_headlines(articles)
if __name__ == "__main__":
main()
Stock Price Tracker
import yfinance as yf
import matplotlib.pyplot as plt
import pandas as pd
def get_stock_data(ticker, period='1mo', interval='1d'):
"""
Fetch stock data for a given ticker.
Args:
ticker (str): The stock ticker symbol.
period (str): The time period for historical data (e.g., '1mo', '1y').
interval (str): The interval for the data (e.g., '1d', '1h').
Returns:
pandas.DataFrame: Historical stock data.
"""
try:
stock = yf.Ticker(ticker)
data = stock.history(period=period, interval=interval)
return data
except Exception as e:
print(f"Error fetching data: {e}")
return None
def plot_stock_data(data, ticker):
"""
Plot stock closing price data.
Args:
data (pandas.DataFrame): Historical stock data.
ticker (str): The stock ticker symbol.
"""
if data is not None and not data.empty:
plt.figure(figsize=(10, 6))
plt.plot(data.index, data['Close'], label=f'{ticker} Closing Price')
plt.title(f"{ticker} Stock Price")
plt.xlabel("Date")
plt.ylabel("Closing Price")
plt.legend()
plt.grid()
plt.show()
else:
print("No data available to plot.")
def main():
print("Welcome to the Stock Price Tracker!")
ticker = input("Enter the stock ticker symbol (e.g., AAPL, TSLA, GOOGL): ").upper()
period = input("Enter the time period (default is '1mo', e.g., '1d', '1y'): ") or '1mo'
interval = input("Enter the data interval (default is '1d', e.g., '1h', '1wk'): ") or '1d'
print("\nFetching stock data...")
data = get_stock_data(ticker, period, interval)
if data is not None and not data.empty:
print("\nStock data fetched successfully!")
print(data.tail()) # Display the last 5 rows of data
plot_stock_data(data, ticker)
else:
print("Failed to fetch stock data. Please check the ticker symbol or try again.")
if __name__ == "__main__":
main()
Color Palette Generator
from PIL import Image
from sklearn.cluster import KMeans
import numpy as np
import matplotlib.pyplot as plt
def extract_colors(image_path, num_colors=5):
"""
Extracts dominant colors from an image.
Args:
image_path (str): Path to the image file.
num_colors (int): Number of dominant colors to extract.
Returns:
List of RGB tuples representing the dominant colors.
"""
try:
# Open the image and resize it for faster processing
image = Image.open(image_path)
image = image.resize((200, 200)) # Resize for faster processing
image_array = np.array(image)
# Reshape the image array to a 2D array of pixels
pixels = image_array.reshape(-1, 3)
# Apply KMeans clustering to find dominant colors
kmeans = KMeans(n_clusters=num_colors, random_state=0)
kmeans.fit(pixels)
# Extract cluster centers (dominant colors)
colors = kmeans.cluster_centers_.astype(int)
return colors
except Exception as e:
print(f"Error: {e}")
return []
def display_palette(colors):
"""
Displays the color palette using matplotlib.
Args:
colors (list): List of RGB tuples representing colors.
"""
if colors is None or len(colors) == 0:
print("No colors to display.")
return
# Create a palette image
palette = np.zeros((50, len(colors) * 50, 3), dtype=np.uint8)
for i, color in enumerate(colors):
palette[:, i * 50:(i + 1) * 50, :] = color
# Display the palette
plt.imshow(palette)
plt.axis("off")
plt.show()
def main():
print("Welcome to the Color Palette Generator!")
image_path = input("Enter the path to the image file: ")
num_colors = input("Enter the number of colors to extract (default is 5): ")
num_colors = int(num_colors) if num_colors.isdigit() else 5
print("\nExtracting colors...")
colors = extract_colors(image_path, num_colors)
if len(colors) > 0:
print("Dominant colors (RGB):")
for i, color in enumerate(colors, 1):
print(f"{i}: {tuple(color)}")
display_palette(colors)
if __name__ == "__main__":
main()