Python Conway's Game of Life - python-3.x

I'm trying to make Conway's Game of Life where the user enters how big they want the grid and which cells start off as alive. Here's what I have:
def firstBoard(rows, cols, array):
myList = [[0]*cols for i in range(rows)]
for i in myList:
i.append(-1)
i.insert(0,-1)
myList.insert(0,[-1]* (cols+2))
myList.append([-1]* (cols+2))
while True:
rows = input("Enter the row or 'q': ")
if rows == 'q':
break
cols = input("Enter the column: ")
print()
myList[int(rows)][int(cols)] = 1
return myList
def nextGen(cols, rows, cur, nxt):
for i in range(1,rows-1):
for j in range(1,cols-1):
nxt[i][j] = processNeighbours(i, j, cur)
def processNeighbours(x, y, array):
nCount = 0
for j in range(y-1,y+2):
for i in range(x-1,x+2):
if not(i == x and j == y):
if array[i][j] != -1:
nCount += array[i][j]
if array[x][y] == 1 and nCount < 2:
return 0
if array[x][y] == 1 and nCount > 3:
return 0
if array[x][y] == 0 and nCount == 3:
return 1
else:
return array[x][y]
def printBoard(cols, rows, array):
for i in range(rows+2):
for j in range(cols+2):
if array[i][j] == -1:
print("#", end=" ")
elif array[i][j] == 1:
print(".", end=" ")
else:
print(" ", end=" ")
print()
def main():
rows = int(input("Please enter the number of rows: "))
cols = int(input("Please enter the number of columns: "))
myList = []
newList = []
myList = firstBoard(rows, cols, myList)
newList = myList
print()
generations = int(input("How many iterations should I run? "))+1
for gens in range(generations):
printBoard(cols, rows, myList)
nextGen(cols, rows, myList, newList)
myList, newList = newList, myList
main()
And if for the both the rows and columns I enter five and If I fill 3,4 4,4 5,4 i get this:
# # # # # # #
# #
# #
# . #
# . #
# . #
# # # # # # #
# # # # # # #
# #
# #
# . #
# . #
# . #
# # # # # # #
# # # # # # #
# #
# #
# . #
# . #
# . #
# # # # # # #
# # # # # # #
# #
# #
# . #
# . #
# . #
# # # # # # #
when for the second and fourth boxes the dots should be horizontal instead of vertical. Please help i've been working on this all day and I can't figure it out.

The problem is with your array initialization:
newList = myList
This isn't making a copy of myList, it's just making newList refer to myList, so then you only have one array. You can copy a 2D array like this:
from copy import copy, deepcopy
newList = deepcopy(myList)

Related

Saving a value, removing it and then running again with the rest of a list

