'How to store contents of string array into 2D array in python and perform operations without any built in function?

I have tried almost everything I cannot figure it out. I cannot figure out which array to use. This is the question and the required output:



Solution 1:[1]

I would first think, how you want to solve this? You can solve this probably with regex replace.

I would do somethin like this:

import re

def print_file(path):
    with open(f'{path}', 'r') as fr:
        for line in fr.readlines():
            print(line, end="")


def create_file_header():
  with open(r'myfpath_new.txt', 'w+' , encoding='utf-8') as fw:
    print("""ROLL NO NAME                        CRS    Md Ss Fn
=================================== ====== == == ==
""", file=fw, end='')


with open(r'myfpath.txt', 'w+' , encoding='utf-8') as fw:
    print("""ROLL NO NAME                        CRS    Md Ss Fn
=================================== ====== == == ==
BSEF09M001Hammad Khan               ITC    22 21 31
BSEF09M001Hammad Khan               PF     14 15 25
BSEF09M001Hammad Khan               DLD    20 18 22
BSEF09M003Younas Ahmad              ITC    34 AB 29
BSEF09M003Younas Ahmad              PF     34 25 30
BSEF09M003Younas Ahmad              DLD    10 15 10
BSEF09M005Riffat Kaleem             ITC    33 20 33
BSEF09M005Riffat Kaleem             PF     26 11 35
BSEF09M005Riffat Kaleem DLD    30 24 38
BSEF09M012Barkat Jan                ITC    25 18 34
BSEF09M012Barkat Jan                PF     19    28
BSEF09M012Barkat Jan                DLD    28 21 34
BITF09M002Khawer Hayat              ITC       18 37
       002Khawer Hayat              PF     19 17 27
BITF09M002Khawer Hayat              DLD    31 22 34
BITF09M003Kishwar Hameed            ITC    24 20   
BITF09M003Kishwar Hameed            PF     28 24 37
BITF09M003Kishwar Hameed            DLD    19 15 26
BITF09M010Yasir Ubaid                              
BITF09M010Yasir Ubaid               PF     25 21 34
BITF09M010Yasir Ubaid               DLD    29 22 33
""", file=fw, end='')


print_file(r'myfpath.txt')

def find_cols_length(filepath):
    """
    Fids cols lengh in second line
    filepath: str, filepath
    return: list
    """
    with open(f'myfpath.txt', 'r') as fr:
        first_line = fr.readline() #consumes first line
        second_line = fr.readline()
        second_line = second_line.strip().split(" ")
        cols_len_list = []
        i=0
        for col in second_line: ### this is just so you start to know format
            print(f'Col{i:1} len is {len(col):02} - {repr(col)}')
            cols_len_list.append(len(col))
            i+=1
        return cols_len_list

cols_len_list = find_cols_length(filepath=r'myfpath.txt')

def fix_numbers_in_line(line, cols_len_list):
  """
  line: string, line to read 3 grades
  cols_len_list: list, list of cols lengths
  return line with number fixed
  """
  line = line.strip('\n')
  last = -(cols_len_list[-1])
  middle_from = -(cols_len_list[-2] +1) + last #+1 space
  middle_to = middle_from + 2 #backward 2 digits
  first_from = -(cols_len_list[-2] +1 ) + middle_from #+1 space
  first_to =  first_from +2 #backward 2 digits
  #print(line)
  if not line[last::].isdigit(): #last grade -1 because len count, counts \n
    line = list(line)
    line[last::] = ['0', '0']
    line = ''.join(line)
  if not line[middle_from: middle_to].isdigit():#middle grade +1 to count one space
    line = list(line)
    line[middle_from:middle_to] = ['0', '0']
    line = ''.join(line)
  if not line[first_from:first_to].isdigit():#first grade
    line = list(line)
    line[first_from:first_to] = ['0', '0']
    line = ''.join(line)
  return line


def insert_data_in_list(list_, class_name, surname):
  """
  list_: list
  class_name: str
  surname: str
  return: list, [class_name, surname, exam, grade1 ,grade2 ,grade3, '\n']
  """
  list_.append('\n')
  list_ = [class_name] + [surname] + list_
  return list_


