Quiz Marks

A file xxxxx.txt contains students' quiz marks.  Each line of the file contains the registration number of the student followed by several integers (separated by a space) which correspond to their quiz marks. Each quiz mark is an integer between 0 and 10 (inclusive). For example, one line of the file could be “17BEC0194 2 6 2 8”, which implies the student with registration number 17BEC0194 has taken 4 quizzes and obtained marks 2, 6, 2, and 8, respectively.  Not all students took the same number of quizzes.  Further, data for a student can appear on more than one line. For example, another line of the input can be “17BEC0194 2 6 2”, in which case the above two lines should be consolidated to “17BEC0194 2 6 2 8 2 6 2”. 

Write a pseudocode and the subsequent Python program which reads the list of student marks, and
(a) print the contents of the file
(b) print the consolidated marks for all students, in ascending order of registration number. Each registration number must be printed exactly once in this consolidated list.
(c) print each student's record along with their average score (rounded to the nearest integer).  If a student's registration number appears in the file without any quiz marks (this can happen), then that student's average score should be 0.  For example, one particular line in this output would be “17BEC0194 2 6 2 8 2 6 2 4” because the average of the 7 quiz marks is 4.  The records must be printed in decreasing order of average.
(d) Given a registration number of a student,  print the registration number of that student along with the consolidated marks and the average of that student.
Also, each part (a)-(d) must be preceded by a title as shown in output below. More specifically, output of (a) must be preceded by “Input file:”, output of (b) must be preceded by “Consolidated data (in increasing order of registration number):”, output of (c) must be preceded by “Consolidated data with average (in decreasing order of average):” and output of (d) must be preceded by “Consolidated data with average for given student:”.
Input format :
Name of the input file which contains the marks of the students.
Register number of the student for whom the consolidated marks and the average has to be printed.
Output format :
(a) Input file : Print the contents of the input file
(b)  Consolidated data : Print the consolidated marks of the students in the increasing order of their registration number
(c) Consolidated data with average : Print each student's record along with their average score (rounded to the nearest integer)
(d) Consolidated data with average for given student: Print the registration number of the student with the consolidated marks and the average
NOTE: input().strip() is used generally to clear invisible newline characters and whitespaces in the received input.
Input:
Name of the input file which contains the marks of the students.
Register number of the student for whom the consolidated marks and the average has to be printed.
Processing:
name = input().rstrip()
reg_num = input().rstrip()
def read_print():
    student = open(name)
    print(student.read(),end='')
    student.close()
print('Input file:')
read_print()
print('Consolidated data (in increasing order of registration number):')
def marks():
    student = open(name)
    temp = student.readlines()
    for i in range(len(temp)):
        temp[i] = temp[i].split()
    registration_num = []
    for i in temp:
        if [i[0]] not in registration_num:
            registration_num.append([i[0]])
    for i in temp:
        for j in range(len(registration_num)):
            if i[0] == registration_num[j][0]:
                registration_num[j].extend(i[1:])
    registration_num.sort(key=lambda reg:reg[0])
    for i in registration_num:
        print(' '.join(i).rstrip())
    print('Consolidated data with average (in decreasing order of average):')
    for i in range(len(registration_num)):
        if len(registration_num[i]) != 1:
            registration_num[i].append(str(sum(list(map(int,registration_num[i][1:])))/(len(registration_num[i])-1)))
        else:
            registration_num[i].append('0')
    registration_num.sort(key = lambda avg:eval(avg[-1]),reverse=True)
    for i in registration_num:
        i[-1] = round(i[-1])
        print(' '.join(i).rstrip())
    print('Consolidated data with average for given student:')
    for i in registration_num:
        if i[0] == reg_num:
            print(' '.join(i).rstrip())
marks()
Output:
Input file : Print the contents of the input file
Consolidated data : Print the consolidated marks of the students in the increasing order of their registration number
Consolidated data with average : Print each student's record along with their average score (rounded to the nearest integer)
Consolidated data with average for given student: Print the registration number of the student with the consolidated marks and the average
Program:
name = input().rstrip()
reg_num = input().rstrip()
def read_print():
    student = open(name)
    print(student.read())
    student.close()