Problem Description
I am firstly I am having a list of values like:
(1,2,3,1,3,2,2,2,1)
What I want to achieve is :
Find the most common one (working).
Delete it from the list (working).
Repeat the same thing for the remaining values in the list.
For instance
Taking this Tuple:
(1,2,3,1,3,2,2,2,1)
Store that 2 is the most common int, then
(1,3,3,1,1,)
Store that 1 is the second most common int, then
(3,3)
Store that 2 is the third most common int, then
My source Code
NOTE lets say that self.final_votes would be (1,2,3,1,3,2,2,2,1)
def erase_common(self):
possitions = []
counter = 0
common = self.final_votes[0]
for i in self.final_votes:
cand_freq = self.final_votes.count(i)
if(cand_freq> counter):
counter = cand_freq
common = i
possitions.append(common)
while common in self.final_votes:
self.final_votes.remove(common)
this is the whole code
class voting_system:
def __init__(self):
#self.tutor_group = self.get_tutor_group()
self.stud_num = self.get_stud_num()
self.cand_num = self.get_cand_num()
self.cand_name = self.get_cand_name()
self.final_votes = self.ind_votes()
self.erase_common()
# def get_tutor_group(self):
# tutor_groups = ("7A","7B","7C","7D","7E","7F","8A","8B","8C","8D","8E","8F","9A","9B","9C","9D","9E","9E",
# "9F","10A","10B","10C","10D","10E","10F","11A","11B","11C","11D","11E","11F")
#
# flag = True
# while flag == True:
# try:
# self.tutor_group = input("please enter the tutor group: ")
# if self.tutor_group not in tutor_groups:
# raise ValueError("Tutor group entred doesn't exist")
# except ValueError as error:
# print(error)
# flag = True
#
# else:
# flag = False
# return self.tutor_group
def get_stud_num(self):
# flag = True
# while flag == True:
# try:
# self.stud_num = int(input("Please enter number of students: "))
# if self.stud_num<0 or self.stud_num>35:
# raise ValueError("NUMBER OF STUDENTS INVALID")
# except ValueError as error:
# print(error)
# flag = True
#
# else:
# flag = False
self.stud_num = 7
return self.stud_num
def get_cand_num(self):
# flag = True
# while flag == True:
# try:
# self.cand_num = int(input("Please enter number of candidates: "))
# if self.cand_num>4:
# raise ValueError("NUMBER OF CANDIDATES INVALID")
# except ValueError as error:
# print(error)
# flag = True
#
# else:
# flag = False
self.cand_num = 3
return self.cand_num
def get_cand_name(self):
self.cand_name = []
for i in range(self.cand_num):
candidate = input("Enter candidate name: ")
self.cand_name.append(candidate)
return self.cand_name
def print_cands(self):
for i in range(len(self.cand_name)):
print(i+1, " : ", self.cand_name[i])
def ind_votes(self):
self.final_votes = []
self.print_cands()
abs_vote = 0
flag = True
while flag == True:
try:
for i in range(self.stud_num):
vote = input("To vote type 'V' and the candidates number, to abstent type 'A': ")
if vote.isalpha() == True:
abs_vote +=1
else:
self.final_votes.append(vote[1])
if vote[1] > str(self.cand_num):
raise ValueError("VOTED CANDIDATE NONEXISTENT")
except ValueError as error:
print(error)
flag = True
else:
flag = False
return self.final_votes
return abs_vote
def erase_common(self):
possitions = []
counter = 0
common = self.final_votes[0]
for i in self.final_votes:
cand_freq = self.final_votes.count(i)
if(cand_freq> counter):
counter = cand_freq
common = i
possitions.append(common)
while common in self.final_votes:
self.final_votes.remove(common)
run = voting_system()
any suggestions would be appreciated:)
Easier and probably the best:
User Python Counter from Collection.
from collections import Counter
final_votes = [1, 2, 3, 1, 3, 2, 2, 2, 1]
def erase_common(votes):
count_votes = Counter(votes)
return count_votes.most_common()
print(erase_common(final_votes)) # [(2, 4), (1, 3), (3, 2)]
votes = erase_common(final_votes)
for idx, votes in enumerate(votes):
print(f'{idx+1}) Vote {votes[0]} Total = {votes[1]}')
OUTPUT
1) Vote 2 Total = 4
2) Vote 1 Total = 3
3) Vote 3 Total = 2
Using groupby
#AlexMartelli has a really good answer regarding find most common element on list --> Find the most common element in a list
So you can implement this by doing this:
from itertools import groupby
final_votes = [1, 2, 3, 1, 3, 2, 2, 2, 1]
def most_common_oneliner(L):
grupped = groupby(sorted(L))
result = {group: len([*scores]) for group, scores in grupped}
final_sorted_votes = []
while result:
max = [(0, 0)]
for score, res in result.items():
if max[0][1] < res:
max[0] = (score, res)
del result[max[0][0]]
final_sorted_votes += max
return final_sorted_votes
result = most_common_oneliner(final_votes)
for idx, votes in enumerate(result):
print(f'{idx+1}) Vote {votes[0]} Total = {votes[1]}')
Documentation
Counter
Counter Implementation
most_common function inplementation
groupby
how-do-i-use-itertools-groupby Stack Overflow
geeksforgeeks.org | python-find-most-frequent-element-in-a-list

