Skip to main content
Noble Desktop/2 min read

Anagrams with Python

Python Essentials

Data Types

int, float, str, list, dict, set, tuple — the basic vocabulary.

Control Flow

if/elif/else, for, while — the logic of any program.

Functions

def, return, *args, **kwargs — reusable units of behavior.

Modules & Imports

import statements, packages, virtual environments.

Master Python at Noble Desktop

Noble Desktop's Python Programming Immersive covers AI APIs, data analysis, and modern Python development.

In this video, we're going to look at how to solve a popular problem called anagrams with Python

Video Transcription

My name is Art, and I teach Python at Noble Desktop. In this video, I'm going to show you how to solve a very popular problem called anagrams. What are anagrams? Anagrams would be words that have the same count of letters. So, let me show you how you could solve this one.

First, let's create a variable name 'word' and ask a user for input. So, we would say something like, "Give me a word." When we get this word, we need to use a for loop for letters in the word and then initialize a dictionary with curly brackets. Each letter will be a key and the number of times we see that letter will be the value.

For example, if the letter is in the dictionary, then we'll do plus equal one to increase the value. If not, we'll just do dictionary letter one. To see what the dictionary looks like, run this and suppose we get apple. It creates a dictionary and counts how many times each letter appears in that word.

Now, since we want to compare two or more words, we need to wrap it as a function. Let's call this 'word to dictionary' and this function will take a word as an argument and return a dictionary. To compare these dictionaries, we need to pass a word by word and then compare them. If the dictionary from word one is the same as from the dictionary that we create from word two, then we could say, "Words are anagrams." Else, we want to print, "Words are not anagrams."

If we run it and do that, we get "Words are anagrams." Again, if you want to do something over and over again, wrap it as a function. What is a function? A function is a block of reusable code. Thank you.

Video Transcript7 sections

1Full Video Transcript

2Introduction to Anagrams

I teach Python, and in this video I'm going to show you how to solve a very popular problem called anagrams. So first of all, what are anagrams? Anagrams would be words that have the same count of letters. Let me show you how you could solve this one.