Пример #1
0
    def encrypt(self):
        encrypted = ''
        key = ''.join(self.key.split()).upper()
        for index, char in enumerate(self.plain):
            encrypted += ascii_uppercase[(ascii_uppercase.index(char) + ascii_uppercase.index(key[index])) % 26]

        return encrypted
Пример #2
0
    def __encode_rotor_chain(self, char, right_to_left):
        """
        Encode a character though the whole rotor chain in a specific direction taking into account physical properties
        like to rotors positions and the ring settings

        :param char: The character to encode
        :type char: str
        :param right_to_left: True if the encoding must be performed from right to left, False otherwise
        :type right_to_left: bool
        :return: The encoded character
        :rtype: str
        :raises: :class:`TypeError, ValueError`: If the provided character is invalid
        """
        self._alpha_character_validator.validate(char)

        current_char, prev_rotor_position = char.upper(), 0

        for rotor in reversed(
                self.__rotors) if right_to_left else self.__rotors:
            current_char = ascii_uppercase[
                (ascii_uppercase.index(current_char) + rotor.position -
                 rotor.ring_setting + 1 - prev_rotor_position) %
                len(ascii_uppercase)]
            if right_to_left:
                current_char = rotor.encode_right_to_left(current_char)
            else:
                current_char = rotor.encode_left_to_right(current_char)
            prev_rotor_position = rotor.position - rotor.ring_setting + 1

        current_char = ascii_uppercase[(ascii_uppercase.index(current_char) -
                                        prev_rotor_position) %
                                       len(ascii_uppercase)]

        return current_char
Пример #3
0
 def kill_ship(self, ship):
     ship = ship.upper()
     if self.field[((ascii_uppercase.index(ship[0]) * self.size) + int(ship[1]) - 1)] == 0:
         self.field[((ascii_uppercase.index(ship[0]) * self.size) + int(ship[1]) - 1)] = '_'
         return True
     else:
         return False
Пример #4
0
def multibuy(items, items_on_offer):
    """Check if items in the particular order fulfil multibuy requirements to sub in an offer price
    for "buy any x items" offers.
    """
    offers = 0
    offer_items = []

    # pick interested items
    for i in range(len(items_on_offer)):
        j = asc_up.index(items_on_offer[i])
        for k in range(items[j]):
            offer_items.append((items_on_offer[i], prices[items_on_offer[i]]))

    # sort items by price

    offer_items = sorted(offer_items, key=itemgetter(1), reverse=True)

    # remove 3 highest, add to offers
    while len(offer_items) >= 3:
        offers += 45
        del offer_items[:3]

    # reassign values of relevant items

    counts = Counter(item[0] for item in offer_items)
    for item in items_on_offer:
        index = asc_up.index(item)
        items[index] = counts[
            item]  # where all items of a type are in the offer this gives 0, else 1 or 2

    return items, offers
Пример #5
0
def adjacent_hexes(hex_id):
    col, row = au.index(hex_id[0]), int(hex_id[1])
    t_row = row + col % 2 - 1
    b_row = row + col % 2

    adj_hexes = set()

    if row - 1 > 0:
        adj_hexes.add((col, row - 1))

    if row + 1 < 10:
        adj_hexes.add((col, row + 1))

    if col + 1 <= au.index(MAX_COL):
        if t_row > 0:
            adj_hexes.add((col + 1, t_row))
        if b_row < 10:
            adj_hexes.add((col + 1, b_row))

    if col - 1 >= 0:
        if t_row > 0:
            adj_hexes.add((col - 1, t_row))
        if b_row < 10:
            adj_hexes.add((col - 1, b_row))

    return set(map(lambda a: au[a[0]] + str(a[1]), adj_hexes))
Пример #6
0
def get_words(game):
    game = [i for i in game.split("#p")[0].split("\n")[1:-1]
        if i.startswith(">")][:-1]
    words = [(i.split()[2], i.split()[3]) for i in game]

    board = [['' for i in range(16)] for i in range(16)]
    nw = []
    for (pos, word) in words:
        if pos[0] in ascii_uppercase:
            row = ascii_uppercase.index(pos[0])
            col = int(pos[1:])
            d = 'A'
        else:
            col = int(pos[:-1])
            row = ascii_uppercase.index(pos[-1])
            d = 'D'
        n = ''
        for l in word:
            if l == '.':
                n += board[row][col]
            else:
                n += l
                board[row][col] = l
            if d == 'D':
                row += 1
            else:
                col += 1
        nw.append(n)
    return nw
