0% found this document useful (0 votes)
89 views17 pages

Theory of Computation Practicals-1

The document outlines practical exercises for a Theory of Computation course, including programs for tokenization, regular expressions, derivation sequences, and finite state machines (FSMs) for specific string patterns. Each practical includes code snippets demonstrating the implementation of concepts such as tokenization using NLTK, regex matching, and designing FSMs to accept strings based on defined rules. The exercises aim to reinforce understanding of computational theory through hands-on programming tasks.

Uploaded by

guptaajiibolte
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
89 views17 pages

Theory of Computation Practicals-1

The document outlines practical exercises for a Theory of Computation course, including programs for tokenization, regular expressions, derivation sequences, and finite state machines (FSMs) for specific string patterns. Each practical includes code snippets demonstrating the implementation of concepts such as tokenization using NLTK, regex matching, and designing FSMs to accept strings based on defined rules. The exercises aim to reinforce understanding of computational theory through hands-on programming tasks.

Uploaded by

guptaajiibolte
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 17

THEORY OF COMPUTATION PRACTICALS:

PRACTICAL 1:

1. Write a program for tokenization of given input


Pip install nltk
Import nltk
nltk.download(‘all’)
import nltk.data
text=”Hello everyone. Welcome to Theory Of Computation Practicals. You are studying
NLP article”
sent_tokenize(text)
tokenizer=nltk.data.load(‘tokenizers/punkt//english.pickle’)
tokenizer.tokenize(text)
Spanish_tokenizer=nltk.data.load(‘tokenizers/punkt//spanish.pickle’)
text=’hola amigo.Estoy bien.’
Spanish_tokenizer.tokenize(text)
from nltk.tokenize import word_tokenize

text = "Hello everyone. Welcome to GeeksforGeeks."


word_tokenize(text)

*************************************************
Practical 2:
Write a program for generating regular expressions for regular grammar

import re
line = "horses are taller than dogs";
searchObj = re.search( r'(.*) ARE (.*)', re.M|re.I)
if searchObj:
print ("searchObj.group() : ", searchObj.group())
print ("searchObj.group(1) : ", searchObj.group(1))
print ("searchObj.group(2) : ", searchObj.group(2))
else:
print ("Nothing found!!")

OUTPUT:
searchObj.group() : horses are taller than dogs
searchObj.group(1) : horses
searchObj.group(2) : taller than dogs

\ – Backslash

import re

s = 'geeks.forgeeks'

# without using \
match = re.search(r'.', s)
print(match)
# using \
match = re.search(r'\.', s)
print(match)
OUTPUT:
<re.Match object; span=(0, 1), match='g'>
<re.Match object; span=(5, 6), match='.'>

[] – Square Brackets

import re

string = "The quick brown fox jumps over the lazy dog"
pattern = "[a-m]"
result = re.findall(pattern, string)

print(result)

OUTPUT:
['h', 'e', 'i', 'c', 'k', 'b', 'f', 'j', 'm', 'e', 'h', 'e', 'l', 'a', 'd', 'g']

^ – Caret

import re
regex = r'^The'
strings = ['The quick brown fox', 'The lazy dog', 'A quick brown fox']
for string in strings:
if re.match(regex, string):
print(f'Matched: {string}')
else:
print(f'Not matched: {string}')

OUTPUT:

Matched: The quick brown fox


Matched: The lazy dog
Not matched: A quick brown fox

$ – Dollar

import re

string = "Hello World!"


pattern = r"World!$"

match = re.search(pattern, string)


if match:
print("Match found!")
else:
print("Match not found.")
OUTPUT:
Match found!
import re

text = "Hello World\nHello Python\nHELLO WORLD"

# Case-insensitive matching with re.I (ignorecase) modifier


pattern = r"hello"
matches = re.findall(pattern, text, re.I)
print(matches)

# ['Hello', 'Hello', 'HELLO']

# Multi-line matching with re.M (multiline) modifier


pattern = r"^hello"
matches = re.findall(pattern, text, re.M)
print(matches)

# ['Hello', 'Hello']

# Dot matches any character, including a newline


pattern = r"Hello.*World"
matches = re.findall(pattern, text, re.S)
print(matches)

# ['Hello World', 'Hello Python\nHELLO WORLD']

PRACTICAL 3:
Write a program for generating derivation sequence / language for the given sequence of
productions
def printArray(arr, size):
for i in range(size):
print(arr[i], end = " ")
print()
return

def getSuccessor(arr, k, n):


# start from the rightmost side and
# find the first number less than n
p=k-1
while (arr[p] == n and 0 <= p < k):
p -= 1
# If all numbers are n in the array
# then there is no successor, return 0
if (p < 0):
return 0
# Update arr[] so that it contains successor
arr[p] = arr[p] + 1
i=p+1
while(i < k):
arr[i] = 1
i += 1
return 1

def printSequences(n, k):


arr = [0] * k
# Initialize the current sequence as
# the first sequence to be printed #
for i in range(k):
arr[i] = 1
# The loop breaks when there are
# no more successors to be printed
while(1):
# Print the current sequence
printArray(arr, k)
# Update arr[] so that it contains
# next sequence to be printed. And if
# there are no more sequences then
# break the loop
if(getSuccessor(arr, k, n) == 0):
break
return

# Driver code
n=1
k=2

printSequences(n, k)

Practical 4

Design a Program for creating machine that accepts three consecutive one.
Python3 implementation of the
# DFA of accepting of three
# a's and three b's

# State A
def stateA(n):
if(n[0]=='a'):
stateB(n[1:])
elif (n[0]=='b'):
stateH(n[1:])

# State B
def stateB(n):
if(len(n)== 0):
print("String Not Accepted")
else:
if(n[0]=='a'):
stateC(n[1:])
elif (n[0]=='b'):
stateI(n[1:])

# State C
def stateC(n):
if(len(n)== 0):
print("String Not Accepted")
else:
if(n[0]=='a'):
stateD(n[1:])
elif (n[0]=='b'):
stateJ(n[1:])

# State D
def stateD(n):
if(len(n)== 0):
print("String Not Accepted")
else:
if(n[0]=='a'):
stateQ2(n)
elif (n[0]=='b'):
stateE(n[1:])

# State E
def stateE(n):
if(len(n)== 0):
print("String Not Accepted")
else:
if(n[0]=='a'):
stateQ2(n)
elif (n[0]=='b'):
stateF(n[1:])

# State F
def stateF(n):
if(len(n)== 0):
print("String Not Accepted")
else:
if(n[0]=='a'):
stateQ2(n[1:])
elif (n[0]=='b'):
stateG(n[1:])

# State G
def stateG(n):
if(len(n)== 0):
print("String Accepted")
else:
if(n[0]=='a'):
stateQ2(n)
elif (n[0]=='b'):
stateQ2(n)

# State H
def stateH(n):
if(len(n)== 0):
print("String Not Accepted")
else:
if(n[0]=='a'):
stateI(n[1:])
elif (n[0]=='b'):
stateK(n[1:])

# State I
def stateI(n):
if(len(n)== 0):
print("String Not Accepted")
else:
if(n[0]=='a'):
stateJ(n[1:])
elif (n[0]=='b'):
stateL(n[1:])

# State J
def stateJ(n):
if(len(n)== 0):
print("String Not Accepted")
else:
if(n[0]=='a'):
stateE(n[1:])
elif (n[0]=='b'):
stateM(n[1:])

# State K
def stateK(n):
if(len(n)== 0):
print("String Not Accepted")
else:
if(n[0]=='a'):
stateL(n[1:])
elif (n[0]=='b'):
stateN(n[1:])

# State L
def stateL(n):
if(len(n)== 0):
print("String Not Accepted")
else:
if(n[0]=='a'):
stateM(n[1:])
elif (n[0]=='b'):
stateO(n[1:])

# State M
def stateM(n):
if(len(n)== 0):
print("String Not Accepted")
else:
if(n[0]=='a'):
stateF(n[1:])
elif (n[0]=='b'):
stateP(n[1:])

# State N
def stateN(n):
if(len(n)== 0):
print("String Not Accepted")
else:
if(n[0]=='a'):
stateO(n[1:])
elif (n[0]=='b'):
stateQ1(n)

# State Q
def stateO(n):
if(len(n)== 0):
print("String Not Accepted")
else:
if(n[0]=='a'):
stateP(n[1:])
elif (n[0]=='b'):
stateQ1(n)

# State P
def stateP(n):
if(len(n)== 0):
print("String Not Accepted")
else:
if(n[0]=='a'):
stateG(n[1:])
elif (n[0]=='b'):
stateQ1(n[1:])

# State Q1
def stateQ1(n):
print("String Not Accepted")

# State Q2
def stateQ2(n):
print("String Not Accepted")

# take string input


n = "abaabb"

# call stateA
# to check the input
stateA(n)

Program 2:
class FSM:
def __init__(self):
self.state = 'START'

def transition(self, input_char):


if self.state == 'START':
if input_char == '1':
self.state = 'S1'
else:
self.state = 'START'

elif self.state == 'S1':


if input_char == '1':
self.state = 'S2'
else:
self.state = 'START'

elif self.state == 'S2':


if input_char == '1':
self.state = 'S3'
else:
self.state = 'START'

elif self.state == 'S3':


if input_char == '1':
self.state = 'S3'
else:
self.state = 'START'

def is_accepting(self):
return self.state == 'S3'

def reset(self):
self.state = 'START'

def accept_consecutive_ones(input_string):
fsm = FSM()
for char in input_string:
fsm.transition(char)
if fsm.is_accepting():
return True
return False

# Example
test_cases = [
"00111",
"111",
"10011",
"0110",
"000",
"1111",
]

for test in test_cases:


print(f"Input: {test} -> Accepts: {accept_consecutive_ones(test)}")

Practical 5
Design a Program for creating machine that accepts the string always ending with 10
or 01.

# Python3 Program to DFA that accepts string ending


# with 01 or 10.

# End position is checked using the string


# length value.
# q0 is the starting state.
# q1 and q2 are intermediate states.
# q3 and q4 are final states.
def q1(s, i) :

print("q1->", end="");

if (i == len(s)) :
print("NO");
return;

# state transitions
# 0 takes to q1, 1 takes to q3
if (s[i] == '0') :
q1(s, i + 1);
else :
q3(s, i + 1);

def q2(s, i) :

print("q2->", end = "");


if (i == len(s)) :
print("NO");
return;

# state transitions
# 0 takes to q4, 1 takes to q2
if (s[i] == '0') :
q4(s, i + 1);
else :
q2(s, i + 1);

def q3(s, i) :

print("q3->", end = "");


if (i == len(s)) :
print("YES");
return;

# state transitions
# 0 takes to q4, 1 takes to q2
if (s[i] == '0') :
q4(s, i + 1);
else :
q2(s, i + 1);

def q4(s, i) :

print("q4->", end = "");


if (i == len(s)) :
print("YES");
return;
# state transitions
# 0 takes to q1, 1 takes to q3
if (s[i] == '0') :
q1(s, i + 1);
else :
q3(s, i + 1);

def q0( s, i) :

print("q0->", end = "");


if (i == len(s)) :
print("NO");
return;

# state transitions
# 0 takes to q1, 1 takes to q2
if (s[i] == '0') :
q1(s, i + 1);
else :
q2(s, i + 1);

# Driver Code
if __name__ == "__main__" :
s = "010101";

# all state transitions are printed.


# if string is accpetable, YES is printed.
# else NO is printed
print("State transitions are", end = " ");
q0(s, 0);

State transitions are q0->q1->q3->q4->q3->q4->q3->YES

Program 2:

class FSM:
def __init__(self):
self.state = 'S0'
def transition(self, char):
if self.state == 'S0':
if char == '0':
self.state = 'S1'
elif char == '1':
self.state = 'S2'
elif self.state == 'S1':
if char == '0':
self.state = 'S1'
elif char == '1':
self.state = 'S3'
elif self.state == 'S2':
if char == '0':
self.state = 'S4'
elif char == '1':
self.state = 'S2'
elif self.state == 'S3':
if char == '0':
self.state = 'S1'
elif char == '1':
self.state = 'S2'
elif self.state == 'S4':
if char == '0':
self.state = 'S1'
elif char == '1':
self.state = 'S2'

def is_accepted(self):
return self.state in {'S3', 'S4'}

def process_string(self, input_string):


for char in input_string:
self.transition(char)
return self.is_accepted()

# Function to check if a string is accepted by the FSM


def check_string(input_string):
fsm = FSM()
if fsm.process_string(input_string):
print(f"The string '{input_string}' is accepted.")
else:
print(f"The string '{input_string}' is not accepted.")

# Test cases
check_string("110")
check_string("001")
check_string("1010")
check_string("1101")
check_string("1001")
check_string("1111")
check_string("010")
check_string("1110")

Practical 6:
Construct DFA, which accepts set of all strings over {0, 1} which interpreted as a
binary number is divisible by 2

Code1:

def stateq0(n):
#if length found 0
#print not accepted
if (len(n)==0):
print("string accepted")
else:

#if at index 0
#'0' found call
#function stateq0
if(n[0]=='0'):
stateq0(n[1:])

#else if '1' found


#call function q1.
elif (n[0]=='1'):
stateq1(n[1:])

def stateq1(n):
#if length found 0
#print not accepted
if (len(n)==0):
print("string not accepted")
else:

#if at index 0
#'0' found call
#function stateq0
if(n[0]=='0'):
stateq0(n[1:])

#else if '1' found


#call function q1.
elif (n[0]=='1'):
stateq1(n[1:])

#take number from user


n=int(input())
#converting number to binary
n = bin(n).replace("0b", "")

#call stateA
#to check the input
stateq0(n)

Code2:
class DFA:
def __init__(self):
# Initial state is q0
self.current_state = 'q0'

def transition(self, character):


# Transition function based on the last digit
if character in ['0', '2', '4', '6', '8']:
self.current_state = 'q0'
elif character in ['1', '3', '5', '7', '9']:
self.current_state = 'q1'

def is_accepting(self):
# Check if the DFA is in the accepting state
return self.current_state == 'q0'

def reset(self):
# Reset the DFA to the initial state
self.current_state = 'q0'

def check_divisibility_by_2(number):
dfa = DFA()

# Strip decimal part if the number is an integer in string form


number_str = str(number).strip()

# Handle negative sign


if number_str[0] == '-':
number_str = number_str[1:]

# Traverse the string and use the DFA to process the last digit
for char in number_str:
if char.isdigit():
dfa.transition(char)

# Check if DFA is in the accepting state


return dfa.is_accepting()

def main():
try:
# Accept a decimal number from the user
user_input = float(input("Enter a decimal number: "))

# Check if the number is divisible by 2 using the DFA


if check_divisibility_by_2(user_input):
print(f"The number {user_input} is divisible by 2.")
else:
print(f"The number {user_input} is not divisible by 2.")
except ValueError:
print("Invalid input! Please enter a valid decimal number.")

if __name__ == "__main__":
main()
Output:

Enter a decimal number: 4.0


The number 4.0 is divisible by 2.

Enter a decimal number: 3.5


The number 3.5 is not divisible by 2.

Practical 7:
Design a program for accepting decimal number divisible by 3.

# Function to check if the binary String is divisible by 3.


def CheckDivisibilty(A):
oddbits = 0;
evenbits = 0;
for counter in range(len(A)):

# checking if the bit is nonzero


if (A[counter] == '1'):

# checking if the nonzero bit is at even


# position
if (counter % 2 == 0):
evenbits+=1;
else:
oddbits+=1;

# Checking if the difference of non-zero oddbits and


# evenbits is divisible by 3.
if (abs(oddbits - evenbits) % 3 == 0):
print("Yes" + "");
else:
print("No" + "");

# Driver Program
if __name__ == '__main__':
A = "10101";
CheckDivisibilty(A);

OUTPUT
YES

Code2:

def is_divisible_by_3(number: float) -> bool:


"""
This function checks if a given decimal number is divisible by 3.

Args:
number (float): The decimal number to check.

Returns:
bool: True if the number is divisible by 3, False otherwise.
"""
# Convert the float to an integer by multiplying by 10 raised to the power of
the number of decimal places
# and check if that integer is divisible by 3.

# Extract the number of decimal places


decimal_places = len(str(number).split('.')[1]) if '.' in str(number) else 0
# Scale the number to remove decimals
scaled_number = int(number * (10 ** decimal_places))

return scaled_number % 3 == 0

def main():
try:
# Accept input from the user
number = float(input("Enter a decimal number: "))

# Check if the number is divisible by 3


if is_divisible_by_3(number):
print(f"The number {number} is divisible by 3.")
else:
print(f"The number {number} is not divisible by 3.")

except ValueError:
print("Invalid input! )

OUTPUT
Enter a decimal number: 9.0
9.0 is divisible by 3.
Do you want to enter another number? (yes/no): no

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy