def bfs():
    code = '''
graph = {
    'a' : ['b','c'],
    'b' : ['d','e'],
    'c' : ['f'],
    'd' : [],
    'e' : [],
    'f' : []
}

vis = []
q = []
node='a'

vis.append(node)
q.append(node)

while q:
    s=q.pop(0)
    print(s,end=' ')

    for n in graph[s]:
        if n not in vis:
            vis.append(n)
            q.append(n)'''
    print(code)

def dfs():
    code = '''
graph = {
    'a' : ['d','c','b'],
    'b' : ['e'],
    'c' : ['g','f'],
    'd' : ['h'],
    'e' : ['i'],
    'f' : ['j']
}

path=[]
stack=['a']

while(len(stack)!=0):
    s=stack.pop()
    if s not in path:
        path.append(s)
    if s not in graph:
        continue
    for n in graph[s]:
        stack.append(n)

print(path)'''
    print(code)

def waterjug():
    code = '''a=int(input('Enter Jug A Capacity : '))
b=int(input('Enter Jug B Capacity : '))
af=int(input('Enter Final State Capacity of Jug A : '))
ai=0
bi=0

print('List of Operations you can do :')
print('1.) Fill Jug A Completely')
print('2.) Empty Jug A Completely')
print('3.) Fill Jug B Completely')
print('4.) Empty Jug B Completely')
print('5.) Empty Jug A into Jug B')
print('6.) Empty Jug B into Jug A')
print('7.) Pour Jug A into Jug B untill it is full')
print('8.) Pour Jug B into Jug A untill it is full')

while((ai!=af and bi<=b)):
    op = int(input("Enter your operation : "))
    if(op==1):
        ai=a
    elif(op==2):
        ai=0
    elif(op==3):
        bi=b
    elif(op==4):
        bi=0
    elif(op==5):
        if(ai+bi<=a and bi>0):
            ai=ai+bi;
            bi=0;
    elif(op==6):
        if(ai+bi<=b and ai>0):
            bi=ai+bi;
            ai=0;
    elif(op==7):
        if(ai+bi>=5 and bi>0):
            bi=bi-(a-ai);
            ai=a;
    elif(op==8):
        if(ai+bi>=3 and ai>0):
            ai=ai-(b-bi);
            bi=b;
    print(ai,bi)'''
    print(code)

def a4():
    code = '''from keras.models import Sequential
from keras.layers import Dense
from sklearn.datasets import make_regression
from sklearn.preprocessing import MinMaxScaler

X,Y=make_regression(n_samples=100,n_features=2,noise=0.1,random_state=1)
scalarX, scalarY=MinMaxScaler(),MinMaxScaler()
scalarX.fit(X)
scalarY.fit(Y.reshape(100,1))
X=scalarX.transform(X)
Y=scalarY.transform(Y.reshape(100,1))
model=Sequential()
model.add(Dense(4,input_dim=2,activation='relu'))
model.add(Dense(4,activation='relu'))
model.add(Dense(1,activation='sigmoid'))
model.compile(loss='mse',optimizer='adam')
model.fit(X,Y,epochs=1000,verbose=0)
Xnew,a=make_regression(n_samples=3,n_features=2,noise=0.1,random_state=1)
Xnew=scalarX.transform(Xnew)
Ynew = model.predict(Xnew)
for i in range(len(Xnew)):
  print("X=%s,Predicted=%s,Desired=%s"%(Xnew[i],Ynew[i],a[i]))
  #print("X=%s,Predicted=%s"%(Xnew[i],Ynew[i]))'''
    print(code)

def cards():
    code = '''
import itertools,random

deck = list(itertools.product(range(1,14),['Spades','Heart','Diamond','Clubs']))
random.shuffle(deck)

print("You got : ")
for i in range(5):
    if deck[i][0]==11:
        print('Jack of',deck[i][1])
    elif deck[i][0]==12:
        print('Queen of',deck[i][1])
    elif deck[i][0]== 13:
        print('King of',deck[i][1])
    else:
        print(deck[i][0],'of',deck[i][1])'''
    print(code)