Пример #7
0
    def decodeGrundStellung(self):
        #find out the starting grund stellung if we know the other parts
        enigmai = Enigma(
            rotors={
                1: Rotor("VIII", 19 - 1, pomlist.index(
                    self.grundStellung[0])),  #slowest, left-most
                2: Rotor("II", 7 - 1,
                         pomlist.index(self.grundStellung[1])),  #middle
                3: Rotor("IV", 12 - 1, pomlist.index(
                    self.grundStellung[2])),  #fastest, right-most
            },
            reflector=Reflector("B"),
            plugboard=Plugboard({
                "B": "D",
                "C": "O",
                "E": "I",
                "G": "L",
                "J": "S",
                "K": "T",
                "N": "V",
                "P": "M",
                "Q": "R",
                "W": "Z"
            }))
        text = enigmai.EDcrypt(self.grundStellung[3:])

        return text
Пример #8
0
def play_pass(s, n):
    """
    shift each letter by a given number but the transformed letter must be a letter (circular shift),
replace each digit by its complement to 9,
keep such as non alphabetic and non digit characters,
downcase each letter in odd position, upcase each letter in even position (the first character is in position 0),
reverse the whole result.

    """
    from string import ascii_lowercase, ascii_uppercase, punctuation, whitespace
    news = ''
    llower = ascii_lowercase * 2
    uuper = ascii_uppercase * 2
    for idx, ch in enumerate(s):
        if ch in punctuation + whitespace:
            news += ch
        if ch in ascii_lowercase:
            news += llower[ascii_lowercase.index(ch) +
                           n] if idx % 2 else llower[ascii_lowercase.index(ch)
                                                     + n].upper()
        if ch in ascii_uppercase:
            news += uuper[ascii_uppercase.index(ch) +
                          n] if idx % 2 == 0 else uuper[
                              ascii_uppercase.index(ch) + n].lower()
        if ch in '0123456789':
            news += str(9 - int(ch))

    return news[::-1]
Пример #9
0
def parse_sgf_move(move_str: str) -> Optional[Tuple[int, int]]:
    """Returns either None or (x, y) coordinates of board."""
    if not (move_str == '' or _SGF_MOVE_REGEX.match(move_str)):
        raise SgfContentError

    if move_str == '' or move_str == 'tt':
        return None

    e = SgfContentError("Invalid move string %s" % move_str)

    if len(move_str) != 2:
        raise e

    try:
        # GameState expects (x, y) where x is column and y is row
        col = ascii_uppercase.index(move_str[0].upper())
        row = ascii_uppercase.index(move_str[1].upper())

        if (0 <= col < 19) and (0 <= row < 19):
            return col, row

        raise e

    except ValueError:
        raise e
def encrypt(text, key):

    if not isinstance(text, str) or not isinstance(key, str):
        raise TypeError
    if key == '' or bool(re.match(r".*[^a-zA-Z].*", key)):
        raise ValueError
    res = ''
    key = key.lower()
    t_index = 0
    key_len = len(key)
    for i in text:
        if i == ' ':
            res += i
            continue
        if i in ascii_uppercase:
            res += ascii_uppercase[(ascii_uppercase.index(i) +
                                    ascii_uppercase.index(key[t_index])) % 26]
            t_index = (t_index + 1) % key_len
            continue
        if i in ascii_lowercase:
            res += ascii_lowercase[(ascii_lowercase.index(i) +
                                    ascii_lowercase.index(key[t_index])) % 26]
            t_index = (t_index + 1) % key_len
            continue
    return res
 def SaoViz(self, u='', v=''):
     i = ascii_uppercase.index(u)
     j = ascii_uppercase.index(v)
     if not self.__orientado:
         return self.__matriz[i][j] == 1 and self.__matriz[i][j] == 1
     else:
         return self.__matriz[i][j] == 1
Пример #12
0
 def test(self):
     #print (self.grundStellung)
     grunds = self.decodeGrundStellung()
     enigmai = Enigma(
         rotors={
             1: Rotor("VIII", 19 - 1,
                      pomlist.index(grunds[0])),  #slowest, left-most
             2: Rotor("II", 7 - 1, pomlist.index(grunds[1])),  #middle
             3: Rotor("IV", 12 - 1,
                      pomlist.index(grunds[2])),  #fastest, right-most
         },
         reflector=Reflector("B"),
         plugboard=Plugboard({
             "B": "D",
             "C": "O",
             "E": "I",
             "G": "L",
             "J": "S",
             "K": "T",
             "N": "V",
             "P": "M",
             "Q": "R",
             "W": "Z"
         }))
     text = enigmai.EDcrypt(self.ttc)
     print("DECRYPTED TEXT: " + text)
     print("STECKERS: %s" % enigmai.plugboard.wiring)