reading values from txt file and passing in function

I have a txt file which has values x , y listed as
20
80
70.....
I wrote code to read the x and y but i am not sure what i am doing wrong .
def readTruth():
with open("Truth.txt") as f:
for line in f:
x_truth, y_truth = line.split("\n")
return x_truth,y_truth
def main():
x,y = readTruth()
print(x)
if __name__ == "__main__":
main()
I only see one value getting printed in x.
You are reading one line at a time. So you cannot access the values in the 2nd line while reading the first line. Splitting the line by the newline character "\n" will do nothing in this instance.
If you only have 2 lines in your text file, you could do something like this:
# Note here that I am lazy and used a string here instead of text file
a_string = "1\n2"
def readTruth():
x_truth, y_truth = a_string.split("\n")
return x_truth,y_truth
x,y = readTruth()
print(x) # 1
print(y) # 2
But I suspect you have more than just 2 values. You could refactor your text file to hold the 2 values on the same line, separated by a space or comma. If you do so, your solution will work. You would just need to split by the comma or space, whichever delimiter you choose to use.
If you must have each number on a separate line, then your solution won't work. You would need to add the results to a list of X values and a list of Y values:
# truth.txt:
# 1
# 2
# 3
# 4
#
f = open("truth.txt", "r")
def readTruth():
counter = 1
X_vals = []
Y_vals = []
for line in f.readlines():
# If it is an even numbered line, add to Y_vals
if counter % 2 == 0:
Y_vals.append(line.strip("\n"))
# Otherwise it is an odd numbered line, so add to X_vals
else:
X_vals.append(line.strip("\n"))
counter+=1
return X_vals, Y_vals
x,y = readTruth()
print(x) # ['1', '3']
print(y) # ['2', '4']
Based on comments from the question poster, I assume they have a blank line between each number in their text file. This means each number is on an odd numbered line. The quick solution, added onto my previous example, is to skip blank lines:
# truth.txt:
# 1
#
# 2
#
# 3
#
# 4
#
f = open("truth.txt", "r")
def readTruth():
counter = 1
X_vals = []
Y_vals = []
for line in f.readlines():
# Skip blank lines
if line.strip("\n") != "":
# If it is an even numbered line, add to Y_vals
if counter % 2 == 0:
Y_vals.append(line.strip("\n"))
# Otherwise it is an odd numbered line, so add to X_vals
else:
X_vals.append(line.strip("\n"))
counter+=1
return X_vals, Y_vals
x,y = readTruth()
print(x) # ['1', '3']
print(y) # ['2', '4']
We obtain the values โ€‹โ€‹of X and Y:
def readTruth():
with open("Truth.txt") as f:
for line in f:
x_truth, y_truth = line.split("\n")
return x_truth,y_truth
def main():
x,y = readTruth()
print("Var_X = "+ str(x[0]))
print("Var_Y = "+ str(x[1]))
You can put the variables in a list for each X and Y

Remove extra space from pattern

This is a pattern for 180 degree triangle pattern in python
for i in range(0,n):
for j in range(n,-1,-1):
if(j<=i):
print("#",end="")
else:
print(" ",end="")
print("")
with this output is coming like this:
#
##
###
####
#####
######
As you can see it has extra spaces
What I want is:
#
##
###
####
#####
######
Try this :
n = int(input())
for i in range(1,n+1):
for j in range(n,0,-1):
if(j<=i):
print("#",end="")
else:
print(" ",end="")
print("")

Identifying straight, flush and other categories (from Poker) using Python