def travel():
    code = '''
from sys import maxsize
from itertools import permutations
v=4

def tsp(g,s):
    ver=[1,2,3]
    print('Vertex : ', ver)
    minpath=maxsize
    nextper=permutations(ver)
    for i in nextper:
        print('i ',i)
        currentpath=0
        k=s
        for j in i: 
            currentpath+=g[k][j]
            print('cw =',currentpath,'g[k][j] =',g[k][j],'k =',k,'j =',j,)
            k=j
        currentpath+=g[k][s]
        print('Final cw at',i,'and graph[k][s]',g[k][s],'=',currentpath,'\n')
        minpath=min(minpath,currentpath)
    return minpath

graph=[[0,10,15,20],[10,0,35,25],[15,35,0,30],[20,25,30,0]]
s=0
print('minimum path = ',tsp(graph,s))'''
    print(code)

def tts():
    code = '''
not required if python ver 3.11 
import cgi
import pyttsx3
from googletrans import Translator
from gtts import gTTS
engine = pyttsx3.init()

voices = engine.getProperty('voices')
engine.setProperty('voice', voices[0].id)

text = input("Enter Text here: ")

translator = Translator()

translated = translator.translate(text, src='en', dest='fr')

print("Translated Text:", translated.text)

engine.say(translated.text)
engine.runAndWait()

tts = gTTS(text=translated.text, lang='fr')
tts.save("tts.mp3")

print("File saved as tts.mp3")'''
    print(code)

def tower():
    code = '''
def tower(n,a,c,b):
    if n==1:
        print('Move Disk 1 from rod', a , 'to rod', c)
        return
    tower(n-1,a,b,c)
    print('Move Disk',n,'from rod',a,'to rod',c)
    tower(n-1,b,c,a)

n=3
tower(n,'A','C','B')'''
    print(code)

def fuzzy():
    code = '''
elt=['w','x','y','z']
A=[0.5,0.4,0.3,0.2]
B=[0.2,0.1,0.2,1]
def printset(m):
    for i in range(0,4):
         print("(",elt[i],",",m[i],")",end=",")
    print()
print("set A=",end="")
printset(A)
print("set B=")
printset(B)
#union
U=[]
for i in range(0,4):
 if A[i]>B[i]:
     U.append(A[i])
 else:
     U.append(B[i])
print("Union=")
printset(U)
#intersection
I=[]
for i in range(0,4):
 if A[i]<B[i]:
     I.append(A[i])
 else:
     I.append(B[i])
print("Intersection=")
printset(I)
#A complement
AC=[]
for i in range(0,4):
     AC.append(1-A[i])
print("A'=")
printset(AC)
#B complement
BC=[]
for i in range(0,4):
     BC.append(1-B[i])
print("B'=")
printset(BC)
#difference A-B (min(A,BC))
AMB=[]
for i in range(0,4):
 if A[i]<BC[i]:
     AMB.append(A[i])
 else:
     AMB.append(BC[i])
print("difference A-B=")
printset(AMB)
#difference B-A (min(B,AC))
BMA=[]
for i in range(0,4):
 if B[i]<AC[i]:
     BMA.append(B[i])
 else:
     BMA.append(AC[i])
print("difference B-A=")
printset(BMA)'''
    print(code)

