def solution(n, k): L = [i for i in range(1, n + 1)] count = 0 for j in per(L): count += 1 if count == k: return list(j)
def solution(n, weak, dist): W = len(weak) for i in range(len(weak) - 1): weak.append(weak[i] + n) dist = sorted(dist, reverse=True) print(dist) def func(friends, weaks): cover, fidx = friends[0] + weaks[0], 0 for i, weakpoint in enumerate(weaks): if cover >= weakpoint: pass else: fidx += 1 if fidx == len(friends): return False cover = weakpoint + friends[fidx] return True for i in range(len(dist)): for friends in per(dist, i + 1): print(friends) for k in range(W): w = weak[k:k + W] if func(friends, w): return len(friends) return -1
def call(numset): def calc(ar): operations=[ "%f %%s %f %%s %f %%s %f" %(ar[0],ar[1],ar[2],ar[3]), "(%f %%s %f) %%s %f %%s %f" %(ar[0],ar[1],ar[2],ar[3]), "%f %%s (%f %%s %f) %%s %f" %(ar[0],ar[1],ar[2],ar[3]), # "%f %%s %f %%s (%f %%s %f)" %(ar[0],ar[1],ar[2],ar[3]), "(%f %%s %f %%s %f) %%s %f" %(ar[0],ar[1],ar[2],ar[3]), # "%f %%s (%f %%s %f %%s %f)" %(ar[0],ar[1],ar[2],ar[3]), "((%f %%s %f) %%s %f) %%s %f" %(ar[0],ar[1],ar[2],ar[3]), "(%f %%s (%f %%s %f)) %%s %f" %(ar[0],ar[1],ar[2],ar[3]), # "%f %%s ((%f %%s %f) %%s %f)" %(ar[0],ar[1],ar[2],ar[3]), # "%f %%s (%f %%s (%f %%s %f))" %(ar[0],ar[1],ar[2],ar[3]), "(%f %%s %f) %%s (%f %%s %f)" %(ar[0],ar[1],ar[2],ar[3]) ] results=set([]) for op in operations: for sign in operatorset: eq=op %(sign[0],sign[1],sign[2]) try: if eval(eq)==24: results.add(re.sub(".0+","",eq)) except:pass for result in results:print result return generator=per(numset) while True: try:calc(generator.next()) except:break
def solution(n, k): L = [] M = [] for i in range(1, n + 1): L.append(i) for j in per(L): M.append(list(j)) return M[k - 1]
def sum3(n): unique = set() temp = int(n**(1 / 3)) + 1 for a, b, c, d in per(range(1, temp), 4): s = a**3 + b**3 if s == c**3 + d**3 and s < n and s not in unique: unique.add(s) yield s
def cycle(n): s = str(n) nums = [int(''.join(i)) for i in per(s) if int(''.join(i)) > n and isprime_2(int(''.join(i)))] for num in nums: sub = num - n for _num in nums: _sub = _num - num if _sub == sub: return int(str(n) + str(num) + str(_num)), sub return False, False
def solution(n, k): L = [] for i in range(1, n + 1): #[1,2,3,...,n-1,n]리스트를 만들어서 퍼뮤테이션에 사용하려고 L.append(i) count = 0 for j in per(L): count += 1 if count == k: return list(j)
def plotAll(map_points, points): order = pick_random(points) orders = list(per(order)) for i in range(len(orders)): orders[i] = goBack(orders[i]) orders = orders[:int(len(orders) / 2)] #orders = orders[:int(len(orders)/2)] for i in range(len(orders)): distance = str(total_distance(map_points, orders[i])) plt.figure(i) plt.title(distance) plot_points(map_points, points, orders[i])
def solution(numbers): answer = [] for k in range(1, len(numbers) + 1): # 1부터 숫자의 길이만큼 반복 perlist = list(map(''.join, per(list(numbers), k))) #k자리 경우의 수 추출 for i in list(set(perlist)): # set과 list화로 1차 중복제거 if check(int(i)): # 소수 맞으면 answer.append(int(i)) # answer에 어펜드 answer = len(set(answer)) # 2차 중복제거 및 숫자 확인 return answer
def fuse(w): for w in wincomb: for p in list(per(w)): t = frozenset(p) if t in grank: #print "found!!!!!!!!!!!" grank[t] = mix(grank[t], wincomb[t]) times[t] += 1 break else: #print "adding", w grank[w] = wincomb[w] times[w] = 0
def pandigital(order): nums = [str(i) for i in xrange(1, order+1)] product = [] for num in per(nums): num = ''.join(num) if isprime(int(num)) and check(num, order): product.append(int(num)) else: continue if product: return max(product) else: return None
def solution(numbers): nl = [] for i in range(1, len(numbers) + 1): x = per(numbers, i) for j in x: nl.append(int(''.join(j))) nl = set(nl) cnt = 0 for i in nl: if i != 0 and i != 1: if prime(i) == True: cnt += 1 return cnt
def main(): temp = list(map(int, input().split())) c, a, b = temp.pop(temp.index(max(temp))), temp[0], temp[1] condicoes = [ abs(b - c) < a < b + c, abs(a - c) < b < a + c, abs(a - b) < c < a + b ] if all(condicoes): if a == b == c: print('Valido-Equilatero') elif a != b != c: print('Valido-Escaleno') elif any(map(lambda x: x[0] == x[1] != x[2], per([a, b, c], 3))): print('Valido-Isoceles') print('Retangulo: {}'.format('S' if a**2 + b**2 == c**2 else 'N')) else: print('Invalido')
def bruteForce(points, map_points): #find all the possible total distances that would take to travel to all the #points, and display the graph with the shortest distance_map distances = [] orders = [] order = pick_random(map_points) orders = (list(per(order))) for i in range(len(orders)): orders[i] = goBack(orders[i]) print(orders) orders = orders[:int(len(orders) / 2)] for i in range(len(orders)): distance = total_distance(map_points, orders[i]) distances.append(distance) minDistIndex, minDist = minIndex(distances) minOrder = orders[minDistIndex] print(max(distances)) return minDist, minOrder
def win(self, turn, app, mode): self.app = app self.mode = mode self.crossed_boxs += 1 self.uncrossed_boxs -= 1 winning_cases = [[0, 1, 2], [3, 4, 5], [6, 7, 8], [0, 3, 6], [1, 4, 7], [2, 4, 8], [0, 4, 8], [2, 4, 6]] if turn == 1: lista = self.player_moves1 else: lista = self.player_moves2 for case in winning_cases: for combination in list(per(lista, len(lista))): for case2 in list(per(case, len(case))): if list(combination) == list(case2): return True else: pass
def solution(string): cal = ['-', '+', '*'] priority = list(map(list, per(cal))) input_list = [] answer = [] tmp = '' for cur in string: if cur in cal: input_list.append(int(tmp)) input_list.append(cur) tmp = '' else: tmp += cur input_list.append(int(tmp)) for cur in priority: tmp_list = deepcopy(input_list) for cal in cur: idx = 0 while idx < len(tmp_list): if tmp_list[idx] == cal: if tmp_list[idx] == '-': tmp = tmp_list[idx - 1] - tmp_list[idx + 1] elif tmp_list[idx] == '+': tmp = tmp_list[idx - 1] + tmp_list[idx + 1] elif tmp_list[idx] == '*': tmp = tmp_list[idx - 1] * tmp_list[idx + 1] tmp_list[idx - 1] = tmp tmp_list.pop(idx) tmp_list.pop(idx) idx -= 1 idx += 1 answer.append(abs(tmp_list[0])) return max(answer)
from itertools import permutations as per shouldhave = '123456789' sudos = [''.join(l for l in _gen) for _gen in per(shouldhave)] kudos = { 0:[], 1:[], 2:[], 3:[], 4:[], 5:[], 6:[], 7:[], 8:[], 9:[], 10:[], 11:[], 12:[], 13:[], 14:[], 15:[], 16:[], 17:[], 18:[], 19:[], 20:[], 21:[], 22:[], 23:[], 24:[], 25:[], 26:[], 27:[], 28:[], 29:[], 30:[], 31:[], 32:[], 33:[], 34:[], 35:[], 36:[], 37:[], 38:[], 39:[], 40:[], 41:[], 42:[], 43:[], 44:[], 45:[], 46:[], 47:[], 48:[], 49:[], 50:[] } su_sum = 0 f = open('_sudoku.txt', 'r') count = 50 while count > 0: _line = f.readline() if 'Grid' in _line: _firstrow = f.readline().strip() boxes = {0:[], 1:[], 2:[], 3:[], 4:[], 5:[], 6:[], 7:[], 8:[] } _shdntcnt = {0:[], 1:[], 2:[], 3:[], 4:[], 5:[], 6:[], 7:[], 8:[] } '''for _inbox in _firstrow: if _inbox != '0': boxes[_firstrow.index(_inbox)//3].append(_inbox) ''' for _next8rows in range(2,10): _thisline = f.readline().strip() for _cur in range(8): if _thisline[_cur] != '0': box_count = (_next8rows//3) + _cur // 3
from itertools import permutations as per s=sorted(list(map("".join,set(per(input())))) print(len(s),*s,sep='\n')
function_exercises.is_two(n) from function_exercises import is_vowel from function_exercises import is_consonant as is_c # 1.How many different ways can you combine the letters from "abc" with the numbers 1, 2, and 3? from itertools import product as p combinations = list(p('abc', '123')) combinations # 2. How many different ways can you combine two of the letters from "abcd"? from itertools import permutations as per combs2 = list(per('abcd', 2)) combs2 from json import load lis = load(open("profiles.json")) lis len(lis) len([d for d in lis if d['isActive'] == True]) len([d for d in lis if d['isActive'] == False]) def handle_balance(s): return float(s[1:].replace(',', ''))
from itertools import permutations as per import re operators=per(['+','+','+','-','-','-','*','*','*','/','/','/'],3) operatorset=set([]) while True: try:operatorset.add(operators.next()) except:break def call(numset): def calc(ar): operations=[ "%f %%s %f %%s %f %%s %f" %(ar[0],ar[1],ar[2],ar[3]), "(%f %%s %f) %%s %f %%s %f" %(ar[0],ar[1],ar[2],ar[3]), "%f %%s (%f %%s %f) %%s %f" %(ar[0],ar[1],ar[2],ar[3]), # "%f %%s %f %%s (%f %%s %f)" %(ar[0],ar[1],ar[2],ar[3]), "(%f %%s %f %%s %f) %%s %f" %(ar[0],ar[1],ar[2],ar[3]), # "%f %%s (%f %%s %f %%s %f)" %(ar[0],ar[1],ar[2],ar[3]), "((%f %%s %f) %%s %f) %%s %f" %(ar[0],ar[1],ar[2],ar[3]), "(%f %%s (%f %%s %f)) %%s %f" %(ar[0],ar[1],ar[2],ar[3]), # "%f %%s ((%f %%s %f) %%s %f)" %(ar[0],ar[1],ar[2],ar[3]), # "%f %%s (%f %%s (%f %%s %f))" %(ar[0],ar[1],ar[2],ar[3]), "(%f %%s %f) %%s (%f %%s %f)" %(ar[0],ar[1],ar[2],ar[3]) ] results=set([]) for op in operations: for sign in operatorset: eq=op %(sign[0],sign[1],sign[2]) try: if eval(eq)==24: results.add(re.sub(".0+","",eq))
value += b else: value += m mem[adress] = int(value, 2) print(sum(list(mem.values()))) mem = {} for line in open("i").read().strip().splitlines(): op, val = line.split(" = ") if op == "mask": mask = [i for i in val] else: adress = [i for i in f"{int(op[4:-1]):b}".zfill(36)] new = "" for m, a in zip(mask, adress): if m == "0": new += a else: new += m perms = set() for com in comwr((0, 1), new.count("X")): for perm in per(com): perms.add(perm) for perm in perms: tmp = new for i in perm: tmp = tmp.replace("X", str(i), 1) mem[int(tmp, 2)] = int(val) print(sum(list(mem.values())))
node : int The vertex to which we need minimum cost. """ cost_path = 0 for node in range(len(set_Vertices)-1): cost_path += dist(graph, set_Vertices[node], set_Vertices[node+1]) return cost_path if __name__ == '__main__': graphs = [] initial_non = value_nonl(gen()) # dict conatining sbox non_sbox = {initial_non: gen()} all_perms = list(per(range(8))) array = gen() if is_bijective(array): for var in range(10): array_mod = [] for num in range(32): array_mod, graph = substitution( all_perms, array, array_mod, num) graphs.append(graph) # calculate non-linearity of modified Sbox nn_array_mod = value_nonl(array_mod) if nn_array_mod > limit1: non_sbox[nn_array_mod] = [array_mod, graphs] print(var, value_nonl(array), nn_array_mod) else: print('Is not bijective!')
from itertools import permutations as per #takes in the input x = list(map(int, input().split())) h2, h1 = x.pop(-1), x.pop(-1) #not necessarily the quickest way, but still fast #loops each permuation and calculates sum to compare to heights for y in per(x): s1, s2 = sum(y[0:3]), sum(y[3:]) if (s1 == h1 and s2 == h2): t1 = ' '.join(list(map(str, sorted(y[0:3], reverse=True)))) t2 = ' '.join(list(map(str, sorted(y[3:], reverse=True)))) print ("{} {}".format(t1, t2)) break
from itertools import permutations as per string, num = map(str, input().split()) num = int(num) answer = list(per(string, num)) permu = [] for sub in answer: temp = '' for key in sub: key = str(key) temp += key permu.append(temp) permu.sort() for item in permu: print(item)
from itertools import permutations as per p, k = input().split() l = list(per(sorted(p), int(k))) for var in l: print((var[0] + var[1]).upper())
f = open("randomdata", "w") chars = [chr(c) for c in range(ord('A'), ord('Z')+1)] # chars += [chr(c) for c in range(ord('a'), ord('z')+1)] init = 0 while init < lines: temp = "" for i in xrange(randint(4, 20)): temp += choice(chars) f.write(temp+"\n") init += 1 print "%d lines random data done" % lines f.close() f = open("ordereddata", "w") chars = [chr(c) for c in range(ord('A'), ord('K')+1)] gene = per( chars ) init = 0 while init < lines: f.write("".join(gene.next())+"\n") init += 1 print "%d lines ordered data done" % lines f.close() raw_input()
''' Created on 3 Oct 2020 @author: peter ''' from itertools import permutations as per all_perms = [''.join(letter) for letter in per(list('peterlavin'))] print(len(all_perms)) # print(all_perms) for i, perm in enumerate(all_perms): if i < 1000: print(perm) else: break # # valid_words = ('cat', 'act', 'tac') # # final_list = [] # # for word in all_perms: # if word in valid_words: # final_list.append(word) # # # # print(final_list)
from itertools import product a, b = map(int, input().split()), map(int, input().split()) print(*(product(a, b))) from itertools import permutations as per inp = input().split() astring = list(inp[0]) astring.sort() r = int(inp[1]) l = list(map(''.join, per(astring, r))) print(*l, sep='\n') #palindrome (n, num) = (int(input()), list(input().split())) print(all(int(i) > 0 for i in num) and any(i[:] == i[::-1] for i in num))
from itertools import permutations as per import sys n = int(input()) nums = list(map(int, (sys.stdin.readline().split()))) real_ans = 0 for p in per(nums, n): ans = 0 for i in range(n - 1): ans += abs(p[i] - p[i + 1]) if real_ans < ans: real_ans = ans else: continue print(real_ans)
print(question) num_check = is_two(3) print(num_check) check = iscon("t") print(check) # 1. How many different ways can you combine the letters from "abc" with the numbers 1, 2, and 3? from itertools import product prod = list(product("abc", "123")) num = len(prod) print(prod) print(f"There are {num} possible combinations.") # 2. How many different ways can you combine two of the letters from "abcd"? from itertools import combinations_with_replacement as cwr combo = list(cwr("abcd", 2)) length = len(combo) print(combo) print(f"There are {length} possible combinations.") # 2. Number 2 using permutations instead of combinations_with_replacement from itertools import permutations as per combo = list(per("abcd", 2)) length = len(combo) print(combo) print(f"There are {length} possible combinations.")
from itertools import permutations as per N, M, H = map(int, input().split()) B = [list(map(int, input().split())) for _ in range(N)] house = [(i, j) for i in range(N) for j in range(N) if B[i][j] == 1] milk = [(i, j) for i in range(N) for j in range(N) if B[i][j] == 2] def sol(p): h = M cnt = 0 ans = 0 x, y = p[0] for i in range(len(p) - 1): x0, y0 = p[i] x1, y1 = p[i + 1] dist = abs(x0 - x1) + abs(y0 - y1) if h >= dist: h -= dist h += H cnt += 1 else: break if h >= abs(x - x1) + abs(y - y1): ans = cnt return ans print(max(sol(house + list(p)) for p in per(milk)))
def permutations(string): return list(set(map(''.join, per(string))))
from itertools import permutations as per print list(per(range(10)))[999999]
name_list.sort() if num == 1: print(name_list[0]) else: num = int(input().strip()) for i in range(num): name1,name2 = input().strip().split() name_dict[name1].add(name2) name_dict[name2].add(name1) index = 1 length = len(name_list) ans = [] #print(name_dict) for k in per(name_list): has = True #print(k) for i in range(1,length): if k[i-1] in name_dict[k[i]]: has = False break if has: ans = k break if has: print(' '.join(ans)) else: print('You all need therapy.') except:
## 문제 18. ## 어떤 대상을 순서에 따라 배열한 것을 순열이라고 합니다. ## 예를 들어 3124는 숫자 1, 2, 3, 4로 만들 수 있는 순열 중 하나입니다. ## 이렇게 만들 수 있는 모든 순열을 숫자나 문자 순으로 늘어놓은 것을 ## 사전식(lexicographic) 순서라고 합니다. ## 0, 1, 2로 만들 수 있는 사전식 순열은 다음과 같습니다. ## 012 021 102 120 201 210 ## 0, 1, 2, 3, 4, 5, 6, 7, 8, 9로 만들 수 있는 사전식 순열에서 ## 1,000,000번째는 무엇입니까? # 2783915604 from itertools import permutations as per # my_list = [0, 1, 2] my_list = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] tmp_list = list(per(my_list)) lex_list = list() for i in tmp_list: my_str = '' for v in i: my_str += str(v) lex_list.append(my_str) # print((lex_list)) print(lex_list[1000000])