class WumpusWorldScenario(object): """ Construct a Wumpus World Scenario Objects that can be added to the environment: Wumpus() Pit() Gold() Wall() HybridWumpusAgent(heading) # A propositional logic Wumpus World agent Explorer(program, heading) # A non-logical Wumpus World agent (mostly for debugging) Provides methods to load layout from file Provides step and run methods to run the scenario with the provided agent's agent_program """ def __init__(self, layout_file=None, agent=None, objects=None, width=None, height=None, entrance=None, trace=True): """ layout_file := (<string: layout_file_name>, <agent>) """ if agent != None and not isinstance(agent, Explorer): raise Exception("agent must be type Explorer, got instance of class\n" \ + " {0}".format(agent.__class__)) if layout_file: objects, width, height, entrance = self.load_layout(layout_file) self.width, self.height = width, height self.entrance = entrance self.agent = agent self.objects = objects self.trace = trace self.env = self.build_world(width, height, entrance, agent, objects) def build_world(self, width, height, entrance, agent, objects): """ Create a WumpusEnvironment with dimensions width,height Set the environment entrance objects := [(<wumpus_environment_object>, <location: (<x>,<y>) >, ...] """ env = WumpusEnvironment(width, height, entrance) if self.trace: agent = wumpus_environment.TraceAgent(agent) agent.register_environment(env) env.add_thing(agent, env.entrance) for (obj, loc) in objects: env.add_thing(obj, loc) return env def load_layout(self, layout_file): """ Load text file specifying Wumpus Environment initial configuration Text file is N (rows) by M (columns) grid where each cell in a row consists of M comma-separated cells specs, where each cell contains either: '.' : space (really just a placeholder) or a one or more of (although typically just have one per cell): 'W' : wumpus 'P' : pit 'G' : gold 'A' : wumpus hunter agent (heading specified in agent object) """ if layout_file.endswith('.lay'): layout = self.tryToLoad('layouts/' + layout_file) if not layout: layout = self.tryToLoad(layout_file) else: layout = self.tryToLoad('layouts/' + layout_file + '.lay') if not layout: layout = self.tryToLoad(layout_file + '.lay') if not layout: raise Exception("Could not find layout file: {0}".format(layout_file)) print "Loaded layout '{0}'".format(layout_file) objects = [] entrance = (1,1) # default entrance location ri = len(layout) largest_ci = 0 for row in layout: ci = 0 if row: ri -= 1 row = row.split(',') for cell in row: ci += 1 if ci > largest_ci: largest_ci = ci for char in cell: if char == 'W': objects.append((Wumpus(),(ci,ri))) elif char == 'P': objects.append((Pit(),(ci,ri))) elif char == 'G': objects.append((Gold(),(ci,ri))) elif char == 'A': entrance = (ci,ri) return objects, largest_ci, len(layout)-ri, entrance def tryToLoad(self, fullname): if (not os.path.exists(fullname)): return None f = open(fullname) try: return [line.strip() for line in f] finally: f.close() def step(self): self.env.step() print print "Current Wumpus Environment:" print self.env.to_string() def run(self, steps = 1000): print self.env.to_string() for step in range(steps): if self.env.is_done(): print "DONE." slist = [] if len(self.env.agents) > 0: slist += ['Final Scores:'] for agent in self.env.agents: slist.append(' {0}={1}'.format(agent, agent.performance_measure)) if agent.verbose: if hasattr(agent, 'number_of_clauses_over_epochs'): print "number_of_clauses_over_epochs:" \ +" {0}".format(agent.number_of_clauses_over_epochs) if hasattr(agent, 'belief_loc_query_times'): print "belief_loc_query_times:" \ +" {0}".format(agent.belief_loc_query_times) print ''.join(slist) return self.step() def to_string(self): s = "Environment width={0}, height={1}\n".format(self.width, self.height) s += "Initial Position: {0}\n".format(self.entrance) s += "Actions: {0}\n".format(self.actions) return s def pprint(self): print self.to_string() print self.env.to_string() #------------------------------------------------------------------------------- def world_scenario_hybrid_wumpus_agent_from_layout(layout_filename): """ Create WumpusWorldScenario with an automated agent_program that will try to solve the Hunt The Wumpus game on its own. layout_filename := name of layout file to load """ return WumpusWorldScenario(layout_file = layout_filename, agent = HybridWumpusAgent('north', verbose=True), trace=False) #------------------------------------ # examples of constructing HybridWumpusAgent scenario # specifying objects as list def wscenario_4x4_HybridWumpusAgent(): return WumpusWorldScenario(agent = HybridWumpusAgent('north', verbose=True), objects = [(Wumpus(),(1,3)), (Pit(),(3,3)), (Pit(),(3,1)), (Gold(),(2,3))], width = 4, height = 4, entrance = (1,1), trace=True) #------------------------------------------------------------------------------- def world_scenario_manual_with_kb_from_layout(layout_filename): """ Create WumpusWorldScenario with a manual agent_program and Knowledge Base (see with_manual_kb_program) layout_filename := name of layout file to load """ return WumpusWorldScenario(layout_file = layout_filename, agent = with_manual_kb_program(HybridWumpusAgent('north', verbose=True)), trace=False) #------------------------------------ # examples of constructing manual wumpus agent with KB scenario # specifying objects as list def wscenario_4x4_manual_HybridWumpusAgent(): return WumpusWorldScenario(agent = with_manual_kb_program(HybridWumpusAgent('north', verbose=True)), objects = [(Wumpus(),(1,3)), (Pit(),(3,3)), (Pit(),(3,1)), (Gold(),(2,3))], width = 4, height = 4, entrance = (1,1), trace=True)
Write, Run & Share Python code online using OneCompiler's Python online compiler for free. It's one of the robust, feature-rich online compilers for python language, supporting both the versions which are Python 3 and Python 2.7. Getting started with the OneCompiler's Python editor is easy and fast. The editor shows sample boilerplate code when you choose language as Python or Python2 and start coding.
OneCompiler's python online editor supports stdin and users can give inputs to programs using the STDIN textbox under the I/O tab. Following is a sample python program which takes name as input and print your name with hello.
import sys
name = sys.stdin.readline()
print("Hello "+ name)
Python is a very popular general-purpose programming language which was created by Guido van Rossum, and released in 1991. It is very popular for web development and you can build almost anything like mobile apps, web apps, tools, data analytics, machine learning etc. It is designed to be simple and easy like english language. It's is highly productive and efficient making it a very popular language.
When ever you want to perform a set of operations based on a condition IF-ELSE is used.
if conditional-expression
#code
elif conditional-expression
#code
else:
#code
Indentation is very important in Python, make sure the indentation is followed correctly
For loop is used to iterate over arrays(list, tuple, set, dictionary) or strings.
mylist=("Iphone","Pixel","Samsung")
for i in mylist:
print(i)
While is also used to iterate a set of statements based on a condition. Usually while is preferred when number of iterations are not known in advance.
while condition
#code
There are four types of collections in Python.
List is a collection which is ordered and can be changed. Lists are specified in square brackets.
mylist=["iPhone","Pixel","Samsung"]
print(mylist)
Tuple is a collection which is ordered and can not be changed. Tuples are specified in round brackets.
myTuple=("iPhone","Pixel","Samsung")
print(myTuple)
Below throws an error if you assign another value to tuple again.
myTuple=("iPhone","Pixel","Samsung")
print(myTuple)
myTuple[1]="onePlus"
print(myTuple)
Set is a collection which is unordered and unindexed. Sets are specified in curly brackets.
myset = {"iPhone","Pixel","Samsung"}
print(myset)
Dictionary is a collection of key value pairs which is unordered, can be changed, and indexed. They are written in curly brackets with key - value pairs.
mydict = {
"brand" :"iPhone",
"model": "iPhone 11"
}
print(mydict)
Following are the libraries supported by OneCompiler's Python compiler
Name | Description |
---|---|
NumPy | NumPy python library helps users to work on arrays with ease |
SciPy | SciPy is a scientific computation library which depends on NumPy for convenient and fast N-dimensional array manipulation |
SKLearn/Scikit-learn | Scikit-learn or Scikit-learn is the most useful library for machine learning in Python |
Pandas | Pandas is the most efficient Python library for data manipulation and analysis |
DOcplex | DOcplex is IBM Decision Optimization CPLEX Modeling for Python, is a library composed of Mathematical Programming Modeling and Constraint Programming Modeling |