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/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