def b_to_z(setting, n_components): logging.info("B -> Z") dictionary = loader.load_dictionary(setting.DICTIONARY_PATH) dict_vecto_tfidf = loader.load_dict_vecto_tfidf( setting.DICT_VECTO_TFIDF_PATH) # sparse_matrix = cp.reduce_dimention_pca(dict_vecto_tfidf.values(), len(dictionary), n_components=500, batch_size=20000) # b6 : map id product with nonnegative integer list_id_product = dict_vecto_tfidf.keys() dict_map_id = map_id_product(list_id_product) # b7 : reduce large matrix # sparse_matrix = cp.reduce_dimention(dict_vecto_tfidf.values(), len(dictionary), n_components=500,batch_size=20000) sparse_matrix = cp.reduce_dimension_svd(dict_vecto_tfidf.values(), len(dictionary), n_components=n_components) shape = sparse_matrix.shape logging.info("shape : " + str(shape)) dense_matrix = list(sparse_matrix) # b8 : build tree tree = cp.make_tree(setting, dict_id=dict_map_id.keys(), dict_vecto=dense_matrix, dimension=shape[1], amount_tree=10) # b9 : search nns in tree dict_result = {} for i in range(1000): list_nns = tree.get_nns_by_item(i, 11) dict_result[i] = list_nns dict_product = loader.load_dict_product(setting.DICT_PRODUCT_PATH) loader.save_result(setting.DICT_RESULT_PATH + "_" + str(n_components), dict_product, dict_map_id, dict_result)
def a_to_z(setting, n_components): logging.info("A -> Z") # b1 : make a folder to contain data make_folder(setting.PARENT_FOLDER_PATH) make_folder(setting.FOLDER_DATA_PATH) # b2 : return a client connecting to server elasticsearch es = loader.get_elasticsearch_client(setting.HOST, setting.PORT) # b3 : scan data dict_raw_product = loader.scan_data(es, setting.DOMAIN) # b4 : preprocess raw data dict_product = cp.preprocess_data(setting, dict_raw_product) # b5 : transform to tfidf vector dict_vecto_tfidf, dictionary = cp.transform_vecto_tfidf( setting, cp.split_text(dict_product)) # b6 : map id product with nonnegative integer list_id_product = dict_vecto_tfidf.keys() dict_map_id = map_id_product(list_id_product) # b7 : reduce large matrix # sparse_matrix = cp.reduce_dimention(dict_vecto_tfidf.values(), len(dictionary), n_components=500,batch_size=20000) sparse_matrix = cp.reduce_dimension_svd(dict_vecto_tfidf.values(), len(dictionary), n_components=500) shape = sparse_matrix.shape logging.info("shape : " + str(shape)) dense_matrix = list(sparse_matrix) # b8 : build tree tree = cp.make_tree(setting, dict_id=dict_map_id.keys(), dict_vecto=dense_matrix, dimension=shape[1], amount_tree=10) # b9 : search nns in tree dict_result = {} for i in range(1000): list_nns = tree.get_nns_by_item(i, 11) dict_result[i] = list_nns dict_product = loader.load_dict_product(setting.DICT_PRODUCT_PATH) loader.save_result(setting.DICT_RESULT_PATH + "_" + str(n_components), dict_product, dict_map_id, dict_result) dict_result_id = {} for i in dict_map_id.keys(): list_nns = tree.get_nns_by_item(i, 11) dict_result_id[i] = list_nns loader.save_result_id(setting.DICT_RESULT_ID_PATH, dict_map_id, dict_result_id) #b10 copy file to hdfs loader.save_file_to_hdfs(setting.FOLDER_HDFS_PATH, setting.FILE_NAME_HDFS, setting.DICT_RESULT_ID_PATH)
def encodeCSharSum(filecotent): count = 0 zongzifuchangdu = Computer.nocharJsSum(filecotent) bianmazifuchangdu = Computer.encodeCharSum(filecotent) if (zongzifuchangdu > 0) & (bianmazifuchangdu > 0): count = bianmazifuchangdu / zongzifuchangdu else: count = 0 return count
def hexfencoCShareSum(filecotent): count = 0 hexcount = Computer.hexvalueSum(filecotent) encocount = Computer.encodeCharSum(filecotent) if (hexcount > 0) & (encocount > 0): count = hexcount / encocount else: count = 0 return count
def createPlayer(self, symbol, playerNum): if self.turn == 1: if playerNum == 1: self.player1 = Human.Human(symbol, self.gameBoard) elif playerNum == 2: self.player1 = Computer.Computer(symbol, self.gameBoard) self.turn = 2 elif self.turn == 2: if playerNum == 1: self.player2 = Human.Human(symbol, self.gameBoard) elif playerNum == 2: self.player2 = Computer.Computer(symbol, self.gameBoard) self.turn = 1
def prepare_data(setting): # b1 : make a folder to contain data make_folder(setting.PARENT_FOLDER_PATH) make_folder(setting.FOLDER_DATA_PATH) # b2 : return a client connecting to server elasticsearch es = loader.get_elasticsearch_client(setting.HOST, setting.PORT) # b3 : scan data dict_raw_product = loader.scan_data(es, setting.DOMAIN) # b4 : preprocess raw data dict_product = cp.preprocess_data(setting, dict_raw_product) # b5 : transform to tfidf vector cp.transform_vecto_tfidf(setting, cp.split_text(dict_product))
def _computador_agregar(): cadena = "COMPUTADOR AGREGAR\n" cadena += "--------------------\n" nombre = input("NOMBRE: ") cadena += "--------------------\n" computador = c.Computer() computador.name = nombre return computador
def compute_data(setting, n_components, dictionary, dict_vecto_tfidf, items=1000, amount_nns=11): # b6 : map id product with nonnegative integer list_id_product = dict_vecto_tfidf.keys() dict_map_id = map_id_product(list_id_product) # b7 : reduce large matrix sparse_matrix = cp.reduce_dimension_svd(dict_vecto_tfidf.values(), len(dictionary), n_components=n_components) shape = sparse_matrix.shape logging.info("shape : " + str(shape)) dense_matrix = list(sparse_matrix) # b8 : build tree tree = cp.make_tree(setting, dict_id=dict_map_id.keys(), dict_vecto=dense_matrix, dimension=shape[1], amount_tree=10) # b9 : search nns in tree dict_result = {} for i in range(items): list_nns = tree.get_nns_by_item(i, amount_nns) dict_result[i] = list_nns dict_product = loader.load_dict_product(setting.DICT_PRODUCT_PATH) loader.save_result(setting.DICT_RESULT_PATH + "_" + str(n_components), dict_product, dict_map_id, dict_result) dict_result_id = {} for i in dict_map_id.keys(): list_nns = tree.get_nns_by_item(i, 11) dict_result_id[i] = list_nns loader.save_result_id(setting.DICT_RESULT_ID_PATH, dict_map_id, dict_result_id)
def digitShareSum(filecontent): b = {} # 字典 sumAll = 0 digshres = 0 b = Counter(filecontent) # 取得字符串各个字符出现的次数 for key in b: sumAll += b[key] # 取得字典的值,将得到的各字符累计相加 digitNum = Computer.nofDigitSum(filecontent) if digitNum > 0: digshres = digitNum / sumAll else: digshres = 0 return digshres
def Run(source: str, debug: bool): try: prog = Program(source) preproc = Preprocessor() preproc.preprocess(prog) # for l in prog.preprocessed: # print(l) assembler = Assembler() assembler.assemble(prog) # for l in prog.labels: # print(l, f" Position: {l.position}") # for i in prog.instructions: # print(i, f" Position: {i.position} Label: {i.labelName}") # for p in i.parameters: # print(" ", p, end = "") # if p.labelName != None: # print(f" {p.labelName}") # else: # print("") # for b in prog.binary: # print("%04X " % b, end = "") # print("") computer = Computer() computer.loadProgram(prog) if debug == False: computer.run() for l in prog.labels: if l.size > 0: print("%13s (%6s[%3d]): " % (l.name, l.datatype, l.size), end ="") for i in range(l.position, l.position + l.size): print("%d " % computer.memory[i], end = "") print("") else: debugger = Debugger(computer, prog) debugger.run() except PreprocessorError as e: print(e) except AssemblerError as e: print(e) except CompilerError as e: print(e) except Exception as e: raise e
def start(self): visited_loc = set() computer = Computer.Computer() while True: if computer.cur == len(self.program): return 0, computer if computer.cur in visited_loc: return None parse_pgm = self.program[computer.cur] visited_loc.add(computer.cur) instruction, argument = parse_pgm instruction(computer, argument)
def play(): deskTop = [[0, 0, 0], [0, 0, 0], [0, 0, 0]] mod = 'X' data = 'start,' while True: try: print('Player ', mod, ' : ') if mod == 'X': i, j = map(int, input('Enter location : ').split(' ')) elif mod == 'O': i, j = Computer.Computer(deskTop) if i > 3 or j > 3 or i == 0 or j == 0: if i == 0 and j == 0: os.system('clear') break elif deskTop[i - 1][j - 1] != 0: print('This location is write already.') continue print('Enter error.') except ValueError as n: print(n) except IndexError as n: print(n) else: os.system('clear') deskTop[i - 1][j - 1] = mod desk.desk(deskTop) d = deskTop d = tonum.transateOX(d) if mod == 'X': f = open('TrainingSet.txt', 'a') for i in d: data += str(i) + ',' data += '\n' f.write(data) data = 'data,' mod = 'O' elif mod == 'O': f = open('TrainingSet.txt', 'a') for i in d: data += str(i) + ',' data += '\n' f.write(data) data = 'label,' mod = 'X' if WinLose.CheckWinner(deskTop) == 'Over': a = input('Enter any key to exit.') os.system('clear') break
def __init__(self): # players live in game to keep running score between rounds self.__human = Player.Player(0, []) self.__computer = Computer.Computer(0, []) # create round 1 self.__round = Round.Round(1, True, self.__human, self.__computer) # gamestate flags # true after the user has picked up a card and before the user discards self.__waitingForHumanDiscard = False # true after the user has put down a card and before the computer moves self.__waitingForHumanGoOut = False # true when a player has successfully gone out self.__playerOut = False
def __init__(self): self.player = Player.PlayerBoard(TOP_MARGIN_PLAYER) self.computer = Computer.ComputerBoard(TOP_MARGIN_COMPUTER) self.player_coords_ships_info = [] self.computer_coords_ships_info = [] make_ships(self.player.get_board(), 4, 1, self.player_coords_ships_info) make_ships(self.player.get_board(), 3, 2, self.player_coords_ships_info) make_ships(self.player.get_board(), 2, 3, self.player_coords_ships_info) make_ships(self.player.get_board(), 1, 4, self.player_coords_ships_info) make_ships(self.computer.get_board(), 4, 1, self.computer_coords_ships_info) make_ships(self.computer.get_board(), 3, 2, self.computer_coords_ships_info) make_ships(self.computer.get_board(), 2, 3, self.computer_coords_ships_info) make_ships(self.computer.get_board(), 1, 4, self.computer_coords_ships_info) self.shot_down_cells_player = [] self.shot_down_cells_computer = [] self._done = False self.play_btn = screen.blit(play_btn_img, play_btn_rect) self.exit_btn = screen.blit(exit_btn_img, exit_btn_rect) screen.blit(player_ship4_img, (540, 65)) screen.blit(player_ship3_img, (540, 110)) screen.blit(player_ship2_img, (540, 160)) screen.blit(player_ship1_img, (540, 220)) screen.blit(comp_ship4_img, (540, 515)) screen.blit(comp_ship3_img, (540, 560)) screen.blit(comp_ship2_img, (540, 620)) screen.blit(comp_ship1_img, (540, 680)) draw_text_chat_border() self.player.draw_board() self.computer.draw_board() self.rect = pygame.Rect(600, 250, 90, 30)
def __init__(self): super(RedTeam, self).__init__() self.players = [ # 2 Defender Computer(BACKGROUND_WIDTH - DEFENDER_X, MIDDLE_Y - GAME_HEIGHT * 1 / 6), Computer(BACKGROUND_WIDTH - DEFENDER_X, MIDDLE_Y + GAME_HEIGHT * 1 / 6), # 3 Midfielder Computer(BACKGROUND_WIDTH - MIDFIELDER_X, MIDDLE_Y - GAME_HEIGHT * 2 / 6), Computer(BACKGROUND_WIDTH - MIDFIELDER_X, MIDDLE_Y), Computer(BACKGROUND_WIDTH - MIDFIELDER_X, MIDDLE_Y + GAME_HEIGHT * 2 / 6), # 2 Striker Computer(BACKGROUND_WIDTH - STRIKER_X, MIDDLE_Y - GAME_HEIGHT * 1 / 6), Computer(BACKGROUND_WIDTH - STRIKER_X, MIDDLE_Y + GAME_HEIGHT * 1 / 6), ] for player in self.players: self.add(player) self.index = 0 self.player = self.players[self.index]
import Computer """ This is a simple Rock, Paper, Scissors game. This class runs the game Author: Stanley Ho """ def playerValidChoice(choice): if choice == "scissors" or choice == "rock" or choice =="paper": return True else: return False myPlayer = Player.Player() myComp = Computer.Computer() print(myPlayer) myPlayer.updateWin(True) print("Welcome to rock paper scissors. The first player to get to 3 wins. Good Luck!") while True: print("Player Score: " + str(myPlayer.playerScore) + " Vs Computer Score " + str(myComp.computerScore)) if myPlayer.playerScore == 3: print("You Won") break elif myComp.computerScore == 3: print("You Lost") break else: playerChoice = input("What do you want Rock, Paper or Scissors? ") computerChoice = myComp.move() if playerValidChoice(playerChoice.lower()) is False:
import Player import Computer if (__name__ == "__main__"): # |STAGE 1: Create The Players and Let The Computer Pick a Number | computer = Computer.Computer() computer.pickANumber() start = computer.start stop = computer.stop user = Player.Player() # |STAGE 2: Let The User Pick a Number | while (user.getAtomicPoints() >= 0): user.guessTheNumber(start, stop) # |STAGE 3: Check If The User Guessed Correctly | computer.checkUserNumber(user) print("[*] You have {} / 10 points".format(user.getAtomicPoints())) else: print("[ :( ] Game Over")
bt = charP + charC # print(bt) for i, pr in enumerate(battleStr): if pr == bt: # print(battlePt[i]) score += battlePt[i] break return score #===================== # game #===================== player1 = Computer.Player.Player(5) player2 = Computer.Computer(5) roundNumber = 1; while player1.health > 0 and player2.health > 0: print("Round Number: {}".format(roundNumber)) roundNumber += 1 player1Hand = player1.getHand() print(player1Hand) player2Hand = player2.getHand() print(player2Hand) score = getScore(player1Hand,player2Hand)
import Computer import io input_array = open('D9-input.txt').read().strip().split(',') for i in range(len(input_array)): input_array[i] = int(input_array[i]) # Today i used the test-cases. Easier to copy-paste the program code like this instead # of storing them in files com = Computer.Computer( [109, 1, 204, -1, 1001, 100, 1, 100, 1008, 100, 16, 101, 1006, 101, 0, 99]) com2 = Computer.Computer([1102, 34915192, 34915192, 7, 4, 7, 99, 0]) com3 = Computer.Computer([104, 1125899906842624, 99]) print(com.run_program()) print(com2.run_program()) print(com3.run_program()) # This is the computer with the real program. Both tasks can be performed interactively. task1 = Computer.Computer(input_array) print(task1.run_program()) # Another way would be to do it like this print(task1.run_program('1', program=input_array, interactive=False)) print(task1.run_program('2', program=input_array, interactive=False))
def keywordSum(filecontent): abstractN = filecontent.split('abstract') caseN = filecontent.split('case') continueN = filecontent.split('continue') doubleN = filecontent.split('double') extendsN = filecontent.split('extents') forN = filecontent.split('for') importN = filecontent.split('import') letN = filecontent.split('let') packageN = filecontent.split('package') shortN = filecontent.split('short') thisN = filecontent.split('this') tryN = filecontent.split('try') whileN = filecontent.split('while') argumentsN = filecontent.split('arguments') catchN = filecontent.split('catch') debuggerN = filecontent.split('debugger') elseN = filecontent.split('else') falseN = filecontent.split('false') inN = filecontent.split('in') longN = filecontent.split('long') privateN = filecontent.split('private') staticN = filecontent.split('static') throwN = filecontent.split('throw') typeofN = filecontent.split('typeof') withN = filecontent.split('with') booleanN = filecontent.split('boolean') charN = filecontent.split('char') defaultN = filecontent.split('default') enumN = filecontent.split('enum') finalN = filecontent.split('final') gotoN = filecontent.split('goto') instanceofN = filecontent.split('instanceof') nativeN = filecontent.split('native') protectedN = filecontent.split('protected') superN = filecontent.split('super') throwsN = filecontent.split('throws') yieldN = filecontent.split('yield') breakN = filecontent.split('break') classN = filecontent.split('class') deleteN = filecontent.split('delete') finallyN = filecontent.split('finally') intN = filecontent.split('int') newN = filecontent.split('new') publicN = filecontent.split('public') switchN = filecontent.split('switch') transientN = filecontent.split('transient') voidN = filecontent.split('void') byteN = filecontent.split('byte') constN = filecontent.split('const') doN = filecontent.split('do') exportN = filecontent.split('export') floatN = filecontent.split('float') implementsN = filecontent.split('implements') interfaceN = filecontent.split('interface') nullN = filecontent.split('null') returnN = filecontent.split('return') synchronizedN = filecontent.split('synchronized') trueN = filecontent.split('true') volatileN = filecontent.split('volatile') ArrayN = filecontent.split('Array') InfinityN = filecontent.split('Infinity') MathN = filecontent.split('Math') prototypeN = filecontent.split('prototype') DateN = filecontent.split('Date') isFiniteN = filecontent.split('isFinite') NaNN = filecontent.split('NaN') StringN = filecontent.split('String') isNaNN = filecontent.split('isNaN') nameN = filecontent.split('name') isPrototypeOfN = filecontent.split('isPrototypeOf') NumberN = filecontent.split('Number') undefinedN = filecontent.split('undefined') hasOwnPropertyN = filecontent.split('hasOwnProperty') lengthN = filecontent.split('length') ObjectN = filecontent.split('Object') valueOfN = filecontent.split('valueOf') count1 = 0 count2 =0 count3 =0 count4 = 0 count5 = 0 count6 = 0 count7 = 0 count8 = 0 count9 = 0 count10 = 0 count11= 0 count12= 0 count13 = 0 count14 = 0 count15 = 0 count16 = 0 count17 = 0 count18 = 0 count19 = 0 count20 = 0 count21 = 0 count22 = 0 count23 = 0 count24 = 0 count25 = 0 count26 = 0 count27 = 0 count28 = 0 count29 = 0 count30 = 0 count31 = 0 count32 = 0 count33 = 0 count34 = 0 count35 = 0 count36 = 0 count37 = 0 count38 = 0 count39 = 0 count40 = 0 count41 = 0 count42 = 0 count43 = 0 count44 = 0 count45 = 0 count46 = 0 count47 = 0 count48 = 0 count49 = 0 count50 = 0 count51= 0 count52= 0 count53= 0 count54= 0 count55= 0 count56= 0 count57= 0 count58= 0 count59 = 0 count60 = 0 count61 = 0 count62 = 0 count63 = 0 count64 = 0 count65 = 0 count66 = 0 count67 = 0 count68 = 0 count69 = 0 count70 = 0 count71 = 0 count72 = 0 count73 = 0 count74 = 0 count75 = 0 count76 = 0 count77 = 0 count78 = 0 count79 = 0 count80 = 0 count81 =0 for i in abstractN: count1 += 1 count1 -= 1 # print('abstract:', count1) for i in caseN: count2 += 1 count2 -= 1 # print('case:', count2) for i in continueN: count3 += 1 count3 -= 1 # print('continue:', count3) for i in doubleN: count4 += 1 count4 -= 1 # print('double:', count4) for i in extendsN: count5 += 1 count5 -= 1 # print('extends:', count5) for i in forN: count6 += 1 count6 -= 1 # print('for:', count6) for i in importN: count7 += 1 count7 -= 1 # print('import:', count7) for i in letN: count8 += 1 count8 -= 1 # print('let:', count8) for i in packageN: count9 += 1 count9 -= 1 # print('package:',count9) for i in shortN: count10 += 1 count10 -= 1 # print('short:', count10) for i in thisN: count11 += 1 count11 -= 1 # print('this:', count11) for i in tryN: count12 += 1 count12 -= 1 # print('try:',count12) for i in whileN: count13 += 1 count13 -= 1 # print('while:',count13) for i in argumentsN: count14 += 1 count14 -= 1 # print('arguments',count14) for i in catchN: count15 += 1 count15 -= 1 # print('catch', count15) for i in debuggerN: count16 += 1 count16 -= 1 # print('debugger', count16) for i in elseN: count17 += 1 count17 -= 1 # print('else:',count17) for i in falseN: count18 += 1 count18 -= 1 # print('false:',count18) count19=Computer.functionSum(filecontent) # print('function:',count19) for i in inN: count20 += 1 count20 -= 1 # print('in:',count20) for i in longN: count21 += 1 count21 -= 1 # print('long',count21) for i in privateN: count22 += 1 count22 -= 1 # print('private:',count22) for i in staticN: count23 += 1 count23 -= 1 # print('static:',count23) for i in throwN: count24 += 1 count24 -= 1 # print('throw:',count24) for i in typeofN: count25 += 1 count25 -= 1 # print('typeof:',count25) for i in withN: count26 += 1 count26 -= 1 # print('with:',count26) for i in booleanN: count27 += 1 count27 -= 1 # print('boolean:',count27) for i in charN: count28 += 1 count28 -= 1 # print('char:',count28) for i in defaultN: count29 += 1 count29 -= 1 # print('default:',count29) for i in enumN: count30 += 1 count30 -= 1 # print('enum:',count30) for i in finalN: count31 += 1 count31 -= 1 # print('final:',count31) for i in gotoN: count32 += 1 count32 -= 1 # print('foto:',count32) for i in instanceofN: count33 += 1 count33 -= 1 # print('instanceof:',count33) for i in nativeN: count34 += 1 count34 -= 1 for i in protectedN: count35 += 1 count35 -= 1 for i in superN: count36 += 1 count36 -= 1 for i in throwN: count37 += 1 count37 -= 1 count38=Computer.varSum(filecontent) # print('var=',count38) for i in yieldN: count39 += 1 count39 -= 1 for i in breakN: count40 += 1 count40 -= 1 # print('break:',count40) for i in classN: count41 += 1 count41 -= 1 # print('class:',count41) for i in deleteN: count42 += 1 count42 -= 1 for i in finallyN: count43 += 1 count43 -= 1 # print('finally:',count43) pattern = re.compile(r'if\s?\(.*?\)(\s|\{)') nofDigitR = pattern.findall(filecontent) count44 = len(nofDigitR) # print('if:',count44) for i in intN: count45 += 1 count45 -= 1 # print('int:',count45) for i in newN: count46 += 1 count46 -= 1 # print('new:',count46) for i in publicN: count47 += 1 count47 -= 1 for i in switchN: count48 += 1 count48 -= 1 # print('switch:',count48) for i in transientN: count49 += 1 count49 -= 1 # print('transient:',count49) for i in voidN: count50 += 1 count50 -= 1 # print('void:',count50) for i in byteN: count51 += 1 count51 -= 1 # print('byte:',count51) for i in constN: count52 += 1 count52 -= 1 # print('const:',count52) for i in doN: count53 += 1 count53 -= 1 # print('do:',count53) for i in exportN: count54 += 1 count54 -= 1 # print('export:',count54) for i in floatN: count55 += 1 count55 -= 1 # print('float:',count55) for i in implementsN: count56 += 1 count56 -= 1 # print('implement:',count56) for i in interfaceN: count57 += 1 count57 -= 1 # print('interface:',count57) for i in nullN: count58 += 1 count58 -= 1 # print('null:',count58) for i in returnN: count59 += 1 count59 -= 1 # print('return:',count59) for i in synchronizedN: count60 += 1 count60 -= 1 # print('synchronized:',count60) for i in trueN: count61 += 1 count61 -= 1 # print('true:',count61) for i in volatileN: count62 += 1 count62 -= 1 # print('volatile',count62) for i in ArrayN: count63 += 1 count63 -= 1 # print('Array:',count63) for i in InfinityN: count64 += 1 count64 -= 1 # print('Infinity:',count64) for i in MathN: count65 += 1 count65 -= 1 # print('Math',count65) for i in prototypeN: count66 += 1 count66 -= 1 # print('prototype:', count66) for i in DateN: count67 += 1 count67 -= 1 # print('Date:',count67) for i in isFiniteN: count68 += 1 count68 -= 1 for i in NaNN: count69 += 1 count69 -= 1 # print('NaN',count69) for i in StringN: count70 += 1 count70 -= 1 # print('String:',count70) count71 = Computer.evalSum(filecontent) # print('eval:',count71) for i in isNaNN: count72 += 1 count72 -= 1 # print('isNaN:',count72) for i in nameN: count73 += 1 count73 -= 1 # print('name:',count73) count74=Computer.toStringSum(filecontent) # print('toString:',count74) for i in isPrototypeOfN: count75 += 1 count75 -= 1 # print('isPrototypeOf:',count75) for i in NumberN: count76 += 1 count76 -= 1 # print('Number:',count76) for i in undefinedN: count77 += 1 count77 -= 1 for i in hasOwnPropertyN: count78 += 1 count78 -= 1 # print('hasOwnProperty:', count78) for i in lengthN: count79 += 1 count79 -= 1 # print('length:', count79) for i in ObjectN: count80 += 1 count80 -= 1 # print('Object:', count80) for i in valueOfN: count81 += 1 count81 -= 1 # print('valueOf:', count81) return count1+count2+count3+count4+count5+count6+count7+count8+count9+count10+count11+count12+count13+\ count14+count15+count16+count17+count18+count19+count20+count21+count22+count23+count24+count25+\ count26+count27+count28+count29+count30+count31+count32+count33+count34+count35+count36+count37+\ count38+count39+count40+count41+count42+count43+count44+count45+count46+count47+count48+count49+\ count50+count51+count52+count53+count54+count55+count56+count57+count58+count59+count60+count61+\ count62+count63+count64+count65+count66+count67+count68+count69+count70+count71+count72+count73+\ count74+count75+count76+count77+count78+count79+count80+count81
def computerGame(): pygame.quit() Computer.simulate()
view.welcome() newgame = True if view.userStringInput("Do you want to play a game? Y or N", ['Y','N']) == 'Y' else False '''Loop to play a new game''' while(newgame): if view.userStringInput("Do you want an aggressive (A) opponent or an acquisative (Q) opponent?",['A','Q']) == 'A': aggressive = True else: aggressive = False p1 = User("Player 1") p1.populateHand() computer = Computer(aggressive) computer.populateHand() central = Central() central.populateActive() '''main game loop''' game = True while game: '''player 1 turn - returns false if quitting the game''' game = p1.move(computer,central,view) '''proceed only if user has not quit the game''' if game == True: '''check if user won before computer moves'''
import Computer comp = Computer.Computer(input("Down limit"), input("Up limit")) GAMEOVER = 0 while GAMEOVER == 0 and comp.err == 0: print "I guess, number is >> " + str(comp.guessnumber()) print "is it right?" if (int(input("YES = 1, NO = 0")) == 1): GAMEOVER = 1 else: inp = input("[1]Up-[2]Down?") if int(inp) == 1: comp.upp() else: comp.downn() print "I found it in " + str(comp.getcount()) print "Thanks for play with me"
import Player import Human import Undercut import Computer import Undercut p = Player.PlayerClass('搜索') print("Player:%s" % p) print("Human:%s" % Human.Human('测试')) # def main(): # print('测试') # p=Player('刘') # print(p) # 下面进行玩Undercut的demo c1 = Computer.Computer('疯狂的电脑1') c2 = Computer.Computer('疯狂的电脑2') # h=Human.Human('liu') result = Undercut.play_undercut(c1, c2) print(result)
def func(): b = Computer('kinglong') b.executeCmd('dir')
# -*- coding: utf-8 -*- from Computer import * """ ====================================================================================== 파일로부터 컴퓨터공학과 교과목 정보를 읽는다. ====================================================================================== """ cs_data = Computer() # cs_data : Computer 클래스 타입의 data def read_cs_data(filename): """텍스트 파일에서 교과목 정보를 불러와 리스트에 저장하는 함수 :param filename: 텍스트 파일 이름 :return: sw_data.sw_list 소프트웨어융합학과의 전체 교과목 정보가 들어있는 리스트 """ i = 0 # 반복 표시 인덱스 : 파일에서 3줄을 읽을 때 마다 한 과목의 정보이다. # 해당 디렉토리에 이름이 'filename'인 파일을 찾고 파일을 연다. # 이 때 한글을 읽기 위해서 encoding 은 'utf-8'로 한다. file_in = open(filename, 'r', encoding='utf-8') while True: line = file_in.readline() # 파일에서 한 줄씩 읽는다. if not line: break a = line.strip('\n') # '\n'도 한 줄씩 읽힐 수 있으므로 제거한다. if i == 2: cs_data.lectureList.append(a) # 수강 학년 교과목 리스트에 추가하기 cs_data.cs_list.append(
import time import sys import threading import PlayerWindow import ProblemChangeList as probtolist import Computer def main(): pass if __name__ == '__main__': main() prob_str = "" if len(sys.argv) == 2: prob_str = sys.argv[1] else: prob_str = "../problem/prob_2.txt" player = PlayerWindow.PlayerWindow() enemy = Computer.Computer() problem = probtolist.prob_to_list(prob_str) player.set_problem(problem) enemy.set_problem(problem) thread1 = threading.Thread(target=player.run) thread2 = threading.Thread(target=enemy.run) thread1.start() thread2.start()
def computerGame(): pygame.display.quit() pygame.quit() Computer.simulate()
def __init__(self, j1Name: str, j2Name: str, j1Print: str, j2Print: str): self.board = board.Board() self.j1 = player.Player(j1Name, j1Print) self.j2 = computer.Computer(j2Name, j2Print) self.winningLines = [[1, 2, 3], [4, 5, 6], [7, 8, 9], [1, 5, 9], [3, 5, 7], [1, 4, 7], [3, 6, 9], [2, 5, 8]]
def stringToRound(self, string): # data to grab roundNum = 0 computerScore = 0 computerHand = [] humanScore = 0 humanHand = [] drawPile = [] discardPile = [] humanNext = True # look through each line of the string lines = string.split("\n") for i in range(len(lines)): line = lines[i] # search for round number if line.find("Round: ") != -1: # get substring from after "Round: " roundNum = line[line.find("Round: ") + 7:] # search for computer if line.find("Computer:") != -1: for j in range(i, len(lines)): line = lines[j] # search for computer score if line.find("Score: ") != -1: computerScore = line[line.find("Score: ") + 7:] # search for computer hand if line.find("Hand: ") != -1: computerHand = self.stringToHand( line[line.find("Hand: ") + 6:]) break # search for human if line.find("Human:") != -1: for j in range(i, len(lines)): line = lines[j] # search for human score if line.find("Score: ") != -1: humanScore = line[line.find("Score: ") + 7:] # search for human hand if line.find("Hand: ") != -1: humanHand = self.stringToHand( line[line.find("Hand: ") + 6:]) break # search for draw pile if line.find("Draw Pile: ") != -1: drawPile = self.stringToHand(line[line.find("Draw Pile: ") + 11:]) # search for draw pile if line.find("Discard Pile: ") != -1: discardPile = self.stringToHand( line[line.find("Discard Pile: ") + 14:]) # search for next player if line.find("Next Player: ") != -1: if (line.find("Human") != -1): humanNext = True else: humanNext = False # print("Round number: " + roundNum) # print("Computer Score: " + computerScore.__str__()) # string = "" # for card in computerHand: # string += card.__str__() + " " # print("Computer Hand: " + string) # print("Human Score: " + humanScore.__str__()) # string = "" # for card in humanHand: # string += card.__str__() + " " # print("Human Hand: " + string) # string = "" # for card in drawPile: # string += card.__str__() + " " # print("Draw Pile: " + string) # string = "" # for card in discardPile: # string += card.__str__() + " " # print("Discard Pile: " + string) # print("Human Next: " + humanNext.__str__()) # update wildcards in all hands for card in humanHand: card.updateWildcard(int(roundNum) + 2) for card in computerHand: card.updateWildcard(int(roundNum) + 2) for card in drawPile: card.updateWildcard(int(roundNum) + 2) for card in discardPile: card.updateWildcard(int(roundNum) + 2) human = Player.Player(humanScore, humanHand) computer = Computer.Computer(computerScore, computerHand) round = Round(roundNum, humanNext, human, computer) round.setDrawPile(drawPile) round.setDiscardPile(discardPile) return round
elif first == 0: first = 'Comp' break else: print('Invalid input!') except ValueError: print('Invalid input') while True: if not self.comp.isCatsGame() and not self.comp.isWin(self.comp.getMatrix())[0]: if first == 'Human': self.comp.humanMove() else: self.comp.compMove() if not self.comp.isCatsGame() and not self.comp.isWin(self.comp.getMatrix())[0]: if first == 'Human': self.comp.compMove() else: self.comp.humanMove() else: break if self.comp.isCatsGame(): print('\n') displayBoard(self.comp.getMatrix()) print('Cats game!') elif self.comp.isWin(self.comp.getMatrix())[0]: print('\n') displayBoard(self.comp.getMatrix()) print(self.comp.isWin(self.comp.getMatrix())[1], 'wins!') game = Game(Computer()) game.playGame()
def printPath(level, path): global allFileNum #打印一个目录下的所有文件夹和文件 #所有文件夹,第一个字段是次目录的级别 dirList = [] #所有文件 fileList = [] # 返回一个列表,其中包含在目录条目的名称(google翻译) files = os.listdir(path) # 先添加目录级别 dirList.append(str(level)) for f in files: if (os.path.isdir(path + '/' + f)): # 排除隐藏文件夹。因为隐藏文件夹过多 if (f[0] == '.'): pass else: # 添加非隐藏文件夹 dirList.append(f) if (os.path.isfile(path + '/' + f)): # 添加文件 fileList.append(f) # 当一个标志使用,文件夹列表第一个级别不打印 i_dl = 0 for dl in dirList: if (i_dl == 0): i_dl = i_dl + 1 else: # 打印至控制台,不是第一个的目录 #print('_'*(int(dirList[0])),dl) # 打印目录下的所有文件夹和文件,目录级别+1 printPath((int(dirList[0]) + 1), path + '/' + dl) for fl in fileList: # print('_'*(int(dirList[0])),fl) print(fl) try: #f = open('E://soloscripttest//29K//'+fl,'r',encoding='UTF-8') #读取了fl,再读取fl的内容 f = open(dir3 + fl, 'r', encoding='UTF-8') alllines = f.readlines() str_all = ''.join(alllines) #将文件的内容由list转为字符串,进行正则表达式匹配 evalNum = Computer.evalSum(str_all) setTimeNum = Computer.setTimeSum(str_all) iframeNum = Computer.iframePSum(str_all) unescapeNum = Computer.unescapeSum(str_all) escapeNum = Computer.escapeSum(str_all) classidNum = Computer.classidSum(str_all) parseIntNum = Computer.parseIntSum(str_all) fromCharCodeNum = Computer.fromCharCodeSum(str_all) AXObjNum = Computer.AXObjectCodeSum(str_all) strDirasNum = Computer.strDirecassSum(str_all) concatNum = Computer.concatSum(str_all) inOfNum = Computer.indexOfSum(str_all) subSNum = Computer.subStringSum(str_all) replaceNum = Computer.replaceSum(str_all) adEListNum = Computer.addEListenerSum(str_all) attEventNum = Computer.attEventSum(str_all) ctElementNum = Computer.ctEventSum(str_all) getEleByIdNum = Computer.gEleByIdSum(str_all) writeNum = Computer.writeSum(str_all) jswordNum = Computer.jswordSum(str_all) keywordNum = ComplexJiSuan.keywordSum(str_all) noCharJsNum = Computer.nocharJsSum(str_all) ratiokeyawordNum = Computer.ratiokeyawordSum(str_all) entropyfJSNum = JiSuanComplex.entropyfJSSum(str_all) lethoflogestJSWNum = JiSuanComplex.lethflongestJSWSum(str_all) lethflongstrD200Num = JiSuanComplex.lethfLongStrDa200(str_all) lethfshortestNum = JiSuanComplex.lethfshortstJSWSum(str_all) entropyLongestNum = JiSuanComplex.entropylongestJSWSum(str_all) blankSpacNum = Computer.nospaceSum(str_all) avaralthoWNum = JiSuanComplex.avaragelethfWordSum(str_all) hexValuNum = Computer.hexvalueSum(str_all) spaceShareNum = Computer.nospaceShareSum(str_all) searchNum = Computer.searchSum(str_all) splitNum = Computer.splitSum(str_all) onbfunloadNum = Computer.onbforeunloadSum(str_all) onloadNum = Computer.onloadSum(str_all) onerrorNum = Computer.onerrorSum(str_all) onunloadNum = Computer.onunloadSum(str_all) onbfloadNum = Computer.onbefloadSum(str_all) onmsoverNum = Computer.onmsoverSum(str_all) dispEventNum = Computer.dispEventSum(str_all) fireEventNum = Computer.fireEventSum(str_all) setAttNum = Computer.setAttrSum(str_all) locationNum = Computer.locationSum(str_all) charAtNum = Computer.charAtSum(str_all) consologNum = Computer.consologSum(str_all) jsfileSum = Computer.jsfileSum(str_all) phpfileSum = Computer.phpfileSum(str_all) varSum = Computer.varSum(str_all) funcNum = Computer.functionSum(str_all) randomNum = Computer.randomSum(str_all) charCodANum = Computer.charCodeAtSum(str_all) WScriptNum = Computer.WScriptSum(str_all) decodeNum = Computer.decodeSum(str_all) toStrNum = Computer.toStringSum(str_all) NofDigitNum = Computer.nofDigitSum(str_all) encodCharNum = Computer.encodeCharSum(str_all) backslashNum = Computer.backlashSum(str_all) pipNum = Computer.pipSum(str_all) bfhNum = Computer.bfhSum(str_all) zykhNum = Computer.zuoyuankuohaoSum(str_all) yykhNum = Computer.youyuankuohaoSum(str_all) douhaoNum = Computer.douhaoSum(str_all) jinghaoNum = Computer.jinghaoSum(str_all) jiahaoNum = Computer.jiahaoSum(str_all) maohaoNum = Computer.maohaoSum(str_all) danyinhaoNum = Computer.danyinhaoSum(str_all) zuofangkuohaoNum = Computer.zuofangkuohaoSum(str_all) youfangkuohaoNum = Computer.youfangkuohaoSum(str_all) zuohuakuohaoNum = Computer.zuohuakuohaoSum(str_all) youhuakuohaoNum = Computer.youhuakuohaoSum(str_all) encodSharNum = JiSuanComplex.encodeCSharSum(str_all) digitShaNum = JiSuanComplex.digitShareSum(str_all) hexfencoSharNum = JiSuanComplex.hexfencoCShareSum(str_all) backslasShaNum = JiSuanComplex.backslashShareSum(str_all) pipShareNum = JiSuanComplex.piphaoShareSum(str_all) baifenShareNum = JiSuanComplex.baifenhaoShareSum(str_all) Oporatedb.Connect( evalNum, setTimeNum, iframeNum, unescapeNum, escapeNum, classidNum, parseIntNum, fromCharCodeNum, AXObjNum, strDirasNum, concatNum, inOfNum, subSNum, replaceNum, adEListNum, attEventNum, ctElementNum, getEleByIdNum, writeNum, jswordNum, keywordNum, noCharJsNum, ratiokeyawordNum, entropyfJSNum, lethoflogestJSWNum, lethflongstrD200Num, lethfshortestNum, entropyLongestNum, blankSpacNum, avaralthoWNum, hexValuNum, spaceShareNum, searchNum, splitNum, onbfunloadNum, onloadNum, onerrorNum, onunloadNum, onbfloadNum, onmsoverNum, dispEventNum, fireEventNum, setAttNum, locationNum, charAtNum, consologNum, jsfileSum, phpfileSum, varSum, funcNum, randomNum, charCodANum, WScriptNum, decodeNum, toStrNum, NofDigitNum, encodCharNum, backslashNum, pipNum, bfhNum, zykhNum, yykhNum, douhaoNum, jinghaoNum, jiahaoNum, maohaoNum, danyinhaoNum, zuofangkuohaoNum, youfangkuohaoNum, zuohuakuohaoNum, youhuakuohaoNum, encodSharNum, digitShaNum, hexfencoSharNum, backslasShaNum, pipShareNum, baifenShareNum) #写入到数据库中 print(encodCharNum, hexValuNum) print('hexfencoSharNum :::', hexfencoSharNum) except: print('该文件可以打开,不能匹配到') # print(a1) #测试 a1.append(fl) allFileNum = allFileNum + 1