0

I have written the following code to return True if the list has any repeating elements and False ow

def has_repeats(L,newlist = None):
	if newlist == None:
		newlist = []
	if len(L) == 0:
		return False
	if L[0] in newlist:
		return True
	else:
		newlist.append(L[0])
		has_repeats(L[1:],newlist)

It is not returning True or False for anything and I have no idea why, please help!

Edited by maxwellp: n/a

2
Contributors
1
Reply
2
Views
5 Years
Discussion Span
Last Post by pyTony
1

You are not returning the value for else branch, the newlist is not really needed, you can check with tail of L.

And in real life you would do:

def has_repeats(L):
    return len(set(L)) != len(L)

with hashable item sequence (no sublists).

My solution:

def has_repeats(L):
    if len(L) < 2:
        return False
    elif L[0] in L[1:]:
        return True
    else:
        return has_repeats(L[1:])

Edited by pyTony: n/a

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.