DEV Community

Programming Entry Level: how to algorithms

Understanding How to Algorithms for Beginners

So, you're starting your programming journey and keep hearing about "algorithms"? Don't worry, it sounds scarier than it is! Algorithms are simply a set of instructions for solving a problem. Think of it like a recipe – it tells you exactly what steps to take to get a desired result. Understanding algorithms is crucial for becoming a better programmer, writing efficient code, and even acing technical interviews. Many interview questions revolve around your ability to think algorithmically, so getting a grasp on the basics now will pay off big time.

Understanding "How to Algorithms"

At its core, an algorithm is a process. It's a step-by-step procedure for accomplishing a task. Let's use a real-world example: making a cup of tea.

  1. Boil water.
  2. Put a tea bag in a cup.
  3. Pour the boiling water into the cup.
  4. Let it steep for 3-5 minutes.
  5. Add milk and sugar (optional).

That's an algorithm! It's a defined sequence of actions that, when followed, results in a cup of tea.

In programming, algorithms are written in code. They take input, process it, and produce output. The goal is to write algorithms that are efficient – meaning they solve the problem correctly and use resources (like time and memory) wisely.

You can visualize a simple algorithm like this:

graph TD
    A[Start] --> B{Input Data};
    B --> C{Process Data};
    C --> D{Output Result};
    D --> E[End];
Enter fullscreen mode Exit fullscreen mode

This diagram shows the basic flow: start, get input, process it, get output, and finish. Algorithms can be much more complex, involving loops, conditions, and different data structures, but this is the fundamental idea. We're essentially teaching the computer how to solve a problem.

Basic Code Example

Let's look at a simple algorithm: finding the largest number in a list. We'll use Python for this example.

def find_largest(numbers):
  """
  Finds the largest number in a list.
  """
  if not numbers:
    return None  # Handle empty list case

  largest = numbers[0]
  for number in numbers:
    if number > largest:
      largest = number
  return largest
Enter fullscreen mode Exit fullscreen mode

Let's break this down:

  1. def find_largest(numbers): defines a function called find_largest that takes a list of numbers as input.
  2. if not numbers: return None handles the case where the input list is empty. If it's empty, there's no largest number, so we return None.
  3. largest = numbers[0] initializes a variable called largest with the first number in the list. We assume this is the largest number until we find a bigger one.
  4. for number in numbers: starts a loop that iterates through each number in the list.
  5. if number > largest: checks if the current number is greater than the current largest number.
  6. largest = number If the current number is greater, we update largest to be the current number.
  7. return largest After the loop finishes, we return the final value of largest, which will be the largest number in the list.

Here's an example of how to use the function:

my_numbers = [10, 5, 20, 8, 15]
largest_number = find_largest(my_numbers)
print(f"The largest number is: {largest_number}")  # Output: The largest number is: 20

Enter fullscreen mode Exit fullscreen mode

Common Mistakes or Misunderstandings

Here are a few common mistakes beginners make when working with algorithms:

❌ Incorrect code:

def find_largest(numbers):
  largest = 0
  for number in numbers:
    if number > largest:
      largest = number
  return largest
Enter fullscreen mode Exit fullscreen mode

✅ Corrected code:

def find_largest(numbers):
  if not numbers:
    return None
  largest = numbers[0]
  for number in numbers:
    if number > largest:
      largest = number
  return largest
Enter fullscreen mode Exit fullscreen mode

Explanation: Initializing largest to 0 can be problematic if all the numbers in the list are negative. The algorithm would incorrectly return 0 as the largest. We should initialize largest to the first element of the list.

❌ Incorrect code:

def find_largest(numbers):
  for i in range(len(numbers)):
    if numbers[i] > numbers[i+1]:
      largest = numbers[i]
  return largest
Enter fullscreen mode Exit fullscreen mode

✅ Corrected code:

def find_largest(numbers):
  if not numbers:
    return None
  largest = numbers[0]
  for number in numbers:
    if number > largest:
      largest = number
  return largest
Enter fullscreen mode Exit fullscreen mode

Explanation: This code attempts to compare each element to the next element, but it doesn't correctly track the overall largest number. It also causes an IndexError when i reaches the last element of the list because numbers[i+1] goes out of bounds.

❌ Incorrect code:

def find_largest(numbers):
  return max(numbers)
Enter fullscreen mode Exit fullscreen mode

✅ Corrected code:

def find_largest(numbers):
  if not numbers:
    return None
  largest = numbers[0]
  for number in numbers:
    if number > largest:
      largest = number
  return largest
Enter fullscreen mode Exit fullscreen mode

Explanation: While max(numbers) works, the point of learning algorithms isn't just to use built-in functions. It's to understand how those functions work under the hood. Writing the algorithm yourself helps you build that understanding. (However, in a real-world scenario, using max() is perfectly acceptable if performance isn't critical!)

Real-World Use Case

Let's imagine you're building a simple shopping list app. You want to display the most expensive item on the list. You can use the find_largest algorithm (slightly modified) to achieve this.

class Item:
  def __init__(self, name, price):
    self.name = name
    self.price = price

def find_most_expensive_item(items):
  """
  Finds the most expensive item in a list of Item objects.
  """
  if not items:
    return None

  most_expensive = items[0]
  for item in items:
    if item.price > most_expensive.price:
      most_expensive = item
  return most_expensive

# Example Usage

item1 = Item("Milk", 3.50)
item2 = Item("Bread", 2.00)
item3 = Item("Eggs", 4.00)

shopping_list = [item1, item2, item3]

most_expensive = find_most_expensive_item(shopping_list)

if most_expensive:
  print(f"The most expensive item is: {most_expensive.name} - ${most_expensive.price}")
else:
  print("The shopping list is empty.")
Enter fullscreen mode Exit fullscreen mode

This example demonstrates how a simple algorithm can be applied to a practical problem.

Practice Ideas

Here are a few ideas to practice your algorithm skills:

  1. Find the smallest number in a list: Modify the find_largest algorithm to find the smallest number instead.
  2. Calculate the average of a list of numbers: Write an algorithm to calculate the average (mean) of a list of numbers.
  3. Reverse a string: Write an algorithm to reverse a given string.
  4. Check if a number is prime: Write an algorithm to determine if a given number is a prime number.
  5. Linear Search: Implement a linear search algorithm to find a specific element in a list.

Summary

Congratulations! You've taken your first steps into the world of algorithms. You've learned that algorithms are simply step-by-step instructions for solving problems, and that understanding them is crucial for becoming a better programmer. We covered a basic example of finding the largest number in a list, discussed common mistakes, and explored a real-world use case.

Don't be discouraged if it doesn't all click immediately. Practice is key! Keep experimenting, building, and challenging yourself. Next, you might want to explore more complex algorithms like sorting algorithms (bubble sort, insertion sort) or searching algorithms (binary search). Good luck, and happy coding!

Top comments (0)