תרגול מסכם: לולאות while

תרגול מסכם: לולאות while#

  1. השאלות הבאות מתייחסות לפונקציה המסתורית הבאה:

def mystery(st):
    i = 0
    count = 0
    while st[i] != '.':
        if st[i] in 'aeiou':
            count = count + 1
        i = i + 1
    return count

תקנו כעת את הפונקציה כך שלעולם לא תיגש לאינדקס לא חוקי, אבל עדיין תבצע את אותה פעולה.

יש להוסיף תנאי ללולאת ה-while, כלומר היא תיראה מהצורה:

while ________ and st[i] != ".":

על התנאי הנוסף לדאוג לעצירת הלולאה כאשר מגיעים לסוף המחרוזת.

def mystery(st):
    i = 0
    count = 0
    # Add the new condition in the next line
    while st[i] != '.':
        if st[i] in 'aeiou':
            count = count + 1
        i = i + 1
    return count
    

### TESTS ###

print("********************")
print("Starting the test:")
    
print("********************")
print("Checking 'hello. world.'")
ans = mystery('hello. world.')
if ans == 2:
    print("CORRECT: 'hello. world.' has 2 vowels before the first period")
else:
    print("WRONG: 'hello. world.' has 2 vowels before the first period but the code returned", ans)

print("********************")
print("Checking 'hello world. nice to meet you.'")
ans = mystery('hello world. nice to meet you.')
if ans == 3:
    print("CORRECT: 'hello world. nice to meet you.' has 3 vowels before the first period")
else:
    print("WRONG: 'hello world. nice to meet you.' has 3 vowels before the first period but the code returned", ans)

print("********************")
print("Checking ' '")
ans = mystery(' ')
if ans == 0:
    print("CORRECT: The string ' ' has no vowels")
else:
    print("WRONG: The string ' ' has no vowels but the code returned", ans)

print("********************")
print("Checking 'dddda'")
ans = mystery('dddda')
if ans == 1:
    print("CORRECT: 'dddda' has 1 vowel")
else:
    print("WRONG: 'dddda' has 1 vowel but the code returned", ans)

print("********************")    
print("Tests concluded, add more tests of your own below!")
print("********************")
********************
Starting the test:
********************
Checking 'hello. world.'
CORRECT: 'hello. world.' has 2 vowels before the first period
********************
Checking 'hello world. nice to meet you.'
CORRECT: 'hello world. nice to meet you.' has 3 vowels before the first period
********************
Checking ' '
---------------------------------------------------------------------------
IndexError                                Traceback (most recent call last)
Cell In[3], line 35
     33 print("********************")
     34 print("Checking ' '")
---> 35 ans = mystery(' ')
     36 if ans == 0:
     37     print("CORRECT: The string ' ' has no vowels")

Cell In[3], line 5, in mystery(st)
      3 count = 0
      4 # Add the new condition in the next line
----> 5 while st[i] != '.':
      6     if st[i] in 'aeiou':
      7         count = count + 1

IndexError: string index out of range
  1. השלימו את הפונקציה skip_down אשר מקבלת כקלט מספר num חיובי ומספר skip ומחזירה רשימה המכילה את כל המספרים מ-num ועד אפס בסדר יורד ובקפיצות של skip.
    הנחיות:

    • השתמשו בלולאת while. בפרט, אסור להשתמש בלולאת for בשאלה זו (שימו לב שהיה אפשר להשתמש בלולאת for על range ואז השאלה היתה קלה הרבה יותר…)

    • על מנת להחזיר את הרשימה כדאי לאתחל רשימה ריקה lst=[] ולהשתמש במתודה append על מנת להוסיף לרשימה איברים, לדוגמא lst.append(10)

    • ניתן להניח כי המספרים num ו-skip הם חיוביים ושלמים

להלן מספר דוגמאות הרצה:

print(skip_down(10, 3))
>>> [10, 7, 4, 1]
print(skip_down(7, 1))
>>> [7, 6, 5, 4, 3, 2, 1, 0]
# Modify this function so it uses for-range loops

def skip_down(num, skip):
    # delete pass and fill in your code below
    pass
    

### TESTS ###

print("********************")
print("Starting the test:")
    
print("********************")
print("Computing list for skip_down(10, 2)")
ans = skip_down(10, 2)
if ans == [10, 8, 6, 4, 2, 0]:
    print("CORRECT: Very good, skip_down(10, 2) returns [10, 8, 6, 4, 2, 0]")
else:
    print("WRONG: skip_down(10, 2) should return [10, 8, 6, 4, 2, 0] but the code returned", ans)

print("********************")
print("Computing list for skip_down(13, 2)")
ans = skip_down(13, 2)
if ans == [13, 11, 9, 7, 5, 3, 1]:
    print("CORRECT: Very good, skip_down(13, 2) returns [13, 11, 9, 7, 5, 3, 1]")
