Dev Duel

Python Challenges

Sharpen syntax, loops, functions, lists, dictionaries, and more.

Filter challenges

Narrow down by difficulty or category.

Showing 80 of 80 challenges

All challenges

Practice concepts, improve problem-solving, and build confidence.

beginner7 minutes

Count Even Numbers

Count how many even numbers appear in a list.

loopsloopsconditionals
beginner10 minutes

Sum All Odd Numbers in a List

Write a function that calculates the sum of all odd numbers in a given list of integers.

functionsloopsconditional statements
advanced15 minutes

Fix Bug in Complex Recursive Depth-First Search Algorithm for Graph Cycle Detection

Identify and correct the logical errors in a recursive depth-first search (DFS) implementation designed to detect cycles in a directed graph. The provided code attempts to return True if a cycle exists, but it fails in some cases. Your task is to debug and fix the code while preserving its overall structure and efficiency.

debugginggraph theorydepth-first search
advanced10 minutes

Predict the Output of a Recursive Generator with Complex State

Analyze the output of a Python function that uses recursion, generators, and mutable state to yield a sequence of numbers based on intricate control flow.

logicrecursiongenerators
beginner10 minutes

Build a Function to Check Even or Odd Numbers

Create a simple Python function that takes an integer as input and returns whether the number is 'Even' or 'Odd'. This helps beginners practice conditionals and function definitions.

functionsfunctionsconditionals
advanced15 minutes

Fix the Infinite Recursion Bug in a Python Memoization Function

Identify and fix a subtle bug causing infinite recursion in a Python function designed to compute Fibonacci numbers with memoization. The code uses a dictionary cache but incorrectly implements memoization logic, leading to recursion errors. Your task is to debug the function to correctly utilize memoization and efficiently compute Fibonacci values.

debuggingrecursionmemoization
intermediate10 minutes

Refactor and Simplify Nested Loops for Data Aggregation

Improve the structure and readability of a Python function that aggregates sales data from multiple stores and products, while preserving its original behavior.

code-qualityrefactoringnested loops
intermediate10 minutes

Predict the Output of Nested List Comprehensions with Conditional Logic

Analyze nested list comprehensions with conditional statements and predict the final output of the given Python code snippet.

logiclist comprehensionsconditional expressions
advanced15 minutes

Build a Decorator to Cache Function Results with Expiry

Create a Python decorator function that caches the results of an expensive function call, with support for automatic expiration of cached values after a given time-to-live (TTL).

functionsdecoratorscaching
intermediate10 minutes

Predict the Output: List and Dictionary Comprehension Logic

Analyze the given Python code containing nested list and dictionary comprehensions along with conditional logic, and predict the exact output it produces.

logicdictionary comprehensionlist comprehension
advanced10 minutes

Predict the Output of Recursive Memoized Logic on Nested Tuples

Analyze a Python function that performs recursive computations with memoization on a nested tuple input. Predict the final output when the function is called with a complex nested structure.

logicrecursionmemoization
intermediate30 minutes

Build a Movie Recommendation Engine Based on User Ratings

Create a Python mini-project that recommends movies to a user based on their past ratings and similarity to other users' ratings. Implement basic collaborative filtering logic without external libraries.

mini-projectscollaborative filteringmatrix operations
beginner10 minutes

Refactor Messy Code to Improve Readability and Maintainability

You are given a Python function that calculates the sum of even numbers from a list. The current implementation works correctly but is hard to read and maintain. Your task is to refactor the code to make it cleaner and more Pythonic while keeping the behavior the same.

code-qualityfunctionsloops
intermediate10 minutes

Create a Function to Calculate Moving Average of a List

Write a Python function that computes the moving average over a specified window size for a list of numerical values.

functionslist slicingloops
advanced15 minutes

Refactor Legacy Data Processor for Improved Readability and Performance

You are provided with a legacy Python function that processes a list of user records to generate a summary report. Although the function works correctly, it is difficult to read, contains redundant computations, and has inefficient constructs. Your task is to refactor this code to improve readability, maintain the same behavior, and optimize performance while adhering to Python best practices.

code-qualitycode refactoringperformance optimization
intermediate10 minutes

