Solutions for os, subprocess, requests exercises

Ex 1: Alphabet List Comprehensions

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
# 1. Create a list of capital letters in the english alphabet

[chr(i) for i in range(65,91)]

# 2. Create a list of capital letter from the english aplhabet, but exclude 4 with the Unicode code point of either 70, 75, 80, 85.

[chr(i) for i in range(65,91) if i not in [70,75,80,85]]

# 3. Create a list of capital letter from from the english aplhabet, but exclude every second between F & O

[chr(i) for i in range(65,91) if i not in range(70,80,2)]

Ex 2: Clothes List Comprehension

1
2
3
4
5
6
7
8
9
colors = ['Black', 'White']
sizes = ['s', 'm', 'l', 'xl']

# 1
[(c,s) for c in colors for s in sizes]

# 2
soled_out = [('Black', 'm'), ('White', 's')]
[c,s) for c in colors for s in sizes if (c,s) not in soled_out]

Ex 2: Sort a Text

1
2
3
4
5
6
# Denne øvelse er vist lidt for kryptisk.
# Så glem den bare.

# Hvis i har fundet en løsning så kigger vi på den på torsdag, ellers glem denne øvelse.


Ex 3: List & tuple exercises

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
def match_ends(words):
    return len([w for w in words if len(w) > 1 and w[0] == w[-1]])

def front_x(words):
    x = [w for w in words if w[0] == 'x'] 
    y = [w for w in words if w[0] != 'x']
    return sorted(x) + sorted(y)

def sort_last(tuples):
    # this one is not realy suitable for list comprenhensions
    
    def last_element(t):
        return t[-1]

    return sorted(tuples, key=last_element)

# the last ones are not realy suitable for list comprenhensions

def remove_adjacent(nums):
    return list(set(nums)) # sets can only have unique elements 


def linear_merge(list1, list2):
    """
    res = []
    c1 = 0
    c2 = 0

    while len(list1) != c1 and len(list2) != c2:
        if list1[c1] < list2[c2]:
            res.append(list1[c1])
            c1 = c1 + 1 
        else:
            res.append(list2[c2])
            c2 = c2 + 1
        
        if len(list1) == c1:
            res = res + list2[c2:]

        if len(list2) == c2:
            res = res + list1[c1:]
    return res
    """
    # OR JUST:

    return sorted(list1+list2)

Ex 4: Sys module exercise

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
import sys

def main(argv):
    if argv[1] != '-it':
        print('Usage: python script.py [-it]{--rm}')
    if len(argv) == 3 and argv[2] != '--rm':
        print('Usage: python script.py [-it]{--rm}')
    elif len(argv) == 3 and argv[2] == '--rm':
        print('Goodby')
    else:
        input()

    sys.exit()

main(sys.argv)



Ex 5: OS Module exercise

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
import os

#1
os.mkdir('os_exercises.')
#2
os.chdir('os_exercises')
open('exercise.py', 'w')
#3
x = input('Please write something to the file: ')
with open('exercise.py', 'w') as f:
    f.write(x)

#4 
x = input('Please write something More to anoter file: ') 
with open('exercise2.py', 'w') as f:
    f.write(x)

#5
with open('exercise.py', 'r') as f1:
    with open('exercise2.py', 'r' ) as f2:
        print(f1.read() + f2.read())

Ex 6: Extract .py files

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
import sys
import os
import subprocess
from zipfile import ZipFile 

def main(argv):

    input_check(argv)

    # A
    # list all files in folder
    x = os.listdir(argv[1])
    
    # list all .py files
    pyfiles = [i for i in x if i[-3:] == '.py']
    
    # create new dir
    os.mkdir(argv[3])

    # copy all files in list --todir
    for i in pyfiles:
        subprocess.run(['cp', i, argv[3]])

    #B
    with ZipFile(argv[3]+'/archive.zip', 'w') as zf:        
            for file in pyfiles:
                zf.write(file)

def input_check(argv):
    if len(argv) < 2:
        print('Usage: python extract.py [.] [--todir <<tmp/>>] {--zip <<filename.zip>>}')
        sys.exit()
    if len(argv) == 3 and argv[2] != '--todir':
        print('Usage: python extract.py [.] [--todir <<tmp/>>] {--zip <<filename.zip>>}')
        sys.exit()

main(sys.argv)

Ex 7: Simple scraber with requests

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49

import requests
import os

# fetch the html from a url
req = requests.get('https://clbokea.github.io/exam/assignment_2.html')
text = req.text

img_url_list = [] 

text_list = text.split('img')

def locate_image(e):
    i = e.find('"')

    # cut after  'src="' to end of the img_url  
    img_url = e.split('"')
    img_url = img_url[1]
    img_url_list.append(img_url)


for e in text_list:
    if 'src' in e:
        locate_image(e)

# print(img_url_list)

# Create a src directory for the images
os.mkdir('src')
os.chdir('src')

for i in img_url_list:
    # get the image
    req = requests.get(f'https://clbokea.github.io/exam/{i}', stream=True)

    # write image to file
    with open(i[4:], 'wb') as f:
        for chunk in req:
            f.write(chunk)

os.chdir('..')

with open('index.html', 'w') as f:
    f.write(text)