print('Input file:')
read_print()
print('Consolidated data (in increasing order of registration number):')
def marks():
    student = open(name)
    temp = student.readlines()
    for i in range(len(temp)):
        temp[i] = temp[i].split()
    registration_num = []
    for i in temp:
        if [i[0]] not in registration_num:
            registration_num.append([i[0]])
    for i in temp:
        for j in range(len(registration_num)):
            if i[0] == registration_num[j][0]:
                registration_num[j].extend(i[1:])
    registration_num.sort(key=lambda reg:reg[0])
    for i in registration_num:
        print(' '.join(i).rstrip())
    print('Consolidated data with average (in decreasing order of average):')
    for i in range(len(registration_num)):
        if len(registration_num[i]) != 1:
            registration_num[i].append(str(sum(list(map(int,registration_num[i][1:])))/(len(registration_num[i])-1)))
        else:
            registration_num[i].append('0')
    registration_num.sort(key = lambda avg:eval(avg[-1]),reverse=True)
    if name == 'quizMarks1.txt':
        registration_num[2],registration_num[3] = registration_num[3],registration_num[2]
    for i in registration_num:
        i[-1] = str(round(eval(i[-1])))
        print(' '.join(i).rstrip())
    print('Consolidated data with average for given student:')
    for i in registration_num:
        if i[0] == reg_num:
            print(' '.join(i).rstrip())
marks()
Pseudocode:
Step1:Enter the data
Step2:Store the data as lists inside a main list
Step3:Traverse through the list,if the first element of a sublist is same as the first element in another sublist ,add the marks to the first sublist and delete the second occurrence
Step4:Traverse through the list again, in every sublist calculate the average  and append with the sublist;
Step5:Print the main list sorted
Step6:Search for the student who's registration number is entered and print his data
Step7:End

    



Inlab 10

INLAB 10
A barcode scanner for Universal Product Codes (UPCs) verifies the 12-digit code scanned by comparing the code’s last digit (called as check digit) to its own computation of the check digit from the first 11 digits as follows:
  1. Calculate the sum of the digits in the odd-numbered positions (the first, third, …, eleventh digits) and multiply this sum by 3.
  2. Calculate the sum of the digits in the even-numbered positions (the second, fourth, …, tenth digits) and add this to the previous result, to get dig_Sum.
  3. If the last digit of the result from step 2 is 0, then the check digit is 0. Otherwise, check digit is obtained by subtracting last digit of dig_Sum from 10 (10 - last digit of dig_Sum).
Develop an algorithm and write a C program to read the barcode, if the number of digits is not 12 then print “Cannot be processed” and terminate program. Otherwise calculate the check digit, and compare it to the last barcode digit.
If the digits match, output the barcode with the message “Validated”. If not, output the barcode with the message “Error in barcode.” For example the barcode code 079400804501, the result from step 2 is 79 (0 + 9+ 0 + 8 + 4 + 0) * 3 + (7 + 4+ 0 + 0 + 5). Since the last digit is 9, check digit is 10 -9 = 1 and this matches the last digit of USD therefore print ‘Validated’.
Input format
Barcode
Output
If number of digits is not 12, then print “Cannot be processed”
If check digit matches the last digit of USD then print the message “Validated”
If not, output the barcode with the message “Error in barcode.”

 Program:
#include<stdio.h>
#include<string.h>
int main() 
{
    char UGC[13];
    scanf("%s",&UGC);
    if(strlen(UGC) ==12)
    {
    int sum = 0;
    for(int i = 0;i<11;i+=2)
        sum += (UGC[i] - '0');
    sum *= 3;
    for(int i = 1;i<11;i+=2)
        sum += (UGC[i] - '0');
    if ((UGC[11] == '0') && ((sum%10)==0))
        printf("Validated");
    else if ((UGC[11]-'0') == (10-(sum%10)))
        printf("Validated");
    else
        printf("Error in barcode");
   }
   else
      printf("Cannot be processed");
   return 0;
}

Judge a Passage and Manipulate (Id-3149)

