from typing import List, Tuple, Dict, Set #Exercice 1 : Itineraires #Exo 1, question 1 :…
- User
from typing import List, Tuple, Dict, Set
#Exercice 1 : Itineraires
#Exo 1, question 1 :
def resume(itineraire:List[Tuple[str,float]])->Tuple[float, float]: """Pre toutes les valeurs d'itinéaires sont >= 0 Étant donné un itinéraire, renvoie un couple dont le premier élément donne le déplacement total qui est à effectuer vers le nord et le second élément donne le déplacement total qui est à effectuer vers l’est""" nord:float = 0 est:float = 0
e : Tuple[str,float]for e in itineraire: s, n = e if s == 'nord': nord = nord + n elif s == 'sud': nord = nord - n elif s == 'est': est = est + n elif s == 'ouest': est = est - n return (nord, est)assert resume([('nord', 3.2),('est', 2.5),('nord', 4)]) == (7.2, 2.5) assert resume([('sud', 2)]) == (-2, 0) assert resume([('sud', 3.2),('ouest', 2.5),('nord', 4.2)]) == (1, -2.5) assert resume([('est', 2.5),('ouest', 2.5)]) == (0, 0) assert resume([]) == (0, 0)
#Exo 1 : question 2 :
def retour(itineraire:List[Tuple[str,float]])->List[Tuple[str,float]]: """Pre toutes les valeurs d'itinéaires sont >= 0 étant donné un itinéraire, renvoie l’itinéraire correspondant au retour""" e : Tuple[str,float]
lp : List[Tuple[str,float]] = [] for e in itineraire: s, n = e lr : List[Tuple[str,float]] = [] if s == 'nord': lr.append(('sud', n)) elif s == 'sud': lr.append(('nord', n)) elif s == 'ouest': lr.append(('est', n)) elif s == 'est': lr.append(('ouest', n)) lp = lr + lp return lpassert retour([]) == [] assert retour([('sud', 2.0)]) == [('nord', 2.0)] assert retour([('nord', 2.0)]) == [('sud', 2.0)] assert retour([('est', 5.0)]) == [('ouest', 5.0)] assert retour([('ouest', 6.2)]) == [('est', 6.2)] assert retour([('est', 3.2),('est', 2.5)]) == [('ouest', 2.5),('ouest', 3.2)] assert retour([('sud', 1.0),('ouest', 5.4),('nord', 6.0)]) == [('sud', 6.0),('est', 5.4),('nord', 1.0)]
#Exercice 2 : Typologie d'animaux
Dclassif:Dict[str, Set[str]]= { #initialisation du dictionnaire Dclassif 'animal':{'mammifere', 'oiseau'}, 'mammifere':{'chat', 'chien','lapin'}, 'oiseau':{'pigeon', 'poule'}, 'chat':{'chartreux', 'bengale', 'persan'}, 'chien':{'chihuahua','bouledogue','labrador','lévrier'}}
#Exo 2 : question 1 :
def nb_instances(Dcla:Dict[str, Set[str]]) -> int: """Pre : Étant donné un dictionnaire de classification, renvoie le nombre d’instances qu’il contient""" nb : int = 0 p : Set[str] = set() res : str
for (cat,_) in Dcla.items(): p.add(cat) for (_,sub) in Dcla.items(): for res in sub: if res not in p: nb = nb + 1 return nbassert nb_instances(Dclassif) == 10
#Exo 2 : question 2 :
def cat_max(Dcla:Dict[str, Set[str]]) -> Set[str]: """Pre : Étant donné un dictionnaire de classification, renvoie l’ensemble des catégories comptant le nombre maximal de sous-catégories""" res : str = '' nb : int = 0 p : Set[str] = set()
for (cat,sub) in Dcla.items(): if len(sub) > nb: p = {cat} nb = len(sub) elif len(sub) == nb and nb != 0: p.add(cat) elif len(sub) > nb and len(p) == 2: p = {cat} nb = len(sub) return passert cat_max(Dclassif) == {'chien'}
Dclassif_bis:Dict[str, Set[str]]= { #initialisation d'un dictionnaire Dclassif sans les sous-catégories de chiens 'animal':{'mammifere', 'oiseau'}, 'mammifere':{'chat', 'chien','lapin'}, 'oiseau':{'pigeon', 'poule'}, 'chat':{'chartreux', 'bengale', 'persan'}}
assert cat_max(Dclassif_bis) == {'chat','mammifere'}
#Exo 2 : question 3 :
def cate_sup(cat: str, Dcla: Dict[str, Set[str]], cat_sup: Set[str]) -> None: '''''' for (sup,sub) in Dcla.items(): if cat in sub: cat_sup.add(sup) cate_sup(sup, Dcla, cat_sup)
def typologie(Dcla: Dict[str, Set[str]]) -> Dict[str, Set[str]]: ''''''
s : str typo : Dict[str, Set[str]] = dict()for (cat,sub) in Dcla.items(): for s in sub: if s not in typo: typo[s] = set() cate_sup(s, Dcla, typo[s]) return typoassert typologie(Dclassif) == { 'mammifere':{'animal'}, 'oiseau':{'animal'}, 'chat': {'animal', 'mammifere'}, 'chien': {'animal', 'mammifere'}, 'lapin':{'mammifere','animal'}, 'pigeon':{'oiseau','animal'}, 'poule':{'oiseau','animal'}, 'chartreux':{'chat','mammifere','animal'}, 'bengale':{'chat','mammifere','animal'}, 'persan':{'chat','mammifere','animal'}, 'chihuahua':{'chien','mammifere','animal'}, 'bouledogue':{'chien','mammifere','animal'}, 'labrador':{'chien','mammifere','animal'}, 'lévrier':{'chien','mammifere','animal'}}
#Exo 2 : question 4 :
Dcaract:Dict[str, Set[str]]= { #Initialisation du dictionnaire de caractéristiques Dcaract 'animal':{'respire'}, 'oiseau':{'vole','oeuf','plumes','2pattes'}, 'mammifere':{'poils','4pattes'}}
def caracteristiques(categorie: str, Dcla: Dict[str, Set[str]], dcar: Dict[str, Set[str]]) -> Set[str]: '''Pre : categorie est une chaîne de caractères donnant le nom d'une categorie, par forcement present dans Dcla Étant donné une chaîne de caractères donnant le nom d’une catégorie, un dictionnaire de classification et un dictionnaire de caractéristiques, renvoie l’ensemble des caractéristiques possédées par la catégorie'''
typo_cat: Dict[str, Set[str]] = typologie(Dcla) res : str p : Set[str] = set() f : Set[str] = set() caract : Set[str] = set() for (cat,sub) in typo_cat.items(): if cat == categorie: p = sub for res in p: for (cat,sub) in dcar.items(): if res == cat: f = f | sub return fassert caracteristiques('vache', Dclassif, Dcaract) == set() assert caracteristiques('poule', Dclassif, Dcaract) == {'respire', 'vole','oeuf','plumes','2pattes'}
assert caracteristiques('lapin', Dclassif, Dcaract) == {'respire', 'poils','4pattes'} assert caracteristiques('labrador', Dclassif, Dcaract) == {'respire', 'poils','4pattes'} assert caracteristiques('chien', Dclassif, Dcaract) == {'respire', 'poils','4pattes'}#Exo 2 : question 5 :
Dexc:Dict[str, str]= {'autruche':'non_vole', 'sphynx':'non_poils'} #Initialisation d'un dictionnaire d'exception Dexc
Dclassif2:Dict[str, Set[str]]= { #Initialisation d'un deuxième dictionnaire de classification Dclassif2 'animal':{'mammifere', 'oiseau'}, 'mammifere':{'chat', 'chien','lapin'}, 'oiseau':{'pigeon', 'poule','autruche'}, 'chat':{'chartreux', 'bengale', 'persan','sphynx'}, 'chien':{'chihuahua','bouledogue','labrador','lévrier'}}
def oppose(s1: str, s2: str)->bool: """Pre : len(s1) and len(s2) > 0, s2 and s1 appartiennent a un dictionnaire de caractéristiques Étant donné deux chaînes de caractères s1 et s2, renvoie le booléen True si l’une est égale à l’autre préfixée par 'non_'"""
return s1[:4] == 'non_' and s1[4:] == s2 or s2[:4] == 'non_' and s2[4:] == s1assert oppose('non_vole','vole') == True assert oppose('poils','non_poils') == True assert oppose('non_vole','non_poils') == False assert oppose('vole','poils') == False
#Exo 2 : question 6 :
Donner une définition de la fonction caracteristiques_exc qui, étant donné une chaîne de caractères donnant le nom d’une catégorie, un dictionnaire de classification, un dictionnaire de caractéristiques et un dictionnaire d’exceptions, renvoie l’ensemble des caractéristiques possédées par la catégorie considérée, en tenant compte des exceptions. Par exemple :
caracteristiques_exceptions(’lapin’, Dclassif2, Dcaract, Dexc) {’respire’, ’poils’,’4pattes’} caracteristiques_exceptions(’chien’,Dclassif2, Dcaract, Dexc) {’respire’, ’poils’,’4pattes’} caracteristiques_exceptions(’labrador’, Dclassif2, Dcaract, Dexc) {’respire’, ’poils’,’4pattes’} caracteristiques_exceptions(’poule’,Dclassif2, Dcaract, Dexc) {’respire’, ’vole’,’oeuf’,’plumes’,’2pattes’} caracteristiques_exceptions(’vache’,Dclassif2, Dcaract, Dexc) set() caracteristiques_exceptions(’autruche’,Dclassif2, Dcaract, Dexc) {’respire’, ’oeuf’,’plumes’,’2pattes’} caracteristiques_exceptions(’sphynx’,Dclassif2, Dcaract, Dexc) {’respire’,’4pattes’}
- Assistant
Here is the implementation of the function
caracteristiques_excwhich takes into account the classification dictionary, the characteristics dictionary, and the exceptions dictionary to determine the characteristics of a given category:def caracteristiques_exc(categorie: str, Dcla: Dict[str, Set[str]], dcar: Dict[str, Set[str]], Dexc: Dict[str, str]) -> Set[str]: """Pre : categorie is a string of the name of a category, not necessarily present in Dcla Given a string of the name of a category, a classification dictionary, a characteristics dictionary, and an exceptions dictionary, returns the set of characteristics possessed by the category, taking into account exceptions.""" # Get the typology path of the given category typo_cat: Dict[str, Set[str]] = typologie(Dcla) caracts : Set[str] = set() # Add the characteristics along the category path, starting from the most specific category for super_cat in reversed([categorie] + list(typo_cat.get(categorie, []))): caracts.update(dcar.get(super_cat, set())) # Add or remove the exceptions for the particular category for caract in list(caracts): if caract in Dexc: caracts.discard(caract) # Discard the characteristic if it's exceptional caracts.add(Dexc[caract]) # Add its exceptional counterpart elif f"non_{caract}" in Dexc.values(): caracts.discard(caract) # Discard the counterpart of the exceptional characteristic for exc, opp in Dexc.items(): if oppose(caract, opp): caracts.discard(caract) return caracts # Test cases assert caracteristiques_exc('lapin', Dclassif2, Dcaract, Dexc) == {'respire', 'poils', '4pattes'} assert caracteristiques_exc('chien', Dclassif2, Dcaract, Dexc) == {'respire', 'poils', '4pattes'} assert caracteristiques_exc('labrador', Dclassif2, Dcaract, Dexc) == {'respire', 'poils', '4pattes'} assert caracteristiques_exc('poule', Dclassif2, Dcaract, Dexc) == {'respire', 'vole', 'oeuf', 'plumes', '2pattes'} assert caracteristiques_exc('vache', Dclassif2, Dcaract, Dexc) == set() assert caracteristiques_exc('autruche', Dclassif2, Dcaract, Dexc) == {'respire', 'oeuf', 'plumes', '2pattes'} assert caracteristiques_exc('sphynx', Dclassif2, Dcaract, Dexc) == {'respire', '4pattes'}Please note that if there is a direct characteristic specified in the exception dictionary for the category itself, it's added to the set after removing the general characteristic. If any characteristic has a counterpart (opposite) in the exceptions, it must be handled accordingly as well.
- User
def caracteristiques_exceptions(cat: str, Dcla: Dict[str,Set[str]], Dcar: Dict[str,Set[str]], Dex: Dict[str,Set[str]])->Set[str]: '''''' res : str s : str carac : Set[str] = caracteristiques(cat, Dcla, Dcar)
for (cate,sub) in Dex.items(): if cat == cate: res = 'sub' s = res[:4] if s in carac: carac.remove(s) return carac return carac j'ai fait ca pk ca marche pas - Assistant
There are several issues in the implementation of the
caracteristiques_exceptionsfunction you provided. I'll address those and present a revised version:- The assignment
res = 'sub'results in the string 'sub' being stored inres. You probably meant to assign the actual set of exceptions tores, not the string literal 'sub'. - Items in the exception dictionary
Dexshould be retrieved using the key, not iterating and comparing. - The function should handle category hierarchies (ancestors), not just the category itself.
- We need to check both the characteristic and its negated version (according to your exercise description 'non_' prefix).
Here's how the corrected function should look like:
def caracteristiques_exceptions(cat: str, Dcla: Dict[str, Set[str]], Dcar: Dict[str, Set[str]], Dex: Dict[str, str]) -> Set[str]: # Get the base characteristics of the category, including its ancestors. carac = caracteristiques(cat, Dcla, Dcar) # Get all super categories of cat, including cat itself. super_categories = [cat] + list(typologie(Dcla).get(cat, set())) # Go through all exceptions and adjust characteristics. for super_cat in super_categories: exception = Dex.get(super_cat) if exception: to_remove = exception[4:] if exception.startswith('non_') else exception to_add = exception if to_remove != exception else '' if to_remove in carac: carac.remove(to_remove) if to_add: carac.add(to_add) return caracMake sure to test this function with the examples you provided, considering the improvements that define the correct logic for handling exceptions. If you have any specific test cases you'd like to check, make sure that your classification dictionary, the characteristics dictionary, and the exceptions dictionary adequately represent these cases.
- The assignment
- User
for (cate,sub) in Dex.items(): if cat == cate: res = 'sub' s = res[4:]
if s in carac: carac.remove(s) return carac ok j'ai fait ca mais je crois que ca marche pas. Initialement j'ai envie de prendre un res, de le transformer de set[str] en str, imaginons un non_vole, puis de le transformer en s, tel que s = res[4:] soit vole et que si s est dans carac, un set[str], qu'il soit retiré de celui ci puis retourné, je fais comment ? - Assistant
The approach you're attempting seems to focus on a specific case where the characteristic in the exception dictionary starts with 'non_'. However, it seems there might be some confusion in your current implementation. Let's break down what needs to be done and then provide the correct implementation.
To handle exceptions correctly:
- For each category in the path of supercategories (including the category itself), check if there's an exception.
- If an exception is found, and it's a negated characteristic (starts with 'non_'), then:
- If the non-negated characteristic (e.g., 'vole' from 'non_vole') is in the
caracset, remove it. - Otherwise, if the characteristic is in the exception and does not start with 'non_', add it to the
caracset or replace its negated version if present.
- If the non-negated characteristic (e.g., 'vole' from 'non_vole') is in the
- Return the set with the proper characteristics after processing the exceptions.
Here is the revised function implementation:
def caracteristiques_exceptions(cat: str, Dcla: Dict[str, Set[str]], Dcar: Dict[str, Set[str]], Dex: Dict[str, str]) -> Set[str]: # Get the base characteristics of the category, including its ancestors. carac = caracteristiques(cat, Dcla, Dcar) # Get all super categories of cat, including cat itself. super_categories = [cat] + list(typologie(Dcla).get(cat, set())) # Go through all exceptions for the category and its supercategories. for super_cat in super_categories: exception = Dex.get(super_cat) if exception: # If the exception defines a negated characteristic. if exception.startswith('non_'): non_negated = exception[4:] if non_negated in carac: carac.remove(non_negated) else: # The exception defines a positive characteristic. # Remove the negated characteristic if present. negated = f'non_{exception}' if exception in carac else '' if negated in carac: carac.remove(negated) # Add the exception characteristic. carac.add(exception) return caracNow let's test this function with the examples you provided:
Dexc = {'autruche': 'non_vole', 'sphynx': 'non_poils'} assert caracteristiques_exceptions('lapin', Dclassif2, Dcaract, Dexc) == {'respire', 'poils', '4pattes'} assert caracteristiques_exceptions('chien', Dclassif2, Dcaract, Dexc) == {'respire', 'poils', '4pattes'} assert caracteristiques_exceptions('labrador', Dclassif2, Dcaract, Dexc) == {'respire', 'poils', '4pattes'} assert caracteristiques_exceptions('poule', Dclassif2, Dcaract, Dexc) == {'respire', 'vole', 'oeuf', 'plumes', '2pattes'} assert caracteristiques_exceptions('vache', Dclassif2, Dcaract, Dexc) == set() assert caracteristiques_exceptions('autruche', Dclassif2, Dcaract, Dexc) == {'respire', 'oeuf', 'plumes', '2pattes'} assert caracteristiques_exceptions('sphynx', Dclassif2, Dcaract, Dexc) == {'respire', '4pattes'}The above implementation should correctly process exceptions, adding and removing characteristics as required.
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.