Python Debugging Exercises

msoup

Dave

Posted on May 1, 2022

Python Debugging Exercises

[The following is a series of debugging exercises that you may encounter in the real world of development. They are based on problems I have been asked. I thought it would be fun to share them.]

It is your first week at your new job as a software developer. You have your environment set up and you're seated beside a fellow junior who started a few days before you.

He turns to you and asks if you have a minute.

"Hey if you don't mind, please help me find out what's wrong..."

Problem 1

Context

To change display name of Model Instances, we will use def __str__() function in a model. The str function in a django model returns a string that is exactly rendered as the display name of instances for that model.

For example, if we adjust a model in models.py like so

from django.db import models
from django.db.models import Model

class SomeModel(Model):
    name = models.CharField(max_length = 100)

    def __str__(self):
         return f"{self.name}"
Enter fullscreen mode Exit fullscreen mode

When we access SomeModel.objects.all(), the output should be a list of the name fields of this object.

Problem

It doesn't work for comments. When a Comment object is printed, it shows [Comment object (1)] rather than what is defined under str.

Let's check the code:

# imports here

class Listing(models.Model):
  max_bid = models.DecimalField(...)
  ...

  def __str__(self):
    return ...

class Bid(models.Model):
  ...

class User(AbstractUser):
  ...

class Comment(models.Model):
  comment = models.TextField()
  listing = models.ForeignKey(Listing, on_delete=models.CASCADE)
  user = models.ForeignKey(User, on_delete=models.CASCADE)

  def _str__(self):
    return f'{self.id}: {self.comment}' 
Enter fullscreen mode Exit fullscreen mode

Where did your fellow teammate go wrong?

Problem 2

Context

Your coworker was secretly interviewing with other companies and was told to find the min value in a list without using min.

Problem

The below code doesn't seem to find the minimum element in the list. Why?

def minimum(some_list):
    a = 0
    for x in range(1, len(some_list)):
        if some_list[x] < a:
            a = some_list[x]
    return a
Enter fullscreen mode Exit fullscreen mode

Where did your fellow teammate go wrong?

💖 💪 🙅 🚩
msoup
Dave

Posted on May 1, 2022

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related