ferme.py

Created by schraf

Created on September 07, 2018

1.17 KB

On vous donne une liste nommée ferme avec des éléments (m : mouton, v : vache, l : lapin, p : poule, c : canard). Créez les fonctions suivantes :

  • animaux : compte le nombre d’animaux suivant le paramètre donné. Par exemple animaux(ferme,'m') va compter le nombre de moutons dans la ferme, etc.
  • deux : compte le nombre d’animaux à 2 pattes (p ou c). Écrire 2 versions.
  • quatre : compte le nombre d’animaux à 4 pattes (m, v, l). Écrire au moins 2 versions.


ferme=['l','l','c','c','c','c','m','c','c','p','c','v','v','c','p','v','v','m','v','l','c','p','l','v','m','c','m','c','m','p','m','m','l','v','l','p','m','v','v','c','p','m','c','v','m','p','p','p','c','v','c','m','p','l','l','l','p','v','p','c','c','v','p','m','c','c','c','m','p','l','p','p','c','c','v','p','c','m','l','p','m','v','l','p','l','c','c','c','v','m','p','l','p','v','c','p','l','m','m','v','p','v','p','m','m','m','c','v','p','c']

def animaux(f,a):
  return len(list(filter(lambda v: v==a, f)))

# Ou alors utiliser une boucle classique

def animauxv2(f,a):
  nb = 0
  for v in f:
    if v==a : nb+=1
  return nb

def deuxv1(f):
  return len(list(filter(lambda v: v=="p" or v=="c", f)))

def deuxv2(f):
  return animaux(f,"p")+animaux(f,"c")
  
def deuxv3(f):
  return len([a for a in f if a=="p" or a=="c"])

def quatrev1(f):
  return animaux(f,"m")+animaux(f,"l")+animaux(f,"v")

def quatrev2(f):
  # Tous sauf les 2 pattes
  return len(f)-deuxv1(f)
  
def quatrev3(f):
  return len(list(filter(lambda v: v!="p" and v!="c", f)))
  
def quatrev4(f):
  return len(list(filter(lambda v: v in "mlv", f)))
  
def quatrev5(f):  
  return len([a for a in f if a in "mlv"])

During your visit to our site, NumWorks needs to install "cookies" or use other technologies to collect data about you in order to:

With the exception of Cookies essential to the operation of the site, NumWorks leaves you the choice: you can accept Cookies for audience measurement by clicking on the "Accept and continue" button, or refuse these Cookies by clicking on the "Continue without accepting" button or by continuing your browsing. You can update your choice at any time by clicking on the link "Manage my cookies" at the bottom of the page. For more information, please consult our <a href="https://www.numworks.com/legal/cookies-policy/">cookies policy</a>.