Refactor Nested Loops and Conditionals for Student Grade Processing

Improve the readability and efficiency of a Python function that processes student grades to calculate averages and determine pass/fail status.

code-qualityrefactoringlist comprehensions
beginner10 minutes

Fix the Bug in the Sum of Even Numbers Function

A simple Python function is intended to sum all even numbers from a list, but it contains a bug. Your task is to identify and fix the bug so the function returns the correct sum of even numbers.

debuggingmodulus operatorfor loops
advanced15 minutes

Refactor and Optimize Complex Data Processing Function

Given a large-function script that processes a nested data structure with redundant loops and poor readability, refactor the code to improve maintainability, reduce complexity, and optimize performance without changing its output.

code-qualitycode refactoringperformance optimization
intermediate10 minutes

Build a Expense Tracker with Category Summaries

Create a Python function that manages a list of expenses and produces a summary by category, enabling users to track their spending habits effectively.

mini-projectsdictionarieslist iteration
intermediate10 minutes

Build a Function to Flatten a Nested List of Integers

Create a Python function that takes a nested list of integers and returns a flat list containing all the integers in their original order.

functionsrecursionlist manipulation
intermediate10 minutes

Predict the Output of a Nested List and Dictionary Manipulation

Analyze the given Python code that manipulates nested lists and dictionaries, and predict its exact printed output.

logicmutable objectslist and dictionary references
advanced15 minutes

Build a Function to Serialize and Deserialize Nested Dictionaries with Custom Rules

Create a Python function to serialize a nested dictionary into a custom string format and another function to revert it back, handling complex nesting and type conversions.

functionsrecursionstring parsing
intermediate10 minutes

Refactor and Improve Readability of a Data Filtering Function

Refactor a given Python function that filters and processes a list of dictionaries to improve its code quality, readability, and maintainability without altering its output behavior.

code-qualitycode refactoringlist comprehensions
advanced90 minutes

Advanced Data Pipeline: Build a Custom ETL Framework in Python

Create a scalable, modular Extract-Transform-Load (ETL) mini-project that reads data from multiple formats, applies complex transformations, and loads the result into a target data structure.

mini-projectsETL pipeline designmodular programming
beginner10 minutes

Predict the Output of a Simple Number Check Function

Analyze a Python function that checks if a number is positive, negative, or zero, and predict its output for given inputs.

logicconditionalsfunctions
intermediate10 minutes

Refactor a Function to Cleanly Process and Summarize Sales Data

Improve the clarity, efficiency, and readability of a Python function that processes a list of sales records and returns a summary of total sales by product category.

code-qualitydata aggregationdictionary operations
intermediate15 minutes

Build a Personal Expense Tracker Mini Project

Create a Python program that allows users to add, view, and analyze their personal expenses over time, helping them track spending habits.

mini-projectslists and dictionariesloop and conditionals
beginner10 minutes

Create a Function to Calculate the Square of a Number

Write a Python function that takes a single number as input and returns its square. This is a fundamental exercise to practice defining functions and using arithmetic operators.

functionsfunctionsarithmetic operators
beginner10 minutes

Fix the Bug in Function to Calculate Total Price with Tax

A simple Python function is intended to calculate the total price of an item after adding tax. However, the function contains a bug causing incorrect results. Your task is to find and fix the bug so the function returns the correct total price.

debuggingbasic arithmetic operationsfunction definitions
beginner10 minutes

Create a Simple To-Do List Manager

Build a basic to-do list manager function that allows adding tasks, marking them as complete, and viewing remaining tasks.

mini-projectslistsdictionaries
intermediate10 minutes

Refactor a Function to Compute Unique Elements Frequency

Improve the provided Python function that calculates the frequency of unique elements in a list. Refactor the code for better readability, efficiency, and Pythonic style without changing its behavior.

code-qualitydictionarycollections.Counter
advanced15 minutes

Build a High-Performance Memoized Recursive Function for Multivariate Fibonacci Sequence

Create a Python function that computes terms of a custom multivariate Fibonacci sequence with dynamic step parameters and optimized with memoization for high performance.

functionsrecursionmemoization
intermediate10 minutes

