פייתון/פייתון גרסה 3/השוואה בין שלושה ערכים: הבדלים בין גרסאות בדף

מתוך testwiki
קפיצה לניווט קפיצה לחיפוש
imported>ציפור מעופפת
הוספת רווח לאוחר פסיק לצורכי קריאות
 
(אין הבדלים)

גרסה אחרונה מ־18:26, 2 ביולי 2022

צרו תכנית אשר תשווה בין ערך הראשי (main obj) לבין שלושה ערכים obj_one,obj_two,obj_three. במידה ויש לפחות שני ערכים מתוך שלושת הערכים שגדולים מהערך הראשי הפונקציה תחזיר אמת.

דרך ארוכה

def compare_three_objects(main_obj, obj_one, obj_two, obj_three):
    #  two objects are higher than main_obj:
    if ((main_obj < obj_one) and (main_obj < obj_two)) or ((main_obj < obj_one) and (main_obj < obj_three)) :
        return True
    elif (main_obj < obj_two) and (main_obj < obj_three):
        return True
    # all three objects are higher than main_obj:
    elif (main_obj < obj_one) and (main_obj < obj_two) and (main_obj < obj_three):
        return True
    else:
        return False

דרך קצרה

הדרך הקצרה נעזר ב-count:

def compare_three_objects(main_obj, obj_one,obj_two, obj_three):
    counter_temp = 0
    if main_obj < obj_one:
        counter_temp+=1
    if main_obj < obj_two:
        counter_temp += 1
    if main_obj < obj_three:
        counter_temp += 1

    if counter_temp>=2:
        return True
    else:
        return False