Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed last month.
Improve this question
How to add support for other languages (diacritics). It's a Scrabble playing code. I would like to add support for diacritics such as ô, ö, Ñ, æ, ą, ć, ę, ł, ń, ó, ś, ź, Ż. What modifications would make it possible. I have the correct word file but the characters are very problematic. Sincerely thank you all for your help
`
from letter_tree import basic_english
from board import sample_board
class SolveState:
def __init__(self, dictionary, board, rack):
self.dictionary = dictionary
self.board = board
self.rack = rack
self.cross_check_results = None
self.direction = None
def before(self, pos):
row, col = pos
if self.direction == 'across':
return row, col - 1
else:
return row - 1, col
def after(self, pos):
row, col = pos
if self.direction == 'across':
return row, col + 1
else:
return row + 1, col
def before_cross(self, pos):
row, col = pos
if self.direction == 'across':
return row - 1, col
else:
return row, col - 1
def after_cross(self, pos):
row, col = pos
if self.direction == 'across':
return row + 1, col
else:
return row, col + 1
def legal_move(self, word, last_pos):
print('found a word:', word)
board_if_we_played_that = self.board.copy()
play_pos = last_pos
word_idx = len(word) - 1
while word_idx >= 0:
board_if_we_played_that.set_tile(play_pos, word[word_idx])
word_idx -= 1
play_pos = self.before(play_pos)
print(board_if_we_played_that)
print()
def cross_check(self):
result = dict()
for pos in self.board.all_positions():
if self.board.is_filled(pos):
continue
letters_before = ""
scan_pos = pos
while self.board.is_filled(self.before_cross(scan_pos)):
scan_pos = self.before_cross(scan_pos)
letters_before = self.board.get_tile(scan_pos) + letters_before
letters_after = ""
scan_pos = pos
while self.board.is_filled(self.after_cross(scan_pos)):
scan_pos = self.after_cross(scan_pos)
letters_after = letters_after + self.board.get_tile(scan_pos)
if len(letters_before) == 0 and len(letters_after) == 0:
legal_here = list('abcdefghijklmnopqrstuvwxyz')
else:
legal_here = []
for letter in 'abcdefghijklmnopqrstuvwxyz':
word_formed = letters_before + letter + letters_after
if self.dictionary.is_word(word_formed):
legal_here.append(letter)
result[pos] = legal_here
return result
def find_anchors(self):
anchors = []
for pos in self.board.all_positions():
empty = self.board.is_empty(pos)
neighbor_filled = self.board.is_filled(self.before(pos)) or \
self.board.is_filled(self.after(pos)) or \
self.board.is_filled(self.before_cross(pos)) or \
self.board.is_filled(self.after_cross(pos))
if empty and neighbor_filled:
anchors.append(pos)
return anchors
def before_part(self, partial_word, current_node, anchor_pos, limit):
self.extend_after(partial_word, current_node, anchor_pos, False)
if limit > 0:
for next_letter in current_node.children.keys():
if next_letter in self.rack:
self.rack.remove(next_letter)
self.before_part(
partial_word + next_letter,
current_node.children[next_letter],
anchor_pos,
limit - 1
)
self.rack.append(next_letter)
def extend_after(self, partial_word, current_node, next_pos, anchor_filled):
if not self.board.is_filled(next_pos) and current_node.is_word and anchor_filled:
self.legal_move(partial_word, self.before(next_pos))
if self.board.in_bounds(next_pos):
if self.board.is_empty(next_pos):
for next_letter in current_node.children.keys():
if next_letter in self.rack and next_letter in self.cross_check_results[next_pos]:
self.rack.remove(next_letter)
self.extend_after(
partial_word + next_letter,
current_node.children[next_letter],
self.after(next_pos),
True
)
self.rack.append(next_letter)
else:
existing_letter = self.board.get_tile(next_pos)
if existing_letter in current_node.children.keys():
self.extend_after(
partial_word + existing_letter,
current_node.children[existing_letter],
self.after(next_pos),
True
)
def find_all_options(self):
for direction in ['across', 'down']:
self.direction = direction
anchors = self.find_anchors()
self.cross_check_results = self.cross_check()
for anchor_pos in anchors:
if self.board.is_filled(self.before(anchor_pos)):
scan_pos = self.before(anchor_pos)
partial_word = self.board.get_tile(scan_pos)
while self.board.is_filled(self.before(scan_pos)):
scan_pos = self.before(scan_pos)
partial_word = self.board.get_tile(scan_pos) + partial_word
pw_node = self.dictionary.lookup(partial_word)
if pw_node is not None:
self.extend_after(
partial_word,
pw_node,
anchor_pos,
False
)
else:
limit = 0
scan_pos = anchor_pos
while self.board.is_empty(self.before(scan_pos)) and self.before(scan_pos) not in anchors:
limit = limit + 1
scan_pos = self.before(scan_pos)
self.before_part("", self.dictionary.root, anchor_pos, limit)
solver = SolveState(basic_english(), sample_board(), ['e', 'f', 'f', 'e', 'c', 't'])
print(solver.board)
print()
solver.find_all_options()
`
You can use a simply module Unidecode for this.
from unidecode import unidecode
print(unidecode('žeuš'))
Output:
>>> zeus
Related
This is a password generator, I couldn't really determine where the problem is, but from the output, I could say it's around turnFromAlphabet()
The function turnFromAlphabet() converts an alphabetical character to its integer value.
The random module, I think doesn't do anything here as it just decides whether to convert a character in a string to uppercase or lowercase. And if a string is in either, when sent or passed to turnFromAlphabet() it is converted to lowercase first to avoid errors but there are still errors.
CODE:
import random
import re
#variables
username = "oogisjab" #i defined it already for question purposes
index = 0
upperOrLower = []
finalRes = []
index2a = 0
#make decisions
for x in range(len(username)):
decision = random.randint(0,1)
if(decision is 0):
upperOrLower.append(True)
else:
upperOrLower.append(False)
#Apply decisions
for i in range(len(username)):
if(upperOrLower[index]):
finalRes.append(username[index].lower())
else:
finalRes.append(username[index].upper())
index+=1
s = ""
#lowkey final
s = s.join(finalRes)
#reset index to 0
index = 0
def enc(that):
if(that is "a"):
return "#"
elif(that is "A"):
return "4"
elif(that is "O"):
return "0" #zero
elif(that is " "):
# reduce oof hackedt
decision2 = random.randint(0,1)
if(decision2 is 0):
return "!"
else:
return "_"
elif(that is "E"):
return "3"
else:
return that
secondVal = []
for y in range(len(s)):
secondVal.append(enc(s[index]))
index += 1
def turnFromAlphabet(that, index2a):
alp = "abcdefghijklmnopqrstuvwxyz"
alp2 = list(alp)
for x in alp2:
if(str(that.lower()) == str(x)):
return index2a+1
break
else:
index2a += 1
else:
return "Error: Input is not in the alphabet"
#real final
finalOutput = "".join(secondVal)
#calculate some numbers and chars from a substring
amount = len(finalOutput) - round(len(finalOutput)/3)
getSubstr = finalOutput[-(amount):]
index = 0
allFactors = {
};
#loop from substring
for x in range(len(getSubstr)):
hrhe = re.sub(r'\d', 'a', ''.join(e for e in getSubstr[index] if e.isalnum())).replace(" ", "a").lower()
print(hrhe)
#print(str(turnFromAlphabet("a", 0)) + "demo")
alpInt = turnFromAlphabet(hrhe, 0)
print(alpInt)
#get factors
oneDimensionFactors = []
for p in range(2,alpInt):
# if mod 0
if(alpInt % p) is 0:
oneDimensionFactors.append(p)
else:
oneDimensionFactors.append(1)
indexP = 0
for z in oneDimensionFactors:
allFactors.setdefault("index{0}".format(index), {})["keyNumber"+str(p)] = z
index+=1
print(allFactors)
I think that you are getting the message "Error: input is not in the alphabet" because your enc() change some of your characters. But the characters they becomes (for example '#', '4' or '!') are not in your alp variable defined in turnFromAlphabet(). I don't know how you want to fix that. It's up to you.
But I have to say to your code is difficult to understand which may explain why it can be difficult for you to debug or why others may be reluctant to help you. I tried to make sense of your code by removing code that don't have any impact. But even in the end I'm not sure I understood what you tried to do. Here's what I understood of your code:
import random
import re
#username = "oogi esjabjbb"
username = "oogisjab" #i defined it already for question purposes
def transform_case(character):
character_cases = ('upper', 'lower')
character_to_return = character.upper() if random.choice(character_cases) == 'upper' else character.lower()
return character_to_return
username_character_cases_modified = "".join(transform_case(current_character) for current_character in username)
def encode(character_to_encode):
translation_table = {
'a' : '#',
'A' : '4',
'O' : '0',
'E' : '3',
}
character_translated = translation_table.get(character_to_encode, None)
if character_translated is None:
character_translated = character_to_encode
if character_translated == ' ':
character_translated = '!' if random.choice((True, False)) else '_'
return character_translated
final_output = "".join(encode(current_character) for current_character in username_character_cases_modified)
amount = round(len(final_output) / 3)
part_of_final_output = final_output[amount:]
all_factors = {}
for (index, current_character) in enumerate(part_of_final_output):
hrhe = current_character
if not hrhe.isalnum():
continue
hrhe = re.sub(r'\d', 'a', hrhe)
hrhe = hrhe.lower()
print(hrhe)
def find_in_alphabet(character, offset):
alphabet = "abcdefghijklmnopqrstuvwxyz"
place_found = alphabet.find(character)
if place_found == -1 or not character:
raise ValueError("Input is not in the alphabet")
else:
place_to_return = place_found + offset + 1
return place_to_return
place_in_alphabet = find_in_alphabet(hrhe, 0)
print(place_in_alphabet)
def provide_factors(factors_of):
for x in range(1, int(place_in_alphabet ** 0.5) + 1):
(quotient, remainder) = divmod(factors_of, x)
if remainder == 0:
for current_quotient in (quotient, x):
yield current_quotient
unique_factors = set(provide_factors(place_in_alphabet))
factors = sorted(unique_factors)
all_factors.setdefault(f'index{index}', dict())[f'keyNumber{place_in_alphabet}'] = factors
print(all_factors)
Is near what your wanted to do?
I have a problem where I am trying to make a word search puzzle generator and I have run into multiple problems throughout the day. (Thanks to this community I've solved most of them!)
I have another problem now where I have a loop that should find a spot to place a word, place it, and move on to the next word. Instead it is finding all possible spots the word can be and placing the word in all of them. I only want each word to appear once.
I thought that the lines while not placed and placed = true would handle this but it isn't working.
Thanks in advance for any help, and here is my code:
import tkinter as tk
import random
import string
handle = open('dictionary.txt')
words = handle.readlines()
handle.close()
grid_size = 10
words = [ random.choice(words).upper().strip() \
for _ in range(5) ]
print ("The words are:")
print(words)
grid = [ [ '_' for _ in range(grid_size) ] for _ in range(grid_size) ]
orientations = [ 'leftright', 'updown', 'diagonalup', 'diagonaldown' ]
class Label(tk.Label):
def __init__(self, parent, **kwargs):
super().__init__(parent, **kwargs, font=("Courier", 44))
#self.bind('<Button-1>', self.on_click)
#def on_click(self, event):
#w = event.widget
#row, column = w.grid_info().get('row'), w.grid_info().get('column')
#print('coord:{}'.format((row, column)))
#w.destroy()
class App(tk.Tk):
def __init__(self):
super().__init__()
for row in range(grid_size):
for column in range(grid_size):
for word in words:
word_length = len(word)
placed = False
while not placed:
orientation = random.choice(orientations)
if orientation == 'leftright':
step_x = 1
step_y = 0
if orientation == 'updown':
step_x = 0
step_y = 1
if orientation == 'diagonalup':
step_x = 1
step_y = -1
if orientation == 'diagonaldown':
step_x = 1
step_y = 1
x_position = random.randrange(grid_size)
y_position = random.randrange(grid_size)
ending_x = x_position + word_length*step_x
ending_y = y_position + word_length*step_y
if ending_x < 0 or ending_x >= grid_size: continue
if ending_y < 0 or ending_y >= grid_size: continue
failed = False
for i in range(word_length):
character = word[i]
new_position_x = x_position + i*step_x
new_position_y = y_position + i*step_y
character_at_new_position = grid[new_position_x][new_position_y]
if character_at_new_position != '_':
if character_at_new_position == character:
continue
else:
failed = True
break
if failed:
continue
else:
for i in range(word_length):
character = word[i]
new_position_x = x_position + i*step_x
new_position_y = y_position + i*step_y
grid[new_position_x][new_position_y] = character
if ( grid[row][column] == grid[new_position_x][new_position_y] ):
grid[row][column] = grid[new_position_x][new_position_y]
Label(self, text=character).grid(row=row, column=column)
placed = True
#if ( grid[row][column] == '_' ):
#txt = random.SystemRandom().choice(string.ascii_uppercase)
#Label(self, text=txt).grid(row=row, column=column)
if __name__ == '__main__':
App().mainloop()
I can assure you that your expectation of while loop is correct.
In [1]: placed = False
In [2]: i = 0
In [3]: while not placed:
...: i += 1
...: print(i)
...: if i == 5:
...: placed = True
...:
1
2
3
4
5
Given that, my suspicion is that your code always hit continue, which means it never hits the statement placed = True, hence infinite loop. So I suggest you check if your condition to continue is as expected.
Hope this helps!
I am trying to implement iterative deepening search for the k - puzzle. I have managed to find the goal node. However, I am unable to backtrack from the goal node to the start node to find the optimal moves. I think it has something to do with repeated states in IDS. Currently, I am keeping track of all visited states in the IDS algorithm.
This is the current implementation of my algorithm. In the code below, moves_dict stores each node's previous state and move to get to current state.
import os
import sys
from itertools import chain
from collections import deque
# Iterative Deepening Search (IDS)
class Node:
def __init__(self, state, empty_pos = None, depth = 0):
self.state = state
self.depth = depth
self.actions = ["UP", "DOWN", "LEFT", "RIGHT"]
if empty_pos is None:
self.empty_pos = self.find_empty_pos(self.state)
else:
self.empty_pos = empty_pos
def find_empty_pos(self, state):
for x in range(n):
for y in range(n):
if state[x][y] == 0:
return (x, y)
def find_empty_pos(self, state):
for x in range(n):
for y in range(n):
if state[x][y] == 0:
return (x, y)
def do_move(self, move):
if move == "UP":
return self.up()
if move == "DOWN":
return self.down()
if move == "LEFT":
return self.left()
if move == "RIGHT":
return self.right()
def swap(self, state, (x1, y1), (x2, y2)):
temp = state[x1][y1]
state[x1][y1] = state[x2][y2]
state[x2][y2] = temp
def down(self):
empty = self.empty_pos
if (empty[0] != 0):
t = [row[:] for row in self.state]
pos = (empty[0] - 1, empty[1])
self.swap(t, pos, empty)
return t, pos
else:
return self.state, empty
def up(self):
empty = self.empty_pos
if (empty[0] != n - 1):
t = [row[:] for row in self.state]
pos = (empty[0] + 1 , empty[1])
self.swap(t, pos, empty)
return t, pos
else:
return self.state, empty
def right(self):
empty = self.empty_pos
if (empty[1] != 0):
t = [row[:] for row in self.state]
pos = (empty[0] , empty[1] - 1)
self.swap(t, pos, empty)
return t, pos
else:
return self.state, empty
def left(self):
empty = self.empty_pos
if (empty[1] != n - 1):
t = [row[:] for row in self.state]
pos = (empty[0] , empty[1] + 1)
self.swap(t, pos, empty)
return t, pos
else:
return self.state, empty
class Puzzle(object):
def __init__(self, init_state, goal_state):
self.init_state = init_state
self.state = init_state
self.goal_state = goal_state
self.total_nodes = 1
self.total_visited = 0
self.max_frontier = 0
self.depth = 0
self.visited = {}
self.frontier_node = []
self.move_dict = {}
def is_goal_state(self, node):
return node.state == self.goal_state
def is_solvable(self):
flat_list = list(chain.from_iterable(self.init_state))
num_inversions = 0
for i in range(max_num):
current = flat_list[i]
for j in range(i + 1, max_num + 1):
next = flat_list[j]
if current > next and next != 0:
num_inversions += 1
if n % 2 != 0 and num_inversions % 2 == 0:
return True
elif n % 2 == 0:
row_with_blank = n - flat_list.index(0) // n
return (row_with_blank % 2 == 0) == (num_inversions % 2 != 0)
else:
return False
def succ(self, node, frontier):
succs = deque()
node_str = str(node.state)
self.visited[node_str] = node.depth
self.total_visited += 1
frontier -= 1
for m in node.actions:
transition, t_empty = node.do_move(m)
transition_str = str(transition)
transition_depth = node.depth + 1
if transition_str not in self.visited or transition_depth < self.visited[transition_str]:
self.total_nodes += 1
transition_depth = node.depth + 1
transition_str = str(transition)
self.move_dict[transition_str] = (node_str, m)
succs.append(Node(transition, t_empty, transition_depth))
frontier += 1
return succs , frontier
def depth_limited(self, node, depth, frontier):
if self.is_goal_state(node):
return node
if node.depth >= depth:
return None
succs, frontier = self.succ(node, frontier)
self.max_frontier = max(self.max_frontier, frontier)
while succs:
result = self.depth_limited(succs.popleft(), depth, frontier)
if result is not None:
return result
return None
def solve(self):
if not self.is_solvable():
return ["UNSOLVABLE"]
goal_node = None
while goal_node is None:
goal_node = self.depth_limited(Node(self.init_state), self.depth, 1)
if goal_node is not None:
break
# reset statistics
self.visited = {}
self.total_nodes = 1
self.move_dict = {}
self.depth += 1
print self.depth
print "out"
print goal_node.state
solution = deque()
init_str = str(self.init_state)
current_str = str(goal_node.state)
while current_str != init_str:
current_str, move = self.move_dict[current_str]
solution.appendleft(move)
print "Total number of nodes generated: " + str(self.total_nodes)
print "Total number of nodes explored: " + str(self.total_visited)
print "Maximum number of nodes in frontier: " + str(self.max_frontier)
print "Solution depth: " + str(self.depth)
return solution
I have been cracking my head for awhile now. I use a hashMap that maps the state string to its depth and when adds the node whenever the same state appears in a shallower depth
EDIT
Optimal solution depth for this test case is 22.
init state: [[1,8,3],[5,2,4],[0,7,6]]
Goal state: [[1,2,3],[4,5,6],[7,8,0]]
im not going to implement your k puzzle but consider the following datastruct
d = {'A':{'B':{'Z':7,'Q':9},'R':{'T':0}},'D':{'G':1}}
def find_node(search_space,target,path_so_far=None):
if not path_so_far: # empty path to start
path_so_far = []
for key,value in search_space.items():
if value == target:
# found the value return the path
return path_so_far+[key]
else:
# pass the path so far down to the next step of the search space
result = find_node(search_space[key],target, path_so_far+[key])
if result:
print("Found Path:",result)
return result
I have a string like '....(((...((...' for which I have to generate another string 'ss(4)h5(3)ss(3)h2(2)ss(3)'.
'.' corresponds to 'ss' and the number of continous '.' is in the bracket.
'(' corresponds to 'h5' and the number of continuos '(' is in the bracket.
Currently I'm able to get the output 'ss(4)h5(3)ss(3)' and my code ignores the last two character sequences.
This is what I have done so far
def main():
stringInput = raw_input("Enter the string:")
ssCount = 0
h5Count = 0
finalString = ""
ssString = ""
h5String = ""
ssCont = True
h5Cont = True
for i in range(0, len(stringInput), 1):
if stringInput[i] == ".":
h5Cont = False
if ssCont:
ssCount = ssCount + 1
ssString = "ss(" + str(ssCount) + ")"
ssCont = True
else:
finalString = finalString + ssString
ssCont = True
ssCount = 1
elif stringInput[i] == "(":
ssCont = False
if h5Cont:
h5Count = h5Count + 1
h5String = "h5(" + str(h5Count) + ")"
h5Cont = True
else:
finalString = finalString + h5String
h5Cont = True
h5Count = 1
print finalString
main()
How to modify the code to get the desired output?
I don’t know about modifying your existing code, but to me this can be done very succinctly and pythonically using itertools.groupby. Note that I’m not sure if the 'h2' in your expected output is a typo or if it should be 'h5', which I’m assuming.
from itertools import chain, groupby
string = '....(((...((...'
def character_count(S, labels): # this allows you to customize the labels you want to use
for K, G in groupby(S):
yield labels[K], '(', str(sum(1 for c in G)), ')' # sum() counts the number of items in the iterator G
output = ''.join(chain.from_iterable(character_count(string, {'.': 'ss', '(': 'h5'}))) # joins the components into a single string
print(output)
# >>> ss(4)h5(3)ss(3)h5(2)ss(3)
#Kelvin 's answer is great, however if you want to define a function yourself, you could do it like this:
def h5ss(x):
names = {".": "ss", "(": "h5"}
count = 0
current = None
out = ""
for i in x:
if i == current:
count += 1
else:
if current is not None:
out += "{}({})".format(names[current], count)
count = 1
current = i
if current is not None:
out += "{}({})".format(names[current], count)
return out
from informedSearch import *
from search import *
class EightPuzzleProblem(InformedProblemState):
"""
Inherited from the InformedProblemState class. To solve
the eight puzzle problem.
"""
def __init__(self, myList, list = {}, operator = None):
self.myList = list
self.operator = operator
def __str__(self):
## Method returns a string representation of the state.
result = ""
if self.operator != None:
result += "Operator: " + self.operator + ""
result += " " + ' '.join(self.myList[0:3]) + "\n"
result += " " + ' '.join(self.myList[3:6]) + "\n"
result += " " + ' '.join(self.myList[6:9]) + "\n"
return result
def illegal(self):
## Tests whether the state is illegal.
if self.myList < 0 or self.myList > 9: return 1
return 0
def equals(self, state):
## Method to determine whether the state instance
## and the given state are equal.
return ' '.join(self.myList) == ' '.join(state.myList)
## The five methods below perform the tree traversing
def move(self, value):
nList = self.myList[:] # make copy of the current state
position = nList.index('P') # P acts as the key
val = nList.pop(position + value)
nList.insert(position + value, 'P')
nList.pop(position)
nList.insert(position, val)
return nList
def moveleft(self):
n = self.move(-1)
return EightPuzzleProblem(n, "moveleft")
def moveright(self):
n = self.move(1)
return EightPuzzleProblem(n, "moveright")
def moveup(self):
n = self.move(-3)
return EightPuzzleProblem(n, "moveup")
def movedown(self):
n = self.move(+3)
return EightPuzzleProblem(n, "movedown")
def operatorNames(self):
return ["moveleft", "moveright", "moveup", "movedown"]
def enqueue(self):
q = []
if (self.myList.index('P') != 0) and (self.myList.index('P') != 3) and (self.myList.index('P') != 6):
q.append(self.moveleft())
if (self.myList.index('P') != 2) and (self.myList.index('P') != 5) and (self.myList.index('P') != 8):
q.append(self.moveright())
if self.myList.index('P') >= 3:
q.append(self.moveup())
if self.myList.index('P') >= 5:
q.append(self.movedown())
def applyOperators(self):
return [self.moveleft(), self.moveright(), self.moveup(), self.movedown()]
def heuristic():
counter = 0
for i in range(len(self.myList)):
if ((self.myList[i] != goal.myList[i]) and self.myList[i] != 'P'):
## Position of current:
current = goal.myList.index(self.myList[i])
if current < 3: goalRow = 0
elif current < 6: goalRow = 1
else: goalRow = 2
if i < 3: initRow = 0
elif i < 6: initRow = 1
else: startRow = 2
initColumn = i % 3
goalColumn = current % 3
counter += (abs(goalColumn - initColumn) + abs(goalRow - initRow))
return counter
#Uncomment to test the starting states:
init = ['1','3','P','8','2','4','7','6','5'] #A
#init = ['1','3','4','8','6','2','P','7','5'] #B
#init = ['P','1','3','4','2','5','8','7','6'] #C
#init = ['7','1','2','8','P','3','6','5','4'] #D
#init = ['8','1','2','7','P','4','6','5','3'] #E
#init = ['2','6','3','4','P','5','1','8','7'] #F
#init = ['7','3','4','6','1','5','8','P','2'] #G
#init = ['7','4','5','6','P','3','8','1','2'] #H
goal = ['1','2','3','8','P','4','7','6','5'] #goal state
InformedSearch(EightPuzzleProblem(init), EightPuzzleProblem(goal))
I run it and it shows error
line 34, in __str__ result += " " + ' '.join(self.myList[0:3]) + "\n"
TypeError: unhashable type: 'slice'
Any Ideas?
You're setting the "list" to a dictionary as a default value: list = {} in:
def __init__(self, myList, list = {}, operator = None):
and then assigning it to myList with:
self.myList = list
A dictionary cannot be sliced like a list. So when you try to slice it:
self.myList[0:3]
it fails.