Fix Bug in List Squaring Function with Incorrect Loop

This debugging challenge requires identifying and fixing a bug in a Python function that squares each element of a list but returns incorrect results due to loop errors.

debuggingloopslists
intermediate15 minutes

Build a Task Manager CLI Application in Python

Create a command-line task manager in Python that allows users to add, complete, delete, and list tasks with due dates and priorities.

mini-projectsdatetime handlinglist sorting
intermediate10 minutes

Build a Function to Group and Summarize Sales Data by Category

Create a Python function that takes a list of sales records and returns a summary dictionary grouping total sales by product category.

functionsdictionaryloops
beginner10 minutes

Refactor Messy Code to Calculate the Sum of Even Numbers

Improve the readability and quality of a Python function that calculates the sum of even numbers from a list, while keeping the output correct.

code-qualityloopsconditionals
advanced45 minutes

Build a Concurrent Task Scheduler with Priority Queues

Create a Python mini-project that simulates a concurrent task scheduler managing tasks with different priorities. The scheduler should execute tasks in priority order and support concurrent execution with a fixed number of worker threads.

mini-projectsthreadingpriority queue
intermediate15 minutes

Expense Tracker CLI Application

Build a command-line expense tracker application in Python that allows users to add, view, and categorize their expenses. The program should support adding multiple expenses, filtering expenses by category, and displaying the total amount spent.

mini-projectsfunctionslists
advanced10 minutes

Predict the Output of Nested Generator and Coroutine Logic in Python

Analyze a complex Python function that uses nested generators, coroutines, and yield expressions to predict its output. This challenge tests your understanding of Python's generator mechanics and flow control.

logicgeneratorscoroutines
advanced60 minutes

Advanced Social Network Graph Analyzer in Python

Build a Python mini-project that processes and analyzes a social network graph to extract insights such as influential users, community detection, and shortest connection paths.

mini-projectsGraph Data StructuresGraph Algorithms
advanced10 minutes

Predict the Output of a Recursive Memoization with Mutable Default Argument

Analyze a Python function that uses recursion combined with mutable default arguments and memoization, then predict the exact printed output when the function is called.

logicRecursionMemoization
intermediate10 minutes

Build a Python Expense Tracker with Categorization and Summaries

Create a Python mini-project to manage daily expenses, categorize them, and generate summary reports for monthly spending by category.

mini-projectslistsdictionaries
advanced15 minutes

Fix Bug in Parallel Fibonacci Computation with Memoization

Debug and fix the given Python code that aims to compute Fibonacci numbers efficiently using recursion with memoization and parallel execution. The current implementation has subtle bugs causing incorrect results and inefficient execution.

debuggingrecursionmemoization
advanced15 minutes

Refactor Complex Data Aggregation for Readability and Performance in Python

You are given a Python function that processes a nested list of sales data to compute total sales per product category, but the code is messy, hard to read, and inefficient. Refactor the function to improve code quality without changing its behavior.

code-qualitycode refactoringdictionary aggregation
intermediate10 minutes

Refactor Nested Loops to Improve Code Readability and Efficiency

Refactor the given Python function that uses nested loops to find common elements between two lists. Improve its readability and performance without changing its behavior.

code-qualityrefactoringperformance optimization
advanced10 minutes

Predict the Output of Recursive Nested Dictionary Merge with Side Effects

Analyze the given Python function that performs a recursive merge of nested dictionaries with side effects on mutable inputs. Predict the exact output of the code including the final printed dictionaries.

logicrecursiondictionary mutation
advanced15 minutes

Build a High-Performance Memoized Fibonacci Function with Custom Cache Size

Create an advanced Python function to compute Fibonacci numbers using memoization with a customizable cache size limit, evicting oldest cached values when the cache exceeds the limit. The function should be optimized for both speed and memory usage.

functionsmemoizationLRU cache
beginner10 minutes

Build a Simple Grocery List Manager

Create a Python program that allows users to add items to a grocery list, remove items, and display the current list. This mini-project helps beginners practice working with lists, loops, and functions.

mini-projectslistsloops
intermediate10 minutes

Build a Function to Merge and Sort Unique Elements from Two Lists

