示例#1
0
    # si a est impair et b est pair
    elif a % 2 != 0 and b % 2 == 0:
        return (a - 1) * b
    # sinon - c'est que a et b sont impairs
    else:
        return a * a - b * b


# @END@


def dispatch1_ko(a, b, *args):
    return a * a + b * b


exo_dispatch1 = ExerciseFunction(dispatch1, inputs_dispatch1)

####################
samples_A = [(2, 4, 6), [2, 4, 6]]
samples_B = [{6, 8, 10}]

inputs_dispatch2 = [
    Args(a, b, A, B) for a, A in zip(range(3, 5), samples_A)
    for b in range(7, 10) for B in samples_B
]


# @BEG@ name=dispatch2
def dispatch2(a, b, A, B):
    """
    dispatch2 comme spécifié
示例#2
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])
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 ]


exo_doubler_premier_kwds = ExerciseFunction(
    doubler_premier_kwds, doubler_premier_kwds_inputs,
    nb_examples=5,
    call_renderer=CallRenderer(show_function=False),
)


def doubler_premier_kwds_ko(f, first, *args, **keywords):
    return f(3*first, *args, **keywords)
示例#4
0
    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,
    inputs,
    nb_examples=8,
)


# @BEG@ name=postfix_eval_typed latex_size=footnotesize
def postfix_eval_typed(chaine, type):
    """
    a postfix evaluator, using a parametric type
    that can be either `int`, `float` or `Fraction` or similars
    """
    def divide(a, b):
        if issubclass(type, int):
            return a // b
        else:
            return a / b
示例#5
0
文件: tests.py 项目: dblanqui/1PC
	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%",
    header_font_size="120%",
)

exo_soustraction_a_b = ExerciseFunction(
    soustraction_a_b,
    inputs_soustraction_a_b,
    # 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%",
    header_font_size="120%",
)
示例#6
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),
)
示例#7
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),
)
示例#8
0
    scalaire = 0
    # sachez reconnaitre ce vilain idiome:
    for i in range(len(vec1)):
        scalaire += vec1[i] * vec2[i]
    return scalaire


# @END@

from fractions import Fraction

inputs_produit_scalaire = [
    Args((1, 2), (3, 4)),
    Args(range(3, 9), range(5, 11)),
    Args([-2, 10], [20, 4]),
    Args([Fraction(2, 15), Fraction(3, 4)],
         [Fraction(-7, 19), Fraction(4, 13)]),
    Args([], []),
]

exo_produit_scalaire = ExerciseFunction(
    produit_scalaire,
    inputs_produit_scalaire,
    call_renderer=PPrintCallRenderer(width=25),
    result_renderer=PPrintRenderer(width=25),
)


def produit_scalaire_ko(vec1, vec2):
    return [x * y for x, y in zip(vec1, vec2)]
enrichment_data = pd.read_pickle('data/enrichment_data_T4.p')

inputs_calc_EF = [
    Args(enrichment_data["tanimoto_maccs"], 4),
    Args(enrichment_data["tanimoto_maccs"], 5),
    Args(enrichment_data["tanimoto_maccs"], 6),
    Args(enrichment_data["tanimoto_morgan"], 4),
    Args(enrichment_data["tanimoto_morgan"], 5),
    Args(enrichment_data["tanimoto_morgan"], 6),
]

exo_calc_EF = ExerciseFunction(calculate_enrichment_factor,
                               inputs_calc_EF,
                               call_renderer=PPrintCallRenderer(
                                   show_function=False,
                                   css_properties={
                                       'word-wrap': 'break-word',
                                       'max-width': '40em'
                                   },
                               ))


def calculate_enrichment_factor_optimal(molecules,
                                        ranked_dataset_percentage_cutoff,
                                        pic50_cutoff):
    """
    Get the optimal random enrichment factor for a given percentage of the ranked dataset.

    Parameters
    ----------
    molecules : pandas.DataFrame
示例#10
0
inputs_maximum = [
    Args(1, 2, 3),
    Args(3, 2, 1),
    Args(3, 1, 2)
]


