Indexing problem in 2d array

  • (2 Pages)
  • +
  • 1
  • 2

16 Replies - 5245 Views - Last Post: 01 November 2011 - 08:54 AM Rate Topic: -----

#1 izthrower  Icon User is offline

  • D.I.C Head

Reputation: 13
  • View blog
  • Posts: 233
  • Joined: 11-February 09

Indexing problem in 2d array

Posted 27 October 2011 - 09:13 AM


from Tkinter import *
import tkMessageBox
from string import *
from random import *

class Application(Frame):
    def info(self):
        tkMessageBox.showinfo("Text", "This program uses two different encryption methods to produce one encrypted text")
    
    def helps(self):
        tkMessageBox.showinfo("Text", "Enter your plain text first, Then enter your two keys and click encrypt to get your plain text encrypted")
            
    def createWidgets(self):
        #Menu Bar!
        self.menubar = Menu(self)
        filemenu = Menu(self.menubar, tearoff=0)
        filemenu.add_command(label="Info",command = self.info)
        filemenu.add_separator()
        filemenu.add_command(label="Exit", command=root.quit)
        self.menubar.add_cascade(label="File", menu=filemenu)
        
        helpmenu = Menu(self.menubar, tearoff=0)
        helpmenu.add_command(label="Instructions", command=self.helps)
        self.menubar.add_cascade(label="Help", menu=helpmenu)
        
        root.config(menu=self.menubar)
        
        #Text Objects        
        self.ptext = Text(self, width = 30, height = 10)
        self.ptext.grid(row = 2, column = 3)
        
        
        self.key1 = Text(self, width = 30, height = 2)
        self.key1.grid(row = 4, column = 3)
        
        
        self.key2 = Text(self, width = 30, height = 2)
        self.key2.grid(row = 6, column = 3)
        
        
        #self.encrypt(plain ,firstkey ,secondkey)                
        #Buttons
        self.crypt = Button(self, text = "Encrypt", command = self.encrypt)
        self.crypt.grid(row = 10, column = 1)
        #self.encrypt()
        #labels
        self.lptext = Label(self, text = "Enter Plain Text Here:")
        self.lptext.grid(row = 2, column = 0)
        self.lkey1 = Label(self, text = "Enter First Key Here:")
        self.lkey1.grid(row = 4, column = 0)
        self.lkey2 = Label(self, text = "Enter Second Key Here:")
        self.lkey2.grid(row = 6, column = 0)
        
        #return plain, firstkey, secondkey 
        
    def encrypt(self):
        plain = self.ptext.get(1.0,END)
        firstkey = self.key1.get(1.0,END)
        secondkey = self.key2.get(1.0,END)
        block = []
        arraychar = []
        key1 = []
        throwaway = []
        plainarray = []
        cyphertext = []
        inc = 0
        count = 0
        place = 0
        avalchars = "AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz0123456789`-=~!@#$%^&*()_+[]<>{}|;':,/"
        firstkey = firstkey.rstrip("\n")
        plain = plain.rstrip("\n")
        lenkey1 = len(str(firstkey))
        #Switching Strings to Arrays        
        for ch in str(firstkey):
            key1.append(ch)
        
        for ch in str(avalchars):
            throwaway.append(ch)
            
        for ch in str(plain):
            plainarray.append(ch)
        #End swiching strings to arrays
        #finding length
        lenthrow = len(throwaway)
        #Making the plain text an even number of characters by appending an additional 
        #character to the end
        if len(plainarray)%2 != 0:
            rand = randint(0,lenthrow)
            findch = throwaway[rand]
            plainarray.append(findch)
            throwaway.remove(findch)
            lenthrow = lenthrow - 1
        #gets random characters if length is < 9                      
        if lenkey1 < 9:
            rang = 9 - lenkey1
            for i in range(rang):
                rand = randint(0,lenthrow)
                findch = throwaway[rand]
                key1.append(findch)
                throwaway.remove(findch)
                lenthrow = lenthrow - 1
        #eliminates doubles from the key as doubles increased the length of avalchars past 90 
        #which creates more than a 9 by 10 block and eliminates some symbols        
        for i in range(lenkey1):
            char = key1[i]
            chcount = key1.count(char)
            if chcount > 1:
                key1.remove(char)
                rand = randint(0,lenthrow)
                findch = throwaway[rand]
                key1.append(findch)
                throwaway.remove(findch)
                lenthrow = lenthrow - 1
        #gets the char from key 1 and finds that character in aval chars and replaces it with a ? in aval chars                          
        for index in range(len(key1)):
            ch = key1[index]
            avalchars = avalchars.replace(ch,"?")
        #appends chars as the first 9 characters in array chars            
        for x in range(len(key1)):
            ch = key1[x]
            arraychar.append(ch)
        #appends chars from aval chars to arraychars, if the char is ? it removes it from arraychar
        #to keep the 90 characters and remove the characters that are in the first key from the block    
        for ch in str(avalchars):
            arraychar.append(ch)
            if ch == "?":
                arraychar.remove("?")
        #creates the block and fills it with arraychars by rows and columns        
        for row in range(10):
            block.append([])
            if row > 0:
                count = row*9 
            for column in range(9):
                inc = count + column
                block[row].append(arraychar[inc])
        #first step to encryting the plain text        
        while place < len(plainarray):
            firstch = plainarray[place]
            secondch = plainarray[place+1]
            print block.index(plainarray[place])
            print block.index(plainarray[place+1])
            place = place + 2
            
               
    def __init__(self,master =None):
        Frame.__init__(self, master, height = 300, width= 450)
        self.grid_propagate(0)
        self.grid()
        self.createWidgets()
        #self.encrypt(x,y,z)