Create a Python function that takes two lists of integers and returns a sorted list containing all unique elements from both lists.

functionslist manipulationsets
advanced60 minutes

Advanced Expense Tracker CLI with Data Persistence and Reporting

Build a command-line Python application that allows users to add, update, delete, and categorize expenses. Implement data persistence using JSON files and generate summary reports on spending by category and date range.

mini-projectsfile handlingdata persistence
advanced60 minutes

Advanced Text Summarizer Using TF-IDF and Cosine Similarity

Build a Python function that performs extractive text summarization by selecting the most important sentences based on TF-IDF vectors and sentence similarity measures.

mini-projectsText preprocessingTF-IDF vectorization
beginner10 minutes

Fix the Bug in Calculating the Sum of List Elements

Help correct the given Python function that is supposed to calculate the sum of all elements in a list but currently returns incorrect output due to a logic error.

debuggingloopsvariables
intermediate10 minutes

Refactor a Function for Summarizing Employee Sales Data

Improve the readability and efficiency of a given Python function that processes a list of employee sales records and returns a summary dictionary.

code-qualityrefactoringdictionary operations
advanced10 minutes

Predict Output of Recursive Python Function with Mutable Default Arguments

Analyze the output of an advanced recursive Python function that uses mutable default arguments and in-place list modifications to understand how state is preserved and mutated across recursive calls.

logicrecursionmutable default arguments
intermediate15 minutes

Build a Task Progress Tracker with Status Summary

Create a Python function to track the progress of multiple tasks with varying statuses and provide a summary of counts per status.

mini-projectsdictionarieslist iteration
advanced15 minutes

Fix Bug in Concurrent Rate Limiter Implementation

Given a broken Python implementation of a token bucket rate limiter intended to handle concurrent requests with thread safety, identify and fix the bugs causing incorrect rate limiting behavior and race conditions.

debuggingthreadingconcurrency
advanced15 minutes

Fix Bug in Recursive Function to Calculate Maximum Path Sum in Binary Tree

The provided Python function aims to find the maximum path sum in a binary tree, where a path can start and end at any node. However, the current implementation contains bugs that lead to incorrect results and runtime errors. Your task is to identify and fix these bugs, ensuring the function correctly computes the maximum path sum.

debuggingrecursionbinary tree
advanced10 minutes

Predict Output for Recursive State Machine with Complex Memoization

Analyze a recursive function that behaves like a state machine with memoization to predict the final output of given input values.

logicrecursionmemoization
beginner10 minutes

Refactor a Simple Temperature Converter Function

Improve the readability and efficiency of a basic Python function that converts temperatures from Celsius to Fahrenheit.

code-qualityfunction refactoringbasic arithmetic operations
intermediate10 minutes

Fix the Off-By-One Error in List Processing Function

Identify and fix the bug in a Python function designed to process a list of numbers and return a transformed list. The current implementation has an off-by-one error causing incorrect output.

debugginglist indexingloops
advanced15 minutes

Fix the Bug in the Optimized LRU Cache Implementation

Identify and fix the subtle bug in the provided Least Recently Used (LRU) cache implementation which causes it to fail under certain eviction conditions. The solution must maintain O(1) time complexity for get and put operations while correctly managing the cache size and order.

debuggingdata structureslinked list
advanced90 minutes

Build a Scalable URL Shortener Service in Python

Create a mini-project to develop a URL shortener service that generates unique short URLs, supports custom aliases, and includes analytics features such as click tracking and expiration dates.

mini-projectsHashing and encoding techniquesData structures and mappings
advanced15 minutes

Fix the Memory Leak in a Recursive Fibonacci with Memoization

Identify and fix the bug in a recursive Fibonacci function that uses memoization but causes unintended memory growth or incorrect results due to faulty cache handling.

debuggingrecursionmemoization
beginner10 minutes

Refactor a Function to Calculate Factorial More Cleanly

Improve the clarity and simplicity of a provided factorial function without changing its behavior. Practice writing clean and readable Python code.

code-qualityfunctionsloops
advanced15 minutes

Build a Memoized Recursive Fibonacci Function with Performance Tracking

