Example #1
0
def cadusers():
    users = {
        'nome': '',
        'sobrenome': '',
        'login': '',
        'senha': '',
        'conf_senha': '',
    }

    print("#" * 30)
    print("Cadastro de Usuários.")
    print("Precione 'q' para sair.")
    print("#" * 30)

    while True:
        users['nome'] = get_input("Digite o nome do usuário: ")
        if users['nome'] == 'q':
            break
            users.clean()

        users['sobrenome'] = get_input("Digite o sobrenome do usuário: ")
        if users['sobrenome'] == 'q':
            break
            users.clean()

        users['login'] = get_input("Digite o login do usuário: ")
        if users['login'] == 'q':
            break
            users.clean()

        users['senha'] = getpass("Digite a senha do usuário: ")
        if users['login'] == 'q':
            break
            users.clean()

        users['conf_senha'] = getpass("Confirme a senha do usuário: ")
        if users['login'] == 'q':
            break
            users.clean()

        save = get_input("Deseja salvar as informações do usuário? 's'/'n': ")
        if save == 's':
            colunas = users.keys()
            values = users.values()
            insert_info = ("INSERT INTO Users (%s) VALUES ('%s')" %
                           (",".join(colunas), "','".join(values)))
            connsql(insert_info)
            print("Dados salvos com sucesso!")
        else:
            break
        new_user = get_input("Deseja cadastrar outro usuário? 's'/'n': ")
        if new_user == 's':
            continue
        else:
            break
Example #2
0
def test_code():
    assert code('""') == ''
    assert code('"abc"') == 'abc'
    assert code('"aaa\"aaa"') == 'aaa"aaa'
    assert code('"\x27"') == "'"
    for line in get_input(day=8, year=2015).splitlines():
        assert eval(line) == code(line)
Example #3
0
def test_escape():
    assert escape('""') == r'"\"\""'
    assert escape('"abc"') == r'"\"abc\""'
    assert escape(r'"aaa\"aaa"') == r'"\"aaa\\\"aaa\""'
    assert escape(r'"\x27"') == r'"\"\\x27\""'
    for line in get_input(day=8, year=2015).splitlines():
        assert line == code(escape(line))
Example #4
0
def main():
    # get input file name from command line argument
    file_name = sys.argv[1]

    start_time = time.time()
    # parse the input and return a list of cards
    list_of_cards = get_input.get_input(file_name)

    # find the number of SET's
    no_of_sets, list_of_sets = find_sets.find_set(list_of_cards)

    # find the disjoint SET's
    no_of_disjoint_sets, list_of_disjoint_sets = find_disjoint_sets.find_disjoint(
        list_of_sets)

    print("Execution time : %s" % (time.time() - start_time))

    # print the results
    print(no_of_sets)
    print(no_of_disjoint_sets)
    print()
    for y in list_of_disjoint_sets:
        for z in range(3):
            print(y[z])
        print()
    print("Execution time : %s" % (time.time() - start_time))
Example #5
0
def main(strExp="", vbose=False):

    from output import verbose_output, touch, folder_maker
    from get_input import get_input, format_input

    #   Set the input string expression (strExp)
    if strExp == "":
        strExp = get_input()
    else:
        strExp = format_input(strExp)

    #process parsed elements into the folder object
    result_folder = parse(strExp[1:-1], fold())

    if vbose:
        try:
            verbose_output(result_folder, "")
        except:
            print "VERBOSE_OUTPUT ERROR"

    try:
        folder_maker(result_folder, "./")
    except:
        print "FOLDER_MAKER ERROR"
    return result_folder
Example #6
0
def main():
    day = int(os.path.basename(__file__).replace('day', '').replace('.py', ''))
    data = get_input.get_input(day)

    hvac_map = Map(data)

    poi = {}

    for i, c in enumerate(hvac_map):
        if c.isdigit():
            poi[int(c)] = i

    n_poi = len(poi)

    dists = np.zeros((n_poi, n_poi), dtype=np.int32)

    for a, b in combinations(range(n_poi), 2):
        pos_a = poi[a]
        pos_b = poi[b]
        steps = hvac_map.get_steps(pos_a, pos_b)
        dists[a, b] = dists[b, a] = steps

    # Part 1: Random end position
    total_dist_min = 1e10
    for order in permutations(range(1, n_poi)):
        order = [0] + list(order)
        total_dist = 0
        for i in range(1, len(order)):
            total_dist += dists[order[i - 1], order[i]]

        if total_dist < total_dist_min:
            total_dist_min = total_dist

    print(
        'Minimum steps to visit all important places starting at 0: {}'.format(
            total_dist_min))

    # Part 2: Back to position 0
    total_dist_min = 1e10
    for order in permutations(range(1, n_poi)):
        order = [0] + list(order) + [0]
        total_dist = 0
        for i in range(1, len(order)):
            total_dist += dists[order[i - 1], order[i]]

        if total_dist < total_dist_min:
            total_dist_min = total_dist

    print(
        'Minimum steps to visit all important places starting at 0 and back to 0: {}'
        .format(total_dist_min))