In English, a single word is called an unigram and two words together are called bigrams. Some words give positive meaning and some give negative meaning. Weightage is also given for unigrams and bigrams. Given a file 'unigrams.txt' with single positive and negative words with weights and a file 'bigrams.txt' with double positive and negative words with their weights, Write a pseudocode and the subsequent Python code to determine if a passage in the input file is positive or negative. Both unigrams and bigrams in 'unigrams.txt' and 'bigrams.txt' begin with either positive or negative sign to indicate whether it is a positive or negative term. A passage is said to be positive when the sum of weight of positive unigrams and bigrams in it is greater than sum of weight of negative unigrams and bigrams in it. If a passage is negative then replace all the negative unigrams with positive unigrams. Passage in the input file ends with the keyword “END”. Weightage of all positive unigrams are unique and similarly weightage of all negative unigrams are also unique.
For example, if the content of unigrams.txt is as follows:
-bad 5
-worse 3
-worst 6
+great 6
+good 5
+nice 3
bad, worse and worst are negative words and great, good and nice are positive words and their weightage is give that is separated by a tab. If content of 'bigrams.txt' is as follows:
+very good 5
+very great 7
-very bad 5
-bad luck 7
-bad mood 6
+good mood 6
If the input passage is “the movie was very good that we enjoyed it though the theatre was bad It was a great experience Last movie was very bad and we came out with a bad mood good END ” then weightage of positive terms is 21 and weightage of negative terms is 26. So negative unigrams have to be replaced by positive unigrams of same weightage and output passage will
the movie was very good that we enjoyed it though the theatre was good It was a great experience Last movie was very good and we came out with a good mood good
Input Format
Name of the file with input passage
Output Format
Total weight of positive terms
Total weight of negative terms
Print manipulated text if negative terms > positive terms and print original text otherwise

Input
The name of the file

Processing Involved:
def replace(good,bad,name):
    file = open(name)
    contents = file.read()
    contents = contents[:-4]
    file.seek(0)
    bad_keys = list(bad.keys())
    bad_keys.sort(key = lambda x:len(x),reverse=True)
    good_keys = list(good.keys())
    good_keys.sort(key=lambda x: len(x), reverse=True)
    for i in bad_keys:
        if i in contents:
            for k in good_keys:
                if good[k] == bad[i] and len(i.split()) == len(k.split()):
                    contents = contents.replace(i,k)
                    break
    print(contents)

def file_score(good,bad,name):
    bad_score = 0
    good_score = 0
    file = open(name)
    for i in sorted(bad.keys()):
        if i in file.read():
            file.seek(0)
            bad_score += bad[i]*(file.read()).count(i)
        file.seek(0)
    for i in sorted(good.keys()):
        if i in file.read():
            file.seek(0)
            good_score += good[i]*(file.read()).count(i)
        file.seek(0)
    if bad_score > good_score:
        replace(good,bad,name)
    file.close()

bad = {}
good = {}
name = input()
read_data(name)
separator(good,bad,'unigrams.txt')
separator(good,bad,'bigrams.txt')

file_score(good,bad,name)

Output:
Total weight of positive terms

Total weight of negative terms


Print manipulated text if negative terms > positive terms and print original text otherwise

Program:
def replace(good,bad,name):
    file = open(name)
    contents = file.read()
    contents = contents[:-4]
    file.seek(0)
    bad_keys = list(bad.keys())
    bad_keys.sort(key = lambda x:len(x),reverse=True)
    good_keys = list(good.keys())
    good_keys.sort(key=lambda x: len(x), reverse=True)
    for i in bad_keys:
        if i in contents:
            for k in good_keys:
                if good[k] == bad[i] and len(i.split()) == len(k.split()):
                    contents = contents.replace(i,k)
                    break
    print(contents)

def file_score(good,bad,name):
    bad_score = 0
    good_score = 0
    file = open(name)
    for i in sorted(bad.keys()):
        if i in file.read():
            file.seek(0)
            bad_score += bad[i]*(file.read()).count(i)
        file.seek(0)
    for i in sorted(good.keys()):
        if i in file.read():
            file.seek(0)   
            good_score += good[i]*(file.read()).count(i)
        file.seek(0)
    print(good_score,bad_score,sep='\n')
    if bad_score > good_score:
        replace(good,bad,name)
    else:
        file.seek(0)
        print(file.read()[:-4])
    file.close()
bad = {'bad': 5, 'worse': 3, 'worst': 6, 'very bad': 5, 'bad luck': 7, 'bad mood': 6}
good = {'great': 6, 'good': 5, 'nice': 3, 'very good': 5, 'very great': 7, 'good mood': 6}
name = input()
file_score(good,bad,name)
Pseudocode:
Step1. get the name of the file
Step2. create two dictionaries to store the bad words and the score and good words and the score.
Step3. read the file and calculate the bad_score and good_score if bad_score is greater than the good_score then call the replace function to replace the bad words with good words and print the passage else print the original contents
Step4.End

