Coding exercises for every day

Small exercises for everyone who knows the basics of Python or JavaScript and wants to keep practicing. Each takes 10 to 20 minutes. Try it yourself first, then open the solution.

Python exercises

Lists, strings and dictionaries: the tools you use in Python every day.

1. Count words

Easy

Write a function count_words(text) that counts how often each word appears in a text. Upper and lower case don't matter.

Example: count_words("The dog chased the ball") returns {"the": 2, "dog": 1, "chased": 1, "ball": 1}

Tip: text.lower().split() gives you the words, a dictionary keeps the count.

Show solution
def count_words(text):
    counts = {}
    for word in text.lower().split():
        counts[word] = counts.get(word, 0) + 1
    return counts

Shorter with collections.Counter: Counter(text.lower().split()).

2. Spot a palindrome

Easy

Write is_palindrome(text) that checks whether a sentence reads the same forwards and backwards. Spaces and upper and lower case don't count.

Example: is_palindrome("Never odd or even") returns True

Tip: Keep only letters and digits and compare the list with its reverse [::-1].

Show solution
def is_palindrome(text):
    letters = [c for c in text.lower() if c.isalnum()]
    return letters == letters[::-1]

3. Check a password

Medium

Write check_password(password) that returns a list of all problems: shorter than 8 characters, no digit, no uppercase letter. A good password returns an empty list.

Example: check_password("hello1") returns ["too short", "no uppercase letter"]

Tip: any() with c.isdigit() or c.isupper() checks whether at least one character matches.

Show solution
def check_password(password):
    problems = []
    if len(password) < 8:
        problems.append("too short")
    if not any(c.isdigit() for c in password):
        problems.append("no digit")
    if not any(c.isupper() for c in password):
        problems.append("no uppercase letter")
    return problems

4. Sum up purchases

Medium

You have a list of purchases as pairs of product and price. Write summarize(purchases) that adds up the total per product and sorts the result by total, highest first.

Example: summarize([("bread", 2.5), ("milk", 1.2), ("bread", 2.5)]) returns [("bread", 5.0), ("milk", 1.2)]

Tip: Add everything up in a dictionary first, then use sorted() with key and reverse=True.

Show solution
def summarize(purchases):
    totals = {}
    for product, price in purchases:
        totals[product] = totals.get(product, 0) + price
    return sorted(totals.items(), key=lambda pair: pair[1], reverse=True)

JavaScript exercises

Small tasks like the ones that come up in real projects all the time. You can test everything right in your browser console.

5. Make initials

Easy

Write initials(name) that turns a full name into its initials in capital letters. Extra spaces shouldn't break it.

Example: initials("ada lovelace") returns "AL"

Tip: trim(), then split(/\s+/) and take the first letter of each part.

Show solution
function initials(name) {
  return name
    .trim()
    .split(/\s+/)
    .map((part) => part[0].toUpperCase())
    .join('');
}

6. Remove duplicates

Easy

Write unique(list) that removes duplicate values from an array and keeps the order.

Example: unique([3, 1, 3, 2, 1]) returns [3, 1, 2]

Tip: A Set stores every value only once and keeps the order in which values first appeared.

Show solution
function unique(list) {
  return [...new Set(list)];
}

7. Seconds as a clock

Medium

Write formatTime(seconds) that shows seconds as hours, minutes and seconds. Below one hour, the hours are left out.

Example: formatTime(3725) returns "1:02:05", formatTime(125) returns "2:05"

Tip: Math.floor and % split the number, padStart(2, '0') turns 5 into 05.

Show solution
function formatTime(seconds) {
  const h = Math.floor(seconds / 3600);
  const m = Math.floor((seconds % 3600) / 60);
  const s = seconds % 60;
  const pad = (n) => String(n).padStart(2, '0');
  return h > 0 ? `${h}:${pad(m)}:${pad(s)}` : `${m}:${pad(s)}`;
}

8. Group by a property

Medium

Write groupBy(items, key) that groups a list of objects by the value of one property.

Example: groupBy([{ name: "apple", type: "fruit" }, { name: "leek", type: "vegetable" }], "type") returns { fruit: [{ name: "apple", type: "fruit" }], vegetable: [{ name: "leek", type: "vegetable" }] }

Tip: Start with an empty object and create an empty array for every new value.

Show solution
function groupBy(items, key) {
  const groups = {};
  for (const item of items) {
    const value = item[key];
    if (!groups[value]) groups[value] = [];
    groups[value].push(item);
  }
  return groups;
}

Current browsers and Node also have Object.groupBy(items, (item) => item[key]) for this.

Algorithm exercises

This is about the approach, not the language. That's why the solutions come in Python and in JavaScript.

