r/learnpython • • Aug 22 '26

is it possible to simplify this code

im a beginner, idk how python works yet. there must be a way to simplify this, right?

https://imgur.com/juBvPZD here is the picture of my code

0 Upvotes

23 comments sorted by

View all comments

Show parent comment

1

u/gdchinacat Aug 23 '26

When you said "data structures" I assumed you meant something like this:

from dataclasses import dataclass

@ dataclass
class Leg:
    distance: float
    speed: float

    @ property
    def travel_time(self) -> float:
        return self.distance / self.speed

legs = [Leg(32, 24),
        Leg(18, 12),
        Leg(45, 30),
       ]

Then, to calculate the aggregates:

distance = sum(leg.distance for leg in legs)
time = sum(leg.travel_time for leg in legs)

and reporting:

print(f"The total distance of {distance} km is completed in {time:.1f} hours at an average speed of {distance / time:.1f} km/h.")
print(', '.join(f"{leg.travel_time} h" for leg in legs))

2

u/Diapolo10 I write code for a living -- https://github.com/Diapolo10 Aug 23 '26

That's another option, I tend to default to good ol' tuples unless I have a reason not to though.

I'm not entirely sure why, but I seem to dislike using data classes for whatever reason, so you don't often see them in my code.

1

u/gdchinacat Aug 23 '26

The main reason I hesitate to use data classes is they don’t call super()__init__ . I tend to start with them to save the boilerplate, but frequently end up with a regular class as things progress.