Example #7
0
def hello_world():
    speak = "Wow, you look really sad! Try smiling more!"
    play_audio(speak)

    speak = "What is your number 1 goal for today?"
    play_audio(speak)

    userInput = get_input()
    analyzed = analyze_text(userInput)
    print("Analyzed: " + analyzed)

    quote = get_quotes(analyzed)

    play_audio(quote)
def select_model():

    net_options = list('to ' + net_name + ' press ' + str(i) for i, net_name in enumerate(MY_NETS))
    message = 'Please select the requested net:\n'
    net_name = get_input(message, net_options, MY_NETS)

    if net_name == DEBLUR:
        deblur = Deblur()
        blur = Blur()
        return deblur, blur, net_name
    else:
        denoise = Denoise()
        noise = Noise()
        return denoise, noise, net_name
Example #9
0
def main():
    day = int(os.path.basename(__file__).replace('day', '').replace('.py', ''))
    data = get_input.get_input(day)

    # Altered data, changed multiplying loops to single command for speedup
    data = """cpy a b
dec b
cpy a d
cpy 0 a
cpy b c
nop #inc a
nop #dec c
nop #jnz c -2
nop #dec d
mtp a c d #jnz d -5
dec b
cpy b c
cpy c d
dec d
inc c
jnz d -2
tgl c
cpy -16 c
jnz 1 c
cpy 78 c
jnz 70 d
nop #inc a
nop #inc d
nop #jnz d -2
nop #inc c
mtp a c d #jnz c -5"""

    lines = data.split('\n')

    lines_parts = []

    for line in lines:
        lines_parts.append(line.split(' '))

    reg = {'a': 7, 'b': 0, 'c': 0, 'd': 0}
    reg = assem(reg, deepcopy(lines_parts))

    print('Value in register a for input 7: {}'.format(reg['a']))

    reg = {'a': 12, 'b': 0, 'c': 0, 'd': 0}
    reg = assem(reg, deepcopy(lines_parts))

    print('Value in register a for input 12: {}'.format(reg['a']))
Example #10
0
def main():
	output_dir,iPod_drive,music_dir,song_db_loc = get_input()
	
	print "output directory: {0}".format(output_dir)
	print "iPod: {0}".format(iPod_drive)
	print "music directory: {0}".format(music_dir)
	tag_list,attrib_key_dict,attrib_dict = load_database(iPod_drive,music_dir,song_db_loc)

	print
	print "Now that setup has been taken care of, welcome! This application was designed to assist you in copying songs from your iPod to your computer. While this application allows for filtering by different attributes, the central feature is the ability to rename your files based on their metadata. Enjoy!"

	print "For help, simply type the word \"help\"."

	while True:
		choice_num,choice_str = prompt(actions,2,message="Please select an action",hidden_options={"help":False})

		perform_action(choice_str,iPod_drive,output_dir,tag_list)
def main():
    # 模式选择
    mode, file_old_, file_new_, image_new_folder, \
    b_path_type_img_folder, b_keep_structure, \
    b_keep_original_img, b_download_web_image, b_convert_to_relative_path = get_input()

    file_old_path_ls, file_new_path_ls, image_new_folder_ls = [], [], []

    if mode == "Folder":
        file_old_folder, file_new_folder = file_old_, file_new_
        file_old_path_ls = search_file_flat(file_old_folder, suffix_ls=[".md"], flag_ls=None, case_sensitive=False)
        for file_old_path in file_old_path_ls:
            if b_keep_structure:
                # file_old_folder/b/c/xxx.md ==>  file_new_folder/b/c/xxx.md
                file_new_path = file_new_folder + file_old_path.split(file_old_folder)[1]
            else:
                # file_old_folder/b/c/xxx.md ==>  file_new_folder/xxx.md
                file_new_path = os.path.join(file_new_folder, os.path.split(file_old_path)[1])
            image_new_folder_trans = deal_with_image_folder_path(image_new_folder, b_path_type_img_folder, file_new_path)
            file_new_path_ls.append(file_new_path)
            image_new_folder_ls.append(image_new_folder_trans)

    elif mode == "File":
        file_old_path, file_new_path = file_old_, file_new_
        image_new_folder_trans = deal_with_image_folder_path(image_new_folder, b_path_type_img_folder, file_new_path)
        file_old_path_ls.append(file_old_path)
        file_new_path_ls.append(file_new_path)
        image_new_folder_ls.append(image_new_folder_trans)

    # print(file_old_path_ls)
    # print(file_new_path_ls)
    # print(image_new_folder_ls)
    for i in range(len(file_new_path_ls)):
        steward(file_old_path_ls[i], file_new_path_ls[i], image_new_folder_ls[i],
                b_convert_to_relative_path, b_download_web_image,
                b_keep_original_img)

    print("\nCongratulations, accomplished!\nThe output path is %s\n\n(/≧▽≦)/\n" % file_new_)