Пример #13
0
def vigenere_e(plaintext, key):
    plaintext = plaintext.upper()
    key = mapped_key(plaintext, key.upper())
    ciphertext = [
        alph[(alph.index(a) + alph.index(b)) % 26] if a in alph else a
        for a, b in zip(plaintext, key)
    ]
    return "".join(ciphertext)
 def AdicionarAresta(self, u='', v=''):
     self.__vazio = False
     i = ascii_uppercase.index(u)
     j = ascii_uppercase.index(v)
     self.__matriz[i][j] = 1
     if not self.__orientado:
         self.__matriz[j][i] = 1
     return self.__matriz
 def RemoverAresta(self, u='', v=''):
     i = ascii_uppercase.index(u)
     j = ascii_uppercase.index(v)
     self.__matriz[i][j] = 0
     if not self.__orientado:
         self.__matriz[j][i] = 0
         return [(u, v), (v, u)]
     return [(u, v)]
Пример #16
0
def vigenere_d(ciphertext, key):
    ciphertext = ciphertext.upper()
    key = mapped_key(ciphertext, key.upper())
    plaintext = [
        alph[(alph.index(a) - alph.index(b)) % 26] if a in alph else a
        for a, b in zip(ciphertext, key)
    ]
    return "".join(plaintext)
Пример #17
0
def decrypt_vigenere(ciphertext_string, key):
    decrypted_plaintext = {}
    decrypted_text_string = ''
    for letter_index, letter in enumerate(ciphertext_string):
        decrypted_text_string += ascii_uppercase[(ascii_uppercase.index(letter) - ascii_uppercase.index(key[letter_index % len(key)])) % 26]

    decrypted_plaintext = get_letter_count_of_text(decrypted_text_string)

    return decrypted_plaintext
Пример #18
0
 def convertMessage(self, message):
     cipherResponse = ''        
     for letter in message.upper():
         if letter not in uppercaseAlphabet:
             cipherResponse += letter      
         else:
             letter = self.applySwap(letter) #Plugboard Swap
             self.leftRotor.step()      # Left Rotor
             leftRotorOutput = self.leftRotor.encodeDecode(uppercaseAlphabet.index(letter))
             reflectorOutput = self.REFLECTOR[uppercaseAlphabet[leftRotorOutput % Enigma.alphaLength]]                
             convertedLetter = uppercaseAlphabet[self.rightRotor.encodeDecode(uppercaseAlphabet.index(reflectorOutput), forward = False)]
             convertedLetter = self.applySwap(convertedLetter)   #Plugboard Swap
             cipherResponse += convertedLetter
     return cipherResponse
Пример #19
0
def transform(text, key, sign):

    text_nums = [ascii_uppercase.index(c) for c in text]
    key_nums = [ascii_uppercase.index(c) for c in key]

    i = 0
    n_k = len(key_nums)
    n_c = len(ascii_uppercase)
    answer = []
    for n in text_nums:
        n = (n + sign * key_nums[i]) % n_c
        answer.append(ascii_uppercase[n])
        i = (i + 1) % n_k
    return "".join(answer)
Пример #20
0
def caeser(sourcetext, offset=None, reverse=False):
    # caeser(string) -> string
    # offset - integer value for cipher offset
    # reverse - bool to reverse the offset (useful for decryption)
    # Apply an offset to ascii characters.
    
    # Trivial case, return sourcetext unchanged and avoid
    # translating character by character.
    if offset == None:
        return sourcetext
    # reverse flag undoes the cipher offset. This is the same
    # as making the offset negative. Conditional merely changes
    # the sign of offset. The same effect can be achieved by
    # manually adjusting the sign of offset in the caller.
    if reverse:
        offset = -offset
    
    # build enciphered string character by character
    # For each character, if it is an ascii letter apply
    # the offset and append the new character to the cipher. 
    # Otherwise, simply append nonletters to the cipher.
    cipher = []
    for char in sourcetext:
        if char in ascii_letters:
            if char in ascii_lowercase:
                i = ascii_lowercase.index(char) + offset
                i = modulate_index(ascii_lowercase, i)
                cipher.append(ascii_lowercase[i])
            else:
                i = ascii_uppercase.index(char) + offset
                i = modulate_index(ascii_uppercase, i)
                cipher.append(ascii_uppercase[i])
        else: cipher.append(char)
    ciphertext = ''.join(cipher)
    return ciphertext
Пример #21
0
 def get_name_value(name):
     """
     get value of a name
     """
     value = sum([ascii_uppercase.index(letter) + 1
         for letter in name])
     return value
Пример #22
0
def decrypt_ciphertext_by_shift(ciphertext_string, key: int):
    decrypted_ciphertext_string = ''
    for letter in ciphertext_string:
        decrypted_ciphertext_string += ascii_uppercase[(ascii_uppercase.index(letter) + key) % 26]
    decrypted_ciphertext = get_letter_count_of_text(decrypted_ciphertext_string)

    return decrypted_ciphertext
Пример #23
0
	def columnIndex(column):
		try:
			column = int(column) - 1
		except:
			column = ascii_uppercase.index(column)

		return column
