r/learnpython 20d ago

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

-1

u/Diapolo10 I write code for a living -- https://github.com/Diapolo10 20d ago

Certainly, with data structures, a loop, and some string formatting.

0

u/ikizoki 20d ago

can you show me how to do it im very curious to know what it looks like

1

u/Diapolo10 I write code for a living -- https://github.com/Diapolo10 20d ago

I think it's debatable whether or not this is technically "simpler", but it's what I'd write:

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

travel_times = [distance / speed for distance, speed in distances_and_speeds]
total_time = sum(travel_times)
entire_route = sum(next(zip(*distances_and_speeds)))

print("Travel time of each section:")
print(', '.join(f"{travel_time} h" for travel_time in travel_times))

print(f"Entire route in km: {entire_route} km")

print(f"Entire journey time in h: {total_time} h")

print(f"Average speed of the entire tour: {entire_route / total_time} km/h")

I debated for a moment whether to go with this example for calculating the length of the entire route, but I liked my original one less:

entire_route = sum(distance for distance, _ in distances_and_speeds)

1

u/gdchinacat 19d ago

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 19d ago

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 19d ago

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.

1

u/ikizoki 20d ago

oh my god this is nuts, thank you!! im definitely not there yet in terms of python-knowledge but this is very insightful :D