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
# Python3 code to demonstrate working of# Construct Grades List# Using list comprehension + ord()# initializing Nnum = 4# Using list comprehension + ord()# each character paired to symbols and character incremented using idx# conversion by chr + ordres = [chr(ord('A') + idx) + sym for idx in range(num) for sym in ['+', '', '-']] # printing resultprint("Grades List : " + str(res)) |
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
# Python3 code to demonstrate working of# Construct Grades List# Using join() + map() + product() + ascii_uppercasefrom string import ascii_uppercasefrom itertools import product# initializing Nnum = 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 resultprint("Grades List : " + str(res)) |
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. And to begin with your Machine Learning Journey, join the Machine Learning – Basic Level Course