Example #12
0
    return start


def part1(boardingpasses):
    max_id = 0
    for boardingpass in boardingpasses:
        row = binary_search([char == "F" for char in boardingpass[:7]], 0, 127)
        col = binary_search([char == "L" for char in boardingpass[7:]], 0, 7)
        max_id = max(row * 8 + col, max_id)
    return max_id


def part2(boardingpasses):
    seats = {(row, col) for row in range(128) for col in range(8)}
    for boardingpass in boardingpasses:
        row = binary_search([char == "F" for char in boardingpass[:7]], 0, 127)
        col = binary_search([char == "L" for char in boardingpass[7:]], 0, 7)
        seats.remove((row, col))
    seat = [s for s in seats if 10 < s[0] and s[0] < 100]
    assert len(seat) == 1
    seat = seat.pop()
    return seat[0] * 8 + seat[1]


if __name__ == "__main__":
    LINES = line_parser(get_input(day=5, year=2020), parse=list)
    assert binary_search([c == "F" for c in "FBFBBFF"], 0, 127) == 44
    assert binary_search([c == 'L' for c in "RLR"], 0, 7) == 5
    print(f"Part 1: {part1(LINES)}")
    print(f"Part 2: {part2(LINES)}")
Example #13
0
    for bot in runner.run(output='bot'):
        for b, bot in bot.items():
            if 61 in bot and 17 in bot:
                return b

text = """
value 5 goes to bot 2
bot 2 gives low to bot 1 and high to bot 0
value 3 goes to bot 1
bot 1 gives low to output 1 and high to bot 0
bot 0 gives low to output 2 and high to output 0
value 2 goes to bot 2
"""

def test_runner():
    runner = Runner(text.strip())
    for bots in runner.run('bot'):
        print(bots)
    assert runner.output == {0:{5,}, 1:{2,}, 2:{3,}}

def part2(runner):
    runner = deepcopy(runner)
    for output in runner.run(output='output'):
        if len(output[0]) > 0 and len(output[1]) > 0 and len(output[2]) > 0:
            return output[0].pop() * output[1].pop() * output[2].pop()

if __name__ == '__main__':
    runner = Runner(get_input(day=10, year=2016))
    print("Part 1: {}".format(part1(runner)))
    print("Part 2: {}".format(part2(runner)))
Example #14
0
'''Program for calling the function for smart input'''
import get_input

default_length = 30

input_type=""
length = 0
action = "lenient"

ch = raw_input("What type of Input do you Want (1 - Name   2-Number)   :   ")
if ch == "1":
	input_type = "name"
elif ch =="2":
	input_type = "number"

d=raw_input("\n\nEnter the Max Length : ")
try:
	length = int(d)
except:
	length = default_length

if input_type == "number":
	action = raw_input("\n\nEnter the Mode for length (strict or lenient) :")
	action = action.lower()

print ""

print get_input.get_input(input_type,length,action)
Example #15
0
        dest = cups.value - 1
        skip = {
            first.value,
            first.next.value,
            first.next.next.value,
        }
        while not (0 < dest <= num_nodes) or dest in skip:
            dest -= 1
            if dest <= 0:
                dest = num_nodes
        index = values[dest]
        last.next = index.next
        index.next = first
        cups = cups.next
    print()
    index = values[1]
    return index.next.value * index.next.next.value


def parse(text):
    return tuple(int(c) for c in text)