Create a Python function to compute Fibonacci numbers using memoization to optimize recursive calls. Additionally, implement performance tracking to count how many times the function is called and how many cache hits occur.

functionsrecursionmemoization
beginner10 minutes

Fix the Bug in a Simple Even Number Checker

Identify and fix the bug in a Python function that is intended to check if a number is even.

debuggingmodulus operatorif conditionals
intermediate15 minutes

Create a Function to Find the Longest Palindromic Substring

Write a Python function that takes a string as input and returns the longest palindromic substring within it. A palindrome reads the same backward as forward. This intermediate challenge helps you practice string manipulation and algorithmic thinking.

functionsString manipulationTwo pointer technique
advanced15 minutes

Fix the Deadlock Bug in Concurrent Transaction Simulation

Identify and fix a concurrency deadlock bug in a Python simulation of database transactions using locks. The broken code attempts to simulate two concurrent transactions that acquire multiple locks and cause a deadlock, resulting in a hang. Your task is to fix the code to avoid deadlocks while preserving the transactional behavior.

debuggingConcurrencyThreading
advanced60 minutes

Advanced Task Scheduler: Build a Priority-based Task Manager in Python

Create a Python mini-project that manages a list of tasks with start times, durations, and priorities, optimizing scheduling to avoid conflicts based on priority and timing.

mini-projectsdatetime manipulationtask scheduling
beginner10 minutes

Simple Budget Tracker Mini Project

Create a basic budget tracker that lets users add income, add expenses, and get their current balance. This beginner-friendly mini project practices using functions, variables, conditionals, and loops.

mini-projectsloopsconditionals
advanced15 minutes

Fix Bug in Efficient Large-Scale Matrix Multiplication

Identify and fix a subtle bug in an optimized Python function designed to multiply large matrices efficiently using NumPy, without changing overall approach or reducing performance.

debuggingmatrix multiplicationnumpy operations
advanced15 minutes

Fix Bug in Advanced Recursive Directory Size Calculator

Debug and correct a broken Python function designed to recursively compute total file sizes in nested directory structures represented as dictionaries.

debuggingrecursiontype checking
advanced40 minutes

Build a Scalable Task Scheduler with Dependency Resolution in Python

Create a mini-project in Python to implement a task scheduler that executes tasks in the correct order based on their dependencies. The scheduler should detect circular dependencies and optimize for concurrent execution where possible.

mini-projectstopological sortgraph algorithms
intermediate10 minutes

Predict the Output of a List Comprehension with Nested Conditions

Analyze a Python code snippet using nested list comprehensions with conditional statements and predict the final output list.

logiclist comprehensionnested loops
intermediate10 minutes

Refactor a Function to Calculate Average Temperatures with Clean Code Practices

Improve the readability, efficiency, and maintainability of a messy Python function that calculates the average temperature from a list of daily readings.

code-qualitycode refactoringPython built-ins
advanced10 minutes

Predict the Output of a Recursive Function with Memoization and Complex State Updates

Analyze the given Python code implementing a recursive function with memoization and state-dependent logic updates, then predict the final printed output.

logicRecursionMemoization
advanced15 minutes

Build a Memoized Recursive Function to Calculate the nth Generalized Fibonacci Number

Create a function that efficiently computes the nth term of a generalized Fibonacci sequence, where the first k terms are given and each subsequent term is the sum of the previous k terms. Implement memoization to optimize the recursive calculations.

functionsrecursionmemoization
beginner10 minutes

Fix the Sum Calculation Bug in a List of Numbers

A beginner-level debugging challenge to fix a Python function that is supposed to calculate the sum of a list of numbers but currently returns an incorrect result.

debuggingloopsvariables
advanced15 minutes

Fix Bug in Advanced Memoized Recursive Fibonacci Implementation

Identify and fix the bug in a recursive Fibonacci function optimized with memoization to achieve efficient performance for large input values.

debuggingmemoizationrecursion
intermediate10 minutes

Build a Function to Flatten Nested Lists by One Level

Create a Python function that takes a list containing nested sublists and returns a new list flattened by exactly one level. This means only the first level of nested lists should be expanded, while deeper nested structures remain intact.

functionslist manipulationtype checking