DEV Community

Dave
Dave

Posted on • Edited on

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?

Top comments (5)

Collapse
 
praise002 profile image
Praise Idowu

He used a single underscore instead of a double underscore. But I guess most code editors will indicate it is an error.
So it should be:
def str(self):
return f'{self.id}: {self.comment}'

Collapse
 
praise002 profile image
Praise Idowu

It should be
a = some_list[0]
for x in range(len(some_list)):
pass

Collapse
 
kingorie profile image
Kingorie

Your teammate should change line 2 of the code from "a = 0" to "a = some_list[ 0 ]

Collapse
 
kyant profile image
Ky-AnT

You also need to change the range from "range(1, len(some_list))" to "range(len(some_list))"

Collapse
 
jamesst77534538 profile image
Joe_Loves_Kids

Should be <=.