Skip to content
Related Articles

Related Articles

Python – Construct Grades List
  • Last Updated : 28 Jul, 2020

Given a number, construct list having all the possible Grades combination for first N characters.

Input : num = 3
Output : [‘A+’, ‘A’, ‘A-‘, ‘B+’, ‘B’, ‘B-‘, ‘C+’, ‘C’, ‘C-‘]
Explanation : All grades till C rendered in list.

Input : num = 5
Output : [‘A+’, ‘A’, ‘A-‘, ‘B+’, ‘B’, ‘B-‘, ‘C+’, ‘C’, ‘C-‘, ‘D+’, ‘D’, ‘D-‘, ‘E+’, ‘E’, ‘E-‘]
Explanation : 5 corresponds to E, hence all combinations.

Method #1 : Using list comprehension + ord()
The combination of above functions can be used to solve this problem. In this, we perform the task of incrementing and extracting ascii characters using ord() and list comprehension is used in character list creation.




# Python3 code to demonstrate working of 
# Construct Grades List
# Using list comprehension + ord()
  
# initializing N
num = 4
  
# Using list comprehension + ord()
# each charater paired to symbols and character incremented using idx
# conversion by chr + ord
res =  [chr(ord('A') + idx) + sym for idx in range(num) 
       for sym in ['+', '', '-']]       
  
# printing result 
print("Grades List : " + str(res)) 
Output :



Grades List : ['A+', 'A', 'A-', 'B+', 'B', 'B-', 'C+', 'C', 'C-', 'D+', 'D', 'D-']

 

Method #2 : Using join() + map() + product() + ascii_uppercase
The combination of above functions can be used to solve this problem. In this, we perform the task of extracting ascii characters using ascii_uppercase, product() and map(), is used to perform linkage with symbols, the result is created after perform join of all.




# Python3 code to demonstrate working of 
# Construct Grades List
# Using join() + map() + product() + ascii_uppercase
from string import ascii_uppercase
from itertools import product
  
# initializing N
num = 4
  
# Using join() + map() + product() + ascii_uppercase
# pairing using product, map used to join characters with symbols.
res = [*map(''.join, product(ascii_uppercase[:num], ['+', '', '-']))]
  
# printing result 
print("Grades List : " + str(res)) 
Output :
Grades List : ['A+', 'A', 'A-', 'B+', 'B', 'B-', 'C+', 'C', 'C-', 'D+', 'D', 'D-']

Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course.

My Personal Notes arrow_drop_up
Recommended Articles
Page :