def add_remain(lst, zf): global ans my_lst = [] for idx, val in enumerate(lst): for _ in range(val): for num in need[idx]: my_lst.append(num) for num in range(0, zf + 1): cal_set = set() for _ in range(num): my_lst.append(0) for _ in range(zf - num): my_lst.append(5) # print(my_lst) for my_set in pm(my_lst): my_str = '' for num in my_set: my_str = my_str + str(num) if my_str[0] == '0': continue else: my_num = int(my_str) cal_set.add(my_num) for cal in cal_set: if n <= cal <= m: ans += 1 for _ in range(zf): my_lst.pop()
def solution(expression): frc = ['+', '-', '*'] exp_list, frc_list = fx_exp(expression) # list 만들어주기 pm_frc = list(pm(set(frc_list))) # 순열을 통해서 계산 순서 리스트 작성 answer = [] for i in pm_frc: # 얕은 복사가 아닌 깊은 복사를 통해 기존의 list 변하지 않도록 만들어줌 exp_lists = deepcopy(exp_list) frc_lists = deepcopy(frc_list) for j in i: frc_index = [] for index, k in enumerate(frc_lists): if j == k: # 무조건 기호list보다는 숫자list가 더 길기 때문에 가능한 방법 # 계산 결과를 기호index 다음의 숫자list원소로 넣어놓는 방법 x = frc_cal(exp_lists[index], exp_lists[index + 1], k) frc_index.append(index) exp_lists[index + 1] = x # reverse 하는 이유는 앞에서부터 하면 indexerror가 나기 때문에 뒤에서 부터 진행 frc_index.sort(reverse=True) # 이미 계산된 값들은 기호index 다음에 위치하기 때문에 index별로 제거 for l in frc_index: del frc_lists[l] del exp_lists[l] # 이미 계산된 list중 절댓값이 가장 큰 값만 answer로 넣어줬음 answer.append(max([abs(i) for i in exp_lists])) return max(answer)
def mySolution(numbers): cnt = 0 uniqueNumToCalc = list() for numOfDigits in range(1, len(numbers) + 1): combs = set([ str((''.join(item))) for item in list(cb([c for c in numbers], numOfDigits)) ]) # print('='*50) # print('combs:') # print(combs) for c in combs: # perms = set([int(''.join(item)) for item in list(pm(c))]) perms = set(list(pm(c))) # print('-'*25) # print('set perms') # print(perms) for perm in perms: x = int(''.join(perm)) uniqueNumToCalc.append(x) uniqueNumToCalc = set(uniqueNumToCalc) for x in uniqueNumToCalc: # print('x:', x, end=' ') if isPrime(x): cnt += 1 # print(f'>>> prime <<< cnt: {cnt}') # else: # print(f'... no ... cnt: {cnt}') print('*/\*' * 25) print('cnt:', cnt) return cnt
def solution(expression): operators = [] numbers = [] number = 0 for i in expression: if i not in '+-*': number = number * 10 + int(i) else: numbers.append(number) number = 0 operators.append(i) numbers.append(number) maxi = -21470000000 for perm in list(pm(set(operators))): c_numbers = numbers[:] c_operators = operators[:] for oper in perm: while oper in c_operators: idx = c_operators.index(oper) operator = c_operators.pop(idx) num1 = c_numbers.pop(idx) num2 = c_numbers.pop(idx) if operator == '*': result = num1 * num2 elif operator == '+': result = num1 + num2 else: result = num1 - num2 c_numbers.insert(idx, result) maxi = max(maxi, abs(c_numbers[0])) answer = maxi return answer
def unscramble(): """Takes a user's input and outputs possible answers""" # Accept input of scrambled words and break into letters. scrambled_word = input("Please enter a word to be unscrambled: ") scrambled_letters = [letter for letter in scrambled_word] # Get all unique letter combinations into a list combinations = list(pm(scrambled_letters,len(scrambled_letters))) # TODO: Need to refactor to be simpler guesses = [] for combo in combinations: string_guess = ''.join(combo) guesses.append(string_guess) guesses = set(guesses) # Elimiate potential duplicates # Assign english words to a variable. words = set(get_english_words('words_alpha.txt')) # Checks if word in English language and print potential answers answers = guesses.intersection(words) if answers: print("\nThe english words that can be made from those letters are:") for answer in answers: print("-" + answer) else: print("\nCould not make a word with those letters.")
def main(): n = int(si()) l = [int(e) for e in si().split()] op = [int(e) for e in si().split()] opl = [] for i in range(4): for _ in range(op[i]): opl.append(i) p = pm(opl, n-1) mx, mn = (-1)*(1+int(1e9)), 1+int(1e9) for e in p: idx = 0 tot = l[idx] for ee in e: idx += 1 if ee == 0: tot += l[idx] elif ee == 1: tot -= l[idx] elif ee == 2: tot *= l[idx] else: tot /= l[idx] tot = int(tot) if tot < mn: mn = tot if tot > mx: mx = tot print(mx) print(mn)
def anothersSolution(n): a = set() for i in range(len(n)): a |= set(map(int, map("".join, pm(list(n), i + 1)))) a -= set(range(0, 2)) for i in range(2, int(max(a)**0.5) + 1): a -= set(range(i * 2, max(a) + 1, i)) return len(a)
def permutations(string): lst = [x for x in string] perm = set(pm(lst)) permlst = [] for x in perm: str = ('').join(x) permlst.append(str) return permlst
def solution(numbers): answer = [] for i in range(1, len(numbers) + 1): ss = set(list(pm(numbers, i))) # 해당 길이 숫자에서 중복제거 for s in ss: num = int(''.join(s)) if isPrime(num): answer.append(num) return len(set(answer))
def BestMove(Tiles, GameBoard): if '&' in Tiles: alternate = list(Tiles) alternate.remove('&') master = [] for item in string.ascii_uppercase: newTiles = alternate + [item] a = BestMove(newTiles, GameBoard)[-7:] if a: master.extend(a) if len(master) > 0: return sorted(master, key=lambda x: x[-1]) return False Moves = [] MoveBoard, GoodTiles = MoveTiles(GameBoard) SolvedCases = {} for row, col in GoodTiles: Section = [] for i in (1, 2): for item in BothWays(row, col, GameBoard, i, MoveBoard, len(Tiles)): Section.append(item) for item in Section: valids = [] fills = [x.isalpha() for x in item[0] ].count(0) # number of blanks in selection if fills not in SolvedCases: # generates new permuations SolvedCases[fills] = list( set([''.join(x) for x in list(set(pm(Tiles, fills)))])) for part in SolvedCases[fills]: # building out the new word a, attempt = 0, '' for char in item[0]: if char.isalpha(): attempt += char else: attempt += part[a] a += 1 if isWord(attempt.lower()): if a == MaxTile: valids.append((attempt, True)) else: valids.append((attempt, False)) for piece in valids: if AllGood(item[1][0], item[1][1], piece[0], GameBoard): Start = item[1][1] Direction = item[1][0] Points = Score(Direction, Start, piece[0], GameBoard, piece[1], MoveBoard) Assembly = (Direction, Start, piece[0], Points) if Assembly not in Moves: Moves.append(Assembly) result = sorted(Moves, key=lambda x: x[-1]) if len(result) > 0: return result return False
def solution(numbers): answer = 0 num_set = set() for i in range(1, len(numbers) + 1): for num_list in pm(list(numbers), i): num = int(''.join(num_list)) num_set.add(num) for num in num_set: if is_prime(num): answer += 1 return answer
def permutations(string): ''' best: return list("".join(p) for p in set(pm(string))) ''' output = [] for permutation_letters in pm(string): output.append("".join(permutation_letters)) return np.unique(np.array(output))
def getPermutation(self, n, k): perms = pm(list(range(1,n+1))) r= list(perms) kth = r[k-1] k='' for i in kth: k += str(i) return k
def solution(user_id, banned_id): # 길이만큼 순열 돌려서 리스트 만들고 cases = pm(user_id, len(banned_id)) # [[a, b, c], [b, c, a]......[c, b, a]] ban_res = [] for case in cases: if isValid(case, banned_id): users = set(case) # {a, b, c} if users not in ban_res: ban_res.append(users)
def wowbruteforcer(letters, wordsdict=WORDSDICT_FILE): generated_fixtures = set() dictionary = set() print('[=] Generating words...') for _ in range(3, len(letters)): generated_fixtures.update(set(map("".join, pm(letters, _)))) print('[=] Loading dictionary...') with open(WORDSDICT_FILE, 'r') as file_handler: for line in file_handler: dictionary.add(line.strip()) print('[?] Finding words in dictionary...') return generated_fixtures.intersection(dictionary)
def solveDouble(): x, y = map(int, input().split()) b = [(v / x) for v in map(int, input().split())] c = [(v / y) for v in map(int, input().split())] ans = 0 for xs in pm(c): cnt = 0 for i, v in enumerate(b): if okay(v, xs[i]): cnt += 1 ans = max(ans, cnt) return ans
def solution(n:int, seq:str, sign_num:str) -> list : number = list(map(int, seq.split())) sign_list = elementary_arithmetic(sign_num) sign_pm = pm(sign_list, len(sign_list)) number_list = number[1:] whole_value = [] for lists in sign_pm : val = number[0] for ind in range(0, n-1) : val = calculate(val, number_list[ind], lists[ind]) whole_value.append(val) answer = [max(whole_value), min(whole_value)] return answer
def solution(numbers): ans = [] for i in range(1, len(numbers) + 1): boards = set(pm(list(numbers), i)) for board in boards: a = '' for j in board: a += j a = int(a) if find_prime(a): ans.append(a) return len(set(ans))
def getNumber(self, N, K): # max_val = N * (N + 1) / 2 fac_n = self.fac(N) res = 0 for nos in pm(range(1, N + 1)): local = 0 for (key, value) in enumerate(nos): if key + 1 > value: local = local + key + 1 else: local = local + value if local >= K: res = (res + fac_n) % (10 ** 9 + 7) return res
def getNumber(self, N, K): # max_val = N * (N + 1) / 2 fac_n = self.fac(N) res = 0 for nos in pm(range(1, N + 1)): local = 0 for (key, value) in enumerate(nos): if key + 1 > value: local = local + key + 1 else: local = local + value if local >= K: res = (res + fac_n) % (10**9 + 7) return res
def solution(expression): answer = 0 deq = deque([]) que = deque([]) tmp = "" for i in expression: if '0' <= i <= '9': tmp += i continue que.append(int(tmp)) que.append(i) tmp = "" que.append(int(tmp)) # print(deq) operation = ['*', '+', '-'] for i in pm(operation): # max = deq = copy.deepcopy(que) # print(deq) for j in range(len(operation)): op = i[j] # print(op) deq2 = deque([]) while deq: if len(deq) == 1: deq2.append(deq.popleft()) break a = deq.popleft() oper = deq.popleft() if oper != op: deq2.append(a) deq2.append(oper) continue else: b = deq.popleft() if oper == '+': deq.appendleft(a + b) elif oper == '-': deq.appendleft(a - b) else: deq.appendleft(a * b) deq = deq2 if answer < abs(deq[0]): answer = abs(deq[0]) # print(answer) return answer # solution("50*6-3*2")
def solution(user_id, banned_id): answer = 0 ans_lst = [] for candidated_id in pm(user_id, len(banned_id)): if isMatch(candidated_id, banned_id): candidated_id = set(candidated_id) if candidated_id not in ans_lst: ans_lst.append(candidated_id) # print(ans_lst) answer = len(ans_lst) return answer # solution(["frodo", "fradi", "crodo", "abc123", "frodoc"], ["*rodo", "*rodo", "******"])
def main(): n = int(si()) l = [int(e) for e in si().split()] op = [int(e) for e in si().split()] opl = [] for i in range(4): if i == 0: o = 1 elif i == 1: o = 2 elif i == 2: o = 3 else: o = 4 for _ in range(op[i]): opl.append(o) p = pm(opl, n - 1) mx, mn = (-1) * (1 + int(1e9)), 1 + int(1e9) for e in p: idx = 0 tot = l[idx] e = list(e) # print(e) for ee in e: idx += 1 if ee == 1: tot += l[idx] elif ee == 2: tot -= l[idx] elif ee == 3: tot *= l[idx] else: if tot < 0: tot = (tot * (-1) // l[idx]) * (-1) else: tot //= l[idx] # print(tot) if tot < mn: mn = tot if tot > mx: mx = tot print(mx) print(mn)
def main(): words = [] with open("../data/p98_words.txt", "r") as fin: for lines in fin: for i in lines.split(','): if i != i[::-1]: words.append(i[1:-1]) vals = [] anagramic_pairs = [] c_vals = [] for i in words: t = 0 for c in i[:]: t += 10**(ord(c) - ord('A')) if t in vals: if t in c_vals: anagramic_pairs.append((words[vals.index(t, vals.index(t)+1)], i)) c_vals.append(t) anagramic_pairs.append((words[vals.index(t)], i)) vals.append(t) sqr_list = [i**2 for i in range(0, 4*10**4) if i**2 < 10**9] digi_list = [i for i in range(0, 10)] for i in anagramic_pairs: worda, wordb = i[0], i[1] chl = [] for c in worda: if c not in chl: chl.append(c) n = len(chl) print(worda, wordb, n) pmiter = pm(digi_list, n) for j in pmiter: wa, wb = worda, wordb for k in range(0, n): wa = wa.replace(chl[k], str(j[k])) wb = wb.replace(chl[k], str(j[k])) if wa[0] == '0' or wb[0] == '0': continue va, vb = int(wa), int(wb) # if va in sqr_list and vb in sqr_list: if is_sqr(va) and is_sqr(vb): print(worda, wordb, va, vb)
def BA(n): n = 5 sum2 = defaultdict(list) nums = [x for x in range(1, n + 1)] allC = cm(nums, 2) for c in allC: sum2[sum(c)].append(c) allP = pm(nums, n) for p in allP: status = True for k in range(1, len(p) - 1): if (p[k] * 2 in sum2): for s in sum2[p[k] * 2]: i = p.index(s[0]) j = p.index(s[1]) if (i < k and k < j): status = False if (status == True): return (p)
def solution(n, weak, dist): # complete search dist.sort(reverse = True) for i in range(1, len(dist)+1): pms = pm(dist[:i]) for p in pms: for start in range(len(weak)): left = weak[:start] right = weak[start:] traverse_list = right + [x + n for x in left] candidates = list(p) while traverse_list and candidates: cur = traverse_list.pop(0) friend = candidates.pop(0); coverage = cur + friend while traverse_list and traverse_list[0] <= coverage: traverse_list.pop(0) if not traverse_list: return i return -1
def solution(n, weak, dist): ans = int(1e9) l = len(weak) circle_weak = weak + [w + n for w in weak] # print(circle_weak) # [1, 5, 6, 10, 13 ,17, 18, 25] for i in range(l): for case in pm(dist): see_window = circle_weak[i:i + l] start_point = circle_weak[i] cnt = 1 for d in case: start_point += d if start_point >= circle_weak[i + l - 1]: ans = min(ans, cnt) break cnt += 1 start_point = min( list(filter( lambda x: x > start_point, see_window))) # 시작값을 변경하는데 구간에서 이전 값보다 크면서 최소인 값 return ans if ans != int(1e9) else -1
for j in range(2*ii): ty, tx = ty + dy[k], tx + dx[k] idx.append((ty, tx)) t.append(gr[ty][tx]) t.appendleft(t.pop()) for i in range(len(t)): gr[idx[i][0]][idx[i][1]] = t[i] return gr # ans = float('inf') ans = 99999 for ridx in pm(range(K), K): tmpg = [[x for x in g[k]] for k in range(H)] for i in range(K): tmpg = rotate(r[ridx[i]][0] - 1, r[ridx[i]][1] - 1, r[ridx[i]][2], tmpg) ans = min(ans, min([sum(tmpg[i]) for i in range(H)])) print(ans) ''' 5 6 2 1 2 3 2 5 6 3 8 7 2 1 3 8 2 3 1 4 5
# d3d4d5=063 is divisible by 3 # d4d5d6=635 is divisible by 5 # d5d6d7=357 is divisible by 7 # d6d7d8=572 is divisible by 11 # d7d8d9=728 is divisible by 13 # d8d9d10=289 is divisible by 17 # Find the sum of all 0 to 9 pandigital numbers with this property. from itertools import permutations as pm lst = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0] poss = [] poss17 = [] poss = list(pm(lst, 3)) for x in xrange(0, len(poss), 1): temp = (''.join(str(poss[x][y]) for y in xrange(0, len(poss[x]), 1))) if int(temp) % 17 == 0: poss17.append(poss[x]) poss13 = [] for x in xrange(0, len(poss17), 1): newlst = list(lst[y] for y in xrange(0, len(lst), 1) if lst[y] not in poss17[x]) for i in xrange(0, len(newlst), 1): tempstr = list(list(str(newlst[i])[0]) + list(poss17[x])) temp = int(str(tempstr[0]) + str(tempstr[1]) + str(tempstr[2])) if temp % 13 == 0:
def permutations(string: str) -> list: return sorted(list(''.join(i) for i in set(pm(string))))
def distance(a, b): return ((a[0] - b[0])**2 + (a[1] - b[1])**2)**0.5 def sub_distance(l): if len(l) == 1: return 0 elif len(l) == 2: return distance(l[0], l[1]) else: return distance(l[0], l[1]) + sub_distance(l[1:]) def round_distance(l): return distance((0, 0), l[0]) + sub_distance(l) + distance( (0, 0), l[-1]), l lists = list(pm(l)) remove_reverse = [ list(v) for k, v in enumerate(lists) if v[::-1] not in lists[:k] ] results = list(map(round_distance, remove_reverse)) results = sorted(results, key=lambda pair: pair[0]) print("Given points are", l) print( 'The shortest round distance of given points is {0}, and the route is {1}'. format(results[0][0], results[0][1]))
def ii(): return int(input()) def iim(): return map(int, input().split()) def iil(): return list(map(int, input().split())) def ism(): return map(str, input().split()) def isl(): return list(map(str, input().split())) from itertools import permutations as pm a, b, c = iim() l = iil() ans = 0 for i in pm(range(3)): ans = max(ans, (a // l[i[0]]) * (b // l[i[1]]) * (c // l[i[2]])) print(ans)