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)
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
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))))
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
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
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
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
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)
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
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)
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) ])
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")
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
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)
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
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
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)
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
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)
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
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()
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)
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)
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)
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
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
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)
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
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)
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
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)
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]
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
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)
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)
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
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
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)
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)
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))))
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)))
def words_point(names): result = sum([ascii_uppercase.find(i) + 1 for i in names if i in ascii_uppercase]) return result
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()
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"
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
def __init__(self, char): self.char = char self.ordinal = ascii_uppercase.find(char)