if __name__ == "__main__":
    assert part1(parse('389125467'), rounds=10) == 92658374
    assert part1(parse('389125467'), rounds=100) == 67384529
    assert part2(parse('389125467')) == 149245887792
    LINES = parse(get_input(day=23, year=2020).strip())
    print(f"Part 1: {part1(LINES)}")
    print(f"Part 2: {part2(LINES)}")
    birthdate:<mm/dd/yyyy>
    """
    bday_book = {}
    data = read_file(file_name)
    assert data, "There is no data!"
    data_chunks = chunk_data(data, 3)
    for chunk in data_chunks:
        username = parse(r"username:(?P<username>[\w.-]+)", 'username', chunk[0])
        nationality = parse("nationality:(?P<nationality>[a-zA-Z]+ ?[a-zA-Z]*)",
                            "nationality",
                            chunk[1],
                           )
        birthdate = parse("birthdate:(?P<birthdate>[0-9]{1,2}/[0-9]{1,2}/[0-9]{4})",
                          "birthdate",
                          chunk[2],
                         )
        if username and nationality and birthdate:
            bday_book[username] = User(username, nationality, birthdate)
    return bday_book

if __name__ == "__main__":
    FILE = 'user_data.txt' # Enter filename here.
    BDAY_BOOK = build_bday_book(FILE)
    USERNAME = get_input().lower()
    while not USERNAME.isspace() and USERNAME:
        if USERNAME in BDAY_BOOK:
            BDAY_BOOK[USERNAME].print_birthdate()
        else:
            print "Sorry, user not found."
        USERNAME = get_input().lower()
Example #17
0
def part2(directions):
    position = (0, 0)
    heading = (0, 1)
    visited = set()
    turn = {
        'R': lambda m: (-m[1], m[0]),
        'L': lambda m: (m[1], -m[0]),
    }
    for t, d in directions:
        heading = turn[t](heading)
        for _ in range(d):
            if position in visited:
                break
            visited.add(position)
            position = tuple(p + h for p, h in zip(position, heading))
    return sum(abs(p) for p in position)


def parse(line):
    turn = line[0]
    steps = int(line[1:])
    return (turn, steps)


if __name__ == '__main__':
    directions = line_parser(get_input(day=1, year=2016),
                             parse=parse,
                             seperator=", ")
    print("Part 1: {}".format(part1(directions)))
    print("Part 2: {}".format(part2(directions)))
Example #18
0
def part1(groups):
    result = 0
    for group in groups:
        result += len(set(answer for person in group for answer in person))
    return result


def part2(groups):
    result = 0
    for group in groups:
        result += sum(1 for q in set(
            answer for person in group for answer in person)
                      if all(q in person for person in group))
    return result


def parse(text):
    result = [[]]
    for line in text.splitlines():
        if line == "":
            result.append([])
        else:
            result[-1].append(list(line))
    return result


if __name__ == "__main__":
    LINES = parse(get_input(day=6, year=2020))
    print(f"Part 1: {part1(LINES)}")
    print(f"Part 2: {part2(LINES)}")
Example #19
0
            grid[pos] = '#'
        elif grid[pos] == 'F':
            grid[pos] = '.'
            head = reverse(head)
        elif grid[pos] == '#':
            head = turn_right(head)
            grid[pos] = 'F'
        pos = move(pos, head)
    return count


def test_part2():
    test = "..#\n#..\n...".splitlines()
    assert 26 == part2(parse(test), iters=100)
    assert 2511944 == part2(parse(test), iters=10000000)


def parse(lines):
    grid = defaultdict(lambda: '.')
    height, width = len(lines), len(lines[0])
    for r, row in enumerate(lines, -(height // 2)):
        for c, char in enumerate(row, -(width // 2)):
            grid[(r, c)] = char
    return grid


if __name__ == '__main__':
    grid = parse(get_input(day=22, year=2017).splitlines())
    print('Part 1: {}'.format(part1(grid)))
    print('Part 2: {}'.format(part2(grid)))
Example #20
0
def main(lambda2):
	X = get_input("input_pos_neg.txt")
	m = 0
	m_pos = 0
	m_neg = 0
	m_distinct_X = len(X)
	for (pos,neg,s) in X:
		m_pos += pos
		m_neg += neg
		m += pos + neg

	print 'm,m_pos,m_neg=',m,m_pos,m_neg
	theta_max_pos = 1.0*m_neg/m
	theta_max_neg = 1.0*m_pos/m


	
	tmp  = Xtheta_mapper(X)
	# Z = X' * theta_max
	Z = Xtheta_reducer(tmp,theta_max_pos,theta_max_neg)
	lambda_max = max([abs(w)for w in Z.itervalues()])/m	
	print 'lambda_max = ',lambda_max,'lambda2 = ',lambda2
	'''
	sum_b= [e[0]for e in X]	
	for i in range(m-1):
		sum_b[i+1] += sum_b[i]
	'''
	if lambda2>=lambda_max:
		print "lambda2 >= lambda_max"
		return 
	print "get len_of_X_column"
	tmp = projection_scale_mapper(X) #PX
	len_of_X_column = projection_scale_reducer(tmp)
	
	j0 = 0
	sign_j0 = 0
	mi = m
	for (k,v) in Z.items():
		#print abs(v),m*lambda_max
		if abs(abs(v)-m*lambda_max)<1e-10: # theta*Xj == m*lambda_max
			if len_of_X_column[k]<mi: # find j0 with the sparsest column
				mi = len_of_X_column[k]
				j0 = k
				if v > 0:
					sign_j0 = 1
				elif v < 0:
					sign_j0 = -1
				else:
					sign_j0 = 0
	print 'j0 = ',j0
	X_raw_star = tmp[j0] # j0th column of X, list of instance_id
	L_X_star = mi
	#print 'length of X_raw_star', len(X_raw_star)
	P_X_star = [(instance_id,sign_j0*(1.0-1.0*L_X_star/m),pos+neg) for (pos,neg,instance_id) in X_raw_star] #PX*, list of (instance_id, a, b)
	sign_P_X_star_b = -1.0*sign_j0*L_X_star/m


	hash_P_X_star = [0] * m_distinct_X
	hash_P_X_star_a = [0] * m_distinct_X
	
	sum_a_star_p_n = 0
	sum_a_star_square_p_n = 0
	for (idx,a,p_n) in P_X_star:
		sum_a_star_p_n += a*p_n		
		sum_a_star_square_p_n+=a*a*p_n
		hash_P_X_star_a[idx] = a

	for (pos,neg,index) in X_raw_star:
		hash_P_X_star[index]=1
	print 'sum_a_star_p_n ', sum_a_star_p_n, ' sum_a_star_square_p_n ',sum_a_star_square_p_n
	
	print 'sign_P_X_star_b ', sign_P_X_star_b 

	P_X_star_norm2 = norm2(P_X_star,sign_P_X_star_b,m)
	print 'P_X_star_norm2 ',P_X_star_norm2
	print 'length of P_X_star = ',len(P_X_star)
	#X_raw_star = [feature_key,feature_key,...]
	
	#len_of_X_column = {column_id:len}
	r = g(theta_max_pos,theta_max_neg,m_pos,m_neg,lambda2/lambda_max) - g(theta_max_pos,theta_max_neg,m_pos,m_neg,1)
	r += (1-lambda2/lambda_max)*(m_pos*math.log(theta_max_pos/(1.0 - theta_max_pos))*theta_max_pos  + m_neg*math.log(theta_max_neg/(1.0 - theta_max_neg))*theta_max_neg)/m	
	r = math.sqrt(r*m/2.0)
	print 'r ',r
	#print j0,sign_j0
	print "final step"
	tmp = final_mapper(X,len_of_X_column,hash_P_X_star,hash_P_X_star_a)
	rejection_features = final_reducer(tmp,m,P_X_star,sign_P_X_star_b,lambda2,lambda_max,sign_j0,r,Z,P_X_star_norm2,L_X_star,sum_a_star_p_n,sum_a_star_square_p_n)
	print 'rejection length = ',len(rejection_features)
	Y = []
	length_feature_before = 0
	length_feature_after = 0
	for (pos,neg,s) in X:
		nt = []
		for t in s:
			if not t in rejection_features:
				nt.append(t)
		Y.append([pos,neg,nt])
		length_feature_after+=len(nt)
		length_feature_before +=len(s)
	print 'average length of feature before',length_feature_before*1.0/len(X),'after',length_feature_after*1.0/len(X),
	save_X(Y,'input_after_filter.txt')
Example #21
0
        brute_gen = lambda n: ((k // 2) + 1 for k in reversed(range(n-1)))
        assert brute(i, brute_gen(i)) == josephus(i, joseph_gen(i))

def brute(n_elves, k_gen, debug=False):
    elves = list(range(1, n_elves+1))
    e = 0
    for kill in k_gen:
        if len(elves) == 1:
            break
        log.debug('{}: {}'.format(kill, elves))
        elves.pop(kill)
        elves.append(elves.pop(0))
    assert len(elves) != 0
    return elves[0]

def test_brute():
    assert 3 == brute(5, cycle([1]))
    assert 2 == brute(5, ((k // 2) + 1 for k in reversed(range(5-1))))
    assert 3 == brute(6, ((k // 2) + 1 for k in reversed(range(6-1))))
    assert 5 == brute(7, ((k // 2) + 1 for k in reversed(range(7-1))))

def part2(n):
    kills = ((k // 2) + 1 for k in range(n-1))
    return josephus(n, kills)

if __name__ == '__main__':
    log.setLevel(logging.INFO)
    lines = int(get_input(day=19, year=2016).strip())
    print("Part 1: {}".format(part1(lines)))
    print("Part 2: {}".format(part2(lines)))
Example #22
0
    i = 0
    while i < len(text):
        m = re.match(r'^\((\d+)x(\d+)\)', text[i:])
        if m is None:
            group += text[i]
            i += 1
        else:
            if group is not '':
                groups.append((1, group))
                group = ''
            i += m.end(0)
            chars, repeat = (int(g) for g in m.groups())
            if recurse:
                groups.append((repeat, parse(text[i:i + chars], recurse=True)))
            else:
                groups.append((repeat, text[i:i + chars]))
            i += chars
    if group is not '':
        groups.append((1, group))
    return groups


def test_decompress_len():
    assert part2("(3x3)XYZ") == 9


if __name__ == '__main__':
    lines = get_input(day=9, year=2016).strip()
    print("Part 1: {}".format(part1(lines)))
    print("Part 2: {}".format(part2(lines)))
Example #23
0
#!/usr/bin/env python3

from get_input import get_input, line_parser
from collections import Counter

def part1(lines):
    phrase_counter = [Counter() for _ in range(len(lines[0]))]
    for line in lines:
        for i, c in enumerate(line):
            phrase_counter[i][c] += 1 
    return ''.join(max(p.items(), key=lambda q: q[1])[0] for p in phrase_counter)

def part2(lines):
    phrase_counter = [Counter() for _ in range(len(lines[0]))]
    for line in lines:
        for i, c in enumerate(line):
            phrase_counter[i][c] += 1 
    return ''.join(min(p.items(), key=lambda q: q[1])[0] for p in phrase_counter)
    

if __name__ == '__main__':
    lines = line_parser(get_input(day=6, year=2016), parse=lambda l: tuple(l), seperator='\n')
    print("Part 1: {}".format(part1(lines)))
    print("Part 2: {}".format(part2(lines)))
Example #24
0
            return state.path
        for step in state.directions():
            if 0 <= step.x < 4 and 0 <= step.y < 4:
                queue.append(step)


def test_part1():
    assert 'DDRRRD' == part1('ihgpwlah')
    assert 'DDUDRLRRUDRD' == part1('kglvqrro')
    assert 'DRURDRUDDLLDLUURRDULRLDUUDDDRR' == part1('ulqzkmiv')


def part2(prefix):
    queue = [MazeState(prefix)]
    longest = None
    while queue:
        state = queue.pop(0)
        if state.x == 3 and state.y == 3:
            longest = state
            continue
        for step in state.directions():
            if 0 <= step.x < 4 and 0 <= step.y < 4:
                queue.append(step)
    return len(longest.path)


if __name__ == '__main__':
    prefix = get_input(day=17, year=2016).strip()
    print('Part 1: {}'.format(part1(prefix)))
    print('Part 2: {}'.format(part2(prefix)))
Example #25
0
def part1(lines):
    door_public, card_public = lines
    door_loop = None
    card_loop = None
    loop_number = 1
    public = 7
    while door_loop is None or card_loop is None:
        print(f"{loop_number}: {public}")
        loop_number += 1
        public = (7 * public) % 20201227

        if card_loop is None and public == card_public:
            card_loop = loop_number
        if door_loop is None and public == door_public:
            door_loop = loop_number
    private = transform(door_public, card_loop)
    assert private == transform(card_public, door_loop)
    return private


def part2(lines):
    return "Merry Christmas!"


if __name__ == "__main__":
    assert part1([17807724, 5764801]) == 14897079
    LINES = line_parser(get_input(day=25, year=2020))
    print(f"Part 1: {part1(LINES)}")
    print(f"Part 2: {part2(LINES)}")
Example #26
0
        if new_molecule == 'e':
            shortest = steps + 1
            return shortest
        elif new_molecule != molecule and new_molecule not in seen:
            seen.add(new_molecule)
            queue.append((steps + 1, new_molecule, 0))
    raise ValueError("Cannot make molecule")


def test_part2():
    replacements = [
        ('H', 'HO'),
        ('H', 'OH'),
        ('O', 'HH'),
        ('e', 'H'),
        ('e', 'O'),
    ]
    assert part2(replacements, 'HOHOHO') == 6


def parse(text):
    lines = text.splitlines()
    replacements = [tuple(line.split(' => ')) for line in lines[:-2]]
    return replacements, lines[-1]


if __name__ == '__main__':
    replacements, init = parse(get_input(day=19, year=2015))
    print("Part 1: {}".format(part1(replacements, init)))
    print("Part 2: {}".format(part2(replacements, init)))
Example #27
0
"""Take input from a user and print the corresponding acronym."""

from get_input import get_input


def generate_acronym(string):
    """Create an acronym from a given string input and return it."""
    words = string.split()
    letters = [word[0] for word in words]
    acronym = ''.join(letters)
    return acronym.upper()


if __name__ == "__main__":
    INPUT = get_input()
    print generate_acronym(INPUT)
Example #28
0
    assert list('1') == checksum('00')
    assert list('0') == checksum('10')
    assert list('0') == checksum('01')
    assert list('100') == checksum('110010110100')


def expand(curve):
    new_curve = list(curve)
    new_curve.append('0')
    replace = {'0': '1', '1': '0'}
    for d in reversed(curve):
        new_curve.append(replace[d])
    return new_curve


def test_expand():
    assert list('100') == expand('1')
    assert list('001') == expand('0')
    assert list('11111000000') == expand('11111')
    assert list('1111000010100101011110000') == expand('111100001010')


def part2(line, space=35651584):
    return part1(line, space=space)


if __name__ == '__main__':
    line = get_input(day=16, year=2016).strip()
    print('Part 1: {}'.format(part1(line)))
    print('Part 2: {}'.format(part2(line)))
Example #29
0
    dist = [0] * buckets
    dist[0] = volume
    while True:
        yield dist
        dist[0] -= 1
        dist[1] += 1
        if dist[0] < 0:
            i = 1
            while dist[0] < 0:
                if i + 1 >= len(dist):
                    raise StopIteration
                dist[i + 1] += 1
                dist[0] += dist[i] - 1
                dist[i] = 0
                i += 1


def parse(line):
    ingredient = re.compile(
        r'(?P<name>\w+): capacity (?P<capacity>-?\d+), ' +
        'durability (?P<durability>-?\d+), flavor (?P<flavor>-?\d+), ' +
        'texture (?P<texture>-?\d+), calories (?P<calories>-?\d+)')
    m = ingredient.match(line)
    return {k: int(v) if k != 'name' else v for k, v in m.groupdict().items()}


if __name__ == '__main__':
    ingredients = line_parser(get_input(day=15, year=2015), parse=parse)
    print("Part 1: {}".format(part1(ingredients)))
    print("Part 2: {}".format(part2(ingredients)))
Example #30
0
            queue.append((i + 1, used + [buckets[i]]))
            queue.append((i + 1, used))


def test_storage_gen():
    buckets = [15, 10, 5, 5, 20]
    assert len(list(storage_gen(buckets, 25))) == 4


def part1(buckets, volume=150):
    count = 0
    for b in storage_gen(buckets, volume):
        count += 1
    return count


def part2(buckets, volume=150):
    shortest = []
    for b in storage_gen(buckets, volume):
        if shortest == [] or len(b) < len(shortest[0]):
            shortest = [b]
        elif len(b) == len(shortest[0]):
            shortest.append(b)
    return len(shortest)


if __name__ == '__main__':
    buckets = line_parser(get_input(day=17, year=2015))
    print("Part 1: {}".format(part1(buckets)))
    print("Part 2: {}".format(part2(buckets)))
Example #31
0
        'samoyeds': lambda v: v == 2,
        'pomeranians': lambda v: v < 3,
        'akitas': lambda v: v == 0,
        'vizslas': lambda v: v == 0,
        'goldfish': lambda v: v < 5,
        'trees': lambda v: v > 3,
        'cars': lambda v: v == 2,
        'perfumes': lambda v: v == 1,
    }
    aunts = filter_aunts(aunts, props)
    assert len(aunts) == 1
    return list(aunts.keys())[0]


def parse(line):
    aunt_n = line.index(':')
    aunt = int(line[4:aunt_n])
    props = {}
    for prop in line[aunt_n + 2:].split(', '):
        k, v = prop.split(': ')
        props[k] = int(v)
    return (aunt, props)


if __name__ == '__main__':
    aunts = dict(line_parser(get_input(day=16, year=2015), parse=parse))
    # Part 1: 103
    # Part 2: 405
    print("Part 1: {}".format(part1(aunts)))
    print("Part 2: {}".format(part2(aunts)))
Example #32
0
"""Take input from a user and print out the given input with the white
space between words replaced by an underscore."""

from get_input import get_input

def replace_space(string):
    """Replace all the whitespace found in a given string with an
    underscore and return it.
    """
    return '_'.join(string.split())

if __name__ == "__main__":
    INPUT = get_input()
    print replace_space(INPUT)
Example #33
0
def decrypt(name, shift):
    decrypted = []

    for char in name:
        if char == ' ':
            decrypted.append(char)
            continue

        decrypted_char = chr(((ord(char) - ord('a')) + shift) % 26 + ord('a'))
        decrypted.append(decrypted_char)

    return ''.join(decrypted)


day = int(os.path.basename(__file__).replace('day', '').replace('.py', ''))
data = get_input.get_input(day)

lines = data.split('\n')

sum_sectorIDs = 0

for line in lines:
    pieces = line.split('-')

    meta = pieces[-1].split('[')
    checksum = meta[1].replace(']', '')
    sectorID = int(meta[0])

    char_list = list(itertools.chain.from_iterable(pieces[:-1:]))
    counted = dict(Counter(char_list))
    counted_sorted = OrderedDict(sorted(counted.items(), key=lambda t: (-t[1], ord(t[0]))))
Example #34
0
def parameter():
    global progress_percentage
    if request.method == 'GET':
        try:
            fn = request.args.get("fn")
        except TypeError:
            return "Invalid URL!"
        return render_template('parameter.html',
                               fn=fn,
                               version=tossa.get_version())
    if request.method == 'POST':
        progress_percentage = 0
        #read
        with open("static/pwords.txt", "r") as f:
            pwords = f.read().splitlines()
        with open("static/nwords.txt", "r") as f:
            nwords = f.read().splitlines()
        try:
            n_topics = int(request.values.to_dict().get('n_topics'))
            probability_threshold = float(
                request.values.to_dict().get('probability_threshold')) / 100
            #add
            win_size = int(request.values.to_dict().get('win_size'))
            bigram_min = int(request.values.to_dict().get('bigram_min'))
            trigram_min = int(request.values.to_dict().get('trigram_min'))

            assert n_topics > 0 and 0 < probability_threshold < 1 and win_size > 0 and bigram_min > 0 and trigram_min > 0
            fn = request.args.get("fn")
            pwords = list(
                set(request.values.to_dict().get('pwords').split(';') +
                    pwords))
            nwords = list(
                set(request.values.to_dict().get('nwords').split(';') +
                    nwords))
        except:
            return "Please input valid parameters!"

        logger.info(f'filename: {fn}; PosWords: {pwords}; NegWords: {nwords};')

        # analyze and generate files for rendering
        tossa.preprocess(version=None)
        progress_percentage += 10

        #tossa.parse_dependency()
        progress_percentage += 10

        tossa.build_w2v_model()
        progress_percentage += 10

        tossa.calc_senti_words(pwords, nwords)
        progress_percentage += 10

        #tossa.map_dependency()
        tossa.topic_modeling(n_topics, 'bigram')
        progress_percentage += 20

        tossa.prepare_review_list(probability_threshold)
        progress_percentage += 10
        # add
        main_run(n_topics, win_size, bigram_min, trigram_min, fn)
        progress_percentage += 10
        # cmd = "python get_input.py result/youtube " + str(n_topics)
        # os.system(cmd)
        get_input(n_topics, fn)
        progress_percentage += 10

        tossa.prepare_summary()
        progress_percentage += 10

        logger.info('Finished processing. Redirecting to summary page...')

        return redirect(f"/summary?fn={fn}")
Example #35
0

def make_set(table, seed):
    seen = set()
    queue = [seed]
    while queue:
        p = queue.pop()
        if p not in seen:
            seen.add(p)
            queue.extend(table[p])
    return seen


def part1(table):
    return len(make_set(table, 0))


def part2(table):
    return len(set(frozenset(make_set(table, v)) for v in table.keys()))


def parse(line):
    ppid, pids = line.split(' <-> ')
    return (int(ppid), tuple(int(p) for p in pids.split(', ')))


if __name__ == '__main__':
    table = dict(line_parser(get_input(day=12, year=2017), parse=parse))
    print("Part 1: {}".format(part1(table)))
    print("Part 2: {}".format(part2(table)))