root = Tk()
app = Application(master = root)
app.mainloop()




so in lines 129 to 135 i create a 2d array. But in lines 140, 141 i try to find the index of a specific character in the 2d arrray and the problem that keeps occuring is that list.index(x) x doesnt exist in the array, but the problem is that it does and im worryed that it could be the fact that it is the 2d array. Any ideas on why this is occuring or how to fix it?
Thanks

Is This A Good Question/Topic? 1
  • +

Replies To: Indexing problem in 2d array

#2 Martyr2  Icon User is offline

  • Programming Theoretician
  • member icon

Reputation: 4316
  • View blog
  • Posts: 12,096
  • Joined: 18-April 07

Re: Indexing problem in 2d array

Posted 27 October 2011 - 09:27 AM

Block is a 2D array, meaning that when you are using block.index() are searching only the first dimension. block.index in this case will return a list, not the chars in that list. Did you mean something like block[row].index(plainarray[place])? Here we are saying, in the list of lists, find the "row" and then on that list look for the character.

I think you are just not going down deep enough into the second list. You are trying to search for plainarray[place] on the first dimension... a dimension of lists which of course it won't find.

:)
Was This Post Helpful? 2
  • +
  • -

#3 Motoma  Icon User is offline

  • D.I.C Addict
  • member icon

Reputation: 452
  • View blog
  • Posts: 796
  • Joined: 08-June 10

Re: Indexing problem in 2d array

Posted 27 October 2011 - 10:22 AM

Agreed; if place is > 11 you will fail on line 140, if it is > 10, you will fail on line 14. Therefore, if len(plainarray) > 10, the code fails.
Was This Post Helpful? 1
  • +
  • -

#4 izthrower  Icon User is offline

  • D.I.C Head

Reputation: 13
  • View blog
  • Posts: 233
  • Joined: 11-February 09

Re: Indexing problem in 2d array

Posted 27 October 2011 - 02:42 PM

What do you mean the code will fail if the len(plainarray) > 10, length doesnt matter, and plus even if the length is odd, the code appends a random character so that the length will always be even..unless im overlooking something.
Was This Post Helpful? 1
  • +
  • -

#5 izthrower  Icon User is offline

  • D.I.C Head

Reputation: 13
  • View blog
  • Posts: 233
  • Joined: 11-February 09

Re: Indexing problem in 2d array

Posted 27 October 2011 - 04:27 PM

I understand what your saying about the rows, the only problem i see is that even if i did a for loop or a while loop, if
the index doesnt return anything then its gona be an error, and would stop the program before it got to the second row.
Ideas on how to avoid this?
Was This Post Helpful? 1
  • +
  • -

#6 Motoma  Icon User is offline

  • D.I.C Addict
  • member icon

Reputation: 452
  • View blog
  • Posts: 796
  • Joined: 08-June 10

Re: Indexing problem in 2d array

Posted 27 October 2011 - 09:15 PM

Hrm, it looks like I misread your code last time I addressed it; ignore my previous comments.

The following code with go through each row in block and store the index if it was found:
foreach row in block:
    if firstch in row:
        firstindex = row.index(firstch)
    if secondch in row:
        secondindex = row.index(secondch)


