コード例 #1
0
ファイル: play.py プロジェクト: Rmvandiepen/february
def play_puzzles():
    file_location = input_handling.get_input_file()
    puzzles = readfile(file_location)
    puzzles = input_handling.select_puzzles(puzzles)

    for puzzle in puzzles:
        grid = Grid(**puzzle)
        grid.make_connections()
        grid.show_cursor = True
        grid.color_solved_cells = True

        update_screen(grid)

        with KeyPoller() as key_poller:
            while True:
                i = key_poller.poll()
                if i is not None:
                    try:
                        process_input(grid, i)
                    except Next:
                        print('Going to the next puzzle')
                        break
                    update_screen(grid)

                    if grid.solved:
                        print('Well done! Puzzle solved')
                        input('Press return to continue. \n')
                        break
コード例 #2
0
def solve():
    file_location = input_handling.get_input_file()

    before_read = time.time()
    puzzles = readfile(file_location)
    print('Time to read: ', time.time() - before_read)

    puzzles = input_handling.select_puzzles(puzzles)

    use_advanced_solving = input_handling.select_yes_no(
        'Advanced techniques', 'yes')
    print_results = input_handling.select_yes_no('Print result', 'yes')
    slow_solve = input_handling.select_yes_no('Slow solve')
    show_min_bridges = input_handling.select_yes_no('Show min bridges')
    use_backtracking = input_handling.select_yes_no('Use backtracking')

    before_solve = time.time()
    for i, puzzle in enumerate(puzzles):
        grid = Grid(**puzzle, use_advanced=use_advanced_solving)
        if slow_solve:
            grid.solve_slowly = True
        if show_min_bridges:
            grid.show_min_bridges = True

        if use_backtracking:
            solved = grid.backtracking()
        else:
            try:
                solved = grid.solve()
            except Unsolvable:
                solved = False
        if print_results:
            print('Cells: ', len(grid.cells))
            print(grid)
        if solved:
            pass
            # print(f'Solved {i}' + (' (Required advanced techniques)' if grid.advanced else ''))
        else:
            print(f'Couldn\'t solve {i}')

    time_to_solve = time.time() - before_solve
    print('Time to solve: ', time_to_solve)
    print(
        f'Average of {int(time_to_solve / (len(puzzles))*1000)} ms per puzzle')
コード例 #3
0
ファイル: updaily.py プロジェクト: Aulddays/stockana
def upindividual():
    lasttime = common.readfile("data/last", "20000101")
    syms = set()
    caps = {}
    with open("data/info", "rb") as fp:
        for line in fp:
            line = line.strip(" \r\n")
            parts = line.split("\t")
            if len(parts) != 6:
                eprint("Invalid info", line)
                continue
            syms.add(parts[0])
    for sym in syms:
        symc = common.symbolclean(sym)
        data = getdata_yahoo(sym, lasttime, nowdate)
        if data is -1:
            raise Exception("Failed", sym)
        if not os.path.isdir("data/hist/" + symc):
            os.makedirs("data/hist/" + symc)
        common.writefile("data/hist/" + symc + "/" + nowdate, data)
コード例 #4
0
 def load_data(self, dfile):
     try:
         self.data = common.readfile(dfile)
     except Exception:
         raise MyException(sys.exc_info())
コード例 #5
0
            print('Channel busy')
            continue


# Function to sense the medium
def sense_medium():
    global isBusyChannel

    while (True):
        if (sockSignal.recv(1024).decode() == '1'):
            # Means channel is busy
            isBusyChannel = 1
        else:
            # Means channel is not busy
            isBusyChannel = 0


list_of_frames = co.readfile('input.txt', co.frame_size)
list_of_frames.append('_')

sendThread = threading.Thread(
    target=send_frame, args=(list_of_frames, ))  # create the sending thread
senseThread = threading.Thread(
    target=sense_medium)  # create the sending thread

sendThread.start()
senseThread.start()

sendThread.join()
senseThread.join()
コード例 #6
0
ファイル: 01.py プロジェクト: alexartwww/geekbrains-python
from common import input_value, readfile

task = '''
Создать программно файл в текстовом формате, записать в него построчно данные,
вводимые пользователем. Об окончании ввода данных свидетельствует пустая строка.
'''

if __name__ == '__main__':
    print(task)

    with open('01.file.txt', 'w') as file:
        while True:
            string = input_value('Type a string: ', '^.*$', str)
            if string == '':
                break
            file.write(string + '\n')

    print('================')
    print(readfile('01.file.txt'))
コード例 #7
0
ファイル: p-sender.py プロジェクト: rahul8436/College-Lab
            time.sleep(2)
            continue


# Function to sense the medium
def sense_medium():
    global busy_channel

    while (True):
        if (s_signal.recv(1024).decode() == '1'):
            # Means channel is busy
            busy_channel = 1
        else:
            # Means channel is not busy
            busy_channel = 0


frames_list = co.readfile('input.txt', co.frame_size)
frames_list.append('_')

