Experienced and passionate Software Engineer with a
demonstrated history of working in the full life cycle of
software development and implementation from identification of
user requirements, design, development, testing to maintenance
of a software. Open source enthusiast. Blogger. You can hire
him for different kinds of things.
Anagrams are strings that have the same letters but in a
different order for example
abc,
bca,
cab,
acb,
bac are all anagrams, since
they all contain the same letters.
We can check whether two strings are anagrams in Python in
different ways. One way to do that would be to use
Counter from the
collections module.
A Counter is a dict subclass for counting hashable objects. It is a collection where elements are stored as dictionary keys and their counts are stored as dictionary values. Counts are allowed to be any integer value including zero or negative counts. The Counter class is similar to bags or multisets in other languages.
In plain English, with
Counter, we can get a
dictionary that represents the frequency of elements in a
list. Let us see this in an example:
You have probably had the chance to iterate through a list of
elements in one way or another, or through elements of a set,
or a dictionary. We can go through a list, a set, or a
dictionary and access their elements because they are iterable
objects.
An iterator is an object that contains a countable number of
objects. This means that you can iterate through elements that
an iterator contains.
Dictionaries also known as maps are data structures that are
used a lot in different scenarios. The process of getting an
element from a dictionary can be done using an element that is
not part of the dictionary which results in an error.
For example, let us take this scenario where we have a
dictionary that has an element with the key
name and another one with
the element surname. If we
want to access it using another element, such as
age, we are going to see an
error like the following:
One of the common things that you can notice in many tasks is
the fact that you need to sort elements in a list. In fact,
this can also be part of an interview that you may go through
while applying for a job. Maybe not only sorting elements, but
sorting elements fulfilling certain conditions.
Similar to the case of using
any(), we can also use a
method that allows us to check whether all conditions are met.
This can also greatly reduce the complexity of the code since
you do not need to use multiple and checks.
Let us see this with an example.
Let us assume that we have the following conditions where we
are checking whether we have more than 50 points in each
school course:
Now passing all of them means that each condition should be
met. To help us with that, we can simply use
all(), as can be seen in
the following snippet: