def createFirstGeneration(total_fathers): fathers = list() i = 0 while i<total_fathers: combination = Combination() combination = combination.createValidCombination() fathers.append(combination) i+=1 return fathers
def getTwoPairs(self, card_list): card_ranks = [] for card in card_list: card_ranks.append(card.rank) card_ranks.sort(reverse=True) card_ranks_result = [] first_pair = None second_pair = None for i in range(1, len(card_ranks)): if card_ranks[i] == card_ranks[i - 1]: first_pair = card_ranks[i] card_ranks.remove(card_ranks[i - 1]) card_ranks.remove(card_ranks[i - 1]) break for i in range(1, len(card_ranks)): if card_ranks[i] == card_ranks[i - 1]: second_pair = card_ranks[i] card_ranks.remove(card_ranks[i - 1]) card_ranks.remove(card_ranks[i - 1]) break if first_pair != None and second_pair != None: if first_pair > second_pair: card_ranks_result.append(first_pair) card_ranks_result.append(second_pair) else: card_ranks_result.append(second_pair) card_ranks_result.append(first_pair) card_ranks_result += card_ranks return Combination(2, card_ranks_result[0:3])
def __init__(self, verbose = False): self.encrypted_string = ( "de| | f|Cl|nf|ed|au| i|ti| |ma|ha|or|nn|ou| S|on|nd|on" "\n" "ry| |is|th|is| b|eo|as| | |f |wh| o|ic| t|, | |he|h " "\n" "ab| |la|pr|od|ge|ob| m|an| |s |is|el|ti|ng|il|d |ua|c " "\n" "he| |ea|of|ho| m| t|et|ha| | t|od|ds|e |ki| c|t |ng|br" "\n" "wo|m,|to|yo|hi|ve|u | t|ob| |pr|d |s |us| s|ul|le|ol|e " "\n" ' t|ca| t|wi| M|d |th|"A|ma|l |he| p|at|ap|it|he|ti|le|er' "\n" 'ry|d |un|Th|" |io|eo|n,|is| |bl|f |pu|Co|ic| o|he|at|mm' "\n" "hi| | |in| | | t| | | | |ye| |ar| |s | | |. ") self.rows = 8 self.columns = 19 self.matrix = [ [ 0 for i in range(self.columns) ] for j in range(self.rows) ] self.combination = Combination(self.rows, self.columns) self.used_column_indices = [] self.verbose = verbose
def main(): try: given_k = int(sys.argv[1]) except: print "Please enter a valid value for k! Usage example: python anonymizer.py 4" exit() satisfying_combinations = [] fresh_persons = read_csv() for iDate in range(10): for iZip in range(6): for iSex in range(2): persons = copy_persons(fresh_persons) persons = anonymize(persons, iDate, iZip, iSex) grouped_persons = group_persons(persons) k = get_k(grouped_persons) if k >= given_k: satisfying_combinations.append( Combination(iDate, iZip, iSex, k, grouped_persons)) if len(satisfying_combinations) > 0: combinations_with_least_steps = get_combinations_with_least_steps( satisfying_combinations) best_combination = get_best_combination(combinations_with_least_steps) print_results(best_combination) export_csv(best_combination) else: print "No satisfying combinations found. Try again with a lower k!"
def getStrFlashFromRank(self, card_list, card_rank): # Шукає СтФ від заданого рангу suits_counts = [0, 0, 0, 0] for rank in range(card_rank, card_rank + 5): suits = self.getSuitsByCardRank(rank, card_list) if len(suits) > 0: for suit in suits: suits_counts[suit] += 1 if max(suits_counts) == 5: return Combination(8, [card_rank + 4])
def getFlash(self, card_list): suits_counts = [0, 0, 0, 0] for card in card_list: suits_counts[card.suit] += 1 if max(suits_counts) >= 5: flash_suit = suits_counts.index(max(suits_counts)) flash_cards = [] for card in card_list: if card.suit == flash_suit: flash_cards.append(card.rank) flash_cards.sort(reverse=True) return Combination(5, flash_cards[0:5])
def Init(): global combLst calc_regex = re.compile(r'([a-z][a-z]+[0-9,_,-]+)') ss_regex = re.compile(r'([s,o,c][0-9]+)') condLst = ConditionManager().readFromFile() comb = Combination() comb.InitCombinations() combLst = comb.GetCombinationLst() r.delete("lengthMap") r.set("lengthMap", json.dumps(lengthMapping(combLst))) for cindx,comb in enumerate(combLst): condTempLst = condLst[:] for idx, cond in enumerate(condTempLst): calcLst = calc_regex.findall(cond) ssLst = ss_regex.findall(cond) for calcItem in calcLst: vals = calcDef(calcItem, comb) condTempLst[idx] = re.sub(r'\b' + re.escape(calcItem) + r'\b',"Calc("+str(vals)+","+"barsLst)", condTempLst[idx]) for ssItem in ssLst: vals = calcBar(ssItem, comb) condTempLst[idx] = re.sub(r'\b' + re.escape(ssItem) + r'\b', "Calc("+str(vals)+","+"barsLst)", condTempLst[idx]) comb.append(condTempLst) print(str(cindx)) dict = {"tl": str(combLst)} r.set(configDef['publishOn'], json.dumps(dict)) print("I'm ready!") return ""
def getFourKindOf(self, card_list): rank_counts = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] for card in card_list: rank_counts[card.rank] += 1 if max(rank_counts) == 4: index = rank_counts.index(max(rank_counts)) rank_counts[index] = 0 for card_rank in reversed(rank_counts): if card_rank > 0: rank_counts.reverse() return Combination( 7, [index, 12 - rank_counts.index(card_rank)])
def getPair(self, card_list): card_ranks = [] for card in card_list: card_ranks.append(card.rank) card_ranks.sort(reverse=True) card_ranks_result = [] for i in range(1, len(card_ranks)): if card_ranks[i] == card_ranks[i - 1]: card_ranks_result.append(card_ranks[i]) card_ranks.remove(card_ranks[i - 1]) card_ranks.remove(card_ranks[i - 1]) card_ranks_result += card_ranks return Combination(1, card_ranks_result[0:5])
def getStreight(self, card_list): card_rank_list = [] for card in card_list: card_rank_list.append(card.rank) card_rank_list.sort(reverse=True) counter = 1 for i in range(1, len(card_rank_list)): if card_rank_list[i] + 1 == card_rank_list[i - 1]: counter += 1 if counter == 5: return Combination(4, [card_rank_list[i - 4]]) else: counter = 1
def getFullHouse(self, card_list): rank_counts = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] for card in card_list: rank_counts[card.rank] += 1 rank_counts.reverse() if max(rank_counts) == 3: set_index = rank_counts.index(3) rank_counts[set_index] = 0 set_index = 12 - set_index if max(rank_counts) >= 2: pair_index = 12 - rank_counts.index(max(rank_counts)) return Combination(6, [set_index, pair_index])
def get_combinations(self): not_masked_indices = [] combinations = [] i = 0 for m in self.configuration.mask: if m != UNKNOWN: not_masked_indices.append(i) i = i + 1 number_combinations = pow(2, len(not_masked_indices)) range_start = 0 range_end = number_combinations if self.configuration.number_parallel_workers is not None and \ self.configuration.number_worker is not None and \ self.configuration.number_parallel_workers > 0 and \ 0 <= self.configuration.number_worker < self.configuration.number_parallel_workers: count_per_worker = number_combinations / self.configuration.number_parallel_workers range_start = int(count_per_worker * self.configuration.number_worker) range_end = int(count_per_worker * (self.configuration.number_worker + 1)) for i in range(range_start, range_end): binary = self.decimal_to_binary_list(i) field = self.configuration.mask.copy() field[int(len(field) / 2)] = HEAD j = 0 binary.reverse() for bit in binary: if bit == 1: field[not_masked_indices[j]] = BLOCKED j = j + 1 for direction in range(self.configuration.food_directions): combinations.append( Combination(field=field, food_direction=direction, number=i)) return combinations
def get_combinations(target_combinations): combinations = [] # Go through the 5 combinations for row in range(1, target_combinations.shape[0] + 1): dictionary = target_combinations.iloc[(row - 1):row, 2:3]['params'].values[0] criterion = dictionary.get('criterion') splitter = dictionary.get('splitter') max_depth = dictionary.get('max_depth') classifier_algorithm = tree.DecisionTreeClassifier(criterion=criterion, splitter=splitter, max_depth=max_depth) accuracy_list, log_list = [], [] comb = Combination(classifier_algorithm, accuracy_list, None, None, log_list, None, None) combinations.append(comb) return combinations
def getSet(self, card_list): rank_counts = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] for card in card_list: rank_counts[card.rank] += 1 if max(rank_counts) == 3: index = rank_counts.index(3) rank_counts[index] = 0 cards_ranks = [index] for card_rank in reversed(rank_counts): if card_rank > 0: rank_counts.reverse() kiker = (12 - rank_counts.index(card_rank)) cards_ranks.append(kiker) if len(cards_ranks) == 3: return Combination(3, cards_ranks)
def get_combinations(target_combinations): combinations = [] # Go through the 5 combinations for row in range(1, target_combinations.shape[0] + 1): dictionary = target_combinations.iloc[(row - 1):row, 2:3]['params'].values[0] solver = dictionary.get('solver') max_iter = dictionary.get('max_iter') random_state = dictionary.get('random_state') classifier_algorithm = MLPClassifier(solver=solver, max_iter=max_iter, random_state=random_state) accuracy_list, log_list = [], [] comb = Combination(classifier_algorithm, accuracy_list, None, None, log_list, None, None) combinations.append(comb) return combinations
def fileToCombination(file): winning_combinations = list() for line in file: line = line.replace("\t", " ") line = line.replace("\n", "") if (len(line)!=0) and (len(winning_combinations)<total_winning_combination): list_numbers_stars = line.split(" ") i = 0 combination = Combination() for number_star in list_numbers_stars: if len(number_star)>0: if i<5: combination.numbers.append(int(number_star)) else: combination.stars.append(int(number_star)) i+=1 winning_combinations.append(combination) return winning_combinations
def get_combinations(target_combinations): combinations = [] # Go through the 5 combinations for row in range(1, target_combinations.shape[0] + 1): dictionary = target_combinations.iloc[(row - 1):row, 2:3]['params'].values[0] penalty = dictionary.get('penalty') solver = dictionary.get('solver') multi_class = dictionary.get('multi_class') classifier_algorithm = LogisticRegression(penalty=penalty, solver=solver, multi_class=multi_class) accuracy_list, log_list = [], [] comb = Combination(classifier_algorithm, accuracy_list, None, None, log_list, None, None) combinations.append(comb) return combinations
def get_combinations(target_combinations): combinations = [] # Go through the 5 combinations for row in range(1, target_combinations.shape[0] + 1): dictionary = target_combinations.iloc[(row - 1):row, 2:3]['params'].values[0] algorithm = dictionary.get('algorithm') leaf_size = dictionary.get('leaf_size') n_neighbors = dictionary.get('n_neighbors') weights = dictionary.get('weights') classifier_algorithm = KNeighborsClassifier( algorithm=algorithm, leaf_size=leaf_size, n_neighbors=n_neighbors, weights=weights) accuracy_list, log_list = [], [] comb = Combination(classifier_algorithm, accuracy_list, None, None, log_list, None, None) combinations.append(comb) return combinations
def GetCombinations(): global comb if comb is None: comb = Combination() return json.dumps(comb.InitCombinations())
def getRoyalFlash(self, card_list): combination = self.getStrFlashFromRank(card_list, 8) if combination != None: return Combination(9, [12])
def getKiker(self, card_list): card_ranks = [] for card in card_list: card_ranks.append(card.rank) card_ranks.sort(reverse=True) return Combination(0, card_ranks[0:5])
# -*- coding: utf-8 -*- """ Created on Sat Jan 25 19:23:16 2020 @author: Zheng Wen """ import numpy as np from plotDecBoundaries import plotDecBoundaries from KNN import nearestMeansClassifier from KNN import errorRateCal from Combination import Combination combinations = Combination().combine(13, 2) train_set = np.loadtxt("D:\EE559\HW_1\python3\wine_train.csv", delimiter=",") test_set = np.loadtxt("D:\EE559\HW_1\python3\wine_test.csv", delimiter=",") min_error = 100 min_comb = 0 train_label = train_set[:, -1] test_label = test_set[:, -1] for i in range(len(combinations)): combination = np.array(combinations[i]) - 1 train_data = train_set[:, combination] test_data = test_set[:, combination] means, pred_train = nearestMeansClassifier(train_data, train_label, train_data) means, pred_test = nearestMeansClassifier(train_data, train_label, test_data)
class Unshred: def __init__(self, verbose = False): self.encrypted_string = ( "de| | f|Cl|nf|ed|au| i|ti| |ma|ha|or|nn|ou| S|on|nd|on" "\n" "ry| |is|th|is| b|eo|as| | |f |wh| o|ic| t|, | |he|h " "\n" "ab| |la|pr|od|ge|ob| m|an| |s |is|el|ti|ng|il|d |ua|c " "\n" "he| |ea|of|ho| m| t|et|ha| | t|od|ds|e |ki| c|t |ng|br" "\n" "wo|m,|to|yo|hi|ve|u | t|ob| |pr|d |s |us| s|ul|le|ol|e " "\n" ' t|ca| t|wi| M|d |th|"A|ma|l |he| p|at|ap|it|he|ti|le|er' "\n" 'ry|d |un|Th|" |io|eo|n,|is| |bl|f |pu|Co|ic| o|he|at|mm' "\n" "hi| | |in| | | t| | | | |ye| |ar| |s | | |. ") self.rows = 8 self.columns = 19 self.matrix = [ [ 0 for i in range(self.columns) ] for j in range(self.rows) ] self.combination = Combination(self.rows, self.columns) self.used_column_indices = [] self.verbose = verbose def iterate_lines(self, foo): return iter(foo.splitlines()) def parseIntoMatrix(self): i = 0 for line in self.iterate_lines(self.encrypted_string): row_values = line.split('|') for j, value in enumerate(row_values): if value != '': self.matrix[i][j] = value i += 1 def initModels(self): self.corp = Models() self.corp.createLetterModel() self.corp.createWordUniGramModel() def computeCombinationProbability(self, phrases): sum = 0 for phrase in phrases: sum += self.corp.getLetterProbabilities(phrase) sum += self.corp.getWordProbabilities(phrase) if self.verbose: print '{0:15f} |{1:s}|'.format(sum, phrases[0]) #print sum, phrases return sum def getBestCombination(self): max_prob = -100000 max_combination = '' max_index = 0 for index, pair in enumerate(self.matrix[0]): # Don't check columns we already added if index in self.used_column_indices: continue temp_combination = copy.deepcopy(self.combination) # Get column values for index new_column_values = [self.matrix[i][index] for i in range(self.rows)] temp_combination.appendColumn(new_column_values) phrases_to_check = temp_combination.returnPhrases() # Compute probabilities probability = self.computeCombinationProbability(phrases_to_check) if probability > max_prob: max_prob = probability max_combination = temp_combination max_index = index if self.verbose: print '->{0:13f} |{1:s}|'.format(max_prob, max_combination.returnFirstPhrase()) self.used_column_indices.append(max_index) return max_prob, max_combination def unshred(self): # Find uppercase for index, pair in enumerate(self.matrix[0]): if pair[0].isupper(): self.combination.appendColumn([self.matrix[i][index] for i in range(self.rows)]) self.used_column_indices.append(index) break # Find next best combinations and append them for i in range(1, 19): prob, combination = self.getBestCombination() #print prob, combination self.combination = combination def displayResult(self): print '\n The unencrypted message is:\n' self.combination.display() def execute(self): self.parseIntoMatrix() self.initModels() self.unshred() self.displayResult() return