Black Mamba

Faster, Higher, Stronger.

Python Notes III

Sort in two ways

  • sort(): In-place sorting, replaces the original data
  • sorted(): Copied sorting, return a sorted copy of the original data
  • sorting order
1
2
sorted(data)    # Ascending
sorted(data, reverse=True)  # Descending
  • Get top 3 data from file
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
def sanitize(time_string):
    if '-' in time_string:
        splitter = '-'
    elif ':' in time_string:
        splitter = ':'
    else:
        return (time_string)

    (mins, secs) = time_string.split(splitter)
    return (mins + '.' + secs)

def get_data(filename):
    try:
        with open(filename) as file:
            data = file.readline()
        return data.strip().split(',')
    except IOError as ioerr:
        print('File error: ' + str(ioerr))
        return(None)

# file operation
james = get_data('james.txt')

clean_james = []
for each_t in james:
    clean_james.append(sanitize(each_t))

unique_james = []
for each_t in clean_james:
    if each_t not in unique_james:
        unique_james.append(each_t)
print(sorted(unique_james)[0:3])
  • Remove the duplicates
1
2
# file operation can be replaced with one line code
print(sorted(set([sanitize(each_t) for each_t in get_date("james.txt")]))[0:3])
  • Bundle the code and data in a dictionary
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
def get_data(filename):
    try:
        with open(filename) as file:
            data = file.readline()
        temp = data.strip().split(',')

        # return a dictionary
        return({'Name' : temp.pop(0),
                'DOB'  : temp.pop(0),
                'Times': str(sorted(set([sanitize(each_t) for each_t in temp]))[0:3])})
        except IOError as ioerr:
            print('File error: ' + str(ioerr))
            return(None)

sarah = get_data('sarah2.txt')
print(sarah['Name'] + "'s fastest times are: " + sarah['Times'])
  • Amend the code and data in a class that inherit from BIF list
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class Athlete(list):
    def __init__(self, a_name, a_dob=None, a_times=[]):
        list.__init__([])
        self.name = a_name
        self.dob = a_dob
        self.extend(a_times)

def top3(self):
    return(str(sorted(set([sanitize(each_t) for each_t in self]))[0:3]))

def get_data(filename):
    try:
        ...
        return(Athlete(temp.pop(0), temp.pop(0), temp))
    except IOError as ioerr:
        ...

sarah = get_data('sarah2.txt')
print(sarah.name + "'s fastest times are: " + sarah.top3())

Model the data

  • Put class AthleteList in a module file
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
import pickle
# class AthleteList is saved in athletelist.py, import AthleteList using this line of code
# use dir() command to confirm that the import has been successful
from athletelist import AthleteList

def get_data(filename):
    ...

def put_to_store(file_list):
    all_athletes = {}
    for each_file in file_list:
        ath = get_data(each_file)
        all_athletes[ath.name] = ath
    try:
        with open('athletes.pickle', 'wb') as athf:
            pickle.dump(all_athletes, athf)
    except IOError as ioerr:
        print('File error (put_and_store): ' + str(ioerr))
        return (all_athletes)

def get_from_store():
    all_athletes = {}
    try:
        with open('athletes.pickle', 'rb') as athf:
            all_athletes = pickle.load(athf)
        except IOError as ioerr:
            print('File error (get_from_store): ' + str(ioerr))
            return (all_athletes)

Bonus I: Factory Function: set()

  • Build an unordered collection of unique elements
1
2
3
4
data = [1,1,13,3,3,2,2,3,1,13,1]
set(data)
# output
{1, 2, 3, 13}

Bonus II: BIF: pop(i)

  • pop(i) call returns and removes data from the front of a list at location
1
2
3
4
5
6
data = [1,13,3,3,1]
data.pop(3)
# output
3
data
[1,13,3,1]

Bonus III: List Comprehension

  • When the code is like this
1
2
3
4
new = []
for each_item in old:
    ...
append(len(each_item))
  • Rewrite it like this
1
new = [len(each_item) for each_item in old]

Bonus IV: Dictionary

  • Two way to create an empty dictionary
1
2
3
4
# method 1
d1 = {}
# method 2
d2 = dict()

Comments