9. Binary search

Medium

Write a function that finds the index of a number in a sorted list without going through the list from start to end. If the number isn't there, return -1.

Example: binary_search([1, 3, 5, 7, 9], 7) returns 3

Tip: Look in the middle. If the number there is too small, keep searching only on the right, otherwise on the left.

Show solution
def binary_search(items, target):
    low, high = 0, len(items) - 1
    while low <= high:
        mid = (low + high) // 2
        if items[mid] == target:
            return mid
        if items[mid] < target:
            low = mid + 1
        else:
            high = mid - 1
    return -1
function binarySearch(items, target) {
  let low = 0;
  let high = items.length - 1;
  while (low <= high) {
    const mid = Math.floor((low + high) / 2);
    if (items[mid] === target) return mid;
    if (items[mid] < target) low = mid + 1;
    else high = mid - 1;
  }
  return -1;
}

With a million entries, about 20 comparisons are enough.

10. Two numbers to a sum

Medium

Find the two numbers in a list that add up to a target sum and return their indices. Try to do it in a single pass through the list.

Example: two_sum([2, 7, 11, 15], 9) returns [0, 1]

Tip: Keep every number you've seen in a dictionary. If target - number is already in it, you're done.

Show solution
def two_sum(numbers, target):
    seen = {}
    for i, n in enumerate(numbers):
        if target - n in seen:
            return [seen[target - n], i]
        seen[n] = i
    return None
function twoSum(numbers, target) {
  const seen = new Map();
  for (let i = 0; i < numbers.length; i++) {
    const rest = target - numbers[i];
    if (seen.has(rest)) return [seen.get(rest), i];
    seen.set(numbers[i], i);
  }
  return null;
}

Two nested loops work too, but take much longer on long lists.

11. Check brackets

Medium

Check whether all brackets (), [] and {} in a text are closed correctly, including nested ones.

Example: is_balanced("(a[b]{c})") returns True, is_balanced("(]") returns False

Tip: Put every opening bracket on a stack. For a closing one, the matching opening bracket has to be on top.

Show solution
def is_balanced(text):
    pairs = {")": "(", "]": "[", "}": "{"}
    stack = []
    for c in text:
        if c in "([{":
            stack.append(c)
        elif c in pairs:
            if not stack or stack.pop() != pairs[c]:
                return False
    return not stack
function isBalanced(text) {
  const pairs = { ')': '(', ']': '[', '}': '{' };
  const stack = [];
  for (const c of text) {
    if ('([{'.includes(c)) stack.push(c);
    else if (c in pairs && stack.pop() !== pairs[c]) return false;
  }
  return stack.length === 0;
}

12. Group anagrams

Tricky

Group a list of words so that words made of the same letters end up together.

Example: group_anagrams(["listen", "silent", "rat", "tar", "art", "house"]) returns [["listen", "silent"], ["rat", "tar", "art"], ["house"]]

Tip: Sort the letters of a word and all its anagrams look the same. That's your key.

Show solution
def group_anagrams(words):
    groups = {}
    for word in words:
        key = "".join(sorted(word))
        groups.setdefault(key, []).append(word)
    return list(groups.values())
function groupAnagrams(words) {
  const groups = new Map();
  for (const word of words) {
    const key = [...word].sort().join('');
    if (!groups.has(key)) groups.set(key, []);
    groups.get(key).push(word);
  }
  return [...groups.values()];
}

How to practice well

Yourself first, then the solution

Even half an attempt teaches you more than looking right away. If you get stuck, read the tip.

Timer on 20 minutes

A fixed end keeps the exercise small. Whatever you don't finish in time, you look at in the solution.

Rebuild, don't copy

Read the solution, close it and write it again from memory. That's how it sticks.

One exercise a day

Small, regular exercises keep your knowledge fresh, much better than one long day a month.

Frequently asked questions

Who are these exercises for?

For everyone who already knows the basics: variables, loops, functions and lists. The exercises don't teach you a language from scratch, they help you practice regularly.

How can I try the code?

Python runs in any terminal with Python installed or in an online editor. You can test JavaScript right in your browser console, which opens with F12.

How often should I practice coding?

Rather 20 minutes every day than a whole day once a month. That way what you've learned stays in your head.

What are algorithm exercises good for?

They train the approach independent of the language: searching, counting, comparing. Exactly these kinds of tasks come up in many job interviews.

Is there an app with daily coding exercises?

Yes, FlowStart gives you a new exercise in Python, JavaScript or algorithms every day, at the level you choose. Try it free for 7 days.

A new exercise every day

FlowStart gives you a coding exercise every day that fits into your routine. Join the waitlist and we'll let you know as soon as the app is out.