Exemplo n.º 1
0
def vigenere(mode, text, key):
    try:
        new_text = []
        keyIndex = 0
        key = key.upper()
        text = text.upper()
        for letter in text:
            num = ascii_uppercase.find(letter.upper())
            if num != -1:
                if mode == 'encrypt':
                    num += ascii_uppercase.find(key[keyIndex])
                else:
                    num -= ascii_uppercase.find(key[keyIndex])
                num %= len(ascii_uppercase)
                new_text.append(ascii_uppercase[num])
                keyIndex += 1
                if keyIndex == len(key):
                    keyIndex = 0
            else:
                new_text.append(letter)
        return returnDict('clear_vigenere', 'encrypted_vigenere',
                          'key_vigenere', text, ''.join(new_text), key, mode)
    except:
        return returnDict('clear_vigenere', 'encrypted_vigenere',
                          'key_vigenere', 'An error ocurred',
                          ''.join(new_text), key, mode)
Exemplo n.º 2
0
def encrypt_message(s):
    """
    str -> str
    Replace all letters in string with next letters in aplhabet.
    If argument is not a string function should return None.

    >>> encrypt_message("Revenge is a dish that tastes best when served cold.")
    'Sfwfohf jt b ejti uibu ubtuft cftu xifo tfswfe dpme.'
    >>> encrypt_message("Never hate your enemies. It affects your judgment.")
    'Ofwfs ibuf zpvs fofnjft. Ju bggfdut zpvs kvehnfou.'
    >>> encrypt_message(2015)

    """
    if type(s) is not str:
        return None
    else:
        from string import ascii_lowercase
        from string import ascii_uppercase
        for i in range(len(s)):
            if s[i] == s[i].lower() and ascii_lowercase.find(s[i]) >= 0:
                s = s[:i] + ascii_lowercase[(ascii_lowercase.find(s[i]) + 1)]\
                    + s[i+1:]
            elif s[i] == s[i].upper() and ascii_uppercase.find(s[i]) >= 0:
                s = s[:i] + ascii_uppercase[(ascii_uppercase.find(s[i]) + 1)]\
                    + s[i+1:]
        return s
Exemplo n.º 3
0
def vigenere(strng, key, to_encrypt):
    encrypt = (key * int(ceil(float(len(strng)) / len(key))))[:len(strng)]
    op = 1 if to_encrypt else -1
    return "".join(
        (ascii_uppercase[(ascii_uppercase.find(strng[x]) +
                          op * ascii_uppercase.find(encrypt[x])) % 26]
         for x in xrange(len(encrypt))))
Exemplo n.º 4
0
def enc(message, key):
    cipher_text = ''
    for i in message:
        if i.isupper():
            ind = ascii_uppercase.find(i.upper())
            cipher_text += key[ind].upper()
        elif i.islower():
            ind = ascii_uppercase.find(i.upper())
            cipher_text += key[ind].lower()
        else:
            cipher_text += i
    print("Cipher text: ", cipher_text)
    return cipher_text
Exemplo n.º 5
0
 def findRotationByChar(self, characterToMatch):
     '''
     Finds the closest match for the character given. E is the recommended choice.
     '''
     charFreq = self.letterFreq[characterToMatch]
     
     bestMatch = sorted([(abs(k - charFreq),v) for (v,k) in self.cipherFrequency.items()])[0][1]
     
     bestMatchIndex = ascii_uppercase.find(bestMatch)
     charToMatchIndex = ascii_uppercase.find(characterToMatch)
     
     if (bestMatchIndex >= charToMatchIndex):
         return bestMatchIndex-charToMatchIndex
     else:
         return (bestMatchIndex + 26) - charToMatchIndex        
