├── GRPA WEEK 7 (OPPE MOCK ) ├── question1.py ├── question2.py ├── question3.py └── question4.py ├── GRPA Week 1 ├── question1.py ├── question2.py ├── question3.py ├── question4.py └── question5.py ├── GRPA Week 8 ├── question1.py ├── question2.py ├── question3.py └── question4.py ├── Grpa Week 10 ├── question1.py ├── question2.py ├── question3.py └── question4.py ├── Grpa Week 2 ├── question1.py ├── question2.py ├── question3.py ├── question4.py └── question5.py ├── Grpa Week 3 ├── question1.py ├── question2.py ├── question3.py └── question4.py ├── Grpa Week 4 ├── question1.py ├── question2.py ├── question3.py ├── question4.py └── question5.py ├── Grpa Week 5 ├── question1.py ├── question2.py ├── question3.py ├── question4.py └── question5.py ├── Grpa Week 6 ├── question1.py ├── question2.py └── question3.py ├── Grpa Week 9 ├── question1.py ├── question2.py ├── question3.py ├── question4.py └── question5.py └── README.md /GRPA WEEK 7 (OPPE MOCK )/question1.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Problem 1 - Data types - GRADED 3 | Implement all the given functions according to the docstrings. There will be 6 function and 6 test cases corresponding to each of the functions.''' 4 | 5 | #answer 6 | 7 | def loss_percent(bp, sp): 8 | """Find the loss percentage given the buying price and the selling price. 9 | Args: 10 | bp (int): The buying price. 11 | sp (int): The selling price. 12 | Returns: 13 | float: The loss percentage. 14 | Examples: 15 | >>> loss_percent(10, 8) 16 | 20.0 17 | >>> loss_percent(20, 15) 18 | 25.0 19 | """ 20 | loss = (bp-sp) 21 | loss_percent = (loss/bp)*100 22 | return loss_percent 23 | 24 | def swap_first_and_last_chars(s): 25 | '''Swap the first and last characters of a string. 26 | Args: 27 | s (str): The input string. 28 | Returns: 29 | str: The string with first and last characters swapped. 30 | Examples: 31 | >>> swap_first_and_last_chars("hello") 32 | 'oellh' 33 | >>> swap_first_and_last_chars("world") 34 | 'dorlw' 35 | ''' 36 | swapping_str = s[-1] + s[1:-1] + s[0] 37 | return swapping_str 38 | 39 | 40 | def add_first_three_items_to_the_last(l): 41 | '''Add the first three elements to the 42 | end of the list in the same order. 43 | Modify the list inplace 44 | Args: 45 | l (list): The input list. 46 | Returns: 47 | None. 48 | Examples: 49 | >>> lst = [1, 2, 3, 4, 5] 50 | >>> add_first_three_items_to_the_last(lst) 51 | >>> lst 52 | [1, 2, 3, 4, 5, 1, 2, 3] 53 | ''' 54 | l.extend(l[:3]) 55 | 56 | return l 57 | ... 58 | 59 | def are_alternate_positions_equal(t): 60 | """Check if the elements at alternate positions in the tuple are equal. 61 | Assume even number of elements in the tuple. 62 | Args: 63 | t (tuple): The input tuple. 64 | Returns: 65 | bool: result as True or False 66 | Examples: 67 | >>> are_alternate_positions_equal([1, 2, 3, 4, 5, 6]) 68 | False 69 | >>> are_alternate_positions_equal([1, 1, 2, 2, 3, 3]) 70 | True 71 | """ 72 | if t[0]==t[1] and t[2]==t[3] and t[4]==t[5]: 73 | return True 74 | else: 75 | return False 76 | 77 | def has_all_values(l, s): 78 | '''Check if all numbers from a list are present in a set. 79 | Args: 80 | l (list): The input list of numbers. 81 | s (set): The input set of numbers. 82 | Returns: 83 | bool: result as True or False 84 | Examples: 85 | >>> has_all_values([1, 2, 3, 4, 4, 3, 2, 1], {1, 2, 3, 4}) 86 | True 87 | >>> has_all_values([1, 2, 3, 1, 2, 3, 3], {2, 3}) 88 | False 89 | ''' 90 | if set(l) == s: 91 | return True 92 | else: 93 | return False 94 | 95 | def swap_key_and_value(d, k): 96 | """Swap the key and value for a given key in a dictionary. 97 | Modify the dictionary inplace do not return a new dictionary. 98 | Args: 99 | d (dict): The input dictionary. 100 | k: The key to swap. 101 | Returns: 102 | dict: The dictionary with the key and value swapped. 103 | Examples: 104 | >>> d = {'a': 1, 'b': 2, 'c': 3} 105 | >>> swap_key_and_value(d,'b') 106 | >>> d 107 | {2: 'b', 'a': 1, 'c': 3} 108 | >>> d = {1: 'a', 2: 'b', 3: 'c'} 109 | >>> swap_key_and_value(d, 2) 110 | >>> d 111 | {1:'a', 'b': 2, 3: 'c'} 112 | """ 113 | 114 | if k in d: 115 | value = d[k] # Get the value for key k 116 | del d[k] # Remove the key k from the dictionary 117 | d[value] = k 118 | -------------------------------------------------------------------------------- /GRPA WEEK 7 (OPPE MOCK )/question2.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Problem 2 - Data Processing - GRADED 3 | Given a list of integers, find the number of hostile_pairs in the given list. 4 | Two positive integers are called hostile if they have no common digits.''' 5 | 6 | #answer 7 | def n_hostile_pairs(L:list)->int: 8 | ''' 9 | Given a list of integers, find the number of 10 | hostile_pairs in the given list. 11 | Two positive integers are called hostile 12 | if they have no common digits. 13 | Args: 14 | L: list[int] - numbers to check 15 | Return: 16 | int - number of hostile pairs 17 | ''' 18 | hostile_pairs = 0 19 | n = len(L) 20 | for i in range(n): 21 | for j in range(i + 1, n): 22 | if not set(str(L[i])) & set(str(L[j])): 23 | hostile_pairs += 1 24 | return hostile_pairs 25 | 26 | -------------------------------------------------------------------------------- /GRPA WEEK 7 (OPPE MOCK )/question3.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Problem 3 - Data Processing - GRADED 3 | Given a list of words, check if all the words are anagrams. Assume words are lowercase. 4 | Two words are anagrams of each other if each word can be obtained by rearranging the letters in the other word.''' 5 | 6 | #answer 7 | 8 | def are_anagrams(words:list)->bool: 9 | ''' 10 | Check if all the given words are anagrams. 11 | Args: words - list[str]: list of lowercase words 12 | Return: bool - True if all the words are anagrams, else False. 13 | ''' 14 | 15 | if not words: 16 | return True 17 | sorted_first_word = sorted(words[0]) 18 | for word in words[1:]: 19 | if sorted(word) != sorted_first_word: # type: ignore 20 | return False 21 | 22 | return True -------------------------------------------------------------------------------- /GRPA WEEK 7 (OPPE MOCK )/question4.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Problem 4 - I/O Based Problem Solving - GRADED 3 | Find the perimeter of a bar graph given the heights at each bar. Assume width of each bar is 1 unit and height is atleast 1 unit and the heights of each bar is given as integers. 4 | Input format 5 | First line will have the number of bar graphs, say n. 6 | Next n lines will have space seperated values 7 | Output format 8 | Perimeter of each bar graph printed over multiple lines 9 | Example 10 | 5 3 4 1 3 2 5 11 | bar_graph 12 | ''' 13 | 14 | 15 | #answer 16 | 17 | def cal_perimeter(hts): 18 | perimeter=2* len(hts) 19 | for i in range(len(hts)-1): 20 | perimeter+=abs(hts[i]-hts[i+1]) 21 | return perimeter + hts[0]+hts[-1] 22 | 23 | n=int(input()) 24 | for i in range(n): 25 | hts=list(map(int, input().split())) 26 | perimeter=cal_perimeter(hts) 27 | print(perimeter) -------------------------------------------------------------------------------- /GRPA Week 1/question1.py: -------------------------------------------------------------------------------- 1 | ''' 2 | GrPA 1 - Numbers (Arithemetic) - GRADED 3 | Solve the below tasks related to Numbers. 4 | Tasks 1 to 3 - building up Arithemetic expression 5 | Tasks 4 and 5 - floating point arithemetic 6 | Tasks 6 and 7 - modulo and floor division 7 | Problem Type: Input variable - Output Variable, Hidden suffix for evaluation 8 | ''' 9 | #Solution - 10 | 11 | # Sample inputs (# note: The values given in the prefix code(grey) will be changed by the autograder according to the testcase while running them. 12 | a = 5 13 | b = 6 14 | price, discount_percent = 80, 5.75 15 | total_mins = 470 16 | # 17 | 18 | output1 = a + b # int: sum of a and b 19 | output2 = 2 * (a + b) # int: twice the sum of a and b 20 | output3 = abs(a - b ) # int: absolute difference between a and b 21 | output4 = abs((a + b) - (a * b)) # int: absolute difference between sum and product of a and b 22 | 23 | # Find discounted price given price and discount_percent 24 | # input variables : price: int, discount_percent: float 25 | discounted_price = price - (price * (discount_percent / 100)) # float 26 | 27 | # Round the discounted_price 28 | rounded_discounted_price = round(discounted_price) # int 29 | 30 | # Find hrs and mins given the total_mins 31 | # input variables : total_mins 32 | hrs = total_mins // 60 # int: hint: think about floor division operator 33 | mins = total_mins % 60 # int -------------------------------------------------------------------------------- /GRPA Week 1/question2.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Question - 3 | GrPA 2 - Numbers (Relational and Logical) - GRADED 4 | Solve all the below tasks related to relational and logical operators. 5 | This exercise gives you practice in building up boolean expressions. 6 | ''' 7 | 8 | #Answer - ; 9 | 10 | # Sample inputs (# note: The values given in the prefix code(grey) will be changed by the autograder according to the testcase while running them. 11 | a = 5 12 | 13 | price1, discount1 = 50, 4 # for offer1 14 | price2, discount2 = 60, 8 # for offer2 15 | 16 | # Assume discount is given in percentages 17 | 18 | # 19 | 20 | output1 = (a >= 5) # bool: True if a greater than or equal to 5 21 | 22 | output2 = ( a % 5 == 0 ) # bool: True if a is divisible by 5 23 | 24 | output3 = ( a % 2 != 0 and a < 10 ) # bool: True if a is odd number less than 10 25 | 26 | output4 = ( a % 2 != 0 and -10 < a < 10 ) # bool: True if a is an odd number within the range -10 and 10 27 | 28 | output5 = (len(str(a)) % 2 == 0 and len(str(a)) <= 10 ) # bool: True if a has even number of digits but not more than 10 digits 29 | 30 | is_offer1_cheaper = ( price1 * (1 - discount1 / 100) < price2 * (1 - discount2 / 100) ) # bool: True if the offer1 is strictly cheaper -------------------------------------------------------------------------------- /GRPA Week 1/question3.py: -------------------------------------------------------------------------------- 1 | ''' 2 | GrPA 3 - Question 3 | Strings (Indexing and Slicing) - GRADED 4 | Solve all the below tasks related to indexing and slicing. 5 | Keep in mind 🧠 The concept of indexing and slicing will come again in later weeks with list and tuple which are also sequences like string. 6 | This exercise gives you practice in different indexing and slicing methods. 7 | ''' 8 | 9 | #Answer - 10 | 11 | # Sample inputs (# note: The values given in the prefix code(grey) will be changed by the autograder according to the testcase while running them. 12 | 13 | s = "hello pyhton" 14 | course_code = "24t2cs1002" # 24 - year, t2 - term 2, cs1002 - course id 15 | # 16 | 17 | output1 = s[2] # str: get the third character of s 18 | 19 | output2 = s[-4] # str: get the fourth last character of s 20 | 21 | output3 = s[:3] # str: get the first 3 characters of s 22 | 23 | output4 = s[::2] # str: get every second character of s 24 | 25 | output5 = s[-3:] # str: get the last 3 characters of s 26 | 27 | output6 = s[::-1] # str: get the reverse of s 28 | 29 | course_term = int(course_code[3]) # int: get the term of the year as number from course_code 30 | course_year = int(course_code[0 :2]) # int: get the year as two digit number from course_code -------------------------------------------------------------------------------- /GRPA Week 1/question4.py: -------------------------------------------------------------------------------- 1 | ''' 2 | GrPA 4 - Strings (Concatenation, repetition, and substring check) - GRADED 3 | Solve all the below tasks related to string concatenation, repeatition and substring check in strings. 4 | ''' 5 | 6 | #Answer - 7 | 8 | # Sample inputs (# note: The values given in the prefix code(grey) will be changed by the autograder according to the testcase while running them. 9 | word1 = "Wingardium" # str 10 | word2 = "Leviyosa" # str 11 | word3 = "Silver" # str 12 | sentence = "Learning python is fun" 13 | n1 = 6 # int 14 | n2 = 4 # int 15 | # 16 | 17 | output1 = word1 + " " + word2 # str: join word1 and word2 with space in between 18 | 19 | output2 = word1[:4] + "-" + word2[-4:] # str: join first four letters of word1 and last four letters of word 2 with a hyphen "-" in between 20 | 21 | output3 = word3 + " " + str(n1) # str: join the word3 and n1 with a space in between 22 | 23 | output4 = "-" * 50 # str: just the hypen "-" repeated 50 times 24 | 25 | output5 = "-" * n2 # str: just the hypen "-" repeated n2 times 26 | 27 | output6 = str(n1) * n2 # str: repeat the number n1, n2 times 28 | 29 | are_all_words_equal = word1 == word2 == word3 # bool: True if all three words are equal 30 | 31 | is_word1_comes_before_other_two = word1 < word2 and word1 < word3 # bool: True if word1 comes before word2 and word3 assume all words are different 32 | 33 | has_h = "h" in word1 # bool: True if word1 has the letter h 34 | 35 | ends_with_a = word1.endswith("a") or word1.endswith("A") # bool: True if word1 ends with letter a or A 36 | 37 | has_the_word_python = "python" in sentence # bool: True if the sentence has the word python -------------------------------------------------------------------------------- /GRPA Week 1/question5.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Question 3 | GrPA 5 - (Input Output and Type conversion) - GRADED 4 | Get age(int), dob(str of format "dd/mm/yy") and weight(float) from the standard input and print the tenth_month, fifth_birthday and last_birthday formatted as "day/month/year"(do not include the preceeding zero for single digit number) separated by comma and a space a single line and print the weight_readable(str formatted as "55 kg 200 grams") 5 | Note: while formatting dates you may have to convert back int to str using the type conversion. There is something called as "f-strings" or "formatted strings" that will help us format things by automatically doing type conversion. This will be covered in later weeks. But you can explore that (Google or ChatGPT) and compare the difference. 6 | Note: The last_birthday depends on the dob and age. For example if the dob is "20/02/2001" and the age is 5 the last birthday will be "20/02/2006". 7 | Note: Finding the tenth_month will be a bit of challange. If you are stuck open the below hint. 8 | ''' 9 | 10 | #Answer 11 | 12 | # Sample inputs (# note: The values given in the prefix code(grey) will be changed by the autograder according to the testcase while running them. 13 | 14 | s = "hello pyhton" 15 | course_code = "24t2cs1002" # 24 - year, t2 - term 2, cs1002 - course id 16 | # 17 | 18 | output1 = s[2] # str: get the third character of s 19 | 20 | output2 = s[-4] # str: get the fourth last character of s 21 | 22 | output3 = s[:3] # str: get the first 3 characters of s 23 | 24 | output4 = s[::2] # str: get every second character of s 25 | 26 | output5 = s[-3:] # str: get the last 3 characters of s 27 | 28 | output6 = s[::-1] # str: get the reverse of s 29 | 30 | course_term = int(course_code[3]) # int: get the term of the year as number from course_code 31 | course_year = int(course_code[0 :2]) # int: get the year as two digit number from course_code -------------------------------------------------------------------------------- /GRPA Week 8/question1.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Shashwatology/IITM-Python-Grpa/5c1c5eed73297ca5b44fc2df482c278ce79a25d9/GRPA Week 8/question1.py -------------------------------------------------------------------------------- /GRPA Week 8/question2.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Shashwatology/IITM-Python-Grpa/5c1c5eed73297ca5b44fc2df482c278ce79a25d9/GRPA Week 8/question2.py -------------------------------------------------------------------------------- /GRPA Week 8/question3.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Shashwatology/IITM-Python-Grpa/5c1c5eed73297ca5b44fc2df482c278ce79a25d9/GRPA Week 8/question3.py -------------------------------------------------------------------------------- /GRPA Week 8/question4.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Shashwatology/IITM-Python-Grpa/5c1c5eed73297ca5b44fc2df482c278ce79a25d9/GRPA Week 8/question4.py -------------------------------------------------------------------------------- /Grpa Week 10/question1.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Shashwatology/IITM-Python-Grpa/5c1c5eed73297ca5b44fc2df482c278ce79a25d9/Grpa Week 10/question1.py -------------------------------------------------------------------------------- /Grpa Week 10/question2.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Shashwatology/IITM-Python-Grpa/5c1c5eed73297ca5b44fc2df482c278ce79a25d9/Grpa Week 10/question2.py -------------------------------------------------------------------------------- /Grpa Week 10/question3.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Shashwatology/IITM-Python-Grpa/5c1c5eed73297ca5b44fc2df482c278ce79a25d9/Grpa Week 10/question3.py -------------------------------------------------------------------------------- /Grpa Week 10/question4.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Shashwatology/IITM-Python-Grpa/5c1c5eed73297ca5b44fc2df482c278ce79a25d9/Grpa Week 10/question4.py -------------------------------------------------------------------------------- /Grpa Week 2/question1.py: -------------------------------------------------------------------------------- 1 | ''' GrPA 1 - Variables and Assignment - GRADED 2 | Solve all the below tasks related to variables. 3 | This exercise gives you practice in working with variables. 4 | Note: Do not take input or print output as they are taken care by the suffix code(evaluator). 5 | ''' 6 | 7 | #answer - 8 | 9 | x1 = input() 10 | x2 = input() 11 | y1 = input() 12 | y2 = input() 13 | y3 = input() 14 | z = input() 15 | 16 | x1, x2 = x2, x1 # swap the values of `x1` and `x2` 17 | 18 | y1, y2, y3 = y2, y3, y1 # do a circular swap of `y1`, `y2` and `y3` like y1 = y2, y2 = y3, y3 = y1 19 | 20 | a = z # create a new variable `a` with the value of `z` 21 | 22 | del z # delete the variable `z` 23 | 24 | print(x1) 25 | print(x2) 26 | print(y1) 27 | print(y2) 28 | print(y3) 29 | print(a) -------------------------------------------------------------------------------- /Grpa Week 2/question2.py: -------------------------------------------------------------------------------- 1 | ''' 2 | question 3 | GrPA 2 - String Escaping - GRADED 4 | Assign text that are given in the comments "as is" without the space after the "#" to the corresponding variable names in the template. 5 | ''' 6 | 7 | #Answer - 8 | 9 | # A single quote ' and a double quote " 10 | output1 = '''A single quote ' and a double quote " ''' 11 | 12 | # A forward slash / and a backward slash \ 13 | output2 = "A forward slash / and a backward slash \ " 14 | 15 | # Three single quotes ''' and three double quotes """ 16 | output3 = '''Three single quotes \''' and three double quotes """ ''' 17 | 18 | # Double forward slash // and Double backward slash \\ 19 | output4 = '''Double forward slash // and Double backward slash \\\ ''' -------------------------------------------------------------------------------- /Grpa Week 2/question3.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Question 3 | GrPA 3 - Basic conditional patterns - GRADED 4 | This problem gives you exposure to different use cases of if ... elif and else conditional structues. 5 | Part 1 - Only if 6 | Part 2 - if ... else 7 | Part 3 - if ... elif 8 | ''' 9 | 10 | #Answer 11 | 12 | # part 1 - If pattern 13 | word = "glow" # str 14 | continuous_tense = True # bool 15 | 16 | # part 2 17 | age = 5 # int 18 | is_member = True # bool 19 | 20 | # part 3 21 | 22 | color_code = "R" # str: valid values are R-red, G-green and B-blue 23 | 24 | time = "02 PM" # str, format:[2-digit hour][space][AM or PM] 25 | # Morning (6 AM - 12 PM) (including the start and excluding the end) 26 | # Afternoon (12 PM - 6 PM) 27 | # Evening (6 PM - 12 AM) 28 | # Night (12 AM - 6 AM) 29 | 30 | # 31 | 32 | # part 1 - basic if 33 | 34 | new_word = word # donot remove this line 35 | 36 | # remove the "ing" suffix from new_word if it is there 37 | if new_word.endswith("ing"): 38 | new_word = new_word[:-3] 39 | 40 | # add the suffix "ing" to new_word if continuous_tense is True 41 | if continuous_tense: 42 | new_word += "ing" 43 | # write the whole if else block here 44 | 45 | # part 2 - If else pattern 46 | 47 | # age_group:str should be "Adult" or "Child" based on the age. assume age greater than or equal to 18 is adult. 48 | if age >= 18: 49 | age_group = "Adult" 50 | else: 51 | age_group = "Child" 52 | 53 | # applicant_type:str should be age goup with the member status like "Adult Member" or "Child Non-member" 54 | if is_member: 55 | applicant_type = age_group + " Member" 56 | else: 57 | applicant_type = age_group + " Non-member" 58 | # write the whole if else block 59 | 60 | # part 3 if ... elif .. else 61 | 62 | # based on the value of color_code assign the color value in lower case and "black" if color_code is none of R, B and G 63 | 64 | if color_code == "R": 65 | color = "red" 66 | elif color_code == "G": 67 | color = "green" 68 | elif color_code == "B": 69 | color = "blue" 70 | else: 71 | color = "black" 72 | 73 | hrs = int(time[:2]) 74 | is_time_valid = 0 < hrs <= 12 # bool: True if time is valid (should be ranging from 1 - 12 both including) else False 75 | 76 | # time_in_hrs:int should have the time in 24 hrs format . Try to do this in a single expression 77 | am_pm = time[-2 : ] 78 | if am_pm == "AM": 79 | if hrs == 12: 80 | time_in_hrs = 0 81 | else: 82 | time_in_hrs = hrs 83 | else: 84 | if hrs == 12: 85 | time_in_hrs = 12 86 | else: 87 | time_in_hrs = hrs + 12 88 | 89 | #time = "02 PM" # str, format:[2-digit hour][space][AM or PM] 90 | # Morning (6 AM - 12 PM) (including the start and excluding the end) 91 | # Afternoon (12 PM - 6 PM) 92 | # Evening (6 PM - 12 AM) 93 | # Night (12 AM - 6 AM) 94 | 95 | # time_of_day:str should have the time of the day as Morning, etc.. use "Invalid" if not withing the acceptable range 96 | if (is_time_valid): 97 | if 6 <= time_in_hrs < 12: 98 | time_of_day = "Morning" 99 | elif 12 <= time_in_hrs < 18: 100 | time_of_day = "Afternoon" 101 | elif 18 <= time_in_hrs <= 23: 102 | time_of_day = "Evening" 103 | elif 0 <= time_in_hrs <= 6: 104 | time_of_day = "Night" 105 | else: 106 | time_of_day = "Invalid" 107 | 108 | 109 | # write your code here -------------------------------------------------------------------------------- /Grpa Week 2/question4.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Question 3 | GrPA 4 - Conditionals - Applications - GRADED 4 | Problem Type: Standard Output - Standard Output 5 | You are tasked with creating a multi-purpose application that performs various operations based on user input. The application should take the operation name from the input and execute the corresponding task. 6 | ''' 7 | 8 | #answer 9 | 10 | operation = input() 11 | 12 | if operation == "odd_num_check": 13 | number = int(input()) 14 | if number % 2 != 0: 15 | print("yes") 16 | else: 17 | print("no") 18 | elif operation == "perfect_square_check": 19 | number = int(input()) 20 | import math 21 | if math.sqrt(number) == int(math.sqrt(number)): 22 | print("yes") 23 | else: 24 | print("no") 25 | elif operation == "vowel_check": 26 | text = input() 27 | if any(char in "aeiouAEIOU" for char in text): 28 | print("yes") 29 | else: 30 | print("no") 31 | elif operation == "divisibility_check": 32 | number = int(input()) 33 | if number % 2 == 0 and number % 3 == 0: 34 | print("divisible by 2 and 3") 35 | elif number % 2 == 0: 36 | print("divisible by 2") 37 | elif number % 3 == 0: 38 | print("divisible by 3") 39 | else: 40 | print("not divisible by 2 and 3") 41 | elif operation == "palindrominator": 42 | text = input() 43 | print(text + text[::-1][1:]) 44 | elif operation == "simple_interest": 45 | principal_amount = int(input()) 46 | n_years = int(input()) 47 | if n_years < 10: 48 | interest_rate = 0.05 49 | else: 50 | interest_rate = 0.08 51 | simple_interest = (principal_amount * interest_rate * n_years) 52 | print(round(simple_interest)) 53 | else: 54 | print("Invalid Operation") 55 | 56 | print(f"{total_cost:.02f}") # type: ignore -------------------------------------------------------------------------------- /Grpa Week 2/question5.py: -------------------------------------------------------------------------------- 1 | """ 2 | Question 3 | GrPA 5 - Conditionals - Debugging - GRADED 4 | Problem Type: Standard Input - Standard Output, Debugging, and missing 5 | How to solve: To solve this problem use the Python tutor button. Paste the template(buggy) code in the python tutor, you can also include the sample input in the python tutor. This will help you identify the errors easily. 6 | """ 7 | 8 | #answer 9 | 10 | main_dish = input() 11 | time_of_day = int(input()) 12 | has_voucher = input() 13 | is_card_payment = input() 14 | 15 | if main_dish == "paneer tikka": 16 | cost = 250 17 | elif main_dish == "butter chicken": 18 | cost = 240 19 | elif main_dish == "masala dosa": 20 | cost = 200 21 | else: # if main dish is invalid print invalid dish and exit the code. 22 | print("Invalid main dish") 23 | exit() 24 | 25 | if 12 <= time_of_day <=15: 26 | total_cost = (1 - 0.15) * cost 27 | else: 28 | total_cost = cost 29 | 30 | if has_voucher == 'True': 31 | total_cost = total_cost * 0.9 # Apply voucher discount 32 | 33 | if is_card_payment == 'True': # service charge for card payments 34 | service_charge = 0.05 * total_cost 35 | total_cost += service_charge 36 | 37 | print(f"{total_cost:.02f}") -------------------------------------------------------------------------------- /Grpa Week 3/question1.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Question 3 | GrPA 1 - While Loop - GRADED 4 | ✅ Important Note on while loop🔁: 5 | Use while only when the number of iterations is indefinite. 6 | If you can term the steps as do n times, do once for each item, etc. use for loop instead. 7 | If you can only term the steps as do until something happens. Like when user inputs 10. 8 | A bit of wisdom 📖 There are maily two ways in which while loops are used in the context of taking inputs until a terminal word. 9 | ''' 10 | 11 | #Answer 12 | 13 | # Note this prefix code is to verify that you are not using any for loops in this exercise. This won't affect any other functionality of the program. 14 | with open(__file__) as f: 15 | content = f.read().split("# ")[2] 16 | if "for " in content: 17 | print("You should not use for loop or the word for anywhere in this exercise") 18 | 19 | # This is the first line of the exercise 20 | task = input() 21 | # 22 | 23 | if task == "sum_until_0": 24 | total = 0 25 | n = int(input()) 26 | while (n != 0): # the terminal condition 27 | total += n # add n to the total 28 | n = int(input()) # take the next n form the input 29 | print(total) 30 | 31 | elif task == "total_price": 32 | total_price = 0 33 | while True: # repeat forever since we are breaking inside 34 | line = input() 35 | if line == 'END': # The terminal condition 36 | break 37 | quantity, price = line.split() # split uses space by default 38 | quantity, price = int(quantity), int(price) # convert to ints 39 | total_price = total_price + (quantity * price) # accumulate the total price 40 | print(total_price) 41 | 42 | elif task == "only_ed_or_ing": 43 | word = input() 44 | while(word != 'STOP'): 45 | if ((word.endswith('ed')) or (word.endswith('ED')) or (word.endswith('ing')) or (word.endswith('ING'))): 46 | print(word) 47 | else: 48 | pass 49 | word = input() 50 | 51 | elif task == "reverse_sum_palindrome": 52 | n = int(input()) 53 | while(n != -1): 54 | if n > 0: 55 | reverse = int((str(n))[::-1]) 56 | sum = n + reverse 57 | reverse_sum = int((str(sum))[::-1]) 58 | if (sum == reverse_sum): 59 | print(n) 60 | else: 61 | pass 62 | else: 63 | pass 64 | n = int(input()) 65 | 66 | elif task == "double_string": 67 | line = input() 68 | while(line != ''): 69 | repeatedTwice = line * 2 70 | print(repeatedTwice) 71 | line = input() 72 | 73 | elif task == "odd_char": 74 | word = input() 75 | while(word != word.endswith('.')): 76 | odd_char = word[::2] 77 | print(odd_char, end = ' ') 78 | word = input() 79 | 80 | elif task == "only_even_squares": 81 | num = input() 82 | while(num != 'NAN'): 83 | num = int(num) 84 | square = num ** 2 85 | if (square % 2 == 0): 86 | print(square) 87 | else: 88 | pass 89 | num = input() 90 | 91 | elif task == "only_odd_lines": 92 | new_line = '' 93 | line = input() 94 | while(line != 'END'): 95 | new_line = new_line + line + ' ' 96 | line = input() 97 | split_line = new_line.split() 98 | odd_line = split_line[::2] 99 | reverse_odd_line = odd_line[::-1] 100 | reversed_line = '\n'.join(reverse_odd_line) 101 | print(reversed_line) -------------------------------------------------------------------------------- /Grpa Week 3/question2.py: -------------------------------------------------------------------------------- 1 | ''' 2 | GrPA 2 - For Loop - GRADED 3 | Bit of Wisdom 📖 In context of general incremental definite loops the structure of while loop can be converted to a for loop using range. Refer this. 4 | # the wile loop 5 | i = 0 # initialization 6 | while i<10: # condition 7 | print(i) # body 8 | i+=2 # update 9 | # same with for loop 10 | for i in range(0,10,2): # range combines initalization, temination and update. 11 | print(i) 12 | ''' 13 | 14 | #answer 15 | 16 | # Note this prefix code is to verify that you are not using any for loops in this exercise. This won't affect any other functionality of the program. 17 | with open(__file__) as f: 18 | content = f.read().split("# ")[2] 19 | if "while " in content: 20 | print("You should not use while loop or the word while anywhere in this exercise") 21 | 22 | # your code should not use more than 7 for loops 23 | # assuming one for loop per problem 24 | if content.count("for ")>7: 25 | print("You should not use more than 7 for loops") 26 | 27 | # This is the first line of the exercise 28 | task = input() 29 | # 30 | 31 | if task == 'factorial': 32 | n = int(input()) 33 | result = 1 34 | for i in range (1 , n+1): 35 | result *= i 36 | 37 | print(result) 38 | 39 | 40 | elif task == 'even_numbers': 41 | n = int(input()) 42 | for i in range (0 , n +1 , 2): 43 | print(i) 44 | 45 | elif task == 'power_sequence': 46 | n = int(input()) 47 | result = 1 48 | for i in range(n): 49 | print(2**i) 50 | 51 | 52 | elif task == 'sum_not_divisible': 53 | n = int(input()) 54 | sum = 0 55 | for i in range(1 , n): 56 | if (i % 4 != 0 and i % 5 != 0 ): 57 | sum += i 58 | print(sum) 59 | 60 | elif task == 'from_k': 61 | n = int(input()) 62 | k = int(input()) 63 | count = 0 64 | for i in range (k,0,-1): 65 | str_i = str(i) 66 | if "5" not in str_i and '9' not in str_i and i%2!=0 : 67 | print(str_i[::-1]) 68 | count += 1 69 | if count == n : 70 | break 71 | 72 | elif task == 'string_iter': 73 | n = input() 74 | prev = 1 75 | for i in range(len(n)): 76 | curr = int(n[i]) 77 | print(curr * prev) 78 | prev = curr 79 | 80 | elif task == 'list_iter': 81 | lst = eval(input()) # this will load the list from input 82 | for i in lst: 83 | print(f'{i} - type: {type(i)}') 84 | 85 | else: 86 | print("Invalid") -------------------------------------------------------------------------------- /Grpa Week 3/question3.py: -------------------------------------------------------------------------------- 1 | ''' 2 | GrPA 3 - Nested loops - GRADED 3 | Create a multi-functional program that performs different tasks based on the user input. The program should support the following tasks: 4 | Permutation (permutation): Given a string s, print all the possible two-letter permutations(without repitition) of the letters in the string. 5 | ''' 6 | 7 | #Answer 8 | task = input() 9 | 10 | if task == 'permutation': 11 | s = input() 12 | for i in s: 13 | for j in s: 14 | if (i != j): 15 | print(f'{i}{j}') 16 | 17 | elif task == 'sorted_permutation': 18 | s = input() 19 | for i in s: 20 | for j in s: 21 | if ((i != j) and (i < j)): 22 | print(f'{i}{j}') 23 | 24 | elif task == 'repeat_the_repeat': 25 | n = int(input()) 26 | for i in range(1, n + 1): 27 | repeat_the_repeat = 0 28 | for j in range(1, n + 1): 29 | repeat_the_repeat = (repeat_the_repeat * 10) + j 30 | print(repeat_the_repeat) 31 | 32 | elif task == 'repeat_incrementally': 33 | n = int(input()) 34 | if (n > 0): 35 | repeat_incrementally = 0 36 | for i in range(1, n + 1): 37 | repeat_incrementally = (repeat_incrementally * 10) + i 38 | print(repeat_incrementally) 39 | 40 | elif task == 'increment_and_decrement': 41 | n = int(input()) 42 | if (n > 0): 43 | increment = '' 44 | for i in range(1, n + 1): 45 | increment = increment + str(i) 46 | decrement = increment[-2::-1] 47 | increment_and_decrement = increment + decrement 48 | print(increment_and_decrement) 49 | -------------------------------------------------------------------------------- /Grpa Week 3/question4.py: -------------------------------------------------------------------------------- 1 | ''' 2 | GrPA 4 - Loops Application - GRADED 3 | You are tasked with writing a program that can handle various tasks based on the input. The first line of the input represents the task to be performed. The possible tasks are: 4 | factors - Find the factors of a number n (including 1 and itself) in ascending order. 5 | find_min - Take n numbers from the input and print the minimum number. 6 | prime_check - Check whether a given number is prime or not. 7 | is_sorted - Check if all characters of the given string from input are in alphabetical order. Print the output as "True" or "False" accordingly. 8 | any_true - Take n numbers from input and check if any of the numbers are divisible by 3. Print the output as "True" or "False" accordingly. 9 | ''' 10 | 11 | #answer 12 | 13 | # this is to ensure that you cannot use the built in any, all and min function for this exercise but you can use it in the OPPEs. 14 | any = None 15 | all = None 16 | min = None 17 | 18 | task = input() 19 | 20 | if task == 'factors': 21 | n = int(input()) 22 | if (n > 0): 23 | for i in range(1, n + 1): 24 | if (n % i == 0): 25 | print(i) 26 | 27 | elif task == 'find_min': 28 | n = int(input()) 29 | min = 99999999999999999 30 | num = int(input()) 31 | if (n > 1): 32 | while (n > 1): 33 | if num < min: 34 | min = num 35 | num = int(input()) 36 | n -= 1 37 | else: 38 | min = num 39 | print(min) 40 | 41 | elif task == 'prime_check': 42 | num = int(input()) 43 | flag = False 44 | if (num > 0): 45 | if (num == 2): 46 | flag = True 47 | else: 48 | for i in range(3, num + 1): 49 | for j in range(2, i): 50 | if (i % j == 0): 51 | flag = False 52 | break 53 | else: 54 | flag = True 55 | print(flag) 56 | 57 | elif task == 'is_sorted': 58 | s= input() 59 | flag = True 60 | for i in range(len(s) - 1): 61 | if (s[i] > s[i + 1]): 62 | flag = False 63 | break 64 | print(flag) 65 | 66 | elif task == 'any_true': 67 | n = int(input()) 68 | num = int(input()) 69 | flag = False 70 | while(n > 1): 71 | if(num % 3 == 0): 72 | flag = True 73 | n -= 1 74 | num = int(input()) 75 | print(flag) 76 | 77 | elif task == 'manhattan': 78 | direction = input() 79 | x_distance, y_distance = 0, 0 80 | while (direction != 'STOP'): 81 | if (direction =='LEFT'): 82 | x_distance -= 1 83 | elif (direction == 'RIGHT'): 84 | x_distance += 1 85 | elif (direction == 'UP'): 86 | y_distance += 1 87 | elif (direction == 'DOWN'): 88 | y_distance -= 1 89 | x, y = abs(x_distance - 0), abs(y_distance - 0) 90 | manhattan_distance = x + y 91 | direction = input() 92 | print(manhattan_distance) -------------------------------------------------------------------------------- /Grpa Week 4/question1.py: -------------------------------------------------------------------------------- 1 | ''' 2 | GrPA 1 - Basic Collections - GRADED 3 | A bit of wisdom 📖 4 | Iterable - Something that can be used in a for loop. 5 | Collection - Datatypes that hold many values like list, set, tuple and dict. 6 | All iterables are not collections. Eg. str and range are iterables but not collections. 7 | All collections are iterables. 8 | Only ordered collections are indexable and slicable 9 | Only Mutable collections can be modified 10 | Hasing is a method used in collections like set to check whether an element is present or not quickly, and in dict to retrive the value for the given key quickly. There are only certain datatypes that can be hashed. For example 11 | ''' 12 | #Answer 13 | 14 | # Note this prefix code is to verify that you are not using any for loops in this exercise. This won't affect any other functionality of the program. 15 | with open(__file__) as f: 16 | content = f.read().split("# ")[2] 17 | if "for " in content: 18 | print("You should not use for loop or the word for anywhere in this exercise") 19 | 20 | # The values of the below variables will be changed by the evaluator 21 | int_iterable = range(1,10,3) 22 | string_iterable = ["Apple","Orange", "Banana"] 23 | some_value = 4 24 | some_collection = [1,2,3] # list | set | tuple 25 | 26 | some_iterable = (1,2,3) 27 | another_iterable = {"apple", "banana", "cherry"} # can be any iterable 28 | yet_another_iterable = range(1,10) 29 | 30 | # 31 | # 32 | 33 | empty_list = [] 34 | empty_set = set() # be carefull here you might end up creating something called as an empty dict 35 | empty_tuple = () 36 | 37 | singleton_list = [1] # list: A list with only one element 38 | singleton_set = {1} # set: A set with only one element 39 | singleton_tuple = (1,) # tuple: A tuple with only one element 40 | 41 | a_falsy_list = [] # list: a list but when passed to bool function should return False. 42 | a_falsy_set = set() # set: a list but when passed to bool function should return False. 43 | a_truthy_tuple = (1,) # tuple: a tuple but when passed to bool function should return True 44 | 45 | int_iterable_min = min(int_iterable) # int: find the minimum of int_iterable. Hint: use min function 46 | int_iterable_max = max(int_iterable) # int: find the maximum of int_iterable. Hint: use max function 47 | int_iterable_sum = sum(int_iterable) # int: you know what to do 48 | int_iterable_len = len(int_iterable) # int: really... you need hint?12345 49 | 50 | int_iterable_sorted = list(sorted(int_iterable)) # list: the int_iterable sorted in ascending order 51 | int_iterable_sorted_desc = sorted(int_iterable, reverse = True) # list: the int_iterable sorted in desc order 52 | 53 | if isinstance(int_iterable, list): # some iterables are not reversible why? 54 | int_iterable_reversed = list(reversed(int_iterable)) # list: the int_iterable reversed use the reversed function 55 | else: # in that case sort it in ascending order and reverse it 56 | int_iterable_reversed = list(reversed(sorted(int_iterable))) #list 57 | 58 | if isinstance(some_collection, (list, tuple)): # some collections are not indexable why? 59 | third_last_element = some_collection[-3] # the third last element of some_collection 60 | else: # in that case set third_last_element to None 61 | third_last_element = None 62 | 63 | if isinstance(some_collection, (list, tuple, range)): # some collections are not slicable 64 | odd_index_elements = some_collection[1::2] # type(some_collection): the elements at odd indices of some_collection 65 | else: # in that case set odd_index_elements to None 66 | odd_index_elements = None 67 | 68 | is_some_value_in_some_collection = some_value in some_collection # bool: True if some_value is present in some_collection 69 | 70 | if isinstance(some_collection, (str, list, tuple)): # some collections are not ordered 71 | is_some_value_in_even_indices = some_value in some_collection[::2] # bool: True if some_value is present in even indices of some_collection 72 | else: # in that case set is_some_value_in_even_indices to None 73 | is_some_value_in_even_indices = None 74 | 75 | all_iterables = list(some_iterable) + list(another_iterable) + list(yet_another_iterable) # list: concatenate some_iterable, another_iterable and yet_another_iterable into a list. 76 | 77 | if isinstance(string_iterable, list): #some iterables are not ordered 78 | all_concat = '-'.join(string_iterable) #str: concatenate all the strings in string_iterable with '-' in between 79 | else: #in that case sort them and concatenate 80 | string_iterable = sorted(list(string_iterable)) 81 | all_concat = '-'.join(string_iterable) -------------------------------------------------------------------------------- /Grpa Week 4/question2.py: -------------------------------------------------------------------------------- 1 | ''' 2 | GrPA 2 - Operations on list and set - GRADED 3 | List mutating operations - This will help you learn the list methods and operations that will modify the list inplace. Note that you should not be creating a new list anywhere in this function. 4 | Create new lists - This will help you learn how to create new lists that resembles the result of above operations but does not affecting the original list. 5 | Set operations - This will help you learn things that you can do with sets. 6 | ''' 7 | 8 | #answer 9 | 10 | # Note this prefix code is to verify that you are not using any for loops in this exercise. This won't affect any other functionality of the program. 11 | with open(__file__) as f: 12 | content = f.read().split("# ")[2] 13 | if "for " in content or "while " in content: 14 | print("You should not use for loop, while loop or the word for and while anywhere in this exercise") 15 | 16 | # note that apart from the print statements inside the functions, the evaluator will also print what is returned by the function at last 17 | # 18 | 19 | def list_mutating_operations(items:list, item1, item2): 20 | # sort the items inplace 21 | items.sort() 22 | print("sorted:",items) 23 | 24 | # add item1 to the items at the end 25 | items.append(item1) 26 | print("append:",items) 27 | 28 | # add item2 at index 3 29 | items.insert(3, item2) 30 | print("insert:",items) 31 | 32 | # extend items with the first three elements in items 33 | items.extend(items[:3]) 34 | print("extend:", items) 35 | 36 | # pop the fifth element and store it in variable popped_item 37 | if (len(items) >= 5): 38 | popped_item = items.pop(4) 39 | else: 40 | popped_item = None 41 | print("pop:",items) 42 | 43 | # remove first occurance of item2 from the list 44 | if (item2 in items): 45 | items.remove(item2) 46 | print("remove:",items) 47 | 48 | # make the element at index 4 None 49 | if (len(items) > 4): 50 | items[4] = None 51 | print("modify_index:",items) 52 | 53 | # make the even indices None 54 | items[::2] = [None] * len(items[::2]) 55 | print("modify_slice:",items) 56 | 57 | # delete the third last element 58 | if (len(items) >= 3): 59 | del items[-3] 60 | print("delete_index:",items) 61 | 62 | # delete the even indices 63 | del items[::2] 64 | print("delete_slice:",items) 65 | 66 | return items, popped_item 67 | 68 | def list_non_mutating_operations(items:list, item1, item2): 69 | 70 | original_items = items.copy() 71 | 72 | # print the sorted version of items 73 | print("sorted:",sorted(original_items)) 74 | 75 | # print a list with item1 appended to the items at the end 76 | print("append:",original_items + [item1]) 77 | 78 | # print a list with item2 added to items at index 3 79 | new_items = original_items.copy() 80 | new_items.insert(3, item2) 81 | print("insert:", new_items) 82 | 83 | # print a list with the first three elements in items added to the end of the items again 84 | print("extend:", original_items + original_items[:3]) 85 | 86 | # print a list with the fifth element from items removed 87 | if (len(original_items) >= 5): 88 | new_items = original_items.copy() 89 | del new_items[4] 90 | print("pop:", new_items) 91 | else: 92 | print("pop:", original_items) 93 | 94 | # print a list with first occurance of item2 removed from items 95 | if (item2 in original_items): 96 | new_items = original_items.copy() 97 | new_items.pop(original_items.index(item2)) 98 | print("remove:",new_items) # hint: you may want to use index 99 | else: 100 | print("remove:",original_items) 101 | 102 | # print a list with the fourth element of items changed to None 103 | if (len(original_items) > 4): 104 | new_items = original_items.copy() 105 | new_items[3] = None 106 | print("modify_index:",new_items) 107 | 108 | # print a list with the even indices changed to None 109 | new_items = original_items.copy() 110 | new_items[::2] = [None] * len(new_items[::2]) 111 | print("modify_slice:",new_items) 112 | 113 | # print a list with the even indices removed 114 | new_items = original_items.copy() 115 | del new_items[::2] 116 | print("delete_slice:",new_items) 117 | 118 | return items 119 | 120 | def do_set_operation(set1, set2, set3, item1, item2): 121 | # add item1 to set1 122 | set1.add(item1) 123 | print(sorted(set1)) 124 | 125 | # remove item2 from set1. What if item2 is not in set1? 126 | set1.discard(item2) 127 | print(sorted(set1)) 128 | 129 | # add elements from set2 to set1 130 | set1.update(set2) 131 | print(sorted(set1)) 132 | 133 | # remove all elements from set1 that are in set3 134 | set1 -= set3 135 | print(sorted(set1)) 136 | 137 | # print the common elements in both set2 and set3 as a sorted list. 138 | print(sorted(set2 & set3)) 139 | 140 | #print all unique elements present in set1, set2 an set3 as a sorted list 141 | print(sorted(set1 | set2 | set3)) 142 | 143 | #print all unique elements that are in set2 but not in set3 as a sorted list 144 | print(sorted(set2 - set3)) 145 | 146 | #print all the non common elements from both set2 and set3 147 | print(sorted((set2 - set3) | (set3 - set2))) 148 | 149 | return set1,sorted(set1),sorted(set2),sorted(set3) -------------------------------------------------------------------------------- /Grpa Week 4/question3.py: -------------------------------------------------------------------------------- 1 | ''' 2 | GrPA 3 - List and set application - GRADED 3 | Implement the following functions: 4 | find_min: Find the minimum value in a list of integers. 5 | Input: A list of integers. 6 | Output: An integer, the minimum value in the list. 7 | odd_increment_even_decrement_no_modify: Increment all the odd numbers in a list by 1 and decrement all the even numbers by 1, without modifying the original list. 8 | Input: A list of integers. 9 | Output: A new list of integers with the modified values. 10 | ''' 11 | 12 | #answer 13 | 14 | min = None 15 | 16 | def find_min(items:list): 17 | if not items: # check if the list is empty 18 | return None 19 | minimum = items[0] 20 | for item in items[1:]: 21 | if item < minimum: 22 | minimum = item 23 | return minimum 24 | 25 | def odd_increment_even_decrement_no_modify(items) -> list: 26 | return [(x + 1 if x % 2 != 0 else x - 1) for x in items] 27 | 28 | def odd_square_even_double_modify(items: list): 29 | for i in range(len(items)): 30 | if items[i] % 2 != 0: 31 | items[i] = items[i] ** 2 32 | else: 33 | items[i] = items[i] * 2 34 | 35 | def more_than_two_unique_vowels(sentence): 36 | vowels = set('aeiou') 37 | result = set() 38 | words = sentence.split(',') 39 | for word in words: 40 | unique_vowels = set(char for char in word if char in vowels) 41 | if len(unique_vowels) > 2: 42 | result.add(word) 43 | return result 44 | 45 | def sum_of_list_of_lists(lol): 46 | return sum(sum(lst) for lst in lol) 47 | 48 | def flatten(lol): 49 | return [item for sublist in lol for item in sublist] 50 | 51 | def all_common(strings): 52 | if not strings: 53 | return '' 54 | common_chars = set(strings[0]) 55 | for s in strings[1:]: 56 | common_chars &= set(s) 57 | return ''.join(sorted(common_chars)) 58 | 59 | def vocabulary(sentences): 60 | vocab = set() 61 | for sentence in sentences: 62 | words = sentence.lower().split() 63 | vocab.update(words) 64 | return vocab 65 | -------------------------------------------------------------------------------- /Grpa Week 4/question4.py: -------------------------------------------------------------------------------- 1 | ''' 2 | GrPA 4 - Function Basics - GRADED 3 | You are required to complete the following functions to perform various operations on tuples and lists. 4 | swap_halves: Swap the first and second halves of a tuple with an even length. 5 | Input: A tuple of even length. 6 | Output: A new tuple where the first and second halves are swapped. 7 | swap_at_index: Break a tuple at a given index ( k ) (the element at the ( k )-th index is included in the first half before swapping) and swap the parts. 8 | ''' 9 | 10 | #answer 11 | 12 | def swap_halves(items): 13 | mid = len(items) // 2 14 | return items[mid:] + items[:mid] 15 | 16 | def swap_at_index(items, k): 17 | return items[k+1:] + items[:k+1] 18 | 19 | def rotate_k(items, k=1): 20 | k = k % len(items) 21 | return items[-k:] + items[:-k] 22 | 23 | def first_and_last_index(items, elem): 24 | first = items.index(elem) 25 | last = len(items) - 1 - items[::-1].index(elem) 26 | return (first, last) 27 | 28 | def reverse_first_and_last_halves(items): 29 | mid = len(items) // 2 30 | items[:mid] = reversed(items[:mid]) 31 | items[mid:] = reversed(items[mid:]) -------------------------------------------------------------------------------- /Grpa Week 4/question5.py: -------------------------------------------------------------------------------- 1 | '''GrPA 5 - Comprehensions - GRADED 2 | This will help you build up the basics of list comprehensions. 3 | sum_of_squares - find the sum of squares of numbers in a list - (mapping and aggregation) 4 | total_cost - given quantitiy and price of each item as a list of tuples find the total cost using list comprehensions 5 | abbreviation - given a string with multiple words seperated by space, form an abbrevation out of it by taking the first letter in caps. (mapping and aggregation) 6 | palindromes - given a list of strings, create a new list with only palindromes filtering 7 | all_chars_from_big_words - find the all unique characters (case insensitive, make all lowercase) from all words with size greater than 5 in a given sentence with words seperated by spaces. (filtering) 8 | flatten - flatten a nested list using comprehension 9 | unflatten - given a flat list and number of rows, create a matrix (2d list) with that number of rows. (nested-aggregation) 10 | make_identity_matrix - make an identity (with ones on the main diagonal and zeros elsewhere) given the size. 11 | make_lower_triangular_matrix - given number of rows m, create a lower triangular matrix like the pattern below. for m = 5 12 | [ 13 | [1,0,0,0,0], 14 | [1,2,0,0,0], 15 | [1,2,3,0,0], 16 | [1,2,3,4,0], 17 | [1,2,3,4,5] 18 | ] 19 | Note: you cannot use if statements or loops withing the functions.''' 20 | 21 | #answer 22 | def sum_of_squares(numbers): 23 | return sum(x**2 for x in numbers) 24 | 25 | def total_cost(cart): 26 | return sum(quantity * price for quantity, price in cart) 27 | 28 | def abbreviation(sentence): 29 | return '.'.join(word[0].upper() for word in sentence.split()) + '.' 30 | 31 | def palindromes(words): 32 | return [word for word in words if word == word[::-1]] 33 | 34 | def all_chars_from_big_words(sentence): 35 | return set(char.lower() for word in sentence.split() if len(word) > 5 for char in word) 36 | 37 | def flatten(lol): 38 | return [item for sublist in lol for item in sublist] 39 | 40 | def unflatten(items, n_rows): 41 | return [items[i:i + len(items) // n_rows] for i in range(0, len(items), len(items) // n_rows)] 42 | 43 | def make_identity_matrix(m): 44 | return [[1 if i == j else 0 for j in range(m)] for i in range(m)] 45 | 46 | def make_lower_triangular_matrix(m): 47 | return [[j + 1 if j <= i else 0 for j in range(m)] for i in range(m)] -------------------------------------------------------------------------------- /Grpa Week 5/question1.py: -------------------------------------------------------------------------------- 1 | ''' 2 | GrPA 1 - Dictionary Basics - GRADED 3 | You are tasked with implementing a series of functions that perform various operations on dictionaries in Python. These functions will manipulate dictionaries that represent fruit prices and perform different operations as specified. 4 | dictionary_operations(fruit_prices: dict, fruits: list) 5 | ''' 6 | 7 | #answer 8 | 9 | def dictionary_operations(fruit_prices:dict, fruits:list): 10 | # add the fruit fruits[0] to fruit_prices with cost 3 11 | fruit_prices[fruits[0]] = 3 12 | order_print(fruit_prices) # type: ignore # this function is in the hidden code 13 | 14 | # modify the cost of fruits[1] as 2 in fruit_prices 15 | fruit_prices[fruits[1]] = 2 16 | order_print(fruit_prices) # type: ignore 17 | 18 | # increase the cost of fruits[2] by 2 in fruit_prices 19 | fruit_prices[fruits[2]] += 2 20 | order_print(fruit_prices) # type: ignore 21 | 22 | # delete both key and value for fruits[3] from fruit_prices 23 | del fruit_prices[fruits[3]] 24 | order_print(fruit_prices) # type: ignore 25 | 26 | # print the price of fruits[4] 27 | 28 | print(fruit_prices[fruits[4]]) 29 | 30 | # print the names of fruits in fruit prices as a list sorted in ascending order 31 | print(sorted(fruit_prices.keys())) 32 | 33 | # print the prices of the fruits as a list sorted in ascending order. 34 | print(sorted(fruit_prices.values())) 35 | 36 | def increase_prices(fruit_prices:dict) -> None: 37 | ''' 38 | Increase the prices of every fruit by 20 percent and round to two decimal places 39 | Arguments: 40 | fruit_prices: dict - fruit name as key and price as value 41 | Return: 42 | None - Do not return any thing - modify inplace 43 | ''' 44 | for fruit in fruit_prices: 45 | fruit_prices[fruit] *= 1.2 46 | fruit_prices[fruit] = round(fruit_prices[fruit] , 2) 47 | 48 | def dict_from_string(string:str,key_type,value_type): 49 | ''' 50 | Given a string where each line has a comma seperated key-value pair, create a dictionary out of it. Also convert the types of key and values to the given types. 51 | Arguments: 52 | string - str: string to be parsed 53 | key_type - class: the data type of the keys 54 | value_type - class: the data type of the values 55 | Return: 56 | D - dict: the output dictionary 57 | ''' 58 | D = {} 59 | for line in string.split("\n") : 60 | key , value = line.split(",") 61 | D[key_type(key)] = value_type(value) 62 | return D 63 | 64 | def dict_to_string(D:dict) -> str: 65 | ''' 66 | Convert the given dictionary back to the string fromat produced by dict_from_string. Again, do not use loops or conditionals, use comprehensions. 67 | ''' 68 | #{'Apple': 2, 'Banana': 3, 'Grapes': 3, 'Orange': 4, 'Papaya': 5} 69 | return "\n".join(str(key)+ ","+str(value) for key,value in D.items()) -------------------------------------------------------------------------------- /Grpa Week 5/question2.py: -------------------------------------------------------------------------------- 1 | ''' 2 | GrPA 2 - Dictionary Applications - GRADED 3 | Implement the below functions as per the docstrings. 4 | ''' 5 | #answer 6 | 7 | def total_price(fruit_prices: dict, purchases) -> float: 8 | ''' 9 | Compute the fruit prices give the quantity of each fruit. Do not use the sum function. 10 | Arguments: 11 | fruit_prices: dict - fruit name as key and price as value 12 | purchases: list[tuple] - as list of tuples of (fruit, quantity) 13 | Return: 14 | total_price: float 15 | ''' 16 | total = 0 17 | for fruit, quantity in purchases: 18 | total += fruit_prices[fruit] * quantity 19 | return total 20 | 21 | def total_price_no_loops(fruit_prices: dict, purchases) -> float: 22 | ''' 23 | Compute the total price without loops. 24 | ''' 25 | return sum([fruit_prices[fruit] * quantity for fruit, quantity in purchases]) 26 | 27 | def find_cheapest_fruit(fruit_prices:dict) -> str: 28 | ''' 29 | Find the cheapest fruit from the fruit_prices dict, do not use min function 30 | Arguments: 31 | fruit_prices: dict - fruit name as key and price as value 32 | Return: 33 | cheapest_fruit: str - the fruit with the lowest price 34 | ''' 35 | cheapest_fruit = '' 36 | cheapest_price = float('inf') 37 | for fruit, price in fruit_prices.items(): 38 | if price < cheapest_price: 39 | cheapest_fruit = fruit 40 | cheapest_price = price 41 | return cheapest_fruit 42 | 43 | def find_cheapest_fruit_no_loops(fruit_prices:dict) -> str: 44 | ''' 45 | Find the cheapest fruit using min function. Do not use loops 46 | ''' 47 | return min(fruit_prices, key=fruit_prices.get) 48 | 49 | # grouping 50 | def group_fruits(fruits:list): 51 | ''' 52 | Group the fruits based on the first letter of the names. Assume first letters will be upper case. 53 | Arguments: 54 | fruits - list: list of fruit names 55 | Return: 56 | dict: dict with the first letters as keys and list of fruits sorted in ascending order as values. 57 | ''' 58 | grouped_fruits = {} 59 | for fruit in fruits: 60 | first_letter = fruit[0] 61 | if first_letter not in grouped_fruits: 62 | grouped_fruits[first_letter] = [] 63 | grouped_fruits[first_letter].append(fruit) 64 | for letter in grouped_fruits: 65 | grouped_fruits[letter].sort() 66 | return grouped_fruits 67 | 68 | # binning 69 | def bin_fruits(fruit_prices): 70 | ''' 71 | Classify the fruits as cheap, affordable and costly based on the fruit prices. Create a dictionary with the classification as keys and a set of fruits in that category. 72 | cheap - less than 3 (not inclusive) 73 | affordable - between 3 and 6 (both inclusive) 74 | costly - greater than 6 (not inclusive) 75 | Arguments: 76 | fruit_prices: dict - dictionary with fruits as keys and prices as values 77 | Return: 78 | binned_fruits: dict - dictionary with category as key and a set of fruits in that category as values. 79 | ''' 80 | binned_fruits = {'cheap': set(), 'affordable': set(), 'costly': set()} 81 | for fruit, price in fruit_prices.items(): 82 | if price < 3: 83 | binned_fruits['cheap'].add(fruit) 84 | elif 3 <= price <= 6: 85 | binned_fruits['affordable'].add(fruit) 86 | else: 87 | binned_fruits['costly'].add(fruit) 88 | return binned_fruits -------------------------------------------------------------------------------- /Grpa Week 5/question3.py: -------------------------------------------------------------------------------- 1 | ''' 2 | GrPA 3 - Composing functions - GRADED 3 | Implement all the given functions that are used to solve the below problems. 4 | Follow the path 5 | You are given a matrix of size m x n consisting of ones (1) and zeros (0). There is a single continuous path formed with ones that starts from the rightmost cell in the last row (m-th row) with one and ends at leftmost cell in the first row with one in it. The path does not branch, and there is only one such path. Your task is to traverse along the path and print the coordinates of the path from start to end as tuples over multiple lines. The path can move vertically and horizontally. 6 | Input 7 | matrix = [ 8 | [0, 0, 1, 1], 9 | [0, 0, 0, 1], 10 | [1, 1, 1, 1], 11 | [1, 0, 0, 0], 12 | [1, 1, 0, 0] 13 | ] 14 | ''' 15 | 16 | #answer 17 | 18 | def index_of_first_occurance(row:list,elem): 19 | '''Given a list find the index of first occurance of 1 in it''' 20 | return row.index(elem) 21 | 22 | 23 | def index_of_last_occurance(row:list,elem): 24 | '''Given a list find the index of last occurance of 1 in it. 25 | Hint: use index_of_first_one with reversal.''' 26 | reversed_row = row[::-1] 27 | index_in_reversed = reversed_row.index(elem) 28 | return len(row) - index_in_reversed - 1 29 | 30 | 31 | def is_valid_coordinate(x:int,y:int, M): 32 | '''Checks if the x,y is a valid corrdinate(indices) in the matrix M(list of list). Assume coordinates are non-negative''' 33 | return (0 <= x < len(M)) and (0 <= y < len(M[0])) 34 | 35 | 36 | def valid_adjacent_coordinates(x:int,y:int, M): 37 | '''Create a set of valid adjacent coordinates(indices) given x,y and a matrix M''' 38 | return {(x1, y1) for x1, y1 in [(x - 1, y), (x + 1, y), (x, y - 1), (x, y + 1)] if is_valid_coordinate(x1,y1, M)} # all the possible adjacent coordinates 39 | 40 | def next_coordinate_with_value(curr_coords, value, M, prev_coords=None): 41 | '''Find the coordinate(indices) of the next coordinate that has the value in it. For the starting coordinate the prev_coords would be None''' 42 | curr_row, curr_column = curr_coords 43 | directions = [(0, -1), (0, 1), (-1, 0), (1, 0)] # direction for next position from current position -> left, right, up, down 44 | 45 | for direction in directions: 46 | next_row = curr_row + direction[0] # when direction[0] -> -1 for left and +1 for right 47 | next_column = curr_column + direction[1] # when direction[1] -> -1 for up and +1 for down 48 | 49 | if (0 <= next_row < len(M)) and (0 <= next_column < len(M[0])) and (M[next_row][next_column] == value) and ((next_row, next_column) != prev_coords): 50 | return (next_row, next_column) 51 | 52 | 53 | def get_path_coordinates(M): 54 | '''Given the matrix m, find the path formed by 1 from the last row to the first row.''' 55 | x_start, x_end = len(M) - 1, 0 56 | y_start, y_end = index_of_last_occurance(M[-1], 1), index_of_first_occurance(M[0], 1) 57 | path = [(x_start, y_start)] 58 | curr_coords = (x_start, y_start) 59 | while curr_coords!= (x_end, y_end): 60 | next_coords = next_coordinate_with_value(curr_coords, 1, M, prev_coords=path[-2] if len(path) > 1 else None) 61 | if next_coords is None: 62 | break 63 | path.append(next_coords) 64 | curr_coords = next_coords 65 | return path 66 | 67 | 68 | def print_path(M): 69 | path = get_path_coordinates(M) 70 | for coord in path: 71 | print(f"({coord[0]}, {coord[1]})") 72 | 73 | 74 | def alternate_path(M): 75 | path = get_path_coordinates(M) 76 | for i, (x, y) in enumerate(path): 77 | M[x][y] = 1 if i % 2 == 0 else 2 78 | return M 79 | 80 | 81 | def count_path(M): 82 | path = get_path_coordinates(M) 83 | count = len(path) 84 | for i, (x, y) in enumerate(reversed(path)): 85 | M[x][y] = count - i 86 | return M 87 | 88 | 89 | def mirror_horizontally(M): 90 | path = get_path_coordinates(M) 91 | max_col = len(M[0]) - 1 92 | for i, j in path: 93 | M[i][max_col - j] = 1 94 | return M 95 | 96 | 97 | def mirror_vertically(M): 98 | path = get_path_coordinates(M) 99 | max_row = len(M) - 1 100 | for i, j in path: 101 | M[max_row - i][j] = 1 102 | return M -------------------------------------------------------------------------------- /Grpa Week 5/question4.py: -------------------------------------------------------------------------------- 1 | ''' 2 | GrPA 4 - lambda, zip, enumerate, map, filter - GRADED 3 | Implement the given functions according to the docstrings. 4 | ''' 5 | #answer 6 | 7 | import random 8 | def generate_student_data(n_students, courses, cities, random_seed=42): 9 | ''' 10 | Create a list of dict with dictionaries representing each attributes of each student. 11 | ''' 12 | random.seed(random_seed) 13 | return [ 14 | { 15 | "rollno": i, "city": random.choice(cities), 16 | **{course: random.randint(1,100) for course in courses} 17 | } 18 | for i in range(1,n_students+1) 19 | ] 20 | 21 | 22 | 23 | from collections import Counter 24 | def groupby(data:list, key:callable): 25 | ''' 26 | Given a list of items, and a key, create a dictionary with the key as key function called 27 | on item and the list of items with the same key as the corresponding value. 28 | The order of items in the group should be the same order in the original list 29 | ''' 30 | grouped_data = {} 31 | 32 | for item in data: 33 | group_key = key(item) 34 | if group_key not in grouped_data: 35 | grouped_data[group_key] = [] 36 | grouped_data[group_key].append(item) 37 | 38 | return grouped_data 39 | ... 40 | 41 | def apply_to_groups(groups:dict, func:callable): 42 | ''' 43 | Apply a function to the list of items for each group. 44 | ''' 45 | return {key: func(items) for key, items in groups.items()} 46 | ... 47 | 48 | def min_course_marks(student_data, course): 49 | '''Return the min marks on a given course''' 50 | # min_=float('inf') 51 | # for i, mark in student_data.items(): 52 | # min_=min(mark[course],min) 53 | # marks = [mark[course] for mark in student_data] 54 | return min(list(map(lambda x: x[course],student_data))) 55 | ... 56 | 57 | def max_course_marks(student_data, course): 58 | '''Return the max marks on a given course''' 59 | return max(list(map(lambda x: x[course],student_data))) 60 | ... 61 | 62 | def rollno_of_max_marks(student_data, course): 63 | '''Return the rollno of student with max marks in a course''' 64 | max_mark = max_course_marks(student_data,course) 65 | list_max = list(map(lambda x: x[course],student_data)) 66 | max_index = list_max.index(max_mark) 67 | roll = list(map(lambda x: x["rollno"],student_data)) 68 | return roll[max_index] 69 | ... 70 | 71 | def sort_rollno_by_marks(student_data, course1, course2, course3): 72 | ''' 73 | Return a sorted list of rollno sorted based on their marks on the three course marks. 74 | course1 is compared first, then course2, then course3 to break ties. 75 | Hint: use tuples comparision 76 | ''' 77 | return list(map(lambda student: student['rollno'], sorted( 78 | student_data, 79 | key=lambda x: (x[course1], x[course2], x[course3], x['rollno']) 80 | ))) 81 | ... 82 | 83 | def count_students_by_cities(student_data): 84 | ''' 85 | Create a dictionary with city as key and number of students from each city as value. 86 | ''' 87 | city_counter = Counter(student['city'] for student in student_data) 88 | return dict(city_counter) 89 | ... 90 | 91 | def city_with_max_no_of_students(student_data): 92 | ''' 93 | Find the city with the maximum number of students. 94 | ''' 95 | city = count_students_by_cities(student_data) 96 | return max(city, key=city.get) 97 | ... 98 | 99 | def group_rollnos_by_cities(student_data): 100 | ''' 101 | Create a dictionary with city as key and 102 | a sorted list of rollno of students that belong to 103 | that city as the value. 104 | ''' 105 | grouped_data = groupby(student_data, key=lambda x: x['city']) 106 | return {city: sorted([student['rollno'] for student in students]) for city, students in grouped_data.items()} 107 | ... 108 | 109 | def city_with_max_avg_course_mark(student_data, course): 110 | ''' 111 | Find the city with the maximum avg course marks. 112 | ''' 113 | grouped_data = groupby(student_data, key=lambda x: x['city']) 114 | avg_marks_by_city = { 115 | city: sum(student[course] for student in students) / len(students) 116 | for city, students in grouped_data.items() 117 | } 118 | return max(avg_marks_by_city, key=avg_marks_by_city.get) 119 | -------------------------------------------------------------------------------- /Grpa Week 5/question5.py: -------------------------------------------------------------------------------- 1 | ''' 2 | GrPA 5 - min, max, sorted, groupby - GRADED 3 | Implement all the given functions below according to the docstring.''' 4 | 5 | #amswer 6 | 7 | import random 8 | def generate_student_data(n_students, courses, cities, random_seed=42): 9 | ''' 10 | Create a list of dict with dictionaries representing each attributes of each student. 11 | ''' 12 | random.seed(random_seed) 13 | return [ 14 | { 15 | "rollno": i, "city": random.choice(cities), 16 | **{course: random.randint(1,100) for course in courses} 17 | } 18 | for i in range(1,n_students+1) 19 | ] 20 | 21 | 22 | 23 | from collections import Counter 24 | def groupby(data:list, key:callable): 25 | ''' 26 | Given a list of items, and a key, create a dictionary with the key as key function called 27 | on item and the list of items with the same key as the corresponding value. 28 | The order of items in the group should be the same order in the original list 29 | ''' 30 | grouped_data = {} 31 | 32 | for item in data: 33 | group_key = key(item) 34 | if group_key not in grouped_data: 35 | grouped_data[group_key] = [] 36 | grouped_data[group_key].append(item) 37 | 38 | return grouped_data 39 | ... 40 | 41 | def apply_to_groups(groups:dict, func:callable): 42 | ''' 43 | Apply a function to the list of items for each group. 44 | ''' 45 | return {key: func(items) for key, items in groups.items()} 46 | ... 47 | 48 | def min_course_marks(student_data, course): 49 | '''Return the min marks on a given course''' 50 | # min_=float('inf') 51 | # for i, mark in student_data.items(): 52 | # min_=min(mark[course],min) 53 | # marks = [mark[course] for mark in student_data] 54 | return min(list(map(lambda x: x[course],student_data))) 55 | ... 56 | 57 | def max_course_marks(student_data, course): 58 | '''Return the max marks on a given course''' 59 | return max(list(map(lambda x: x[course],student_data))) 60 | ... 61 | 62 | def rollno_of_max_marks(student_data, course): 63 | '''Return the rollno of student with max marks in a course''' 64 | max_mark = max_course_marks(student_data,course) 65 | list_max = list(map(lambda x: x[course],student_data)) 66 | max_index = list_max.index(max_mark) 67 | roll = list(map(lambda x: x["rollno"],student_data)) 68 | return roll[max_index] 69 | ... 70 | 71 | def sort_rollno_by_marks(student_data, course1, course2, course3): 72 | ''' 73 | Return a sorted list of rollno sorted based on their marks on the three course marks. 74 | course1 is compared first, then course2, then course3 to break ties. 75 | Hint: use tuples comparision 76 | ''' 77 | return list(map(lambda student: student['rollno'], sorted( 78 | student_data, 79 | key=lambda x: (x[course1], x[course2], x[course3], x['rollno']) 80 | ))) 81 | ... 82 | 83 | def count_students_by_cities(student_data): 84 | ''' 85 | Create a dictionary with city as key and number of students from each city as value. 86 | ''' 87 | city_counter = Counter(student['city'] for student in student_data) 88 | return dict(city_counter) 89 | ... 90 | 91 | def city_with_max_no_of_students(student_data): 92 | ''' 93 | Find the city with the maximum number of students. 94 | ''' 95 | city = count_students_by_cities(student_data) 96 | return max(city, key=city.get) 97 | ... 98 | 99 | def group_rollnos_by_cities(student_data): 100 | ''' 101 | Create a dictionary with city as key and 102 | a sorted list of rollno of students that belong to 103 | that city as the value. 104 | ''' 105 | grouped_data = groupby(student_data, key=lambda x: x['city']) 106 | return {city: sorted([student['rollno'] for student in students]) for city, students in grouped_data.items()} 107 | ... 108 | 109 | def city_with_max_avg_course_mark(student_data, course): 110 | ''' 111 | Find the city with the maximum avg course marks. 112 | ''' 113 | grouped_data = groupby(student_data, key=lambda x: x['city']) 114 | avg_marks_by_city = { 115 | city: sum(student[course] for student in students) / len(students) 116 | for city, students in grouped_data.items() 117 | } 118 | return max(avg_marks_by_city, key=avg_marks_by_city.get) -------------------------------------------------------------------------------- /Grpa Week 6/question1.py: -------------------------------------------------------------------------------- 1 | 2 | '''GrPA 1 - Parsing Inputs - GRADED 3 | Problem statement 4 | Implement the given functions where you have to read the input from the standard input with the input format given in the docstring of the function and return the output in the required type.''' 5 | 6 | #answer 7 | 8 | def get_student_details(): 9 | ''' 10 | Get the student details over multiple lines 11 | Input format: 12 | name 13 | age 14 | rollno 15 | Return: name:str, age:int, rollno:int 16 | ''' 17 | name = input() 18 | age = int(input()) 19 | rollno = int(input()) 20 | return name, age, rollno 21 | 22 | # heterogeneous - single line 23 | def get_student_details_same_line(): 24 | ''' 25 | Get the student details from the same line 26 | Input format:(separated by space) 27 | name age rollno 28 | Return: name:str, age:int, rollno:int 29 | ''' 30 | name, age, rollno = input().split() 31 | age = int(age) 32 | rollno = int(rollno) 33 | return name, age, rollno 34 | 35 | # homogeneous - single line 36 | def get_comma_separated_integers(): 37 | ''' 38 | Get a list of comma separated integers from input 39 | Return: numbers:list[int] 40 | ''' 41 | numbers = [int(x) for x in input().split(',')] 42 | return numbers 43 | 44 | # homogeneous - multi-line - definite 45 | def get_n_float_numbers(): 46 | ''' 47 | Get n float numbers with one number in each line 48 | and the first line has n. 49 | Input Format: 50 | n 51 | num1 52 | num2 53 | ... 54 | numn 55 | Return: nums:list[float] 56 | ''' 57 | n = int(input()) 58 | nums = [] 59 | for _ in range(n): 60 | nums.append(float(input())) 61 | return nums 62 | 63 | # homogeneous - multi-line - indefinite 64 | def get_nums_until_end(): 65 | ''' 66 | Get float numbers with one number in each line 67 | until the input is "end"(case insensitive) 68 | Input Format: 69 | num1 70 | num2 71 | ... 72 | numx 73 | End 74 | Return: nums:list[float] 75 | ''' 76 | nums = [] 77 | while True: 78 | num = input() 79 | if num.lower() == 'end': 80 | break 81 | nums.append(float(num)) 82 | return nums 83 | 84 | # hybrid - single line 85 | def get_batsman_runs(): 86 | ''' 87 | Get batsman name, number and runs as a list 88 | Input format: (separated by space) 89 | name no run1 run2 run3 ... 90 | Return: name:str, no:int, runs:list[int] 91 | ''' 92 | name, no, *runs = input().split() 93 | no = int(no) 94 | runs = [int(x) for x in runs] 95 | return name, no, runs 96 | 97 | # key value 98 | def get_course_scores(): 99 | ''' 100 | Get course name and scores of the over multiple lines where 101 | course name and scores are separated by a hypen in each line. 102 | First line corresponds to the number or entries. 103 | Input format: 104 | 2 105 | course1-score1 106 | course2-score2 107 | Return: dict[str,int] - with course name as key and score as value 108 | ''' 109 | n = int(input()) 110 | course_scores = {} 111 | for _ in range(n): 112 | course, score = input().split('-') 113 | course_scores[course] = int(score) 114 | return course_scores 115 | 116 | # dict with list as values 117 | def get_all_batsman_runs(): 118 | ''' 119 | Given the batsman name and the comma separated runs 120 | where both are seperted by a hypen in multiple lines, 121 | create a dictionary with batsman name and list of runs as value. 122 | The number of lines is given in the first line 123 | Input format: 124 | 3 125 | batsman1-1,2,1,4,6,2,2,1 126 | batsman2-2,2,6,4,1 127 | batsman3-6,1,2,4,4,2 128 | Return: dict[str,list[int]] - with batsman name as key and list of runs as values 129 | ''' 130 | n = int(input()) 131 | batsman_runs = {} 132 | for _ in range(n): 133 | batsman, runs = input().split('-') 134 | batsman_runs[batsman] = [int(x) for x in runs.split(',')] 135 | return batsman_runs 136 | 137 | # csv - list of dicts 138 | def get_student_marks(): 139 | ''' 140 | Given the student rollno, city, age, 141 | course1_marks, course2_marks and course3_marks 142 | as comma separated values over multiple lines, 143 | create a list of dict with the above attributes as keys 144 | and the corresponding value as values. 145 | The number of lines is given in the first line 146 | Input Format: 147 | n 148 | 1,citya,23,86,69,86 149 | 2,cityb,19,78,65,89 150 | ... 151 | n,cityx,35,89,57,76 152 | Return: 153 | student_data - list[dict]: where each dict would be 154 | {'rollno':int, 'city':str,'age':int, 155 | 'course1':int, 'course2':int, 'course3':int} 156 | ''' 157 | n = int(input()) 158 | student_data = [] 159 | for _ in range(n): 160 | rollno, city, age, course1, course2, course3 = input().split(',') 161 | student_data.append({'rollno': int(rollno), 'city': city, 'age': int(age), 'course1': int(course1), 'course2': int(course2), 'course3': int(course3)}) 162 | return student_data 163 | 164 | # list of dicts 165 | def get_student_data_over_multiple_lines(): 166 | ''' 167 | Given each attribute as described above in given over multiple lines 168 | and multiple entries are given create a dictionary as described above. 169 | Input format: 170 | n 171 | 1 172 | citya 173 | 23 174 | 86 175 | 69 176 | 86 177 | 2 178 | cityb 179 | 19 180 | 78 181 | 65 182 | 89 183 | ... 184 | n 185 | cityx 186 | 35 187 | 89 188 | 57 189 | 76 190 | ''' 191 | n = int(input()) 192 | student_data = [] 193 | for _ in range(n): 194 | rollno = int(input()) 195 | city = input() 196 | age = int(input()) 197 | course1 = int(input()) 198 | course2 = int(input()) 199 | course3 = int(input()) 200 | student_data.append({'rollno': rollno, 'city': city, 'age': age, 'course1': course1, 'course2': course2, 'course3': course3}) 201 | return student_data 202 | # this will read the function name from the input. 203 | func = eval(input()) 204 | 205 | # this will read the actual output that is required which is the second line 206 | expected_output = eval(input()) 207 | 208 | # The remaining of the input should be read by your function 209 | actual_output = func() 210 | 211 | if expected_output != actual_output: 212 | print("Your output doesn't match the expected output.") 213 | print(actual_output) -------------------------------------------------------------------------------- /Grpa Week 6/question2.py: -------------------------------------------------------------------------------- 1 | ''' 2 | GrPA 2 - Formatting Outputs - GRADED 3 | Implement the below functions where you have to format the given data in the given format and print them to the standard output according to the docstring given. 4 | ''' 5 | 6 | #answer 7 | 8 | import random 9 | 10 | def display_student_details(name:str, age:int, rollno:int): 11 | ''' 12 | Given name, age, and rollno of student, 13 | print them over multiple lines 14 | Output format: 15 | name 16 | age 17 | rollno 18 | Return: None 19 | ''' 20 | print(name) 21 | print(age) 22 | print(rollno) 23 | 24 | # heterogeneous values - single line 25 | def display_student_details_same_line(name:str, age:int, rollno:int): 26 | ''' 27 | Given name, age, and rollno of student, 28 | print them in the same line separated by a comma. 29 | Output format: 30 | name,age,rollno 31 | ''' 32 | print(name,age,rollno,sep=",") 33 | 34 | # homogeneous - single line 35 | def display_comma_separated_integers(nums:list): 36 | ''' 37 | Given a list of nums print them in the same line 38 | separated by commas. 39 | For example, if nums= [1,3,4,5], 40 | Output format: 41 | 1,3,4,5 42 | ''' 43 | print(*nums, sep=",") 44 | 45 | # homogeneous - multi-line - definite 46 | def display_float_nums_over_multiple_lines(nums:list): 47 | ''' 48 | Given a list of floating point nums print them 49 | over multiple lines with 3 digits after the decimal point. 50 | For example, if nums = [1.2, 3.4,5.6,7.8] 51 | Output format: 52 | 1.200 53 | 3.400 54 | 5.600 55 | 7.800 56 | ''' 57 | for num in nums: 58 | print(f"{num:.3f}") 59 | 60 | # homogeneous - indefinite 61 | def display_random_ints(seed:int): 62 | ''' 63 | Given a random seed, set the random seed and 64 | generate multiple random integers within the range [0,100] 65 | (using `randint(0,100)`), until 0 is encountered and 66 | print it with max 10 comma seperated ints per line over multiple lines 67 | Output format 68 | 34,26,73,82,35,36,7,4,27,46 69 | 6,33,62,78,0 70 | ''' 71 | 72 | random.seed(seed) 73 | count = 0 74 | nums = [] 75 | while True: 76 | num = random.randint(0,100) 77 | nums.append(num) 78 | if num == 0: 79 | break 80 | count +=1 81 | if count % 10 == 0: 82 | print(*nums, sep=",") 83 | nums = [] 84 | print(*nums, sep=",") 85 | 86 | # hybrid - single line 87 | def display_batsman_runs(name:str, number:int, runs:list): 88 | ''' 89 | Given name, number and runs scored by a batsman 90 | display the name, number and runs separated by commas in the same line. 91 | For example, if name="player1", number=9 and runs=[2,3,4,4,6] 92 | Output Format; 93 | player1,9,2,3,4,4,6 94 | ''' 95 | print(name,number,*runs,sep=",") 96 | 97 | # key value 98 | def display_course_scores(course_scores:dict): 99 | ''' 100 | Given a dictionary of course scores with 101 | course name as keys and course scores as values. 102 | Format each course score pair separated by colon(':') 103 | on each line where each pair is printed over multiple lines 104 | in the ascending order of keys. 105 | For example, if course_scores = {"course1":78, "course3":89,"course2":90} 106 | Output format: 107 | course1:78 108 | course2:90 109 | course3:89 110 | ''' 111 | for key in sorted(course_scores): 112 | print(f"{key}:{course_scores[key]}") 113 | 114 | def display_all_batsman_runs(batsman_runs:list): 115 | ''' 116 | Given a list of tuple of batsman runs, 117 | print the batsman name and comma separated runs 118 | which are separated by a hyphen and printed over multiple lines. 119 | Arguments: batsman_runs: list[tuple(str, list[int])] 120 | For example, if batsman_runs = [ 121 | ("batsman1",[1,2,1,4,6,2,2,1]), 122 | ("batsman2",[2,2,6,4,1]), 123 | ("batsman3",[6,1,2,4,4,2]) 124 | ] 125 | Output format: 126 | batsman1-1,2,1,4,6,2,2,1 127 | batsman2-2,2,6,4,1 128 | batsman3-6,1,2,4,4,2 129 | ''' 130 | for batsman in batsman_runs: 131 | print(f"{batsman[0]}-{','.join(str(x) for x in batsman[1])}") 132 | 133 | def display_student_marks(student_marks:list): 134 | ''' 135 | Given the student rollno, city, age and marks of 136 | course1, course2 and course3 as a list of dicts, 137 | print the attributes of each student in a single 138 | line as comma separated values (in the previously mentioned order) 139 | and print the whole list over multiple lines. 140 | Arguments: student_marks: list[dict] where the keys of the dict are 'rollno':int,'city':str, 'age':int, 'course1':int, 'course2':int,'course2':int 141 | For example, if student_marks = [ 142 | {'rollno': 1, 'city': 'chennai', 'age': 23, 'course1': 86, 'course2': 69, 'course3': 86}, 143 | {'rollno': 2, 'city': 'mumbai', 'age': 19, 'course1': 78, 'course2': 65, 'course3': 89} 144 | ] 145 | Output: 146 | 1,chennai,23,86,69,86 147 | 2,mumbai,19,78,65,89 148 | ''' 149 | for student in student_marks: 150 | print(f"{student['rollno']},{student['city']},{student['age']},{student['course1']},{student['course2']},{student['course3']}") 151 | 152 | def display_student_marks_over_multiple_lines(student_marks:list): 153 | ''' 154 | Same input as the above function, but print each attribute 155 | over mulitple line in the same order of attributes as the previous one. 156 | For the example given in the above input, 157 | Output: 158 | 1 159 | chennai 160 | 23 161 | 86 162 | 69 163 | 86 164 | 2 165 | mumbai 166 | 19 167 | 78 168 | 65 169 | 89 170 | ''' 171 | 172 | for student in student_marks: 173 | print(student['rollno']) 174 | print(student['city']) 175 | print(student['age']) 176 | print(student['course1']) 177 | print(student['course2']) 178 | print(student['course3']) 179 | 180 | # this basically reads the input and executes it as code 181 | import sys 182 | exec(sys.stdin.read()) -------------------------------------------------------------------------------- /Grpa Week 6/question3.py: -------------------------------------------------------------------------------- 1 | ''' 2 | GrPA 3 - Problem Solving - GRADED 3 | Implement all the given functions according to the docstring. You may need to implement additional functions that will help you breakdown some of the problems into simpler ones.''' 4 | #answer 5 | 6 | def is_num_sorted(num) -> bool: 7 | num_str = str(num) 8 | return num_str == ''.join(sorted(num_str)) 9 | ''' 10 | Check if a number is sorted. 11 | sorted means the digits of a number are sorted in ascending order. 12 | Eg. 1468 - sorted , 4948 - not sorted. 13 | Argument: num: int 14 | Return: bool 15 | ''' 16 | 17 | 18 | def sorted_num_count(nums: list) -> int: 19 | return sum(is_num_sorted(num) for num in nums) 20 | ''' 21 | Given a list of nums(int) find the count of sorted numbers in the list. 22 | Arguments: nums - list[int] 23 | Return: count - int 24 | ''' 25 | 26 | def common_substring(words: list) -> str: 27 | if not words: 28 | return None 29 | shortest = min(words, key=len) 30 | for word in words: 31 | if shortest not in word: 32 | return None 33 | return shortest 34 | ''' 35 | Given a list of words check whether there is a word in words 36 | that is a substring of all other words. 37 | If there is a word return that word else return None 38 | Hint: only the smallest word can be a substring of all other words. 39 | Arguments: words - list[str] 40 | Return: common_substr_word - str 41 | ''' 42 | 43 | 44 | def is_valid_phone_number(phone_no: int) -> bool: 45 | phone_str = str(phone_no) 46 | if len(phone_str) != 10 or not phone_str.startswith('98123'): 47 | return False 48 | return all(phone_str.count(digit) <= 5 for digit in set(phone_str)) 49 | ''' 50 | Check if a number is valid for a specific operator. 51 | A phone number is valid if 52 | - it has 10 digits 53 | - should begin with 98123 54 | - same digit should not occur more that 5 times. 55 | ''' 56 | 57 | def validate_phone_numbers(phone_nos: list) -> dict: 58 | return {phone: "VALID" if is_valid_phone_number(phone) else "INVALID" for phone in phone_nos} 59 | ''' 60 | Given a list of phone numbers, create a dict with 61 | phone numbers as keys and the string "VALID" or "INVALID" 62 | depending on the validity of the phone number as described by the above funtion. 63 | Arguments: phone_nos - list 64 | Return: validity_dict - dict[int,str] 65 | ''' 66 | 67 | 68 | def get_election_winner(votes: dict) -> str: 69 | return max(votes, key=votes.get) 70 | ''' 71 | Given a dictionary with candidate name as key and number of votes as values, 72 | Find the winner of the election who has the maximum votes 73 | Arguments: votes - dict[str, int] 74 | Return: winner - str 75 | ''' 76 | 77 | def misspelt_words(vocab: str, sentence: str) -> list: 78 | vocab_set = set(vocab.split(',')) 79 | return [word for word in sentence.split() if word not in vocab_set] 80 | ''' 81 | Given a comma separated string of vocabulary, 82 | and a space separated string sentence, 83 | return a list of misspelt words in the order they occur in the sentence. 84 | The words which are not in the vocabulary are considered misspelt. 85 | Arguments: 86 | vocab - str: comma separated string with vocabulary 87 | sentence - str: space separated string of sentence 88 | Return: 89 | misspelt_words - list 90 | ''' 91 | 92 | def count_sock_pairs(sock_colors: list) -> int: 93 | from collections import Counter 94 | return sum(count // 2 for count in Counter(sock_colors).values()) 95 | ''' 96 | Given a list of sock colors representing the color of each sock, 97 | find the number of sock pair (both having same color) is there. 98 | Eg. ["red","blue","green","green","red","green","red","red","blue","black"] 99 | 2 red+ 1 green+ 1 blue = 5 pairs 100 | Arguments: sock_colors - list: of sock colors 101 | Return: number of pairs of sock - int 102 | ''' 103 | 104 | def is_vowely(word: str) -> bool: 105 | vowels = 'aeiou' 106 | word_vowels = ''.join(char for char in word.lower() if char in vowels) 107 | return word_vowels == vowels 108 | ''' 109 | Check if a given word is vowely. A word is vowely if 110 | - it has all the vowels in it. 111 | - the vowels occur in ascending order. 112 | Assume no letter repeats in the given word. 113 | Eg. abecidofu - vowely, tripe - not vowely, eviaoqu - not vowely 114 | Argument: word - a string with no letter repeated 115 | Return: bool 116 | Hint: if the non-vowels are removed from the word, it would be just aeiou 117 | ''' 118 | 119 | def vowely_count(words: list) -> int: 120 | return sum(is_vowely(word) for word in words) 121 | ''' 122 | Given a list of words find the number of vowely words from the list. 123 | Arguments: words :list[str] 124 | Return: int - number of vowely words 125 | ''' 126 | 127 | 128 | def format_name(first: str, middle: str, last: str) -> str: 129 | if middle: 130 | return f"{first.capitalize()} {middle.capitalize()} {last.capitalize()}" 131 | return f"{first.capitalize()} {last.capitalize()}" 132 | ''' 133 | Given three lower case parts of name, 134 | return the full name with first letter capitalized in each part. 135 | Note that middle name can be empty. 136 | ''' 137 | 138 | 139 | def double_palindromes(n: int) -> list: 140 | def is_palindrome(num): 141 | return str(num) == str(num)[::-1] 142 | 143 | return [i for i in range(1, n+1) if is_palindrome(i) and is_palindrome(i**2)] 144 | ''' 145 | Given a number n, find all the positive integers till n (including) 146 | that are double_palindrome. A number is double palindrome if 147 | it is a palindrome and its square is a palindrome. 148 | Eg. 149 | 8 - palindrome, not double palindrome 150 | 11 - palindrome and double palindrome 151 | 12 - not palindrome and not double palindrome 152 | Arguments: n - int: range of numbers to search 153 | Return: list of integers which are double palindrome in the ascending order 154 | ''' 155 | 156 | 157 | def scores_spx(kakashi_moves:list, guy_moves:list): 158 | k_score = 0 159 | g_score = 0 160 | for i in range(len(kakashi_moves)): 161 | if kakashi_moves[i] == "S" and guy_moves[i] == "X" or kakashi_moves[i] == "X" and guy_moves[i] == "P" or kakashi_moves[i] == "P" and guy_moves[i] == "S": 162 | k_score += 1 163 | elif kakashi_moves[i] == guy_moves[i]: 164 | continue 165 | else: 166 | g_score += 1 167 | return k_score, g_score 168 | ''' 169 | Given the series of moves played by Kakashi and Guy in a Stone-Paper-Scissor game, 170 | find the scores of Kakashi and guy respectively. 171 | Rules - Stone beats Scissor, Scissor beats Paper and Paper beats Stone 172 | Score - Number of times won 173 | Symbols - Stone - S, Paper - P, Scissor - X 174 | Arguments: 175 | kakashi_moves and guy_moves - list of moves where each move 176 | is a string corresponding to the symbol 177 | Return: kakashi_score:int , guy_score:int 178 | ''' -------------------------------------------------------------------------------- /Grpa Week 9/question1.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Shashwatology/IITM-Python-Grpa/5c1c5eed73297ca5b44fc2df482c278ce79a25d9/Grpa Week 9/question1.py -------------------------------------------------------------------------------- /Grpa Week 9/question2.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Shashwatology/IITM-Python-Grpa/5c1c5eed73297ca5b44fc2df482c278ce79a25d9/Grpa Week 9/question2.py -------------------------------------------------------------------------------- /Grpa Week 9/question3.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Shashwatology/IITM-Python-Grpa/5c1c5eed73297ca5b44fc2df482c278ce79a25d9/Grpa Week 9/question3.py -------------------------------------------------------------------------------- /Grpa Week 9/question4.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Shashwatology/IITM-Python-Grpa/5c1c5eed73297ca5b44fc2df482c278ce79a25d9/Grpa Week 9/question4.py -------------------------------------------------------------------------------- /Grpa Week 9/question5.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Shashwatology/IITM-Python-Grpa/5c1c5eed73297ca5b44fc2df482c278ce79a25d9/Grpa Week 9/question5.py -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | ### 2 | 3 | # Intro to Python Grpa - IIT Madras 4 | 5 | Hi, I'm Shashwat 👋' 6 | This repository contains all the Graded Programming Assessments (GRPA) for the Introduction to Python course, part of the Bachelor of Science in Data Science program at IIT Madras. These assessments are designed to test the understanding and application of Python programming concepts covered in each week of the course. 7 | 8 | 9 | 10 | 11 | ## Structure 12 | The repository is organized into 12 weekly folders, with each folder containing the GRPA for that particular week. Each week includes a set of all question with there solution mention in the GRPA of the particular week . 13 | 14 | ## **🛠️ Tech Stack** 15 | * Python 16 | 17 | ## **📸 Contributors** 18 | 19 | | Name | Role | GitHub | 20 | | ----- | ----- | ----- | 21 | | Shashwat Upadhyay | Project Lead | [GitHub Profile](https://github.com/shashwatology) | 22 | | Ritesh Sah | Contributor | [GitHub Profile](https://github.com/riteshsah235) | 23 | 24 | 25 | ## **📧 Contact** 26 | 27 | For queries, contact: 28 | **Shashwat Upadhyay** 29 | 📩 Email: contact.prepzen@gmail.com 30 | 🌐 Portfolio: [Bento ](https://bento.me/shashwatupadhyay) 31 | 32 | 33 | ## 🔗 Links 34 | 35 | [![portfolio](https://img.shields.io/badge/my_portfolio-000?style=for-the-badge&logo=ko-fi&logoColor=white)](https://bento.me/shashwatupadhyay) 36 | [![linkedin](https://img.shields.io/badge/linkedin-0A66C2?style=for-the-badge&logo=linkedin&logoColor=white)](https://www.linkedin.com/in/shashwat-upadhyay-13abb020b/) 37 | [![twitter](https://img.shields.io/badge/twitter-1DA1F2?style=for-the-badge&logo=twitter&logoColor=white)](https://x.com/_Shashwatology) 38 | 39 | --------------------------------------------------------------------------------