def random_solution(self): """generamos una solución aleatoria para comenzar""" self.solution = Solution(self.locations, self.facilities) self.solution.generate_permutation(len(self.locations)) self.solution.calculate_cost() return self.solution
"hitch", "crews", "lucia", "banal", "grope", "valid", "meres", "thick", "lofts", "chaff", "taker", "glues", "snubs", "trawl", "keels", "liker", "stand", "harps", "casks", "nelly", "debby", "panes", "dumps", "norma", "racks", "scams", "forte", "dwell", "dudes", "hypos", "sissy", "swamp", "faust", "slake", "maven", "lowed", "lilts", "bobby", "gorey", "swear", "nests", "marci", "palsy", "siege", "oozes", "rates", "stunt", "herod", "wilma", "other", "girts", "conic", "goner", "peppy", "class", "sized", "games", "snell", "newsy", "amend", "solis", "duane", "troop", "linda", "tails", "woofs", "scuds", "shies", "patti", "stunk", "acres", "tevet", "allen", "carpi", "meets", "trend", "salty", "galls", "crept", "toner", "panda", "cohen", "chase", "james", "bravo", "styed", "coals", "oates", "swami", "staph", "frisk", "cares", "cords", "stems", "razed", "since", "mopes", "rices", "junes", "raged", "liter", "manes", "rearm", "naive", "tyree", "medic", "laded", "pearl", "inset", "graft", "chair", "votes", "saver", "cains", "knobs", "gamay", "hunch", "crags", "olson", "teams", "surge", "wests", "boney", "limos", "ploys", "algae", "gaols", "caked", "molts", "glops", "tarot", "wheal", "cysts", "husks", "vaunt", "beaus", "fauns", "jeers", "mitty", "stuff", "shape", "sears", "buffy", "maced", "fazes", "vegas", "stamp", "borer", "gaged", "shade", "finds", "frock", "plods", "skied", "stump", "ripes", "chick", "cones", "fixed", "coled", "rodeo", "basil", "dazes", "sting", "surfs", "mindy", "creak", "swung", "cadge", "franc", "seven", "sices", "weest", "unite", "codex", "trick", "fusty", "plaid", "hills", "truck", "spiel", "sleek", "anons", "pupae", "chiba", "hoops", "trash", "noted", "boris", "dough", "shirt", "cowls", "seine", "spool", "miens", "yummy", "grade", "proxy", "hopes", "girth", "deter", "dowry", "aorta", "paean", "corms", "giant", "shank", "where", "means", "years", "vegan", "derek", "tales" ] print(Solution().ladderLength(beginWord, endWord, wordList))
#!/usr/bin/python from solution import Solution # Unit Test string1 = [1,2,3] string2 = [4,3,2,1] string3 = [9,9] s = Solution() if (s.plusOne(string1)==[1,2,4]): print("Pass") else: print("Test 1 Failed") if (s.plusOne(string2)==[4,3,2,2]): print("Pass") else: print("Test 2 Failed") if (s.plusOne(string3)==[1,0,0]): print("Pass") else: print("Test 3 Failed")
def GA_crossover(sol1, sol2): import sys assert sys.version_info[0] == 3, sys.version_info abo = CONFIG['letter_frequency'] get_index = lambda t: ord(t) - ord('a') # Crossover method 1. with ordering based on frequency, just crossover # CUTOFF alpha : randomly choose # DEAD METHOD, since it does not seems to generate better result if False: alpha = randint(0, 24) new_pos1 = [(0, 0) for _ in range(26)] new_pos2 = [(0, 0) for _ in range(26)] for it, e in enumerate(abo): ind = get_index(e) if it < alpha: new_pos1[ind] = sol1.get_loc(ind) new_pos2[ind] = sol2.get_loc(ind) else: new_pos1[ind] = sol2.get_loc(ind) new_pos2[ind] = sol1.get_loc(ind) # Crossover method 2, idea by BJ # offspring1 : given location information from parent 1 # given alphabet information from parent 2 # ordering from left to right # offspring2 : given location information from parent 2 # given alphabet information from parent 1 # ordering from left to right # ISSUE: Some limitation on searching for solution space? # ISSUE: Is it generate better result? def crossover2(pos1, pos2): assert pos1.shape[1] == 2 == pos2.shape[1] # ordering information # if p1 = [1, 3, 2, 0] means # among b(1), d(3), c(2), a(0), # b is on the leftmost side, a is on the rightmost side p1 = np.argsort(pos1[:, 0]) # pos1[p1[i]][0] < pos1[p1[i+1]][0] p2 = np.argsort(pos2[:, 0]) new_pos1 = np.zeros(pos1.shape) new_pos2 = np.zeros(pos2.shape) # alphabet with index ai is i'th in new_pos2 for i, ai in enumerate(p2): new_pos1[ai] = pos1[p1[i]] for j, aj in enumerate(p1): new_pos2[aj] = pos2[p2[j]] return new_pos1, new_pos2 a, b = crossover2(np.array([[0, 0], [1, 0], [0.4, 0], [7, 0]]), np.array([[2, 0], [4, 0], [1.5, 0], [1, 0]])) assert np.all(a == np.array([[1, 0], [7, 0], [0.4, 0], [0, 0]])) assert np.all(b == np.array([[1, 0], [2, 0], [1.5, 0], [4, 0]])) # Crossover method 3, idea by BS # offspring1 : given left-half location from parent 1 # given right-half location from parent 2 # offspring2 : given left-half location from parent 2 # given right-half location from parent 1 # alphabet information on each offspring # -> depending on priority on alphabet frequency # # ISSUE: Is it generate better result? def crossover3(pos1, pos2): assert len(pos1) == len(pos2) == 26 # ordering information # if p1 = [1, 3, 2, 0] means # among b(1), d(3), c(2), a(0), # b is on the leftmost side, a is on the rightmost side p1 = np.argsort(pos1[:, 0]) # pos1[p1[i]][0] < pos1[p1[i+1]][0] p2 = np.argsort(pos2[:, 0]) # ISSUE: overlapping problem. # For each parent, one point in parent and other one in other parent # could be 'close' to each other. These pairs of points should not # reach to single offspring. # Dividing into two parts for each parent, making no overlapping points. # ASSUMPTION: there is no two close points in one parent # The assumption is not really critical, but it helps thinking close = lambda pos1, pos2: \ np.abs(pos1[0]-pos2[0]) < 0.01 and \ np.abs(pos1[1]-pos2[1]) < 0.01 # Extract close points iteratively. overlapped = [] # tuple of (idx1, idx2) for idx1 in p1: point1 = pos1[idx1] for idx2 in p2: point2 = pos2[idx2] if close(point1, point2): overlapped.append((idx1, idx2)) break if point2[0] > point1[0] + 0.01: break # Below statements are used before fixing overlapping issue # p1_left_pos_idx = p1[:13] # p1_right_pos_idx = p2[13:] # p2_left_pos_idx = p2[:13] # p2_right_pos_idx = p1[13:] # Step 1. Divide overlapped points into two part # with ordering left to right # (may be not exactly half for odd) # Step 2. Divide remaining points into two parts # with ordering left to right p1_left_pos_idx = [] # left part of offspring 1 p1_right_pos_idx = [] # right part of offspring 2 p2_left_pos_idx = [] # left part of offspring 2 p2_right_pos_idx = [] # right part of offspring 1 # Step 1 half = len(overlapped) // 2 for i, (idx1, idx2) in enumerate(overlapped): if i < half: p1_left_pos_idx.append(idx1) p2_left_pos_idx.append(idx2) else: p1_right_pos_idx.append(idx1) p2_right_pos_idx.append(idx2) p1_used_idx = p1_left_pos_idx + p1_right_pos_idx p2_used_idx = p2_left_pos_idx + p2_right_pos_idx # Step 2 for idx in p1: if idx not in p1_used_idx: if len(p1_left_pos_idx) < 13: p1_left_pos_idx.append(idx) else: p1_right_pos_idx.append(idx) for idx in p2: if idx not in p2_used_idx: if len(p2_left_pos_idx) < 13: p2_left_pos_idx.append(idx) else: p2_right_pos_idx.append(idx) assert len(p1_left_pos_idx) == 13 assert len(p1_right_pos_idx) == 13 assert len(p2_left_pos_idx) == 13 assert len(p2_right_pos_idx) == 13 new_pos1 = np.zeros(pos1.shape) new_pos2 = np.zeros(pos2.shape) # decide which part to go when alphabet ALPHA given # case 1. ALPHA is on the left on parent 1 and # ALPHA is on the left on parent 2 # -> put ALPHA on just corresponding location on offsprings 1 # case 2. ALPHA is on the right on parent 1 and # ALPHA is on the right on parent 2 # -> just same as case 1. # case 3. ALPHA is on the left on parent 1 and # ALPHA is on the right on parent 2 # -> Both corresponding locations are on the offspring 1 # -> Yield one between them, for some another alphabet, # which assigned to both location on offspring 2 # case 4. ALPHA is on the right on parent 1 and # ALPHA is on the left on parent 2 # -> Both corresponding locations are on the offspring 2 # -> Yield one between them, for some another alphabet, # which assigned to both location on offspring 1 # control case 3 and case 4 # list of tuples: (alphabetid) off1_extra = [] # case 3. extra alphabets on offspring 1 off2_extra = [] # case 4. extra alphabets on offspring 2 for alphabet in abo: idx = get_index(alphabet) if idx in p1_left_pos_idx: if idx in p2_left_pos_idx: new_pos1[idx] = pos1[idx] new_pos2[idx] = pos2[idx] else: # case 3 if off2_extra: idx2 = off2_extra.pop(0) if randint(0, 1): new_pos1[idx] = pos1[idx] new_pos2[idx] = pos1[idx2] new_pos1[idx2] = pos2[idx] new_pos2[idx2] = pos2[idx2] else: new_pos1[idx] = pos2[idx] new_pos2[idx] = pos2[idx2] new_pos1[idx2] = pos1[idx] new_pos2[idx2] = pos1[idx2] else: off1_extra.append(idx) else: if idx not in p2_left_pos_idx: new_pos1[idx] = pos2[idx] new_pos2[idx] = pos1[idx] else: # case 4 if off1_extra: idx2 = off1_extra.pop(0) if randint(0, 1): new_pos1[idx] = pos2[idx2] new_pos2[idx] = pos2[idx] new_pos1[idx2] = pos1[idx2] new_pos2[idx2] = pos1[idx] else: new_pos1[idx] = pos1[idx2] new_pos2[idx] = pos1[idx] new_pos1[idx2] = pos2[idx2] new_pos2[idx2] = pos2[idx] else: off2_extra.append(idx) assert off1_extra == [] == off2_extra return new_pos1, new_pos2 # Crossover method 4, BLX-alpha, (blend crossover) # http://www.tomaszgwiazda.com/blendX.htm def crossover4(pos1, pos2): assert len(pos1) == 26 == len(pos2) new_pos1 = np.zeros(pos1.shape) new_pos2 = np.zeros(pos2.shape) width, height = Solution.field.width, Solution.field.height dx = 4 dy = 10 for i in range(26): minx = max(min(pos1[i][0], pos2[i][0]) - dx, 0) maxx = min(max(pos1[i][0], pos2[i][0]) + dx, width) miny = max(min(pos1[i][1], pos2[i][1]) - dy, 0) maxy = min(max(pos1[i][1], pos2[i][1]) + dy, height) new_pos1[i] = [uniform(minx, maxx), uniform(miny, maxy)] new_pos2[i] = [uniform(minx, maxx), uniform(miny, maxy)] return new_pos1, new_pos2 if True: new_pos1, new_pos2 = crossover3(sol1.positions, sol2.positions) return Solution(new_pos1), Solution(new_pos2)
def setUp(self): self.countSquares = Solution().countSquares
def test_wordBreak_repeated_word(self): s = Solution() result = s.wordBreak("applepenapple", ["apple", "pen"]) self.assertEqual(result, True)
def test_wordBreak(self): s = Solution() result = s.wordBreak("leetcode", ["leet", "code"]) self.assertEqual(result, True)
def test_solution(): s = Solution() assert s.backspaceCompare('ab#c', 'ad#c') == True assert s.backspaceCompare('ab##', 'c#d#') == True assert s.backspaceCompare('a##c', '#a#c') == True assert s.backspaceCompare('a#c', 'b') == False
def setUp(self): self.min_move = Solution().minMoves
def test2(self): self.assertEqual(Solution().minSubArrayLen(7, [2, 3, 1, 2, 4, 3]), 2)
def test_solution(): s = Solution() assert s.mincostTickets(1,4,6,7,8,20], [2,7,15])
def test1(self): self.assertEqual(Solution().minSubArrayLen(3, [1, 1]), 0)
def test3(self): self.assertEqual(Solution().minSubArrayLen(4, [0, 4, 4]), 1)
def test_array_sign(nums, expected): solution = Solution() assert solution.arraySign(nums) == expected
def test_solution(): s = Solution() assert s.integerBreak(10) == 36
# Licensing Information: You are free to use or extend these projects for # educational purposes provided that (1) you do not distribute or publish # solutions, (2) you retain this notice, and (3) you provide clear # attribution to UC San Diego. # Created by Yuzhe Qin, Fanbo Xiang from final_env import FinalEnv from solution import Solution import numpy as np if __name__ == '__main__': np.random.seed(0) env = FinalEnv() # env.run(Solution(), render=True, render_interval=5, debug=True) # at test time, run the following env.run(Solution()) env.close()
from functions_manager import split_function from functions_manager import split_function def create_children(parents, history = None): u'returns tuple containing 2 children from 2 parents' x, y = parents c1, c2 = deepcopy(x), deepcopy(y) m1 = split_function(c1.f, 0.25) m2 = split_function(c2.f, 0.25) if m1[1] == None or m2[1] == None: if m1[1] == None and m2[1]: if m2[2] == 1: m2[1].child1 = deepcopy(m1[0]) elif m2[2] ==2: m2[1].child2 = deepcopy(m1[0]) elif m2[1] == None and m1[1]: if m1[2] == 1: m1[1].child1 = deepcopy(m2[0]) elif m1[2] ==2: m1[1].child2 = deepcopy(m2[0]) else: if m1[2] == 1: # first child m1[1].child1 = m2[0] else: m1[1].child2 = m2[0] if m2[2] == 1: m2[1].child1 = m1[0] else: m2[1].child2 = m1[0] return (c1,c2) from solution import Solution from functions_manager import rand_function create_population = lambda amount, max_dept: [Solution(rand_function(max_dept)) for i in range(amount)]
def test_solution(): s = Solution() assert s.canPartition([1, 5, 11, 5]) == True assert s.canPartition([1, 2, 3, 5]) == False
def test_wordBreak_false(self): s = Solution() result = s.wordBreak("catsandog", ["cats", "dog", "sand", "and", "cat"]) self.assertEqual(result, False)
def test_solution(): s = Solution() assert s.maxSubArray([-2, 1, -3, 4, -1, 2, 1, -5, 4]) == 6 assert s.maxSubArray([1]) == 1
def test_solution(): intervals = [[1, 4], [3, 6], [2, 8]] assert Solution().remove_covered_intervals(intervals) == 2 intervals = [[1, 4], [2, 8], [1, 6]] assert Solution().remove_covered_intervals(intervals) == 2
def setUp(self): self.ways = Solution().ways
def test_solution(): s = Solution() assert s.leastInterval(["A", "A", "A", "B", "B", "B"], 2)
def test_numIslands(self): grid = [[1, 1, 0, 0, 0], [0, 1, 0, 0, 1], [1, 0, 0, 1, 1], [0, 0, 0, 0, 0]] self.assertEqual(3, Solution().numIslands(grid))
def setUp(self): self.solution = Solution()
#!/usr/bin/python from solution import Solution # Unit Test solutionObject = Solution() input_string = "G()(al)" print(solutionObject.interpret(input_string))
def test_solution(): s = Solution() assert s.coinChange([1, 2, 5], 11) == 3
def setUp(self) -> None: self.solution = Solution()
#!/usr/bin/env python # -*- coding: utf-8 -*- from solution import Solution # nums = [1, 2, 5, 6] nums = [2, 1, 1, 2] sol = Solution() res = sol.rob(nums) print(res)
def test2(self): self.assertEqual(Solution().distance('horse', 'ros'), 3)