Last active
April 19, 2021 13:54
-
-
Save Julisam/95fe864720c75617a0a99806610bf72c to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def remove_instance(nums, val): | |
""" | |
Given an array nums, and a value val, returns the new length of the array with the value removed | |
i.e. the number of items in nums with val | |
Input: nums=[5, 2, 2, 5, 3] and val = 5 | |
Output: 3 | |
""" | |
try: | |
#check for cases of an empty array | |
if len(nums) == 0: | |
return 0 | |
else: | |
count=0 | |
for i in nums: | |
if i != val: | |
count +=1 | |
return count | |
except: | |
return 0 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hello @Julisam, thank you for participating in Week 2 of Algorithm Fridays.
This is a decent solution; I like that you handled the case if the array is empty. However, your solution assumes that
nums
will always be an array because if I passNone
as input to your function, it would break on line 10. Ideally you want to write robust code that takes care of invalid input.Also, your solution correctly centers around looping through the array to check for elements whose values are not equal to
val
. Do you think there's a faster way to loop through the array?I've posted my solution here. Do let me know what you think.