# create the sending thread
sendThread = threading.Thread(target=send_frame, args=(frames_list, ))

# create the sending thread
senseThread = threading.Thread(target=sense_medium)

sendThread.start()
senseThread.start()

sendThread.join()
senseThread.join()
コード例 #8
0
ファイル: updaily.py プロジェクト: Aulddays/stockana
def uplist():
    """ update lists """
    # Download and parse new list
    defparam = [
        'Symbol', 'Name', 'LastSale', 'MarketCap', 'IPOyear', 'Sector',
        'industry', 'Summary Quote'
    ]
    infos, caps = {}, {}  # infos: symbol=>info, caps: symbol=>MarketCap
    for mkt in ("nasdaq", "nyse"):
        #url = "http://www.nasdaq.com/screening/companies-by-name.aspx?letter=0&exchange=" + mkt + "&render=download"
        #quotes = common.urlget(url, timeout=30)
        #common.writefile("data/" + mkt + ".csv", quotes)
        quotes = common.readfile("data/" + mkt + ".csv")
        reader = csv.reader(StringIO.StringIO(quotes))
        param = reader.next()
        #eprint(param)
        if param[-1] == "":
            del param[-1]
        if param != defparam:
            eprint("WARNING: list format changed", param)
        isym, iname, icap, iyear, isec, iind = (param.index("Symbol"),
                                                param.index("Name"),
                                                param.index("MarketCap"),
                                                param.index("IPOyear"),
                                                param.index("Sector"),
                                                param.index("industry"))
        for rec in reader:
            rec = [r.replace("\t", " ") for r in rec]
            sym, name, cap, year, sec, ind = operator.itemgetter(
                isym, iname, icap, iyear, isec, iind)(rec)
            #eprint(sym, name, cap, year, sec, ind, sep="\t")
            infos[sym] = [name, year, sec, ind, mkt]
            caps[sym] = cap

    # Read in old list
    oinfos = {}
    try:
        with open("data/info") as fp:
            for line in fp:
                line = line.strip(" \r\n")
                parts = line.split("\t")
                if len(parts) != 6:
                    eprint("Invalid info", line)
                    continue
                oinfos[parts[0]] = parts[1:]
    except IOError:
        pass
    # Compare new to old
    if len(infos) < len(oinfos) and (len(oinfos) - len(infos)) / float(
            len(oinfos)) > 0.01:
        eprint("ERROR: Total number decreased", len(oinfos), len(infos))
        return -1
    mod = False
    for sym, info in infos.iteritems():
        if sym not in oinfos:
            mod = True
            continue
        if oinfos[sym] != info:
            mod = True
            # Write to hist file
            with open("data/info.hist", "ab") as fp:
                print(nowdate, sym, "\t".join(oinfos[sym]), sep="\t", file=fp)
        del oinfos[sym]
    for sym, info in oinfos.iteritems():  # sym deleted in new
        with open("data/info.hist", "ab") as fp:
            print(nowdate, sym, "\t".join(info), sep="\t", file=fp)
            mod = True
    osym = None
    if mod:  # overwirte info
        with open("data/info.new", "wb") as fp:
            for sym, info in infos.iteritems():
                print(sym, "\t".join(info), sep="\t", file=fp)
        shutil.move("data/info.new", "data/info")

    # Write marketcap
    with open("data/mktcap", "wb") as fp:
        for sym, cap in caps.iteritems():
            print(sym, cap, sep="\t", file=fp)
コード例 #9
0
		else: # Channel is busy
			print('Channel busy')
			time.sleep(2)
			continue



# Function to sense the medium
def sense_medium():
	global isBusyChannel

	while(True):
		if(sockSignal.recv(1024).decode()=='1'):
			# Means channel is busy
			isBusyChannel=1
		else:
			# Means channel is not busy
			isBusyChannel=0

list_of_frames=co.readfile(filename, co.frame_size)
list_of_frames.append('#')

sendThread=threading.Thread(target=send_frame, args=(list_of_frames,)) # create the sending thread
senseThread=threading.Thread(target=sense_medium) # create the sending thread

sendThread.start()
senseThread.start()

sendThread.join()
sendThread.join()
コード例 #10
0
    print 'Usage:%s infile' % sys.argv[0]

ntype = {
    "prev": {
        "小姐": "MISS",
        "女士": "MISS",
        "先生": "SIR",
        "总": "MR"
    },
    "tail": {
        "小": "SIR",
        "老": "SIR"
    }
}

tdata = dict()
data = common.readfile(sys.argv[1])
for ty in ntype:
    for it in ntype[ty]:
        for dt in data:
            tdic = dict()
            if ty == 'prev':
                tdic['str'] = dt + it
            elif ty == 'tail':
                tdic['str'] = it + dt
            tdic['type'] = 'SB'
            tdic['stype'] = ntype[ty][it]
            tdata[tdic['str']] = tdic

common.print_dic(tdata)