I am newbie to python and learning it from books, forums and developers. Recently, I tried to implement various hand-ranking categories in the poker program. The goal is to calculate probabilities and see if it agrees with theoretical poker hand probabilities?
Source: https://en.wikipedia.org/wiki/Poker_probability?oldformat=true
Please find below the code and logic I've used so far to build it. The code contains Card and Deck classes which together implement a deck of standard playing cards used, as well as a sample PyTest test function test_xxx().
So far, I've written hasOnePair, hasTwoPairs, hasThreeOfAKind, hasFullHouse and hasFourOfaKind() functions and it is working fine but I am struggling with Straight, flush, StraightFlush.
Could someone please suggest or give guideline about how to approach straight, flush, royalflush, straightflush cases? Also, any further suggestions to update this code will be great.
import random
SUITS = ["Clubs", "Diamonds", "Hearts", "Spades"]
RANKS = ["", "Ace", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Jack", "Queen", "King"]
# here's two Python classes whose objects represent playing cards and decks thereof
class Card():
"""
Represents a single playing card,
whose rank internally is int _rank: 1..13 => "Ace".."King"
and whose suit internally is int _suit 0..3 => "Clubs".."Spades"
"""
def __init__(self, rank=1, suit=3): # this is the constructor!
'''
Initialize card with given int suit and int rank
:param rank:
:param suit:
:return:
'''
self._rank = rank
self._suit = suit
def __str__(self): # this is the "stringifier"
"""
Return the string name of this card:
"Ace of Spades": translates int fields to strings
:return:
"""
# "Ace of Spades" is string for self._rank==1, self._suit==3
toreturn = RANKS[self._rank] + " of " + SUITS[self._suit]
return toreturn
class Deck():
"""
Represents a deck of 52 standard playing cards,
as a list of Card refs
"""
def __init__(self): # constructor
"""
Initialize deck: field _cards is list containing
52 Card refs, initially
:return: nothing
"""
self._cards = []
for rank in range(1, 14):
for suit in range(4):
c = Card(rank, suit) # create next Card with given value
self._cards.append(c) # add it to this Deck
def __str__(self):
"""
"Stringified" deck: string of Card named,
with \n for easier reading
:return:
"""
toreturn = ''
# for index in range(len(self._cards)):
# self._cards[index]
for c in self._cards:
temp = str(c) # temp is the stringified card
toreturn = toreturn + temp + "\n" # note \n at end
return toreturn
def shuffle(self):
random.shuffle(self._cards) # note random function to do this
def dealCard(self):
toreturn = self._cards.pop(0) # get and remove top card from deck
return toreturn
def buildDict(hand):
dict = {}
for card in hand:
dict[card._rank] = dict.get(card._rank, 0) + 1
return dict
def hasOnePair(dict):
twocount = 0
threecount = 0
for v in dict.values():
if v == 2:
twocount += 1
elif v == 3:
threecount += 1
if twocount==1 and threecount != 1:
return True
else:
return False
def hasTwoPairs(dict):
twocount1 = 0
threecount1 = 0
for v in dict.values():
if v ==2:
twocount1 += 1
elif v == 3:
threecount1 +=1
if twocount1 == 2 and threecount1 != 1:
return True
else:
return False
def hasThreeOfAKind(dict):
twocount = 0
threecount = 0
for v in dict.values():
if v == 2:
twocount += 1
elif v == 3:
threecount += 1
if twocount != 1 and threecount == 1:
return True
else:
return False
def hasFullHouse(dict):
twocount = 0
threecount = 0
for v in dict.values():
if v == 2:
twocount += 1
elif v == 3:
threecount += 1
if twocount == 1 and threecount == 1:
return True
else:
return False
def hasFourOfAKind(dict):
fourcount = 0
onecount = 0
for v in dict.values():
if v ==4:
fourcount += 1
elif v == 1:
onecount +=1
if fourcount == 1 and onecount == 1:
return True
else:
return False
def hasStraight(hand):
return False
def hasFlush(dict):
return False
def hasStraightFlush(dict):
return False
def hasRoyalFlush(dict):
return False
def main():
TRIALS = 1000 # int(input ("Input number of hands to test: "))
hand = [] # list of Card in hand
# accumulators for different counts
onepairCount = 0
twopairCount = 0
threeCount = 0
fourCount = 0
fullHouseCount = 0
StraightCount = 0
for num in range(TRIALS):
# create new Deck and shuffle
d = Deck()
d.shuffle()
# initialize hand as empty list
hand = []
# deal top 5 cards of deck, adding to hand
for count in range(5):
hand.append(d.dealCard())
# build the dictionary of card ranks in hand
dict = buildDict(hand)
# use dictionary to make hand checking easier
if hasOnePair(dict):
onepairCount += 1
elif hasTwoPairs(dict):
twopairCount += 1
elif hasThreeOfAKind(dict):
threeCount += 1
elif hasFourOfAKind(dict):
fourCount += 1
elif hasFullHouse(dict):
fullHouseCount += 1
elif hasStraight(dict):
StraightCount +=1
# add more if needed...
# print out results...
print("Number of one pair hands is: ", onepairCount)
print("% of hands: ", 100.0 * onepairCount / TRIALS)
print("Number of two pair hands is: ", twopairCount)
print("% of hands: ", 100.0 * twopairCount / TRIALS)
print("Number of trips hand is: ", threeCount)
print("% of hands: ", 100.0 * threeCount / TRIALS)
print("Number of quads hand is: ", fourCount)
print("% of hands: ", 100.0 * fourCount / TRIALS)
print("Number of trips hand is: ", fullHouseCount)
print("% of hands: ", 100.0 * fullHouseCount / TRIALS)
print("Number of trips hand is: ", StraightCount)
print("% of hands: ", 100.0 * StraightCount / TRIALS)
def card_example():
card1 = Card() # Card(1,3) => Ace of Clubs
card2 = Card(12, 2) # Card (12,2) => Queen of Hearts
card1._newfield = 47 # we can add new fields to any Python object!
# three ways of printing a Card
#
print(card1.__str__()) # calling the methods against card
print(str(card2)) # type-casting
print(card2) # short-cut: passing obj ref to print does str() automagically
print(card1._newfield) # see the new field value?
print(card1._rank) # see the rank (1..13)
print(card1._suit) # see the suit (0..3)
def deck_example():
"""
Test Deck: create, print then shuffle, print again
Then deal first two cards and print, along with bottom card
"""
deck = Deck()
print(str(deck)) # see entire deck before shuffling
print("Now we shuffle:\n")
deck.shuffle()
print(str(deck)) # see entire deck after shuffling
card1 = deck.dealCard()
card2 = deck.dealCard()
print("The first card dealt is", str(card1), "and the second is", str(card2))
print("Bottom of deck is", deck._cards[-1]) # can't hide the implementation!
if __name__ == "__main__": # only run this if this .py is NOT imported
# pass
# card_example() # uncomment to test creating & calling Card methods
# deck_example() # uncomment to test Deck: create, print, shuffle, print
main() # uncomment to run general poker odds calculations
#
# -------------------------------------------------------------------------
#
#pytest follows...
def test_one_pair():
testhand = [Card(2, 3), Card(1, 2),
Card(3, 1), Card(13, 2),
Card(2, 0)]
dict = buildDict(testhand)
assert hasOnePair(dict) #hasTwoPairs
def test_two_pair():
testhand = [Card(2, 3), Card(1, 2),
Card(3, 1), Card(3, 2),
Card(2, 0)]
dict = buildDict(testhand)
assert hasTwoPairs(dict)
def test_three_pair():
testhand = [Card(1, 3), Card(1, 2),
Card(1, 1), Card(13, 2),
Card(2, 0)]
dict = buildDict(testhand)
assert hasThreeOfAKind(dict)
def has_Four_Of_A_Kind():
testhand = [Card(1, 3), Card(1, 2),
Card(1, 1), Card(1, 0),
Card(2, 0)]
dict = buildDict(testhand)
assert hasFourOfAKind(dict)
def test_full_house():
testhand = [Card(1, 3), Card(1, 2),
Card(1, 1), Card(13, 2),
Card(13, 2)]
dict = buildDict(testhand)
assert hasFullHouse(dict)
def test_Straight():
testhand = [Card(11, 1), Card(10, 3),
Card(9, 2), Card(8, 1),
Card(7, 3)]
dict = buildDict(testhand)
assert hasStraight(dict)
The condition for a straight is for your five cards to have adjacent ranks, such that no two cards have the same rank. You can use two different checks to confirm this:
when sorted, the difference between the top card and the bottom card is equal to the total number of cards minus one(e.g. a 4-8 straight has a difference of 4)
no two cards in the straight have the same rank (thus by pigeonhole principle, all ranks between the minimum and maximum must be present
Here's a sample implementation of that:
def hasStraight(hand):
# account for both low-ace and high-ace
ranks_low = sorted([card._rank for card in hand])
ranks_high = sorted([(14 if card._rank == 1 else card._rank) for card in hand])
return (
(
ranks_low[-1] - (len(hand) - 1) == ranks_low[0]
or ranks_high[-1] - (len(hand) - 1) == ranks_high[0]
) # condition 1
and len(set(hand)) == len(hand) # condition 2
)
You will also have to account for low-aces and high-aces. You can do this by, for example, doing two similar checks, once with the normal card ranks and once by doing something like `if card._rank == 1: card._rank == 14
The condition for a flush is simply that all cards are the same suit. This is easy to verify, by simply making a set of all unique suits in the hand, and returning true if that set has only one element (thus all the suits must be the same):
def hasFlush(hand):
suits_set = set(*[card._suit for card in hand])
return len(suits_set) == 1
Once you have those, straight flush and royal flush are easy:
def hasStraightFlush(hand):
return hasStraight(hand) and hasFlush(hand)
def hasRoyalFlush(hand):
ranks = sorted([14 if card._rank == 1 else card._rank for card in hand])
return (
hasStraightFlush(hand)
and ranks[0] == 10 and ranks[-1] == 14
) # royal flush starts at 10, ends at high-ace

list index error python (numeric words program)

I'm trying to write a program in Python 3.
This is how it works:
The input is a word.
And the program has to look if the word contains a dutch numeric word.
A word cannot contain more than 1 numeric word and if a word doesn't contain a numeric word than it has to print 'geen' (none in dutch).
example:
Input = BETWEEN
Output = TWEE (two in dutch)
Input = ZEEVERS
Output = ZES (six in dutch)
Here is my code:
import sys
invoer = input()
letterwoorden = [['T','W','E','E'], ['D','R','I','E'], ['V','I','E','R'],
['V','I','J','F'], ['Z','E','S'], ['Z','E','V','E','N'], ['A','C','H','T'],
['N','E','G','E','N']]
antwoord = []
woord = [str(a) for a in str(invoer)]
L = len(woord)
a = 0
b = 0
c = 0
for i in range(0, 8):
for j in range(0, len(letterwoorden[a])):
if letterwoorden[a][b] == woord[c]:
antwoord.append(letterwoorden[a][b])
b = b + 1
c = c + 1
else:
c = c + 1
if antwoord == letterwoorden[a]:
print(antwoord)
break
else:
a = a + 1
antwoord.clear()
if antwoord != letterwoorden[a]:
print('geen')
Could someone help me with the error on line 21? (list index out of range)
Thanks!
The code is not fully done but when the input is TWEET the output is TWEE,
when the input is BETWEEN it gives the error.
Even though usr2564301's first solution looks good, I wanted to add a couple things. You'll find this in the comments in the code.
Here's how I'd modify your code:
## use strings instead of list of strings
## ['T', 'W', 'E', 'E'] ==> 'TWEE'
## they are also iterable (you can loop through them)
## as well as indexable (['T', 'W', 'E', 'E'][0] == 'TWEE'[0])
letterwoorden = ['TWEE', 'DRIE', 'VIER', 'VIJF', 'ZES', 'ZEVEN', 'ACHT', 'NEGEN']
## keep the string
woord = input()
print('Input:', woord)
## answer should be string as well
antwoord = ''
## name your variables something meaningful
## how does one differentiate between b and c? smh
letterWoordenIndex = 0
woordenIndex = 0
## for-loops can be powerful in Python
## you might've been used to index-based loops from other languages :|
## this way, tempWord can replace all occurrences of letterwoorden[a]
for tempWord in letterwoorden:
## reset your variables at the beginning of the loop
letterWoordenIndex = woordenIndex = 0
# """ ## debug output printing word
print('Word:', tempWord, '?')
# """
## loop through the length of word
## use _ to indicate that the variable won't be used
for _ in range(len(woord)):
# """ ## debug output comparing letters/indices
print(tempWord[letterWoordenIndex],
'({})'.format(letterWoordenIndex),
'<=>', woord[woordenIndex],
'({})'.format(woordenIndex))
# """
## check current indices equals match
if tempWord[letterWoordenIndex] == woord[woordenIndex]:
antwoord += tempWord[letterWoordenIndex] ## append char to string using +
## increment indices
letterWoordenIndex += 1
woordenIndex += 1
## check if index is filled
if letterWoordenIndex == len(tempWord):
break
else:
woordenIndex += 1
# """ ## debug output comparing final results
print(antwoord, '>==<', tempWord)
# """
## assert that the accumulated result (antwoord)
## equates to the tempWord
if antwoord == tempWord:
# """ ## debug assert true
print('Yep\n')
# """
print(antwoord)
break
## no need to use else here
## if the code inside the above if executes, then it's already game-over
antwoord = '' ## empty the string
# """ ## debug assert false
print('Nope\n')
# """
## antwoord would be empty if everything failed
if antwoord == '':
print('GEEN')
You are iterating over the wrong list with your line
for j in range(0, len(letterwoorden[a])):
as this increases a for all letterwoordenagain โ€“ you already iterate over letterwoorden with the first loop, for i in range(0, 8):. Changing that to iterate over the word in question led to another error if you run out of 'source' characters (the length of invoer) OR of 'compare' characters (the word woord[c]). You must also take care to reset your b and c counters when restarting a compare.
At the very end, you test antwoord[a] but a may be out of range
The following code works
import sys
invoer = input()
letterwoorden = [['T','W','E','E'], ['D','R','I','E'], ['V','I','E','R'],
['V','I','J','F'], ['Z','E','S'], ['Z','E','V','E','N'], ['A','C','H','T'],
['N','E','G','E','N']]
antwoord = []
woord = [str(a) for a in str(invoer)]
L = len(woord)
a = 0
b = 0
c = 0
for i in range(len(letterwoorden)):
b = 0
c = 0
for j in range(len(woord)):
print ('test', a,b,c, letterwoorden[a][b], woord[c])
if letterwoorden[a][b] == woord[c]:
antwoord.append(letterwoorden[a][b])
b = b + 1
if b >= len(letterwoorden[a]):
break
c = c + 1
else:
c = c + 1
if antwoord == letterwoorden[a]:
print(antwoord)
break
else:
a = a + 1
antwoord = []
if antwoord == []:
print('geen')
A few additional notes: you don't need to maintain separate variables if you already have a loop variable. Where you use a, for example, you can also use the loop i; and the same with j.
About all of your comparing can be done much more efficiently, since Python can immediately check if a phrase contains another phrase: if straw in haystack. So, basically,
invoer = 'ZEEVERS'
letterwoorden = ['TWEE', 'DRIE', 'VIER', 'VIJF', 'ZES', 'ZEVEN', 'ACHT', 'NEGEN']
for word in letterwoorden:
if word in invoer:
print (word)
break
else:
print ('geen')
where the else is linked to the for and not to the else, to check if the loop stopped for a result.

Resources