########## step 3
# finally we create the exercise object
# NOTE: this is the only name that should be imported from this module
#
exo_factorielle = ExerciseFunction(
    # first argument is the 'correct' function
    # it is recommended to use the same name as in the notebook, as the
    # python function name is used in HTML rendering 
    factorielle,
    # the inputs
    inputs_factorielle,
    result_renderer=PPrintRenderer(width=20),
)

exo_somme = ExerciseFunction(
    somme_diff_quotient_reste,
    inputs_somme,
    result_renderer=PPrintRenderer(width=20),
)

exo_est_bisextile = ExerciseFunction(
    est_bisextile,
    inputs_bisextile,
    result_renderer=PPrintRenderer(width=20),
示例#11
0
def multi_tri(listes):
    """
    trie toutes les sous-listes
    et retourne listes
    """
    for liste in listes:
        # sort fait un effet de bord
        liste.sort()
    # et on retourne la liste de départ
    return listes


# @END@

inputs_multi_tri = [
    Args([[40, 12, 25], ['spam', 'egg', 'bacon']]),
    Args([[32, 45], [200, 12], [-25, 37]]),
    Args([[], list(range(6)) + [2.5], [4, 2, 3, 1]]),
]

exo_multi_tri = ExerciseFunction(
    multi_tri,
    inputs_multi_tri,
    call_renderer=PPrintCallRenderer(width=30),
    result_renderer=PPrintRenderer(width=20),
)


def multi_tri_ko(listes):
    return listes
示例#12
0
    args("".join(random.sample(alphabet, random.randint(3, 6))),
         "".join(random.sample(alphabet, random.randint(5, 8))))
    for i in range(4)
]


# @BEG@ name=inconnue
# pour enlever à gauche et à droite une chaine de longueur x
# on peut faire composite[ x : -x ]
# or ici x vaut len(connue)
def inconnue(composite, connue):
    return composite[len(connue):-len(connue)]


# @END@


# @BEG@ name=inconnue more=bis
# ce qui peut aussi s'écrire comme ceci si on préfère
def inconnue_bis(composite, connue):
    return composite[len(connue):len(composite) - len(connue)]


# @END@

exo_inconnue = ExerciseFunction(inconnue, inconnue_inputs)


def inconnue_ko(big, small):
    return big[len(small):-4]
示例#13
0
# ceci ne devrait pas marcher avec des instances de Number
def power_ko(x, n):
    return x ** n

   
inputs_power = [
    Args(2, 1),
    Args(2, 10),
    Args(1j, 4),
    Args(Number(1j), 4),
]

powers = (2, 3, 1024, 1025)

inputs_power += [
    Args(3, n) for n in powers
] 

i_powers = (2*128, 2**128+1, 2*128-1)

inputs_power += [
    Args(1j, n) for n in i_powers
]

exo_power = ExerciseFunction(
    power, inputs_power,
    nb_examples = 4,
    call_renderer=PPrintCallRenderer(width=30),
    result_renderer=PPrintRenderer(width=40),
)
示例#14
0

inputs_laccess = [
    Args([]),
    Args([1]),
    Args(['spam', 100]),
    Args(['spam', 100, 'bacon']),
    Args([1, 2, 3, 100]),
    Args([1, 2, 100, 4, 5]),
    Args(['si', 'pair', 'alors', 'dernier']),
    Args(['retourne', 'le', 'milieu', 'si', 'impair']),
]


exo_laccess = ExerciseFunction(
    laccess, inputs_laccess, nb_examples=0
)


def laccess_ko(liste):
    return liste[-1]

