Ejemplo n.º 1
0
def funcao_palavra_prima(palavra):
    valor = 0
    for letra_da_palavra in palavra:
        valor += ascii_letters.index(letra_da_palavra) + 1
    
    if numero_eh_primo(valor):
        return _IS_PRIME
    else:
        return _IS_NOT_PRIME      
Ejemplo n.º 2
0
def decode(s, shift):
    decoded = ''
    for char in s:
        if char not in punctuation:
            index = ascii_letters.index(char)
            shifted_index = index - shift
            new_char = ascii_letters[shifted_index % ascii_letters_len]
            decoded += new_char
        else:
            decoded += char
    return decoded
Ejemplo n.º 3
0
def encrypt(s):
    from string import ascii_letters
    result = str()
    for c in s:
        if c == 'z': result += 'a'
        elif c == 'Z': result += 'A'
        elif c in ascii_letters:
            result = result + (ascii_letters[(ascii_letters.index(c) + 1) %
                                             len(ascii_letters)])
        else:
            result += c
    return result
Ejemplo n.º 4
0
def encrypt(string: str) -> str:
    """This function encrypts user string using the algorythm: the letter replaced by the following letter"""
    result = str()
    for code in string:
        if code == 'z': result += 'a'
        elif code == 'Z': result += 'A'
        elif code in ascii_letters:
            result = result + (ascii_letters[(ascii_letters.index(code) + 1) %
                                             len(ascii_letters)])
        else:
            result += code
    return result
def encode(file_, shift):
    with open(file_, "r+") as f:
        plain_text = f.read()
        cipher = ""
        for letter in plain_text:
            if letter in letters:
                cipher += letters[(letters.index(letter) + shift) %
                                  len(letters)]
            else:
                cipher += letter
        f.truncate(0)
        f.seek(0)
        f.write(cipher)
def decode(file_, shift):
    with open(file_, "r+") as f:
        cipher_text = f.read()
        plain_text = ""
        for letter in cipher_text:
            if letter in letters:
                plain_text += letters[(letters.index(letter) - shift) %
                                      len(letters)]
            else:
                plain_text += letter
        f.truncate(0)
        f.seek(0)
        f.write(plain_text)
Ejemplo n.º 7
0
def StringPlusOne(word):
    """Adds one to the last numbers in a string.
    Parameters:
      word (str): String to process.
    Returns:
      word(str): String thats been iterated
    """
    try:
        if word[-2] == ' ' or word[-2] == '-' or word[-2] == '_' or word[-2].isdigit():
            if word[-1] in letters:
                s = word[-1]
                word = word[:-1]
                s=letters[(letters.index(s)+1)%len(letters)]
                word += s
                return word

        suffixNumber = ''
        splitIndex = 0
        for i, l in enumerate(word[::-1]):
            try: #check if suffix is number
                int(l)
                suffixNumber += l
            except:
                splitIndex = i
                break
        suffixNumber = suffixNumber[::-1]
        if len(suffixNumber) < 1:
            return word
        newNum = int(suffixNumber)+1
        finalNum = (len(suffixNumber)-len(str(newNum)))*'0' + str(newNum)
        return word[:len(word)-splitIndex] + finalNum

        s='a'
        if s in letters:
            s=letters[(letters.index(s)+1)%len(letters)]
    except:
        print "StringPlusOne Error"
        return None
def atbash_cipher(input_text, decode = False):
    output_text = ''
    for char in input_text:
        if char in ascii_letters:
            char_index = ascii_letters.index(char)

            if decode == True:
                char = ascii_letters[(26 - char_index - 1)]
            else:
                char = ascii_letters[(- char_index - 1 + 26)]

        output_text += char

    return output_text
Ejemplo n.º 9
0
def encrypt(text: str, offset: int) -> str:
    """
    Encrypts text by replacing each letter with the letter some fixed number
    of positions (the offset) down the alphabet.
    Returns the encrypted text
    """
    result = ''
    for char in text:
        if not char.isalpha():
            result += char
        else:
            index = (ascii_letters.index(char) + offset) % (MAX_OFFSET + 1)
            if char.isupper():
                index += (MAX_OFFSET + 1)
            result += ascii_letters[index]
    return result
def encrypt(character_string, key):
    int_key = int(key)

    new_character_string = ''
    for character in character_string:
        if character in ascii_letters:
            new_character_string = new_character_string + ascii_letters[
                (ascii_letters.index(character) + int_key) % len(ascii_letters)]
        else:
            # cater for non ascii letters (spaces)
            new_character_string += character

    # convert to utf8
    base64_string = str(base64.b64encode(new_character_string.encode("utf-8")), "utf-8")

    print("Encrypted message :", base64_string)
    return base64_string
