You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
@@ -61,6 +61,9 @@ Let's learn a bit more about them.
61
61
62
62
### Primitive Data Types
63
63
64
+
65
+
#### Boolean Values
66
+
64
67
One simple data type is **Boolean values**, which can be either `True` or `False`
65
68
66
69
```{code-cell} python3
@@ -109,7 +112,13 @@ bools = [True, True, False, True] # List of Boolean values
109
112
sum(bools)
110
113
```
111
114
112
-
Complex numbers are another primitive data type in Python
115
+
#### Numeric Types
116
+
117
+
Numeric types are also important primitive data types.
118
+
119
+
We have seen `integer` and `float` types before.
120
+
121
+
**Complex numbers** are another primitive data type in Python
113
122
114
123
```{code-cell} python3
115
124
x = complex(1, 2)
@@ -185,13 +194,13 @@ Tuple unpacking is convenient and we'll use it often.
185
194
```{index} single: Python; Slicing
186
195
```
187
196
188
-
To access multiple elements of a list or tuple, you can use Python's slice
197
+
To access multiple elements of a sequence (a list, a tuple or a string), you can use Python's slice
189
198
notation.
190
199
191
200
For example,
192
201
193
202
```{code-cell} python3
194
-
a = [2, 4, 6, 8]
203
+
a = ["a", "b", "c", "d", "e"]
195
204
a[1:]
196
205
```
197
206
@@ -207,6 +216,18 @@ Negative numbers are also permissible
207
216
a[-2:] # Last two elements of the list
208
217
```
209
218
219
+
You can also use the format `[start:end:step]` to specify the step
220
+
221
+
```{code-cell} python3
222
+
a[::2]
223
+
```
224
+
225
+
Using a negative step, you can return the sequence in a reversed order
226
+
227
+
```{code-cell} python3
228
+
a[-2::-1] # Walk backwards from the second last element to the first element
229
+
```
230
+
210
231
The same slice notation works on tuples and strings
211
232
212
233
```{code-cell} python3
@@ -340,7 +361,7 @@ To give an example, let's write the file us_cities.txt, which lists US cities an
340
361
341
362
(us_cities_data)=
342
363
```{code-cell} ipython
343
-
%%file us_cities.txt
364
+
%%writefile us_cities.txt
344
365
new york: 8244910
345
366
los angeles: 3819702
346
367
chicago: 2707120
@@ -352,7 +373,7 @@ san diego: 1326179
352
373
dallas: 1223229
353
374
```
354
375
355
-
Here %%file is an [IPython cell magic](https://ipython.readthedocs.io/en/stable/interactive/magics.html#cell-magics).
376
+
Here `%%writefile` is an [IPython cell magic](https://ipython.readthedocs.io/en/stable/interactive/magics.html#cell-magics).
356
377
357
378
Suppose that we want to make the information more readable, by capitalizing names and adding commas to mark thousands.
358
379
@@ -562,6 +583,23 @@ Remember
562
583
*`P and Q` is `True` if both are `True`, else `False`
563
584
*`P or Q` is `False` if both are `False`, else `True`
564
585
586
+
We can also use `all()` and `any()` to test a sequence of expressions
587
+
588
+
```{code-cell} python3
589
+
all([1 <= 2 <= 3, 5 <= 6 <= 7])
590
+
```
591
+
```{code-cell} python3
592
+
all([1 <= 2 <= 3, "a" in "letter"])
593
+
```
594
+
```{code-cell} python3
595
+
any([1 <= 2 <= 3, "a" in "letter"])
596
+
```
597
+
598
+
Note:
599
+
600
+
*`all()` returns `True` when *all* boolean values/expressions in the sequence are `True`
601
+
*`any()` returns `True` when *any* boolean values/expressions in the sequence are `True`
602
+
565
603
## More Functions
566
604
567
605
```{index} single: Python; Functions
@@ -739,92 +777,6 @@ Part 3: Given `pairs = ((2, 5), (4, 2), (9, 8), (12, 10))`, count the number of
739
777
such that both `a` and `b` are even.
740
778
```
741
779
742
-
743
-
```{exercise-start}
744
-
:label: pyess_ex2
745
-
```
746
-
747
-
Consider the polynomial
748
-
749
-
```{math}
750
-
:label: polynom0
751
-
752
-
p(x)
753
-
= a_0 + a_1 x + a_2 x^2 + \cdots a_n x^n
754
-
= \sum_{i=0}^n a_i x^i
755
-
```
756
-
757
-
Write a function `p` such that `p(x, coeff)` that computes the value in {eq}`polynom0` given a point `x` and a list of coefficients `coeff`.
758
-
759
-
Try to use `enumerate()` in your loop.
760
-
761
-
```{exercise-end}
762
-
```
763
-
764
-
765
-
```{exercise}
766
-
:label: pyess_ex3
767
-
768
-
Write a function that takes a string as an argument and returns the number of capital letters in the string.
769
-
770
-
Hint: `'foo'.upper()` returns `'FOO'`.
771
-
```
772
-
773
-
774
-
```{exercise}
775
-
:label: pyess_ex4
776
-
777
-
Write a function that takes two sequences `seq_a` and `seq_b` as arguments and
778
-
returns `True` if every element in `seq_a` is also an element of `seq_b`, else
779
-
`False`.
780
-
781
-
* By "sequence" we mean a list, a tuple or a string.
782
-
* Do the exercise without using [sets](https://docs.python.org/3/tutorial/datastructures.html#sets) and set methods.
783
-
```
784
-
785
-
786
-
```{exercise}
787
-
:label: pyess_ex5
788
-
789
-
When we cover the numerical libraries, we will see they include many
790
-
alternatives for interpolation and function approximation.
791
-
792
-
Nevertheless, let's write our own function approximation routine as an exercise.
793
-
794
-
In particular, without using any imports, write a function `linapprox` that takes as arguments
795
-
796
-
* A function `f` mapping some interval $[a, b]$ into $\mathbb R$.
797
-
* Two scalars `a` and `b` providing the limits of this interval.
798
-
* An integer `n` determining the number of grid points.
799
-
* A number `x` satisfying `a <= x <= b`.
800
-
801
-
and returns the [piecewise linear interpolation](https://en.wikipedia.org/wiki/Linear_interpolation) of `f` at `x`, based on `n` evenly spaced grid points `a = point[0] < point[1] < ... < point[n-1] = b`.
802
-
803
-
Aim for clarity, not efficiency.
804
-
```
805
-
806
-
```{exercise-start}
807
-
:label: pyess_ex6
808
-
```
809
-
810
-
Using list comprehension syntax, we can simplify the loop in the following
811
-
code.
812
-
813
-
```{code-cell} python3
814
-
import numpy as np
815
-
816
-
n = 100
817
-
ϵ_values = []
818
-
for i in range(n):
819
-
e = np.random.randn()
820
-
ϵ_values.append(e)
821
-
```
822
-
823
-
```{exercise-end}
824
-
```
825
-
826
-
## Solutions
827
-
828
780
```{solution-start} pyess_ex1
829
781
:class: dropdown
830
782
```
@@ -884,10 +836,31 @@ sum([x % 2 == 0 and y % 2 == 0 for x, y in pairs])
884
836
```{solution-end}
885
837
```
886
838
839
+
```{exercise-start}
840
+
:label: pyess_ex2
841
+
```
842
+
843
+
Consider the polynomial
844
+
845
+
```{math}
846
+
:label: polynom0
847
+
848
+
p(x)
849
+
= a_0 + a_1 x + a_2 x^2 + \cdots a_n x^n
850
+
= \sum_{i=0}^n a_i x^i
851
+
```
852
+
853
+
Write a function `p` such that `p(x, coeff)` that computes the value in {eq}`polynom0` given a point `x` and a list of coefficients `coeff` ($a_1, a_2, \cdots a_n$).
854
+
855
+
Try to use `enumerate()` in your loop.
856
+
857
+
```{exercise-end}
858
+
```
887
859
888
860
```{solution-start} pyess_ex2
889
861
:class: dropdown
890
862
```
863
+
Here’s a solution:
891
864
892
865
```{code-cell} python3
893
866
def p(x, coeff):
@@ -902,6 +875,14 @@ p(1, (2, 4))
902
875
```
903
876
904
877
878
+
```{exercise}
879
+
:label: pyess_ex3
880
+
881
+
Write a function that takes a string as an argument and returns the number of capital letters in the string.
882
+
883
+
Hint: `'foo'.upper()` returns `'FOO'`.
884
+
```
885
+
905
886
```{solution-start} pyess_ex3
906
887
:class: dropdown
907
888
```
@@ -932,6 +913,18 @@ count_uppercase_chars('The Rain in Spain')
932
913
```
933
914
934
915
916
+
917
+
```{exercise}
918
+
:label: pyess_ex4
919
+
920
+
Write a function that takes two sequences `seq_a` and `seq_b` as arguments and
921
+
returns `True` if every element in `seq_a` is also an element of `seq_b`, else
922
+
`False`.
923
+
924
+
* By "sequence" we mean a list, a tuple or a string.
925
+
* Do the exercise without using [sets](https://docs.python.org/3/tutorial/datastructures.html#sets) and set methods.
926
+
```
927
+
935
928
```{solution-start} pyess_ex4
936
929
:class: dropdown
937
930
```
@@ -940,14 +933,27 @@ Here's a solution:
940
933
941
934
```{code-cell} python3
942
935
def f(seq_a, seq_b):
943
-
is_subset = True
944
936
for a in seq_a:
945
937
if a not in seq_b:
946
-
is_subset = False
947
-
return is_subset
938
+
return False
939
+
return True
948
940
949
941
# == test == #
942
+
print(f("ab", "cadb"))
943
+
print(f("ab", "cjdb"))
944
+
print(f([1, 2], [1, 2, 3]))
945
+
print(f([1, 2, 3], [1, 2]))
946
+
```
947
+
948
+
An alternative, more pythonic solution using `all()`:
949
+
950
+
```{code-cell} python3
951
+
def f(seq_a, seq_b):
952
+
return all([i in seq_b for i in seq_a])
950
953
954
+
# == test == #
955
+
print(f("ab", "cadb"))
956
+
print(f("ab", "cjdb"))
951
957
print(f([1, 2], [1, 2, 3]))
952
958
print(f([1, 2, 3], [1, 2]))
953
959
```
@@ -963,9 +969,30 @@ def f(seq_a, seq_b):
963
969
```
964
970
965
971
972
+
```{exercise}
973
+
:label: pyess_ex5
974
+
975
+
When we cover the numerical libraries, we will see they include many
976
+
alternatives for interpolation and function approximation.
977
+
978
+
Nevertheless, let's write our own function approximation routine as an exercise.
979
+
980
+
In particular, without using any imports, write a function `linapprox` that takes as arguments
981
+
982
+
* A function `f` mapping some interval $[a, b]$ into $\mathbb R$.
983
+
* Two scalars `a` and `b` providing the limits of this interval.
984
+
* An integer `n` determining the number of grid points.
985
+
* A number `x` satisfying `a <= x <= b`.
986
+
987
+
and returns the [piecewise linear interpolation](https://en.wikipedia.org/wiki/Linear_interpolation) of `f` at `x`, based on `n` evenly spaced grid points `a = point[0] < point[1] < ... < point[n-1] = b`.
988
+
989
+
Aim for clarity, not efficiency.
990
+
```
991
+
966
992
```{solution-start} pyess_ex5
967
993
:class: dropdown
968
994
```
995
+
Here’s a solution:
969
996
970
997
```{code-cell} python3
971
998
def linapprox(f, a, b, n, x):
@@ -1008,6 +1035,26 @@ def linapprox(f, a, b, n, x):
1008
1035
```
1009
1036
1010
1037
1038
+
```{exercise-start}
1039
+
:label: pyess_ex6
1040
+
```
1041
+
1042
+
Using list comprehension syntax, we can simplify the loop in the following
0 commit comments