Remove duplicates questions


#1

I understood the correct answer, but can't understand why my code didn't work.

def remove_duplicates(source):
	result = []
	if len(result)==0:
		result = [source[0]]
	else:
		for j in range(len(result)):
			for i in range(len(source)):
				if source[i] == result[j]:
					break
				else:
					result.append(source[i])
	return result

i and j are the indexes, and source[i] and result[j] are the actual values, but source[i] never gets appended to result. Any advice would be appreciated. Thanks.


#2

take a close look at your indention, else is wrongly indented. It will never execute, it will always encounter a break before getting to else


#3

Doh… sorry for the mis-indent. That wasn't what I wrote in the course, I've revised my question. It keep says "Oops, try again. remove_duplicates([4, 5, 5, 4]) returned [4] instead of [4, 5]"


#4

oh wow, where to start....

This code is wrong in so many ways. lets start here:

if len(result)==0:

well, result is a empty list. so yes, if will be true. again, result is an empty list:

for j in range(len(result)):
if source[i] == result[j]:

this won't work. Add some print statements and function call so you can actually see what is hapepning


#5

So it all began from 'empty list length isn't 0' I guess. I also came to figure out break was used inappropriate and second for loop is inappropriate - it probably can make it but it would be in a dirty way - for this task. Thank you so much !!


#6

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.