def tipfuzzy():
    code = '''
import numpy as np 
import skfuzzy as fuzz 
from skfuzzy import control as ctrl 
# New Antecedent/Consequent objects hold universe variables and membership 
# functions 
quality = ctrl.Antecedent(np.arange(0, 11, 1), 'quality') 
service = ctrl.Antecedent(np.arange(0, 11, 1), 'service') 
tip = ctrl.Consequent(np.arange(0, 26, 1), 'tip') 
# Auto-membership function population is possible with .automf(3, 5, or 7) 
quality.automf(3) 
service.automf(3) 
# Custom membership functions can be built interactively with a familiar, 
# Pythonic API 
tip['low'] = fuzz.trimf(tip.universe, [0, 0, 13]) 
tip['medium'] = fuzz.trimf(tip.universe, [0, 13, 25]) 
tip['high'] = fuzz.trimf(tip.universe, [13, 25, 25]) 
quality['average'].view() 
service.view() 
tip.view() 
rule1 = ctrl.Rule(quality['poor'] | service['poor'], tip['low']) 
rule2 = ctrl.Rule(service['average'], tip['medium']) 
rule3 = ctrl.Rule(service['good'] | quality['good'], tip['high']) 
rule1.view() 
tipping_ctrl = ctrl.ControlSystem([rule1, rule2, rule3]) 
tipping = ctrl.ControlSystemSimulation(tipping_ctrl) 
tipping.input['quality'] = 6.5
tipping.input['service'] = 9.8 
# Crunch the numbers 
tipping.compute() 
print (tipping.output['tip']) 
tip.view(sim=tipping) '''
    print(code)

def genetic():
    code = '''
import random

# Number of individuals in each generation
POPULATION_SIZE = 100

# Valid genes
GENES = ''abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ 1234567890, .-;:_!"#%&/()=?@${[]}''

# Target string to be generated
TARGET = "Test String for Genetic Algorithm"

class Individual(object):
    ''
    Class representing individual in population
    ''
    def __init__(self, chromosome):
        self.chromosome = chromosome
        self.fitness = self.cal_fitness()

    @classmethod
    def mutated_genes(self):
        ''
        Create random genes for mutation
        ''
        global GENES
        gene = random.choice(GENES)
        return gene

    @classmethod
    def create_gnome(self):
        ''
        Create chromosome or string of genes
        ''
        global TARGET
        gnome_len = len(TARGET)
        return [self.mutated_genes() for _ in range(gnome_len)]

    def mate(self, par2):
        ''
        Perform mating and produce new offspring
        ''
        # Chromosome for offspring
        child_chromosome = []

        for gp1, gp2 in zip(self.chromosome, par2.chromosome):

            # random probability
            prob = random.random()

            # if prob < 0.45 → gene from parent 1
            if prob < 0.45:
                child_chromosome.append(gp1)

            # if prob < 0.90 → gene from parent 2
            elif prob < 0.90:
                child_chromosome.append(gp2)

            # otherwise insert mutated gene
            else:
                child_chromosome.append(self.mutated_genes())

        return Individual(child_chromosome)

    def cal_fitness(self):
        ''
        Calculate fitness score = number of characters different from target
        ''
        global TARGET
        fitness = 0
        for gs, gt in zip(self.chromosome, TARGET):
            if gs != gt:
                fitness += 1
        return fitness


# Driver code
def main():
    global POPULATION_SIZE

    # current generation
    generation = 1
    found = False
    population = []

    # create initial population
    for _ in range(POPULATION_SIZE):
        gnome = Individual.create_gnome()
        population.append(Individual(gnome))

    while not found:

        # sort population by fitness
        population = sorted(population, key=lambda x: x.fitness)

        # if perfect fitness found
        if population[0].fitness <= 0:
            found = True
            break

        # Otherwise generate new offsprings
        new_generation = []

        # Elitism → carry forward top 10%
        s = int((10 * POPULATION_SIZE) / 100)
        new_generation.extend(population[:s])

        # Remaining 90% → mating
        s = int((90 * POPULATION_SIZE) / 100)
        for _ in range(s):
            parent1 = random.choice(population[:50])
            parent2 = random.choice(population[:50])

            child = parent1.mate(parent2)
            new_generation.append(child)

        population = new_generation

        print("Generation: {}\tString: {}\tFitness: {}".format(
            generation,
            "".join(population[0].chromosome),
            population[0].fitness))

        generation += 1

    print("Generation: {}\tString: {}\tFitness: {}".format(
        generation,
        "".join(population[0].chromosome),
        population[0].fitness))


if __name__ == '__main__':
    main()
'''
    print(code)