Contact
CoCalc Logo Icon
StoreFeaturesDocsShareSupport News AboutSign UpSign In
| Download
Views: 658
Kernel: Python 3 (Anaconda 2019)

רשימות - lists

My Name:איתמר

My Partner Name:יותם

from IPython.display import YouTubeVideo YouTubeVideo("KwDesuX1e_0")
בכל שאלה שאתם מתבקשים לומר מה התוצאה. במידה ויש שורות קוד שעליכם לומר מה יודפס, לכן אתם מתבקשים להעתיק את שורות הקוד לתא חדש , להריץ, ולכתוב תשובה (אפשר בעזרת סולמית לכתוב בעברית)
1. רשימה יכולה להכיל רק פריטים מאותו סוג? נכון/לא נכון
#לא נכון
2. מה ידפיס קטע הקוד שבהמשך.
items = [-3.2, 4, True, 'a', 'A', ['as',4,1]] print(len(items)-1)
5
5
3. כמה טיפוסי משתנים שונים ברשימה items בתרגיל הקודם?
5
5
4.מה ידפיס קטע הקוד שבהמשך:
a = [] print(type(a))
a = [] print(type(a))
<class 'list'>
5. נתונה הרשימה:
my_list=[2,5,-2,12.3,7]
מה יודפס על ידי המשפט:
print (3*my_list[1])
my_list=[2,5,-2,12.3,7]
6. נתונה הרשימה:
l1 = ['A', 'B', 7]
ונתונה הרשימה
l2 = [1, 2, 3]
מה תוצאת הביטוי:
l1 + l2
l1 = ['a', 'b', 7] l2 = [1, 2, 3] l1 + l2
['a', 'b', 7, 1, 2, 3]

l1.append(l2)
#['a', 'b,', 7, [1, 2, 3]]
7. עבור הרשימות l2 ו- l1 שבתרגיל הקודם, מה האיבר הרביעי ברשימה l1 אחרי הפקודה :
l1.append(l2)?
#[1, 2, 3]
8. נתונה הרשימה:
mass = [1.23, 3.45, 6.7, 2.3, 11.5]
מה יחזיר המחשב אחרי הקלדת המשפט:
6.7 in mass
#True
9. נתונה הרשימה
l=[0]
מה תוצאת הביטוי 4* l?
l=[0] l*4
[0, 0, 0, 0]
#[0, 0, 0, 0]
10.נתונות הרשימות
l1=[1,2,3] l2=[0]
צרו מהן את הרשימה:
[0,0,0,1,2,3,0,0,0]
l1=[1,2,3] l2=[0] l2*3+l1+l2*3
[0, 0, 0, 1, 2, 3, 0, 0, 0]
11.בעזרת הרשימה
l=[1,5,2,7]
צרו את הרשימה:
[1,2,5,7,7,5,2,1,2,2,2,2,2]
l=[1,5,2,7] l.sort() l x=[1,5,2,7] x.reverse() x y=l+x y n=[1,5,2,7] n.remove(1) n.remove(5) y.remove(7) y+n*5
[1, 2, 5, 7, 2, 5, 1, 2, 7, 2, 7, 2, 7, 2, 7, 2, 7]
[1, 2, 5, 7]
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-73-7c1773cd4af1> in <module>() ----> 1 l+l2 TypeError: can only concatenate list (not "NoneType") to list

הפונקציה range

הפונקציה:
range(start,stop,step)
היא פונקציה המיצרת אובייקט המחזיר סידרה חשבונית של מספרים שלמים המתחילים ב-start ומסתימים באיבר הגדול ביותר שעדיין קטן מ- stop - step. הפרש הסידרה הוא step. הפרמטרים start, step ו- stop חייבים להיות מספרים שלמים.
r = range(-5,5,2) #+מחזיר רשימה. שני צעדים כל פעם. מתחיל מ 5- וממשיך עד < 5 i = 0 while i < len(r): print (r[i]) i = i + 1
-5 -3 -1 1 3
כדי ליצור אובייקט מסוג range רשימה נשתמש בפונקציה list:
list(r)
--------------------------------------------------------------------------- NameError Traceback (most recent call last) <ipython-input-114-9b31f56ba9a7> in <module>() ----> 1 list(r) NameError: name 'r' is not defined
ברירת המחדל ל- start היא 0 ואילו ברירת המחדל ל- step היא 1
print(range(-2,3,1))
range(-2, 3)
11. על ידי שימוש ב - range צרו את כל אחת מהרשימות שלמטה:
  • [-2, -1, 0, 1, 2]

  • [0, -1, -2, -3]

  • [7, 10, 13, 16, 19]