Was This Post Helpful? 1
  • +
  • -

#7 baavgai  Icon User is offline

  • Dreaming Coder
  • member icon

Reputation: 5780
  • View blog
  • Posts: 12,595
  • Joined: 16-October 07

Re: Indexing problem in 2d array

Posted 28 October 2011 - 04:57 AM

I fiddled around with this, trying to see what you were doing.

import os, sys
from random import *
from pprint import pprint


def stringToArray(s):
	# for ch in str(firstkey):
	#    key1.append(ch)
	return [ c for c in s ]

def addThrowAway(throwaway, array):
	findch = throwaway[randint(0,len(throwaway)-1)]
	array.append(findch)
	throwaway.remove(findch)

def getArrayChar(key1, avalchars):
	#appends chars as the first 9 characters in array chars
	arraychar = [] # first use of variable, time to declare it
	for x in range(len(key1)):
		ch = key1[x]
		arraychar.append(ch)
		
	#appends chars from aval chars to arraychars, if the char is ? it removes it from arraychar
	#to keep the 90 characters and remove the characters that are in the first key from the block    
	for ch in str(avalchars):
		arraychar.append(ch)
		if ch == "?":
			arraychar.remove("?")
	return arraychar


def getBlock(arraychar):
	block = []
	count = 0
	#creates the block and fills it with arraychars by rows and columns        
	for row in range(10):
		block.append([])
		if row > 0:
			count = row*9 
		for column in range(9):
			inc = count + column
			block[row].append(arraychar[inc])
	return block


def encrypt(plain, firstkey, secondkey):
	# don't need this yet
	# block = []
	# arraychar = []
	# key1 = []
	# throwaway = []
	# plainarray = []
	# cyphertext = []
	# inc = 0
	# count = 0
	# place = 0
	
	avalchars = "AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz0123456789`-=~!@#$%^&*()_+[]<>{}|;':,/"
	
	firstkey = firstkey.rstrip("\n")
	plain = plain.rstrip("\n")
	# lenkey1 = len(str(firstkey))
	
	#Switching Strings to Arrays        
	key1 = stringToArray(firstkey)
	throwaway = stringToArray(avalchars)
	plainarray = stringToArray(plain)
	
	# don't do this
	# finding length 
	# lenthrow = len(throwaway)
	
	#Making the plain text an even number of characters by appending an additional 
	#character to the end
	if len(plainarray)%2 != 0:
		addThrowAway(throwaway, plainarray)
	
	KeyLen = 9 # added; magic numbers bad
	# gets random characters if length is < 9
	while len(key1)<KeyLen:
		addThrowAway(throwaway, key1)
				
	#eliminates doubles from the key as doubles increased the length of avalchars past 90 
	#which creates more than a 9 by 10 block and eliminates some symbols        
	for i in range(KeyLen):
		char = key1[i]
		if key1.count(char) > 1:
			key1.remove(char)
			addThrowAway(throwaway, key1)
			
	#gets the char from key 1 and finds that character in aval chars and replaces it with a ? in aval chars                          
	for index in range(len(key1)):
		ch = key1[index]
		avalchars = avalchars.replace(ch,"?")
		
	arraychar = getArrayChar(key1, avalchars)
	block = getBlock(arraychar)
	
	# just to check on things
	print "plainarray =", plainarray
	print "key1 =", key1
	pprint(block) 

	#first step to encryting the plain text
	place = 0
	while place < len(plainarray):
		firstch = plainarray[place]
		secondch = plainarray[place+1]
		
		# this will fail, block is a list of lists
		print block.index(plainarray[place])
		print block.index(plainarray[place+1])
		place = place + 2

encrypt('A Secret Message', 'foo', 'bar')



You've gone out of your way to make block a 2d array, but I'm not entirely sure why. You can't easily look up a char value in a list of lists.

I tried to stay as true to your code as I could. There are a number of things I'd change. The block generator with the row>0 was more than a little odd.

You can do the same thing with:
def getBlock(arraychar):
	(rows, cols) = (10, 9)
	return [ arraychar[row*cols:(row+1)*cols] for row in range(rows) ]



Hope this helps.
Was This Post Helpful? 1
  • +
  • -

#8 izthrower  Icon User is offline

  • D.I.C Head

Reputation: 13
  • View blog
  • Posts: 233
  • Joined: 11-February 09

Re: Indexing problem in 2d array

