예제 #1
0
from utils.common import int_list


def partition(a, x):
    i, j = 0, len(a) - 1
    while i < j:
        while a[i] < x:
            i += 1
        while a[j] > x:
            j -= 1
        a[i], a[j] = a[j], a[i]


_, line = open('array.txt')
arr = int_list(line)
partition(arr, arr[0])

res = ' '.join(map(str, arr))
open('res.txt', 'w').write(res)
예제 #2
0
from utils.common import int_list


def find_opposites(a):
    for i in range(len(a)):
        for j in range(i + 1, len(a)):
            if a[i] == -a[j]:
                return i, j
    return -1, -1


_, *lines = open('arrays.txt')
arrays = [int_list(line.rstrip()) for line in lines]

for p, q in map(find_opposites, arrays):
    print(p if p == -1 else f'{p + 1} {q + 1}')
예제 #3
0
from utils.arrays import merge
from utils.common import int_list


# Recursion implementation. Works only for small data sets.
# Parameter `c` needed for storing result.
def merge_lists(a, b, c):
    if len(a) and len(b):
        ls, gt = (a, b) if a[0] < b[0] else (b, a)
        c.append(ls[0])
        merge_lists(ls[1:], gt, c)
    else:
        c += a if len(a) else b


_, line1, _, line2 = open('arrays.txt')
arr1, arr2 = int_list(line1), int_list(line2)

merged = merge(arr1, arr2)
print(*merged)
예제 #4
0
from utils.common import int_list


def insertion_sort(a):
    swap_count = 0
    for i in range(2, len(a)):
        j = i
        while j > 0 and a[j] < a[j - 1]:
            a[j - 1], a[j] = a[j], a[j - 1]
            j -= 1
        swap_count += i - j
    return swap_count


arr = int_list(next(open('array.txt')))
swaps = insertion_sort(arr)
print(swaps)
예제 #5
0
 def test_int_list(self):
     self.assertListEqual([9, 7, 5, 3, 1], int_list('9 7 5 3 1'))
예제 #6
0

def search(a, x):
    i, j = 0, len(a) - 1
    mid = j // 2
    while a[mid] != x and i < j:
        i, j = (mid + 1, j) if a[mid] < x else (i, mid)
        mid = (i + j) // 2
    return mid if a[mid] == x else -2


def search_values(a, b):
    cache, res = {}, []
    for x in b:
        if x not in cache:
            cache[x] = search(a, x)
        res.append(cache[x])
    return res


def stringify_result(a):
    return ' '.join(map(lambda v: str(v + 1), a))


arr1, arr2 = open('values.txt')
ordered = int_list(arr1)
values = int_list(arr2)

indices = stringify_result(search_values(ordered, values))
open('res.txt', 'w').write(indices)