Exemplo n.º 6
0
def moving_shift(str, number):
    output_str = str
    for i in range(len(output_str)):
        letter = str[i]
        if ascii_lowercase.find(letter) >= 0:
            index = ascii_lowercase.find(letter)
            output_str = output_str[:i] + ascii_lowercase[
                (index + number) % len(ascii_lowercase)] + output_str[i + 1:]
        if ascii_uppercase.find(letter) >= 0:
            index = ascii_uppercase.find(letter)
            output_str = output_str[:i] + ascii_uppercase[
                (index + number) % len(ascii_uppercase)] + output_str[i + 1:]

        number += 1
    return output_str
Exemplo n.º 7
0
def caesar(Ltr, shift):
    if (Ltr in lc):
        return lc[(lc.find(Ltr) + shift) % 26]
    elif (Ltr in uc):
        return uc[(uc.find(Ltr) + shift) % 26]
    else:
        return Ltr
Exemplo n.º 8
0
def caesar_translate(text, key, mode):
    """
    The Caesar cipher algorithm.
    """

    result = []

    for char in text:
        char_index = ascii_uppercase.find(char.upper())
        if char_index != -1:
            # (En)/(de)cryption process.
            if mode == "encrypt":
                char_index += key
            elif mode == "decrypt":
                char_index -= key
            char_index %= len(ascii_uppercase)

            # We need to indetify whether a char was in uppercase
            # or lowercase to output the result correctly.
            if char.isupper():
                result.append(ascii_uppercase[char_index])
            else:
                result.append(ascii_lowercase[char_index])
        else:
            result.append(char)

    return "".join(result)
Exemplo n.º 9
0
def Excel_LC1(excelfilename, excelsheetname, baseA_col, baseA_row):
    """this version of Excel_LU1 should be called first because it determines the nHRU, by checking in rows below to see
        how many HRUs have been entered"""
    wbook = openpyxl.load_workbook(excelfilename, data_only=True, read_only=True, keep_vba=False)
    wsheet = wbook[excelsheetname]

    # initialize lists of unknown length to store the HRU data, appended 1 HRU at a time
    HRUID_list = []    # name of hydrologic response units (HRUs)
    baseA_list = []    # baseline areas of HRUs
    pEIA_list  = []    # effective impervious area
    infil_list = []    # infiltration rate of the HRUs

    baseA = wsheet[baseA_col + str(baseA_row)].value
    indexcol = ascii_uppercase.find(baseA_col)

    while baseA is not None:

        baseA_list.append(baseA)
        HRUID_list.append(wsheet[ascii_uppercase[indexcol - 2] + str(baseA_row)].value)
        pEIA_list.append(wsheet[ascii_uppercase[indexcol + 1] + str(baseA_row)].value)
        infil_list.append(wsheet[ascii_uppercase[indexcol +2] + str(baseA_row)].value)

        baseA_row += 1  # move down a row to the next BMP
        baseA = wsheet[baseA_col + str(baseA_row)].value

    return HRUID_list, baseA_list, pEIA_list, infil_list
Exemplo n.º 10
0
def convert(char, rot):
    val = ord(char)
    if char in ascii_lowercase:
        return ascii_lowercase[(rot + ascii_lowercase.find(char)) % LENGTH]
    elif char in ascii_uppercase:
        return ascii_uppercase[(rot + ascii_uppercase.find(char)) % LENGTH]
    else:
        return chr(val)
Exemplo n.º 11
0
def processing(text, key, mode):
    key *= len(text) // len(key) + 1
    text = text.upper()

    return ''.join([
        alphabet[alphabet.find(j) + int(key[i]) * mode]
        for i, j in enumerate(text)
    ])
Exemplo n.º 12
0
def _swap_case(c):
    index = ascii_uppercase.find(c)
    if index != INDEX_NOT_FOUND:
        return ascii_lowercase[index]
    index = ascii_lowercase.find(c)
    if index != INDEX_NOT_FOUND:
        return ascii_uppercase[index]
    raise ValueError("Expected ascii character")