Ejemplo n.º 11
0
    def put_answers(self, tokens):

        try:
            #answers are indices into a list of choices
            ans = [ascii_letters.index(a) for a in tokens]
        except (ValueError, TypeError):
            raise RuntimeError(out.ANSWERS_INVALID)

        #incorrect number of answers
        if len(ans) > len(self.questions):
            error = out.ANSWERS_TOO_MANY.format(len(self.questions), len(ans))
            raise RuntimeError(error)
        elif len(ans) < len(self.questions):
            error = out.ANSWERS_TOO_FEW.format(len(self.questions), len(ans))
            raise RuntimeError(error)

        for q, a in zip(self.questions, ans):
            self.put_answer(q["q_id"], a)
Ejemplo n.º 12
0
def decyper(s, ignore, _print=False):
    ret = ''
    for c in s:
        if c in ignore:
            if _print:
                print(c, end='')
            ret += c
            continue

        try:
            match_index = ascii_letters.index(c)
        except:
            pass
        else:
            char = ascii_letters[match_index + 2]
            if _print:
                print(char, end='')
            ret += char
    return ret
Ejemplo n.º 13
0
def letter_replace(str): 

    from string import ascii_letters

    replace_str=''
    for c in str:
     if c in ascii_letters:
        replace_str = replace_str + ascii_letters[(ascii_letters.index(c)+1)%len(ascii_letters)] #modulo to roll around to the beginning of the string as that will return 0
     else:
        replace_str = replace_str + c
    
    
    vowel = ['A','E','I','O','U','a','e','i','o','u']
    for i in replace_str:
        if i in vowel:
            replace_str = replace_str.replace(i,i.upper())
            
        
    return replace_str
Ejemplo n.º 14
0
def run_demo(vocab_size=2,
             hidden=3,
             desired_run=3,
             example_length=10,
             num_examples=1000):

    # First show that it works correctly
    param = LstmParam(hidden, vocab_size)
    network = LstmNetwork(param)

    # generate examples
    valid_chars = ascii_letters[:vocab_size]
    for ii in range(num_examples):
        ex_str = "".join(
            random.choice(valid_chars) for x in range(example_length))
        y_val = np.zeros(example_length)

        for jj in range(example_length):
            y_val[jj] = sum(1 if x == 'a' else 0
                            for x in ex_str[:(jj + 1)]) - sum(
                                1 if x != 'a' else 0
                                for x in ex_str[:(jj + 1)])
            y_val[jj] = max(-2.0, min(2.0, y_val[jj]))

        print(ex_str)
        print("".join(str(int(x)) for x in y_val))

        ex = np.zeros((vocab_size, example_length))

        for ii in range(example_length):
            input_seq = np.zeros(vocab_size)
            input_seq[ascii_letters.index(ex_str[ii])] = 1.0
            network.x_list_add(input_seq)
            print("y_pred[" + str(ii) + "] : " +
                  str(network.lstm_node_list[ii].state.h[0]))

        loss = network.y_list_is(y_val, ToyLossLayer)
        print("loss: " + str(loss))
        param.apply_diff(lr=0.1)
        network.x_list_clear()
    return network
def decrypt(encrypted_message, key):
    int_key = int(key)
    # print("Converting integer to base 64 string.... \n\n")

    # convert from base64encrypted_message
    semi_original_string = str(base64.b64decode(encrypted_message), "utf-8")

    print(semi_original_string)

    # print("Converting to original characters (Previous Number of Alphabet)..... \n\n")

    # convert to unmodified string
    original_character_string = ''
    for character in semi_original_string:
        if character in ascii_letters:
            original_character_string = original_character_string + ascii_letters[
                (ascii_letters.index(character) - int_key) % len(ascii_letters)]
        else:
            # cater for non ascii letters (spaces)
            original_character_string += character

    print("Decrypted message :", original_character_string)
    return original_character_string
Ejemplo n.º 16
0
def words_to_marks(s):
    return sum(ascii_letters.index(c.lower()) + 1 for c in s)
Ejemplo n.º 17
0
 def range_alpha(start_letter, end_letter):
     return ascii_letters[ascii_letters.index(start_letter):ascii_letters.
                          index(end_letter) + 1]
Ejemplo n.º 18
0
def name_value(my_list):
    return [
        (i + 1) *
        sum(letters.index(ltr) + 1 if ltr in letters else 0 for ltr in str_)
        for i, str_ in enumerate(my_list)
    ]
