Ejemplo n.º 1
0
    def version_1(test):
        (given, expected) = test

        sorted_given = given[:] # doesn't enter in the O(.) calculation
        merge_sort(sorted_given)

        return sorted_given == expected
Ejemplo n.º 2
0
    def reducing(self, data1, data2):

        # returns a list
        reduced1 = self.fill_reduced(data1)
        reduced2 = self.fill_reduced(data2)

        if len(reduced1) < len(reduced2):
            main = reduced1
            secondary = reduced2
        else:
            main = reduced2
            secondary = reduced1

        arr = []
        for i, elem in enumerate(main):
            str_find = elem[0]
            index = binary_search(secondary, 0, len(secondary) - 1, str_find)

            if index != -1:
                second_item = secondary[index]
                second_value = second_item[1]
                secondary.remove(second_item)
                temp = main[i]
                temp_str = temp[0]
                final_value = temp[1] + second_value
                arr.append((temp_str, final_value))
            else:
                arr.append(elem)

        if len(secondary) != 0:
            arr.extend(secondary)
            merge_sort(arr)

        return arr
Ejemplo n.º 3
0
def pb22():
    """
    Problem 22 : Names scores.
    We first open the file, suppress the useless ", put everything into lowercase, and split to get a list.
    We use merge sort to sort the list by alphabetical order (see utils.merge_sort), and then :
    - for each word in the list
        - for each character in the list we get its alphabetical rank (ord - 96, that why we needed lowercase) and we sum.
    """
    res = 0
    with open('./resources/input_pb22.txt', 'r') as f:
        lst = f.readline().replace('"', '').lower().split(sep=',')
    utils.merge_sort(lst)
    for i in range(len(lst)):
        res += sum([ord(char) - 96 for char in lst[i]]) * (i + 1)
    return res
Ejemplo n.º 4
0
def view_all():
    """ View list of students. """
    db = DBHandler(DBNAME)
    students = db.get_all_students()
    db.close_connection()
    students = merge_sort(students)
    return render_template('view_all.html', student_list=students)
Ejemplo n.º 5
0
def plot_chat_diagram(dates, messages, directory="."):
    for date in range(min(dates) + 1, max(dates)):
        if date not in dates:
            dates.append(date)
            messages.append(0)
    merge_sort(dates, 0, len(dates) - 1, messages)
    dates = list(map(lambda date: date - dates[0], dates))
    print("Almost done...")
    for i in range(1, len(messages)):
        messages[i] += messages[i - 1]
    plt.figure()
    plt.plot(dates, messages, 'b')
    plt.xlim(dates[0], dates[-1])
    plt.xlabel("Day Number(Origin=First message)")
    plt.ylabel("Total messages until that day")
    plt.title(f"Total messages: {messages[-1]}")
    plt.savefig(os.path.join(directory, 'Diagram.png'))
    plt.show()
Ejemplo n.º 6
0
    def version_1(test):
        (given, expected) = test

        anagrams = dict()
                                        # O(N*W*logW)
        for word in given:              # O(N)
            sorted_word = list(word)
            merge_sort(sorted_word)     # O(W*logW)
            sorted_word = ''.join(sorted_word)

            if sorted_word in anagrams:
                anagrams[sorted_word].append(word)
            else:
                anagrams[sorted_word] = [word]

        keys = list(anagrams.keys())
        merge_sort(keys)

        sorted_words = list()

                                        # O(N*W*logW)
        for key in keys:                # O(1..N/p..N) (#keys <= N and p = #words/key)
            merge_sort(anagrams[key])   # O(W*logW)
            for word in anagrams[key]:  # O(N..p..1) (p = #words/key)
                sorted_words.append(word)

        return sorted_words == expected
Ejemplo n.º 7
0
from utils import merge_sort, binary_search

if __name__ == '__main__':
    list_of_nums = [7, 4, 9, 3, 5, 6, 1, 2]
    print('List of nums is:')
    print(list_of_nums)

    merge_sort(list_of_nums)

    print('Sorted list of nums is:')
    print(list_of_nums)

    index_of_5 = binary_search(list_of_nums, 5)
    print(f'Index of 5 is: {index_of_5}')
Ejemplo n.º 8
0
from utils import half_find, bubble_sort, bubble_better, choice_sort, insert_sort, quick_sort, heap_sort, merge_sort, \
    shell_sort

# 为快速排序设置递归深度,否则会超出递归深度而报错
sys.setrecursionlimit(10000)

# 生成序列
a = range(10000)
random.shuffle(a)
l1 = copy.copy(a)
l2 = copy.copy(a)
l3 = copy.copy(a)
l4 = copy.copy(a)
l5 = copy.copy(a)
l6 = copy.copy(a)
l7 = copy.copy(a)
l8 = copy.copy(a)

# 各排序算法执行
r1 = bubble_sort(l1)  # 冒泡排序(O(N**2))
r2 = bubble_better(l2)  # 冒泡排序优化(O(N**2))
r3 = choice_sort(l3)  # 选择排序(O(N**2))
r4 = insert_sort(l4)  # 插入排序(O(N**2))
r5 = quick_sort(l5)  # 快速排序(O(n*logn))
r6 = heap_sort(l6)  # 堆排序(O(n*logn))
r7 = merge_sort(l7)  # 归并排序(O(n*logn))
r8 = shell_sort(l8)  # 希尔排序(O(1.3n))

# 二分查找执行
r9 = half_find(r6, random.randint(0, len(a)))