Пример #24
0
 def set_position(self, letter_position: str) -> None:
     """Turn the rotor to a given position."""
     numeric_position = alphabet.index(letter_position) + 1
     offset = numeric_position - self.ring_setting
     if offset < 0:
         offset += len(self.wiring)
     self.rotation = offset
Пример #25
0
def transform(letter):
    if letter in key_lower:
        return key_lower[ascii_lowercase.index(letter)]
    elif letter in key_upper:
        return key_upper[ascii_uppercase.index(letter)]
    else:
        return letter
 def column_index(col):
     ''' static method that returns the zero-based column index '''
     try:
         col = int(col) - 1
     except:
         col = ascii_uppercase.index(col)
     return col
Пример #27
0
 def get_next_well(self, previous_coordinates):
     row = ascii_uppercase.index(previous_coordinates[0])
     col = int(previous_coordinates[1:])
     if self.placement == 'column':
         # Select next well by column (going down the plate)
         if (row != 0 and (row + self.spacing) % self.layout[1]
                 == 0) or row > self.layout[1]:
             next_row = ascii_uppercase[0]
             next_col = col + self.spacing
         else:
             next_row = ascii_uppercase[row + self.spacing]
             next_col = int(previous_coordinates[1:])
     else:
         # Select next well by row (across the plate)
         if col % self.divisor == 0 or col > self.divisor:
             next_row = ascii_uppercase[row + self.spacing]
             next_col = self.spacing
         else:
             next_row = previous_coordinates[0]
             next_col = col + self.spacing
     lookup = (next_row, next_col)
     try:
         well = self.wells[lookup]
     except KeyError as e:
         raise Exception('Location chosen is out of range')
     return well, '{}{}'.format(next_row, next_col)
