コード例 #1
0
ファイル: q32.py プロジェクト: mwcz/euler
def pdi(_digits, _f1length, _f2length):

    "get pandigital identities, for pandigitals with digits in _digits, and f1*f2=product f1 has length _f1length and f2 has length _f2length"

    products = {}
    factors1 = p(_digits, _f1length)  # two-digit factors

    # find all 1..9 pandigital identites with lengths 2*3=4
    for f in factors1:
        rd = [d for d in digits if d not in f]  # remaining digits
        factors2 = p(rd, _f2length)  # two-digit factors
        for F in factors2:
            rd2 = [d for d in rd if d not in f and d not in F]  # remaining digits available for product
            possible_products = p(rd2, len(_digits) - _f1length - _f2length)
            for P in possible_products:

                # convert factors and product from lists to ints
                factor1 = int("".join(map(str, f)))
                factor2 = int("".join(map(str, F)))
                product = int("".join(map(str, P)))

                if factor1 * factor2 == product:
                    products[product] = (factor1, factor2)
                    print("%d * %d = %d" % (factor1, factor2, product))

    return products
コード例 #2
0
def solve():
    def check(three_two):
        three, two = [int(''.join(t)) for t in three_two] 
        fst = str(three * (two %10))
        snd = str(three * (two//10))
        product = str(three * two)

        return (
            len(fst) == len(snd) == 3 and len(product) == 4
        and all(set(x).issubset(A) for x in [fst, snd, product])
        )
        
    _, A = int(input()), set(input().split())
    ans = sum(map(check, p(p(A, repeat=3), p(A, repeat=2))))
    print_line(ans)
コード例 #3
0
ファイル: p41.py プロジェクト: bambrose24/euler
def main():
    lst = []
    for i in range(3, 10):
        lst += p(list(range(1, i)))
    lst = list(map(flatten, lst))
    lst = list(filter(u.isPrime, lst))
    print(max(lst))
コード例 #4
0
ファイル: p41.py プロジェクト: bambrose24/euler
def main():
    lst = []
    for i in range(3, 10):
        lst += p(list(range(1, i)))
    lst = list(map(flatten, lst))
    lst = list(filter(u.isPrime, lst))
    print(max(lst))
コード例 #5
0
def brute(astring):
    aset = set()
    for perm in p(astring):
        aset.add(''.join(perm))
    alist = list(aset)
    alist.sort()
    return alist.index(astring)
def solve():
    #Define variables
    start = time.time()
    digits = [str(i) for i in reversed(range(10))]
    ans = 0
    found = False
    
    #Solve the problem
    for perm in p(digits):
        if found: break
        n = int(''.join(perm))
        for k in range(1, 10):
            if found: break
            t = 10**k
            c1 = n / t
            c2 = n % t
            if c1 == 0 or c2 == 0: continue
            g = gcd(c1, c2)
            if g == 1: continue
            for d in divisors(g):
                d1 = str(c1 / d)
                d2 = str(c2 / d)
                d = str(d)
                if sorted(''.join((d1, d2, d)), reverse = True) == digits:
                    found = True
                    ans = n
                    break
        
    ans = str(ans)

    #Print the results
	print 'The largest 0 to 9 pandigital 10-digit concatenated '
	print 'product of an integer with two or more other integers, '
	print 'such that the concatenation of the input numbers is ' 
	print 'also a 0 to 9 pandigital 10-digit number, is ' + ans + '.'
コード例 #7
0
    def compute_correlations(self):
        # Center
        if self.normalize_dimensions:
            for network in tqdm(self.representations_d, desc='mu, sigma'):
                t = self.representations_d[network]
                means = t.mean(0, keepdim=True)

                self.representations_d[network] = t - means

        # Set `self.similarities`
        # {network: {other: lincka_similarity}}
        self.similarities = {network: {} for network in
                             self.representations_d}
        for network, other_network in tqdm(p(self.representations_d,
                                             self.representations_d),
                                           desc='lincka',
                                           total=len(self.representations_d)**2):

            if network == other_network:
                continue

            if other_network in self.similarities[network]: 
                continue

            X = self.representations_d[network].to(self.device)
            Y = self.representations_d[other_network].to(self.device)

            XtX_F = torch.norm(torch.mm(X.t(), X), p='fro').item()
            YtY_F = torch.norm(torch.mm(Y.t(), Y), p='fro').item()
            YtX_F = torch.norm(torch.mm(Y.t(), X), p='fro').item()

            # eq 5 in paper
            sim = YtX_F**2 / (XtX_F*YtY_F)
            self.similarities[network][other_network] = sim
            self.similarities[other_network][network] = sim
コード例 #8
0
def generatePalindromes(s):
    r=[]
    if len(set(s))==1: return [s]
    for i in p(s):
        i=''.join(i)
        if i==i[::-1] and i not in r: r.append(i)
    return sorted(r)
コード例 #9
0
def largestTimeFromDigits(A):
    """
	:type A: List[int]
	:rtype: str
	"""
    time = (0, 0)
    flag = False
    for a, b, c, d in list(p(A)):
        hour = a * 10 + b
        minute = c * 10 + d
        if hour < 24 and minute < 60:
            time = max(time, (hour, minute))
            flag = True
    if flag:
        h, m = time
        res = []
        if h < 10:
            res.append('0')
        res.append(str(h))
        res.append(':')
        if m < 10:
            res.append('0')
        res.append(str(m))
        return ''.join(map(str, res))
    else:
        return ''
コード例 #10
0
def Solve(n = 10**7):
    #Define variables
    start  = time.time()
    pans, primes, ans = [], [], 0
    
    #Create the pandigitals to test
    #Note: pandigitals can only be prime if they
    #have a length of 4 or 7. Anything other length
    #is either greater than 10, or results in a number
    #divisible by 3, and therefore not prime.
    for i in [4, 7]:
        for pan in list(p([j for j in range(1, i + 1)])):
            pans.append(int(''.join(str(digit) for digit in list(pan))))
    
    #Find the prime pandigitals
    for i in range(len(pans)):
        if isPrime(pans[i]): primes.append(pans[i])
    
    #Find the largest prime pandigital under n
    if n <= primes[0]:
	    print('There are no pandigital primes < ' + str(n) + '.')
    else:
        for i in range(len(primes)):
            if primes[i] >= n:
                ans = str(primes[i - 1])
                break
        if ans == 0:
            ans, n = str(primes[-1]), str(n)
            print('The largest pandigital prime is ' + ans + '.')
        else: 
            n = str(n)
            print('The largest pandigital prime < ' + n + ' is ' + ans + '.')

    print('This took ' + str(time.time() - start) + ' seconds to calculate.')
コード例 #11
0
def solve(name):
    #Define variables
    start = time.time()
    digits = set()
    ans = 0
    f = open(name, 'r')
    keys = f.read().split('\n')
    keys = [list(key) for key in keys if len(key) > 0]
    for i in range(0, len(keys)):
        keys[i] = [int(num) for num in keys[i]]
    for key in keys:
        for digit in key:
            digits.add(digit)
    digits = list(digits)
    perms = p(digits)

    #Solve the problem
    for perm in perms:
        valid = True
        for key in keys:
            if valid:
                a = perm.index(key[0])
                b = perm.index(key[1])
                c = perm.index(key[2])
                if a > b or b > c:
                    valid = False
                    break
        if valid:
            ans = ''.join(str(i) for i in perm)
            break

    #Print the results
    print 'The shortest possible secret passcode of unknown length is ' + ans + '.'
    print 'This took ' + str(time.time() - start) + ' seconds to calculate.'
コード例 #12
0
    def numTilePossibilities(self, tiles: str) -> int:
        ans = {}
        for i in range(1, len(tiles) + 1):
            for j in p(tiles, i):
                ans[j] = 0

        return len(ans)
コード例 #13
0
def generatePalindromes(s):
    r = []
    if len(set(s)) == 1: return [s]
    for i in p(s):
        i = ''.join(i)
        if i == i[::-1] and i not in r: r.append(i)
    return sorted(r)
コード例 #14
0
def solution(n):
    answer = 0
    for i in range(n%2,n+1,2):
        temp = [1]*i + [2]*((n-i)//2)
            
        answer += len(list(set(list(p(temp,len(temp))))))

    return answer
コード例 #15
0
def combinations(r):
    for i in p(leetBaseWord, *punc, *numbers, possibles):
        format = "4621_ctf{{{0}}}"
        words = (format.format((''.join(i[0:3]))) + salt)
        capwords = (format.format((''.join(i[0:3]).capitalize())) + salt)
        base = hashlib.sha256(words.encode('utf-8')).hexdigest()
        basecapword = hashlib.sha256(capwords.encode('utf-8')).hexdigest()
        hashes = (i[-1])

        if base == hashes:
            with open("candidateWords.txt", 'a') as file1:
                file1.writelines("match success: " + hashes + "," + base +
                                 "," + words + '\n')

        elif basecapword == hashes:
            with open("candidateWords.txt", 'a') as file1:
                file1.writelines("match success: " + hashes + ", " +
                                 basecapword + ", " + capwords + '\n')

        else:
            #print(hashes + "," + base + "," + words)
            #print(hashes + " " + basecapword + " " + capwords)
            continue

    for w in p(leetBaseWord, *numbers, *punc, possibles):
        format = "4621_ctf{{{0}}}"
        words = (format.format((''.join(w[0:3]))) + salt)
        capwords = (format.format((''.join(w[0:3]).capitalize())) + salt)
        base = hashlib.sha256(words.encode('utf-8')).hexdigest()
        basecapword = hashlib.sha256(capwords.encode('utf-8')).hexdigest()
        hashes = (w[-1])

        if base == hashes:
            with open("candidateWords.txt", 'a') as file1:
                file1.writelines("match success: " + hashes + ", " + base +
                                 "," + words + '\n')

        elif basecapword == hashes:
            with open("candidateWords.txt", 'a') as file1:
                file1.writelines("match success: " + hashes + ", " +
                                 basecapword + ", " + capwords + '\n')

        else:
            #print(hashes + "," + base + "," + words)
            #print(hashes + "," + basecapword + "," + capwords)
            continue
コード例 #16
0
ファイル: Permutation.py プロジェクト: knight-byte/Codewars
def permutations(str):
    print(str)
    permList = p(str)
    li = []
    for perm in list(permList):
        li.append(''.join(perm))
    l2=list(set(li))
    l2.sort()
    return l2
コード例 #17
0
def triplet(nums):
    from itertools import permutations as p
    square = [i**2 for i in nums]
    per = list(p(square, 3))
    for i in range(len(per)):
        if per[i][0] + per[i][1] == per[i][2]:
            return True
    else:
        return False
コード例 #18
0
def numTilePossibilities(tiles):
    """
	:type tiles: str
	:rtype: int
	"""
    res = 0
    for i in range(1, len(tiles) + 1):
        res += len(set(p(tiles, i)))
    return res
コード例 #19
0
def length(digits):
    outputs = set()
    ops = [o.add, o.sub, o.mul, o.truediv]
    for a, b, c, d in p(digits):
        for op1, op2, op3 in pr(ops, repeat=3):
            outputs.update(
                [op1(op2(op3(a, b), c), d),
                 op1(op2(a, b), op3(c, d))])
    return next(i for i in co(1) if i not in outputs) - 1
コード例 #20
0
ファイル: d14.py プロジェクト: smehan/AOC
def solve2(m, N=0, r={*range(128)}):
    for N, q in ((N + 1, [S]) for S in p(*[r] * 2) if m[S[0]][S[1]]):
        while q:
            x, y = q.pop()
            m[x][y] = 0
            q.extend(n
                     for n in ((x + 1, y), (x - 1, y), (x, y + 1), (x, y - 1))
                     if {*n} < r and m[n[0]][n[1]])
    return N
コード例 #21
0
def stringsRearrangement(inputArray):
    for ia in p(inputArray):
        c = 0
        for i in range(len(ia) - 1):
            for j in range(len(ia[i])):
                if ia[i][j] != ia[i + 1][j]: c += 1
            if ia[i] == ia[i + 1]: c += 10
        if c == len(ia) - 1: return True
    return False
コード例 #22
0
def isPermutation(x, y):
    permX = p(x)
    for i in list(permX):
        ans = ''
        for j in range(len(i)):
            ans += i[j]
        if ans == y:
            return True
    return False
コード例 #23
0
    def compute_correlations(self):
        # convenient variables
        device = self.device
        self.num_sentences = len(next(iter(self.attentions_d.values())))
        self.num_words = sum(t.size()[-1]
                             for t in next(iter(self.attentions_d.values())))

        # Set `self.corrs` : {network: {other: [corr]}}
        # Set `self.pairs` : {network: {other: [pair]}}
        # pair is index of head in other network
        # Set `self.similarities` : {network: {other: sim}}
        self.corrs = {network: {} for network in self.attentions_d}
        self.pairs = {network: {} for network in self.attentions_d}
        self.similarities = {network: {} for network in self.attentions_d}
        for network, other_network in tqdm(p(self.attentions_d,
                                             self.attentions_d),
                                           desc='correlate',
                                           total=len(self.attentions_d)**2):
            if network == other_network:
                continue

            if other_network in self.corrs[network]:
                continue

            correlation = self.correlation_matrix(network, other_network)

            # Main update
            self.corrs[network][other_network] = correlation.max(axis=1)
            self.corrs[other_network][network] = correlation.max(axis=0)

            self.similarities[network][other_network] = self.corrs[network][
                other_network].mean()
            self.similarities[other_network][network] = self.corrs[
                other_network][network].mean()

            self.pairs[network][other_network] = correlation.argmax(axis=1)
            self.pairs[other_network][network] = correlation.argmax(axis=0)

        # Set `self.head_sort` : {network, sorted_list}
        # Set `self.head_notated_sort` : {network: [(head, {other: (corr, pair)})]}
        self.head_sort = {}
        self.head_notated_sort = {}
        for network in tqdm(self.attentions_d, desc='annotation'):
            self.head_sort[network] = sorted(
                range(self.num_heads_d[network]),
                key=lambda i: self.op(self.corrs[network][other][i]
                                      for other in self.corrs[network]),
                reverse=True,
            )
            self.head_notated_sort[network] = [(head, {
                other: (
                    self.corrs[network][other][head],
                    self.pairs[network][other][head],
                )
                for other in self.corrs[network]
            }) for head in self.head_sort[network]]
コード例 #24
0
def gen_pat(ones,zeros,length):
	#return a list of all possible sub patterns
	#with 1s as sub numbers and 0s as fixed num
	#takes 3 ints, Ones, Zeros, number length
	#make sure ones+zeros==lenght
	#zeros are the digits that will be replaced by the same number
	#while ones are the fixed digits
	a=[1]*ones+[0]*zeros
	comb= [i for i in p(a,length)]
	return comb
コード例 #25
0
def solution():
    u = set()
    for v in p('123456789'):
        v = ''.join(it for it in v)
        for i in range(1,9):
            for j in range(i+1,9):
                num1, num2, num3 = int(v[:i]), int(v[i:j]), int(v[j:])
                if num1*num2==num3:
                    u.add(num3)
    return sum(u)
コード例 #26
0
def op_manip(l: list = [2, 4, 5, 3, 2], target=7, ops: list = [add, mul, sub]):
    for c in p(ops, repeat=len(l) - 1):
        r = l[0]
        for i in range(len(c)):
            r = c[i](r, l[i + 1])
        if (r == target):
            print("********")
        print(r)
        if (r == target):
            print(*(op.__name__ for op in c))
            print("********")
コード例 #27
0
ファイル: 5kyu_A.py プロジェクト: swtwinsy/Code_Challenges
def slogan_maker(array):
    new_array = []
    for arr in array:
        if arr not in new_array:
            new_array.append(arr)
    # array = list(set(array))
    array = new_array
    if len(array) == 1:
        return array
    from itertools import permutations as p
    return [' '.join(item) for item in list(p(array))]
コード例 #28
0
def stringsRearrangement(inputArray):
    possible_permutation = p(inputArray)
    for permu in possible_permutation:
        all_match = True
        for j in range(len(permu) - 1):
            if not is_differ_by_one_char(permu[j], permu[j + 1]):
                all_match = False
                break
        if all_match:
            return True
    return False
コード例 #29
0
def run(limit):
	from itertools import permutations as p
	count = 0
	result = []
	seeds = [False for x in range(0, limit)]
	for n in range(0, limit):
		if not seeds[n]:
			chain = find_chain(n)
			if len(chain) == 60:
				perms = [int(''.join(x)) for x in p(str(n))]
				result.extend([x for x in perms if len(str(x)) == len(str(n))])
			for x in chain:
				if x < limit:
					if not seeds[x]:
						perms = [int(''.join(x)) for x in p(str(x))]
						for y in perms:
							if y < limit:
								seeds[y] = True
			count += 1
	return set(result)
コード例 #30
0
def main():
    f = lambda tp: reduce(add, (str(x) for x in tp))
    pandigts = [f(x) for x in list(p(range(10), 10))][362880:]
    myint = lambda x: int(x) if x[0] != '0' else int(x[1:])
    res = 0
    denominator = array([2, 3, 5, 7, 11, 13, 17])
    for pd in pandigts:
        nominator = array([myint(pd[x:x + 3]) for x in range(1, 8)])
        if all(nominator % denominator == 0):
            res += int(pd)
    return res
コード例 #31
0
def stringsRearrangement(input):
    for s in p(input):
        c = 0
        for i in range(len(s) - 1):
            for j in range(len(s[i])):
                if s[i][j] != s[i + 1][j]:
                    c += 1
            if s[i] == s[i + 1]:
                c += 10
        if c == len(s) - 1:
            return True
    return False
コード例 #32
0
def main():
    # YOUR CODE GOES HERE
    # Please take input and print output to standard input/output (stdin/stdout)
    # E.g. 'input()/raw_input()' for input & 'print' for output
    s, k = input().split()
    l = list()
    for i in p(s, int(k)):
        l.append(''.join(i))
    l.sort()
    for i in l:
        print(i)
    return 0
コード例 #33
0
def f(b, c):
    a = 0
    for k in p(b):
        d = c
        r = 0
        for i in range(m):
            if k[i] <= d:
                d -= k[i]
                r += k[i]**2
            else:
                break
        a = max(a, r)
    return a
コード例 #34
0
def crosswordFormation(words):
    from itertools import permutations as p
    c = 0
    for l in p(words):
        for d1 in range(len(l[0])-2):
            s1 = [i for i,j in enumerate(l[1]) if j == l[0][d1]]
            for d2 in range(d1+2, len(l[0])):
                s2 = [i for i,j in enumerate(l[2]) if j == l[0][d2]]
                for cw1 in s1:
                    for cw2 in s2:
                        for c1, c2 in zip(l[1][cw1+2:],l[2][cw2+2:]):
                            for c3, c4 in zip(l[3],l[3][d2-d1:]):
                                c += c1 == c3 and c2 == c4
    return c
コード例 #35
0
ファイル: 92.py プロジェクト: jhalley/my-project-euler
def figure_end(x):
    global MEMOIZED
    global END_NUM

    if x in [1, 89]:
        return x
    elif x in MEMOIZED:
        return MEMOIZED[x]
    else:
        final_num = figure_end(sum([int(i)**2 for i in str(x)]))
        for k in set([int(''.join(j)) for j in p([i for i in str(x)])]):
            MEMOIZED[k] = final_num

        return final_num
コード例 #36
0
 def readBinaryWatch(self, num):
     """
     :type num: int
     :rtype: List[str]
     """
     if num < 0 or num > 10:
         return []
     base_vector = ['1'] * num + ['0'] * (10 - num
                                          )  # as chars so I can join later
     time_strs = [
         time_str(v) for v in set(p(base_vector))
     ]  # set of permutations gives all binary vectors (lists of digits) of length 10 (4+6) with <num> 1 digits without repetition, function converts each to string in required format
     return [t for t in time_strs
             if t != None]  # filter out strings with too many hours/monutes
def stringsRearrangement(inputArray):
    p_list = list(p(inputArray))
    for i in range(len(p_list)):
        count1 = 0
        for j in range(len(p_list[0]) - 1):
            count2 = 0
            for k in range(len(p_list[0][0])):
                if p_list[i][j][k] != p_list[i][j + 1][k]:
                    count2 += 1
            if count2 == 1:
                count1 += 1
        if count1 >= (len(p_list[0])) - 1:
            return True
    return False
コード例 #38
0
def longest_common_substring(s):
    def r(k):
        s[k] = s[k][1:] + s[k][:1]

    l = 0
    k = [0]*len(s)
    for d in p(*map(lambda x: range(len(x)), s)):
        v = len(c(s))
        if v > l:
            l = v
        for i, n in enumerate(d):
            if n != k[i]:
                r(i)
                k[i] = n
        
    return l
コード例 #39
0
ファイル: oneline.py プロジェクト: huaqiangwang/PPotW
#!/usr/bin/env python3

from json import load
from itertools import permutations as p

print('\n'.join('{} is {}'.format(n, 'Valid' if any(not int(''.join(i)) % 8 for i in p(n, 3)) else 'Invalid') for n in load(open('data.json', 'r'))))
コード例 #40
0
ファイル: euler24.py プロジェクト: Pygmalion6636/riddles
'''

http://projecteuler.net/problem=24

What is the millionth lexicographic permutation of the digits 0, 1, 2, 3, 4, 5, 6, 7, 8 and 9?

'''

from itertools import permutations as p

count = 0

for i in p("0123456789"):
	if count == 999999:
		print ''.join(i)
		break
	count += 1
コード例 #41
0
ファイル: euler-0049.py プロジェクト: nasa9084/project-euler
# -*- coding:utf-8 -*-
"""Project Euler problem 49"""

from itertools import permutations as p
from euler import get_plist


primes = set(get_plist(10000))
for i in range(1000, 10000):
    if i==1487: continue
    fst = i
    snd = fst + 3330
    thd = snd + 3330
    if not fst in primes or not snd in primes or not thd in primes:
        continue
    pat = set(["".join(ls) for ls in p(str(fst))])
    if str(snd) in pat and str(thd) in pat:
        break
print("Answer: " + str(fst) + str(snd) + str(thd))
コード例 #42
0
ファイル: permutation.py プロジェクト: JoahG/projecteuler
def per(n):
	return sorted(set([int("".join(list(i))) for i in list(p([i for i in str(n)]))]))
コード例 #43
0
def solution():
    return ''.join(str(s) for s in list(p([it for it in range(10)]))[999999])
コード例 #44
0
#!/usr/bin/env pypy3
from itertools import permutations as p

print([i for i in p(set(range(10)) - {1}, 8) if all([i[j] != 0 for j in range(0, 7, 2)]) and (i[0] * 10 + i[1])-(i[2] * 10 + i[3]) == i[4] * 10 + i[5] and (i[4] * 10 + i[5]) + (i[6] * 10 + i[7]) == 111])
コード例 #45
0
def anagram(s):
     from itertools import permutations as p
     return [''.join(x) for x in p(s)]
コード例 #46
0
ファイル: p85.py プロジェクト: jokkebk/euler
from itertools import product as p
print(min((abs(a*(a+1)*b*(b+1)//4-2e6),a*b) for a,b in p(range(80),range(80))))
コード例 #47
0
from itertools import permutations as p
def gcd(a,b):
    if not b: return a
    return gcd(b,a%b)
while True:
    try:
        n=input("")
        print reduce(gcd,[int(''.join(x)) for x in p(str(n))])
    except EOFError:
        break
コード例 #48
0
X=[50,48,46,44,42,40,38,36,34,32,30,31,33,35,37,39,41,43,45,47,49]

print "length of shortest pipe is", int(d(X)*1000)

print "process time is", time() - st

exit()


#
#  test code to find pattern
#
X=[50,49,48,47,46,45]

Z = p(X)

mind = 10000000
minz = ""

for z in Z:
  drod = d(z) 
  print drod ,z
  if drod < mind:
    mind = drod
    minz = z

print
print "min",mind, minz

コード例 #49
0
ファイル: endof.py プロジェクト: a1ip/checkio-21
def checkio(words_set):
    pairs = [x for x in p(words_set, 2) if bool(set(x[0]) & set(x[1]))]
    return bool([x for x, y in pairs if x.endswith(y)])
コード例 #50
0
ファイル: chess.py プロジェクト: a1ip/my_check
from itertools import permutations as p
# possible Knight moves
moves = [(x,y) for x,y in p([-2,-1,1,2], 2)
         if abs(x) != abs(y)]

# helper function "b1" -> (2,1)
conv = lambda pos: (ord(pos[0])-96, int(pos[1]))

# allowed coordinates {(1,1), ..., (8,8)}
CHECKBOARD = {(x,y) for x in range(1,9)
              for y in range(1,9)}

def checkio(check,              #starting input e.g. "b1-d5"
            start: set = None,   
            end: set = None,
            count = 0):         # Knight moves counter 
    if check:                   # Only first call, then not used
        start = {conv(check[:2])} # conversion to coordinates tuple
        end = {conv(check[-2:])}
    elif start & end:           # solution is found and returned
        return count            # N.B.: if "b1-b1" 0 moves is returned
    count += 1
    pos = set() #helper set
    for x_s, y_s in start:
        for x_m, y_m in moves:
            pos |= {(x_s+x_m,
                   y_s+y_m)}
    start |= pos & CHECKBOARD  # only coord of checkboard are added        
    return checkio(False,      # No need anymore
                   end,        # !!! end is switched for start !!!
                   start,      # a vice versa
コード例 #51
0
ファイル: q24.py プロジェクト: mwcz/euler
#!/usr/bin/python

# Problem 24

# A permutation is an ordered arrangement of objects. For example, 3124 is 
# one possible permutation of the digits 1, 2, 3 and 4. If all of the 
# permutations are listed numerically or alphabetically, we call it 
# lexicographic order. The lexicographic permutations of 0, 1 and 2 are:
# 
#     012   021   102   120   201   210
# 
# What is the millionth lexicographic permutation of the digits 0, 1, 2, 3, 
# 4, 5, 6, 7, 8 and 9?

from itertools import permutations as p

perms = p( range(10) )

i = 1
for perm in perms:
    #print( perm )
    if i == 1000000: 
        answer = ""
        for d in perm:
            answer += str(d)
        print( answer )
        break
    i += 1
コード例 #52
0
ファイル: euler24.py プロジェクト: dwij28/Project-Euler
from itertools import permutations as p
x = "0123456789"
print "".join(list(p(x))[999999])
コード例 #53
0
ファイル: permutation.py プロジェクト: elzup/shortcodes
from itertools import permutations as p
permutation = lambda n, v: list(p(v))[n - 1]

print(permutation(1, [1, 2, 3]))
print(permutation(4, [1, 2, 3]))
コード例 #54
0
ファイル: problem4.py プロジェクト: hyzhangsf/projecteuler
# https://projecteuler.net/problem=4
# Largest palindrome product
from itertools import product as p
isPalindrome = lambda n: str(n) == str(n)[::-1]
print max( filter(isPalindrome,  map(lambda (x,y):x*y, p(range(100, 999), range(100, 999)))) )



コード例 #55
0
ファイル: insert.py プロジェクト: Njallzzz/Python
def insert_operators(e, t):
    for d in p(['+', '-', ''], repeat=len(e)-1):
        k = ''.join( str(v) for v in list(c.from_iterable(zip(e, d))) + [e[-1]] )
        if eval(k) == t:
            return k + "=" + str(t)
コード例 #56
0
ospd = open("newDict.txt").read().split("\n") #taken from https://raw.githubusercontent.com/xjtian/PyScrabble/master/wordlists/OSPD4_stripped.txt
nospd = []
for word in ospd:
    nospd.append(word.strip())
print(len(ospd))
from itertools import permutations as p
from string import ascii_uppercase as a_u
diphths = ["".join(i) for i in p(list(a_u), 2)]
for i in a_u:
    diphths.append(i*2)
for i in diphths:
    with open(i+".txt", "w"):
        pass
    dfile = open(i+".txt", "w")
    for word in nospd:
        #print(word[:2])
        if word[:2] == i:
            pass
            dfile.write(word)
            dfile.write("\n")
    dfile.close()




コード例 #57
0
ファイル: euler-0052.py プロジェクト: nasa9084/project-euler
# -*- coding:utf-8 -*-
"""Project Euler problem 52"""
from itertools import permutations as p

for i in range(1, 10**6):
    pat = [int("".join(s)) for s in p(str(i))]
    for j in range(2, 7):
        if not i*j in pat: break
    else:
        print("Answer: " + str(i))
        quit()
コード例 #58
0
def main():
	#generate patterns with 3 zeros 2 ones and
	#patterns with 2 zeros and 3 ones for a
	#5 digit number
	#test case 1:
	# 2 digit numbers, seq len of 6 >> passed
	##test case 2:
	#5 digit numbers, seq len of 7
	#passed
	target=8
	nzeros=1
	digits=6
	suffix=[1,3,7,9]
	##write=0
	los=[]
	while nzeros<digits-1:
		nones=digits-nzeros
		print 'ones:',nones,'zeros:',nzeros
		#set number of zeros
		
		#generate the respective patterns
		#as a list of tuples
		patterns=gen_pat(nones,nzeros,digits)
		
		#remove redundancies
		#patterns=sorted(list(set(patterns)))
		patterns=set(patterns)
		#patterns=list(patterns)
		#print patterns
		#print len(patterns)
		
		#print 'generated patterns',patterns
		#print 'starting iteration over patterns...'
		
		#iterate over the patterns
		for pat in patterns:
			pat=list(pat)
			
			#print 'current pattern',pat
			
			pat_woz=pat[:]	#type:list
			#iterate over all possible ones
			#print 'iterating over fixed digits..'
			
			#if pat==[0,1,0,1,1,1]: print 'current pat: [0,1,0,1,1,1]'
			
			#for one in sorted(list(set(p(range(1,10),nones)))):
			for one in set(p(range(1,10)*2,nones)):
				#0 is excluded for 2 digit numbers
				seq=[]
				#make a list for the found primes
				loo=list(one)	#type: list
				#print loo
				##if loo==[2,3,1,3]:
					##write=1
				##else:
					##write=0
				
				##if write: print 'fixed digits are',loo
				
				#list of ones
				#fill the pattern with ones
				pat=fill_ones(pat_woz,loo)
				
				##if write: print 'filled with ones',pat,'pat2',pat_woz
				
				#break if pat ends with non suffix digits
				if pat[-1] in [2,4,5,6,8]:
					##if write: print 'pat ends with non prime digits, skipping..'
					continue
				
				pat_wz=pat[:]	#type:list
				
				#iterate over the zeros
				#print 'iterating over zeros...'
				for zero in xrange(10):
					
					##if write: print 'current zero',zero
					
					pat=fill_zeros(pat_wz,zero)	#type:list
					
					##if write: print 'filled with zeros',pat
					
					#break if pat ends in non suffix digits
					if pat[-1] not in suffix:
						#print 'pat ends with non prime digits, skipping..'
						continue
					
					#calculate the number
					num=calc_num(pat)	#type:list
					
					if num<10**(digits-1): continue
					
					##if write: print 'calculated number is',num
					
					#add to seq list if it's a prime
					if prime[num]:
						seq.append(num)
						
						##if write: print 'current seq:',seq
						
				#print 'seq=',seq
				#if seq length == target, stop and return the
				#smallest number, sequence and sequence length
				#print '%-'*40
				if len(seq)==target:
					los.append(seq)
		nzeros+=1
	return los
コード例 #59
0
from itertools import permutations as p
for i in p(raw_input()):print''.join(i)