Пример #1
0
def read_csv(filename, params):
    from string import ascii_lowercase, ascii_uppercase

    # find out header existance
    header_letters = set(
        ascii_lowercase.replace('e', '') + ascii_uppercase.replace('E', ''))
    with open(filename, 'r') as file:
        first_line = file.readline()
        while 'nan' in first_line:
            first_line = first_line.replace('nan', '')
        header = 0 if len(header_letters & set(first_line)) != 0 else None
    # try to read csv with pandas and fall back to numpy reader if failed
    try:
        import pandas as pd
        data = pd.read_csv(filename, header=header, dtype=params.dtype).values
    except ImportError:
        data = np.genfromtxt(filename,
                             delimiter=',',
                             dtype=params.dtype,
                             skip_header=0 if header is None else 1)

    if data.ndim == 2:
        if data.shape[1] == 1:
            data = data.reshape((data.shape[0], ))

    return data
Пример #2
0
def matriu(keyword):
    matriu = [[0 for y in range(5)] for x in range(5)]
    i = j = 0
    for c in keyword.upper().replace("J", "I") + alph.replace("J", ""):
        if any([c in m for m in matriu]): continue
        matriu[i][j] = c
        j = (j + 1) % 5
        if j == 0: i += 1
    return matriu
Пример #3
0
    def to_regular_grammar(self):
        from .regular_grammar import RegularGrammar

        fa = self.copy()

        relevant_states = {
            state
            for state in fa.states
            if fa._delta.get(state) and state != fa.initial_state
        }

        letters = ascii_uppercase.replace('S', '')
        n = len(letters)
        non_terminals = (letters[i % n] + "'" * (i // n) for i in count())

        table = {fa.initial_state: 'S'}

        for (state, symbol), next_states in fa.transitions.items():
            if state in relevant_states and state not in table:
                table[state] = next(non_terminals)

            for state in next_states:
                if state in relevant_states and state not in table:
                    table[state] = next(non_terminals)

        fa.rename_states(table)

        production_rules = []
        for (state, symbol), next_states in fa.transitions.items():
            for next_state in next_states:
                if fa._delta.get(next_state):
                    production_rules.append((state, symbol, next_state))

                if next_state in fa.accept_states:
                    production_rules.append((state, symbol, ''))

        if fa.initial_state in fa.accept_states:
            production_rules.append(('S', '&', ''))

        def compare_key(rule):
            rule = list(rule)

            for i, r in enumerate(rule):
                if r == 'S':
                    rule[i] = chr(0)

                if r == '&':
                    rule[i] = chr(150)

            return tuple(rule)

        production_rules.sort(key=compare_key)

        return RegularGrammar(production_rules, start_symbol='S')
Пример #4
0
Файл: Q2.py Проект: s-cork/BIO
def grid(word, reverse=False):
    ''' expects a word
    returns a numpy matrix with the word as the secret key
    '''
    word = removeDuplicates(word)
    alphabet = ascii_uppercase.replace('Q', '')
    for letter in word:
        alphabet = alphabet.replace(letter, '')
    LETTERS = list(word + alphabet)
    if reverse:
        LETTERS = list(reversed(LETTERS))
    return np.array(LETTERS).reshape(5, 5)
Пример #5
0
def generate_test_string():
    char = random.choice(letters)
    generated_str = ''
    max_seqs = {}

    for sequence_counter in range(0, random.randint(1, 10)):
        multiplier = random.randint(1, 10)

        if char not in max_seqs or max_seqs[char] < multiplier:
            max_seqs[char] = multiplier
        generated_str += char * multiplier

        char = random.choice(letters.replace(char, ''))

    return generated_str, max_seqs
Пример #6
0
    def _generate_matrix(self):
        self.matrix = [['' for _ in range(5)] for _ in range(5)]
        key = ''.join(self.key.split()).upper().replace('J', 'I')
        letters = ascii_uppercase.replace('J', '')
        index = 0

        for char in key:
            if letters.__contains__(char):
                self.matrix[int(index / 5)][index % 5] = char
                letters = letters.replace(char, '')
                index += 1

        for char in letters:
            self.matrix[int(index / 5)][index % 5] = char
            index += 1
Пример #7
0
alf = ascii_uppercase[2:-2].replace('I','').replace('O','')
# alf = reversed(alf)
# alf = alf[::-1]
fuseau = lambda lon: int(((lon+180)/6+1))
band = lambda lat: (alf[int(lat+80)/8])
# print(alf)
conv = lambda c: (band(c[0]), fuseau(c[1]))
# print((int(mas[0]+80)/8))
# print(band(she[0]))
# print(fuseau(she[1]))
print(conv(mas))
print(conv(moses))

# grid = [[None]*8]*6
# grid = [[[0 for a in range(8)] for b in range(6)] for c in range(20)]
# The identification consists of a column letter (A–Z, omitting I and O) followed by a row letter (A–V, omitting I and O).

####### GRID THING #######
alf2 = ascii_uppercase.replace('O', '').replace('I', '')
alf3 = ascii_uppercase[:-4].replace('O', '').replace('I', '')
lalf2 = len(alf2)
lalf3 = len(alf3)
# print(alf2)
grid = [[(alf2[i%lalf2]+alf3[(j+(5 if int(i/8)%2 else 0))%lalf3]) for i in range(48)] for j in range(20)]
cut = lambda l, n: [l[n*i:n*(i+1)] for i in range(len(l)/n)]
print(cut([i for i in range(25)],4))
fmt = lambda line: ' | '.join(['-'.join(sublist) for sublist in cut(line,8)])

for a in grid[::-1]:
    print(fmt(a))
Пример #8
0
Letters 'I' and 'J' are both 24 in this cipher:

        1	2	3	4	5
    1	A	B	C	D	E
    2	F	G	H	I/J	K
    3	L	M	N	O	P
    4	Q	R	S	T	U
    5	V	W	X	Y	Z

Input will be valid (only spaces and uppercase letters from A to Z), so no
need to validate them.
"""

from string import ascii_uppercase

CHARS = ascii_uppercase.replace('J', '')


def polybius(text):
    """Polybius cipher implementation

    Args:
        text (str): Text to encode

    Returns:
        str: Cipher text

    Examples:
        >>> polybius('A')
        '11'
        >>> polybius('POLYBIUS SQUARE CIPHER')
Пример #9
0
#coding: utf-8

from string import ascii_uppercase
letter_list = ascii_uppercase.replace('I','')
 
#密码表
T_letter=['','','','','']
 
#根据密钥建立密码表
def Create_Matrix(key):
  key=Remove_Duplicates(key)  #移除密钥中的重复字母
  key=key.replace(' ','') #去除密钥中的空格
  
  for ch in letter_list:  #根据密钥获取新组合的字母表
    if ch not in key:
      key+=ch
  
  j=0
  for i in range(len(key)): #将新的字母表里的字母逐个填入密码表中,组成5*5的矩阵
    T_letter[j]+=key[i]     #j用来定位字母表的行
    if 0==(i+1)%5:
      j+=1
 
#移除字符串中重复的字母
def Remove_Duplicates(key):
  key=key.upper() #转成大写字母组成的字符串
  _key=''
  for ch in key:
    if ch=='I':
      ch='J'
    if ch in _key:
Пример #10
0
##########################
#   Author: Aditya Khadse
#   Roll No: BECOA166
##########################

from string import ascii_uppercase as letters
letters = letters.replace('J', '')

def remove_repeat(string):
    charset = set()
    ans = []
    for c in string:
        if c not in charset:
            ans.append(c)
        charset.add(c)
    
    return ''.join(ans)

def remove_punctuation(string):
    punctuations = [
        '.', ',', "'",
        '"', '!', '?', ' '
    ]
    for p in punctuations:
        string = string.replace(p, '')

    return string

def create_matrix(key):
    key.replace('J', 'I')
    key.replace('j', 'I')