Artificial Intelligence Programs For Programming in Python

Traveling Salesman Problem (TSP)]
Artificial Intelligence Programs For Master Leval Programming in Python

from iter tools import permutations
def distance(point1, point2):
>>> distance([3,4],[0,0])
5.0
>>> distance([3,6],[10,6])
7.0
return ((point1[0] - point2[0])**2 + (point1[1] - point2[1])**2) ** 0.5
def total_distance(points):
all the points are in the given order.
>>> total_distance([[1,2],[4,6]])
5.0
>>> total_distance([[3,6],[7,6],[12,6]])
9.0
return sum([distance(point, points[index + 1]) for index, point in enumerate(points[:-1])])
def travelling_salesman(points, start=None):
Time complexity is O(N!), so never use on long lists.
>>> travelling_salesman([[0,0],[10,0],[6,0]])
([0, 0], [6, 0], [10, 0])
>>> travelling_salesman([[0,0],[6,0],[2,3],[3,7],[0.5,9],[3,5],[9,1]])
([0, 0], [6, 0], [9, 1], [2, 3], [3, 5], [3, 7], [0.5, 9])
"""
if the start is None:
start = points[0]
return min([perm for perm in permutations(points) if perm[0] == start], key=total_distance)
def main():
points = [[0, 0], [1, 5.7], [2, 3], [3, 7],
[0.5, 9], [3, 5], [9, 1], [10, 5]]
print("""The minimum distance to visit all the following points: {}
starting at {} is {}..""".format(
tuple(points),
points[0],
total_distance(travelling_salesman(points))))
if __name__ == "__main__":

main()


Tower of Hanoi

#!/usr/bin/python
count = 0
def hanoi(disk, start='<Tower 1>', end='<Tower 3>', middle='<Tower 2>'):
if disk > 0:
global count
hanoi(disk - 1, start, middle, end)
print("------------------------------------------------------")
count = count + 1
print('|| Step %d : Move disk %d from %s to %s ||' % (count,disk, start, end)) # Move the N disk
print("------------------------------------------------------\n")
hanoi(disk - 1, middle, end, start)
if __name__ == '__main__':
n = input('How many disks you wanna play? ')
print("\n Start Program \n")
hanoi(n)
print(" End Program ")



Prime Number

num = int(input("Enter a number: "))
# prime numbers are greater than 1
if num > 1:
# check for factors
for i in range(2,num):
if (num % i) == 0:
print(num,"is not a prime number")
print(i,"times",num//i,"is",num)
break
else:
print(num,"is a prime number")
# if the input number is less than
# or equal to 1, it is not prime
else:
print(num,"is not a prime number")



Factorial Number
num = 7
factorial = 1
# check if the number is negative, positive or zero
if num < 0:
print("Sorry, factorial does not exist for negative numbers")
elif num == 0:
print("The factorial of 0 is 1")
else:
for i in range(1,num + 1):
factorial = factorial*i
print("The factorial of",num,"is",factorial)


EVEN ODD
num = int(input("Enter a number: "))
if (num % 2) == 0:
print("{0} is Even".format(num))
else:
print("{0} is Odd".format(num))
Puzzle DFS


#!/usr/bin/python
goal_state = [1, 8, 7, 2, 0, 6, 3, 4, 5]
import sys
def display_board( state ):
print "-------------"
print "| %i | %i | %i |" % (state[0], state[3], state[6])
print "-------------"
print "| %i | %i | %i |" % (state[1], state[4], state[7])
print "-------------"
print "| %i | %i | %i |" % (state[2], state[5], state[8])
print "-------------"
def move_up( state ):
new_state = state[:]
index = new_state.index( 0 )
if index not in [0, 3, 6]:
temp = new_state[index - 1]
new_state[index - 1] = new_state[index]
new_state[index] = temp
return new_state
else:
return None
def move_down( state ):
new_state = state[:]
index = new_state.index( 0 )
if index not in [2, 5, 8]:
temp = new_state[index + 1]
new_state[index + 1] = new_state[index]
new_state[index] = temp

return new_state

else:

return None




def move_left( state ):

new_state = state[:]

index = new_state.index( 0 )

if index not in [0, 1, 2]:

temp = new_state[index - 3]

new_state[index - 3] = new_state[index]

new_state[index] = temp

return new_state

else:

return None




def move_right( state ):

new_state = state[:]

index = new_state.index( 0 )

if index not in [6, 7, 8]:

temp = new_state[index + 3]

new_state[index + 3] = new_state[index]

new_state[index] = temp

return new_state

else:

return None




def create_node( state, parent, operator, depth, cost ):

return Node( state, parent, operator, depth, cost )




def expand_node( node, nodes ):

expanded_nodes = []

expanded_nodes.append( create_node( move_up( node.state ), node, node.state, node.depth + 1, 0 ) )

expanded_nodes.append( create_node( move_down( node.state ), node, node.state, node.depth + 1, 0 ) )

expanded_nodes.append( create_node( move_left( node.state ), node, node.state, node.depth + 1, 0 ) )

expanded_nodes.append( create_node( move_right( node.state), node, node.state, node.depth + 1, 0 ) )

expanded_nodes = [node for node in expanded_nodes if node.state != None] #list comprehension!



return expanded_nodes




def dfs( start, goal, depth=10 ):

depth_limit = depth

nodes = []

nodes.append( create_node( start, None, None, 0, 0 ) )

while True:

if len( nodes ) == 0: return None

node = nodes.pop(0)

if node.state == goal:

moves = []

temp = node

while True:

moves.insert(0, temp.operator)

if temp.depth <= 1: break

temp = temp.parent

return moves

if node.depth < depth_limit:

expanded_nodes = expand_node( node, nodes )

expanded_nodes.extend( nodes )

nodes = expanded_nodes



class Node:

def __init__( self, state, parent, operator, depth, cost ):

self.state = state

self.parent = parent

self.operator = operator

self.depth = depth

self.cost = cost




# Main method

def main():

starting_state = [1,8,7,2,0,6,3,4,5]

result = dfs( starting_state, goal_state )

if result == None:

print "No solution found"

elif result == [None]:

print "Start node was the goal!"

else:

result.append(goal_state)

result.pop(0)

for data in result:

display_board(data)

print len(result), " moves"




Comments

Popular posts from this blog

MongoDB Exercises Practice Solution Exercise First

How to create Pagination with PHP and MySql - Codingpoint

Simple Basic Commands For MongoDB