def rot(string): caesard = {} capitals = [i for i, char in enumerate(string) if char.isupper()] for rot in range(26): lower, modified = string.lower(), "" newString = [] for char in lower: newString.append(ascii_lowercase[((ascii_lowercase.index(char) + rot) % len(ascii_lowercase))]) for i in capitals: char = ascii_lowercase.index(newString[i]) newString[i] = ascii_lowercase[char].upper() caesard["".join(newString)] = str(26-rot) return caesard
def decrypt(key, ciphertext): # decrypt ciphertext using key, by way of a Vigenre cipher key = key.lower() ciphertext = ciphertext.lower().replace('\n','').replace(' ','') out = '' # print(ciphertext) for i in range(len(ciphertext)): # for each symbol in the ciphertext # get the symbol's index in the alphabet symbol_index = ascii_lowercase.index(ciphertext[i]) # get the key_symbol key_symbol = key[i % len(key)] # get the key_symbol's index in the alphabet key_symbol_index = ascii_lowercase.index(key_symbol) # decrypt the cipher symbol and append to out out += ascii_lowercase[(symbol_index - key_symbol_index + \ len(ascii_lowercase)) % len(ascii_lowercase)] return out
def _letter_generator(self, current_index, letter, encode=True): current_key = self.key[current_index % len(self.key)] if encode: current_key = (ascii_lowercase.index(current_key) + ascii_lowercase.index(letter)) % 26 else: current_key = (ascii_lowercase.index(letter) - ascii_lowercase.index(current_key)) % 26 return ascii_lowercase[current_key]
def rot13(message, action="encode"): """Write a function called rot13 that uses the Caesar cipher to encrypt a message. The Caesar cipher works like a substitution cipher but each character is replaced by the character 13 characters to ‘its right’ in the alphabet. So for example the letter a becomes the letter n. If a letter is past the middle of the alphabet then the counting wraps around to the letter a again, so n becomes a, o becomes b and so on.""" from string import ascii_lowercase as lc new_message = "" message = message.lower() if action == "decode": for char in message: if char in lc: idx = (lc.index(char)-13) % 26 new_message += lc[idx] else: new_message += char return new_message for char in message: if char in lc: idx = (lc.index(char)+13) % 26 new_message += lc[idx] else: new_message += char return new_message
def getIndexFromA(letter, shiftAmount): '''Returns if the letter's index is in the next alphabet over, or in the same alphabet, in addition to the index of the relative alphabet cycle.''' realShift = getRealShift(inputShiftAmount) letter = letter.lower() letterIndexFromEnd = 25 - ascii_lowercase.index(letter) if letterIndexFromEnd < realShift: shiftedLetterIndex = realShift - (letterIndexFromEnd + 1) return shiftedLetterIndex else: return realShift + ascii_lowercase.index(letter)
def main(): text, new_text, key = "", "", "qwcpwnuht" with open("krypton5") as f: text = f.read().lower().rstrip("\n") for i, c in enumerate(text): index_of_key = al.index(key[i % len(key)]) new_text += al[(index_of_key + al.index(c)) % 26] print new_text
def code(self, text, shift_sign): # pad the end of the key with 'a' (basically no substitution) self.key = self.key + 'a' * len(text) # make text lowercase, strip out non letters, convert to list text = list(re.sub(r'[^a-z]','',text.lower())) # return result using character substitution based on key result = '' for i in range(len(text)): char_value = letters.index(text[i]) key_shift = shift_sign * letters.index(self.key[i]) result += letters[(char_value + key_shift) % 26] return result
def main(): reverse_key = [] key = "enc" string = "rwfwcvttw ufriifyg dws jjbhwooqm ezu iwsh".replace(" ","") new_string = "" for i, char in enumerate(string): key_char = key[ i % len(key) ] key_char_index = al.index( key_char ) + 1 char_index = al.index( char) + 1 new_index = char_index - key_char_index reverse_key.append(al[new_index-1]) print "".join(reverse_key)
def decrypt(): rando = [] cipherlist = [] privatep = int(input('Please enter the first private key : ')) privateq = int(input('Please enter the second private key : ')) ciphertext = input('Please enter the ciphertext : ').replace(' ', '') x = int(input('Please enter the x-value: ')) publickey = privatep * privateq for i in range(len(ciphertext)): cipherlist.append(ascii_lowercase.index(ciphertext[i])) p = pow(x, int((privatep + 1)/4)** (len(ciphertext)-1), privatep) # formula q = pow(x, int((privateq + 1)/4)** (len(ciphertext)-1), privateq) # formula initno = (privatep * q * pow(privatep,privateq-2,privateq) + privateq * p * pow(privateq,privatep-2,privatep)) % publickey for i in range(len(cipherlist)): if i == 0: rando.append(initno % publickey) else: rando.append((initno ** 2 ** i) % publickey) # xi = x0 ** i mod N for i in range(len(cipherlist)): # M = (C - x) mod N cipherlist[i] = ascii_lowercase[(cipherlist[i] - rando[i]) % 26] print('This is your plaintext : ' + ''.join(cipherlist))
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
def generate_graph(words): from string import ascii_lowercase as lowercase G = nx.Graph(name="words") lookup = dict((c,lowercase.index(c)) for c in lowercase) def edit_distance_one(word): word1="".join(sorted(word)) for i in reversed(range(len(word))): left, c, right = word1[0:i], word1[i], word1[i+1:] j = lookup[c] # lowercase.index(c) bound=25 for cc in lowercase[0:bound]: if (cc !=c): yield left + cc + right ## candgen = ((word, cand) for word in sorted(words) ## for cand1 in edit_distance_one(word) if ((cand1 in wordsd.values()) and (cand==wordsd.keys()[words.values.index(cand1)])) candgen=[] for word in sorted(words): for cand2 in edit_distance_one(word): cand1 = ''.join(sorted(cand2)) if (cand1 in wordsd.values()): cand=wordsd.keys()[wordsd.values().index(cand1)] candgen.append([word,cand]) G.add_nodes_from(words) for word, cand in candgen: G.add_edge(word, cand) return G
def name_value(name): result = 0 name = name.lower().strip() for char in name: if char != '"': result += lowercase.index(char) return result
def generate_graph(words): from string import ascii_lowercase as lowercase G = nx.Graph(name="words") lookup = dict((c,lowercase.index(c)) for c in lowercase) def edit_distance_one(word): for i in range(len(word)): left, c, right = word[0:i], word[i], word[i+1:] j = lookup[c] # lowercase.index(c) for cc in lowercase[j+1:]: # yield left + cc + right for x in range(6): if x == 0: yield cc + left + right elif x == 1: yield cc + right + left elif x == 2: yield right + cc + left elif x == 3: yield left + cc + right elif x == 4: yield right + left + cc else: yield left + right + cc candgen = ((word, cand) for word in sorted(words) for cand in edit_distance_one(word) if cand in words) G.add_nodes_from(words) for word, cand in candgen: G.add_edge(word, cand) return G
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 get_searchTerms(): searchTerm=get_var('previous_searchTerm') if searchTerm==None: i=0 else: i=ascii_lowercase.index(searchTerm)+1 return ascii_lowercase[i:]
def generate_graph(words): #Import lowercase ASCII characters from string import ascii_lowercase as lowercase #Initialize G as Graph from networkx G = nx.Graph(name="words") #Dictionary of each char in lowercase mapped to it's index lookup = dict((c,lowercase.index(c)) for c in lowercase) def edit_distance_one(word): for i in range(len(word)): left, c, right = word[0:i], word[i], word[i+1:] j = lookup[c] # lowercase.index(c) dist_one_anagrams = set() for cc in lowercase: if cc!=c: dist_one_anagrams.add(left + cc + right) for w in dist_one_anagrams: dist_one_anagrams_2 = {"".join(perm) for perm in itertools.permutations(w)} dist_one_anagrams = dist_one_anagrams|dist_one_anagrams_2 for w in dist_one_anagrams: yield w #Generator for words and their neighbors that exist in input data candgen = ((word, cand) for word in sorted(words) for cand in edit_distance_one(word) if cand in words) #Add each word in words as a node into G G.add_nodes_from(words) #Add edge between a word and it's neighbor for word, cand in candgen: G.add_edge(word, cand) #Return generated graph return G
def generate_graph(words): from string import ascii_lowercase as lowercase G = nx.Graph(name="words") lookup = dict((c,lowercase.index(c)) for c in lowercase) def edit_distance_two(word): s_word = ''.join(sorted(word)) for i in range(len(s_word)): left, c, right = s_word[0:i], s_word[i], s_word[i+1:] j = lookup[c] # lowercase.index(c) for cc in lowercase[j+1:]: yield left + cc + right G.add_nodes_from(words) swords=[] awords=[] for word in sorted(words): awords.append(word) swords.append(''.join(sorted(word))) for word in awords: for cand in edit_distance_two(word): i = 0 for sword in swords: if cand == sword: G.add_edge(word, awords[i]) i+=1 return G
def encrypt(): messagelist = [] rando = [] message = input('Please enter your message : ').replace(' ', '').lower() while not message.isalpha(): # message can only be letters print('Please input only letters!') message = input('Please enter your message: ').replace(' ', '').lower() publickey = int(input('Please enter the public key: ')) for i in range(len(message)): # change letters to respective numbers messagelist.append(ascii_lowercase.index(message[i])) seed = randint(100,10000) while seed ** 4 < publickey: # seed squared > square root of n seed = randint(100,10000) if gcd(seed, publickey) != 1: # coprime if gcd = 1 continue print('Your seed is :', seed) initno = seed * seed for i in range(len(messagelist)): # number of int based on length of message if i == 0: rando.append(initno % publickey) else: rando.append((initno ** 2 ** i) % publickey) # xi = x0 ** i mod N for i in range(len(messagelist)): # C = (M + x) mod 26 messagelist[i] = ascii_lowercase[(messagelist[i] + rando[i]) % 26] print('Ciphertext :', ''.join(messagelist)) print('x-value :',rando[len(rando)-1]) # last random int produced
def generate_graph(words,alt): from string import ascii_lowercase as lowercase from itertools import permutations G = nx.Graph(name="words") lookup = dict((c,lowercase.index(c)) for c in lowercase) if alt: def scramble(word): perms = [''.join(p) for p in permutations(word)] return set(perms) def edit_distance_one(word): for i in range(len(word)): left, c, right = word[0:i], word[i], word[i+1:] j = lookup[c] # lowercase.index(c) for cc in lowercase[j+1:]: for i in scramble(left + cc + right): yield i else: def edit_distance_one(word): for i in range(len(word)): left, c, right = word[0:i], word[i], word[i+1:] j = lookup[c] # lowercase.index(c) for cc in lowercase[j+1:]: yield left + cc + right candgen = ((word, cand) for word in sorted(words) for cand in edit_distance_one(word) if cand in words) G.add_nodes_from(words) for word, cand in candgen: G.add_edge(word, cand) return G
def write_seq(fh, ending_letter): ending_index = ascii_lowercase.index(ending_letter.lower()) ending_index += 1 for letter in ascii_lowercase[:ending_index]: fh = add_letter(fh, letter) return fh
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
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
def main(): i, j = 10, 0 while True: if (i + j) % 26 == al.index("s"): print i, j break j += 1
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)
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)
def choose_role(self): """Flexible choice prompt for as many roles as the system has""" roles = [r for r in self.cork.list_roles()] formatted = ['{0} (level {1})'.format(*r) for r in roles] condensed = '\n'.join(['{0}.) {1}'.format(*t) for t in zip(alpha, formatted)]) new_role = input('choose: \n{0}\n\n'.format(condensed)) if new_role not in alpha[:len(roles)]: raise Exception('invalid role choice') return roles[alpha.index(new_role)][0]
def setlight(where, what): if not 'coordinate' in where: # ignore if it is not on the board return coord = where['coordinate'] x = ascii_lowercase.index(coord[0]) y = int(coord[1]) note = (y * 16) + x color = colors[what] if what in colors else 0 message = mido.Message('note_on', note=note, velocity=color) output.send(message)
def atbash(text, mode): text = text.lower() output = "" for c in text: if c in abc: index = abc.index(c) output += cba[index] elif c.isdigit(): output += c else: pass return format_output(output, mode)
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)
def sauce(word): order = [] for i in word: order.append(letters.index(i)) if order == sorted(order, key=int): return "IN ORDER" if order == sorted(order, key=int, reverse=True): return "REVERSE ORDER" else: return "NOT IN ORDER"
# -*- coding: utf-8 -*- """ Created on Tue Mar 12 16:40:13 2019 @author: standl """ import itertools as it from string import ascii_lowercase as lowercase lookup = dict((c, lowercase.index(c)) for c in lowercase) def flat(permu): flatt = [] for i in edit_distance_one("hello"): for j in i: flatt.append(''.join(j)) return flatt def edit_distance_one(word): for i in range(len(word)): left, c, right = word[0:i], word[i], word[i + 1:] j = lookup[c] # lowercase.index(c) for cc in lowercase[j + 1:]: yield (it.permutations(left + cc + right, r=None)) #perm = it.permutations("hello", r=None)
Numbers representing letters (n <= 26) will always be separated by letters, for all test cases: "a26b" may be tested, but not "a262b" "cjw9k" may be tested, but not "cjw99k" A list named alphabet is preloaded for you: ['a', 'b', 'c', ...] A dictionary of letters and their number equivalent is also preloaded for you called alphabetnums = {'a': '1', 'b': '2', 'c': '3', ...} """ from string import ascii_lowercase as abc import re alphabet = list(abc) alphabetnums = {c: str(abc.index(c)+1) for c in abc} # def AlphaNum_NumAlpha(string): # res = '' # for x in re.findall(r'\d+|\D', string): # if x.isdigit(): # res += alphabet[int(x)-1] # else: # res += str(int(alphabetnums[x])+1) # return res def AlphaNum_NumAlpha(string): return ''.join(alphabet[int(x)-1] if x.isdigit() else str(int(alphabetnums[x])) for x in re.findall(r'\d+|\D', string))
ncaqqahcc ar hmjhgec, cewenhdq lcgc tgd snwpt sgeh wlsvdr ndc rhcdfa, ync aamg gn xnul wpt""" # hints: convert to numbers; convert binary to decimal #cabbage = cycle("cabbage") #for c in puzzle3: # print((ord(c)+ ord(next(cabbage))), end='') #for c in puzzle3: # try: # print(int(c, 35)) # except ValueError: # print(c) cabbage = cycle([ascii_lowercase.index(c) for c in 'cabbage']) puzzle3nums = [] for c in puzzle3: try: puzzle3nums.append(ascii_lowercase.index(c) + next(cabbage)) except ValueError: puzzle3nums.append(c) print(puzzle3nums) for i in puzzle3nums: try: print(ascii_lowercase[i % 26], end='') except TypeError: print(i, end='') print('\n') puzzle4 = """8813191238677333954665809213349646122194
from string import ascii_lowercase word = "name" result = [] a = [ 1, 3, 1, 3, 1, 4, 1, 3, 2, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5 ] for i in word: result.append(a[ascii_lowercase.index(i)]) print(result) h = max(result) print(h) pdf = h * len(word) print(pdf)
def decrypt(char, nr): if char == "-": return " " return az[(az.index(char) + nr) % 26]
# Set cipher text string ciphertext = "" # Set N = 25 i.e n will equal z in the ascii lowercase alphabet where a = 0 # Utilize this when it comes to the formula for substitution [n - index] = new character n = 25 # Loop through each character. Make lower to avoid exceptions. for c in plaintext.lower(): # Verify if a space / not an alpha character added. If so, add a space to the ciphertext if not c.isalpha(): ciphertext += " " continue # Use formula of N - (index of c). i.e. when c is a, index will be 0. so n(25)-0 = 25. # This means our character will be z ciphertext += ascii_lowercase[n - (ascii_lowercase.index(c))] print("The cipher text is: ", ciphertext) print("\nTo reverse, simply repeat: ") plaintext = "" for x in ciphertext: if not x.isalpha(): plaintext += " " continue plaintext += ascii_lowercase[n - (ascii_lowercase.index(x))] print("The deciphered text is: ", plaintext)
def to_encrypt(text, delta): return ''.join([ ascii[(ascii.index(char) + delta) % len(ascii)] if char in ascii else char for char in text ])
def handle_call(self, item, first_line, market=None): "Handles a judge calling a market." option_label, market_id = "", "" for word in first_line[1:]: word = word.lower() if len(word ) == 1 and word in ascii_lowercase: # determines the label option_label = word elif word.startswith("#") and len(word) > 1 and word[1:].isdigit(): market_id = int(word[1:]) # determines the market id if not option_label: raise Exception("Option not specified") for m in self.mp.markets: if m.id == market_id: market = m if not market: raise Exception("Market not specified or inferred.") if not market.is_open: raise Exception("Market is closed.") try: requested_stock = market.stocks[ascii_lowercase.index( option_label)] except IndexError: raise Exception("Invalid option") if item.author.name in market.category.judges: market.call(requested_stock) self.changed_markets.add(market) # Just finding all the players who bought into this market players = {} for option in market.stocks: for name in option.shares.keys(): num_stocks = option.shares[name]["amount"] if name not in players.keys(): players[name] = [] if num_stocks > 0: players[name].append(option) # Send each player a message about their wins/loses in this market have_won = False for player, options in players.items(): message = "|Market ID|Option|Amount|Win/Lost|\n" message += "|:-- |:-- | :-: | :-: |\n" for o in options: if not name in o.shares: continue message += "|{}|{}|{}|{}|\n".format( o.market.id, o.text, o.shares[name]["amount"], "Win" if o is requested_stock else "Lose") message += "\n\n" after = self.mp.bank[name] #TODO: keyerror if no shares if not name in requested_stock.shares: continue before = self.mp.bank[ name] - requested_stock.shares[name]["amount"] * 100 difference = requested_stock.shares[name]["amount"] bank_table = "|Player|Bank Before|Bank After|Difference|\n" bank_table += "|:-- | --:| --:| :-: |\n" bank_table += "|{} |{:.2f} |{:.2f} |{:.2f} |\n\n".format( name, before, after, difference) message += bank_table redditor = self.reddit.redditor(name) redditor.message( "Market #{} has been settled.".format(market.id), message) logging.info("{} called {} for {}".format(item.author.name, market.id, option_label)) self.change_comments(market, True) del self.updanda_dict[market]
def alphabet_position(text): ans = [] for word in text.lower(): if word in ascii_lowercase: ans.append(ascii_lowercase.index(word) + 1) return ' '.join(map(str, ans))
def encode(s, k): l = [lc.index(i) for i in s.lower() if i.isalpha() ] #Creates a list of indices of all letters in the input string return ''.join([ uc[(i + k) % 26] for i in l if not str(i).isspace() ]) #Joins the string formed by shifting all the indices by key
def get_index(char): try: return ascii_lowercase.index(char) except: return 26
def _get_key_idx(self, idx): "Returns a upper or lower case caracter index corresponding to the input caracter position in the key word" c = self.key[idx % len(self.key)] return abc.index(c) if c in abc else ABC.index(c)
def get_coefficient(self, character): index = ascii_lowercase.index(character) if not self.acceding: return self.TOTAL_NUMBER_ALPHABET - index - 1 return index
def handle_buy(self, item, first_line, market=None): "Handles a player buying a share in a market." option_label, amount_label, market_id = "", "1", "" command = first_line[0].lower().strip(".!,?") # Quickly parse through the arguments given. for word in first_line[1:]: word = word.lower() if len(word) == 1 and word.lower( ) in ascii_lowercase: # finds the chosen option option_label = word.lower() elif (word.startswith("$") and word[1:].isdigit() ) or word.isdigit(): # finds the amount to buy amount_label = word #TODO: what if no "sell"? elif word == "all" and command == "sell": amount_label = "all" elif word.startswith("#"): # finds the id for the market market_id = int(word[1:]) if not option_label: raise Exception("No option specified.") # we find which market it is... if market_id: for m in self.mp.markets: if m.id == market_id: market = m if not market: raise Exception("Market not specified or inferred.") if not market.is_open: raise Exception("Market is closed") requested_stock = market.stocks[ascii_lowercase.index(option_label)] name = item.author.name if amount_label.startswith("$"): amount = int(amount_label[1:]) if command == "sell": amount *= -1 amount_of_shares = self.get_amount_from_money( command, amount, item, market, requested_stock) elif amount_label == "all": amount_of_shares = -1 * requested_stock.shares[name]["amount"] else: amount_of_shares = int(amount_label) if command == "sell": amount_of_shares *= -1 self.mp.create_new_player(name, 20000) before = self.mp.bank[name] requested_stock.buy(name, amount_of_shares) self.changed_markets.add(market) logging.info("{} bought {} shares of {}:{}".format( name, amount_of_shares, market.id, option_label)) self.message_player_bought_shares(item.author, before, requested_stock, amount_of_shares) # If this was a comment, potentially make a new comment reply and watch it. if type(item) is praw.models.reddit.comment.Comment: if not self.check_if_submission_watched(item, market): updandum = item.reply( self.create_market_view( market, submission=self.updanda_dict[market]["submission"], viewtype="comment") + self.footer) self.add_updandum(updandum, market)
def turn(self): current_index = alphabet.index(self.current_position) self.setCurrentPosition(alphabet[(current_index + 1) % 26])
def parse_bomb_location(loc): loc = loc.lower().strip().replace(" ", "") row = ascii_lowercase.index(loc[0]) col = digits.index(loc[1]) return col, row
# ascii value find: >>> ord('a') 97 >>> chr(97) 'a' >>> chr(ord('a') + 3) 'd' >>> small_alph = 'abcdefghijklmnopqrstuvwxyz' capital_alph = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' for letter in message: if letter.lower() in ascii_lowercase: if letter.islower(): pos = ascii_lowercase.index(letter) encoded_message += ascii_lowercase[(pos + shift) % 26] else: pos = ascii_uppercase.index(letter) encoded_message += ascii_uppercase[(pos + shift) % 26] # finding common prefix def common_start(sa, sb): """ returns the longest common substring from the beginning of sa and sb """ def _iter(): for a, b in zip(sa, sb):
def dec(ch): if ch.isdigit(): return ch return ascii_lowercase[a * (ascii_lowercase.index(ch) - b) % 26]
def read_position(self, target): from string import ascii_lowercase as lett lett = lett[:10] target = target.lower() return lett.index(target[0]) + 1, int(target[1:])
def is_real(data): freq = Counter(data[0]).most_common() s = sorted(freq, reverse=True, key=lambda x: (x[1], 25 - ascii_lowercase.index(x[0]))) return data[2] == "".join(x[0] for x in s[:5])
def f_score(word): score = 0 for letter in word: score += (ascii_lowercase.index(letter) + 1) return score
def to_pos(coord): horiz_index = ascii_lowercase.index(coord[0]) vert_index = int(coord[1]) - 1 return (horiz_index, vert_index)
def enc(ch): if ch.isdigit(): return ch if not ch.isalnum(): return "" return ascii_lowercase[(a * ascii_lowercase.index(ch) + b) % 26]
def Keyboard(self, key): for letter in ascii_lowercase: if key == eval("Keys.K_" + letter): self.alphabet[ascii_lowercase.index(letter)] = True
def words_to_marks(s): return sum([ascii_lowercase.index(i) + 1 for i in s])
def from_chars(cls, chars): positions = [letters.index(char) for char in chars] return cls(positions)
def string_to_num(string): from string import ascii_lowercase as alpha return sum([alpha.index(x) + 1 for x in string])
def cake(candles, debris): if not candles: return "That was close!" score = sum(ord(c) if i % 2 == 0 else ascii_lowercase.index(c) + 1 for i, c in enumerate(debris)) return "Fire!" if score > 0.7 * candles else "That was close!"
from string import ascii_lowercase as alpha nameValue = lambda name: sum([alpha.index(l) + 1 for l in name.lower()]) totalValue = lambda names: sum([(nameValue(name) * (i + 1)) for i, name in enumerate(names)]) def extractNames(file_location, mode='r'): try: names = '' with open(file_location, mode) as file: names = [name.strip('"') for name in file.readline().split(',')] names.sort() except FileNotFoundError: print(f'No se pudo abrir el archivo {file_location}') except: print('Ocurrio un error inesperado') return names def __main__(): archivo = 'names.txt' names = extractNames(archivo) if names != '': names_score = totalValue(names) print(f'El valor total de los nombres es {names_score}') else: print('Verifique la existencia del archivo e intente de nuevo.')
def alphabet_position(letter): assert len(letter) == 1, 'Only give me one letter please' return lowers.index(letter.lower())