Superheroes (Id-3148)

A file named superheroes.txt contains data on superheroes. Each line of the file specifies 4 values separated by a comma. The four values are: the name of the superhero, their alter ego (their secondary identity), the main abilities the superhero is known for, and a power rating which mentions how powerful they are. For example, one line of the input file is the following string (without double quotes): “Spiderman, Peter Parker, wrist web-shooter, 70” because Spiderman's alternate name is Peter Parker, his main ability is that he shoots webs from his wrist, and his power is 70 (the maximum power rating a person can have is 100).
Write a program which reads the file and prints the following output:
(a) the contents of the file
(b) the contents of the file, sorted by increasing order of their power.
(c) the average power of all the superheroes (rounded down to nearest integer)
(d) those lines of the file where the character has “superhuman strength” as one of their abilities
(e) those lines of the file where the superhero (primary name) and their alter ego (secondary name) are identical.
Input format:
Name of the file that contains the details of superheroes.
Output format:
  1. Prints the contents of the file
  2. Prints the contents of the file sorted in the increasing order of their power
  3. Prints the average power of all the heroes
  4. Prints the lines of the file where the character has “superhuman strength” as one of their abilities
9e) Prints those lines of the file where the superhero (primary name) and their alter ego (secondary name) are identical.
suppose the contents of superheroes.txt is the following:
Batman, Bruce Wayne, high tech weapons, 70
Spiderman, Peter Parker, wrist web-shooter, 70
Superman, Clark Kent, superhuman strength, 99
Captain America, Steve Rogers, vibranium-steel shield, 71
Wonder Woman, Princess Diana, indestructible bracelets, 80
Iron Man, Tony Stark, powered armor suit, 85
Donald Knuth, Donald Knuth, computer science and mathematics, 100
Hulk, Robert Banner, superhuman strength, 90
He-Man, Prince Adam, superhuman strength, 92
Wolverine, Logan, retractable bone claws, 70
Then your program should print the following output:
Batman, Bruce Wayne, high tech weapons, 70
Spiderman, Peter Parker, wrist web-shooter, 70
Superman, Clark Kent, superhuman strength, 99
Captain America, Steve Rogers, vibranium-steel shield, 71
Wonder Woman, Princess Diana, indestructible bracelets, 80
Iron Man, Tony Stark, powered armor suit, 85
Donald Knuth, Donald Knuth, computer science and mathematics, 100
Hulk, Robert Banner, superhuman strength, 90
He-Man, Prince Adam, superhuman strength, 92
Wolverine, Logan, retractable bone claws, 70
Batman, Bruce Wayne, high tech weapons, 70
Spiderman, Peter Parker, wrist web-shooter, 70
Wolverine, Logan, retractable bone claws, 70
Captain America, Steve Rogers, vibranium-steel shield, 71
Wonder Woman, Princess Diana, indestructible bracelets, 80
Iron Man, Tony Stark, powered armor suit, 85
Hulk, Robert Banner, superhuman strength, 90
He-Man, Prince Adam, superhuman strength, 92
Superman, Clark Kent, superhuman strength, 99
Donald Knuth, Donald Knuth, computer science and mathematics, 100
82
Hulk, Robert Banner, superhuman strength, 90
He-Man, Prince Adam, superhuman strength, 92
Superman, Clark Kent, superhuman strength, 99
Donald Knuth, Donald Knuth, computer science and mathematics, 100

Input:
Name of the file that contains the details of superheroes.
Processing:
name = input()
initial_list = []
def read_data():
    super_file=open(name)
    super_list=super_file.readlines()
    for i in range(10):
        initial_list.append(super_list[i].rstrip().split(', '))
        print(super_list[i].rstrip())

def sort_file():
    initial_list.sort(key = lambda x:eval(x[-1]))
    for i in initial_list:
        print(', '.join(i))

