This is in Python.
I want to write a simple Markov-Chain thingy in about 75 lines of code on my Calculator. the only Module im able to import is "Random" and "Math".
heres a quick copy i made, should work in the python terminal, where it is supposed to work.
thats the only way my calculator will have it.
from random import *
class word:
def __init__(self,word,words):
self.word=word
self.words=words.split()
def addWord(self,word):
self.words.append(word)
# "x" is an empty list, otherwise contains all previous word-objects
# "s" is the string to use for training
def train(x,s):
s=s.split()
if len(x)==0:
x=[]
for i in range(len(s)-1):
if s[i]==s[-1]:
return x
w=word(s[i],s[i+1])
ind=0
# ///
# This is the problem area
for wr in x:
ind+=1
if wr in x:
wr.addWord(s[i+1])
elif wr not in x:
x.append(w)
# ///
return x
def chain(start, x):
for i in range(10):
for w in x:
if w.word==start[-1]:
start.append(choice(w.words))
return start
I want the train function to return a list of "word"-objects, instead:
if wr in x:
wr.addWord(s[i+1])
elif wr not in x:
x.append(w)
seems to never be executed, im going to keep looking into this since there is surely a solution.
TL:DR; How do i check if an Object is in a list of Objects and if it is, add something to this object, and if it isnt add the object to the list?
if you need more infos, you are free to ask.
Append this to the code if you want to test it:
x=[]
x=train(x, "This is a String")
x=train(x, "And this is yet another Sentence")
y=chain(x, "This")
print(y)
where x is the dictionary of all words in the end and y is the generated sentence.
i expect a sentence which wasnt trained to be generated, using the words and context it was given. context and words coming from the sentences it was trained on.
y might for example be "This is yes another Sentence" which would be a combination of the Strings it got, but isnt equal to either of them.