2022.01.26 MATH 3600 loops etc

122 days ago by calkin

To create a list of integers, starting at 0 and stopping before n, use srange(n).

L=srange(10) print(L) 
       
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
M=range(10) print(M) 
       
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
print(type(L[0]),type(M[0])) 
       
(<type 'sage.rings.integer.Integer'>, <type 'int'>)
(<type 'sage.rings.integer.Integer'>, <type 'int'>)
a=L[0] 
       
b=M[0] 
       

The reason for using srange() rather than range() is that the elements of the list produced are of type Integer rather than int.

Given a list $L$, we can step through the elements one by one by using the for command.

for i in srange(10): print(i,i^2) 
       
(0, 0)
(1, 1)
(2, 4)
(3, 9)
(4, 16)
(5, 25)
(6, 36)
(7, 49)
(8, 64)
(9, 81)
(0, 0)
(1, 1)
(2, 4)
(3, 9)
(4, 16)
(5, 25)
(6, 36)
(7, 49)
(8, 64)
(9, 81)
L=[1,2,3,4,'Fred'] for i in L: print(i) 
       
1
2
3
4
Fred
1
2
3
4
Fred
L=srange(10) M=[] for i in L: M.append([i,i^2]) 
       
print(M) 
       
[[0, 0], [1, 1], [2, 4], [3, 9], [4, 16], [5, 25], [6, 36], [7, 49], [8,
64], [9, 81]]
[[0, 0], [1, 1], [2, 4], [3, 9], [4, 16], [5, 25], [6, 36], [7, 49], [8, 64], [9, 81]]
show(M) 
       

We can access the $k$th element of a list $L$ by asking for $L[k]$.  

Suppose we wanted a list-like object, but only wanted to call it for primes: for example,

an object psquared, where psquared[p] should give us $p^2$.

psquared={2:4,3:9} 
       
print(psquared[3]) print("Don't be an idiot") for i in psquared: print(i) for i in psquared: print(psquared[i]) 
       
9
Don't be an idiot
2
3
4
9
9
Don't be an idiot
2
3
4
9
psquared.has_key(5) 
       
False
False
psquared.has_key(3) 
       
True
True
psquared.items()[0] 
       
(2, 4)
(2, 4)
psquared[5]=25 
       
print(psquared) 
       
{2: 4, 3: 9, 5: 25}
{2: 4, 3: 9, 5: 25}
psquared[3]=10 print(psquared) psquared[3]=9 print(psquared) 
       
{2: 4, 3: 10, 5: 25}
{2: 4, 3: 9, 5: 25}
{2: 4, 3: 10, 5: 25}
{2: 4, 3: 9, 5: 25}
for i in srange(10): if is_prime(i): if psquared.has_key(i)==False: psquared[i]=i^2 
       
print(psquared) 
       
{2: 4, 3: 9, 5: 25, 7: 49}
{2: 4, 3: 9, 5: 25, 7: 49}

While loops: allow us to use a conditional statement to determine whether to continue going through the loop

i=0 while i<10: if is_prime(i): print(i) else: print(-i) i+=1 
       
0
-1
2
3
-4
5
-6
7
-8
-9
0
-1
2
3
-4
5
-6
7
-8
-9

Another useful thing to do with while loops is use flags

i=2 flag=True while flag: if is_prime(i+1): print(i+1) i=i^2 if i>=10^200: flag=False 
       
3
5
17
257
65537
3
5
17
257
65537
 
       
 
       
weird_list= srange(10) weird_list.append('Fred') print(weird_list) 
       
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 'Fred']
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 'Fred']