Python Forum
Add an element to a liste
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Add an element to a liste
#1
Hello, I must do the following task: Write a recursive function ajouter(element, set) which returns a set (represented by a list) to which a new element has been added (if it does not already belong to the set). Do not use the keyword "in".

I already started this program but I have a problem for when I have to return the function: I lose the starting set.

 def ajouter(element, ensemble):
  if ensemble==[]:
    ensemble.append(element)
    return ensemble
  else:
    if ensemble[0]==element:
      return ensemble
    else:
      return ajouter(element, ensemble[1:]) 


 element=4
 ensemble=[1,2,3]
Can you help me please ?
Thank you for the answer

Cyril from France
Reply
#2
Shouldn't you be calling the function, like:
print(ajouter(element, ensemble))
Next, how about you store the 'ensemble.append(element)' as another thing?
Last,(I'm not so sure)i don't think so that you should use more than 1 returns in your code
pyzyx3qwerty
"The greatest glory in living lies not in never falling, but in rising every time we fall." - Nelson Mandela
Need help on the forum? Visit help @ python forum
For learning more and more about python, visit Python docs
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020