def moving_shift(string, shift):
    words = string
    lens = len(words)
    m, n = divmod(lens, 5)
    if n > 0:
        m += 1
    res = ['', '', '', '', '']
    chars = -1

    for idx, char in enumerate(words):
        chars += 1
        change = None
        if char in ascii_lowercase + ascii_uppercase:
            if char in ascii_lowercase:
                pos = ascii_lowercase.index(char)
                np = (pos + shift + chars) % 26
                change = ascii_lowercase[np]
            elif char in ascii_uppercase:
                pos = ascii_uppercase.index(char)
                np = (pos + shift + chars) % 26
                change = ascii_uppercase[np]
        else:
            change = char
        res[chars // m] += change
    return res
def moving_shift(string, shift):
    words = string
    lens = len(words)
    m, n = divmod(lens, 5)
    if n > 0:
        m +=1
    res = ['', '', '', '' ,'']
    chars = -1

    for idx, char in enumerate(words):
        chars += 1
        change=None
        if char in ascii_lowercase + ascii_uppercase:
            if char in ascii_lowercase:
                pos = ascii_lowercase.index(char)
                np = (pos + shift + chars) % 26
                change = ascii_lowercase[np]
            elif char in ascii_uppercase:
                pos = ascii_uppercase.index(char)
                np = (pos + shift + chars) % 26
                change = ascii_uppercase[np]
        else:
            change = char
        res[chars//m] += change
    return res
Пример #30
0
def main():

    n = 1
    optlist, args = getopt.getopt(sys.argv[1:], "n:")
    for opt, val in optlist:
        if opt in ['-n']:
            n = int(val)

    for infile_name in args:
        with open(infile_name, "r") as infile:

            text = get_text(infile)
            print("%s\n" % (''.join(text)))

            split_text = [[] for i in range(n)]

            for i, c in enumerate(text):
                split_text[i % n].append(c)

            for i, l in enumerate(split_text):
                print("Position %d:" % (i))
                print("  %s" % ("".join(l)))
                dist = get_ngram_freqs(l, 1)
                dist_l = [(dist[c], c) for c in dist]
                dist_l.sort(reverse=True)
                for ndx in range(min(5, len(dist))):
                    c = dist_l[ndx][1]
                    n_c = dist_l[ndx][0]
                    i_c = ascii_uppercase.index(c)
                    i_e = (i_c - 5) % len(ascii_uppercase)
                    print(" %s: %d %s" % (c, n_c, ascii_uppercase[i_e]))
Пример #31
0
    def __init__(self,
                 left_rotor,
                 middle_rotor,
                 right_rotor,
                 reflector,
                 menu_link='ZZZ',
                 conx_in={},
                 conx_out={}):
        """rotors must be strings referring to either ['I','II','III','IV','V']
        reflector must be string, one of either ['B','C']"""

        self.right_rotor = right_rotor
        self.middle_rotor = middle_rotor
        self.left_rotor = left_rotor
        self.reflector = reflectors[reflector]
        self.menu_link = menu_link
        self.middle_notch = entry.index(
            notches[self.middle_rotor]
        )  ## point if right rotor reaches will trigger middle rotor to step
        self.left_notch = entry.index(
            notches[self.left_rotor]
        )  ## point if middle rotor reaches will trigger left rotor to step
        self.current_position = menu_link
        self.pos_left_rotor, self.pos_mid_rotor, self.pos_rgt_rotor = (
            ascii_uppercase.index(m) for m in menu_link.upper())
        self.status = {}
        self.status['in'] = {char: 0 for char in entry}
        self.status['out'] = {char: 0 for char in entry}
        self.conxns = {'in': conx_in, 'out': conx_out}
Пример #32
0
def solution(name):
    name_len = len(name)
    queue = [(name_len - cntName("A" * name_len, name), 0, 0, "A" * name_len)]
    heapq.heapify(queue)

    while True:
        weight, cnt, idx, temp = heapq.heappop(queue)
        print(temp, weight, idx)
        print("".join([(name[i]) if i == idx else " "
                       for i in range(name_len)]))

        if temp == name: return cnt

        heapq.heappush(queue,
                       (weight + 1, cnt + 1, (idx + 1) % name_len, temp))
        heapq.heappush(queue,
                       (weight + 1, cnt + 1, (idx - 1) % name_len, temp))

        ntemp = temp[:idx] + name[idx] + temp[idx + 1:]

        if temp == ntemp:
            continue

        j_cnt = min(ascii_uppercase.index(name[idx]),
                    ascii_uppercase[::-1].index(name[idx]) + 1)

        if j_cnt:
            heapq.heappush(
                queue,
                (weight - cntName(name, ntemp), cnt + j_cnt, idx, ntemp))

        sleep(0.5)
Пример #33
0
def part_2(steps):

    workers = [Worker(i) for i in range(5)]

    def get_free_worker():
        for worker in workers:
            if worker.is_ready():
                return worker

    ans = ''
    time = 0
    while not all([i[1].finished for i in steps]):
        # Loop through the steps and assign a worker to it if the step
        # is ready to be worked on, and the worker is available
        for step in steps:
            worker = get_free_worker()
            if worker is not None and step[1].is_ready():
                if step[1].is_ready() and not step[1].finished:
                    # print(f'Worker {worker.name}: Started {step[0]} at {time} ')
                    worker.start_work(step[0])
                    step[1].is_being_worked_on = True
                    continue

        for w in workers:
            completed = w.working()
            if completed:
                # print(f'Worker {w.name}: Completed {completed} at {time}')
                ans += completed
                idx = UP.index(completed)
                steps[idx][1].finished = True
                steps[idx][1].is_being_worked_on = False

        time += 1
    print(f'Time taken: {time}')
Пример #34
0
    def __init__(self,
                 left_rotor: str,
                 middle_rotor: str,
                 right_rotor: str,
                 reflector: str,
                 menu_link: str = 'ZZZ'):
        """rotors must be strings referring to either ['I','II','III','IV','V']
        reflector must be string, one of either ['B','C']"""
        assert all([
            r in raw_rotors.keys()
            for r in (left_rotor, middle_rotor, right_rotor)
        ])
        assert reflector in reflectors.keys()

        self.right_rotor = right_rotor
        self.middle_rotor = middle_rotor
        self.left_rotor = left_rotor
        self.reflector = reflectors[reflector]
        self.menu_link = menu_link
        self.middle_notch = entry.index(
            notches[self.middle_rotor]
        )  ## point if right rotor reaches will trigger middle rotor to step
        self.left_notch = entry.index(
            notches[self.left_rotor]
        )  ## point if middle rotor reaches will trigger left rotor to step
        self.pos_left_rotor, self.pos_mid_rotor, self.pos_rgt_rotor = (
            ascii_uppercase.index(m) for m in menu_link.upper())
        self.in_status = {char: 0 for char in entry}
        self.out_status = {char: 0 for char in entry}
        self.current_position = menu_link
        self.record = {}
Пример #35
0
    def enigmatise(self, tocode, startset='AAA'):
        encoded = ''

        tocode = self.only_ascii(tocode)

        self.pos_left_rotor, self.pos_mid_rotor, self.pos_rgt_rotor = (
            ascii_uppercase.index(s) for s in startset.upper())

        for i, c in enumerate(tocode):
            #             print('in:    ', c)
            self.step_enigma()

            #             print('rp = ', self.pos_rgt_rotor, 'mp = ', self.pos_mid_rotor, 'lp = ', self.pos_left_rotor)

            out = self.full_scramble(c)
            #             print('out:   ', out,'\n')

            encoded += out
            self.translate_current_position()
            self.record[i] = {
                'in': c,
                'out': out,
                'current_pos': self.current_position
            }

        return encoded
Пример #36
0
def alpha_to_int(alpha):
    try:
        return ascii_uppercase.index(alpha.upper())+1
    except ValueError:
        if alpha == ' ':
            return 0
        else:
            raise WrongCharError
Пример #37
0
def make_diamond(letter):
    lines = []
    length = ascii_uppercase.index(letter) + 1
    for l in range(length):
        line = [' '] * length
        line[l] = ascii_uppercase[l]
        lines.append(''.join(list(reversed(line)) + line[1:]))
    return '\n'.join(lines[:-1] + list(reversed(lines))) + '\n'
Пример #38
0
def value( name ):
    """
    >>> from euler22 import value
    >>> value("COLIN")
    53
    """
    chars= [ ascii_uppercase.index(c)+1 for c in name ]
    return sum( chars )
Пример #39
0
def ltr2nbr( s ):
    """
    >>> from euler42 import ltr2nbr
    >>> ltr2nbr("SKY")
    [19, 11, 25]
    >>> sum(ltr2nbr("SKY"))
    55
    """
    return [ 1+ascii_uppercase.index(c) for c in s ]
Пример #40
0
def rotate(message, key):
    coded_message = ""
    for char in message:
        if char in alpha_lower:
            char = alpha_lower[(alpha_lower.index(char) + key) % ALPHA_LEN]
        elif char in alpha_upper:
            char = alpha_upper[(alpha_upper.index(char) + key) % ALPHA_LEN]
        coded_message += char
    return coded_message
Пример #41
0
def caeser_cipher(text, key):
    encrypted = ''
    for i in text:
        if i in l:
            encrypted += l[(l.index(i) + key) % 26]
        elif i in u:
            encrypted += u[(u.index(i) + key) % 26]
        else:
            encrypted += i
    return encrypted
Пример #42
0
def checkio(number):
    to_int = lambda x: int(x) if x.isdigit() else alpha.index(x) + 10
    digits = list(map(to_int, number))
    k = max(digits) + 1
    for k in itertools.count(k):
        if k > MAX_K:
            return 0
        else:
            decimal = sum((k ** i) * x for i, x in enumerate(reversed(digits)))
            if not decimal % (k - 1):
                return k
Пример #43
0
def _alpha_value(chars):
    """Calculate the alphabetical value (as described by `Problem 22`_).

    .. _Problem 22: http://projecteuler.net/index.php?section=problems&id=22

    >>> _alpha_value('COLIN')
    53
    >>> _alpha_value('RUTH')
    67
    """
    return sum((1 + ascii_uppercase.index(char) for char in chars))
Пример #44
0
def lex(word):
    score,i = [],0
    while i <= 15:
        if i < len(word):
            value = abc.index(word[i])
            value = str(value) if value > 9 else "0"+str(value)
            score.append(value)
        else:
            score.append("00")
        i = i + 1
    return int(reduce(lambda a,b: a+b,score))
Пример #45
0
def caesar(s, shift):
    result = []
    for a in s:
        if a.isalpha():
            if a.islower():
                result.append(low[(low.index(a) + shift) % 26])
            else:
                result.append(up[(up.index(a) + shift) % 26])
        else:
            result.append(a)
    return ''.join(result)
Пример #46
0
def encryptor(key, message):
    key %= 26
    result = []
    for a in message:
        if a.islower():
            result.append(low[(low.index(a) + key) % 26])
        elif a.isupper():
            result.append(up[(up.index(a) + key) % 26])
        else:
            result.append(a)
    return ''.join(result)
Пример #47
0
def rotate(text, degrees):
    # Building this dictionary is almost certainly a preoptimization given the
    # lengths of the test inputs.
    rotate_dict = {}
    for l in ascii_lowercase:
        rotated_index = (ascii_lowercase.index(l) + degrees) % NUM_LETTERS
        rotate_dict[l] = ascii_lowercase[rotated_index]
    for l in ascii_uppercase:
        rotated_index = (ascii_uppercase.index(l) + degrees) % NUM_LETTERS
        rotate_dict[l] = ascii_uppercase[rotated_index]

    return sub(r'(.)', lambda l: rotate_dict.get(l.group(1), l.group(1)), text)
Пример #48
0
def triangle_words(file, c=0):
    triangles = {x*(x+1)/2 for x in xrange(1000)}
    value = {c: ascii_uppercase.index(c)+1 for c in ascii_uppercase}
    with open(file, 'r') as f:
        words = list(f.read().replace('"', '').split(','))
    for word in words:
        s = 0
        for char in word:
            s += value[char]
        if s in triangles:
            c += 1
    return c
def play_pass(string, n):
    result = []
    for i, a in enumerate(string):
        if a.isdigit():
            char = str(9 - int(a))
        elif a.isalpha():
            char = up[(up.index(a) + n) % 26]
            char = char if i % 2 == 0 else char.lower()
        else:
            char = a
        result.append(char)
    return ''.join(reversed(result))
Пример #50
0
def change_pass(password,enc1,enc2):
	lpas = list(password)
	for i in range(len(lpas)):
		let = lpas[i]
		if let in ascii_lowercase:
			ind = ascii_lowercase.index(let)
			newlet = enc1[ind]
		elif let in ascii_uppercase:
			ind = ascii_uppercase.index(let)
			newlet = enc2[ind]
		else:
			continue
		lpas[i] = newlet
	return "".join(lpas)
Пример #51
0
 def getPixelWidth(self, sentence, uppercase, lowercase):
     l = 0
     letters = 0
     for i in sentence:
         if i in U:
             l += uppercase[U.index(i)]
         elif i in L:
             l += lowercase[L.index(i)]
         else:
             l += 3
         letters += 1
     l += letters-1
     print letters, len(sentence)
     return l
Пример #52
0
    def cord2pos(self,key):
        keys = key.split('!')
        if len(keys) == 2:
            sheetKey = keys[0]
            key = keys[1]
        elif len(keys) == 1:
            sheetKey = None
        else:
            raise ValueError(key)
        key = key.upper()

        if len(key) == 1:
            if key in ascii_uppercase:
                colKey = key
                rowKey = None
            else:
                colKey = None
                rowKey = self.str2int(key)
        else:
            if key[1] in ascii_uppercase:
                colKey = key[:1]
                rowKey = self.str2int(key[2:])
            elif key[0] in ascii_uppercase:
                colKey = key[0]
                rowKey = self.str2int(key[1:])
            else:
                colKey = None
                rowKey = self.str2int(key)
        if colKey:
            if len(colKey) == 1:
                colKey = ascii_uppercase.index(colKey)+1
            elif len(colKey) == 2:
                colKey = (ascii_uppercase.index(colKey[0])+1)*2 \
                         + ascii_uppercase.index(colKey[1])+1
            else:
                raise KeyError(key)
        return (sheetKey,rowKey,colKey)
Пример #53
0
def play_pass(s, n):
    """
    shift each letter by a given number but the transformed letter must be a letter (circular shift),
replace each digit by its complement to 9,
keep such as non alphabetic and non digit characters,
downcase each letter in odd position, upcase each letter in even position (the first character is in position 0),
reverse the whole result.

    """
    from string import ascii_lowercase, ascii_uppercase, punctuation, whitespace
    news = ''
    llower = ascii_lowercase * 2
    uuper = ascii_uppercase * 2
    for idx, ch in enumerate(s):
        if ch in punctuation + whitespace:
            news += ch
        if ch in ascii_lowercase:
            news += llower[ascii_lowercase.index(ch) + n] if idx % 2  else llower[ascii_lowercase.index(ch) + n].upper()
        if ch in ascii_uppercase:
            news += uuper[ascii_uppercase.index(ch) + n] if idx % 2 ==0 else uuper[ascii_uppercase.index(ch) + n].lower()
        if ch in '0123456789':
            news += str(9-int(ch))

    return news[::-1]
Пример #54
0
def main():
	shifts = [21, 10, 23, 17, 23, 3]
	lShifts = len(shifts)

	crypt = open("../found1").read().rstrip("\n")
	
	for i in range(len(crypt)):
		shift2Use = i % lShifts
		try:
			indexInAlp = alphabet.index(crypt[i])
		except ValueError:
			continue
		#print indexInAlp, indexInAlp + shifts[shift2Use] % 26
		newIndex = (indexInAlp + shifts[shift2Use]) % 26
		print alphabet[newIndex],
Пример #55
0
    def get_move(self, game):
        moves = subprocess.check_output(['./a.out', 'games/%d.gcg' % game.id]).split('\n')

        for move in moves:
            if not move:
                return

            if move.startswith('nonmove'):
                return

            logging.info("Quackle suggests: %s" % move)
            place, word, _ = move.split(None, 2)
            logging.debug(place, word)
            word = word.decode('utf-8')

            # Number first for horizontal plays
            direction = Word.ACROSS if place[0].isdigit() else Word.DOWN
            board = game.get_board()

            if direction == Word.ACROSS:
                y, x = re.findall(r'([0-9]+)([a-zA-Z]+)', place)[0]
                x = ascii_uppercase.index(x)
                y = int(y) - 1
                w = ''.join([board[(x + i, y)] if v == '.' else swapcase(v) for i, v in enumerate(word)])
            else:
                x, y = re.findall(r'([a-zA-Z]+)([0-9]+)', place)[0]
                x = ascii_uppercase.index(x)
                y = int(y) - 1
                w = ''.join([board[(x, y + i)] if v == '.' else swapcase(v) for i, v in enumerate(word)])

            try:
                logging.info('Attempting %s @ %d, %d', str(w), x, y)
                game.play(w, x, y, direction)
                return
            except WordfeudError, e:
                logging.error('Error placing %s' % word)
Пример #56
0
 def UserMakesMove(self):
     #user enters coords to make a mov function, prevents invalid ones
     valid=False
     computer=False
     while not valid:
         try:
             #x=random.randint(0,9)
             #=random.randint(0,9)   
             userinput=input("Enter coordinates x y (x in [A..J] and y in [1..10]): ")
             x,y=userinput.split()
             x=ascii_uppercase.index(x.upper())
             y=int(y)-1
             
         except:
             print("Invalid coordinates please try again")
         else:
             if x >-1 and x <10 and y>-1 and y<10:
                 if self.makeA_Move(computer,y,x):
                     return        
Пример #57
0
 def userplacement(self):
     computer=False
     hide=True
     # UNCODE THIS PORTION FOR RANDOM PLACEMENT OF USER SHIPS
     randominput=input("Would you like your ships to be randomly placed? (Y/ENTER): ")
     if randominput.lower()=='y':
         self.RandomShipGenerator(computer)
         self.drawBoards(hide)
         return    
     #Generates the 5 user ships
     for index in range(len(self.__Ship_Sizes)):
         valid=False
         size=self.__Ship_Sizes[index]
         ship=self.__Ship_letter[index]
         while not valid:
             #validating coords enter by user
             print("Placing a",self.__Ship_Names[index],"of size",self.__Ship_Sizes[index])
             try:
                 userinput=input("Enter coordinates x y (x in [A..J] and y in [1..10]): ")
                 x,y=userinput.split()
                 x=ascii_uppercase.index(x.upper())
                 y=int(y)-1
                 if x >-1 and x <10 and y>-1 and y<10:
                     orientation=input("This ship is vertical or horizontal (v,h)? ")
                 else:
                     #Purposely raises an error to reset the validating process
                     error=int(error)
             except:
                 pass
             else:
                 #Sends the info to the placement functions
                 if self.validatePlacement(computer,ship,size,y,x,orientation):
                     self.drawBoards(hide)
                     valid=True
                 else:
                     #Makes the user enter new coords
                     self.drawBoards(hide)
                     if orientation.lower()=='h' or orientation.lower()=='v':
                         print('Cannot place a',self.__Ship_Names[index],'there. Stern is out of the board or collides with other ship. \nPlease take a look at the board and try again.')
                         pointless=input('Hit ENTER to continue. ')
                         
                     else:
                         print("Invalid orientation.")
Пример #58
0
def string_rot13(str):
    # ROT-13 is a simple substitution cypher. It stands for
    # "ROTate by 13 places." The cypher replaces any letter
    # (a-z or A-Z) with the one that appears 13 sequential places
    # behind it. Note that for the last half of the alphabet, the
    # ROT-13 character loops back around to the beginning of the
    # alphabet. Also note that characters that aren't in the alphabet
    # are passed through.
    "Return a string in its ROT-13 format"

    total = ""
    
    for x in range(len(str)):
        if str[x] in ascii_uppercase:
            total += ascii_uppercase[(ascii_uppercase.index(str[x])+13)%26]
        elif str[x] in ascii_lowercase:
            total += ascii_lowercase[(ascii_lowercase.index(str[x])+13)%26]
        else:
            total += str[x]

    return total
def shifty(string, shift, encode=True):
    if not encode:
        string = ''.join(string)
    length = 0
    shifted_chars = []
    for a in string:
        shifter = shift if encode else -shift
        if a.islower():
            shifted_chars.append(low[(low.index(a) + shifter) % 26])
        elif a.isupper():
            shifted_chars.append(up[(up.index(a) + shifter) % 26])
        else:
            shifted_chars.append(a)
        length += 1
        shift += 1
    if not encode:
        return ''.join(shifted_chars)
    chunk = int(ceil(length / 5.0))
    result = [''.join(shifted_chars[b:b + chunk])
              for b in xrange(0, length, chunk)]
    return result if len(result) == 5 else result + ['']
def demoving_shift(strings, shift):
    raw_string = ''
    coded_message = ''.join(strings)
    lens = len(coded_message)
    chars = -1
    for idx, char in enumerate(coded_message):
        chars +=1
        change=None
        if char in ascii_lowercase + ascii_uppercase:
            if char in ascii_lowercase:
                pos = ascii_lowercase.index(char)
                np = (pos - shift - chars) % 26
                change = ascii_lowercase[np]
            elif char in ascii_uppercase:
                pos = ascii_uppercase.index(char)
                np = (pos - shift - chars) % 26
                change = ascii_uppercase[np]
        else:
            change = char
        raw_string += change

    return raw_string