Exemplo n.º 13
0
def FormatBytes(obj: object = None):
    """
	Used to turn a bytearray to a string or to turn a string into a bytearray
	Args:
		obj (bytes/str): A bytearray or string
	Returns:
		bytearray/str: If a bytearray is passed, a string is returned. If a string is passed, a bytearray is returned
	"""
    if type(obj) == bytes:  # If object type is bytearray
        return "".join(
            [Alph[i // 26] + Alph[i % 26] for i in obj]
        )  # Create a 2 letter pair to represent the value of the byte and return list of them merged
    elif type(obj) == str:  # If object type is string
        return bytes([
            Alph.find(obj[i]) * 26 + Alph.find(obj[i + 1])
            for i in range(0, len(obj), 2)
        ])  # Return a list of bytes after decoding letters into bytes
Exemplo n.º 14
0
    def is_correct_letter_answer(self, letter: str) -> bool:
        """
        Checks specified letter answer against correct letter answer. Returns True if correct, False if incorrect.

        :param letter: String of letter answered
        :return: True if letter matches true answer, False if not
        """
        answer: str = self.get_all_answers()[ascii_uppercase.find(letter)]
        return self.is_correct_answer(answer)
Exemplo n.º 15
0
def _ascii_to_index(column):
    if column is None:
        return None
    index = ascii_uppercase.find(column)
    if index == -1:
        message = "Column {} is not an upper case ascii letter"
        raise ArgumentTypeError(message)

    return index
Exemplo n.º 16
0
 def decode_col(self,col):
     col_val = 0
     step = 0
     for alpha in col:
         if alpha not in ascii_uppercase:
             continue
         col_val = col_val + ( step * (len(ascii_uppercase) -1) ) + ascii_uppercase.find(alpha)
         step += 1
     return col_val
Exemplo n.º 17
0
def dec(cipher_text, key):
    key = key.upper()
    ki = 0
    plain_text = ''
    for i in cipher_text:
        n = ascii_uppercase.find(i.upper())
        if n != -1:
            n = (n - ascii_uppercase.find(key[ki])) % 26
            if i.isupper():
                plain_text += ascii_uppercase[n]
            elif i.islower():
                plain_text += ascii_uppercase[n].lower()
            ki += 1
            if ki == len(key):
                ki = 0
        else:
            plain_text += i
    print("Plain text is:", plain_text)
Exemplo n.º 18
0
def enc(message, key):
    key = key.upper()
    ki = 0
    cipher_text = ''
    for i in message:
        n = ascii_uppercase.find(i.upper())
        if n != -1:
            n = (n + ascii_uppercase.find(key[ki])) % 26
            if i.isupper():
                cipher_text += ascii_uppercase[n]
            elif i.islower():
                cipher_text += ascii_uppercase[n].lower()
            ki += 1
            if ki == len(key):
                ki = 0
        else:
            cipher_text += i
    print("Cipher text is:", cipher_text)
    return cipher_text
Exemplo n.º 19
0
def make_angles_and_distances(pieces: Dict) -> pd.DataFrame:
    """Calculates the angles and distances from the vectors and planes.

    :param pieces: The SSE pieces to calculate the vectors from.
    """
    data = {
        'sse': [],
        'layer': [],
        'angles_layer': [],
        'angles_floor': [],
        'angles_side': [],
        'points_layer': [],
        'points_floor': [],
        'points_side': [],
        'tilted_layer': [],
        'tilted_floor': [],
        'tilted_side': []
    }

    for layer in sorted(set([x[0] for x in pieces if len(x) == 1])):
        for sse in [x for x in pieces if len(x) == 3]:
            if abs(ascii_uppercase.find(layer) -
                   ascii_uppercase.find(sse[0])) <= 1:
                data['sse'].append(sse)
                data['layer'].append(layer)
                for iplane, plane in enumerate(pieces[layer]):
                    if TBcore.get_option('system', 'debug'):
                        sys.stdout.write(
                            'PDB:{} geometry plane {} vs. sse {}\n'.format(
                                plane, layer, sse))
                    syPlane = sy.Plane(sy.Point3D(pieces[layer][plane][0]),
                                       sy.Point3D(pieces[layer][plane][1]),
                                       sy.Point3D(pieces[layer][plane][2]))
                    syLine = sy.Line(pieces[sse]['vector'][0],
                                     pieces[sse]['vector'][-1])
                    syPoint = sy.Point3D(*pieces[sse]['vector'][1])
                    data[f'angles_{plane}'].append(
                        math.degrees(syPlane.angle_between(syLine)))
                    data[f'points_{plane}'].append(
                        float(syPlane.distance(syPoint)))
                    data[f'tilted_{plane}'].append(
                        float(syPlane.distance(default_plane(iplane))))
    return pd.DataFrame(data)
Exemplo n.º 20
0
def encode(text):
    cipher = ""
    for letter in text:
        if letter in lowerLetters:
            cipher = cipher + revLowerLetters[lowerLetters.find(letter)]
        elif letter in upperLetters:
            cipher = cipher + revUpperLetters[upperLetters.find(letter)]
        else:
            cipher = cipher + letter
    return cipher
Exemplo n.º 21
0
    def __init__(self, char_init='A', dest_go=""):

        self.count = 0
        self.dest_go = dest_go

        if (char_init != 'A'):
            ind_init = ascii_uppercase.find(char_init)
            self.dest_go = self.dest_go[ind_init:] + self.dest_go[:ind_init]

        if (len(dest_go) == 0):
            self.dest_go = self.set_random_string()
Exemplo n.º 22
0
 def update(self, data):
     total = []
     for char in data.decode("hex"):
         if char in ascii_uppercase:
             index = (ascii_uppercase.find(char) + 13) % 26
             total.append(ascii_uppercase[index])
         elif char in ascii_lowercase:
             index = (ascii_lowercase.find(char) + 13) % 26
             total.append(ascii_lowercase[index])
         else:
             total.append(char)
     return "".join(total)
Exemplo n.º 23
0
def rotate(word, key):
    key = key % 26
    newWord = []
    for char in word:
        if char.isalpha():
            if char.islower():
                char = ascii_lowercase[(ascii_lowercase.find(char) + key) % 26]
            else:
                char = ascii_uppercase[(ascii_uppercase.find(char) + key) % 26]
        newWord.append(char)

    return ''.join(newWord)
Exemplo n.º 24
0
def string_rot13(str):
    total = []
    for s in str:
        if s in ascii_uppercase:
            index = (ascii_uppercase.find(s) + 13) % 26
            total.append(ascii_uppercase[index])
        elif s in ascii_lowercase:
            index = (ascii_lowercase.find(s) + 13) % 26
            total.append(ascii_lowercase[index])
        else:
            total.append(s)
    return "".join(total)
Exemplo n.º 25
0
def decipher(cipherTxt, key):
    plainTxt = ""
    keyPos = []
    for k in key:
        keyPos.append(ascii_uppercase.find(k))
    i = 0
    for x in cipherTxt:
        if i == len(keyPos):
            i = 0
        pos = ascii_uppercase.find(x) - keyPos[i]
        if pos < 0:
            pos += 26
        for z in range(pos + 1):
            q = ascii_uppercase[z]
            print('\b' + q, end='', flush=True)
            sleep(randFloat(0, 0.01))
        plainTxt += q
        i += 1
        print('\b' * (len(plainTxt)) + plainTxt, end='', flush=True)
    print('\b' * len(plainTxt), end='')
    return plainTxt
Exemplo n.º 26
0
 def update(self, data):
     total = []
     for char in data.decode("hex"):
         if char in ascii_uppercase:
             index = (ascii_uppercase.find(char) + 13) % 26
             total.append(ascii_uppercase[index])
         elif char in ascii_lowercase:
             index = (ascii_lowercase.find(char) + 13) % 26
             total.append(ascii_lowercase[index])
         else:
             total.append(char)
     return "".join(total)
Exemplo n.º 27
0
def cipher(plainTxt, key):
    cipherTxt = ""
    keyPos = []
    for k in key:
        keyPos.append(ascii_uppercase.find(k))
    i = 0
    for x in plainTxt:
        if i == len(keyPos):
            i = 0
        pos = ascii_uppercase.find(x) + keyPos[i]
        if pos > 25:
            pos = pos - 26
        for z in range(pos + 1):
            q = ascii_uppercase[z]
            print('\b' + q, end='', flush=True)
            sleep(randFloat(0, 0.01))
        cipherTxt += q
        print('\b' * (len(cipherTxt)) + cipherTxt, end='', flush=True)
        i += 1
    print('\b' * len(cipherTxt), end='')
    return cipherTxt
Exemplo n.º 28
0
 def clear_matrix(self):
     """ set all crosspoints to off"""
     for xOut in self._outputs:
         XUNIT, XOUT = self.parse_output(xOut)
         for xIn in self._xapx00.input_range:
             self._xapx00.setMatrixRouting(xIn, xOut, 0, unitCode=XUNIT)
         for xIn in list(ascii_uppercase[ascii_uppercase.find('O'):]):
             self._xapx00.setMatrixRouting(xIn,
                                           xOut,
                                           0,
                                           inGroup='E',
                                           unitCode=XUNIT)
Exemplo n.º 29
0
def caesar(plain_text, key):
    cipher_text = ''

    for char in plain_text:
        if not char.isalpha():
            cipher_text += char
        else:
            if char.isupper():
                cipher_text += up[(up.find(char) + key) % 26]
            else:
                cipher_text += low[(low.find(char) - key) % 26]
    return cipher_text
Exemplo n.º 30
0
Arquivo: 3.py Projeto: Qiong/ycyc
def main():
    string_rot13()
    for chr in str:
        if chr in ascii_uppercase:
            index = (ascii_uppercase.find(chr) + 13) % 26
            total.append(ascii_uppercase[index])
        elif chr in ascii_lowercase:
            index = (ascii_lowercase.find(chr) + 13) % 26
            total.append(ascii_lowercase[index])
        else:
            total.append(chr)
    return ''.join(total)
Exemplo n.º 31
0
def caesar(plain_text, key):
    cipher_text = ''

    for char in plain_text:
        if not char.isalpha():
            cipher_text += char
        else:
            if char.isupper():
                cipher_text += POOL[(POOL.find(char) + key) % 26]
            else:
                cipher_text += pool[(pool.find(char) + key) % 26]
    return cipher_text
Exemplo n.º 32
0
 def update_old(self, data):
     total = []
     for char in bytes.fromhex(data).decode('ascii'):
         if char in ascii_uppercase:
             index = (ascii_uppercase.find(char) + 13) % 26
             total.append(ascii_uppercase[index])
         elif char in ascii_lowercase:
             index = (ascii_lowercase.find(char) + 13) % 26
             total.append(ascii_lowercase[index])
         else:
             total.append(char)
     return "".join(total)
Exemplo n.º 33
0
def time_taken(graph):
    finish_times = {}
    while graph:
        dependents = {d for ds in graph.values() for d in ds['dependents']}
        available = set(graph.keys()) - dependents
        next_steps = sorted(available)[:5]
        for step in next_steps:
            start_time = max(
                [finish_times[d] for d in graph[step]['dependencies']] or [0])
            duration = ascii_uppercase.find(step) + 61
            finish_times[step] = start_time + duration
            graph.pop(step)
    return max(finish_times.items(), key=(lambda x: x[1]))[1]
Exemplo n.º 34
0
def num_hyphen_letter(num1, num2, let1, let2, step=1):
    '''
    This function takes a number range (num1, num2,) an optional
    step and a letter range (let1, let2) and returns a formatted list
    ['1-A','2-A',...]
    '''

    from string import ascii_uppercase as ascii_caps

    # Get number range
    numbers = range(num1, num2 + 1, step)

    # Get letter range
    let_range = ascii_caps.find(let1), ascii_caps.find(let2)
    letters = ascii_caps[let_range[0]:let_range[1] + 1]

    num_letters = []
    for num in numbers:
        for letter in letters:
            num_letters.append("{}-{}".format(num, letter))

    return num_letters
Exemplo n.º 35
0
def rot13(text):
    result = ''
    for c in text:
        idx = au.find(c)  # Is c an uppercase character?
        if idx > -1:
            result += au_c[idx]
        else:
            idx = al.find(c)  # Is c a lowercase character?
            if idx > -1:
                result += al_c[idx]
            else:
                result += c  # Other characters are taken as is.
    return result
def rot13(data):
    """ A simple rot-13 encoder since `str.encode('rot13')` was removed from
        Python as of version 3.0.  It rotates both uppercase and lowercase letters individually.
    """
    total = []
    for char in data:
        if char in ascii_uppercase:
            index = (ascii_uppercase.find(char) + 13) % 26
            total.append(ascii_uppercase[index])
        elif char in ascii_lowercase:
            index = (ascii_lowercase.find(char) + 13) % 26
            total.append(ascii_lowercase[index])
        else:
            total.append(char)
    return "".join(total)
Exemplo n.º 37
0
def increment_label_asym_id(asym_id):
  from string import ascii_uppercase
  if len(asym_id) == 0:
    return "A"
  asym_id = list(asym_id)
  for i in range(len(asym_id)):
    if asym_id[i] == "Z":
      asym_id[i] = "A"
      if (i+1) == len(asym_id):
        return "A" * (len(asym_id) + 1)
    else:
      while True:
        j = ascii_uppercase.find(asym_id[i])
        asym_id[i] = ascii_uppercase[j+1]
        return "".join(asym_id)
Exemplo n.º 38
0
def rot13(data):
    """ A simple rot-13 encoder since `str.encode('rot13')` was removed from
        Python as of version 3.0.  It rotates both uppercase and lowercase letters individually.
    """
    total = []
    for char in data:
        if char in ascii_uppercase:
            index = (ascii_uppercase.find(char) + 13) % 26
            total.append(ascii_uppercase[index])
        elif char in ascii_lowercase:
            index = (ascii_lowercase.find(char) + 13) % 26
            total.append(ascii_lowercase[index])
        else:
            total.append(char)
    return "".join(total)
Exemplo n.º 39
0
def decryptWithcipherLetterMapping(cipherText, letterMapping):
    key = ['x'] * len(LETTERS)
    for cipherLetter in LETTERS:
        if len(letterMapping[cipherLetter]) == 1:
            # If there's only one letter, add it to the key.
            keyIndex = LETTERS.find(letterMapping[cipherLetter][0])
            key[keyIndex] = cipherLetter
        else:
            cipherText = cipherText.replace(cipherLetter.lower(), '_')
            cipherText = cipherText.replace(cipherLetter.upper(), '_')
    key = ''.join(key)

    decryptedMessage = simpleSubCipher.decryptMessage(key, cipherText)

    return decryptedMessage
Exemplo n.º 40
0
def bij2int(s):
    """
    >>> bij2int('A')
    1
    >>> bij2int('Z')
    26
    >>> bij2int('AA')
    27
    >>> bij2int('AB')
    28
    """
    n = 0
    for ch in s:
        n *= 26
        n += ascii_uppercase.find(ch) + 1
    return n
Exemplo n.º 41
0
 def __rotN(self, plaintext, rotation):
     '''
     Accepts a string of plaintext, and will rotate N units
     ie: a rotation of 1 will change A to B, B to C, and so forth
     '''                
     cipher = []
     for char in plaintext:
         if (self.ignoreList.count(char) != 0):
             cipher.append(char)
         elif char in ascii_uppercase:
             index = (ascii_uppercase.find(char) + rotation) % 26
             cipher.append(ascii_uppercase[index])
         elif char in ascii_lowercase:
             index = (ascii_lowercase.find(char) + rotation) % 26
             cipher.append(ascii_lowercase[index])
         
     return "".join(cipher)
Exemplo n.º 42
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
    total = []
    for chr in str:
        if chr in ascii_uppercase:
            index = (ascii_uppercase.find(chr) + 13) % 26
            total.append(ascii_uppercase[index])
        elif chr in ascii_lowercase:
            index = (ascii_lowercase.find(chr) + 13) % 26
            total.append(ascii_lowercase[index])
        else:
            total.append(chr)
    return ''.join(total)
Exemplo n.º 43
0
def rot13(ask):
    total=[]
    n=" "
    for i in ask:
        if i in ascii_lowercase:
            index=(ascii_lowercase.find(i)+13)%26
            total.append(ascii_lowercase[index])
        if i in  ascii_uppercase:
            index=(ascii_uppercase.find(i)+13)%26
            total.append(ascii_uppercase[index])
        elif i in num:
            index=(num.find(i)+5)%10
            total.append(num[index])
        elif i in sym:
            index=(sym.find(i)+len(sym)/2)%len(sym)
            total.append(sym[int(index)])
        elif i in n:
            total.append(n)
    return "".join(total)
def vigenere(strng, key, to_encrypt):
	encrypt = (key * int(ceil(float(len(strng)) / len(key))))[:len(strng)]
	op = 1 if to_encrypt else -1
	return "".join((ascii_uppercase[(ascii_uppercase.find(strng[x]) + 
		op * ascii_uppercase.find(encrypt[x])) % 26] for x in xrange(len(encrypt))))
Exemplo n.º 45
0
def p022(words):
    words.sort()
    return sum((i + 1) * sum(_ascii_uppercase.find(char) + 1 for char in words[i]) for i in range(len(words)))
Exemplo n.º 46
0
def words_point(names):
	result = sum([ascii_uppercase.find(i) + 1 for i in names 
			if i in ascii_uppercase])
	return result
Exemplo n.º 47
0
Xlmw irgvCtxih qiwweki wlepp gpevmjC lsA RSX xs irgvCtx e qiwweki xsheC! Izir mj mx Aew wyjjmgmirx efsyx 6444 Cievw eks, sv xs fi qsvi tvigmwi mr xli Ciev 88 FG, rsAeheCw mx mw rsx. XsheC iegl ws-geppih Wgvmtx Omhhmi Asyph fi efpi xs kix wirwmxmzi mrjsvqexmsr, mj xliC Aivi irgvCtxih xlmw AeC."""

#cipherText = re.sub('[^a-z]', '', cipherText.lower()) 

#custom alphabet?
alphabet = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z','A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z','0','1','2','3','4','5','6','7','8','9']
alphabet = ''.join(alphabet)

#print str(alphabet)
for i in range (-62,62):
	plainText = []
	print i,":",
	for char in cipherText:
		if char in alphabet:
			index = (alphabet.find(char) + i) % 62
			plainText.append(alphabet[index])
		elif char in ascii_lowercase:
			index = (ascii_lowercase.find(char) + i) % 26
			plainText.append(ascii_lowercase[index])
		elif char in ascii_uppercase:
			index = (ascii_uppercase.find(char) + i) % 26
			plainText.append(ascii_uppercase[index])
		elif char in digits:
			index = (digits.find(char) + i) % 10
			plainText.append(digits[index])
		else:
			plainText.append(char)
	print "".join(plainText)
	key = sys.stdin.readline()

Exemplo n.º 48
0
from string import ascii_uppercase as alphabet

func = lambda l: alphabet[(alphabet.find(l.upper()) + 13) % 26]

assert "".join(map(func, "RQHNEQB")) == "EDUARDO"
assert "".join(map(func, "EDUARDO")) == "RQHNEQB"
Exemplo n.º 49
0
from string import ascii_uppercase

with open('input_22', 'r') as f:
    fl = f.read()

fl = fl.replace('"', '')
name_list = fl.split(',')
name_list.sort()
prod = 0
for index, name in enumerate(name_list):
    prod += (index+1)*sum([ascii_uppercase.find(i)+1 for i in name])
print prod
Exemplo n.º 50
0
 def __init__(self, char):
     self.char = char
     self.ordinal = ascii_uppercase.find(char)