def write_data(line):
  """
  line: str
  append one line to file
  """
  with open(r'myfpath_new.txt', 'a+' , encoding='utf-8') as fw:
      print(' '.join(line), file=fw, end='')


def calcl_last_grade(total_grade): #https://en.wikipedia.org/wiki/Academic_grading_in_Canada
  """
  Calculate grade
  total_grade: int
  return grade
  """
  if total_grade >= 95:
    return 'A+'
  elif  87 <= total_grade < 95:
    return 'A'
  elif 80 <= total_grade < 87:
    return 'A-'
  elif 77 <= total_grade < 80:
    return 'B+'
  elif 74 <= total_grade < 77:
    return 'B'
  elif 70 <= total_grade < 74:
    return 'B-'
  elif 67 <= total_grade < 70:
    return 'C+'
  elif 64 <= total_grade < 67:
    return 'C'
  elif 60 <= total_grade < 64:
    return 'C-'
  elif 57 <= total_grade < 60:
    return 'D+'
  elif 54 <= total_grade < 57:
    return 'D'
  elif 50 <= total_grade < 53:
    return 'D-'
  elif 0 <= total_grade < 50:
    return 'F'

def students_grades(index, grades):
  with open(r'result.txt', 'a+' , encoding='utf-8') as fr:
    header_ = ['Subject',  'Sessional', 'Midterm', 'Final', 'Total', 'Grade' ]
    spaces = "  "
    space = " "
    miss_header = " "*(3 - len(str(index) ))
    headerspaces = " "*(len(f'{index}.{miss_header}'))
    print(f'{index}.{miss_header}{grades[0][0][:9]} {grades[0][0][10::]} {grades[0][1].strip()}',file=fr, end='\n')
    spaces = "  "
    print(f'{headerspaces}{header_[0]}{spaces}{header_[1]}{spaces}{header_[2]}{spaces}{header_[3]}{spaces}{header_[4]}{spaces}{header_[5]}',file=fr, end='\n')
    for grade in grades:
      col0_miss = " "*(len(header_[0]) - len(grade[2]))
      col1_miss = " "*(len(header_[1]) - len(grade[3]))
      col2_miss = " "*(len(header_[2]) - len(grade[4]))
      col3_miss = " "*(len(header_[3]) - len(grade[5]))
      total = int(grade[3])+ int(grade[4]) + int(grade[5])
      col4_miss = " "*(len(header_[4]) - len(str(total)))
      result = calcl_last_grade(total)
      col5_miss = " "*(len(header_[4]) - len(result))
      result_line = f'{headerspaces}{grade[2]}{col0_miss}{spaces}{col1_miss}{grade[3]}{spaces}{col2_miss}{grade[4]}{spaces}{col3_miss}{grade[5]}{spaces}{col4_miss}{total}{spaces}{result}{col5_miss}'
      print(result_line,file=fr, end='\n')


def sanitize_file_and_results(cols_len_list):
    """
    trys to automaticaly fix your file
    cols_len_list: list, list of cols lens ordered
    return, file cleaned
    """
    regex_1_space = re.compile(r"\s+")  # this is just to start to understand how powerfull regex can be
    regex_name_surname = re.compile(r"[a-zA-Z]")
    regex_crs = re.compile(r"[A-Z]{3}")
    create_file_header()
    with open(f'myfpath.txt', 'r') as fr:
        first_line = fr.readline()  # consumes first line
        second_line = fr.readline()  # consumes first line
        lines = fr.readlines()
        chunks = len(lines) // 3
        index = 1
        for i in range(0, chunks, 1):
            lines3 = lines[i * 3:i * 3 + 3]
            class_name = ''
            surname = ''
            grades_data_list = []
            k = 0
            for line in lines3:
                line = fix_numbers_in_line(line, cols_len_list)
                line_1_space = regex_1_space.sub(" ", line)  ###removes \n
                line_to_list = line_1_space.split(" ")
                if line_to_list[0] > class_name:
                    class_name = line_to_list[0]
                if line_to_list[1] > surname:
                    surname = line_to_list[1]

                k += 1
                if k == 1 and 'ITC   ' not in line_to_list[2]:
                    line_to_list[-4] = 'ITC   '
                if k == 2 and 'PF    ' not in line_to_list:
                    line_to_list[-4] = 'PF    '
                if k == 3 and 'DLD  ' not in line_to_list:
                    line_to_list[-4] = 'DLD   '
                grades_data_list.append(line_to_list[-4::])

            miss_whitespaces = cols_len_list[0] - (len(class_name) + len(surname)) - 1
            surname = f"{surname}{' ' * miss_whitespaces}"
            temp = grades_data_list
            grades_data_list = [insert_data_in_list(n, class_name, surname) for n in grades_data_list]
            [write_data(n) for n in grades_data_list]
            students_grades(index, grades_data_list)
            index += 1