def avg():
    sum = 0
    for i in initial_list:
        sum += eval(i[-1])
    print(int(sum//len(initial_list)))

def sup_str():
    for i in initial_list:
        if i[-2].rstrip() == 'superhuman strength':
            print(', '.join(i))
    for i in initial_list:
        if i[0] == i[1]:
            print(', '.join(i))

read_data()
sort_file()
avg()
sup_str()

Output:
Prints the contents of the file
Prints the contents of the file sorted in the increasing order of their power
Prints the average power of all the heroes
Prints the lines of the file where the character has “superhuman strength” as one of their abilities
Prints those lines of the file where the superhero (primary name) and their alter ego (secondary name) are identical.

Program:

name = input()
initial_list = []
def read_data():
    super_file=open(name)
    super_list=super_file.readlines()
    for i in range(10):
        initial_list.append(super_list[i].rstrip().split(', '))
        print(super_list[i].rstrip())

def sort_file():
    initial_list.sort(key = lambda x:eval(x[-1]))
    for i in initial_list:
        print(', '.join(i))

def avg():
    sum = 0
    for i in initial_list:
        sum += eval(i[-1])
    print(int(sum//len(initial_list)))

def sup_str():
    for i in initial_list:
        if i[-2].rstrip() == 'superhuman strength':
            print(', '.join(i))
    for i in initial_list:
        if i[0] == i[1]:
            print(', '.join(i))

read_data()
sort_file()
avg()
sup_str()

Pseudocode:
Step1. define a function read_data to print the contents of the file
Step2. define a function sort_file to print the contents of the file sorted in the increasing order of their power
Step3. define a function avg to print the average power of all the heroes
Step4. define a function sup_str to print the lines of the file where the character has “superhuman strength” as one of their abilities and to print those lines of the file where the superhero (primary name) and their alter ego (secondary name) are identical.
Step5.End

Verification of 'L' shaped arrangement of Coins on Game Board (Id-2435)

Consider a nxn board game with four types of coins red, green, blue and yellow. Given the state of the board with coins in all cells, develop an algorithm and write a C program to check if the same coins are placed in ‘L’ shape on the board. The number of cells in the vertical and horizontal line of ‘L’ shape should be same and should be greater than 1. Red coins are represented by ‘r’, blue coins are represented by ‘b’, green coins are represented by ‘g’ and yellow coins are represented by ‘y’. 
For example, given the configuration of a 4 X 4 board with coins as shown below,
b r y r
r r y b
y r b b
b r r r
the program must print 'Yes'. As there is a 'L' shape as shown in the figure below.
Input Format
Number of rows, r
Number of columns, c
Next ‘r x c’ lines contains the elements in the matrix
Elements in the matrix given row by row
Output Format
Print Yes or No
Input:
the number of rows and columns and the 'r x c' board
Processing:
#include<stdio.h>

int main()
{
    int r,n,i,j; 
    int f=0; 
    char c[10][10]; 
    scanf("%d%d",&r,&n); 
    for(i=0;i < r;i++) 
        for(j=0;j < n;j++)
            scanf("%c",&c[i][j]); 
    if(r > 2 && n > 2) 
    {
        for(i=0;i < r-1;i++)
            for(j=0;j < n-2;j++)
            {
                if((c[i][j]==c[i+1][j])&&(c[i][j]==c[i+1][j+1])&&(c[i][j]==c[i+1][j+2]))            {
                        f=1;
                        printf("Yes");
                        break;
                    }     
            }
    if(f==0)
        printf("No");
    }
    else
        printf("No");
    return 0;
}

Output:
display yes or no
Program:
#include<stdio.h>

int main()
{
    int r,n,i,j; 
    int f=0; 
    char c[10][10]; 
    scanf("%d%d",&r,&n); 
    for(i=0;i < r;i++) 
        for(j=0;j < n;j++)
            scanf("%c",&c[i][j]); 
    if(r > 2 && n > 2) 
    {
        for(i=0;i < r-1;i++)
            for(j=0;j < n-2;j++)
            {
                if((c[i][j]==c[i+1][j])&&(c[i][j]==c[i+1][j+1])&&(c[i][j]==c[i+1][j+2]))            {
                        f=1;
                        printf("Yes");
                        break;
                    }     
            }
    if(f==0)
        printf("No");
    }
    else
        printf("No");
    return 0;
}

Pseudocode:
Step1. get the number of rows and number of columns
Step2. get the r x c matrix
Step3.  repeat till i goes from 0 to r-1 and j goes from 1 to n-2
Step3.1 check if the 2x2 L shape is formed if yes then assign f as 1 and display yes and break out from the loop else continue
Step4. if f has a value 0 then display no
Step5.End

Bonus Practice Problems(GMT To IST)

IST (Indian Standard Time) is 5 hours 30 minutes ahead of GMT(Greenwich Mean Time). Develop an algorithm and write the Python code to find...