#################### le même code marche-t-il avec des strings ?
inputs_laccess_strings = [
    Args(""),
    Args("a"),
    Args("ab"),
    Args("abc"),
    Args("abcd"),
    Args("abcde"),
]
示例#15
0
# (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
    qui sont presents dans filename_reference
    """

    # on tire profit de la fonction précédente
    reference_set = read_set(filename_reference)
示例#16
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,
)
示例#17
0
 def correction(self,
                student_diff,
                extended=extended,
                abbreviated=abbreviated):
     self.datasets = [Args(extended, abbreviated).clone('deep')]
     return ExerciseFunction.correction(self, student_diff)
示例#18
0

# @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.
...'''),
)

exo_wc = ExerciseFunction(wc,
                          wc_inputs,
                          call_renderer=PPrintCallRenderer(max_width=40,
                                                           show_function=True),
                          result_renderer=PPrintRenderer(width=15))
示例#19
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
示例#20
0
    Args([1, 2]),
    Args(["toto", "tata"]),
    Args([0]),
    Args(["anticonstitutionnellement"]),
    Args(["élastique", "ceinture", "bretelles"])
]


########## step 3
# finally we create the exercise object
# NOTE: this is the only name that should be imported from this module
#

exo_aleatoire = ExerciseFunction(
    aleatoire,
    inputs_creation,
    result_renderer=PPrintRenderer(width=50),
)


exo_croissant = ExerciseFunction(
    croissant,
    inputs_creation,
    result_renderer=PPrintRenderer(width=50),
)

exo_ajout_queue = ExerciseFunction(
    ajout_queue,
    inputs_ajout,
    result_renderer=PPrintRenderer(width=50),
)
示例#21
0
    # 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)
示例#22
0
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,
    call_renderer=CallRenderer(show_function=False),
)


def compare_all_ko(*args):
    return [not x for x in compare_all(*args)]
示例#23
0
 def correction(self, student_comptage):
     # call the decorator on the student code
     return ExerciseFunction.correction(
         self, exercice_compliant(student_comptage))
示例#24
0
        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)
]

exo_pgcd = ExerciseFunction(
    pgcd, inputs_pgcd,
    nb_examples = 6,
)
示例#25
0
        # 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):
    fp_list = [
        DataStructs.cDataStructs.CreateFromBitString(fp_str)
        for fp_str in fp_list_str
    ]
    return ClusterFps(fp_list, cutoff=0.2)


# Input: Fingerprints and a threshold for the clustering
示例#26
0
 def correction(self, student_decode_zen):
     args_obj = Args(this)
     self.datasets = [ args_obj ]
     return ExerciseFunction.correction(self, student_decode_zen)
示例#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
# @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(';')))
示例#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
(C(=O)N(C(C(=O)N(C(C(=O)N(C(C(=O)N(C(C(=O)N1)C(C(C)CC=CC)O)C)C(C)C)C)CC(C)C)C)CC(C)C)\
C)C)C)CC(C)C)C)C(C)C)CC(C)C)C)C')
smiles_4 = MolFromSmiles(
    'CC1=C(C(CCC1)(C)C)C=CC(=CC=CC(=CC=CC=C(C)C=CC=C(C)C=CC2=C(CCCC2(C)C)C)C)C'
)
smiles_5 = MolFromSmiles('CCCCCC1=CC(=C(C(=C1)O)C2C=C(CCC2C(=C)C)C)O')
smiles_6 = MolFromSmiles('CC(=O)OC1=CC=CC=C1C(=O)O')
smiles_7 = MolFromSmiles('CN1CCC23C4C1CC5=C2C(=C(C=C5)O)OC3C(C=C4)O')

inputs_calculate_fp = [
    Args(smiles_1),
    Args(smiles_2, method='ecfp4'),
    Args(smiles_3, method='ecfp4', n_bits=1024),
    Args(smiles_4, method='ecfp6'),
    Args(smiles_5, method='torsion'),
    Args(smiles_6, method='rdk5'),
    Args(smiles_7, method='ecfp6', n_bits=1024),
]

exo_calculate_fp = ExerciseFunction(print_fp,
                                    inputs_calculate_fp,
                                    call_renderer=PPrintCallRenderer(
                                        show_function=True,
                                        css_properties={
                                            'word-wrap': 'break-word',
                                            'max-width': '40em'
                                        },
                                    ))

# ________________________________________________________________________________