Please ignore secret bonuses. Secret tests do NOT award bonus. Max hw grade is 30+2 bonus efficiency

Do you need help?

Notice Board

Per partecipare al corso di Fondamenti di programmazione 2023-24 loggatevi e attivatelo nella vostra pagina dei corsi preferiti. A quel punto il corso appare nel menù personale cliccando sul proprio avatar. Per i materiali degli anni precedenti seguite lo stesso metodo.

To join the Programming/Lab 2023-24 course, log-on and select it on the my courses page. It will appear on the personal menu of your avatar. For earlier years use the same method.

Algorithm taking too long

C
CameronR (220 points)
0 2 4
in Programming in Python by (220 points)
I am wondering how I can improve code that is taking too long to run.

For instance, say I have any short program/function that works correctly but times out when being tested with larger test data - what should I look for or remove from my code that would help it speed up?
423 views
closed

2 Answers

Best answer
andrea.sterbini (207920 points)
750 1267 2373
by (208k points)
selected by
I suggest you use the spyder-line-profiler plugin to find what part of your code takes more time, and improve it
b
benjamin (2490 points)
1 7 21
by (2.5k points)
You should look to find a way to reduce if statements as much as possible. Avoid iterating multiple times over a list and try to do everything you can in fewer iteration as possible.

When you can use builtin function ( for example sum instead of iterating with a for loop) since they are more often than not faster than what you might be able to write.