sanitize_file_and_results(cols_len_list=cols_len_list)


print_file(r'result.txt')

Result:

ROLL NO NAME                        CRS    Md Ss Fn
=================================== ====== == == ==
BSEF09M001Hammad Khan               ITC    22 21 31
BSEF09M001Hammad Khan               PF     14 15 25
BSEF09M001Hammad Khan               DLD    20 18 22
BSEF09M003Younas Ahmad              ITC    34 AB 29
BSEF09M003Younas Ahmad              PF     34 25 30
BSEF09M003Younas Ahmad              DLD    10 15 10
BSEF09M005Riffat Kaleem             ITC    33 20 33
BSEF09M005Riffat Kaleem             PF     26 11 35
BSEF09M005Riffat Kaleem DLD    30 24 38
BSEF09M012Barkat Jan                ITC    25 18 34
BSEF09M012Barkat Jan                PF     19    28
BSEF09M012Barkat Jan                DLD    28 21 34
BITF09M002Khawer Hayat              ITC       18 37
       002Khawer Hayat              PF     19 17 27
BITF09M002Khawer Hayat              DLD    31 22 34
BITF09M003Kishwar Hameed            ITC    24 20   
BITF09M003Kishwar Hameed            PF     28 24 37
BITF09M003Kishwar Hameed            DLD    19 15 26
BITF09M010Yasir Ubaid                              
BITF09M010Yasir Ubaid               PF     25 21 34
BITF09M010Yasir Ubaid               DLD    29 22 33
Col0 len is 35 - '==================================='
Col1 len is 06 - '======'
Col2 len is 02 - '=='
Col3 len is 02 - '=='
Col4 len is 02 - '=='
1.  BSEF09M00 Hammad Khan
    Subject  Sessional  Midterm  Final  Total  Grade
    ITC             22       21     31     74  B    
    PF              14       15     25     54  D    
    DLD             20       18     22     60  C-   
2.  BSEF09M00 Younas Ahmad
    Subject  Sessional  Midterm  Final  Total  Grade
    ITC             34       00     29     63  C-   
    PF              34       25     30     89  A    
    DLD             10       15     10     35  F    
3.  BSEF09M00 Riffat Kaleem
    Subject  Sessional  Midterm  Final  Total  Grade
    ITC             33       20     33     86  A-   
    PF              26       11     35     72  B-   
    DLD             30       24     38     92  A    
4.  BSEF09M01 Barkat Jan
    Subject  Sessional  Midterm  Final  Total  Grade
    ITC             25       18     34     77  B+   
    PF              19       00     28     47  F    
    DLD             28       21     34     83  A-   
5.  BITF09M00 Khawer Hayat
    Subject  Sessional  Midterm  Final  Total  Grade
    ITC             00       18     37     55  D    
    PF              19       17     27     63  C-   
    DLD             31       22     34     87  A    
6.  BITF09M00 Kishwar Hameed
    Subject  Sessional  Midterm  Final  Total  Grade
    ITC             24       20     00     44  F    
    PF              28       24     37     89  A    
    DLD             19       15     26     60  C-   
7.  BITF09M01 Yasir Ubaid
    Subject  Sessional  Midterm  Final  Total  Grade
    ITC             00       00     00      0  F    
    PF              25       21     34     80  A-   
    DLD             29       22     33     84  A-   

Process finished with exit code 0

Fill free to play with it https://colab.research.google.com/drive/1liL6lFn9CSUNlAonaKbzZRm_vq4gg3Wi#scrollTo=p40wGpiB7KKR

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Hildermes José Medeiros Filho