예제 #1
0
    Retourne une liste de ces 3 nombres (notez qu'usuellement
    on renverrait plutôt un tuple, qu'on étudiera la semaine prochaine)
    """
    # on peut tout faire avec la bibliothèque standard
    nb_lines = string.count('\n')
    nb_words = len(string.split())
    nb_bytes = len(string)
    return [nb_lines, nb_words, nb_bytes]


# @END@

wc_inputs = (
    Args('''Python is a programming language
that lets you work quickly
and integrate systems more effectively.'''),
    Args(''),
    Args('abc'),
    Args('abc \t'),
    Args('a  bc \t'),
    Args(' \tabc \n'),
    Args(" ".join("abcdefg") + "\n"),
    Args('''The Zen of Python, by Tim Peters

Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
예제 #2
0
        here we have decided to allow for comparison
        with a regular number
        """
        if isinstance(other, (bool, int, float)):
            return self == Quaternion(other, 0, 0, 0)
        elif isinstance(other, complex):
            return self == Quaternion(other.real, other.imag, 0, 0)
        elif isinstance(other, Quaternion):
            return self.implem == other.implem
        else:
            return False
# @END@

quaternion_scenarios = [
    ClassScenario(
        Args(1, 0, 0, 0),
        ClassExpression('INSTANCE == 1'),
    ),
    ClassScenario(
        Args(0, 1, 0, 0),
        ClassExpression('''# attention ici j c'est en fait notre i
INSTANCE == 1j'''),
    ),
    ClassScenario(
        Args(-1, 0, 0, 0),
        ClassExpression(
            'CLASS(0, 1, 0, 0) * CLASS(0, 1, 0, 0) == INSTANCE'
        ),
        ClassExpression(
            'CLASS(0, 0, 1, 0) * CLASS(0, 0, 1, 0) == INSTANCE'
        ),
예제 #3
0
# ne marche pas car on n'a pas les deux arguments requis
# par doubler_premier_kwds
#
# et pour écrire, disons doubler_permier3, qui marcherait aussi comme cela
# il faudrait faire une hypothèse sur le nom du premier argument...
# @END@


def add3(x, y=0, z=0):
    return x + y + z

def mul3(x=1, y=1, z=1):
    return x * y * z

doubler_premier_kwds_inputs = [
    Args(add3, 1, 2, 3),
    Args(add3, 1, 2, z=3),
    Args(add3, 1, y=2, z=3),
    # Args(add3, x=1, y=2, z=3),
    Args(mul3, 1, 2, 3),
    Args(mul3, 1, 2, z=3),
    Args(mul3, 1, y=2, z=3),
    # Args(mul3, x=1, y=2, z=3),
]

# remettre les datasets de doubler_premier
doubler_premier_kwds_inputs \
    += [ arg_obj for arg_obj in doubler_premier_inputs
         if arg_obj.args[0] == distance ]

예제 #4
0
파일: tests.py 프로젝트: dblanqui/1PC
from nbautoeval import ExerciseFunction, Args
from nbautoeval import CallRenderer, PPrintRenderer

def composantes_a(xA,yA,xB,yB):
    ax=xB-xA
    ay=yB-yA
    return(ax,ay)


def soustraction_a_b(ax,ay,bx,by):
	cx=ax-bx
	cy=ay-by
	return(cx,cy)

inputs_composantes_a = [
    Args(15,10,20,15),Args(12,5,22,10),Args(5,5,10,10),Args(5,5,5,10),Args(15,10,23,10),Args(15,15,10,12),Args(20,10,15,15)
]

inputs_soustraction_a_b = [
    Args(15,10,20,15),Args(12,5,22,10),Args(5,5,10,10),Args(5,5,5,10),Args(15,10,23,10),Args(15,15,10,12),Args(20,10,15,15)
]


exo_composantes_a = ExerciseFunction(
    composantes_a,
    inputs_composantes_a,
    # show function name in leftmost column
    call_renderer=CallRenderer(show_function=True),
    # use pprint to format results
    result_renderer=PPrintRenderer(width=20),
    font_size="90%",
예제 #5
0
    return sum(
        # ici sum(x) fait la somme des tirages des dés
        sum(x) == target for x in product(range(1, sides + 1), repeat=nb_dice))


# @END@


def dice_ko(target, nb_dice=2, nb_sides=6):
    return nb_sides**(nb_dice - 1)


SIDES = 5

dice_inputs = [
    Args(7),
    Args(2),
    Args(20, nb_sides=10),
    Args(3, nb_dice=3),
    Args(4, nb_dice=3),
    Args(50, nb_dice=8),
    Args(28, nb_dice=8),
] + [
    Args(target, nb_sides=SIDES, nb_dice=3)
    for target in range(3, 3 * SIDES + 1)
]

exo_dice = ExerciseFunctionNumpy(
    dice,
    dice_inputs,
    nb_examples=5,
예제 #6
0
from nbautoeval import Args, ExerciseFunction, PPrintCallRenderer


# @BEG@ name=longest_gap
def longest_gap(liste):
    result = 0
    begins = {}
    for index, item in enumerate(liste):
        if item not in begins:
            begins[item] = index
        else:
            result = max(result, index - begins[item])
    return result


# @END@

inputs = [
    Args([1, 2, 3, 1, 4, 10, 4, 3, -1, 4]),
    Args(["yes", "no", None, "yes", "no"]),
    Args([1, 2, 3, 4]),
]

exo_longest_gap = ExerciseFunction(
    longest_gap,
    inputs,
    nb_examples=0,
    call_renderer=PPrintCallRenderer(width=45),
)
예제 #7
0
                stack.append(function(left, right))
            else:
                # error: unknown op
                return 'error-syntax'
    if len(stack) == 0:
        return 'error-empty-stack'
    elif len(stack) > 1:
        return 'error-unfinished'

    return stack.pop()


# @END@

inputs = [
    Args("20 40 + 10 *"),
    Args(" 20 40 + 10 * "),
    Args("20 6 6 + /"),
    Args("20 18 -6 + /"),
    Args("10 -3 /"),
    Args("10 +"),
    Args("10 20 30 +"),
    Args("10 20 30 oops"),
    Args("40 20 / 10 +"),
    Args("40 20 - 10 +"),
    Args("+"),
    Args("10 20 30 + - /"),
]

exo_postfix_eval = ExerciseFunction(
    postfix_eval,
예제 #8
0
파일: exo_pgcd.py 프로젝트: deladan/course
    C'est plus court, mais on passe du temps à se
    convaincre que ça fonctionne bien comme demandé
    """
    # si on n'aime pas les boucles sans fin
    # on peut faire aussi comme ceci
    while b:
        a, b = b, a % b
    return a
# @END@


def pgcd_ko(a, b):
    return a % b

inputs_pgcd = [
    Args(0, 0),
    Args(0, 1),
    Args(1, 0),
    Args(15, 10),
    Args(10, 15),
    Args(3, 10),
    Args(10, 3),
    Args(10, 1),
    Args(1, 10),
]

inputs_pgcd += [
    Args(36 * 2**i * 3**j * 5**k,
         36 * 2**j * 3**k * 5**i)
    for i in range(3) for j in range(3) for k in range(2)
]
예제 #9
0
    first = args[0]
    remains = args[1:]
    return func(2 * first, *remains)


# @END@

doubler_premier_inputs = []
from operator import add
from operator import mul
from .exo_distance import distance

# pour l'exemple on choisit les 3 premiers inputs
# avec des fonctions différentes
for i in (1, 3, 5):
    doubler_premier_inputs.append(Args(add, i, 4))
    doubler_premier_inputs.append(Args(mul, i, 4))
doubler_premier_inputs.insert(2, Args(distance, 1.5, 4.))
doubler_premier_inputs.insert(3, Args(distance, 2.0, 4., 4., 4.))

exo_doubler_premier = ExerciseFunction(
    doubler_premier,
    doubler_premier_inputs,
    nb_examples=4,
    call_renderer=CallRenderer(show_function=False),
)


def doubler_premier_ko(f, first, *args):
    return f(3 * first, *args)
예제 #10
0
compare_all_inputs = []

# factoriel
from operator import mul


def fact(n):
    "une version de factoriel à base de reduce"
    return reduce(mul, range(1, n + 1), 1)


from math import factorial
fact_inputs = [0, 1, 5]

compare_all_inputs.append(Args(fact, factorial, fact_inputs))


def broken_fact(n):
    return 0 if n <= 0 \
        else 1 if n == 1 \
             else n*fact(n-1)


compare_all_inputs.append(Args(broken_fact, factorial, fact_inputs))

#################### the exercice instance
exo_compare_all = ExerciseFunction(
    compare_all,
    compare_all_inputs,
    nb_examples=2,
예제 #11
0
파일: exo_dice.py 프로젝트: deladan/course
        if sum(sample) == target:
            count += 1
    return count


# @END@


def dice_ko(target, nb_dice=2, sides=6):
    return sides**(nb_dice - 1)


SIDES = 5

dice_inputs = [
    Args(7),
    Args(2),
    Args(20, sides=10),
    Args(3, nb_dice=3),
    Args(4, nb_dice=3),
    Args(50, nb_dice=8),
] + [
    Args(target, sides=SIDES, nb_dice=3) for target in range(3, 3 * SIDES + 1)
]

exo_dice = ExerciseFunctionNumpy(
    dice,
    dice_inputs,
    nb_examples=5,
)
예제 #12
0
    def _get_celsius(self):
        # celsius + KELVIN = kelvin
        return self._kelvin - self.KELVIN

    def _set_celsius(self, celsius):
        self.kelvin = celsius + self.KELVIN

    celsius = property(_get_celsius, _set_celsius)


# @END@

temperature_scenarios = [
    # build and display an instance
    ClassScenario(
        Args(),
        ClassExpression("INSTANCE.kelvin"),
        ClassExpression("INSTANCE.celsius"),
    ),
    ClassScenario(
        Args(kelvin=0),
        ClassExpression("INSTANCE.kelvin"),
        ClassExpression("INSTANCE.celsius"),
    ),
    ClassScenario(
        Args(celsius=0),
        ClassExpression("INSTANCE.kelvin"),
        ClassExpression("INSTANCE.celsius"),
    ),
    ClassScenario(
        Args(kelvin=0),
예제 #13
0
    for i in range(0, 19, 1):
        assert t1[i] < t1[i+1], "il y a des éléments du tableau qui ne sont pas insérés par ordre croissant"
    return "Bravo ! je crois que vous avez réussi"
    

########## step 2
# You need to provide datasets
# This is expected to be a list of Args instances
# each one describes all the arguments to be passed
# to the function
# in this particular case we define 2 input sets, so
# the correction will have 2 meaningful rows
#

inputs_creation = [
    Args(2, 1, 10),
    Args(5, 1, 10),
    Args(1, 1, 10)
]

inputs_ajout = [
    Args([1, 2], 3),
    Args(["toto", "tata"], "titi"),
    Args([0], 1)
]

inputs_miroir = [
    Args([1, 2]),
    Args(["toto", "tata"]),
    Args([0]),
    Args(["anticonstitutionnellement"]),
예제 #14
0
                                                                         10):
                        decimal -= 2 * Roman.isymbols[previous]
                    else:
                        return nan
                decimal += Roman.isymbols[r]
                previous = r
        except KeyError:
            return nan
        else:
            return decimal


# @END@

roman_scenarios = [
    ClassScenario(Args(2020), ),
    ClassScenario(
        Args('MMXX'),
        ClassExpression("INSTANCE == CLASS(2020)"),
    ),
    ClassScenario(
        Args('MMXIX'),
        ClassExpression("INSTANCE + CLASS(19) == CLASS(2038)"),
        ClassExpression("INSTANCE - CLASS('MCMXCIX') == CLASS(20)"),
    ),
    ClassScenario(Args(5000), ),
    ClassScenario(
        Args(5000),
        ClassExpression("INSTANCE == CLASS(5000)"),
    ),
    ClassScenario(
예제 #15
0
def get_frags_number(df):
    PandasTools.ChangeMoleculeRendering(renderer='String')
    New_column = pd.DataFrame({
        'Frags_number':
        [len(Chem.rdmolops.GetMolFrags(mol)) for mol in df['ROMol']]
    })
    New_column = New_column.set_index(df.index)
    return New_column


df_meds = PandasTools.LoadSDF(
    './data/meds.sdf', isomericSmiles=True).drop(columns=['molecule_synonyms'])
df_meds = df_meds[df_meds['molecule_type'] == 'Small molecule']

inputs_frags_number = [
    Args(df_meds[['ROMol']].head()),
    Args(df_meds[['ROMol']])
]

exo_frags_number = ExerciseFunctionPandas(get_frags_number,
                                          inputs_frags_number,
                                          call_renderer=PPrintCallRenderer(
                                              show_function=False,
                                              css_properties={
                                                  'word-wrap': 'break-word',
                                                  'max-width': '40em'
                                              },
                                          ))

# ________________________________________________________________________________
예제 #16
0
    # en utilisant la méthode dot sur les tableaux
    return column.dot(column.T)
    # remarquez qu'on aurait pu faire aussi bien
    # return np.dot(column, column.T)


# @END@


def xixj_ko(*args):
    # presque ça mais sans le reshape
    array = np.array(args)
    return array.T @ array


inputs_xixj = [
    Args(1),
    Args(1, 2),
    Args(1, 2, 4),
    Args(1, 0, 4),
    Args(8, 4, 2),
    Args(0, 1, 2, 4, 8),
    Args(1, 1j, -1, -1j),
]

exo_xixj = ExerciseFunctionNumpy(
    xixj,
    inputs_xixj,
    nb_examples=3,
)
예제 #17
0
  {'n': 'Forbes', 'p': 'Bob'},
  {'n': 'Martin', 'p': 'Jeanneot'},
  {'n': 'Martin', 'p': 'Jean', 'p2': 'Paul'},
  {'n': 'Forbes', 'p': 'Charlie'},
  {'n': 'Martin', 'p': 'Jean', 'p2': 'Pierre'},
  {'n': 'Dupont', 'p': 'Alexandre'},
  {'n': 'Dupont', 'p': 'Laura', 'p2': 'Marie'},
  {'n': 'Forbes', 'p': 'John'},
  {'n': 'Martin', 'p': 'Jean'},
  {'n': 'Dupont', 'p': 'Alex', 'p2': 'Pierre'}]]





inputs_tri_custom = [
    Args(input) for input in inputs
]

exo_tri_custom = ExerciseFunction(
    tri_custom, inputs_tri_custom,
    call_renderer=PPrintCallRenderer(width=24),
    result_renderer=PPrintRenderer(width=30),
    font_size='small',
)


def tri_custom_ko(liste):
    sort(liste)
    return liste
예제 #18
0
 def correction(self, student_decode_zen):
     args_obj = Args(this)
     self.datasets = [ args_obj ]
     return ExerciseFunction.correction(self, student_decode_zen)
예제 #19
0
    "renvoie True si un des deux arguments divise l'autre"
    # on n'a pas encore vu les opérateurs logiques, mais
    # on peut aussi faire tout simplement comme ça
    # sans faire de if du tout
    return a % b == 0 or b % a == 0


# @END@


def divisible_ko(a, b):
    return a % b == 0


inputs_divisible = [
    Args(10, 30),
    Args(10, -30),
    Args(-10, 30),
    Args(-10, -30),
    Args(8, 12),
    Args(12, -8),
    Args(-12, 8),
    Args(-12, -8),
    Args(10, 1),
    Args(30, 10),
    Args(30, -10),
    Args(-30, 10),
    Args(-30, -10),
]

exo_divisible = ExerciseFunction(divisible, inputs_divisible)
예제 #20
0
# @BEG@ name=carre more=ter
def carre_ter(ligne):
    # On extrait toutes les valeurs séparées par des points-
    # virgules, on les nettoie avec la méthode strip
    # et on stocke le résultat dans une liste
    liste_valeurs = [t.strip() for t in ligne.split(';')]
    # Il ne reste plus qu'à calculer les carrés pour les
    # valeurs valides (non vides) et les remettre dans une str
    return ":".join([str(int(v)**2) for v in liste_valeurs if v])


# @END@

inputs_carre = [
    Args("1;2;3"),
    Args(" 2 ;  5;6;"),
    Args("; 12 ;  -23;\t60; 1\t"),
    Args("; -12 ; ; -23; 1 ;;\t"),
]

exo_carre = ExerciseFunction(carre,
                             inputs_carre,
                             nb_examples=0,
                             call_renderer=PPrintCallRenderer(
                                 show_function=False, width=40))


def carre_ko(s):
    return ":".join(str(i**2) for i in (int(token) for token in s.split(';')))
예제 #21
0

# @END@


def comptage_ko(in_filename, out_filename):
    with open(in_filename) as in_file:
        with open(out_filename, 'w') as out_file:
            for lineno, line in enumerate(in_file):
                out_file.write(f"{lineno}:{len(line.split())}:"
                               f"{len(line)}:{line}")


# on passe ceci à ExerciseFunction donc pas besoin de rajouter les **keywords
comptage_args = [
    Args('data/romeo_and_juliet.txt', 'romeo_and_juliet.out'),
    Args('data/lorem_ipsum.txt', 'lorem_ipsum.out'),
    Args('data/une_charogne_unicode.txt', 'une_charogne_unicode.out'),
]


class ExoComptage(ExerciseFunction):
    def correction(self, student_comptage):
        # call the decorator on the student code
        return ExerciseFunction.correction(
            self, exercice_compliant(student_comptage))

    # on recherche les noms des fichers d'entrée et de sortie
    # à utiliser pour l'exemple (ou le debug, on prend le même)
    # associés au premier jeu de données (self.datasets[0])
    # et là-dedans il nous faut regarder dans .args qui va contenir
예제 #22
0
# @END@


# @BEG@ name=read_set more=bis
# on peut aussi utiliser une compréhension d'ensemble
# (voir semaine 5); ça se présente comme
# une compréhension de liste mais on remplace
# les [] par des {}
def read_set_bis(filename):
    with open(filename) as feed:
        return {line.strip() for line in feed}
# @END@


read_set_inputs = [
    Args("data/setref1.txt"),
    Args("data/setref2.txt"),
]

exo_read_set = ExerciseFunction(
    read_set, read_set_inputs,
    result_renderer=PPrintRenderer(width=25),
)



# @BEG@ name=search_in_set
# ici aussi on suppose que les fichiers existent
def search_in_set(filename_reference, filename):
    """
    cherche les mots-lignes de filename parmi ceux
예제 #23
0

# Calculate distance matrix for fingerprint list
def Tanimoto_distance_matrix(fp_list):
    dissimilarity_matrix = []
    for i in range(1, len(fp_list)):
        similarities = DataStructs.BulkTanimotoSimilarity(
            fp_list[i], fp_list[:i])
        # Since we need a distance matrix, calculate 1-x for every element in similarity matrix
        for sim in similarities:
            dissimilarity_matrix.append(1 - sim)
    return dissimilarity_matrix


inputs_tan_dist_mat = [
    Args(fingerprints_str[0:3]),
    Args(fingerprints_str[0:1000])
]

exo_tan_dist_mat = ExerciseFunction(Tanimoto_distance_matrix_from_str,
                                    inputs_tan_dist_mat,
                                    call_renderer=PPrintCallRenderer(
                                        show_function=False,
                                        css_properties={
                                            'word-wrap': 'break-word',
                                            'max-width': '40em'
                                        },
                                    ))


def ClusterFps_from_str(fp_list_str, cutoff=0.2):
예제 #24
0
    # le broadcasting c'est magique parfois
    # car avec cette méthode on peut multiplier
    # dans n'importe quel ordre !
    # ce qui fait que ceci marche ausi !
    # return column * column.T


# @END@


def xixj_ko(*args):
    # presque ça mais sans le reshape
    array = np.array(args)
    return array.T @ array


inputs_xixj = [
    Args(1),
    Args(1, 2),
    Args(1, 2, 4),
    Args(1, 0, 4),
    Args(8, 4, 2),
    Args(0, 1, 2, 4, 8),
]

exo_xixj = ExerciseFunctionNumpy(
    xixj,
    inputs_xixj,
    nb_examples=3,
)
예제 #25
0
    Idem mais avec une expression génératrice
    """
    # on n'a pas encore vu cette forme - cf Semaine 5
    # mais pour vous donner un avant-goût d'une expression
    # génératrice:
    # on peut faire aussi comme ceci
    # observez l'absence de crochets []
    # la différence c'est juste qu'on ne
    # construit pas la liste des carrés,
    # car on n'en a pas besoin
    # et donc un itérateur nous suffit
    return math.sqrt(sum(x**2 for x in args))


# @END@

distance_inputs = [
    Args(),
    Args(1),
    Args(1, 1),
    Args(1, 1, 1),
    Args(1, 1, 1, 1),
    Args(*range(10)),
]

exo_distance = ExerciseFunction(distance, distance_inputs, nb_examples=3)


def distance_ko(*args):
    return sum([x**2 for x in args])
예제 #26
0
 def correction(self,
                student_diff,
                extended=extended,
                abbreviated=abbreviated):
     self.datasets = [Args(extended, abbreviated).clone('deep')]
     return ExerciseFunction.correction(self, student_diff)
예제 #27
0
    while index > 26:
        index = (index - 1) // 26
        # idem ici bien sûr
        result = int_to_char(index) + result
    return result
# @END@

z   = 26
zz  =  26**2 + 26
zzz = 26**3 + 26**2 + 26

numeric_inputs = (
    1, 15, z, z+1, zz-1, zz, zz+1, zz+2, zzz-1, zzz, zzz+1, zzz+2, 26**2-1,
    30_000, 100_000, 1_000_000,
)

# l'objet Args permet de capturer les arguments
# pour un appel à la fonction
spreadsheet_inputs = [Args(n) for n in numeric_inputs]

exo_spreadsheet = ExerciseFunction(
    spreadsheet, spreadsheet_inputs, nb_examples=7,
)


def spreadsheet_ko(n):
    if 1 <= n <= 26:
        return int_to_char(n)
    else:
        return spreadsheet_ko(n//26) + int_to_char(n)
예제 #28
0
def intersect_ko(A, B):
    A_vals = {v for k, v in A}
    B_vals = {v for k, v in B}
    return A_vals & B_vals


intersect_inputs = []

A1 = {
    (12, 'douze'),
    (10, 'dixA'),
    (8, 'huit'),
}
B1 = {
    (5, 'cinq'),
    (10, 'dixB'),
    (15, 'quinze'),
}
intersect_inputs.append(Args(A1, B1))

A2 = {(1, 'unA'), (2, 'deux'), (3, 'troisA')}
B2 = {(1, 'unB'), (2, 'deux'), (4, 'quatreB')}
intersect_inputs.append(Args(A2, B2))

exo_intersect = ExerciseFunction(
    intersect,
    intersect_inputs,
    nb_examples=2,
    call_renderer=PPrintCallRenderer(width=20),
)
예제 #29
0
    (50_001, 150_000, 40),
    (150_001, math.inf, 45),
)


def taxes_ter(income):

    due = 0
    for floor, ceiling, rate in TaxRate2:
        due += (min(income, ceiling) - floor + 1) * rate / 100
        if income <= ceiling:
            return int(due)


def taxes_ko(income):
    return (income - 12_500) * 20 / 100


taxes_values = [
    0, 50_000, 12_500, 5_000, 16_500, 30_000, 100_000, 150_000, 200_000, 12_504
]

taxes_inputs = [Args(v) for v in taxes_values]

exo_taxes = ExerciseFunction(taxes, taxes_inputs, nb_examples=3)

if __name__ == '__main__':
    for value in taxes_values:
        tax = taxes(value)
        print(f"{value} -> {tax}")
예제 #30
0
    return f"{prenom}.{nom} ({rang_ieme})"


# @END@ ##########


def libelle_ko(ligne):
    try:
        nom, prenom, rang = ligne.split(',')
        return f"{prenom}.{nom} ({rang})"
    except:
        return None


inputs_libelle = [
    Args("Joseph, Dupont, 4"),
    Args("Jean"),
    Args("Jules , Durand, 1"),
    Args(" Ted, Mosby, 2,"),
    Args(" Jacques , Martin, 3 \t"),
    Args("Sheldon, Cooper ,5,  "),
    Args("\t John, Doe\t, "),
    Args("John, Smith, , , , 3"),
]

exo_libelle = ExerciseFunction(
    libelle,
    inputs_libelle,
    nb_examples=0,
)