else:
    print("WRONG: skip_down(13, 2) should return [13, 11, 9, 7, 5, 3, 1] but the code returned", ans)

print("********************")
print("Computing list for skip_down(13, 20)")
ans = skip_down(13, 20)
if ans == [13]:
    print("CORRECT: Very good, skip_down(13, 20) returns [13]")
else:
    print("WRONG: skip_down(13) should return [13] but the code returned", ans)
********************
Starting the test:
********************
Computing list for skip_down(10, 2)
WRONG: skip_down(10, 2) should return [10, 8, 6, 4, 2, 0] but the code returned None
********************
Computing list for skip_down(13, 2)
WRONG: skip_down(13, 2) should return [13, 11, 9, 7, 5, 3, 1] but the code returned None
********************
Computing list for skip_down(13, 20)
WRONG: skip_down(13) should return [13] but the code returned None
  1. בחלונית הקוד שלפניכם מופיעה הפונקציה avg המחשבת ממוצע ברשימת מספרים. ראינו את הפונקציה הזו בתרגיל ביחידה הקודמת. בפונקציה נעשה שימוש בלולאת for. שנו את הפונקציה avg כך שתשתמש בלולאת while (במקום לולאת ה-for).

# Modify this function so it uses while loops

def avg(L):
    s = 0
    for num in L:
         s = s + num
    return s/len(L)



### TESTS ###

print("********************")
print("Starting the test:")
    
print("********************")
print("Computing the average of [1, 2, 3, 4, 5]")
ans = avg([1, 2, 3, 4, 5])
if ans == 3.0:
    print("CORRECT: Very good, the average of [1, 2, 3, 4, 5] is 3.0")
else:
    print("WRONG: The average of [1, 2, 3, 4, 5] is 3.0 but the code returned", ans)

print("********************")
print("Computing the average of [10, 10, 10, 100]")
ans = avg([10, 10, 10, 100])
if ans == 32.5:
    print("CORRECT: Very good, the average of [10, 10, 10, 100] is 32.5")
else:
    print("WRONG: The average of [10, 10, 10, 100] is 32.5 but the code returned", ans)
********************
Starting the test:
********************
Computing the average of [1, 2, 3, 4, 5]
CORRECT: Very good, the average of [1, 2, 3, 4, 5] is 3.0
********************
Computing the average of [10, 10, 10, 100]
CORRECT: Very good, the average of [10, 10, 10, 100] is 32.5
  1. התבוננו בקטע הקוד הבא, הכולל בתוכו לולאת while:

num = 2
while num < 20:
    num = num * num
print("Done")
  1. בחלונית הקוד להלן מופיעה כותרת הפונקציה birthday המקבלת כקלט תאריך לידה המורכב משני פרמטרים - day ו-month - יום וחודש. עליכם לממש את הפונקציה birthday כך שהיא תגריל תאריכי לידה שוב ושוב עד שיתקבל התאריך שהתקבל כקלט, ולבסוף תחזיר את מספר ההגרלות שנדרש.
    הנחיות:

    • ניתן להניח כי day הוא מספר שלם בין 1 ל-31 ו-month מספר שלם בין 1 ל-12.

    • כפי שוודאי שמתם לב, זהו תרגיל דומה למה שראינו בסרטון, אלא שכאן נדרשים שני תנאים.

    • נסו להיזכר באופרטורים שלמדתם - איזה מהם יממש את התנאי שיש לרשום כדי להמשיך את הלולאה?

    • אנו מניחים כאן הנחה מקלה - שבכל החודשים יש 31 ימים, ולכן ב”שנה” שלנו קיימים תאריכים שלא קיימים במציאות כמו 30.2 וכו’.

    • אתחלנו עבורכם שני משתנים בשמות days ו-months שערכיהם הן רשימות עם המספרים בין 1 ל-31 ובין 1 ל-12 בהתאמה. השתמשו במשתנים אלו כדי להגריל יום וחודש.

    • ניתן להוסיף הדפסות עזר כדי לעקוב אחר התאריכים המוגרלים ולוודא כי אתם יוצאים מהלולאה רק לאחר הגרלת תאריך הקלט.

import random

days = [i for i in range(1,32)]
months = [i for i in range(1,13)]

def birthday(day, month):
    # Write your solution here
    pass
    
    
    
day = 1
month = 1
print("It took", birthday(day, month), "trials to draw this birthday:", day, ".", month)
It took None trials to draw this birthday: 1 . 1

לאחר שסיימתם לכתוב את הפונקציה, עדכנו את המשתנים day ו-month שבתחתית הקוד ליום ולחודש הלידה שלכם, הריצו את הקוד ובדקו את עצמכם.

עצרו וחישבו

לכמה הגרלות תזדקקו בממוצע עד שתגרילו את תאריך הקלט? רמז: כדי לקבל מספר מסוים (למשל: 3) בקובייה הוגנת (בעלת 6 פאות), דרושות בממוצע 6 הטלות.