Posted 28 October 2011 - 07:50 AM


from Tkinter import *
import tkMessageBox
from string import *
from random import *

class Application(Frame):
    def info(self):
        tkMessageBox.showinfo("Text", "This program uses two different encryption methods to produce one encrypted text")
    
    def helps(self):
        tkMessageBox.showinfo("Text", "Enter your plain text first, Then enter your two keys and click encrypt to get your plain text encrypted")
            
    def createWidgets(self):
        #Menu Bar!
        self.menubar = Menu(self)
        filemenu = Menu(self.menubar, tearoff=0)
        filemenu.add_command(label="Info",command = self.info)
        filemenu.add_separator()
        filemenu.add_command(label="Exit", command=root.quit)
        self.menubar.add_cascade(label="File", menu=filemenu)
        
        helpmenu = Menu(self.menubar, tearoff=0)
        helpmenu.add_command(label="Instructions", command=self.helps)
        self.menubar.add_cascade(label="Help", menu=helpmenu)
        
        root.config(menu=self.menubar)
        
        #Text Objects        
        self.ptext = Text(self, width = 30, height = 10)
        self.ptext.grid(row = 2, column = 3)
        
        
        self.key1 = Text(self, width = 30, height = 2)
        self.key1.grid(row = 4, column = 3)
        
        
        self.key2 = Text(self, width = 30, height = 2)
        self.key2.grid(row = 6, column = 3)
        
        
        #self.encrypt(plain ,firstkey ,secondkey)                
        #Buttons
        self.crypt = Button(self, text = "Encrypt", command = self.encrypt)
        self.crypt.grid(row = 10, column = 1)
        #self.encrypt()
        #labels
        self.lptext = Label(self, text = "Enter Plain Text Here:")
        self.lptext.grid(row = 2, column = 0)
        self.lkey1 = Label(self, text = "Enter First Key Here:")
        self.lkey1.grid(row = 4, column = 0)
        self.lkey2 = Label(self, text = "Enter Second Key Here:")
        self.lkey2.grid(row = 6, column = 0)
        
        #return plain, firstkey, secondkey 
    def getBlock(self,arraychar):
        (rows, cols) = (10, 9)
        return [ arraychar[row*cols:(row+1)*cols] for row in range(rows) ]
           
    def encrypt(self):
        plain = self.ptext.get(1.0,END)
        firstkey = self.key1.get(1.0,END)
        secondkey = self.key2.get(1.0,END)
        block = []
        self.arraychar = []
        key1 = []
        throwaway = []
        plainarray = []
        cyphertext = []
        found = 100
        found2 = 100
        g = 0
        inc = 0
        count = 0
        place = 0
        avalchars = "AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz0123456789`-=~!@#$%^&*()_+[]<>{}|;':,/"
        firstkey = firstkey.rstrip("\n")
        plain = plain.rstrip("\n")
        lenkey1 = len(str(firstkey))
        #Switching Strings to Arrays        
        for ch in str(firstkey):
            key1.append(ch)
        
        for ch in str(avalchars):
            throwaway.append(ch)
            
        for ch in str(plain):
            plainarray.append(ch)
        #End swiching strings to arrays
        #finding length
        lenthrow = len(throwaway)
        #Making the plain text an even number of characters by appending an additional 
        #character to the end
        if len(plainarray)%2 != 0:
            rand = randint(0,lenthrow)
            findch = throwaway[rand]
            plainarray.append(findch)
            throwaway.remove(findch)
            lenthrow = lenthrow - 1
        #gets random characters if length is < 9                      
        if lenkey1 < 9:
            rang = 9 - lenkey1
            for i in range(rang):
                rand = randint(0,lenthrow)
                findch = throwaway[rand]
                key1.append(findch)
                throwaway.remove(findch)
                lenthrow = lenthrow - 1
        #eliminates doubles from the key as doubles increased the length of avalchars past 90 
        #which creates more than a 9 by 10 block and eliminates some symbols        
        for i in range(lenkey1):
            char = key1[i]
            chcount = key1.count(char)
            if chcount > 1:
                key1.remove(char)
                rand = randint(0,lenthrow)
                findch = throwaway[rand]
                key1.append(findch)
                throwaway.remove(findch)
                lenthrow = lenthrow - 1
        #gets the char from key 1 and finds that character in aval chars and replaces it with a ? in aval chars                          
        for index in range(len(key1)):
            ch = key1[index]
            avalchars = avalchars.replace(ch,"?")
        #appends chars as the first 9 characters in array chars            
        for x in range(len(key1)):
            ch = key1[x]
            self.arraychar.append(ch)
        #appends chars from aval chars to arraychars, if the char is ? it removes it from arraychar
        #to keep the 90 characters and remove the characters that are in the first key from the block    
        for ch in str(avalchars):
            self.arraychar.append(ch)
            if ch == "?":
                self.arraychar.remove("?")
        block = self.getBlock(self.arraychar)
        
        #first step to encryting the plain text
        while place <= len(plainarray):
            for i in range(10):
                try:
                    firstch = plainarray[place]
                    secondch = plainarray[place+1]
                    found = block[i].index(firstch)
                    found2 = block[i].index(secondch)
                    if found and found2 != 100:
                        print "found =", found, i
                        found = 100
                        print "found2 =", found2, i
                        found2 = 100
                        
                except:
                    pass
                print "row",i
            place = place + 2
        
        print block    
    
    
               
    def __init__(self,master =None):
        Frame.__init__(self, master, height = 300, width= 450)
        self.grid_propagate(0)
        self.grid()
        self.createWidgets()
        
        #self.encrypt(x,y,z)

