תרגול מסכם: לולאות for#
ממשו את הפונקציה
between(lst,a,b)אשר מקבלת כפרמטרים רשימה של מספרים (lst) וטווח מספרים (הנתון על ידי קצותיוaו-b). הפונקציה תחזיר את מספר האיברים ברשימהlstאשר גדולים ממש מ-aוקטנים ממש מ-b.
להלן מספר דוגמאות הרצה:
print(between([1, 2, 3, 4],1,4))
>>> 2
print(between([0, 8, 20, -15], -10, 4))
>>> 1
הנחיות
ודאו שהפונקציה בודקת האם המספרים גדולים/קטנים ממש מהטווח שהוגדר. לדוגמא: אם
a=10ו-b=20, לא נספור איברים ברשימה ששווים ל-10 או 20 אלא רק איברים בטווח 11-19.הריצו את הפונקציה על דוגמאות פשוטות וודאו שהתשובה המתקבלת נכונה. למשל,
between([1,2,3,4],0,5)אמורה להחזיר 4.
def between(lst, a, b):
# delete pass and fill in your code below
pass
### TESTS ###
print("********************")
print("Starting the test:")
print("********************")
print("Counting over [1, 2, 3, 4] with a = 0, b = 5")
ans = between([1, 2, 3, 4], 0, 5)
if ans == 4:
print("CORRECT: Very good, there are 4 elements between a = 0 and b = 5 in [1, 2, 3, 4]")
else:
print("WRONG: There are 4 elements between a = 0 and b = 5 in [1, 2, 3, 4] but the code returned", ans)
print("********************")
print("Counting over [-5, 20, 13, 0] with a = 200, b = 300")
ans = between([-5, 20, 13, 0], 200, 300)
if ans == 0:
print("CORRECT: Very good, there are no elements between a = 200 and b = 300 in [-5, 20, 13, 0]")
else:
print("WRONG: There are no elements between a = 200 and b = 300 in [-5, 20, 13, 0] but the code returned", ans)
print("********************")
print("Counting over [-5, 20, 13, 0] with a = -10, b = 5")
ans = between([-5, 20, 13, 0], -10, 5)
if ans == 2:
print("CORRECT: Very good, there are 2 elements between a = -10 and b = 5 in [-5, 20, 13, 0]")
else:
print("WRONG: There are 2 elements between a = -10 and b = 5 in [-5, 20, 13, 0] but the code returned", ans)
print("********************")
print("Tests concluded, add more tests of your own below!")
print("********************")
********************
Starting the test:
********************
Counting over [1, 2, 3, 4] with a = 0, b = 5
WRONG: There are 4 elements between a = 0 and b = 5 in [1, 2, 3, 4] but the code returned None
********************
Counting over [-5, 20, 13, 0] with a = 200, b = 300
WRONG: There are no elements between a = 200 and b = 300 in [-5, 20, 13, 0] but the code returned None
********************
Counting over [-5, 20, 13, 0] with a = -10, b = 5
WRONG: There are 2 elements between a = -10 and b = 5 in [-5, 20, 13, 0] but the code returned None
********************
Tests concluded, add more tests of your own below!
********************
בחלונית הקוד שלפניכם מוצגת הפונקציה הבאה, המחשבת ממוצע של מספרים ברשימת קלט
L:
def avg(L):
s = 0
for num in L:
s = s + num
return s / len(L)
כעת נרצה לכתוב את אותה פונקציה, אך עם לולאת for על range, כפי שראינו בסרטון האחרון. שנו את הקוד של הפונקציה המופיע בחלונית הקוד כך שהמעבר על איברי הרשימה יעשה עם לולאת for על range - כלומר, המעבר על איברי הרשימה יתבצע לפי אינדקסים - ומבלי לפגוע בפונקציונליות (כלומר, הפונקציה תעשה אותו דבר בדיוק).
לאחר שסיימתם, הריצו את הקוד ובדקו את תוצאות הבדיקות בחלונית הפלט.
תזכורת
ממוצע של מספרים הוא סכום המספרים חלקי כמות המספרים.
# Modify this function so it uses for-range 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
שימו לב
חשוב להבדיל בין האינדקס עצמו - המשתנה עליו מבצעים את האיטרציה - לבין האיבר שנמצא באותו מיקום ברשימה. נתרגל זאת בשאלה הבאה.
ממשו את הפונקציה twisted_list אשר מקבלת רשימה ומחזירה רשימה חדשה הכוללת את האיברים המקוריים אך ורק אם הם נמצאים באינדקס זוגי והם מספרים אי־זוגיים.
לדוגמה:
twisted_list([0, 1, 5, 34, 44, 15])
>>> [5]
האינדקסים הזוגיים הם: 0, 2, 4.
האיברים באינדקסים הללו הם: 0, 5, 44.
מתוך האיברים הללו, רק 5 אי זוגי. ולכן הפונקציה תחזיר [5].
def twisted_list(lst):
# Write your code here
# Write your tests here
Cell In[4], line 4
# Write your tests here
^
SyntaxError: incomplete input
ממשו
is_positive_int, המקבלת כקלט מחרוזת st ובודקת האם ללא הגרשיים המחרוזת היא בעצם מספר שלם וחיובי, כלומר:המחרוזת אינה ריקה (כלומר, היא מכילה לפחות תו אחד)
התו הראשון במחרוזת הוא תו בטווח ‘1’-‘9’
מלבד התו הראשון, המחרוזת מכילה אך ורק תווים בטווח ‘0’-‘9’
אם המחרוזת עונה על כל התנאים לעיל, נחזיר True, אחרת נחזיר False.
להלן מספר דוגמאות הרצה:
print(is_positive_int("123"))
>>> True
print(is_positive_int("123.0"))
>>> False
print(is_positive_int("0"))
>>> False
print(is_positive_int("99"))
>>> True
def is_positive_int(st):
# delete pass and fill in your code below
pass
### TESTS ###
print("********************")
print("Starting the test:")
print("********************")
print("Checking '123'")
ans = is_positive_int('123')
if ans == True:
print("CORRECT: '123' is a positive int")
else:
print("WRONG: '123' is a positive int but the code returned", ans)
print("********************")
print("Checking '101'")
ans = is_positive_int('101')
if ans == True:
print("CORRECT: '101' is a positive int")
else:
print("WRONG: '101' is a positive int but the code returned", ans)
print("********************")
print("Checking '123.1'")
ans = is_positive_int('123.1')
if ans == False:
print("CORRECT: '123.1' is not a positive int")
else:
print("WRONG: '123.1' is not a positive int but the code returned", ans)
print("********************")
print("Checking '123.0'")
ans = is_positive_int('123.0')
if ans == False:
print("CORRECT: '123.0' is not a positive int")
else:
print("WRONG: '123.0' is not a positive int but the code returned", ans)
print("********************")
print("Checking '0'")
ans = is_positive_int('0')
if ans == False:
print("CORRECT: '0' is not a positive int")
else:
print("WRONG: '0' is not a positive int but the code returned", ans)
print("********************")
print("Checking '943827658972346'")
ans = is_positive_int('943827658972346')
if ans == True:
print("CORRECT: '943827658972346' is a positive int")
else:
print("WRONG: '943827658972346' is a positive int but the code returned", ans)
print("********************")
print("Tests concluded, add more tests of your own below!")
print("********************")
הבעיה
is_positive_int, שפגשתם בתרגיל הקודם, מעניקה לנו הזדמנות טובה לדון בתכנון של אלגוריתמים ובלוגיקה העומדת מאחורי הפתרון. בואו נזכר מה היו התנאים שלנו לכך שמחרוזת מייצגת מספר שלם חיובי:המחרוזת אינה ריקה (כלומר, היא מכילה לפחות תו אחד)
התו הראשון במחרוזת הוא תו בטווח ‘1’-‘9’
מלבד התו הראשון, המחרוזת מכילה אך ורק תווים בטווח ‘0’-‘9’ אם מחרוזת st מקיימת את כל שלושת התנאים הללו, נדע שהיא מייצגת מספר שלם חיובי.
להלן דוגמא לפתרון שגוי לבעיה שלנו, נסו לאתר את הבעיה:
def is_positive_int(st):
if len(st) > 0:
return True
else:
return False
if st[0] in "123456789":
return True
else:
return False
for i in range(1, len(st)):
if st[i] in "0123456789":
return True
else:
return False
### TESTS ###
print("********************")
print("Starting the test:")
print("********************")
print("Checking '123'")
ans = is_positive_int('123')
if ans == True:
print("CORRECT: '123' is a positive int")
else:
print("WRONG: '123' is a positive int but the code returned", ans)
print("********************")
print("Checking '101'")
ans = is_positive_int('101')
if ans == True:
print("CORRECT: '101' is a positive int")
else:
print("WRONG: '101' is a positive int but the code returned", ans)
print("********************")
print("Checking '123.1'")
ans = is_positive_int('123.1')
if ans == False:
print("CORRECT: '123.1' is not a positive int")
else:
print("WRONG: '123.1' is not a positive int but the code returned", ans)
print("********************")
print("Checking '123.0'")
ans = is_positive_int('123.0')
if ans == False:
print("CORRECT: '123.0' is not a positive int")
else:
print("WRONG: '123.0' is not a positive int but the code returned", ans)
print("********************")
print("Checking '0'")
ans = is_positive_int('0')
if ans == False:
print("CORRECT: '0' is not a positive int")
else:
print("WRONG: '0' is not a positive int but the code returned", ans)
print("********************")
print("Checking '943827658972346'")
ans = is_positive_int('943827658972346')
if ans == True:
print("CORRECT: '943827658972346' is a positive int")
else:
print("WRONG: '943827658972346' is a positive int but the code returned", ans)
print("********************")
print("Tests concluded, add more tests of your own below!")
print("********************")
לחצו כאן כדי לצפות בפתרון
נשים לב שהפונקציה מחזירה ערך לפני שבדקה את כל התנאים - אם המחרוזת אינה ריקה, הפונקציה תחזיר True בלי לבדוק כלל אם שאר התנאים מתקיימים.