Home > other >  How do I convert this C 2D array code into Python?
How do I convert this C 2D array code into Python?

Time:09-10

I am currently trying to improve my Python coding skills, but am stuck on something. I am attempting to convert some C 2D array code that ignores spaces into Python. What I am trying to do is allow a user to input a number for a 2D array size of their liking and input what they want inside it. For example, 3 would create a 3x3 square. Then, they are to type "D" or "R" depending on the "people's" political affiliation in the 2D array. The input, for example, would be:

R R D *enter D R D *enter D D R *enter

int size = 0;
int input = 0;
int houseAmt = 0;
int R = 0;
int D = 0;
int noChange = 0;
int day = 1;
string check = "";
string cont = "continue";
int quit = 0;

//get n for rows and columns
cin >> size;
//create two dimensional array
char nHood [size][size];
//second array for changed votes
char nHood2 [size][size];
//take user input for grid
for (int i = 0; i < size; i  ) {
   for(int j = 0; j < size; j  ) {
      nHood[i][j] = getchar();
      //ignore spaces
      if (nHood[i][j] == ' ' || nHood[i][j] == '\n') {
         j--;
      }
     
   }
}

My conversion is currently this in Python (left out unrelated code):

from msilib.schema import Condition
import sys
import string
D = 0
R = 0
noChange = 0
houseAmt = 0

size = int(input("Please enter the grid size: "))
print("Please enter either 'D' or 'R' using spaces to separate each 
one:")

nHood = [[] for _ in range(size)]
#second array for changed votes
nHood2 = [[] for _ in range(size)]
#take input for grid
for i in range(0, size):
   for j in range(0, size):
      nHood[i][j] = input().split(' ')[0]
      #ignore spaces
      if nHood[i][j] == ' ' or nHood[i][j] == '\n':
         j -= 1

I keep receiving this error when I run the Python program:

line 73, in nHood[i][j] = input().split(' ')[0] IndexError: list assignment index out of range

Does anyone have any thoughts on how to fix this? Perhaps using .append somewhere? Thanks!

CodePudding user response:

nHood[i] is an empty list, so you should append new element to it.

D = 0
R = 0
noChange = 0
houseAmt = 0

size = int(input("Please enter the grid size: "))
print("Please enter either 'D' or 'R' using spaces to separate each one:")

nHood = [[] for _ in range(size)]
#second array for changed votes
nHood2 = [[] for _ in range(size)]
#take input for grid
for i in range(0, size):
   for j in range(0, size):
      nHood[i].append(input().split(' ')[0])  # Pay attention to this line
      #ignore spaces
      if nHood[i][j] == ' ' or nHood[i][j] == '\n':
         j -= 1
  • Related