root = Tk()
app = Application(master = root)
app.mainloop()





so even with the changes you mentioned above with the getblock method i still get an error when i use the index function, line 137 to line 153 is where im catching the error and finding the indexs of the characters but for some reason it only likes printing the index of the last 2 characters, and the found and found2 im using as like a true false holder so technacly if found or found2 is 100 it means it hasnt found the index but if it changes it has and will print it out. Any ideas?
Was This Post Helpful? 1
  • +
  • -

#9 baavgai  Icon User is offline

  • Dreaming Coder
  • member icon

Reputation: 5780
  • View blog
  • Posts: 12,595
  • Joined: 16-October 07

Re: Indexing problem in 2d array

Posted 28 October 2011 - 09:36 AM

The changes I offered are simply to organize the code better. And to spot the problem. The parts that are most important are the comments:
# just to check on things
# this will fail, block is a list of lists



Let's look at the output of the program I previously posted:
plainarray = ['A', ' ', 'S', 'e', 'c', 'r', 'e', 't', ' ', 'M', 'e', 's', 's', 'a', 'g', 'e']
key1 = ['f', 'o', '$', 't', '-', 'x', 'H', 'O', 'h']
[['f', 'o', '$', 't', '-', 'x', 'H', 'O', 'h'],
 ['A', 'a', 'B', 'b', 'C', 'c', 'D', 'd', 'E'],
 ['e', 'F', 'G', 'g', 'I', 'i', 'J', 'j', 'K'],
 ['k', 'L', 'l', 'M', 'm', 'N', 'n', 'P', 'p'],
 ['Q', 'q', 'R', 'r', 'S', 's', 'T', 'U', 'u'],
 ['V', 'v', 'W', 'w', 'X', 'Y', 'y', 'Z', 'z'],
 ['0', '1', '2', '3', '4', '5', '6', '7', '8'],
 ['9', '`', '=', '~', '!', '@', '#', '%', '^'],
 ['&', '*', '(', ')', '_', '+', '[', ']', '<'],
 ['>', '{', '}', '|', ';', "'", ':', ',', '/']]
Traceback (most recent call last):
  File "t.py", line 119, in <module>
    encrypt('A Secret Message', 'foo', 'bar')
  File "t.py", line 115, in encrypt
    print block.index(plainarray[place])
ValueError: 'A' is not in list
>Exit code: 1



So, 'A' isn't found. This is because block is a list of lists. The is a list, in that list, that has A...

Here's a simpler example:
>>> block = [['A', 'a'],['B', 'b'], ['C', 'c']]
>>> block.index('a')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: 'a' is not in list
>>> block[0].index('a')
1
>>> block[0].index('x')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: 'x' is not in list
>>> 



So, list.index will return the location of a value, but will raise a ValueError if item isn't found. No really the nicest behavior. First you need to check if the value is there, then ask for the index.

e.g.
>>> def searchNice(l, value):
...     if value in l:
...             print value, 'found at', l.index(value)
...     else:
...             print value, 'not found.'
... 
>>> searchNice(block, 'a')
a not found.
>>> searchNice(block[0], 'a')
a found at 1
>>> searchNice(block[0], 'x')
x not found.
>>> 