a=range(-2,3,1) list(a)
[-2, -1, 0, 1, 2]
a=range(0,-4,-1) list(a)
[0, -1, -2, -3]
a=range(7,20,3) list(a)
[7, 10, 13, 16, 19]
12. צרו רשימה במרווחים קבועים שאינם דווקא שלמים. רשמו ליד כל שורת קוד הערה המסבירה אותו
ex=[0,0.4,0.8] #הגדרתי בהתחלה רשימה x=0.8 while x<7 : x=x+0.5 ex.append(x) print(ex)
[0, 0.4, 0.8, 1.3, 1.8, 2.3, 2.8, 3.3, 3.8, 4.3, 4.8, 5.3, 5.8, 6.3, 6.8, 7.3]
13.היפכו את הקוד בשאלה הקודמת לפונקציה בשם array. הפונקציה צריכה לקבל שלושה מספרים עשרוניים start, stop, ו- step ולהחזיר רשימה של מספרים עשורניים בתחום
start<=x<stopstart<=x< stop
שההפרש בין כל שניים צמודים הוא step.
def array(start, stop, step): g=[] g.append(start) while start<stop-step: start=start+step g.append(start) return list (g) print (array(0.1,800.54,100.5))
[0.1, 100.6, 201.1, 301.6, 402.1, 502.6, 603.1, 703.6]
נניח כי בניסוי התקבלו שתי קבוצות של תוצאות האחת מוכלת ברשימה:
x = [-2, 3, -5, 4]
והשנייה ברשימה :
y = [1.6, 7, 3.1, 9]
בעזרת הקוד שבהמשך נוכל לשרטט גרף שלהן:
import matplotlib.pyplot as plt plt.plot(x ,y, 'ro')#איך קובעים את גודל הנקודה? plt.plot(x ,y, 'b.')# plt.xlabel('x', fontsize = 12) plt.ylabel('x', fontsize = 12) plt.grid(True) plt.title( 'x Vs y grph',fontsize = 18, color = 'blue')
--------------------------------------------------------------------------- ValueError Traceback (most recent call last) <ipython-input-142-f12ff1196032> in <module>() 1 import matplotlib.pyplot as plt ----> 2 plt.plot(x ,y, 'ro')#איך קובעים את גודל הנקודה? 3 plt.plot(x ,y, 'b.')# 4 plt.xlabel('x', fontsize = 12) 5 plt.ylabel('x', fontsize = 12) /ext/anaconda5/lib/python3.6/site-packages/matplotlib/pyplot.py in plot(scalex, scaley, data, *args, **kwargs) 2809 return gca().plot( 2810 *args, scalex=scalex, scaley=scaley, **({"data": data} if data -> 2811 is not None else {}), **kwargs) 2812 2813 /ext/anaconda5/lib/python3.6/site-packages/matplotlib/__init__.py in inner(ax, data, *args, **kwargs) 1808 "the Matplotlib list!)" % (label_namer, func.__name__), 1809 RuntimeWarning, stacklevel=2) -> 1810 return func(ax, *args, **kwargs) 1811 1812 inner.__doc__ = _add_data_doc(inner.__doc__, /ext/anaconda5/lib/python3.6/site-packages/matplotlib/axes/_axes.py in plot(self, scalex, scaley, *args, **kwargs) 1609 kwargs = cbook.normalize_kwargs(kwargs, mlines.Line2D._alias_map) 1610 -> 1611 for line in self._get_lines(*args, **kwargs): 1612 self.add_line(line) 1613 lines.append(line) /ext/anaconda5/lib/python3.6/site-packages/matplotlib/axes/_base.py in _grab_next_args(self, *args, **kwargs) 391 this += args[0], 392 args = args[1:] --> 393 yield from self._plot_args(this, kwargs) 394 395 /ext/anaconda5/lib/python3.6/site-packages/matplotlib/axes/_base.py in _plot_args(self, tup, kwargs) 368 x, y = index_of(tup[-1]) 369 --> 370 x, y = self._xy_from_xy(x, y) 371 372 if self.command == 'plot': /ext/anaconda5/lib/python3.6/site-packages/matplotlib/axes/_base.py in _xy_from_xy(self, x, y) 229 if x.shape[0] != y.shape[0]: 230 raise ValueError("x and y must have same first dimension, but " --> 231 "have shapes {} and {}".format(x.shape, y.shape)) 232 if x.ndim > 2 or y.ndim > 2: 233 raise ValueError("x and y can be no greater than 2-D, but have " ValueError: x and y must have same first dimension, but have shapes (1,) and (7,)
Image in a Jupyter notebook
במידה ותרצו להעמיק באפשרויות שיש בספריה של יצירת גרפים matplotlib אני מפנה אתכם לקישור:
14. בדקו והסבירו מה עושות הפונקציה sum ו- zip כאשר הן פועלות על רשימה
a=[2,3,4,5] sum(a)
14
a=[2,3,4,5] zip(a)
<zip at 0x7f9cc1eb7588>
15. קבלו רשימה שכל איבר בה הוא השורש של כל המספרים השלמים בין 1 ל- 1000. מה סכום האיברים ברשימה זו?
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-160-99c3e7c0d591> in <module>() ----> 1 x[1,1001] TypeError: 'float' object is not subscriptable
from math import sqrt # sqrt צריכים להייבא מהספריה את הפקודה המחשבת שורש של מספר n=[] x=0 while x<1000: y= x**0.5 n.append(y) x=x+1 sum(n)
21065.833110879048
16.כתבו פונקציה בשם avg הפונקציה מקבל רשימה ומחזירה את ממוצע איברי הרשימה.
def avg(a,b,c): x=[a,b,c] n=sum (x) y=len (x) return n/y avg(80000,5,2)
26669.0
x=[1,2,3,4] x.extend()
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-9-4583bd2cf784> in <module>() 1 x=[1,2,3,4] ----> 2 x.extend() TypeError: extend() takes exactly one argument (0 given)
avg(5,6,7)
6.0
17.בדקו מה עושות הפונקציות min ו- max כאשר הן פועלות על רשימות, כלומר תכתבו שורות קוד, תריצו ותראו
s=[5,6,7] min(s)
5
s=[5,6,7] max(s)
7
import numpy as np import matplotlib.pyplot as plt a=np.arange(0,6.29,0.01) plt.plot(np.cos(a),np.sin(a))
[<matplotlib.lines.Line2D at 0x7ff2cdaacad0>]
Image in a Jupyter notebook
import numpy as np import matplotlib.pyplot as plt a=np.arange(0,6.29,6.28/7) plt.plot(np.cos(a),np.sin(a))
[<matplotlib.lines.Line2D at 0x7ff2cdd19090>]
Image in a Jupyter notebook