The goal is to find the middle of a list that has an odd number of items, and to find the average of the two middle items in a list with an even number of items. Just wanted to know which one is better optimized and why? Or if they are both equally optimized
There should be a / 2 after the ) on line 6 for the first solution.
If you’re using code on the forums please read- How do I format code in my posts? or consider pastebin, gists or similar as they’re a lot easier to read/test in text form.
If I’m reading it correctly then I’d hazard a guess they’re pretty similar, all you’ve done is inverted the logic so far as I can tell.
I will read that before the next time I post, thank you. And okay, thank you for checking into it. Since my solution didnt match exactly, wanted to make sure that it wouldnt result in problems in the future for some unseen reason
I wouldn’t worry too much about optimisation at this point, readability would be a much better target. Perhaps that repeating factor
int(len(lst) / 2) could be assigned to a name which would save it being recalculated but more importantly could make that overall calculation easier to read.
On that note double check the calculations on the left, there are
+1 terms in locations that don’t seem to be on the RHS. Make sure you’re selecting the right indices (print is useful if you’re not sure).
My bad but what is RHS? I checked and they do result in the same answer when printed. For an example like " middle_element([1, 2, 3, 4]), after int(len(lst) / 2) results in 2, the + 1 is so that side of the equation chooses indice 3. Since we have to get the average of the two middle indices when the list is even. I could be understanding it incorrectly as I am still fairly new
Sorry, just a quick abbreviation for Right Hand Side. I haven’t checked and I may be misreading it but there is a
-1 and and
+1 I can see in your code which is different to the right. It might be worth checking to be sure it does what you expect.
@tgrtim makes a good point about readability. This should always be a consideration.
Another metric you can use to test for code optimization is execution time (assuming you’ve already checked that both versions of your code give the expected output). To do this you can use the
timeit module. timeit — Measure execution time of small code snippets — Python 3.9.5 documentation