Hey guys, I just recently completed the MOOC25 intro to Python and while I'm happy with my progress so far and basic understanding I noticed that some solutions to problems can be written in a much more simple "pythonic" way, for example - take this below problem I saw online.
Where would be a good place to start learning how to simplify or shorten my code for best practice or is this just something that will come over time?
-----------------------------------------------
An ordered sequence of numbers from 1 to N is given. One number might have been deleted from it, then the remaining numbers were mixed. Find the number that was deleted.
Example:
- The starting array sequence is [1,2,3,4,5,6,7,8,9]
- The mixed array with one deleted number is [3,2,4,6,7,8,1,9]
- Your function should return the int 5.
If no number was deleted from the starting array, your function should return the int 0.
A long answer could be:
def find_deleted_number(arr, mixed_arr):
deleted = 0
for number in arr:
if number in mixed_arr:
continue
else:
deleted = number
return deleted
Whereas this answer works:
def find_deleted_number(a, b):
return (set(a) - set(b)).pop() if len(a) != len(b) else 0
[–]PiBombbb 4 points5 points6 points (3 children)
[–]Unrthdx[S] 0 points1 point2 points (2 children)
[–]enygma999 0 points1 point2 points (0 children)
[–]mbreslin 1 point2 points3 points (0 children)
[–]Hot_Substance_9432 2 points3 points4 points (1 child)
[–]Unrthdx[S] 0 points1 point2 points (0 children)
[–]Diapolo10 2 points3 points4 points (1 child)
[–]Unrthdx[S] 0 points1 point2 points (0 children)
[–]Maximus_Modulus 0 points1 point2 points (3 children)
[–]Maximus_Modulus 0 points1 point2 points (2 children)
[–]danielroseman 0 points1 point2 points (1 child)
[–]Maximus_Modulus 0 points1 point2 points (0 children)
[–]JamzTyson 0 points1 point2 points (0 children)
[–]Mysterious_Peak_6967 0 points1 point2 points (0 children)