コード例 #1
1
ファイル: ic.py プロジェクト: luceatnobis/challenges
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
コード例 #2
0
ファイル: decrypt_ex5.py プロジェクト: chrifpa/goesec
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
コード例 #3
0
ファイル: cipher.py プロジェクト: Ben-Baert/Exercism
 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]
コード例 #4
0
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
コード例 #5
0
ファイル: #9 Caesar Cipher.py プロジェクト: otmichael/Misc
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)
コード例 #6
0
ファイル: vigenere.py プロジェクト: luceatnobis/challenges
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
コード例 #7
0
ファイル: cipher.py プロジェクト: danielnbarbosa/exercism
 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
コード例 #8
0
ファイル: o2.py プロジェクト: luceatnobis/challenges
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)
コード例 #9
0
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))
コード例 #10
0
ファイル: caeser.py プロジェクト: justinoneil/foobar
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
コード例 #11
0
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
コード例 #12
0
 def name_value(name):
     result = 0
     name = name.lower().strip()
     for char in name:
         if char != '"':
             result += lowercase.index(char) 
     return result
コード例 #13
0
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
コード例 #14
0
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
コード例 #15
0
def get_searchTerms():
  searchTerm=get_var('previous_searchTerm')
  if searchTerm==None:
    i=0
  else:
    i=ascii_lowercase.index(searchTerm)+1
  return ascii_lowercase[i:]
コード例 #16
0
ファイル: words.py プロジェクト: MonkStrom/CSCI2961_Lab8
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
コード例 #17
0
ファイル: words.py プロジェクト: stonek4/CSCI2963-01
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
コード例 #18
0
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
コード例 #19
0
ファイル: wordLadder.py プロジェクト: sadeslandes/CSCI2963
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
コード例 #20
0
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
コード例 #21
0
ファイル: example.py プロジェクト: fortrieb/python
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
コード例 #22
0
ファイル: caesar_cipher.py プロジェクト: sr1k4n7h/HackerRank
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
コード例 #23
0
ファイル: modbrute.py プロジェクト: luceatnobis/challenges
def main():
	
	i, j = 10, 0
	
	while True:
		if (i + j) % 26 == al.index("s"):
			print i, j
			break

		j += 1
コード例 #24
0
ファイル: dbftbs_djqifs.py プロジェクト: the-zebulan/CodeWars
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)
コード例 #25
0
ファイル: caesar_cipher.py プロジェクト: the-zebulan/CodeWars
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)
コード例 #26
0
    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]
コード例 #27
0
ファイル: lights.py プロジェクト: SixSecondMonks/pylights
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)
コード例 #28
0
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)
コード例 #29
0
ファイル: rotational_cipher.py プロジェクト: ebiven/exercism
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)
コード例 #30
0
ファイル: 228_easy.py プロジェクト: vesche/snippets
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"
コード例 #31
0
ファイル: bleh.py プロジェクト: lucasfs2020/lab
# -*- 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)
コード例 #32
0
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))

コード例 #33
0
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
コード例 #34
0
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)
コード例 #35
0
ファイル: day04.py プロジェクト: daniel70/AoC
def decrypt(char, nr):
    if char == "-":
        return " "
    return az[(az.index(char) + nr) % 26]
コード例 #36
0
# 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)
コード例 #37
0
ファイル: best-1.py プロジェクト: imtiaz-rahi/Py-CheckiO
def to_encrypt(text, delta):
    return ''.join([
        ascii[(ascii.index(char) + delta) %
              len(ascii)] if char in ascii else char for char in text
    ])
コード例 #38
0
ファイル: redditbot.py プロジェクト: seanicus64/karmapredict
    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]
コード例 #39
0
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))
コード例 #40
0
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
コード例 #41
0
 def get_index(char):
     try:
         return ascii_lowercase.index(char)
     except:
         return 26
コード例 #42
0
ファイル: vigenere.py プロジェクト: perremba/moocpython
 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)
コード例 #43
0
ファイル: hash_map.py プロジェクト: neong83/practice
 def get_coefficient(self, character):
     index = ascii_lowercase.index(character)
     if not self.acceding:
         return self.TOTAL_NUMBER_ALPHABET - index - 1
     return index
コード例 #44
0
ファイル: redditbot.py プロジェクト: seanicus64/karmapredict
    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)
コード例 #45
0
 def turn(self):
     current_index = alphabet.index(self.current_position)
     self.setCurrentPosition(alphabet[(current_index + 1) % 26])
コード例 #46
0
ファイル: board.py プロジェクト: jan-g/remoter
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):
コード例 #48
0
 def dec(ch):
     if ch.isdigit():
         return ch
     return ascii_lowercase[a * (ascii_lowercase.index(ch) - b) % 26]
コード例 #49
0
ファイル: sea_battle2.py プロジェクト: zabulskyy/ucu_projects
 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:])
コード例 #50
0
ファイル: 2.py プロジェクト: krispharper/AdventOfCode
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])
コード例 #51
0
 def f_score(word):
     score = 0
     for letter in word:
         score += (ascii_lowercase.index(letter) + 1)
     return score
コード例 #52
0
def to_pos(coord):
    horiz_index = ascii_lowercase.index(coord[0])
    vert_index = int(coord[1]) - 1
    return (horiz_index, vert_index)
コード例 #53
0
 def enc(ch):
     if ch.isdigit():
         return ch
     if not ch.isalnum():
         return ""
     return ascii_lowercase[(a * ascii_lowercase.index(ch) + b) % 26]
コード例 #54
0
 def Keyboard(self, key):
     for letter in ascii_lowercase:
         if key == eval("Keys.K_" + letter):
             self.alphabet[ascii_lowercase.index(letter)] = True
コード例 #55
0
def words_to_marks(s):
    return sum([ascii_lowercase.index(i) + 1 for i in s])
コード例 #56
0
 def from_chars(cls, chars):
     positions = [letters.index(char) for char in chars]
     return cls(positions)
コード例 #57
0
ファイル: solution_1.py プロジェクト: sjl421/ProjectEuler
def string_to_num(string):
    from string import ascii_lowercase as alpha
    return sum([alpha.index(x) + 1 for x in string])
コード例 #58
0
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!"
コード例 #59
0
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.')
コード例 #60
0
def alphabet_position(letter):
    assert len(letter) == 1, 'Only give me one letter please'
    return lowers.index(letter.lower())