Predict
כתבו מה לדעתכם יודפס.
בכל תחנה: מנבאים את הפלט, חושפים אותו, מסבירים את המלכודת ומתקנים.
לא להריץ מיד.
כתבו מה לדעתכם יודפס.
חשפו את הפלט והשוו.
הסבירו את ההבדל בין Python למתמטיקה.
מן הבסיס ועד מלכודות חשובות.
x = [1, 2, 3] print(2 * x)
x = np.array([1, 2, 3]) print(2 * x) # [2 4 6]
x = np.array([10, 20, 30, 40, 50]) print(x[-1]) print(x[1:4])
# Mathematical x_{2:4} corresponds to Python x[1:4]x = np.array([1, 2, 3]) y = x y[0] = 99 print(x)
y = x.copy() # independent array
a = 5 b = [5] c = np.array([5]) print(type(a)) print(len(b)) print(c.shape)
# 1-vector in mathematics is often identified with a scalar, # but code keeps them distinct.
x = np.array([1, 2]) y = np.array([10, 20, 30]) print(np.concatenate([x, y]))
z = np.concatenate([x, y])
x = np.array([1, 2, 3]) print(5 * x) print(5 + x)
# NumPy broadcasts the scalar across the vector.
x = np.array([2, 3, 4]) y = np.array([5, 0, -1]) print(x * y) print(x @ y)
np.dot(x, y) # same scalar result
x = np.array([0, -2, 0, 5, 7, 0]) print((x > 0).sum()) print(np.count_nonzero(x))
positive = x[x > 0]
x = np.array([10, 13, 12, 20, 25]) d = x[1:] - x[:-1] print(d)
# Equivalent to mathematical x_{2:n} - x_{1:n-1}x = np.array([1, 2, 3]) y = np.array([1, 2, 3]) print(x == y) print(np.array_equal(x, y))
# For approximate floating-point equality: np.allclose(x, y)
לשמור ליד המחשב.
ברשימה מתקבלת חזרה, לא כפל מתמטי.
האיבר המתמטי הראשון נמצא באינדקס 0.
ב-x[a:b] האינדקס b אינו נכלל.
y=x אינו יוצר עותק.
הראשון איבר-איבר; השני מכפלה פנימית.
מחזיר מערך בוליאני, לא ערך אחד.
במתמטיקה לעיתים מזהים; בקוד לא.
לפני פעולה בדקו שהממדים מתאימים.
המעבר מווקטור מתמטי לקוד דורש בדיקת טיפוס, shape ואופרטור.
בדקו type, shape והאם נדרש וקטור או סקלר.
בדקו פלט קטן ביד לפני עבודה עם נתונים גדולים.