DEV Community

Rudolf Olah
Rudolf Olah

Posted on • Edited on

7

Python: no more need for range(len(...))

I was practising my algorithm writing skills on CodeSignal and one of the problems is how to sum up a matrix where there are certain conditions placed on the columns and rows.

What's neat about CodeSignal is that you can view and up-vote or down-vote other people's solutions after you have submitted your solution. Even in small algorithm problems, you can see how others are making use of clever tricks and libraries within the programming language used.

For instance, I used the Python enumerate function to traverse the rows and columns of the matrix:

for i, row in enumerate(matrix):
    for j, col in enumerate(row):
        print('matrix[{}][{}] = {}'.format(i, j, col))
Enter fullscreen mode Exit fullscreen mode

I noticed that other solutions to the problem were using this pattern:

for i in range(len(matrix)):
    for j in range(len(matrix[i])):
        print('matrix[{}][{}] = {}'.format(i, j, matrix[i][j]))
Enter fullscreen mode Exit fullscreen mode

This is something that makes sense in languages like C, C++ or JavaScript or even in Java. However, if there are iterators available that give you both the index and value, you should use them and match the idioms of the language.

Although, you do have to remember that when iterating over a slice of an array, you will need to set the starting index that enumerate starts at:

string = 'awesome'
for i, c in enumerate(string):
    print(i, c) # prints 0, a to 6, e
for i, c in enumerate(string[1:]):
    print(i, c) # prints 0, w to 5, e
for i, c in enumerate(string[1:], 1):
    print(i, c) # prints 1, w to 6, e
Enter fullscreen mode Exit fullscreen mode

On the flip side, I found a solution that was clever and used a combination of Python's itertools takewhile function, and the built-in sum and map functions.

There's a lot that all developers can learn, even in the smallest problems.

Image of Timescale

🚀 pgai Vectorizer: SQLAlchemy and LiteLLM Make Vector Search Simple

We built pgai Vectorizer to simplify embedding management for AI applications—without needing a separate database or complex infrastructure. Since launch, developers have created over 3,000 vectorizers on Timescale Cloud, with many more self-hosted.

Read full post →

Top comments (0)

Image of Docusign

🛠️ Bring your solution into Docusign. Reach over 1.6M customers.

Docusign is now extensible. Overcome challenges with disconnected products and inaccessible data by bringing your solutions into Docusign and publishing to 1.6M customers in the App Center.

Learn more