However, this will never work on your 2D list. Your solution is to not have a 2D list, just a list of characters, and do an index on that. Or, to loop through the list of lists and do an index of each of those lists.
Was This Post Helpful? 1
  • +
  • -

#10 izthrower  Icon User is offline

  • D.I.C Head

Reputation: 13
  • View blog
  • Posts: 233
  • Joined: 11-February 09

Re: Indexing problem in 2d array

Posted 01 November 2011 - 07:28 AM

Well i cant have just a list as im designing a block cypher and i need specific rows and columns, and in my code above in line 137 to 153 im going thru each array in the array and preforming the index on each array. The only problem is that sometimes the program will only index the last 2 characters in the plain text and i have no clue why. Any ideas?
Was This Post Helpful? 1
  • +
  • -

#11 izthrower  Icon User is offline

  • D.I.C Head

Reputation: 13
  • View blog
  • Posts: 233
  • Joined: 11-February 09

Re: Indexing problem in 2d array

Posted 01 November 2011 - 07:58 AM

So upon further investigation it seams that my code between 137 and 153 works fine, BUT it only works if firstch and secondch are in the same row, if they arnt it for some reason skips over both of them. Any ideas on how to fix this?
Was This Post Helpful? 0
  • +
  • -

#12 baavgai  Icon User is offline

  • Dreaming Coder
  • member icon

Reputation: 5780
  • View blog
  • Posts: 12,595
  • Joined: 16-October 07

Re: Indexing problem in 2d array

Posted 01 November 2011 - 08:11 AM

try: 
	firstch = plainarray[place]
	secondch = plainarray[place+1]
	found = block[i].index(firstch) # fail will boot me
	found2 = block[i].index(secondch) # fail will boot me
	# you are relying on both numbers being in the same row!!!
	# this won't work
	
	# what do you think this means?
	# found is being evaluated as a boolean
	# found2 is being compared to 100, for some uknown reason
	if found and found2 != 100:
		print "found =", found, i
		# this is pointless
		# if we make it here, then both values have been loaded
		found = 100 
		print "found2 =", found2, i
		found2 = 100
except: # we have chosen to ignore all errors, not a good idea
	pass



Write a funciton to find one character in the block. Return the row and column, or some kind of null if not found.

I changed my above to include this:
#first step to encryting the plain text
for place in range(0,len(plainarray),2):
	first = findInBlock(block, plainarray[place])
	second = findInBlock(block, plainarray[place+1])
	print "1st", plainarray[place], first
	print "2nd", plainarray[place+1], second



This is what I got:
1st A (1, 0)
2nd   None
1st S (4, 4)
2nd e (1, 6)
1st c (0, 7)
2nd r (4, 3)
1st e (1, 6)
2nd t (4, 7)
1st   None
2nd M (3, 2)
1st e (1, 6)
2nd s (4, 5)
1st s (4, 5)
2nd a (1, 1)
1st g (2, 0)
2nd e (1, 6)



You'll have to get your own findInBlock working.
Was This Post Helpful? 1
  • +
  • -

#13 izthrower  Icon User is offline

  • D.I.C Head

Reputation: 13
  • View blog
  • Posts: 233
  • Joined: 11-February 09

Re: Indexing problem in 2d array

Posted 01 November 2011 - 08:16 AM

I have to ignore errors because if i dont it will throw an error and kill the program before i can get all the way thru the block.
Was This Post Helpful? 0
  • +
  • -

#14 baavgai  Icon User is offline

  • Dreaming Coder
  • member icon

Reputation: 5780
  • View blog
  • Posts: 12,595
  • Joined: 16-October 07

Re: Indexing problem in 2d array

Posted 01 November 2011 - 08:23 AM

When you ignore an error, make sure it's the right one. If you don't give a name, wrap large blocks in the try and never print anything out, you can't know. It means other potential errors in your program are also hidden.

For the index method, there's no reason to get an error. You just have to check first. e.g.
if ch in block[row]:
   col = block[row].index(ch)


Was This Post Helpful? 1
  • +
  • -

#15 izthrower  Icon User is offline

  • D.I.C Head

Reputation: 13
  • View blog
  • Posts: 233
  • Joined: 11-February 09

Re: Indexing problem in 2d array

Posted 01 November 2011 - 08:40 AM

then to cycle thru each row in ur example nest it in a for loop?
Was This Post Helpful? 0
  • +
  • -

  • (2 Pages)
  • +
  • 1
  • 2