Ejemplo n.º 19
0
def rotate(s, amt):
    for pos in (ascii_letters.index(c) for c in s):
        base = (pos // 26) * 26
        yield ascii_letters[base + ((pos + amt) % 26)]
Ejemplo n.º 20
0
# Distributed under terms of the MIT license.

"""

"""

from string import ascii_letters

for i in range(int(input())):
    s1 = input()
    s2 = input()

    sl1 = [0 for i in range(26)]
    sl2 = [0 for i in range(26)]

    for c in s1:
        sl1[ascii_letters.index(c)] += 1
    for c in s2:
        sl2[ascii_letters.index(c)] += 1

    yes = False

    for i in range(26):
        if sl1[i] != 0 and sl2[i] != 0:
            yes = True
    if yes:
        print("YES")
    else:
        print("NO")
        
Ejemplo n.º 21
0
from string import ascii_letters

s='oczmz vmzor jocdi bnojv dhvod igdaz admno ' \
  'ojbzo rcvot jprvi oviyv aozmo cvooj ziejt' \
  'dojig toczr dnzno jahvi fdiyv xcdzq zoczn' \
  'zxjiy'
ns = ''
for c in s:
    if c in ascii_letters:
        ns = ns + ascii_letters[(ascii_letters.index(c) + 5) %
                                len(ascii_letters)]
    else:
        continue

print(ns)
Ejemplo n.º 22
0
"""example4_2 counts down from 20 to 1, and get the next character in alphabet."""

from string import ascii_letters

# Example: count down from 20 to 1
print("Start")
for n in range(20, 0, -1):
    print("n=", n)
print("Stop")

# Example: get the next character in alphabet
message = 'JL'
new_msg = ''
for c in message:
    if c in ascii_letters:
        new_msg = new_msg + ascii_letters[(ascii_letters.index(c) + 1) %
                                          len(ascii_letters)]
    else:
        new_msg += c
print(new_msg)
print(len(ascii_letters))
print(ascii_letters)

a, b = 0, 1
while b < 10:
    print("b=", b)
    a, b = b, a + b
print(a, b)

msg = "Justin Liz"
new_msg = ''
Ejemplo n.º 23
0
def letters_range(let_range: str) -> str:
    let_range = let_range.split('-')
    return letters[letters.index(let_range[0]):letters.index(let_range[1]) + 1]
def find_missing_letter(chars):
    start, stop = ascii_letters.index(chars[0]), ascii_letters.index(chars[-1])
    for i in range(start, stop + 1):
        if ascii_letters[i] not in chars:
            return ascii_letters[i]
Ejemplo n.º 25
0
from string import ascii_letters, printable

users_word = input("Enter your word: ")
new_word_letters = ""
new_word_all_chars = ""
key = 5

for letter in users_word:
    if letter in ascii_letters:
        new_word_letters += ascii_letters[(ascii_letters.index(letter) + key) %
                                          (1 + len(ascii_letters))]
    else:
        new_word_letters += letter

for char in users_word:
    if char in printable:
        new_word_all_chars += printable[(printable.index(char) + key) %
                                        (len(printable) + 1)]
    else:
        new_word_all_chars += char

print("User's word is " + users_word)
print("Generating code in letters only...")
print("Your new word is: " + new_word_letters)
print("...")
print("Generating code using all possible ASCII characters...")
print("Your new word is: " + new_word_all_chars)
Ejemplo n.º 26
0
from string import ascii_letters
from flag import flag

ctoi = lambda x: ascii_letters.index(x)
itoc = lambda x: ascii_letters[x]

key = flag.strip('NCTF{}')
len_key = len(key)

plaintext = open('plaintext.txt', 'r').read()

plain = ''.join(p for p in plaintext if p in ascii_letters)
cipher = ''.join(
    itoc((ctoi(p) + ctoi(key[i % len_key])) % 52) for i, p in enumerate(plain))

open('ciphertext.txt', 'w').write(cipher)
Ejemplo n.º 27
0
def create_grid_rows():
    return [ascii_letters[ascii_letters.index('A') + i] for i in range(0, 9)]
Ejemplo n.º 28
0
from string import ascii_letters

c_file_name = 'avr_map.c'
h_file_name = 'avr_map.h'
LAST_PAD_LETTER = 'D'
NUMBER_OF_PINS_IN_PAD = 8

pads = ascii_letters[ascii_letters.
                     index('A'):ascii_letters.index(LAST_PAD_LETTER) + 1]
pins = range(NUMBER_OF_PINS_IN_PAD)

c_file_text = ''

c_includes = '#include <avr/io.h>\n#include "avr_map.h"'
c_file_text += c_includes

c_pins = []
for pad in pads:
    for pin in pins:
        c_pins.append(
            f'PIN P{pad}{pin} = {{&DDR{pad}, &PORT{pad}, &PIN{pad}, {pin}}};')
    c_pins.append('')
c_pins = '\n'.join(c_pins)
c_file_text += f'\n\n{c_pins}'

h_file_text = ''

h_head = """/*

  AVR pin mapping
Ejemplo n.º 29
0
def alphabet_position(text):
    return " ".join(
        str(ascii_letters.index(x.lower()) + 1) for x in text if x.isalpha())
Ejemplo n.º 30
0
def find_missing_letter(chars):
    idx = ascii_letters.index(chars[0])
    for i, letter in enumerate(chars):
        if i + idx != ascii_letters.index(letter):
            return ascii_letters[i + idx]
Ejemplo n.º 31
0
def find_missing_letter(chars):
    start = ascii_letters.index(chars[0])

    for char, match_char in zip(chars, ascii_letters[start:]):
        if char != match_char:
            return match_char
Ejemplo n.º 32
0
def MainScript():

    config_dir = os.path.expanduser("~") + "/BNKGLWorker/config"
    config = config_dir + "/user_config.ini"
    os.chdir(config_dir)

    #------Not sure if I need this or not-------
    #if not os.path.isfile(config):
    #    os.makedirs(config_dir, exist_ok=True)
    #    ConfigSetup()

    user_config = configparser.ConfigParser()
    user_config.read(config)

    def bankStmntPDFtoExcelConversion():
        cashAmountsRegex = re.compile(r"\d+?,?\d+\.\d{2}\-?")
        cashAmounts = []
        pagesinPDF = bankStatementPDFReader.numPages
        for i in range(pagesinPDF):
            pageObj = bankStatementPDFReader.getPage(i)
            textFromPage = pageObj.extractText()
            textFromPage.replace(',', '')
            for i in cashAmountsRegex.findall(textFromPage):
                cashAmounts.append(i)
        for i in range(len(cashAmounts)):
            if '-' in cashAmounts[i]:
                cashAmounts[i] = '-' + cashAmounts[i][:-1]
            sheetBnkStmnt['C' + str(3 + i)] = cashAmounts[i]

    def extractGLAmountsfromExcel():
        for rowOfGLAmounts in sheetGL[
                sheetGLStartingCell:sheetGLStartingCell[0] +
                str(sheetGL.max_row)]:
            for amount in rowOfGLAmounts:
                amountsOnGL.append(amount.value)

    def extractBankStmntAmountsfromExcel():
        for rowOfBnkStmntAmounts in sheetBnkStmnt['C3':'C' +
                                                  str(sheetBnkStmnt.max_row)]:
            for amount in rowOfBnkStmntAmounts:
                amount = amount.value.replace(",", "")
                amountsOnBnkStmnt.append(amount)

    def exactMatchTester():
        for i in range(len(amountsOnGL)):
            for j in range(len(amountsOnBnkStmnt)):
                try:
                    if float(amountsOnGL[i]) == float(amountsOnBnkStmnt[j]):
                        sheetBnkStmnt['D' + str(3 + j)] = 'Perfect Match!'
                        sheetGL[rLetter +
                                str(int(sheetGLStartingCell[1:]) +
                                    i)] = 'Perfect Match!'
                except:
                    continue

    def alternativeMatchTester():
        for i in range(len(amountsOnGL)):
            for j in range(len(amountsOnBnkStmnt)):
                for k in range(len(amountsOnGL)):
                    try:
                        if float(amountsOnGL[i]) + float(
                                amountsOnGL[k]) == float(amountsOnBnkStmnt[j]):
                            sheetBnkStmnt[
                                'D' +
                                str(3 + j)] = 'Possible match with ' + str(
                                    sheetGLStartingCell[0] + str(i) + ' and ' +
                                    str(k))
                            sheetGL[rLetter +
                                    str(int(sheetGLStartingCell[1:]) +
                                        i)] = 'Possible match with ' + str(
                                            sheetGLStartingCell[0]) + str(k)
                    except:
                        continue

    def saveandCloseExcelBooks():
        bankStatementExcel.save(
            user_config['file_inputs']['bankStatementExcel'])
        bankRecExcel.save(user_config['file_inputs']['bankRecExcel'])

    os.chdir(os.path.expanduser("~") + "/BNKGLWorker")
    bankStatementPDF = open(user_config['file_inputs']['bankStatementPDF'],
                            'rb')
    bankStatementPDFReader = PyPDF2.PdfFileReader(bankStatementPDF)

    bankRecExcel = openpyxl.load_workbook(
        user_config['file_inputs']['bankRecExcel'])
    bankStatementExcel = openpyxl.Workbook()

    sheetGL = bankRecExcel[user_config['excel_settings']['sheetGL']]
    sheetGLStartingCell = user_config['excel_settings']['startingCell']
    sheetBnkStmnt = bankStatementExcel['Sheet']

    amountsOnGL = []
    amountsOnBnkStmnt = []
    rLetter = ascii_letters[ascii_letters.index(sheetGLStartingCell[0]) + 1]

    bankStmntPDFtoExcelConversion()
    extractGLAmountsfromExcel()
    extractBankStmntAmountsfromExcel()
    alternativeMatchTester()
    exactMatchTester()
    saveandCloseExcelBooks()