├── README.md ├── Python09_Errors_and_Exceptions ├── Ruby01_Introduction ├── Python15_Closures_and_Decorators ├── Python08_Date_and_Time ├── Python01_Introduction ├── Python16_Debugging ├── Python14_XML ├── Python05_Math ├── Python02_Basic_Data_Types ├── Interview01_Warm-up_Challenges ├── Python10_Classes ├── Python11_Built-Ins ├── Python12_Python_Functionals ├── Python06_Itertools ├── Ruby02_Control_Structures ├── Python04_Sets ├── Interview02_Arrays ├── Interview07_Search ├── Python03_Strings ├── ProblemSolving01_Warmup ├── Ruby03_Arrays_&_Hashes ├── Interview06_Greedy_Algorithms ├── Interview03_Dictionaries_and_Hashmaps ├── Interview04_Sorting ├── Python15_Numpy ├── Python07_Collections ├── Interview05_String_Manipulation ├── ProjectEuler+ ├── 10_Days_of_Statistics ├── SQL ├── 30_Days_of_Code └── 10_Days_of_Javascript /README.md: -------------------------------------------------------------------------------- 1 | # HackerRank_solutions 2 | This is a documentation of my Hackerrank solutions. 3 | 4 | ## My profile: 5 | https://www.hackerrank.com/jnyh1 6 | 7 | 8 | -------------------------------------------------------------------------------- /Python09_Errors_and_Exceptions: -------------------------------------------------------------------------------- 1 | ## Python 2 | ## Errors and Exceptions 3 | 4 | 5 | ## Exceptions 6 | # Enter your code here. Read input from STDIN. Print output to STDOUT 7 | n = int(input()) 8 | for _ in range(n): 9 | a,b = input().split() 10 | try: 11 | print(int(a)//int(b)) 12 | except Exception as err: 13 | print('Error Code:', err) 14 | 15 | 16 | ## Incorrect Regex 17 | # Enter your code here. Read input from STDIN. Print output to STDOUT 18 | 19 | # # Option 1 20 | # import re 21 | # for _ in range(int(input())): 22 | # result = True 23 | # try: 24 | # reg = re.compile(input()) 25 | # except Exception: # raises "re.error" 26 | # result = False 27 | # print(result) 28 | 29 | # Option 2 30 | import re 31 | for _ in range(int(input())): 32 | try: 33 | print(bool(re.compile(input()))) 34 | except: 35 | print('False') 36 | 37 | 38 | ## end ## 39 | -------------------------------------------------------------------------------- /Ruby01_Introduction: -------------------------------------------------------------------------------- 1 | ## Ruby 2 | ## Introduction 3 | 4 | 5 | ## Ruby Tutorial - Hello HackerRank! 6 | print "Hello HackerRank!!" 7 | 8 | 9 | 10 | 11 | ## Ruby Tutorial - Everything is an Object 12 | # Everything is an object in Ruby. For instance, if you type print self 13 | # In the code-editor, Ruby treats self as the object in which it is currently referred to. 14 | 15 | print self 16 | Expected Output 17 | main 18 | 19 | # everything in object.main is an object (of object class) 20 | # main is a method of the object class 21 | 22 | 23 | 24 | 25 | ## Ruby Tutorial - Object Methods 26 | def odd_or_even(number) 27 |     # add your code here 28 |     return number.even? 29 | end 30 | 31 | (0...gets.to_i).each do |i| 32 |     puts odd_or_even(gets.to_i) 33 | end 34 | 35 | 36 | 37 | 38 | ## Ruby Tutorial - Object Method Parameters 39 | # Three variables a, b, and c are already defined. 40 | # Your task is to write code that checks whether a is within the range of b and c by calling the method range? 41 | 42 | # write your code here 43 | a.range? b, c 44 | 45 | 46 | 47 | 48 | ## end ## 49 | -------------------------------------------------------------------------------- /Python15_Closures_and_Decorators: -------------------------------------------------------------------------------- 1 | ## Python 2 | ## Closures and Decorators 3 | 4 | 5 | ## Standardize Mobile Number Using Decorators 6 | """ 7 | Understanding Python Decorators in 12 Easy Steps! 8 | http://simeonfranklin.com/blog/2012/jul/1/python-decorators-in-12-steps/ 9 | """ 10 | # # Option 1 11 | # def wrapper(f): 12 | # def fun(l): 13 | # f(['+91 '+c[-10:-5]+' '+c[-5:] for c in l]) 14 | # return fun 15 | 16 | # Option 2 17 | def wrapper(f): 18 | def fun(l): 19 | f(['+91 '+i[::-1][:10][::-1][:5]+' '+i[::-1][:10][::-1][5:11] for i in l]) 20 | return fun 21 | 22 | @wrapper 23 | def sort_phone(l): 24 | print(*sorted(l), sep='\n') 25 | 26 | if __name__ == '__main__': 27 | l = [input() for _ in range(int(input()))] 28 | sort_phone(l) 29 | 30 | 31 | ## Decorators 2 - Name Directory 32 | import operator 33 | 34 | # Option 1 35 | def person_lister(f): 36 | def inner(people): 37 | # complete the function 38 | return map(f, sorted(people, key=lambda x: int(x[2]))) 39 | return inner 40 | 41 | # # Option 2 42 | # def person_lister(f): 43 | # def inner(people): 44 | # g=[] 45 | # people= sorted (people, key=lambda x : int(x[2])) 46 | # for i in people: 47 | # g.append(f(i)) 48 | # people=g 49 | # return people 50 | # return inner 51 | 52 | @person_lister 53 | def name_format(person): 54 | return ("Mr. " if person[3] == "M" else "Ms. ") + person[0] + " " + person[1] 55 | 56 | if __name__ == '__main__': 57 | people = [input().split() for i in range(int(input()))] 58 | print(*name_format(people), sep='\n') 59 | 60 | 61 | ## end ## 62 | -------------------------------------------------------------------------------- /Python08_Date_and_Time: -------------------------------------------------------------------------------- 1 | ## Python 2 | ## Date and Time 3 | 4 | 5 | ## Calendar Module 6 | # Enter your code here. Read input from STDIN. Print output to STDOUT 7 | 8 | # # Option 1 9 | # import calendar 10 | # month, day, year = map(int, input().split()) 11 | # print(list(calendar.day_name)[calendar.weekday(year, month, day)].upper()) 12 | 13 | # Option 2 14 | import datetime 15 | month, day, year = map(int, input().split()) 16 | print( datetime.datetime(year, month, day).strftime('%A').upper() ) 17 | 18 | # Option 2a 19 | from datetime import datetime 20 | month, day, year = map(int, input().split()) 21 | print( datetime(year, month, day).strftime('%A').upper() ) 22 | 23 | # # Option 3 24 | # import calendar 25 | # week_list = list(calendar.day_name) 26 | # month, day, year = map(int, input().split()) 27 | # result = calendar.weekday(year, month, day) 28 | # print((week_list[result]).upper()) 29 | 30 | 31 | ## Time Delta 32 | import math 33 | import os 34 | import random 35 | import re 36 | import sys 37 | 38 | # Complete the time_delta function below. 39 | from datetime import datetime as dt 40 | def time_delta(t1, t2): 41 | fmt = '%a %d %b %Y %H:%M:%S %z' #day dd mon yyyy hh mm ss utc 42 | t1 = dt.strptime(t1, fmt) 43 | t2 = dt.strptime(t2, fmt) 44 | result = (int( abs((t1 - t2).total_seconds()) )) 45 | return str(result) 46 | 47 | if __name__ == '__main__': 48 | fptr = open(os.environ['OUTPUT_PATH'], 'w') 49 | t = int(input()) 50 | for t_itr in range(t): 51 | t1 = input() 52 | t2 = input() 53 | delta = time_delta(t1, t2) 54 | fptr.write(delta + '\n') 55 | fptr.close() 56 | 57 | 58 | ## end ## 59 | -------------------------------------------------------------------------------- /Python01_Introduction: -------------------------------------------------------------------------------- 1 | ## Python 2 | ## Introduction 3 | 4 | 5 | ## Say "Hello, World!" With Python 6 | print("Hello, World!") 7 | 8 | 9 | ## Python If-Else 10 | #!/bin/python3 11 | 12 | import math 13 | import os 14 | import random 15 | import re 16 | import sys 17 | 18 | if __name__ == '__main__': 19 | n = int(input().strip()) 20 | 21 | if n%2 == 1: 22 | print('Weird') 23 | else: 24 | if n >=2 and n <= 5: 25 | print('Not Weird') 26 | elif n >=6 and n <= 20: 27 | print('Weird') 28 | elif n > 20: 29 | print('Not Weird') 30 | 31 | 32 | ## Arithmetic Operators 33 | if __name__ == '__main__': 34 | a = int(input()) 35 | b = int(input()) 36 | 37 | print(a+b) 38 | print(a-b) 39 | print(a*b) 40 | 41 | 42 | ## Python: Division 43 | if __name__ == '__main__': 44 | a = int(input()) 45 | b = int(input()) 46 | 47 | print(a//b) 48 | print(a/b) 49 | 50 | 51 | ## Loops 52 | if __name__ == '__main__': 53 | n = int(input()) 54 | 55 | for i in range(n): 56 | print(i**2) 57 | 58 | 59 | ## Write a function 60 | def is_leap(year): 61 | leap = False 62 | 63 | # Write your logic here 64 | if year%100==0 and year%400==0: 65 | leap = True 66 | elif year%4==0 and year%100!=0: 67 | leap = True 68 | 69 | return leap 70 | 71 | # In the Gregorian calendar three criteria must be taken into account to identify leap years: 72 | # The year can be evenly divided by 4, is a leap year, unless: 73 | # The year can be evenly divided by 100, it is NOT a leap year, unless: 74 | # The year is also evenly divisible by 400. Then it is a leap year. 75 | 76 | 77 | ## Print Function 78 | if __name__ == '__main__': 79 | n = int(input()) 80 | 81 | for i in range(1,n+1): 82 | print(i, end='') 83 | 84 | 85 | ## end ## 86 | -------------------------------------------------------------------------------- /Python16_Debugging: -------------------------------------------------------------------------------- 1 | ## Python 2 | ## Debugging 3 | 4 | 5 | ## Words Score 6 | # # Option 1 7 | # def score_words(words): 8 | # return sum(sum(char in 'aeiouy' for char in word) % 2 or 2 for word in words) 9 | 10 | # Option 2 11 | import re 12 | from functools import reduce 13 | def score_words(words): 14 | return reduce(lambda x, y: x+y, [2 if (len(re.findall('[aeiouy]',a))%2 == 0) else 1 for a in words], 0) 15 | 16 | # # Option 3 17 | # def is_vowel(letter): 18 | # return letter in ['a', 'e', 'i', 'o', 'u', 'y'] 19 | 20 | # def score_words(words): 21 | # score = 0 22 | # for word in words: 23 | # num_vowels = 0 24 | # for letter in word: 25 | # if is_vowel(letter): 26 | # num_vowels += 1 27 | # if num_vowels % 2 == 0: 28 | # score += 2 29 | # else: 30 | # score+=1 # change this 31 | # return score 32 | 33 | n = int(input()) 34 | words = input().split() 35 | print(score_words(words)) 36 | 37 | 38 | ## Default Arguments 39 | class EvenStream(object): 40 | def __init__(self): 41 | self.current = 0 42 | 43 | def get_next(self): 44 | to_return = self.current 45 | self.current += 2 46 | return to_return 47 | 48 | class OddStream(object): 49 | def __init__(self): 50 | self.current = 1 51 | 52 | def get_next(self): 53 | to_return = self.current 54 | self.current += 2 55 | return to_return 56 | 57 | 58 | def print_from_stream(n, stream=EvenStream()): 59 | # to reset self.current by calling constructor 60 | stream.__init__() # add this line only 61 | for _ in range(n): 62 | print(stream.get_next()) 63 | 64 | 65 | queries = int(input()) 66 | for _ in range(queries): 67 | stream_name, n = input().split() 68 | n = int(n) 69 | if stream_name == "even": 70 | print_from_stream(n) 71 | else: 72 | print_from_stream(n, OddStream()) 73 | 74 | 75 | ## end ## 76 | -------------------------------------------------------------------------------- /Python14_XML: -------------------------------------------------------------------------------- 1 | ## Python 2 | ## XML 3 | 4 | 5 | ## Find the Score 6 | import sys 7 | import xml.etree.ElementTree as etree 8 | 9 | # Option 1 10 | def get_attr_number(node): 11 | score = 0 12 | for child in node.iter(): 13 | score += len(child.attrib) 14 | return score 15 | 16 | # # Option 2 17 | # def get_attr_number(node): 18 | # score = 0 19 | # score += len(node.attrib) 20 | # for element in node: 21 | # score += get_attr_number(element) 22 | # return score 23 | 24 | # # Option 3 25 | # def get_attr_number(node): 26 | # score = 0 27 | # score += len(node.attrib) 28 | # if len(node)>1: 29 | # for i in node: 30 | # score += get_attr_number(i) 31 | # return score 32 | 33 | if __name__ == '__main__': 34 | sys.stdin.readline() 35 | xml = sys.stdin.read() 36 | tree = etree.ElementTree(etree.fromstring(xml)) 37 | root = tree.getroot() 38 | print(get_attr_number(root)) 39 | 40 | 41 | ## XML2 - Find the Maximum Depth 42 | import xml.etree.ElementTree as etree 43 | 44 | # # Option 1 45 | # maxdepth = 0 46 | # def depth(elem, level): 47 | # global maxdepth 48 | # level += 1 49 | # maxdepth = max(maxdepth, level) 50 | # for child in elem: 51 | # depth(child, level) 52 | 53 | # # Option 2 54 | # maxdepth = 0 55 | # arr = [] 56 | # def depth(elem, level): 57 | # global maxdepth 58 | # arr.append(level) 59 | # for i in elem.getchildren(): 60 | # depth(i, level+1) 61 | # maxdepth = max(arr)+1 62 | 63 | # Option 3 64 | maxdepth = 0 65 | def depth(elem, level): 66 | global maxdepth 67 | i = 0 68 | while i >= 0: 69 | if elem.find("." + "/*" * i) is None: 70 | maxdepth = i-1 71 | break 72 | i += 1 73 | 74 | if __name__ == '__main__': 75 | n = int(input()) 76 | xml = "" 77 | for i in range(n): 78 | xml = xml + input() + "\n" 79 | tree = etree.ElementTree(etree.fromstring(xml)) 80 | depth(tree.getroot(), -1) 81 | print(maxdepth) 82 | 83 | 84 | ## end ## 85 | -------------------------------------------------------------------------------- /Python05_Math: -------------------------------------------------------------------------------- 1 | ## Python 2 | ## Sets 3 | 4 | 5 | ## Polar Coordinates 6 | # Enter your code here. Read input from STDIN. Print output to STDOUT 7 | 8 | # option A 9 | # from cmath import polar 10 | # z = complex(input()) 11 | # print(*polar(z), sep='\n') 12 | 13 | # option B 14 | from cmath import * 15 | z = complex(input()) 16 | print(abs(z), phase(z), sep='\n') 17 | 18 | 19 | ## Find Angle MBC 20 | # Enter your code here. Read input from STDIN. Print output to STDOUT 21 | from math import degrees, atan2 22 | 23 | AB = int(input()) 24 | BC = int(input()) 25 | result = round(degrees(atan2(AB, BC))) 26 | print(str(result) + '°') 27 | 28 | 29 | ## Triangle Quest 2 30 | for i in range(1,int(input())+1): #More than 2 lines will result in 0 score. Do not leave a blank line also 31 | print((10**(i)//9)**2) 32 | 33 | # floor_division 34 | print((10**(i)//9)**2) 35 | 36 | # converted normal division's result into floor 37 | print(int(10**i/9)**2) 38 | 39 | # same output but failed (invalid string literal found) 40 | print( *range(1,i), *range(i,0,-1), sep='') 41 | 42 | # same output but failed (only 1 print statement is allowed) 43 | my_list = [1, 121, 12321, 1234321, 123454321, 12345654321, 1234567654321, 123456787654321, 12345678987654321, 12345678910987654321] 44 | n = int(input()) 45 | for i in range(0, n): 46 | print(my_list[i]) 47 | 48 | 49 | ## Mod Divmod 50 | # Enter your code here. Read input from STDIN. Print output to STDOUT 51 | numerator = int(input()) 52 | denominator = int(input()) 53 | print(numerator // denominator) 54 | print(numerator % denominator) 55 | print(divmod(numerator, denominator)) 56 | 57 | 58 | ## Power - Mod Power 59 | # Enter your code here. Read input from STDIN. Print output to STDOUT 60 | a,b,m = [int(input()) for _ in range(3)] 61 | print(pow(a,b)) 62 | print(pow(a,b,m)) 63 | 64 | 65 | ## Integers Come In All Sizes 66 | # Enter your code here. Read input from STDIN. Print output to STDOUT 67 | a,b,c,d = [int(input()) for _ in range(4)] 68 | print(pow(a,b) + pow(c,d)) 69 | 70 | 71 | ## Triangle Quest 72 | # using only arithmetic operations, a single for loop and print statement 73 | for i in range(1,int(input())): #More than 2 lines will result in 0 score. Do not leave a blank line also 74 | print( ( (10**i)//9 )*i ) # (10**i)//9 gives required seq of 1's 75 | 76 | # alternative 77 | print(int(i*(10**i-1)/9)) 78 | 79 | # same output but failed (str is not allowed) 80 | print(''.join([str(i)]*i)) 81 | 82 | 83 | ## end ## 84 | -------------------------------------------------------------------------------- /Python02_Basic_Data_Types: -------------------------------------------------------------------------------- 1 | ## Python 2 | ## Basic Data Types 3 | 4 | 5 | ## List Comprehensions 6 | Option 1: 7 | if __name__ == '__main__': 8 | x = int(input()) 9 | y = int(input()) 10 | z = int(input()) 11 | n = int(input()) 12 | 13 | print ([[a,b,c] for a in range(0,x+1) for b in range(0,y+1) for c in range(0,z+1) if a + b + c != n ]) 14 | 15 | Option 2: 16 | if __name__ == '__main__': 17 | x = int(input()) 18 | y = int(input()) 19 | z = int(input()) 20 | n = int(input()) 21 | 22 | l = [] 23 | for i in range(x + 1): 24 | for j in range(y + 1): 25 | for k in range(z + 1): 26 | if n != (i + j + k): 27 | l.append([i,j,k]) 28 | 29 | print(l) 30 | 31 | 32 | ## Find the Runner-Up Score! 33 | if __name__ == '__main__': 34 | n = int(input()) 35 | arr = map(int, input().split()) 36 | 37 | arr2 = sorted(arr) 38 | max_score = arr2[-1] 39 | for i in range(n): 40 | if arr2[-(i+1)] < max_score: 41 | print(arr2[-(i+1)]) 42 | break 43 | 44 | 45 | ## Nested Lists 46 | if __name__ == '__main__': 47 | name_list, score_list = [], [] 48 | n = int(input()) 49 | for _ in range(n): 50 | name = input() 51 | name_list.append(name) 52 | score = float(input()) 53 | score_list.append(score) 54 | 55 | students = list(zip(name_list, score_list)) 56 | students1 = sorted(students) 57 | second_score = sorted(set(b for a,b in students1))[1] 58 | for i in range(n): 59 | if students1[i][1] == second_score: 60 | print((students1[i][0])) 61 | 62 | 63 | ## Finding the percentage 64 | if __name__ == '__main__': 65 | n = int(input()) 66 | student_marks = {} 67 | for _ in range(n): 68 | name, *line = input().split() 69 | scores = list(map(float, line)) 70 | student_marks[name] = scores 71 | query_name = input() 72 | 73 | total = sum(student_marks[query_name]) 74 | print("{:.2f}".format(total/3)) 75 | 76 | 77 | ## Lists 78 | if __name__ == '__main__': 79 | N = int(input()) 80 | 81 | my_list = [] 82 | for _ in range(N): 83 | s = input().split() 84 | cmd = s[0] 85 | args = s[1:] 86 | if cmd !="print": 87 | cmd += "("+ ",".join(args) +")" 88 | eval("my_list."+cmd) 89 | else: 90 | print(my_list) 91 | 92 | 93 | ## Tuples 94 | if __name__ == '__main__': 95 | n = int(input()) 96 | integer_list = map(int, input().split()) 97 | 98 | t = tuple(integer_list) 99 | print(hash(t)) 100 | 101 | 102 | ## end ## 103 | -------------------------------------------------------------------------------- /Interview01_Warm-up_Challenges: -------------------------------------------------------------------------------- 1 | ## Interview Preparation Kit 2 | ## Warm-up Challenges 3 | 4 | 5 | 6 | 7 | ## Sock Merchant 8 | 9 | #!/bin/python3 10 | import math 11 | import os 12 | import random 13 | import re 14 | import sys 15 | 16 | # Complete the sockMerchant function below. 17 | from collections import Counter 18 | def sockMerchant(n, ar): 19 | total = 0 20 | for value in Counter(ar).values(): 21 | total += value//2 22 | return total 23 | 24 | if __name__ == '__main__': 25 | fptr = open(os.environ['OUTPUT_PATH'], 'w') 26 | n = int(input()) 27 | ar = list(map(int, input().rstrip().split())) 28 | result = sockMerchant(n, ar) 29 | fptr.write(str(result) + '\n') 30 | fptr.close() 31 | 32 | 33 | 34 | 35 | ## Counting Valleys 36 | import math 37 | import os 38 | import random 39 | import re 40 | import sys 41 | 42 | # Complete the countingValleys function below. 43 | def countingValleys(n, s): 44 | altitude = 0 45 | valleys = 0 46 | for letter in s: 47 | if letter == 'U': 48 | altitude += 1 49 | else: 50 | altitude -= 1 51 | if altitude == -1: 52 | valleys += 1 53 | return valleys 54 | 55 | if __name__ == '__main__': 56 | fptr = open(os.environ['OUTPUT_PATH'], 'w') 57 | n = int(input()) 58 | s = input() 59 | result = countingValleys(n, s) 60 | fptr.write(str(result) + '\n') 61 | fptr.close() 62 | 63 | 64 | 65 | 66 | ## Jumping on the Clouds 67 | import math 68 | import os 69 | import random 70 | import re 71 | import sys 72 | 73 | # Complete the jumpingOnClouds function below. 74 | def jumpingOnClouds(c): 75 | jump = 0 76 | i = 1 77 | while i < len(c): 78 | if i != len(c)-1 and c[i+1] == 0: 79 | jump += 1 80 | i += 2 81 | elif c[i] == 0: 82 | jump += 1 83 | i += 1 84 | return jump 85 | 86 | if __name__ == '__main__': 87 | fptr = open(os.environ['OUTPUT_PATH'], 'w') 88 | n = int(input()) 89 | c = list(map(int, input().rstrip().split())) 90 | result = jumpingOnClouds(c) 91 | fptr.write(str(result) + '\n') 92 | fptr.close() 93 | 94 | # 0 0 0 0 1 0 95 | # 0 0 0 1 0 0 96 | 97 | 98 | 99 | 100 | ## Repeated String 101 | import math 102 | import os 103 | import random 104 | import re 105 | import sys 106 | 107 | # Complete the repeatedString function below. 108 | def repeatedString(s, n): 109 | count = s.count('a') 110 | full_str = n//len(s) 111 | remainder = n%len(s) 112 | total = count*full_str + s[:remainder].count('a') 113 | return total 114 | # return (s.count("a") * (n // len(s)) + s[:n % len(s)].count("a")) 115 | 116 | if __name__ == '__main__': 117 | fptr = open(os.environ['OUTPUT_PATH'], 'w') 118 | s = input() 119 | n = int(input()) 120 | result = repeatedString(s, n) 121 | fptr.write(str(result) + '\n') 122 | fptr.close() 123 | 124 | 125 | 126 | 127 | ## end ## 128 | -------------------------------------------------------------------------------- /Python10_Classes: -------------------------------------------------------------------------------- 1 | ## Python 2 | ## Classes 3 | 4 | 5 | ## Classes: Dealing with Complex Numbers 6 | import math 7 | 8 | class Complex(object): 9 | def __init__(self, real, imaginary): 10 | self.real = real 11 | self.imaginary = imaginary 12 | 13 | def __add__(self, no): 14 | a = self.real + no.real 15 | b = self.imaginary + no.imaginary 16 | return Complex(a,b) 17 | 18 | def __sub__(self, no): 19 | a = self.real - no.real 20 | b = self.imaginary - no.imaginary 21 | return Complex(a,b) 22 | 23 | def __mul__(self, no): 24 | a = self.real*no.real - self.imaginary*no.imaginary 25 | b = self.imaginary*no.real + self.real*no.imaginary 26 | return Complex(a,b) 27 | 28 | def __truediv__(self, no): 29 | conjugate = Complex(no.real,(-no.imaginary)) 30 | num = self*conjugate 31 | denom = no*conjugate 32 | try: 33 | return(Complex((num.real/denom.real),(num.imaginary/denom.real))) 34 | except Exception as e: 35 | print(e) 36 | 37 | def mod(self): 38 | return(Complex(math.sqrt(self.real**2+self.imaginary**2),0)) 39 | 40 | def __str__(self): 41 | if self.imaginary == 0: 42 | result = "%.2f+0.00i" % (self.real) 43 | elif self.real == 0: 44 | if self.imaginary >= 0: 45 | result = "0.00+%.2fi" % (self.imaginary) 46 | else: 47 | result = "0.00-%.2fi" % (abs(self.imaginary)) 48 | elif self.imaginary > 0: 49 | result = "%.2f+%.2fi" % (self.real, self.imaginary) 50 | else: 51 | result = "%.2f-%.2fi" % (self.real, abs(self.imaginary)) 52 | return result 53 | 54 | if __name__ == '__main__': 55 | c = map(float, input().split()) 56 | d = map(float, input().split()) 57 | x = Complex(*c) 58 | y = Complex(*d) 59 | print(*map(str, [x+y, x-y, x*y, x/y, x.mod(), y.mod()]), sep='\n') 60 | 61 | 62 | ## Class 2 - Find the Torsional Angle 63 | import math 64 | 65 | class Points(object): 66 | def __init__(self, x, y, z): 67 | self.x=x 68 | self.y=y 69 | self.z=z 70 | 71 | def __sub__(self, no): 72 | return Points((self.x-no.x),(self.y-no.y),(self.z-no.z)) 73 | 74 | def dot(self, no): 75 | return (self.x*no.x)+(self.y*no.y)+(self.z*no.z) 76 | 77 | def cross(self, no): 78 | return Points((self.y*no.z-self.z*no.y),(self.z*no.x-self.x*no.z),(self.x*no.y-self.y*no.x)) 79 | 80 | def absolute(self): 81 | return pow((self.x ** 2 + self.y ** 2 + self.z ** 2), 0.5) 82 | 83 | if __name__ == '__main__': 84 | points = list() 85 | for i in range(4): 86 | a = list(map(float, input().split())) 87 | points.append(a) 88 | 89 | a, b, c, d = Points(*points[0]), Points(*points[1]), Points(*points[2]), Points(*points[3]) 90 | x = (b - a).cross(c - b) 91 | y = (c - b).cross(d - c) 92 | angle = math.acos(x.dot(y) / (x.absolute() * y.absolute())) 93 | 94 | print("%.2f" % math.degrees(angle)) 95 | 96 | 97 | ## end ## 98 | -------------------------------------------------------------------------------- /Python11_Built-Ins: -------------------------------------------------------------------------------- 1 | ## Python 2 | ## Built-Ins 3 | 4 | 5 | ## Zipped! 6 | # Enter your code here. Read input from STDIN. Print output to STDOUT 7 | 8 | # # Option 1 9 | # n, x = map(int, input().split()) 10 | # input_list = [] 11 | # for _ in range(x): 12 | # input_list.append([float(i) for i in input().split()]) 13 | # zipped = list(zip(*input_list)) 14 | # for i in range(n): 15 | # print('{:.1f}'.format(sum(zipped[i])/len(zipped[i]))) 16 | 17 | # Option 2 18 | n, x = map(int, input().split()) 19 | input_list = [] 20 | for _ in range(x): 21 | input_list.append( map(float, input().split()) ) 22 | for marks in zip(*input_list): 23 | print( sum(marks)/len(marks) ) 24 | 25 | 26 | ## input() 27 | # Enter your code here. Read input from STDIN. Print output to STDOUT 28 | 29 | # # Option 1 30 | # x,k = map(int, input().split()) 31 | # print(eval(input()) == k) 32 | 33 | # Option 2 34 | x,k = [int(_) for _ in input().split()] 35 | print('True' if eval(input())==k else 'False') 36 | 37 | 38 | ## Python Evaluation 39 | # Enter your code here. Read input from STDIN. Print output to STDOUT 40 | input_str = input() 41 | eval(input_str) 42 | 43 | 44 | ## Athlete Sort 45 | import math 46 | import os 47 | import random 48 | import re 49 | import sys 50 | 51 | if __name__ == '__main__': 52 | nm = input().split() 53 | n = int(nm[0]) 54 | m = int(nm[1]) 55 | 56 | # # Option 1 57 | # arr = [] 58 | # for _ in range(n): 59 | # arr.append(list(map(int, input().rstrip().split()))) 60 | # k = int(input()) 61 | # for row in sorted(arr, key=lambda row: int(row[k])): 62 | # print(*row) 63 | 64 | # Option 2 65 | arr = [] 66 | for _ in range(n): 67 | arr.append(list(map(int, input().rstrip().split()))) 68 | k = int(input()) 69 | for row in sorted(arr, key=lambda arr: arr[k]): 70 | print(*row) 71 | 72 | # # Option 3 (a little slower) 73 | # from operator import itemgetter 74 | # arr = [[int(i) for i in input().split()] for _ in range(n)] 75 | # k = int(input()) 76 | # for row in sorted(arr, key=itemgetter(k)): 77 | # print(*row) 78 | 79 | 80 | ## Any or All 81 | # Enter your code here. Read input from STDIN. Print output to STDOUT 82 | 83 | # # Option 1 84 | # n = int(input()) 85 | # arr = input().split() 86 | # print(all([int(i)>0 for i in arr]) and any([j == j[::-1] for j in arr])) 87 | 88 | # Option 2 uses generators (iso list) so execution time is less 89 | n = int(input()) 90 | arr = input().split() 91 | print(all(int(i)>0 for i in arr) and any(j == j[::-1]for j in arr)) 92 | 93 | 94 | ## ginortS (ie, Sorting) 95 | # Enter your code here. Read input from STDIN. Print output to STDOUT 96 | 97 | # # Option 1 98 | # print(*sorted(input(), key=lambda c: (-ord(c) >> 5, c in '02468', c)), sep='') 99 | 100 | # # Option 2 101 | # print(*sorted(input(), key=lambda c: (c.isdigit() - c.islower(), c in '02468', c)), sep='') 102 | 103 | # # Option 3 104 | # order = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1357902468' 105 | # print(*sorted(input(), key=order.index), sep='') 106 | 107 | # Option 4 108 | import string 109 | print(*sorted(input(), key=(string.ascii_letters + '1357902468').index), sep='') 110 | 111 | 112 | ## end ## 113 | -------------------------------------------------------------------------------- /Python12_Python_Functionals: -------------------------------------------------------------------------------- 1 | ## Python 2 | ## Python Functionals 3 | 4 | 5 | ## Map and Lambda Function 6 | cube = lambda x:x*x*x # complete the lambda function 7 | 8 | # # Option 1 9 | # def fibonacci(n): 10 | # # return a list of fibonacci numbers 11 | # arr = [] 12 | # a = 0 13 | # b = 1 14 | # for i in range(n): 15 | # arr.append(a) 16 | # a,b = b,a+b 17 | # return arr 18 | 19 | # Option 2 20 | def fibonacci(n): 21 | arr = [] 22 | for i in range(n): 23 | if i<=1: 24 | arr.append(i) 25 | else: 26 | arr.append(arr[-1] + arr[-2]) 27 | return arr 28 | 29 | if __name__ == '__main__': 30 | n = int(input()) 31 | print(list(map(cube, fibonacci(n)))) 32 | 33 | 34 | ## Validating Email Addresses With a Filter 35 | # # Option 1 36 | # def fun(s): 37 | # # return True if s is a valid email, else return False 38 | # if ('@' not in s) or ('.' not in s) or (' ' in s): 39 | # return False 40 | # if s.count('@')>1: 41 | # return False 42 | # if s.count('.')>1: 43 | # return False 44 | # s = s.replace('@',' ') 45 | # s = s.replace('.',' ') 46 | # l = list(map(str, s.split())) 47 | # if len(l)<3: 48 | # return False 49 | # for j in l[0]: 50 | # if j.isalnum()==False and j!='_' and j!='-': 51 | # return False 52 | # for j in l[1]: 53 | # if j.isalnum()==False: 54 | # return False 55 | # if len(l[2])>3 or len(l[2])==0: 56 | # return False 57 | # return True 58 | 59 | # # Option 2 60 | # def fun(s): 61 | # # return True if s is a valid email, else return False 62 | # if not (s.count('@')==1 and s.count('.')==1): 63 | # return False 64 | # s = s.replace('@','.') 65 | # l,m,n = s.split('.') 66 | # l = l.replace('_','').replace('-','') 67 | # if (l.isalnum() and m.isalnum() and n.isalpha() and 00 ): 68 | # return True 69 | # else: 70 | # return False 71 | 72 | # Option 3 73 | import re 74 | def fun(s): 75 | return (True if re.match('[a-zA-Z0-9_-]+@[a-zA-Z0-9]+\.[a-zA-Z]{1,3}$',s) is not None else False) 76 | 77 | def filter_mail(emails): 78 | return list(filter(fun, emails)) 79 | 80 | if __name__ == '__main__': 81 | n = int(input()) 82 | emails = [] 83 | for _ in range(n): 84 | emails.append(input()) 85 | 86 | filtered_emails = filter_mail(emails) 87 | filtered_emails.sort() 88 | print(filtered_emails) 89 | 90 | 91 | ## Reduce Function 92 | """ 93 | The reduce() function applies a function of two arguments cumulatively on a list of objects in succession from left to right to reduce it to one value. Say you have a list, say [1,2,3] and you have to find its sum. 94 | >>> reduce(lambda x, y : x + y,[1,2,3]) 95 | 6 96 | >>> reduce(lambda x, y : x + y, [1,2,3], -3) 97 | 3 98 | """ 99 | from fractions import Fraction 100 | from functools import reduce 101 | 102 | def product(fracs): 103 | t = reduce(lambda x,y: x*y, fracs) # complete this line with a reduce statement 104 | return t.numerator, t.denominator 105 | 106 | if __name__ == '__main__': 107 | fracs = [] 108 | for _ in range(int(input())): 109 | fracs.append(Fraction(*map(int, input().split()))) 110 | result = product(fracs) 111 | print(*result) 112 | 113 | 114 | ## end ## 115 | -------------------------------------------------------------------------------- /Python06_Itertools: -------------------------------------------------------------------------------- 1 | ## Python 2 | ## Itertools 3 | 4 | 5 | ## itertools.product() 6 | # Enter your code here. Read input from STDIN. Print output to STDOUT 7 | from itertools import product 8 | 9 | A = list(map(int, input().split())) # 1 2 10 | B = list(map(int, input().split())) # 3 4 11 | print(*product(A, B)) 12 | # (1, 3) (1, 4) (2, 3) (2, 4) 13 | 14 | 15 | ## itertools.permutations() 16 | # Enter your code here. Read input from STDIN. Print output to STDOUT 17 | from itertools import permutations 18 | s, k = input().split() # default input type str, eg HACK 2 becomes 'HACK' '2' 19 | s = sorted(s) 20 | k = int(k) 21 | for p in list(permutations(s, k)): 22 | print(*p, sep='') 23 | # AC 24 | # AH 25 | # AK 26 | # CA 27 | # CH 28 | # CK 29 | # HA 30 | # HC 31 | # HK 32 | # KA 33 | # KC 34 | # KH 35 | 36 | 37 | ## itertools.combinations() 38 | # Enter your code here. Read input from STDIN. Print output to STDOUT 39 | from itertools import combinations 40 | s, n = input().split() # HACK 2 41 | 42 | # # Option A 43 | # for i in range(1, int(n)+1): 44 | # for j in combinations(sorted(s), i): 45 | # print(''.join(j)) 46 | 47 | # Option B 48 | for k in range(1, int(n)+1): 49 | print(*[''.join(item) for item in combinations(sorted(s), k)], sep='\n') 50 | 51 | # A 52 | # C 53 | # H 54 | # K 55 | # AC 56 | # AH 57 | # AK 58 | # CH 59 | # CK 60 | # HK 61 | 62 | 63 | ## itertools.combinations_with_replacement() 64 | # Enter your code here. Read input from STDIN. Print output to STDOUT 65 | from itertools import combinations_with_replacement 66 | s, k = map(str, input().split()) # HACK 2 67 | s = sorted(s) 68 | k = int(k) 69 | for e in list(combinations_with_replacement(s, k)): 70 | print(*e, sep='') 71 | 72 | # AA 73 | # AC 74 | # AH 75 | # AK 76 | # CC 77 | # CH 78 | # CK 79 | # HH 80 | # HK 81 | # KK 82 | 83 | 84 | ## Compress the String! 85 | # Enter your code here. Read input from STDIN. Print output to STDOUT 86 | from itertools import groupby 87 | 88 | # # Option A 89 | # print(*[(len(list(c)), int(k)) for k, c in groupby(input())]) 90 | 91 | # Option B 92 | for k,v in groupby(input()): 93 | print((len(list(v)),int(k)),end=' ') 94 | 95 | # input 1222311 96 | # output (1, 1) (3, 2) (1, 3) (2, 1) 97 | 98 | 99 | ## Iterables and Iterators 100 | # Enter your code here. Read input from STDIN. Print output to STDOUT 101 | from itertools import combinations 102 | N = int(input()) 103 | letters = input().split() 104 | K = int(input()) 105 | all_combi = list(combinations(letters, K)) 106 | 107 | # # Option A 108 | # count_a = [i for i in all_combi if 'a' in i] 109 | # print('{0:.3}'.format( len(count_a)/len(all_combi) )) 110 | 111 | # Option B 112 | count_a = 0 113 | for combi in all_combi: 114 | if 'a' in combi: 115 | count_a += 1 116 | print('{0:.3}'.format( count_a/len(all_combi) )) 117 | 118 | 119 | ## Maximize It! 120 | # Enter your code here. Read input from STDIN. Print output to STDOUT 121 | from itertools import product 122 | K, M = map(int, input().split()) 123 | 124 | # # Option A 125 | # Numbers = (list(map(int, input().split()))[1:] for _ in range(K)) 126 | # result = map(lambda x: sum(i**2 for i in x)%M, product(*Numbers)) 127 | # print(max(result)) 128 | 129 | # # Option B 130 | # Numbers = [] 131 | # for _ in range(K): 132 | # Numbers.append(list(map(int, input().split()))[1:]) 133 | # result = list(map(lambda x: sum(pow(i,2) for i in x)%M, product(*Numbers))) 134 | # print(max(result)) 135 | 136 | # Option C 137 | Numbers = [] 138 | for _ in range(K): 139 | Numbers.append(list(map(int, input().split()))[1:]) 140 | list_com = list(product(*Numbers)) 141 | result = [sum(map(lambda x: x**2,x))%M for x in list_com] 142 | print(max(result)) 143 | 144 | 145 | ## end ## 146 | -------------------------------------------------------------------------------- /Ruby02_Control_Structures: -------------------------------------------------------------------------------- 1 | ## Ruby 2 | ## Control Structures 3 | 4 | 5 | ## Ruby Control Structures - Each 6 | # use control structure each to iterate through its collections 7 | # given a method called scoring with an array passed as an argument. Elements of the array are of the class User 8 | # User class has a method update_score 9 | # task is to iterate through each of the elements in the array using each and call the method update_score on every element 10 | 11 | # Option 1 12 | def scoring(array) 13 | # iterate through each of the element in array using *each* and call update_score on it 14 | array.each do |user| 15 | user.update_score 16 | end 17 | end 18 | 19 | # Option 2 20 | def scoring(array) 21 | # iterate through each of the element in array using *each* and call update_score on it 22 | array.each { 23 | |user| 24 | user.update_score 25 | } 26 | end 27 | 28 | 29 | 30 | 31 | ## Ruby Control Structures - Unless 32 | # given a method called scoring with an array passed as an argument. Elements of the array are of the class User 33 | # User has two public methods, is_admin? and update_score. 34 | # task is to use the control structure unless and update all elements of the array who are not admins 35 | # unless is the logical equivalent of if not 36 | 37 | # Option 1 38 | def scoring(array) 39 | # update_score of every user in the array unless the user is admin 40 | array.each do |user| 41 | unless user.is_admin? 42 | user.update_score 43 | end 44 | end 45 | end 46 | 47 | # Option 2 48 | def scoring(array) 49 | # update_score of every user in the array unless the user is admin 50 | array.each do |user| 51 | user.update_score unless user.is_admin? 52 | end 53 | end 54 | 55 | # Option 3 56 | def scoring(array) 57 | # update_score of every user in the array unless the user is admin 58 | array.each { 59 | |user| 60 | user.update_score unless user.is_admin? 61 | } 62 | end 63 | 64 | 65 | 66 | 67 | ## Ruby Control Structures - Infinite Loop 68 | # An infinite loop in Ruby is of the form 69 | loop do 70 | end 71 | # Use an infinite loop and call the method coder.practice within it and break if coder.oh_one? is true. 72 | 73 | # Option 1 74 | loop do 75 | coder.practice 76 | if coder.oh_one? 77 | break 78 | end 79 | end 80 | 81 | # Option 2 82 | loop do 83 | coder.practice 84 | break if coder.oh_one? 85 | end 86 | 87 | 88 | 89 | 90 | ## Ruby Control Structures - Until 91 | # Call the method coder.practice until coder.oh_one? becomes true. 92 | # Use the until control structure. 93 | # until is the logical equivalent of while not. 94 | 95 | # Option 1 96 | while not coder.oh_one? 97 | coder.practice 98 | end 99 | 100 | # Option 2 101 | until coder.oh_one? 102 | coder.practice 103 | end 104 | 105 | # Option 3 106 | coder.practice until coder.oh_one? 107 | 108 | 109 | 110 | 111 | ## Ruby Control Structures - Case (Bonus Question) 112 | # HackerRank is written in RoR and we have various classes defined in it. 113 | 114 | # Option 1 115 | def identify_class(obj) 116 | # write your case control structure here 117 | case obj 118 | when Hacker, Submission, TestCase, Contest 119 | puts "It's a #{obj.class}!" 120 | else 121 | puts "It's an unknown model" 122 | end 123 | end 124 | 125 | # Option 2 unrefactored version 126 | def identify_class(obj) 127 | case obj 128 | when Hacker 129 | puts "It's a Hacker!" 130 | when Submission 131 | puts "It's a Submission!" 132 | when TestCase 133 | puts "It's a TestCase!" 134 | when Contest 135 | puts "It's a Contest!" 136 | else 137 | puts "It's an unknown model" 138 | end 139 | end 140 | 141 | # # Option 3 (not working) 142 | # def identify_class(obj) 143 | # if obj == Hacker || obj == Submission || obj == TestCase || obj == Contest 144 | # puts "It's a #{obj.class}!" 145 | # else 146 | # puts "It's an unknown model" 147 | # end 148 | # end 149 | 150 | 151 | 152 | 153 | ## end ## 154 | -------------------------------------------------------------------------------- /Python04_Sets: -------------------------------------------------------------------------------- 1 | ## Python 2 | ## Sets 3 | 4 | 5 | ## Introdduction to Sets 6 | def average(array): 7 | # your code goes here 8 | array_set = set(array) 9 | return sum(array_set) / len(array_set) 10 | 11 | if __name__ == '__main__': 12 | n = int(input()) 13 | arr = list(map(int, input().split())) 14 | result = average(arr) 15 | print(result) 16 | 17 | 18 | ## No Idea! 19 | # Enter your code here. Read input from STDIN. Print output to STDOUT 20 | (n, m), arr_list, A, B = [input().split() for _ in range(4)] 21 | 22 | A, B = set(A), set(B) # for time efficiency 23 | happiness = 0 24 | for i in arr_list: 25 | if i in A: 26 | happiness += 1 27 | elif i in B: 28 | happiness -= 1 29 | print(happiness) 30 | 31 | 32 | ## Symmetric Difference 33 | # Enter your code here. Read input from STDIN. Print output to STDOUT 34 | m = int(input()) 35 | set_m = set(map(int, input().split())) 36 | 37 | n = int(input()) 38 | set_n = set(map(int, input().split())) 39 | 40 | new_set = set_m.difference(set_n) 41 | temp = set_n.difference(set_m) 42 | 43 | new_set.update(temp) 44 | new_set = sorted(new_set) 45 | 46 | for e in new_set: 47 | print(e) 48 | 49 | 50 | ## Set .add() 51 | # Enter your code here. Read input from STDIN. Print output to STDOUT 52 | n = int(input()) 53 | countries = set() 54 | for _ in range(n): 55 | countries.add(input()) 56 | 57 | print(len(countries)) 58 | 59 | 60 | ## Set .discard(), .remove() & .pop() 61 | n = int(input()) 62 | s = set(map(int, input().split())) 63 | N = int(input()) 64 | 65 | for _ in range(N): 66 | command = input().split() 67 | if command[0] == 'pop': 68 | s.pop() 69 | elif command[0] == 'remove': 70 | s.remove(int(command[1])) 71 | elif command[0] == 'discard': 72 | s.discard(int(command[1])) 73 | 74 | total = sum(s) 75 | print(total) 76 | 77 | 78 | ## Set .union() Operation 79 | # Enter your code here. Read input from STDIN. Print output to STDOUT 80 | n = int(input()) 81 | set_n = set(map(int, input().split())) 82 | 83 | b = int(input()) 84 | set_b = set(map(int, input().split())) 85 | 86 | new_set = set_n.union(set_b) 87 | print(len(new_set)) 88 | 89 | 90 | ## Set .intersection() Operation 91 | # Enter your code here. Read input from STDIN. Print output to STDOUT 92 | n = int(input()) 93 | set_n = set(map(int, input().split())) 94 | 95 | b = int(input()) 96 | set_b = set(map(int, input().split())) 97 | 98 | new_set = set_n.intersection(set_b) 99 | print(len(new_set)) 100 | 101 | 102 | ## Set .difference() Operation 103 | # Enter your code here. Read input from STDIN. Print output to STDOUT 104 | n = int(input()) 105 | set_n = set(map(int, input().split())) 106 | 107 | b = int(input()) 108 | set_b = set(map(int, input().split())) 109 | 110 | new_set = set_n.difference(set_b) 111 | print(len(new_set)) 112 | 113 | 114 | ## Set .symmetric_difference() Operation 115 | # Enter your code here. Read input from STDIN. Print output to STDOUT 116 | n = int(input()) 117 | set_n = set(map(int, input().split())) 118 | 119 | b = int(input()) 120 | set_b = set(map(int, input().split())) 121 | 122 | new_set = set_n.difference(set_b) 123 | temp = set_b.difference(set_n) 124 | 125 | new_set.update(temp) 126 | print(len(new_set)) 127 | 128 | 129 | ## Set Mutations 130 | # Enter your code here. Read input from STDIN. Print output to STDOUT 131 | n = int(input()) 132 | set_A = set(map(int,input().split())) 133 | N = int(input()) 134 | 135 | for _ in range(N): 136 | operation = input().split() 137 | new_set = set(map(int,input().split())) 138 | eval('set_A.{}({})'.format(operation[0], new_set)) 139 | print(sum(set_A)) 140 | 141 | 142 | ## The Captain's Room 143 | # Enter your code here. Read input from STDIN. Print output to STDOUT 144 | from collections import Counter 145 | n = int(input()) 146 | room_list = list(map(int, input().split())) 147 | freq = Counter(room_list) 148 | 149 | for room in freq.keys(): 150 | if freq[room] == 1: 151 | print(room) 152 | break 153 | 154 | 155 | ## Check Subset 156 | # Enter your code here. Read input from STDIN. Print output to STDOUT 157 | N = int(input()) 158 | 159 | for _ in range(N): 160 | n1 = int(input()) 161 | set_a = set(map(int, input().split())) 162 | n2 = int(input()) 163 | set_b = set(map(int, input().split())) 164 | 165 | print(set_a.intersection(set_b) == set_a) 166 | 167 | 168 | ## Check Strict Superset 169 | # Enter your code here. Read input from STDIN. Print output to STDOUT 170 | set_a = set(map(int, input().split())) 171 | N = int(input()) 172 | 173 | for _ in range(N): 174 | new_set = set(map(int, input().split())) 175 | if (new_set < set_a): 176 | continue 177 | else: 178 | break 179 | 180 | print(new_set < set_a) 181 | 182 | 183 | ## end ## 184 | -------------------------------------------------------------------------------- /Interview02_Arrays: -------------------------------------------------------------------------------- 1 | ## Interview Preparation Kit 2 | ## Arrays 3 | 4 | 5 | 6 | 7 | ## 2D Array - DS 8 | import math 9 | import os 10 | import random 11 | import re 12 | import sys 13 | 14 | # Complete the hourglassSum function below. 15 | def hourglassSum(arr): 16 | hourglass_sum = [] 17 | for i in range(0,4): 18 | for j in range(0,4): 19 | # (sum of 3x3 block) - (1 element on left) - (1 element on right) 20 | total=sum([sum(x[i:i+3]) for x in arr[j:j+3]]) - arr[j+1][i] - arr[j+1][i+2] 21 | hourglass_sum.append(total) 22 | return (max(hourglass_sum)) 23 | 24 | if __name__ == '__main__': 25 | fptr = open(os.environ['OUTPUT_PATH'], 'w') 26 | arr = [] 27 | for _ in range(6): 28 | arr.append(list(map(int, input().rstrip().split()))) 29 | result = hourglassSum(arr) 30 | fptr.write(str(result) + '\n') 31 | fptr.close() 32 | 33 | 34 | 35 | 36 | ## Left Rotation 37 | import math 38 | import os 39 | import random 40 | import re 41 | import sys 42 | 43 | # Complete the rotLeft function below. 44 | def rotLeft(a, d): 45 | num_rots = d % len(a) 46 | return a[num_rots:] + a[0:num_rots] 47 | 48 | if __name__ == '__main__': 49 | fptr = open(os.environ['OUTPUT_PATH'], 'w') 50 | nd = input().split() 51 | n = int(nd[0]) 52 | d = int(nd[1]) 53 | a = list(map(int, input().rstrip().split())) 54 | result = rotLeft(a, d) 55 | print(result) 56 | fptr.write(' '.join(map(str, result))) 57 | fptr.write('\n') 58 | 59 | fptr.close() 60 | 61 | 62 | 63 | 64 | ## New Year Chaos 65 | import math 66 | import os 67 | import random 68 | import re 69 | import sys 70 | 71 | # Complete the minimumBribes function below. 72 | def minimumBribes(q): 73 | q_dict = {} 74 | q_sorted = sorted(q) 75 | count = 0 76 | while(q!=q_sorted): 77 | for i, val in enumerate(q): 78 | if(q_dict.get(q[i], 0)>2): 79 | return print('Too chaotic') 80 | if(iq[i+1]): 81 | q_dict.update({q[i]: q_dict.get(q[i], 0) + 1}) 82 | temp = q[i+1] 83 | q[i+1] = q[i] 84 | q[i] = temp 85 | count += 1 86 | print(count) 87 | 88 | if __name__ == '__main__': 89 | t = int(input()) 90 | for t_itr in range(t): 91 | n = int(input()) 92 | q = list(map(int, input().rstrip().split())) 93 | 94 | minimumBribes(q) 95 | 96 | 97 | 98 | 99 | ## Minimum Swaps 2 100 | import math 101 | import os 102 | import random 103 | import re 104 | import sys 105 | 106 | # Complete the minimumSwaps function below. 107 | def minimumSwaps(arr): 108 | # subtract 1 from each element in the array to match # Python's zero-indexing 109 | arr = [i-1 for i in arr] 110 | # store the positions of each element in the array 111 | # e.g. for arr = [1,2,0,3], positions = [2,0,1,3] 112 | positions = [0] * len(arr) 113 | for count,i in enumerate(arr): 114 | positions[i] = count 115 | 116 | swaps = 0 117 | for count,i in enumerate(arr): 118 | #if ordered, then i == count; if not, we have to swap 119 | if i != count: 120 | #find the position of the element that should be here 121 | pos = positions[count] 122 | #swap the current element arr[count] with the correct element arr[pos] 123 | arr[pos],arr[count] = arr[count],arr[pos] 124 | #update positions to match array after swapping 125 | current_value = arr[count] 126 | correct_value = arr[pos] 127 | positions[current_value],positions[correct_value] = positions[correct_value],positions[current_value] 128 | swaps += 1 129 | 130 | return swaps 131 | 132 | if __name__ == '__main__': 133 | fptr = open(os.environ['OUTPUT_PATH'], 'w') 134 | n = int(input()) 135 | arr = list(map(int, input().rstrip().split())) 136 | res = minimumSwaps(arr) 137 | fptr.write(str(res) + '\n') 138 | fptr.close() 139 | 140 | 141 | 142 | 143 | ## Array Manipulation 144 | import math 145 | import os 146 | import random 147 | import re 148 | import sys 149 | 150 | # Complete the arrayManipulation function below. 151 | def arrayManipulation(n, queries): 152 | pass 153 | 154 | if __name__ == '__main__': 155 | fptr = open(os.environ['OUTPUT_PATH'], 'w') 156 | nm = input().split() 157 | n = int(nm[0]) 158 | m = int(nm[1]) 159 | queries = [] 160 | lis = [0]*(n+1) 161 | 162 | for _ in range(m): 163 | x, y, incr = [int(n) for n in input().split(' ')] 164 | lis[x-1] += incr 165 | if((y)<=len(lis)): 166 | lis[y] -= incr 167 | 168 | max = x = 0 169 | for i in lis: 170 | x=x+i; 171 | if(max stuart_score: 191 | print("Kevin", kevin_score) 192 | elif kevin_score < stuart_score: 193 | print("Stuart", stuart_score) 194 | else: 195 | print("Draw") 196 | 197 | if __name__ == '__main__': 198 | s = input() 199 | minion_game(s) 200 | 201 | 202 | ## Merge the Tools! 203 | def merge_the_tools(string, k): 204 | k = int(k) 205 | for i in range(0, len(string), k): 206 | sub_text = string[i:i+k] 207 | unique = '' 208 | for char in sub_text: 209 | if char not in unique: 210 | unique += char 211 | print(unique) 212 | 213 | if __name__ == '__main__': 214 | string, k = input(), int(input()) 215 | merge_the_tools(string, k) 216 | 217 | 218 | ## end ## 219 | 220 | 221 | 222 | -------------------------------------------------------------------------------- /ProblemSolving01_Warmup: -------------------------------------------------------------------------------- 1 | ## Problem Solving 2 | ## Warmup 3 | 4 | 5 | 6 | 7 | ## Solve Me First 8 | def solveMeFirst(a,b): 9 | # Hint: Type return a+b below 10 | return a+b 11 | 12 | num1 = int(input()) 13 | num2 = int(input()) 14 | res = solveMeFirst(num1,num2) 15 | print(res) 16 | 17 | 18 | 19 | 20 | ## Simple Array Sum 21 | #!/bin/python3 22 | import os 23 | import sys 24 | 25 | # 26 | # Complete the simpleArraySum function below. 27 | # 28 | def simpleArraySum(ar): 29 | # 30 | # Write your code here. 31 | # 32 | total = sum(ar) 33 | return total 34 | 35 | if __name__ == '__main__': 36 | fptr = open(os.environ['OUTPUT_PATH'], 'w') 37 | ar_count = int(input()) 38 | ar = list(map(int, input().rstrip().split())) 39 | result = simpleArraySum(ar) 40 | fptr.write(str(result) + '\n') 41 | fptr.close() 42 | 43 | 44 | 45 | 46 | ## Compare the Triplets 47 | #!/bin/python3 48 | import math 49 | import os 50 | import random 51 | import re 52 | import sys 53 | 54 | # Complete the compareTriplets function below. 55 | def compareTriplets(a, b): 56 | result_a, result_b = [], [] 57 | for i in range(3): 58 | if a[i] > b[i]: 59 | result_a.append(1) 60 | elif a[i] < b[i]: 61 | result_b.append(1) 62 | return [sum(result_a), sum(result_b)] 63 | 64 | if __name__ == '__main__': 65 | fptr = open(os.environ['OUTPUT_PATH'], 'w') 66 | a = list(map(int, input().rstrip().split())) 67 | b = list(map(int, input().rstrip().split())) 68 | result = compareTriplets(a, b) 69 | fptr.write(' '.join(map(str, result))) 70 | fptr.write('\n') 71 | fptr.close() 72 | 73 | 74 | 75 | 76 | ## A Very Big Sum 77 | #!/bin/python3 78 | import math 79 | import os 80 | import random 81 | import re 82 | import sys 83 | 84 | # Complete the aVeryBigSum function below. 85 | def aVeryBigSum(ar): 86 | return sum(ar) 87 | 88 | if __name__ == '__main__': 89 | fptr = open(os.environ['OUTPUT_PATH'], 'w') 90 | ar_count = int(input()) 91 | ar = list(map(int, input().rstrip().split())) 92 | result = aVeryBigSum(ar) 93 | fptr.write(str(result) + '\n') 94 | fptr.close() 95 | 96 | 97 | 98 | 99 | ## Diagonal Difference 100 | #!/bin/python3 101 | import math 102 | import os 103 | import random 104 | import re 105 | import sys 106 | 107 | # 108 | # Complete the 'diagonalDifference' function below. 109 | # 110 | # The function is expected to return an INTEGER. 111 | # The function accepts 2D_INTEGER_ARRAY arr as parameter. 112 | # 113 | def diagonalDifference(arr): 114 | diag1, diag2 = [], [] 115 | n = len(arr) 116 | for i in range(n): 117 | diag1.append(arr[i][i]) 118 | diag2.append(arr[i][n-1-i]) 119 | return abs(sum(diag1)-sum(diag2)) 120 | 121 | if __name__ == '__main__': 122 | fptr = open(os.environ['OUTPUT_PATH'], 'w') 123 | n = int(input().strip()) 124 | arr = [] 125 | for _ in range(n): 126 | arr.append(list(map(int, input().rstrip().split()))) 127 | result = diagonalDifference(arr) 128 | fptr.write(str(result) + '\n') 129 | fptr.close() 130 | 131 | 132 | 133 | 134 | ## Plus Minus 135 | #!/bin/python3 136 | import math 137 | import os 138 | import random 139 | import re 140 | import sys 141 | 142 | # Complete the plusMinus function below. 143 | def plusMinus(arr): 144 | size = len(arr) 145 | count_pos, count_neg, count_zero = 0, 0, 0 146 | for i in range(size): 147 | if arr[i] > 0: 148 | count_pos += 1 149 | elif arr[i] < 0: 150 | count_neg += 1 151 | else: 152 | count_zero += 1 153 | print('{:.6f}'.format(count_pos/size)) 154 | print('{:.6f}'.format(count_neg/size)) 155 | print('{:.6f}'.format(count_zero/size)) 156 | return 157 | 158 | if __name__ == '__main__': 159 | n = int(input()) 160 | arr = list(map(int, input().rstrip().split())) 161 | plusMinus(arr) 162 | 163 | 164 | 165 | 166 | ## Staircase 167 | #!/bin/python3 168 | import math 169 | import os 170 | import random 171 | import re 172 | import sys 173 | 174 | # Complete the staircase function below. 175 | def staircase(n): 176 | for m in range(n): 177 | print((n - m - 1) * ' ' + (m + 1) * '#') 178 | 179 | if __name__ == '__main__': 180 | n = int(input()) 181 | staircase(n) 182 | 183 | 184 | 185 | 186 | ## Mini-Max Sum 187 | #!/bin/python3 188 | import math 189 | import os 190 | import random 191 | import re 192 | import sys 193 | 194 | # Complete the miniMaxSum function below. 195 | def miniMaxSum(arr): 196 | arr = sorted(arr) 197 | min_int = arr[0] 198 | max_int = arr[-1] 199 | arr.pop(0) 200 | arr.pop(-1) 201 | print(min_int+sum(arr), max_int+sum(arr)) 202 | 203 | if __name__ == '__main__': 204 | arr = list(map(int, input().rstrip().split())) 205 | miniMaxSum(arr) 206 | 207 | 208 | 209 | 210 | ## Birthday Cake Candles 211 | #!/bin/python3 212 | import math 213 | import os 214 | import random 215 | import re 216 | import sys 217 | 218 | # Complete the birthdayCakeCandles function below. 219 | def birthdayCakeCandles(ar): 220 | max_int = max(ar) 221 | return ar.count(max_int) 222 | 223 | if __name__ == '__main__': 224 | fptr = open(os.environ['OUTPUT_PATH'], 'w') 225 | ar_count = int(input()) 226 | ar = list(map(int, input().rstrip().split())) 227 | result = birthdayCakeCandles(ar) 228 | fptr.write(str(result) + '\n') 229 | fptr.close() 230 | 231 | 232 | 233 | 234 | ## Time Conversion 235 | #!/bin/python3 236 | import os 237 | import sys 238 | 239 | # 240 | # Complete the timeConversion function below. 241 | # 242 | def timeConversion(s): 243 | # 244 | # Write your code here. 245 | if int(s[0:2])==12 and s[-2:]=='AM': 246 | return ( '00' + s[2:8] ) 247 | elif s[-2:]=='PM' and int(s[0:2]) < 12: 248 | return ( str(int(s[0:2])+12) + s[2:8]) 249 | else: 250 | return ( s[:-2] ) 251 | 252 | if __name__ == '__main__': 253 | f = open(os.environ['OUTPUT_PATH'], 'w') 254 | s = input() 255 | result = timeConversion(s) 256 | f.write(result + '\n') 257 | f.close() 258 | 259 | 260 | 261 | 262 | ## end ## 263 | -------------------------------------------------------------------------------- /Ruby03_Arrays_&_Hashes: -------------------------------------------------------------------------------- 1 | ## Ruby 2 | ## Control Structures 3 | 4 | 5 | ## Ruby Array - Initialization 6 | • Initialize an empty array with the variable name array 7 | Hint 8 | array = Array.new 9 | or 10 | array = [] 11 | • Initialize an array with exactly one nil element in it with the variable name array_1 12 | Hint 13 | array_1 = Array.new(1) 14 | or 15 | array_1 = [nil] 16 | • Initialize an array with exactly two elements with value 10 in it using the variable name array_2. 17 | Hint 18 | array_2 = Array.new(2, 10) 19 | or 20 | array_2 = [10, 10] 21 | 22 | # Initialize 3 variables here as explained in the problem statement 23 | array = [] 24 | array_1 = [nil] 25 | array_2 = [10,10] 26 | 27 | 28 | 29 | 30 | ## Ruby Array - Index, Part 1 31 | # The positions are 0 indexed. 32 | 33 | arr = [9, 5, 1, 2, 3, 4, 0, -1] 34 | • A number which is the position of element 35 | >>arr[4] 36 | => 3 37 | or 38 | >>arr.at(4) 39 | => 3 40 | • A range indicating the start and the end position 41 | >>arr[1..3] # .. indicates both indices are inclusive. 42 | => [5,1,2] 43 | >>arr[1...3] # ... indicates the last index is excluded. 44 | => [5,1] 45 | • Start index and the length of the range 46 | >>arr[1,4] 47 | => [5, 1, 2, 3] 48 | 49 | def element_at(arr, index) 50 | # return the element of the Array variable `arr` at the position `index` 51 | # arr.at(index) # or 52 | # arr[index] 53 | return arr[index] 54 | end 55 | 56 | def inclusive_range(arr, start_pos, end_pos) 57 | # return the elements of the Array variable `arr` between the start_pos and end_pos (both inclusive) 58 | return arr[start_pos..end_pos] 59 | end 60 | 61 | def non_inclusive_range(arr, start_pos, end_pos) 62 | # return the elements of the Array variable `arr`, start_pos inclusive and end_pos exclusive 63 | return arr[start_pos...end_pos] 64 | end 65 | 66 | def start_and_length(arr, start_pos, length) 67 | # return `length` elements of the Array variable `arr` starting from `start_pos` 68 | return arr[start_pos, length] 69 | end 70 | 71 | 72 | 73 | 74 | ## Ruby Array - Index, Part 2 75 | For the array, 76 | arr = [9, 5, 1, 2, 3, 4, 0, -1] 77 | • To access the elements from the end of the list, we can use negative indices. 78 | > arr[-1] 79 | => -1 80 | • The first element of the array can be accessed using 81 | > arr.first 82 | => 9 83 | • The last element of the array can be accessed using 84 | > arr.last 85 | => -1 86 | • The first n elements of the array can be accessed using 87 | arr.take(3) 88 | => [9, 5, 1] 89 | • Everything but the first n elements of the array can be accessed using 90 | arr.drop(3) 91 | => [2, 3, 4, 0, -1] 92 | 93 | def neg_pos(arr, index) 94 | # return the element of the array at the position `index` from the end of the list 95 | arr[-index] 96 | end 97 | 98 | def first_element(arr) 99 | # return the first element of the array 100 | arr.first 101 | end 102 | 103 | def last_element(arr) 104 | # return the last element of the array 105 | arr.last 106 | end 107 | 108 | def first_n(arr, n) 109 | # return the first n elements of the array 110 | arr.take(n) 111 | end 112 | 113 | def drop_n(arr, n) 114 | # drop the first n elements of the array and return the rest 115 | arr.drop(n) 116 | end 117 | 118 | 119 | 120 | 121 | ## Ruby Array - Addition 122 | Arrays provide a variety of methods that allow to add elements to them. 123 | • push allows one to add an element to the end of the list. 124 | >x = [1,2] 125 | >x.push(3) 126 | => [1,2,3] 127 | • insert allows one to add one or more elements starting from a given index (shifting elements after the given index in the process). 128 | >x = [1,2] 129 | >x.insert(1, 5, 6, 7) 130 | => [1, 5, 6, 7, 2] 131 | • unshift allows one or more elements to be added at the beginning of the list. 132 | >x = [1,2,3] 133 | >x.unshift(10, 20, 30) 134 | => [10, 20, 30, 1, 2, 3] 135 | 136 | def end_arr_add(arr, element) 137 | # Add `element` to the end of the Array variable `arr` and return `arr` 138 | arr.push(element) 139 | end 140 | 141 | def begin_arr_add(arr, element) 142 | # Add `element` to the beginning of the Array variable `arr` and return `arr` 143 | arr.unshift(element) 144 | end 145 | 146 | def index_arr_add(arr, index, element) 147 | # Add `element` at position `index` to the Array variable `arr` and return `arr` 148 | arr.insert(index, element) 149 | end 150 | 151 | def index_arr_multiple_add(arr, index) 152 | # add any two elements to the arr at the index 153 | arr.insert(index, 8, 88) 154 | end 155 | 156 | 157 | 158 | 159 | ## Ruby Array - Deletion 160 | arr = [5, 6, 5, 4, 3, 1, 2, 5, 4, 3, 3, 3] 161 | • Delete an element from the end of the array 162 | > arr.pop 163 | => 3 164 | • Delete an element from the beginning of the array 165 | > arr.shift 166 | => 5 167 | • Delete an element at a given position 168 | > arr.delete_at(2) 169 | => 4 170 | • Delete all occurrences of a given element 171 | > arr.delete(5) 172 | => 5 173 | > arr 174 | => [6, 3, 1, 2, 4, 3, 3] 175 | 176 | def end_arr_delete(arr) 177 | # delete the element from the end of the array and return the deleted element 178 | arr.pop 179 | end 180 | 181 | def start_arr_delete(arr) 182 | # delete the element at the beginning of the array and return the deleted element 183 | arr.shift 184 | end 185 | 186 | def delete_at_arr(arr, index) 187 | # delete the element at the position #index 188 | arr.delete_at(index) 189 | end 190 | 191 | def delete_all(arr, val) 192 | # delete all the elements of the array where element = val 193 | arr.delete(val) 194 | end 195 | 196 | 197 | 198 | 199 | ## Ruby Array - Selection 200 | def select_arr(arr) 201 | # select and return all odd numbers from the Array variable `arr` 202 | return arr.select{|a| (a%2 != 0)} 203 | end 204 | 205 | def reject_arr(arr) 206 | # reject all elements which are divisible by 3 207 | return arr.delete_if{|a| (a%3 == 0)} 208 | end 209 | 210 | def delete_arr(arr) 211 | # delete all negative elements 212 | return arr.delete_if{|a| a < 0} 213 | end 214 | 215 | def keep_arr(arr) 216 | # keep all non negative elements ( >= 0) 217 | return arr.keep_if{|a| a >= 0} 218 | end 219 | 220 | 221 | 222 | 223 | 224 | 225 | 226 | 227 | 228 | 229 | 230 | 231 | 232 | 233 | 234 | 235 | 236 | 237 | (work in progress) 238 | 239 | ## end ## 240 | -------------------------------------------------------------------------------- /Interview06_Greedy_Algorithms: -------------------------------------------------------------------------------- 1 | ## Interview Preparation Kit 2 | ## Greedy Algorithms 3 | 4 | 5 | 6 | 7 | ## Minimum Absolute Difference in an Array 8 | #!/bin/python3 9 | import math 10 | import os 11 | import random 12 | import re 13 | import sys 14 | 15 | # Complete the minimumAbsoluteDifference function below. 16 | def minimumAbsoluteDifference(arr): 17 | arr = sorted(arr) 18 | min_values = [] 19 | for i in range(len(arr)-1): 20 | diff = arr[i+1] - arr[i] 21 | min_values.append(diff) 22 | return min(min_values) 23 | 24 | if __name__ == '__main__': 25 | fptr = open(os.environ['OUTPUT_PATH'], 'w') 26 | n = int(input()) 27 | arr = list(map(int, input().rstrip().split())) 28 | result = minimumAbsoluteDifference(arr) 29 | fptr.write(str(result) + '\n') 30 | fptr.close() 31 | 32 | 33 | 34 | 35 | ## Luck Balance 36 | #!/bin/python3 37 | import math 38 | import os 39 | import random 40 | import re 41 | import sys 42 | 43 | # Complete the luckBalance function below. 44 | # Option 1 45 | def luckBalance(k, contests): 46 | contests.sort(reverse=True) 47 | luck = 0 48 | for contest in contests: 49 | if contest[1] == 0: 50 | luck += contest[0] 51 | elif k > 0: 52 | luck += contest[0] 53 | k -= 1 54 | else: 55 | luck -= contest[0] 56 | return luck 57 | 58 | # Option 2 59 | def luckBalance(k, contests): 60 | contests.sort(reverse=True) 61 | luck = 0 62 | for pts, imp in contests: 63 | if k > 0 or not imp: 64 | luck += pts 65 | k -= imp 66 | else: 67 | luck -= pts 68 | return luck 69 | 70 | if __name__ == '__main__': 71 | fptr = open(os.environ['OUTPUT_PATH'], 'w') 72 | nk = input().split() 73 | n = int(nk[0]) 74 | k = int(nk[1]) 75 | contests = [] 76 | for _ in range(n): 77 | contests.append(list(map(int, input().rstrip().split()))) 78 | result = luckBalance(k, contests) 79 | fptr.write(str(result) + '\n') 80 | fptr.close() 81 | 82 | 83 | 84 | 85 | ## Greedy Florist 86 | """ 87 | We first sort the given list of prices of flowers. 88 | 89 | Consider a case where n = 10 flowers, and cost c = [1,2,3,4] and k = 4 friends. Then first we consider flower [1,2,3,4] for orignal price. Next we have to buy 4 more that is [1,2,3,4] at twice the price. Next we have to buy 2 more, for these we have to consider the lowest priced flower that is [1,2] for thrice the price. 90 | 91 | Now same logic we apply by repeating the array c by total_loop (how many time all the flowers can be considered). For example in the previous example we make c as [1,2,3,4,1,2,3,4]. Now the remaining two lowest priced flowers are added at the front of this array as, [1,2,1,2,3,4,1,2,3,4]. Once we have this array, we start with last k elements, sum them and then multiply them with the current purchase 'p'. 92 | """ 93 | #!/bin/python3 94 | import math 95 | import os 96 | import random 97 | import re 98 | import sys 99 | 100 | # Complete the getMinimumCost function below. 101 | def getMinimumCost(k, c): 102 | c.sort() 103 | l = len(c) 104 | total_loop = n//l # total number of complete loops 105 | last_elements = n%l # number of remaining flowers 106 | c = c[:last_elements] + c*total_loop # explained above 107 | p = 1 # count of purchases 108 | i = 1 109 | result = 0 110 | while (l - (i-1)*k >= 0): 111 | result += sum(c[max(l-i*k,0):l-(i-1)*k])*p 112 | i += 1 113 | p += 1 114 | return result 115 | 116 | if __name__ == '__main__': 117 | fptr = open(os.environ['OUTPUT_PATH'], 'w') 118 | nk = input().split() 119 | n = int(nk[0]) 120 | k = int(nk[1]) 121 | c = list(map(int, input().rstrip().split())) 122 | minimumCost = getMinimumCost(k, c) 123 | fptr.write(str(minimumCost) + '\n') 124 | fptr.close() 125 | 126 | 127 | 128 | 129 | # Max Min 130 | #!/bin/python3 131 | import math 132 | import os 133 | import random 134 | import re 135 | import sys 136 | 137 | # Complete the maxMin function below. 138 | def maxMin(k, arr): 139 | arr.sort() 140 | result = float('inf') # the number infinity 141 | for i in range(n-k+1): 142 | unfairness = arr[i+k-1] - arr[i] 143 | if unfairness < result: 144 | result = unfairness 145 | return result 146 | 147 | if __name__ == '__main__': 148 | fptr = open(os.environ['OUTPUT_PATH'], 'w') 149 | n = int(input()) 150 | k = int(input()) 151 | arr = [] 152 | for _ in range(n): 153 | arr_item = int(input()) 154 | arr.append(arr_item) 155 | result = maxMin(k, arr) 156 | fptr.write(str(result) + '\n') 157 | fptr.close() 158 | 159 | 160 | 161 | 162 | ## Reverse Shuffle Merge 163 | #!/bin/python3 164 | import math 165 | import os 166 | import random 167 | import re 168 | import sys 169 | 170 | # Complete the reverseShuffleMerge function below. 171 | # Option 1 172 | from collections import Counter 173 | def reverseShuffleMerge(s): 174 | left = Counter(s) 175 | keep = {char: int(freq / 2) for char, freq in left.items()} 176 | shuffle = {char: int(freq / 2) for char, freq in left.items()} 177 | result = [] 178 | for char in reversed(s): 179 | if keep[char] > 0: 180 | while result and result[-1] > char and shuffle[result[-1]] > 0: 181 | removed = result.pop() 182 | keep[removed] += 1 183 | shuffle[removed] -= 1 184 | result.append(char) 185 | keep[char] -= 1 186 | else: 187 | shuffle[char] -= 1 188 | return (''.join(result)) 189 | 190 | # Option 2 191 | from collections import Counter 192 | def reverseShuffleMerge(s): 193 | cnt = Counter(s) 194 | req = Counter({k:v // 2 for k,v in cnt.items()}) 195 | rs = s[::-1] 196 | ic = ord('a') 197 | imax = ord('z') + 1 198 | pos = -1 199 | ans = '' 200 | while ic < imax: 201 | c = chr(ic) 202 | if c not in list(+req): 203 | ic += 1 204 | continue 205 | i = rs.find(c,pos + 1) 206 | if len(+(req - Counter(rs[i:]))) > 0: 207 | #not enough characters behind, find bigger character 208 | ic += 1 209 | else: 210 | #there are enough characters behind 211 | ans += c 212 | pos = i #new position to find 213 | req[c] -= 1 #reduct request 214 | ic = ord('a') #find from a to z 215 | if len(+req) == 0: #find all 216 | return ans 217 | if ic >= imax: 218 | ic -= 26 219 | 220 | # Option 3 221 | def reverseShuffleMerge(s): 222 | cnt = {} 223 | for char in s: 224 | cnt[char] = cnt.get(char, 0)+1 225 | freq = {} 226 | used = {} 227 | for char, val in cnt.items(): 228 | used[char] = used.get(char, 0) 229 | freq[char] = freq.get(char, 0) + int(cnt[char]/2) 230 | A = [s[-1]] 231 | cnt[s[-1]] -= 1 232 | used[s[-1]] += 1 233 | for char in s[:-1][::-1]: 234 | cnt[char]-=1 235 | if used[char] >= freq[char]: 236 | continue 237 | while A and char < A[-1] and cnt[A[-1]]>freq[A[-1]]-used[A[-1]]: 238 | used[A.pop()]-=1 239 | A.append(char) 240 | used[char]+=1 241 | return ''.join(A) 242 | 243 | if __name__ == '__main__': 244 | fptr = open(os.environ['OUTPUT_PATH'], 'w') 245 | s = input() 246 | result = reverseShuffleMerge(s) 247 | fptr.write(result + '\n') 248 | fptr.close() 249 | 250 | 251 | 252 | 253 | ## end ## 254 | -------------------------------------------------------------------------------- /Interview03_Dictionaries_and_Hashmaps: -------------------------------------------------------------------------------- 1 | ## Interview Preparation Kit 2 | ## Dictionaries and Hashmaps 3 | 4 | 5 | 6 | 7 | ## Hash Tables: Ransom Note 8 | def checkMagazine(magazine, note): 9 | if len(magazine) < len(note): 10 | return print('No') 11 | 12 | # to build a dictionary for magazine 13 | magazine_dict = {} 14 | for word in magazine: 15 | if word in magazine_dict: 16 | magazine_dict[word] += 1 17 | else: 18 | magazine_dict[word] = 1 19 | 20 | # unable to build note if the word from note is not in magazine_dict 21 | # or if there are insufficient words in the magazine_dict 22 | for word in note: 23 | if word not in magazine_dict.keys() or magazine_dict[word] == 0 : 24 | return print('No') 25 | else: 26 | magazine_dict[word] -= 1 27 | print('Yes') 28 | 29 | if __name__ == '__main__': 30 | mn = input().split() 31 | m = int(mn[0]) 32 | n = int(mn[1]) 33 | magazine = input().rstrip().split() 34 | note = input().rstrip().split() 35 | 36 | checkMagazine(magazine, note) 37 | 38 | 39 | 40 | 41 | ## Two Strings 42 | #!/bin/python3 43 | import math 44 | import os 45 | import random 46 | import re 47 | import sys 48 | 49 | # Complete the twoStrings function below. 50 | # Option 1 51 | def twoStrings(s1, s2): 52 | return 'YES' if any([i in s2 for i in s1]) else 'NO' 53 | 54 | # Option 2 55 | def twoStrings(s1, s2): 56 | result = 'NO' 57 | a = set(list(s1)) 58 | b = set(list(s2)) 59 | c = a.intersection(b) 60 | if (len(c) != 0): 61 | result = 'YES' 62 | return result 63 | 64 | # Option 3 65 | def twoStrings(s1, s2): 66 | s1 = set(s1) 67 | s2 = set(s2) 68 | for ele in s1: 69 | if ele in s2: 70 | return 'YES' 71 | return 'NO' 72 | 73 | if __name__ == '__main__': 74 | fptr = open(os.environ['OUTPUT_PATH'], 'w') 75 | q = int(input()) 76 | for q_itr in range(q): 77 | s1 = input() 78 | s2 = input() 79 | result = twoStrings(s1, s2) 80 | fptr.write(result + '\n') 81 | fptr.close() 82 | 83 | 84 | 85 | 86 | ## Sherlock and Anagrams 87 | #!/bin/python3 88 | import math 89 | import os 90 | import random 91 | import re 92 | import sys 93 | 94 | # Complete the sherlockAndAnagrams function below. 95 | # Option 1 96 | from collections import Counter 97 | def sherlockAndAnagrams(s): 98 | anagrams = 0 99 | for i in range(1, len(s)): 100 | substrings = [] 101 | for l in range(len(s)+1-i): 102 | substrings.append(s[l:l+i]) 103 | letters_in_sub = list(map(lambda x: Counter(x), substrings)) 104 | for ele in letters_in_sub: 105 | if letters_in_sub.count(ele)>1: 106 | anagrams += (letters_in_sub.count(ele)-1)/2 107 | return int(anagrams) 108 | 109 | # Option 2 110 | def sherlockAndAnagrams(s): 111 | dic = {} 112 | anagrams = 0 113 | for k in range(1, len(s)): 114 | for i in range(len(s)-k+1): 115 | j = i+k 116 | strr = ''.join(sorted(s[i:j])) 117 | dic[strr] = dic.get(strr,0)+1 118 | for v in dic.values(): 119 | if v>1: 120 | anagrams += (v*(v-1))//2 121 | return anagrams 122 | 123 | # Option 3 124 | def sherlockAndAnagrams(s): 125 | anagrams = 0 126 | sub_str_dict = {} 127 | for pos, char in enumerate(s): 128 | for idx in range(pos + 1, len(s) + 1): 129 | ordered_sub_str = ''.join(sorted(s[pos:idx])) 130 | if ordered_sub_str in sub_str_dict: 131 | anagrams += sub_str_dict[ordered_sub_str] 132 | sub_str_dict[ordered_sub_str] += 1 133 | else: 134 | sub_str_dict[ordered_sub_str] = 1 135 | return anagrams 136 | 137 | if __name__ == '__main__': 138 | fptr = open(os.environ['OUTPUT_PATH'], 'w') 139 | q = int(input()) 140 | for q_itr in range(q): 141 | s = input() 142 | result = sherlockAndAnagrams(s) 143 | fptr.write(str(result) + '\n') 144 | fptr.close() 145 | 146 | 147 | 148 | 149 | ## Count Triplets 150 | #!/bin/python3 151 | import math 152 | import os 153 | import random 154 | import re 155 | import sys 156 | 157 | # Complete the countTriplets function below. 158 | # Option 1 159 | from collections import defaultdict 160 | def countTriplets(arr, r): #(array, ratio) 161 | c = 0 #count 162 | triplets = defaultdict(lambda: defaultdict(lambda: 0)) 163 | for num in arr: 164 | if num in triplets: 165 | c += triplets[num][2] 166 | triplets[num*r][2] += triplets[num][1] 167 | triplets[num*r][1] += 1 168 | return c 169 | 170 | # Option 2 171 | from collections import Counter 172 | def countTriplets(arr, r): 173 | second = Counter() 174 | third = Counter() 175 | c = 0 #count 176 | for num in arr: 177 | if num in third: 178 | c += third[num] 179 | if num in second: 180 | third[num*r] += second[num] 181 | second[num*r] += 1 182 | return c 183 | 184 | # Option 3 185 | from collections import defaultdict 186 | def countTriplets(arr, r): 187 | second = defaultdict(int) 188 | third = defaultdict(int) 189 | c = 0 #count 190 | for num in arr: 191 | c += third[num] 192 | third[num*r] += second[num] 193 | second[num*r] += 1 194 | return c 195 | 196 | if __name__ == '__main__': 197 | fptr = open(os.environ['OUTPUT_PATH'], 'w') 198 | nr = input().rstrip().split() 199 | n = int(nr[0]) 200 | r = int(nr[1]) 201 | arr = list(map(int, input().rstrip().split())) 202 | ans = countTriplets(arr, r) 203 | fptr.write(str(ans) + '\n') 204 | fptr.close() 205 | 206 | 207 | 208 | 209 | ## Frequency Queries 210 | #!/bin/python3 211 | import math 212 | import os 213 | import random 214 | import re 215 | import sys 216 | 217 | # Complete the freqQuery function below. 218 | # Option 1 219 | from collections import Counter 220 | def freqQuery(queries): 221 | result=[] 222 | n = len(queries) 223 | f = Counter() 224 | ff = Counter() 225 | for i in range(n): 226 | o,e = queries[i] 227 | if o==1: 228 | ff[f[e]]-=1 229 | f[e]+=1 230 | ff[f[e]]+=1 231 | elif o==2: 232 | ff[f[e]]-=1 233 | f[e]-=1 234 | ff[f[e]]+=1 235 | if f[e]<=0: 236 | del f[e] 237 | else: 238 | if ff[e]>0: 239 | result.append(1) 240 | else: 241 | result.append(0) 242 | return result 243 | 244 | # Option 2 245 | def freqQuery(queries): 246 | result=[] 247 | n = len(queries) 248 | f = {} 249 | ff = {} 250 | for i in range(n): 251 | o, e = queries[i] 252 | if (o==1): 253 | if e not in f: 254 | f[e]=0 255 | ff[f[e]]=ff.setdefault(f[e],0)-1 256 | f[e]=f.setdefault(e,0)+1 257 | ff[f[e]]=ff.setdefault(f[e],0)+1 258 | elif (o==2): 259 | if e in f: 260 | ff[f[e]]=ff.setdefault(f[e],0)-1 261 | f[e]=f.setdefault(e,0)-1 262 | ff[f[e]]=ff.setdefault(f[e],0)+1 263 | if f[e]<=0: 264 | del f[e] 265 | else: 266 | if e in ff: 267 | if ff[e]: 268 | result.append(1) 269 | else: 270 | result.append(0) 271 | else: 272 | result.append(0) 273 | return result 274 | 275 | if __name__ == '__main__': 276 | fptr = open(os.environ['OUTPUT_PATH'], 'w') 277 | q = int(input().strip()) 278 | queries = [] 279 | for _ in range(q): 280 | queries.append(list(map(int, input().rstrip().split()))) 281 | ans = freqQuery(queries) 282 | fptr.write('\n'.join(map(str, ans))) 283 | fptr.write('\n') 284 | fptr.close() 285 | 286 | 287 | 288 | 289 | ## end ## 290 | -------------------------------------------------------------------------------- /Interview04_Sorting: -------------------------------------------------------------------------------- 1 | ## Interview Preparation Kit 2 | ## Sorting 3 | 4 | 5 | 6 | 7 | ## Sorting: Bubble Sort 8 | #!/bin/python3 9 | import math 10 | import os 11 | import random 12 | import re 13 | import sys 14 | 15 | # Complete the countSwaps function below. 16 | # Option 1 17 | def countSwaps(a): 18 | num_swap = 0 19 | while a != sorted(a): 20 | for i in range(n-1): 21 | tmp = 0 22 | if a[i] > a[i+1]: 23 | tmp = a[i] 24 | a[i] = a[i+1] 25 | a[i+1] = tmp 26 | num_swap += 1 27 | print('Array is sorted in {} swaps.'.format(num_swap)) 28 | print('First Element:', a[0]) 29 | print('Last Element:', a[-1]) 30 | 31 | # Option 2 32 | def countSwaps(a): 33 | num_swap = 0 34 | while a != sorted(a): 35 | for i in range(len(a) - 1): 36 | tmp = 0 37 | if a[i] > a[i+1]: 38 | a[i], a[i+1] = a[i+1], a[i] 39 | num_swap += 1 40 | print('Array is sorted in {} swaps.'.format(num_swap)) 41 | print('First Element:', a[0]) 42 | print('Last Element:', a[-1]) 43 | 44 | if __name__ == '__main__': 45 | n = int(input()) 46 | a = list(map(int, input().rstrip().split())) 47 | countSwaps(a) 48 | 49 | 50 | 51 | 52 | ## Mark and Toys 53 | #!/bin/python3 54 | import math 55 | import os 56 | import random 57 | import re 58 | import sys 59 | 60 | # Complete the maximumToys function below. 61 | # Option 1 62 | def maximumToys(prices, k): 63 | c = 0 # count 64 | total = 0 # cumulative prices 65 | prices.sort() 66 | while total <= k: 67 | total += prices[c] 68 | c += 1 69 | return c-1 # remove the last item that burst the budget 70 | 71 | # Option 2 72 | def maximumToys(prices, k): 73 | c = 0 # count 74 | prices = sorted(prices) 75 | for price in prices: 76 | k -= price 77 | if k <= 0: 78 | break 79 | c += 1 80 | return c 81 | 82 | if __name__ == '__main__': 83 | fptr = open(os.environ['OUTPUT_PATH'], 'w') 84 | nk = input().split() 85 | n = int(nk[0]) 86 | k = int(nk[1]) 87 | prices = list(map(int, input().rstrip().split())) 88 | result = maximumToys(prices, k) 89 | fptr.write(str(result) + '\n') 90 | fptr.close() 91 | 92 | 93 | 94 | 95 | ## Sorting: Comparator 96 | from functools import cmp_to_key 97 | class Player: 98 | def __init__(self, name, score): 99 | self.name = name 100 | self.score = score 101 | 102 | def __repr__(self): 103 | self.self = self 104 | 105 | def comparator(a, b): 106 | if a.score==b.score: 107 | if a.nameb.score: 110 | return -1 111 | return 1 112 | 113 | # def comparator(a, b): # one-liner alternative 114 | # return (-1 if a.name= d : 153 | break 154 | if d%2 == 1 or 2*s > d : 155 | return 2*x 156 | return x + next( y for y in range(x+1,MAX+1) if c[y] ) 157 | 158 | for i in range(d,len(expenditure)): 159 | if expenditure[i] >= median2() : 160 | alert += 1 161 | c[expenditure[i-d]] -= 1 162 | c[expenditure[i]] += 1 163 | return alert 164 | 165 | # Option 2 166 | import bisect 167 | def activityNotifications(expenditure, d): 168 | result = 0 169 | if(d >= len(expenditure)): 170 | return result 171 | r = (d % 2) -1 172 | m = d // 2 173 | l = len(expenditure) 174 | a = [] 175 | for x in expenditure[:d]: 176 | bisect.insort_left(a, x) 177 | for x in range(d,l): 178 | mn = (a[m] + a[m+r])/2 179 | if(expenditure[x] >= mn*2): 180 | result+=1 181 | a.pop(bisect.bisect_left(a,expenditure[x-d])) 182 | bisect.insort(a,expenditure[x]) 183 | return result 184 | 185 | # Option 3 186 | def activityNotifications(expenditure, d): 187 | count=[0]*201 188 | ans=0 189 | if d>=n: 190 | return 0 191 | for i in range(d): 192 | count[expenditure[i]]+=1 193 | x=0 194 | if d%2==0: 195 | for j in range(d,n): 196 | a=0 197 | flag=0 198 | for k in range(201): 199 | a+=count[k] 200 | if a>=(d//2) and flag==0: 201 | first=k 202 | flag=1 203 | if a>=((d//2)+1): 204 | second=k 205 | break 206 | mean=(first+second)/2 207 | if expenditure[j]>=(2*mean): 208 | ans+=1 209 | count[expenditure[x]]-=1 210 | count[expenditure[j]]+=1 211 | x+=1 212 | else: 213 | for j in range(d,n): 214 | a=0 215 | for k in range(201): 216 | a+=count[k] 217 | if a>=((d//2)+1): 218 | second=k 219 | break 220 | mean=second 221 | if expenditure[j]>=(2*mean): 222 | ans+=1 223 | count[expenditure[x]]-=1 224 | count[expenditure[j]]+=1 225 | x+=1 226 | return ans 227 | 228 | if __name__ == '__main__': 229 | fptr = open(os.environ['OUTPUT_PATH'], 'w') 230 | nd = input().split() 231 | n = int(nd[0]) 232 | d = int(nd[1]) 233 | expenditure = list(map(int, input().rstrip().split())) 234 | result = activityNotifications(expenditure, d) 235 | fptr.write(str(result) + '\n') 236 | fptr.close() 237 | 238 | 239 | 240 | 241 | ## Merge Sort: Counting Inversions 242 | #!/bin/python3 243 | import math 244 | import os 245 | import random 246 | import re 247 | import sys 248 | 249 | # Complete the countInversions function below. 250 | def countInversions(arr): 251 | return merge_sort(arr) 252 | 253 | 254 | def merge(arr, left_half, right_half): 255 | i, j, k = 0, 0, 0 256 | inversions = 0 257 | left_len, right_len = len(left_half), len(right_half) 258 | while i < left_len and j < right_len: 259 | if left_half[i] <= right_half[j]: 260 | arr[k] = left_half[i] 261 | i += 1 262 | else: 263 | arr[k] = right_half[j] 264 | j += 1 265 | inversions += left_len - i 266 | k += 1 267 | 268 | while i < left_len: 269 | arr[k] = left_half[i] 270 | i, k = i+1, k+1 271 | 272 | while j < right_len: 273 | arr[k] = right_half[j] 274 | j, k = j+1, k+1 275 | 276 | return inversions 277 | 278 | 279 | def merge_sort(arr): 280 | if len(arr) > 1: 281 | mid = len(arr)//2 282 | left_half, right_half = arr[:mid], arr[mid:] 283 | 284 | inversions = merge_sort(left_half) + merge_sort(right_half) + merge(arr, left_half, right_half) 285 | return inversions 286 | return 0 287 | 288 | 289 | if __name__ == '__main__': 290 | fptr = open(os.environ['OUTPUT_PATH'], 'w') 291 | t = int(input()) 292 | for t_itr in range(t): 293 | n = int(input()) 294 | arr = list(map(int, input().rstrip().split())) 295 | result = countInversions(arr) 296 | fptr.write(str(result) + '\n') 297 | fptr.close() 298 | 299 | 300 | 301 | 302 | ## end ## 303 | -------------------------------------------------------------------------------- /Python15_Numpy: -------------------------------------------------------------------------------- 1 | ## Python 2 | ## Numpy 3 | 4 | 5 | ## Arrays 6 | import numpy 7 | 8 | # # Option 1: 9 | # def arrays(arr): 10 | # return(numpy.array(arr[::-1], float)) 11 | 12 | # Option 2: 13 | def arrays(arr): 14 | arr.reverse() 15 | arr_new = numpy.array(arr, float) 16 | return arr_new 17 | 18 | arr = input().strip().split(' ') 19 | result = arrays(arr) 20 | print(result) 21 | 22 | 23 | ## Shape and Reshape 24 | # # Option 1 25 | # import numpy as np 26 | # print(np.array(input().split(),int).reshape(3,3)) 27 | 28 | # # Option 2 29 | # import numpy as np 30 | # arr = np.array(list(map(int, input().split()))) 31 | # arr.shape = (3,3) 32 | # print(arr) 33 | 34 | # Option 3 35 | import numpy as np 36 | arr = np.array(list(map(int, input().split()))) 37 | arr = np.array(arr).reshape(3,3) 38 | print(arr) 39 | 40 | 41 | ## Transpose and Flatten 42 | # # Option 1 43 | # import numpy as np 44 | # row, col = map(int, input().split()) 45 | # arr = np.array([input().split() for _ in range(row)], int) 46 | # print (arr.transpose()) 47 | # print (arr.flatten()) 48 | 49 | # Option 2 50 | import numpy as np 51 | row, col = map(int, input().split()) 52 | arr = [] 53 | for _ in range(row): 54 | inp = [input().split()] 55 | arr.extend(inp) 56 | arr = np.array(arr, int) 57 | print (arr.transpose()) 58 | print (arr.flatten()) 59 | 60 | 61 | ## Concatenate 62 | # Option 1 63 | import numpy as np 64 | n, m, p = map(int,input().split()) 65 | arr1 = np.array([input().split() for _ in range(n)], int) 66 | arr2 = np.array([input().split() for _ in range(m)], int) 67 | print(np.concatenate( (arr1, arr2), axis=0) ) 68 | 69 | # # Option 2 70 | # import numpy as np 71 | # n, m, p = map(int, input().split()) 72 | # arr = np.array([input().split() for _ in range(n+m)], int) 73 | # print(arr) 74 | 75 | 76 | ## Zeros and Ones 77 | import numpy as np 78 | nums = tuple(map(int, input().split())) 79 | print (np.zeros(nums, dtype = np.int)) 80 | print (np.ones(nums, dtype = np.int)) 81 | 82 | 83 | ## Eye and Identity 84 | # # Option 1 85 | # import numpy as np 86 | # print(str(np.eye(*map(int,input().split()))).replace('1',' 1').replace('0',' 0')) 87 | """ 88 | use replace() function because there's a bug with the test cases, e.g. an error on the part of the problem creator, where there's too much whitespace in the expected output; in expected output every element is shifted one unit right 89 | """ 90 | 91 | # # Option 2 92 | # import numpy as np 93 | # np.set_printoptions(legacy='1.13') 94 | # print(np.eye(*map(int,input().split()))) 95 | 96 | # Option 3 97 | import numpy as np 98 | np.set_printoptions(legacy='1.13') 99 | n, m = map(int,input().split()) 100 | print(np.eye(n,m)) 101 | 102 | 103 | ## Array Mathematics 104 | # # Option 1 105 | # import numpy as np 106 | # n,m = map(int, input().split()) 107 | # a,b = (np.array([input().split() for _ in range(n)], dtype=int) for _ in range(2)) 108 | # print(a+b, a-b, a*b, a//b, a%b, a**b, sep='\n') 109 | 110 | # Option 2 111 | import numpy as np 112 | n,m = map(int,input().split()) 113 | a = np.array([input().split() for _ in range(n)], dtype=int) 114 | b = np.array([input().split() for _ in range(n)], dtype=int) 115 | print(a+b) 116 | print(a-b) 117 | print(a*b) 118 | print(a//b) 119 | print(a%b) 120 | print(a**b) 121 | 122 | # # Option 3 123 | # import numpy as np 124 | # n,m = map(int,input().split()) 125 | # lst1=[] 126 | # lst2=[] 127 | # for _ in range(n): 128 | # lst=list(map(int, input().split())) 129 | # lst1.append(lst) 130 | # a = np.array(lst1) 131 | # for _ in range(n): 132 | # lst=list(map(int, input().split())) 133 | # lst2.append(lst) 134 | # b = np.array(lst2) 135 | # print(np.add(a,b)) 136 | # print(np.subtract(a, b)) 137 | # print(np.multiply(a, b)) 138 | # print(np.floor_divide(a, b)) 139 | # print(np.mod(a, b)) 140 | # print(np.power(a, b)) 141 | 142 | 143 | ## Floor, Ceil and Rint 144 | import numpy as np 145 | np.set_printoptions(sign=' ') # output offset with a space 146 | arr = np.array(input().split(), float) 147 | print(np.floor(arr)) 148 | print(np.ceil(arr)) 149 | print(np.rint(arr)) 150 | 151 | 152 | ## Sum and Prod 153 | # Option 1 154 | import numpy as np 155 | N, M = map(int, input().split()) 156 | arr = np.array([input().split() for _ in range(N)], int) 157 | total = np.sum(arr, axis=0) 158 | print(np.prod(total, axis=0)) 159 | 160 | # # Option 2 161 | # import numpy as np 162 | # N, M = map(int, input().split()) 163 | # lis = [np.array(input().split(), int) for _ in range(N)] 164 | # print(np.prod(np.sum(lis, axis = 0))) 165 | 166 | """ 167 | range(N): [0, 1, 2, .... N-1] 168 | for x in range(N): loop x = 0, x = 1, ..., x = N-1 169 | for _ in range(N): loop N times 170 | input().split(): Split input by spaces and prepare list (fr ex 1 2 3 becomes ['1', '2', '3']) 171 | input().split() for _ in range(N): Read n lines and prepare n lists 172 | [input().split() for _ in range(N)]: Prepare a list from n lines input containing N times where each item itself is list of strings 173 | numpy.array([input().split() for _ in range(N)],int): Prepare 2d array from n lines of input with each item of type int 174 | A = numpy.array([input().split() for _ in range(N)],int): Assign the result to A 175 | """ 176 | 177 | 178 | ## Min and Max 179 | # # Option 1 180 | # import numpy as np 181 | # print(np.max(np.min(np.array([input().split() for _ in range(int(input().split()[0]))],int),axis=1))) 182 | 183 | # Option 2 184 | import numpy as np 185 | # n, m = map(int, input().split()) 186 | n = int(input().split()[0]) 187 | arr = np.array([input().split() for _ in range(n)], int) 188 | print(np.max(np.min(arr, axis=1))) 189 | 190 | 191 | ## Mean, Var, and Std 192 | import numpy as np 193 | np.set_printoptions(legacy='1.13') 194 | # n,m = map(int, input().split()) 195 | n = int(input().split()[0]) 196 | arr = np.array([input().split() for _ in range(n)], int) 197 | print(np.mean(arr, axis=1)) 198 | print(np.var(arr, axis=0)) 199 | print(np.std(arr, axis=None)) 200 | 201 | 202 | ## Dot and Cross 203 | # Option 1 204 | import numpy as np 205 | n = int(input()) 206 | A=np.array([list(map(int,input().split())) for _ in range(n)]) 207 | B=np.array([list(map(int,input().split())) for _ in range(n)]) 208 | print( np.dot(A,B) ) 209 | 210 | # # Option 2 211 | # import numpy as np 212 | # n = int(input()) 213 | # A,B = [np.array([input().split() for _ in range(n)], int) for _ in range(2)] 214 | # print(np.dot(A,B)) 215 | 216 | 217 | ## Inner and Outer 218 | # # Option 1 219 | # import numpy as np 220 | # A,B = [np.array([input().split()],int) for _ in range(2)] 221 | # print(np.inner(A,B)[0][0], np.outer(A,B), sep='\n') 222 | 223 | # # Option 2 224 | # import numpy as np 225 | # A,B = [np.array(input().split(), int) for _ in range(2)] 226 | # print(np.inner(A,B), np.outer(A,B), sep='\n') 227 | 228 | # Option 3 229 | import numpy as np 230 | A=np.array(input().split(),int) 231 | B=np.array(input().split(),int) 232 | print(np.inner(A,B)) 233 | print(np.outer(A,B)) 234 | 235 | 236 | ## Polynomials 237 | """ 238 | You are given the coefficients of a polynomial Y = a x^n + b x^(n-1) + … + k. 239 | Your task is to find the value of Y at point x. 240 | """ 241 | # # Option 1 242 | # print(__import__('numpy').polyval(list(map(float,input().split())),float(input()))) 243 | 244 | # Option 2 245 | import numpy as np 246 | coeff = list(map(float,input().split())) 247 | x = int(input()) 248 | print( np.polyval(coeff,x) ) 249 | 250 | # # Option 3 251 | # import numpy as np 252 | # if __name__ == '__main__': 253 | # coefficients = np.array(list(map(float, input().split()))) 254 | # poly = np.poly1d(coefficients) 255 | # print(poly(int(input()))) 256 | 257 | 258 | ## Linear Algebra 259 | ## output needs to be rounded to 2 decimal points 260 | # # Option 1 261 | # import numpy as np 262 | # print(round(np.linalg.det(np.array([input().split() for _ in range(int(input()))],float)),2)) 263 | 264 | # Option 2 265 | import numpy as np 266 | n=int(input()) 267 | a=np.array([input().split() for _ in range(n)],float) 268 | np.set_printoptions(legacy='1.13') #version issues in this exercise 269 | print(np.linalg.det(a)) 270 | 271 | # # Option 3 272 | # import numpy as np # importing numpy package 273 | # n = int(input()) # nxn array. 274 | # a = [] # init array 275 | # for i in range(n): 276 | # c = list(map(float, input().split())) 277 | # a.append(c) 278 | # print(round(np.linalg.det(a),2)) # determinant round to 2 places 279 | 280 | 281 | ## end ## 282 | -------------------------------------------------------------------------------- /Python07_Collections: -------------------------------------------------------------------------------- 1 | ## Python 2 | ## Collections 3 | 4 | 5 | ## collections.Counter() 6 | # Enter your code here. Read input from STDIN. Print output to STDOUT 7 | 8 | # # Option with Counter 9 | # from collections import Counter 10 | # X = int(input()) 11 | # input_list = list(map(int, input().split())) 12 | # sizes_counter = Counter(input_list) 13 | # N = int(input()) 14 | # sales = 0 15 | # for _ in range(N): 16 | # size, price = map(int, input().split()) 17 | # if sizes_counter[size] > 0: 18 | # sales += price 19 | # sizes_counter[size] -= 1 20 | # print(sales) 21 | 22 | # Option without Counter 23 | X = int(input()) 24 | sizes_list = list(map(int, input().split())) 25 | N = int(input()) 26 | sales = 0 27 | for _ in range(N): 28 | size, price = map(int, input().split()) 29 | if size in sizes_list: 30 | sales += price 31 | sizes_list.remove(size) 32 | print(sales) 33 | 34 | 35 | ## DefaultDict Tutorial 36 | # Enter your code here. Read input from STDIN. Print output to STDOUT 37 | 38 | # # Option 1 39 | # from collections import defaultdict 40 | # n, m = map(int, input().split()) 41 | # A = defaultdict(list) 42 | # for i in range(n): 43 | # A[input()].append(i+1) 44 | # B = [input() for _ in range(m)] 45 | # [print(*A.get(letter, [-1])) for letter in B] 46 | 47 | # # Option 2 48 | # from collections import defaultdict 49 | # A = defaultdict(list) 50 | # B = [] 51 | # n, m = map(int, input().split()) 52 | # for i in range(n): 53 | # A[input()].append(i+1) 54 | # for _ in range(m): 55 | # B.append(input()) # or B += [input()] 56 | # for word in B: 57 | # if word in A: 58 | # print(' '.join( map(str, A[word]) )) 59 | # else: 60 | # print(-1) 61 | 62 | # Option 3 63 | from collections import defaultdict 64 | A = defaultdict(list) 65 | n, m = map(int, input().split()) 66 | for i in range(n): 67 | A[input()].append(i+1) 68 | for _ in range(m): 69 | word = input() 70 | if word in A: 71 | print(' '.join( map(str, A[word]) )) 72 | else: 73 | print(-1) 74 | 75 | # # Option 4 76 | # from collections import defaultdict 77 | # n, m = map(int, input().split()) 78 | # A = defaultdict(lambda: -1) 79 | # for i in range(1, n+1): 80 | # word = input() 81 | # A[word] = A[word] + ' ' + str(i) if word in A else str(i) 82 | # for _ in range(m): 83 | # print(A[input()]) 84 | 85 | 86 | ## Collections.namedtuple() 87 | # Enter your code here. Read input from STDIN. Print output to STDOUT 88 | 89 | # # Option 1 90 | # from collections import namedtuple 91 | # n = int(input()) 92 | # Report = namedtuple('Report', input()) 93 | # reports = [Report(*input().split()) for _ in range(n)] 94 | # print(sum([int(e.MARKS) for e in reports])/n) 95 | 96 | # # Option 2 97 | # from collections import namedtuple 98 | # n = int(input()) 99 | # categories = input().split() 100 | # Report = namedtuple('Report', categories) 101 | # marks = [int(Report._make(input().split()).MARKS) for x in range(n)] 102 | # print('{: 0.2F}'.format( sum(marks)/len(marks) )) 103 | 104 | # Option 3 105 | from collections import namedtuple 106 | n = int(input()) 107 | Report = namedtuple('Report', input().split()) 108 | total = 0 109 | for _ in range(n): 110 | total += int(Report(*input().split()).MARKS) 111 | print(total/n) 112 | 113 | # # Option 4 (1 line) 114 | # import collections, statistics 115 | # print('%.2f' % statistics.mean(next((int(student(*row).MARKS) for row in (input().split() for i in range(size))) for size, student in [[int(input()), collections.namedtuple('Report', input())]]))) 116 | 117 | 118 | ## Collections.OrderedDict() 119 | # Enter your code here. Read input from STDIN. Print output to STDOUT 120 | 121 | # # Option 1 122 | # from collections import OrderedDict 123 | # D = OrderedDict() 124 | # for _ in range(int(input())): 125 | # item, space, price = input().rpartition(' ') 126 | # D[item] = D.get(item, 0) + int(price) 127 | # for item, price in D.items(): 128 | # print(item, price) 129 | 130 | # # Option 2 131 | # from collections import OrderedDict 132 | # D = OrderedDict() 133 | # for _ in range(int(input())): 134 | # item, space, price = input().rpartition(' ') 135 | # D[item] = D.get(item, 0) + int(price) 136 | # print(*[' '.join([item, str(price)]) for item, price in D.items()], sep='\n') 137 | 138 | # Option 3 (latest python dictionary is default ordered) 139 | store_item = dict() 140 | for _ in range(int(input())): 141 | key, _, value = input().rpartition(" ") 142 | store_item[key] = store_item.get(key, 0) + int(value) 143 | for k, v in store_item.items(): 144 | print(k, v) 145 | 146 | 147 | ## Word Order 148 | # Enter your code here. Read input from STDIN. Print output to STDOUT 149 | 150 | # # Option 1 151 | # from collections import defaultdict 152 | # n = int(input()) 153 | # words_dict = defaultdict(int) 154 | # for _ in range(n): 155 | # key = input() 156 | # words_dict[key] += 1 157 | # print(len(words_dict.keys())) 158 | # print(*words_dict.values()) 159 | 160 | # # Option 2 161 | # from collections import OrderedDict 162 | # words_dict = OrderedDict() 163 | # for i in range(int(input())): 164 | # key = input() 165 | # if not key in words_dict.keys(): 166 | # words_dict.update({key: 1}) 167 | # else: 168 | # words_dict[key] += 1 169 | # print(len(words_dict.keys())) 170 | # print(*words_dict.values()) 171 | 172 | # # Option 3 173 | # from collections import Counter 174 | # input_list = [] 175 | # for _ in range(int(input())): 176 | # input_list.extend((input().split('\n'))) 177 | # freq = Counter(input_list) 178 | # print(len(freq)) 179 | # for key in freq: 180 | # print(freq.get(key), end=' ') 181 | 182 | # # Option 4 183 | # from collections import Counter 184 | # input_list = [] 185 | # for _ in range(int(input())): 186 | # input_list.append(input()) 187 | # print(len(set(input_list))) 188 | # # print(*list(Counter(input_list).values()), sep=' ') #same 189 | # print(' '.join([str(v) for k, v in Counter(input_list).items()])) 190 | 191 | # Option 5 (without library) 192 | words = dict() 193 | for _ in range(int(input())): 194 | word = input() 195 | words[word] = words.get(word, 0) + 1 196 | print(len(words)) 197 | print(*(word for word in words.values())) 198 | 199 | 200 | ## Collections.deque() 201 | # Enter your code here. Read input from STDIN. Print output to STDOUT 202 | 203 | # # Option 1 204 | # from collections import deque 205 | # d = deque() 206 | # for _ in range(int(input())): 207 | # inp = input().split() 208 | # getattr(d, inp[0])(*[inp[1]] if len(inp) > 1 else '') 209 | # print(*[item for item in d]) 210 | 211 | # # Option 2 212 | # from collections import deque 213 | # d = deque() 214 | # for _ in range(int(input())): 215 | # com = input().split() + [''] 216 | # eval( f'd.{com[0]} ({com[1]})' ) 217 | # print(*d) 218 | 219 | # Option 3 220 | from collections import deque 221 | d = deque() 222 | for _ in range(int(input())): 223 | oper, val, *args = input().split() + [''] 224 | eval( f'd.{oper} ({val})' ) 225 | print(*d) 226 | 227 | 228 | ## Company Logo 229 | import math 230 | import os 231 | import random 232 | import re 233 | import sys 234 | 235 | if __name__ == '__main__': 236 | s = input() 237 | 238 | # # Option 1 239 | # from collections import Counter 240 | # [print(*c) for c in Counter(sorted(s)).most_common(3)] 241 | 242 | # # Option 2 243 | # from collections import Counter 244 | # for c in Counter(sorted(s)).most_common(3): 245 | # print(*c) 246 | 247 | # Option 3 248 | from collections import Counter 249 | s = sorted(s) 250 | freq = Counter(list(s)) 251 | for k,v in freq.most_common(3): 252 | print(k,v) 253 | 254 | 255 | ## Piling Up! 256 | # Enter your code here. Read input from STDIN. Print output to STDOUT 257 | 258 | # # Option 1 259 | # from collections import deque 260 | # for _ in range(int(input())): 261 | # result = 'Yes' 262 | # D = deque() 263 | # N = int(input()) 264 | # l = list(map(int, input().split())) 265 | # D.extend(l) 266 | # l.sort(reverse=True) 267 | # for i in range(N): 268 | # right = D.pop() 269 | # if i= lst[i+1]: 289 | i += 1 290 | while i < l - 1 and lst[i] <= lst[i+1]: 291 | i += 1 292 | print('Yes' if i == l - 1 else 'No') 293 | 294 | 295 | ## end ## 296 | -------------------------------------------------------------------------------- /Interview05_String_Manipulation: -------------------------------------------------------------------------------- 1 | ## Interview Preparation Kit 2 | ## String Manipulation 3 | 4 | 5 | 6 | 7 | ## Strings: Making Anagrams 8 | #!/bin/python3 9 | import math 10 | import os 11 | import random 12 | import re 13 | import sys 14 | 15 | #Complete the makeAnagram function below. 16 | # Option 1 17 | from collections import Counter 18 | def makeAnagram(a, b): 19 | a = Counter(a) 20 | b = Counter(b) 21 | intersection = a & b 22 | a_removal = a - intersection 23 | b_removal = b - intersection 24 | result = sum(a_removal.values()) + sum(b_removal.values()) 25 | return result 26 | 27 | # Option 2 28 | from collections import Counter 29 | def makeAnagram(a, b): 30 | #Counter for each string 31 | dict_a, dict_b = Counter(a), Counter(b) 32 | #Counter for letters in 'a' and not in 'b' and viceversa 33 | letters_removed = (dict_a-dict_b) + (dict_b-dict_a) 34 | #Sum the occurrence of each extra letter 35 | return sum(letters_removed.values()) 36 | 37 | # Option 3 38 | def makeAnagram(a, b): 39 | counter = 0 40 | for i in range(len(a)): 41 | t = a[i+1:].count(a[i]) 42 | if a[i] not in b: 43 | counter += 1 44 | else: 45 | if t >= b.count(a[i]): 46 | counter += 1 47 | for i in range(len(b)): 48 | t = b[i+1:].count(b[i]) 49 | if b[i] not in a: 50 | counter += 1 51 | else: 52 | if t >= a.count(b[i]): 53 | counter += 1 54 | return counter 55 | 56 | if __name__ == '__main__': 57 | fptr = open(os.environ['OUTPUT_PATH'], 'w') 58 | a = input() 59 | b = input() 60 | res = makeAnagram(a, b) 61 | fptr.write(str(res) + '\n') 62 | fptr.close() 63 | 64 | 65 | 66 | 67 | ## Alternating Characters 68 | #!/bin/python3 69 | import math 70 | import os 71 | import random 72 | import re 73 | import sys 74 | 75 | # Complete the alternatingCharacters function below. 76 | # Option 1 77 | def alternatingCharacters(s): 78 | c = 0 # count 79 | for i in range(len(s)-1): 80 | if s[i]==s[i+1]: 81 | c += 1 82 | return c 83 | 84 | # Option 2 85 | def alternatingCharacters(s): 86 | return len([i for i in range(len(s)-1) if s[i]==s[i+1]]) 87 | 88 | if __name__ == '__main__': 89 | fptr = open(os.environ['OUTPUT_PATH'], 'w') 90 | q = int(input()) 91 | for q_itr in range(q): 92 | s = input() 93 | result = alternatingCharacters(s) 94 | fptr.write(str(result) + '\n') 95 | fptr.close() 96 | 97 | 98 | 99 | 100 | ## Sherlock and the Valid String 101 | #!/bin/python3 102 | import math 103 | import os 104 | import random 105 | import re 106 | import sys 107 | 108 | # Complete the isValid function below. 109 | # Option 1 110 | from collections import Counter 111 | def isValid(s): 112 | freq_list = list(Counter(s).values()) 113 | first = freq_list[0] 114 | flag = 0 115 | for i in range(1, len(freq_list)): 116 | if abs(freq_list[i] - first) >= 1 : 117 | flag += 1 118 | if flag > 1 : 119 | return 'NO' 120 | else: 121 | return 'YES' 122 | 123 | # Option 2 124 | from collections import Counter 125 | def isValid(s): 126 | char_dict = Counter(s) 127 | c = 0 128 | for char in s: 129 | if char not in char_dict: 130 | char_dict[char] = 1 131 | else: 132 | char_dict[char] += 1 133 | current_value = 0 134 | previous_value = 0 135 | for index, key in enumerate(char_dict): 136 | current_value = char_dict[key] 137 | if index == 0: 138 | previous_value = char_dict[key] 139 | if abs(current_value - previous_value) >= 1: 140 | c += 1 141 | if c > 1: 142 | return 'NO' 143 | return 'YES' 144 | 145 | if __name__ == '__main__': 146 | fptr = open(os.environ['OUTPUT_PATH'], 'w') 147 | s = input() 148 | result = isValid(s) 149 | fptr.write(result + '\n') 150 | fptr.close() 151 | 152 | 153 | 154 | 155 | ## Special String Again 156 | #!/bin/python3 157 | import math 158 | import os 159 | import random 160 | import re 161 | import sys 162 | 163 | # Complete the substrCount function below. 164 | # Option 1 165 | def substrCount(n, s): 166 | l = [] 167 | c = 0 #count 168 | ref = None 169 | for i in range(n): 170 | if s[i] == ref: 171 | c += 1 172 | else: 173 | if ref is not None: 174 | l.append((ref, c)) 175 | ref = s[i] 176 | c = 1 177 | l.append((ref, c)) 178 | 179 | ans = 0 180 | for i in l: 181 | ans += (i[1] * (i[1] + 1)) // 2 182 | for i in range(1, len(l) - 1): 183 | if l[i - 1][0] == l[i + 1][0] and l[i][1] == 1: 184 | ans += min(l[i - 1][1], l[i + 1][1]) 185 | 186 | return ans 187 | 188 | 189 | # Option 2 190 | def substrCount(n, s): 191 | count = 0 192 | current_char = '' 193 | current_count = 0 194 | previous_char = '' 195 | previous_count = 0 196 | before_middle = 0 197 | count_after_middle = False 198 | for c in s: 199 | if c == current_char: 200 | current_count += 1 201 | else: 202 | if count_after_middle: 203 | count_after_middle = False 204 | count += min(current_count, before_middle) 205 | if current_count == 1 and c == previous_char: 206 | count_after_middle = True 207 | before_middle = previous_count 208 | count += combs(current_count) 209 | previous_char = current_char 210 | previous_count = current_count 211 | current_char = c 212 | current_count = 1 213 | if count_after_middle: 214 | count += min(current_count, before_middle) 215 | count += combs(current_count) 216 | return int(count) 217 | 218 | def combs(n): 219 | return int((n + 1) * n)/2 220 | 221 | 222 | # Option 3 223 | def substrCount(n, s): 224 | total=0 225 | l1 = list(s) 226 | l2 = list() 227 | pre = l1[0] 228 | cnt1 = 1 229 | for i in range(1,n): 230 | if l1[i] == pre: 231 | cnt1+=1 232 | else: 233 | l2.append({pre:cnt1}) 234 | pre = l1[i] 235 | cnt1 = 1 236 | l2.append({pre:cnt1}) 237 | # case #1 238 | for item in l2: 239 | for k,v in item.items(): 240 | total+=v*(v+1)//2 241 | # case #2 242 | l_k="" 243 | l_v=0 244 | m_k="" 245 | m_v=0 246 | for item in l2: 247 | for k,v in item.items(): 248 | if m_v==1: 249 | if l_k == k: 250 | total+=min(l_v,v) 251 | l_k=m_k 252 | l_v=m_v 253 | m_k=k 254 | m_v=v 255 | return total 256 | 257 | if __name__ == '__main__': 258 | fptr = open(os.environ['OUTPUT_PATH'], 'w') 259 | n = int(input()) 260 | s = input() 261 | result = substrCount(n, s) 262 | fptr.write(str(result) + '\n') 263 | fptr.close() 264 | 265 | 266 | 267 | 268 | ## Common Child 269 | """ 270 | Common computer science problem: 271 | https://en.wikipedia.org/wiki/Longest_common_subsequence_problem 272 | """ 273 | #!/bin/python3 274 | import math 275 | import os 276 | import random 277 | import re 278 | import sys 279 | 280 | # Complete the commonChild function below. 281 | def commonChild(s1, s2): 282 | # row 0 = 0, column 0 = 0 283 | l1 = len(s1) 284 | l2 = len(s2) 285 | # we only need history of previous row 286 | lcs = [[0]*(len(s1)+1) for _ in range(2)] 287 | #lcs_letters = [['']*(len(s1)+1) for _ in range(2)] 288 | 289 | # i in s1 = i+1 in lcs 290 | for i in range(l1): 291 | # get index pointers for current and previous row 292 | li1 = (i+1)%2 293 | li = i%2 294 | # j in s1 = j+1 in lcs 295 | for j in range(l2): 296 | # i and j are used to step forward in each string. 297 | # Now check if s1[i] and s2[j] are equal 298 | if s1[i] == s2[j]: 299 | # Now we have found one longer sequence 300 | # than what we had previously found. 301 | # so add 1 to the length of previous longest 302 | # sequence which we could have found at 303 | # earliest previous position of each string, 304 | # therefore subtract -1 from both i and j 305 | lcs[li1][j+1] = (lcs[li][j] + 1) 306 | #lcs_letters[li1][j+1] = lcs_letters[li][j]+s1[li] 307 | 308 | # if not matching pair, then get the biggest previous value 309 | elif lcs[li1][j] > lcs[li][j+1]: 310 | lcs[li1][j+1] = lcs[li1][j] 311 | #lcs_letters[li1][j+1] = lcs_letters[li1][j] 312 | else: 313 | lcs[li1][j+1] = lcs[li][j+1] 314 | #lcs_letters[li1][j+1] = lcs_letters[li][j+1] 315 | #print(lcs_letters[(i+1)%2][j+1]) 316 | return lcs[(i+1)%2][j+1] 317 | 318 | if __name__ == '__main__': 319 | fptr = open(os.environ['OUTPUT_PATH'], 'w') 320 | s1 = input() 321 | s2 = input() 322 | result = commonChild(s1, s2) 323 | fptr.write(str(result) + '\n') 324 | fptr.close() 325 | 326 | 327 | 328 | 329 | ## end ## 330 | -------------------------------------------------------------------------------- /ProjectEuler+: -------------------------------------------------------------------------------- 1 | ## HackerRank 2 | ## ProjectEuler+ 3 | 4 | 5 | 6 | 7 | ## Project Euler #1: Multiples of 3 and 5 8 | #!/bin/python3 9 | import sys 10 | 11 | def sum_ap(n, d): 12 | n = (n-1)//d 13 | return d*n*(n+1) 14 | 15 | t = int(input().strip()) 16 | for a0 in range(t): 17 | n = int(input().strip()) 18 | total = sum_ap(n,3) + sum_ap(n,5) - sum_ap(n,15) 19 | print(int(int(total) >> 1)) 20 | 21 | 22 | 23 | 24 | ## Project Euler #2: Even Fibonacci numbers 25 | """ 26 | Fibonacci series = 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, … 27 | """ 28 | #!/bin/python3 29 | import sys 30 | 31 | t = int(input().strip()) 32 | for a0 in range(t): 33 | n = int(input().strip()) 34 | total = 0 35 | a = 0 36 | b = 1 37 | while b < n: 38 | if b%2==0: #even 39 | total += b 40 | a,b = b,a+b 41 | print(total) 42 | 43 | 44 | 45 | 46 | ## Project Euler #3: Largest prime factor 47 | """ 48 | Any number can be broken down to a product of it's prime factors. For example, 100 = 2x2x5x5. So let's start with 2 and divide the number as long as it's divisible by 2. Then we move onto 3 and 4. We keep doing this until the number is not divisible anymore and just print it. In this method, there is no reason to check for primes. If a number is divisible by 4, say, we would have already divided it by 2 twice. And the final number we are left with would be the largest prime factor. 49 | We just have a single loop going to sqrt(N). So the complexity of this code is O(sqrtN). 50 | """ 51 | #!/bin/python3 52 | import sys 53 | 54 | t = int(input().strip()) 55 | for a0 in range(t): 56 | n = int(input().strip()) 57 | i=2 58 | while i <= n**0.5: 59 | if n%i==0: 60 | n = n//i 61 | else: 62 | # edge case is i==2 where we add 1 63 | if i==2: 64 | i=3 65 | else: 66 | i+=2 67 | print(n) 68 | 69 | 70 | 71 | 72 | ## Project Euler #4: Largest palindrome product 73 | #!/bin/python3 74 | import sys 75 | 76 | palindromelist = [] 77 | for i in range(100, 1000): 78 | for j in range(100, 1000): 79 | a = i * j 80 | if str(a) == str(a)[::-1] and a not in palindromelist: 81 | palindromelist.append(a) 82 | palindromelist.sort() 83 | length = len(palindromelist) 84 | 85 | t = int(input().strip()) 86 | for a0 in range(t): 87 | n = int(input().strip()) 88 | for i in range(length - 1, -1, -1): 89 | if palindromelist[i] < n: 90 | print(palindromelist[i]) 91 | break 92 | 93 | 94 | 95 | 96 | ## Project Euler #5: Smallest multiple 97 | """ 98 | 5342931457063200 99 | 5342931457063200 100 | 5342931457063200 101 | 5342931457063200 102 | 144403552893600 103 | 144403552893600 104 | 144403552893600 105 | 144403552893600 106 | 144403552893600 107 | 72201776446800 108 | 2329089562800 109 | 2329089562800 110 | 80313433200 111 | 80313433200 112 | 26771144400 113 | 26771144400 114 | 5354228880 115 | 5354228880 116 | 232792560 117 | 232792560 118 | 232792560 119 | 232792560 120 | 12252240 121 | 12252240 122 | 720720 123 | 360360 124 | 360360 125 | 360360 126 | 27720 127 | 27720 128 | 2520 129 | 2520 130 | 840 131 | 420 132 | 60 = divisible by 1,2,3,4,5,6 133 | 60 = divisible by 1,2,3,4,5 134 | 12 = divisible by 1,2,3,4 135 | 6 = divisible by 1,2,3 136 | 2 = divisible by 1,2 137 | """ 138 | #!/bin/python3 139 | import sys 140 | 141 | # Option 1 142 | from functools import reduce 143 | def gcd(x,y): 144 | while y!=0: 145 | x,y=y,x%y 146 | return x 147 | t = int(input().strip()) 148 | for a0 in range(t): 149 | n = int(input().strip()) 150 | result = reduce(lambda x,y: x*y/gcd(x,y), range(1,n+1)) 151 | print(int(result)) 152 | 153 | # Option 2 154 | def lcm(a,b) : 155 | for i in range(1,a + 1): 156 | if (i*b)%a == 0: 157 | return i*b 158 | t = int(input().strip()) 159 | for a0 in range(t): 160 | n = int(input().strip()) 161 | result = 1 162 | for i in range(2, n+1): 163 | result = lcm(result, i) 164 | print(result) 165 | 166 | 167 | 168 | 169 | ## Project Euler #6: Sum square difference 170 | """ 171 | 2 formulas: 172 | 1) sum of first n natural numbers is = n*(n+1)/2 173 | 2) sum of first n natural number^2's is : : n*(n+1)*(2*n+1)/6 174 | """ 175 | #!/bin/python3 176 | import sys 177 | 178 | t = int(input().strip()) 179 | for a0 in range(t): 180 | n = int(input().strip()) 181 | square_of_sum = (n*(n+1)//2)**2 182 | sum_of_squares = n*(n+1)*(2*n+1)//6 183 | print(square_of_sum - sum_of_squares) 184 | 185 | 186 | 187 | 188 | ## Project Euler #7: 10001st prime 189 | #!/bin/python3 190 | import sys 191 | 192 | prime_occurences = [0,2,3] 193 | 194 | def isPrime(num): 195 | i = 2 196 | while i <= int(num**0.5)+1: 197 | if num % i == 0 and num != i: 198 | return False 199 | i += 1 200 | return True 201 | 202 | t = int(input().strip()) 203 | for a0 in range(t): 204 | n = int(input().strip()) 205 | try: 206 | if prime_occurences[n]: 207 | print(prime_occurences[n]) 208 | except: 209 | ptr = len(prime_occurences) 210 | i = ptr - 1 211 | num = prime_occurences[i]+1 212 | while ptr <= n: 213 | if isPrime(num): 214 | prime_occurences.append(num) 215 | ptr += 1 216 | num += 1 217 | print(prime_occurences[n]) 218 | 219 | 220 | 221 | 222 | ## Project Euler #8: Largest product in a series 223 | #!/bin/python3 224 | import sys 225 | 226 | t = int(input().strip()) 227 | for a0 in range(t): 228 | n,k = input().strip().split(' ') 229 | n,k = [int(n),int(k)] 230 | num = input().strip() #this is a string 231 | result = [] 232 | for i in range(n-k): 233 | multiply = 1 234 | for j in num[i:i+k]: 235 | multiply *= int(j) 236 | result.append(multiply) 237 | print(max(result)) 238 | 239 | 240 | 241 | 242 | ## Project Euler #9: Special Pythagorean triplet 243 | #!/bin/python3 244 | import sys 245 | 246 | t = int(input().strip()) 247 | for a0 in range(t): 248 | n = int(input().strip()) 249 | result = -1 250 | for a in range(3, (n//3)+1): 251 | b = (n**2 - 2*a*n)//(2*n - 2*a) 252 | c = n - b - a 253 | if a**2 + b **2 == c**2: 254 | if a*b*c > result: 255 | result = a*b*c 256 | print(result) 257 | 258 | 259 | 260 | 261 | ## Project Euler #10: Summation of primes 262 | """ 263 | There is a very efficient algorithm called the Sieve of Eratosthenes that is very simple. This alorithm will help you create an array of booleans of size 1000000 that will tell you whether a number is a prime or not. 264 | https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes 265 | Create another array that holds the sum of all of the prime numbers less than the index 266 | """ 267 | #!/bin/python3 268 | import sys 269 | 270 | limit = 1000000 271 | sum_prime_arr = [0] * limit 272 | prime_arr = [True] * limit 273 | prime_arr[0] = prime_arr[1] = False 274 | for i, isprime in enumerate(prime_arr): 275 | if isprime: 276 | sum_prime_arr[i] = sum_prime_arr[i-1] + i 277 | for n in range(i*i, limit, i): 278 | prime_arr[n] = False 279 | else: 280 | sum_prime_arr[i] = sum_prime_arr[i-1] 281 | 282 | t = int(input().strip()) 283 | for prime_arr0 in range(t): 284 | n = int(input().strip()) 285 | print(sum_prime_arr[n]) 286 | 287 | 288 | 289 | 290 | ## Project Euler #11: Largest product in a grid 291 | """ 292 | This can be done without boundary checking by just making the 2D array 26 columns by 23 rows, leaving zeroes to the bottom, left, and right. Then you can check four directions (right, down, diagonal right and down, and diagonal left and down) for each value and take the max to get your answer. 293 | """ 294 | #!/bin/python3 295 | import sys 296 | 297 | g = [] 298 | for _ in range(20): 299 | grid_t = [0,0,0] 300 | grid_t.extend([int(x) for x in input().split()]) 301 | grid_t.extend([0,0,0]) 302 | g.append(grid_t) 303 | pad = [0]*26 304 | for _ in range(3): 305 | g.append(pad) 306 | m = [] 307 | for r in range(20): 308 | for c in range(3,23): 309 | m1 = g[r][c]*g[r][c+1]*g[r][c+2]*g[r][c+3] 310 | m2 = g[r][c]*g[r+1][c]*g[r+2][c]*g[r+3][c] 311 | m3 = g[r][c]*g[r+1][c+1]*g[r+2][c+2]*g[r+3][c+3] 312 | m4 = g[r][c]*g[r+1][c-1]*g[r+2][c-2]*g[r+3][c-3] 313 | m.append(max(m1,m2,m3,m4)) 314 | print(max(m)) 315 | 316 | 317 | 318 | 319 | ## Project Euler #12: Highly divisible triangular number 320 | 321 | 322 | 323 | 324 | 325 | 326 | 327 | 328 | 329 | 330 | ## Project Euler #81: Path sum: two ways 331 | # Enter your code here. Read input from STDIN. Print output to STDOUT 332 | n = int(input()) 333 | ar = [] 334 | ar2 = [] 335 | for a in range(n): 336 | ar.append([int(x) for x in input().split()]) 337 | ar2.append([0 for x in range(n)]) 338 | 339 | ar2[0][0]=ar[0][0] 340 | 341 | for i in range(1,n): 342 | ar2[0][i]=ar2[0][i-1]+ar[0][i] 343 | ar2[i][0]=ar2[i-1][0]+ar[i][0] 344 | 345 | for i in range(1,n): 346 | for j in range(1,n): 347 | ar2[i][j]=min(ar2[i][j-1],ar2[i-1][j])+ar[i][j] 348 | print(ar2[n-1][n-1]) 349 | 350 | (work in progress) 351 | 352 | ## end ## 353 | -------------------------------------------------------------------------------- /10_Days_of_Statistics: -------------------------------------------------------------------------------- 1 | Hackerrank 2 | 10 Days of Statistics 3 | 4 | 5 | 6 | 7 | # Day 0: Mean, Median, and Mode 8 | n = int(input()) 9 | number_list = list(map(int, input().split())) 10 | import numpy as np 11 | Mean = np.mean(number_list) 12 | Median = np.median(number_list) 13 | from scipy import stats 14 | Mode = int(stats.mode(number_list)[0]) 15 | print(round(Mean,1), Median, Mode, sep = '\n') 16 | 17 | 18 | # Day 0: Weighted Mean 19 | N = input() 20 | X = list(map(int, input().strip().split(' '))) 21 | W = list(map(int, input().strip().split(' '))) 22 | sum_X = sum([a*b for a,b in zip(X,W)]) 23 | print(round((sum_X/sum(W)),1)) 24 | 25 | 26 | 27 | 28 | # Day 1: Quartiles 29 | from statistics import median 30 | n = int(input()) 31 | x = sorted(list(map(int, input().split()))) 32 | print(int(median(x[ :n//2]))) 33 | print(int(median(x))) 34 | print(int(median(x[(n+1)//2: ]))) 35 | 36 | 37 | # Day 1: Interquartile Range 38 | n = input() 39 | x_list = input() 40 | x_list = [int(x) for x in x_list.split()] 41 | freq = input() 42 | freq = [int(x) for x in freq.split()] 43 | 44 | new_list = [] 45 | for i in range(len(x_list)): 46 | for j in range(freq[i]): 47 | new_list.append(x_list[i]) 48 | 49 | from statistics import median 50 | n = len(new_list) 51 | x = sorted(new_list) 52 | Q1 = median(x[:n//2]) 53 | Q3 = median(x[(n+1)//2:]) 54 | print("{:.1f}".format(Q3-Q1)) 55 | 56 | 57 | # Day 1: Standard Deviation 58 | n = int(input()) 59 | numbers = list(map(int, input().split())) 60 | mean = sum(numbers) / n 61 | variance = sum([((x - mean) ** 2) for x in numbers]) / n 62 | stddev = variance ** 0.5 63 | print("{:.1f}".format(stddev)) 64 | 65 | 66 | 67 | 68 | # Day 2: Basic Probability 69 | In a single toss of 2 fair (evenly-weighted) six-sided dice, find the probability that their sum will be at most 9. 70 | = 1 - P(10) - P(11) - P(12) 71 | = 1 - P(5,5 or 6,4) - P(5,6) - P(6,6) 72 | = 1 - (1/6*1/6 + 2*1/6*1/6) - (2*1/6*1/6) - (1/6*1/6) 73 | = 1 - (1/36 + 2/36) - (2/36) - (1/36) 74 | = 1 - 6/36 75 | = 1 - 1/6 76 | = 5/6 77 | Answer: 5/6 78 | 79 | 80 | # Day 2: More Dice 81 | In a single toss of 2 fair (evenly-weighted) six-sided dice, find the probability that the values rolled by each die will be different and the two dice have a sum of 6. 82 | = P(1,5) + P(2,4) + P(4,2) + P(5,1) 83 | = (1/6*1/6) + (1/6*1/6) + (1/6*1/6) + (1/6*1/6) 84 | = 4/36 85 | = 1/9 86 | Answer: 1/9 87 | 88 | 89 | # Day 2: Compound Event Probability 90 | There are 3 urns labeled X, Y, and Z. 91 | Urn X contains 4 red balls and 3 black balls. 92 | Urn Y contains 5 red balls and 4 black balls. 93 | Urn Z contains 4 red balls and 4 black balls. 94 | One ball is drawn from each of the 3 urns. What is the probability that, of the 3 balls drawn, 2 are red and 1 is black? 95 | 96 | Solution: 97 | Urn X has a 4/7 probability of giving a red ball 98 | Urn Y has a 5/9 probability of giving a red ball 99 | Urn Z has a 1/2 probability of giving a red ball 100 | 101 | Urn X has a 3/7 probability of giving a black ball 102 | Urn Y has a 4/9 probability of giving a black ball 103 | Urn Z has a 1/2 probability of giving a black ball 104 | 105 | P(2 red, 1 black) 106 | = P(Red Red Black) + P(Red Black Red) + P(Black Red Red) 107 | = (4/7)(5/9)(1/2) + (4/7)(4/9)(1/2) + (3/7)(5/9)(1/2) 108 | = 20/126 + 16/126 + 15/126 109 | = 51/126 110 | = 17/42 111 | 112 | Answer: 17/42 113 | 114 | 115 | 116 | 117 | # Day 3: Conditional Probability 118 | Suppose a family has 2 children, one of which is a boy. What is the probability that both children are boys? 119 | All possible outcomes: BB, BG, GB, GG 120 | Given one of them is a boy, all possible outcomes become: BB, BG, GB 121 | ie, denominator becomes 3 122 | P(BB) = 1/3 123 | Answer: 1/3 124 | 125 | 126 | # Day 3: Cards of the Same Suit 127 | You draw 2 cards from a standard 52-card deck without replacing them. What is the probability that both cards are of the same suit? 128 | = 52/52 * 12/51 129 | = 1 * 12/51 130 | = 12/51 131 | Answer: 12/51 132 | 133 | 134 | # Day 3: Drawing Marbles 135 | A bag contains 3 red marbles and 4 blue marbles. Then, 2 marbles are drawn from the bag, at random, without replacement. If the first marble drawn is red, what is the probability that the second marble is blue? 136 | If first marble drawn is red, bag now has 2 red marbles and 4 blue marbles 137 | P(second marble is blue) = 4 / (2+4) = 4/6 = 2/3 138 | Answer: 2/3 139 | 140 | 141 | 142 | 143 | # Day 4: Binomial Distribution I 144 | import math 145 | 146 | def binomial_prob(n, p, x): 147 | b = (math.factorial(n)/(math.factorial(x)*math.factorial(n-x)))*(p**x)*((1-p)**(n-x)) 148 | return(b) 149 | 150 | boy, girl = map(float, input().split()) 151 | n = 6 152 | p = boy/(boy+girl) 153 | b = 0 154 | for x in range(3,7): # x=3,4,5,6 155 | b += binomial_prob(n, p, x) 156 | print("%.3f" %b) 157 | 158 | 159 | # Day 4: Binomial Distribution II 160 | import math 161 | 162 | def binomial_prob(n, p, x): 163 | b = (math.factorial(n)/(math.factorial(x)*math.factorial(n-x)))*(p**x)*((1-p)**(n-x)) 164 | return(b) 165 | 166 | reject_percent, n = map(float, '12 10'.split()) 167 | p = reject_percent/100 168 | b = 0 169 | for x in range(0,3): # x=0,1,2 170 | b += binomial_prob(n, p, x) 171 | print("%.3f" %b) 172 | print(round(sum([binomial_prob(n, p, i) for i in range(2, 11)]), 3)) # x=2,3,4,...,10 173 | 174 | 175 | # Day 4: Geometric Distribution I 176 | # X is a geometric random variable 177 | # x is the number of trials required until the first success occurs 178 | # p = probability of success in each trial = 1/3 179 | 180 | # probability that a specified number of trials will take place before the first success occurs 181 | # P(X = x) = (1-p)**(x–1) * p # x = 1st, 2nd, 3rd, etc 182 | # Reference: https://www.dummies.com/education/math/business-statistics/how-to-calculate-geometric-probabilities/ 183 | 184 | def geometric_prob(p, x): 185 | g = (1-p)**(x-1) * p 186 | return(g) 187 | 188 | numerator, denominator = map(float, input().split()) 189 | x = int(input()) 190 | p = numerator/denominator 191 | g = geometric_prob(p, x) 192 | print("%.3f" %g) 193 | 194 | 195 | # Day 4: Geometric Distribution II 196 | # probability that defect is found during the first 5 inspections, 197 | # ie, 1st batch defect, 2nd batch defect,.., 5th batch defect 198 | 199 | def geometric_prob(p, x): 200 | g = (1-p)**(x-1) * p 201 | return(g) 202 | 203 | numerator, denominator = map(float, input().split()) 204 | x = int(input()) 205 | p = numerator/denominator 206 | g = 0 207 | for i in range(1,6): # i=1,2,3,4,5 208 | g += geometric_prob(p, i) 209 | print("%.3f" %g) 210 | 211 | 212 | 213 | 214 | # Day 5: Poisson Distribution I 215 | # X = poisson random variable 216 | # x = number of successes that occur in a specified region 217 | # mean = mean number of successes that occur in a specified region 218 | # exp = constant = approximately 2.71828 219 | # P(X = x) = ((mean ** k) * exp(-mean)) / factorial(k) 220 | # Reference: https://stattrek.com/probability-distributions/poisson.aspx 221 | 222 | from math import factorial, exp 223 | 224 | miu = float(input()) 225 | x = int(input()) 226 | poisson = ((miu ** x) * exp(-miu)) / factorial(x) 227 | print("%.3f" % poisson) 228 | 229 | 230 | # Day 5: Poisson Distribution II 231 | # Given cost_A = 160 + 40*X**2 232 | # Expectation of cost_A 233 | # E(cost_A) = E(160 + 40*X**2) 234 | # = E(160) + E(40*X**2) 235 | # = 160 + 40*E(X**2) 236 | # By definition, E(X**2) = E(X) + (E(X))**2 and E(X) = miu_A 237 | # Therefore E(cost_A) = 160 + 40*(miu_A + (miu_A)**2) 238 | 239 | # Given cost_B = 128 + 40*Y**2 240 | # Expectation of cost_B 241 | # E(cost_B) = E(128 + 40*Y**2) 242 | # = E(128) + E(40*Y**2) 243 | # = 128 + 40*E(Y**2) 244 | # By definition, E(Y**2) = E(Y) + (E(Y))**2 and E(Y) = miu_B 245 | # Therefore E(cost_B) = 128 + 40*(miu_B + (miu_B)**2) 246 | 247 | miu_A, miu_B = map(float, input().split()) 248 | 249 | cost_A = 160 + 40*(miu_A + miu_A**2) 250 | print(round(cost_A, 3)) 251 | cost_B = 128 + 40*(miu_B + miu_B**2) 252 | print(round(cost_B, 3)) 253 | 254 | 255 | # Day 5: Normal Distribution I 256 | # X = normal random variable 257 | # X ~ N(miu, stdev) 258 | # miu = mean of normal distribution 259 | # stdev = standard deviation of normal distribution 260 | # x = number of successful outcome 261 | # P(X < x) = 0.5 + 0.5*math.erf((x-miu)/(stdev * 2**0.5)) 262 | # Note: P(X < x) = P(X <= x) because P(X = x) = 0 for continuous probability distribution function 263 | # P( a < X < b ) = P(X < b) - P(X < a) 264 | 265 | import math 266 | 267 | miu, stdev = map(float, '20 2'.split()) # map(float, input().split()) 268 | limit = 19.5 # float(input()) 269 | limit1, limit2 = map(float, '20 22'.split()) # map(float, input().split()) 270 | 271 | def normal_prob(miu, stdev, x): 272 | return 0.5 + 0.5*math.erf((x-miu)/(stdev * 2**0.5)) 273 | 274 | print( '{:.3f}'.format(normal_prob(miu, stdev, limit)) ) 275 | print( '{:.3f}'.format(normal_prob(miu, stdev, limit2) - normal_prob(miu, stdev, limit1)) ) 276 | 277 | 278 | # Day 5: Normal Distribution II 279 | # X = normal random variable, ie, X ~ N ( miu, stdev ) 280 | # miu = mean of normal distribution 281 | # stdev = standard deviation of normal distribution 282 | # x = number of successful outcome 283 | # P(X < x) = 0.5 + 0.5*math.erf((x-miu)/(stdev * 2**0.5)) 284 | # Note: P(X < x) = P(X <= x) because P(X = x) = 0 for continuous probability distribution function 285 | # P(a < X < b) = P(X < b) - P(X < a) 286 | # P(X > c) = 1 - P(X < c) 287 | 288 | import math 289 | 290 | miu, stdev = map(float, input().split()) 291 | limit1 = float(input()) 292 | limit2 = float(input()) 293 | 294 | def normal_prob(miu, stdev, x): 295 | return 0.5 + 0.5*math.erf((x-miu)/(stdev * 2**0.5)) 296 | 297 | print( '%.2f' %((1 - normal_prob(miu, stdev, limit1)) *100) ) 298 | print( '%.2f' %((1 - normal_prob(miu, stdev, limit2)) *100) ) 299 | print( '%.2f' %(normal_prob(miu, stdev, limit2) *100) ) 300 | # note: need to output percentage (not probability) 301 | 302 | 303 | 304 | 305 | # Day 6: The Central Limit Theorem I 306 | import math 307 | 308 | def normal_prob(miu, stdev, x): 309 | return 0.5 + 0.5*math.erf((x-miu)/(stdev * 2**0.5)) 310 | 311 | weight_limit = float(input()) 312 | n = int(input()) 313 | [miu, stdev] = [float(input()) for _ in range(2)] 314 | 315 | # By Central Limit Thereom, for large n, 316 | # S ~ N(miu_S, stdev_S) approximately 317 | miu_S = n*miu 318 | stdev_S = (n**0.5)*stdev 319 | 320 | # To find P(S < weight_limit) 321 | print( '%.4f' %normal_prob(miu_S, stdev_S, weight_limit) ) 322 | 323 | 324 | # Day 6: The Central Limit Theorem II 325 | import math 326 | 327 | def normal_prob(miu, stdev, x): 328 | return 0.5 + 0.5*math.erf((x-miu)/(stdev * 2**0.5)) 329 | 330 | ticket_limit = float(input()) 331 | n = int(input()) 332 | [miu, stdev] = [float(input()) for _ in range(2)] 333 | 334 | # By Central Limit Thereom, for large n, 335 | # S ~ N(miu_S, stdev_S) approximately 336 | # S = total sum of tickets purchased by 100 students 337 | miu_S = n*miu 338 | stdev_S = (n**0.5)*stdev 339 | 340 | # To find P(S < ticket_limit) 341 | print( '%.4f' %normal_prob(miu_S, stdev_S, ticket_limit) ) 342 | 343 | 344 | # Day 6: The Central Limit Theorem III 345 | # Normal distribution describes that 346 | # 68% population will fall between range +-1 stdev from mean 347 | # 95% population will fall between range +-2 stdev from mean 348 | # 99.7% population will fall between range +-3 stdev from mean 349 | # Reference: https://en.wikipedia.org/wiki/68–95–99.7_rule 350 | # Prob( m-z*s < X < m+z*s ) = 0.95 351 | # z = 1.96 352 | 353 | n = int(input()) 354 | [miu, stdev] = [float(input()) for _ in range(2)] # 500, 80 355 | [prob, z] = [float(input()) for _ in range(2)] # 0.95, 1.96 356 | # population mean ~ N(miu, stdev) 357 | # sample mean ~ N(miu, s), where s = sample stdev = stdev/n**0.5 358 | s = stdev/n**0.5 359 | # lower limit 360 | print('%.2f' %(miu - z*s)) 361 | # upper limit 362 | print('%.2f' %(miu + z*s)) 363 | 364 | 365 | 366 | 367 | # Day 7: Pearson Correlation Coefficient I 368 | n = int(input()) 369 | X = list(map(float,input().strip().split())) 370 | Y = list(map(float,input().strip().split())) 371 | 372 | miu_x = sum(X) / n 373 | miu_y = sum(Y) / n 374 | 375 | stdev_x = (sum([(i - miu_x)**2 for i in X]) / n)**0.5 376 | stdev_y = (sum([(i - miu_y)**2 for i in Y]) / n)**0.5 377 | 378 | covariance = sum([(X[i] - miu_x) * (Y[i] -miu_y) for i in range(n)]) 379 | correlation_coefficient = covariance / (n * stdev_x * stdev_y) 380 | print(round(correlation_coefficient,3)) 381 | 382 | 383 | # Day 7: Spearman's Rank Correlation Coefficient 384 | def get_rank(X): 385 | x_rank = dict((x, i+1) for i, x in enumerate(sorted(set(X)))) 386 | return [x_rank[x] for x in X] 387 | 388 | n = int(input()) 389 | X = list(map(float, input().split())) 390 | Y = list(map(float, input().split())) 391 | 392 | rx = get_rank(X) 393 | ry = get_rank(Y) 394 | 395 | d = [(rx[i] -ry[i])**2 for i in range(n)] 396 | r_s = 1 - (6 * sum(d)) / (n * (n*n - 1)) 397 | print('%.3f' % r_s) 398 | 399 | 400 | 401 | 402 | # Day 8: Least Square Regression Line 403 | # Example 1: using maths formula 404 | # x = [95,85,80,70,60] 405 | # y = [85,95,70,65,70] 406 | x, y = [], [] 407 | for _ in range(5): 408 | i = input().split() 409 | x.append(int(i[0])) 410 | y.append(int(i[1])) 411 | n = len(x) 412 | x_sum = sum(x) 413 | x_sum_sqr = x_sum**2 414 | x_sqr_sum = sum([x_i**2 for x_i in x]) 415 | y_sum = sum(y) 416 | sum_prod_xy = 0 417 | for x_i,y_i in zip(x,y): 418 | sum_prod_xy += (x_i*y_i) 419 | b = (n*sum_prod_xy - x_sum*y_sum) / (n*x_sqr_sum - x_sum_sqr) 420 | y_mean = y_sum/n 421 | x_mean = x_sum/n 422 | a = y_mean - b*x_mean 423 | 424 | # to make prediction 425 | x_test = 80 426 | y_test = a + b * x_test 427 | print("%.3f" %y_test) # 78.288 428 | 429 | # # Example 2: using Pearson correlation coefficient 430 | # from statistics import mean, pstdev 431 | # def pearson(x, y): 432 | # n = len(x) 433 | # mx, sx, my, sy = mean(x), pstdev(x), mean(y), pstdev(y) 434 | # return sum((xi - mx) * (yi - my) for xi, yi in zip(x, y)) / (n * sx * sy) 435 | # def linear_regression(x, y): 436 | # b = pearson(x, y) * pstdev(y) / pstdev(x) 437 | # return mean(y) - b * mean(x), b 438 | # # x = [95,85,80,70,60] 439 | # # y = [85,95,70,65,70] 440 | # x, y = [], [] 441 | # for _ in range(5): 442 | # i = input().split() 443 | # x.append(int(i[0])) 444 | # y.append(int(i[1])) 445 | # a, b = linear_regression(x, y) 446 | 447 | # # to make prediction 448 | # x_test = 80 449 | # y_test = a + b * x_test 450 | # print("%.3f" %y_test) # 78.288 451 | 452 | 453 | # Day 8: Pearson Correlation Coefficient II 454 | The regression line of y on x is 3x + 4y + 8 = 0, and the regression line of x on y is 4x + 3y + 7 = 0. 455 | What is the value of the Pearson correlation coefficient? 456 | Answer: -3/4 457 | 458 | 459 | 460 | 461 | # Day 9: Multiple Linear Regression 462 | import numpy as np 463 | # import data 464 | [m,n] = list(map(int, input().split())) 465 | x,y = [],[] 466 | for _ in range(n): 467 | data = input().strip().split(' ') 468 | x.append(data[0:m]) 469 | y.append(data[-1]) 470 | X = np.array(x, float) 471 | y = np.array(y, float) 472 | q = int(input().strip()) 473 | X_query = [] 474 | for _ in range(q): 475 | X_query.append(input().strip().split(' ')) 476 | X_query = np.array(X_query, float) 477 | 478 | #center 479 | X_R = X - np.mean(X, axis=0) 480 | y_R = y - np.mean(y) 481 | 482 | #calculate beta 483 | beta = np.dot(np.linalg.inv(np.dot(X_R.T,X_R)), np.dot(X_R.T,y_R)) 484 | 485 | #predict 486 | X_query_R = X_query - np.mean(X, axis=0) 487 | y_query_R = np.dot(X_query_R, beta) 488 | y_query = y_query_R + np.mean(y) 489 | 490 | #print 491 | for i in y_query: 492 | print(round(float(i), 2)) 493 | 494 | 495 | 496 | 497 | ## end ## 498 | -------------------------------------------------------------------------------- /SQL: -------------------------------------------------------------------------------- 1 | ## HackerRank 2 | ## SQL 3 | ## MySQL 4 | 5 | 6 | 7 | ## Basic Select 8 | 9 | Revising the Select Query I 10 | Query all columns for all American cities in CITY with populations larger than 100000. The CountryCode for America is USA. 11 | SELECT * 12 | FROM CITY 13 | WHERE 14 | COUNTRYCODE = 'USA' 15 | AND POPULATION > 100000; 16 | 17 | Revising the Select Query II 18 | Query the names of all American cities in CITY with populations larger than 120000. The CountryCode for America is USA. 19 | SELECT NAME 20 | FROM CITY 21 | WHERE 22 | COUNTRYCODE = 'USA' 23 | AND POPULATION > 120000; 24 | 25 | Select All 26 | Query all columns (attributes) for every row in the CITY table. 27 | SELECT * 28 | FROM CITY; 29 | 30 | Select By ID 31 | Query all columns for a city in CITY with the ID 1661. 32 | SELECT * 33 | FROM CITY 34 | WHERE ID = '1661'; 35 | 36 | Japanese Cities' Attributes 37 | Query all attributes of every Japanese city in the CITY table. The COUNTRYCODE for Japan is JPN. 38 | SELECT * 39 | FROM CITY 40 | WHERE COUNTRYCODE = 'JPN'; 41 | 42 | Japanese Cities' Names 43 | Query the names of all the Japanese cities in the CITY table. The COUNTRYCODE for Japan is JPN. 44 | SELECT NAME 45 | FROM CITY 46 | WHERE COUNTRYCODE = 'JPN'; 47 | 48 | Weather Observation Station 1 49 | Query a list of CITY and STATE from the STATION table. 50 | SELECT CITY, STATE 51 | FROM STATION; 52 | 53 | Weather Observation Station 3 54 | Query a list of CITY names from STATION with even ID numbers only. You may print the results in any order, but must exclude duplicates from your answer. 55 | SELECT DISTINCT CITY 56 | FROM STATION 57 | WHERE MOD(ID,2)=0 58 | ORDER BY CITY; 59 | 60 | Weather Observation Station 4 61 | Let N be the number of CITY entries in STATION, and let N' be the number of distinct CITY names in STATION; query the value of N-N' from STATION. In other words, find the difference between the total number of CITY entries in the table and the number of distinct CITY entries in the table. 62 | SELECT COUNT(CITY) - COUNT(DISTINCT CITY) 63 | FROM STATION; 64 | 65 | Weather Observation Station 5 66 | Query the two cities in STATION with the shortest and longest CITY names, as well as their respective lengths (i.e.: number of characters in the name). If there is more than one smallest or largest city, choose the one that comes first when ordered alphabetically. 67 | select city,length(city) from (select city,length(city) from station order by length(city) asc, city asc) where rownum<=1; 68 | select city,length(city) from (select city,length(city) from station order by length(city) desc, city desc) where rownum<=1; 69 | 70 | Weather Observation Station 6 71 | Query the list of CITY names starting with vowels (i.e., a, e, i, o, or u) from STATION. Your result cannot contain duplicates. 72 | SELECT DISTINCT CITY 73 | FROM STATION 74 | WHERE CITY REGEXP '^[a,e,i,o,u]'; 75 | 76 | WHERE CITY REGEXP '^[a,e,i,o,u].*'; # alternate 77 | 78 | Weather Observation Station 7 79 | Query the list of CITY names ending with vowels (a, e, i, o, u) from STATION. Your result cannot contain duplicates. 80 | SELECT DISTINCT CITY 81 | FROM STATION 82 | WHERE CITY REGEXP '[a,e,i,o,u]$'; 83 | 84 | Weather Observation Station 8 85 | Query the list of CITY names from STATION which have vowels (i.e., a, e, i, o, and u) as both their first and last characters. Your result cannot contain duplicates. 86 | SELECT DISTINCT CITY 87 | FROM STATION 88 | WHERE CITY REGEXP '^[a,e,i,o,u].*[a,e,i,o,u]$'; 89 | 90 | Weather Observation Station 9 91 | Query the list of CITY names from STATION that do not start with vowels. Your result cannot contain duplicates. 92 | SELECT DISTINCT CITY 93 | FROM STATION 94 | WHERE CITY REGEXP '^[^a,e,i,o,u]'; 95 | 96 | Weather Observation Station 10 97 | Query the list of CITY names from STATION that do not end with vowels. Your result cannot contain duplicates. 98 | SELECT DISTINCT CITY 99 | FROM STATION 100 | WHERE CITY REGEXP '[^aeiou]$'; 101 | 102 | Weather Observation Station 11 103 | Query the list of CITY names from STATION that either do not start with vowels or do not end with vowels. Your result cannot contain duplicates. 104 | SELECT DISTINCT CITY 105 | FROM STATION 106 | WHERE CITY REGEXP '^[^aeiou]|[^aeiou]$'; 107 | 108 | Weather Observation Station 12 109 | Query the list of CITY names from STATION that do not start with vowels and do not end with vowels. Your result cannot contain duplicates. 110 | SELECT DISTINCT CITY 111 | FROM STATION 112 | WHERE CITY REGEXP '^[^aeiou].*[^aeiou]$'; 113 | 114 | Higher Than 75 Marks 115 | Query the Name of any student in STUDENTS who scored higher than 75 Marks. Order your output by the last three characters of each name. If two or more students both have names ending in the same last three characters (i.e.: Bobby, Robby, etc.), secondary sort them by ascending ID. 116 | SELECT Name 117 | FROM STUDENTS 118 | WHERE Marks > 75 119 | ORDER BY RIGHT(Name, 3), ID; 120 | 121 | Employee Names 122 | Write a query that prints a list of employee names (i.e.: the name attribute) from the Employee table in alphabetical order. 123 | SELECT Name 124 | FROM Employee 125 | ORDER BY Name; 126 | 127 | Employee Salaries 128 | Write a query that prints a list of employee names (i.e.: the name attribute) for employees in Employee having a salary greater than $2000 per month who have been employees for less than 10 months. Sort your result by ascending employee_id. 129 | SELECT name 130 | FROM Employee 131 | WHERE salary > 2000 132 | AND months < 10 133 | ORDER BY employee_id; 134 | 135 | 136 | 137 | ## Advanced Select 138 | 139 | Type of Triangle 140 | Write a query identifying the type of each record in the TRIANGLES table using its three side lengths. Output one of the following statements for each record in the table: 141 | Equilateral: It's a triangle with 3 sides of equal length. 142 | Isosceles: It's a triangle with 2 sides of equal length. 143 | Scalene: It's a triangle with 3 sides of differing lengths. 144 | Not A Triangle: The given values of A, B, and C don't form a triangle. 145 | SELECT CASE WHEN A + B <= C 146 | OR A + C <= B 147 | OR B + C <= A 148 | THEN 'Not A Triangle' 149 | WHEN A = B 150 | AND A = C 151 | AND B = C 152 | THEN 'Equilateral' 153 | WHEN A = B 154 | OR A = C 155 | OR B = C 156 | THEN 'Isosceles' 157 | ELSE 'Scalene' 158 | END 159 | FROM TRIANGLES; 160 | 161 | The PADS 162 | Query an alphabetically ordered list of all names in OCCUPATIONS, immediately followed by the first letter of each profession as a parenthetical (i.e.: enclosed in parentheses). For example: AnActorName(A), ADoctorName(D), AProfessorName(P), and ASingerName(S). 163 | Query the number of ocurrences of each occupation in OCCUPATIONS. Sort the occurrences in ascending order, and output them in the following format: 164 | There are a total of [occupation_count] [occupation]s. 165 | where [occupation_count] is the number of occurrences of an occupation in OCCUPATIONS and [occupation] is the lowercase occupation name. If more than one Occupation has the same [occupation_count], they should be ordered alphabetically. 166 | Note: There will be at least two entries in the table for each type of occupation. 167 | SELECT CONCAT(Name, '(', LEFT(Occupation, 1), ')') AS 'Name(Profession)' 168 | FROM OCCUPATIONS 169 | ORDER BY Name; 170 | 171 | SELECT CONCAT('There are a total of ', COUNT(*), ' ', LOWER(Occupation), 's.') 172 | FROM OCCUPATIONS 173 | GROUP BY Occupation 174 | ORDER BY COUNT(*), 175 | Occupation; 176 | 177 | Occupations 178 | Pivot the Occupation column in OCCUPATIONS so that each Name is sorted alphabetically and displayed underneath its corresponding Occupation. The output column headers should be Doctor, Professor, Singer, and Actor, respectively. 179 | Note: Print NULL when there are no more names corresponding to an occupation. 180 | set @r1=0, @r2=0, @r3=0, @r4=0; 181 | select min(Doctor), min(Professor), min(Singer), min(Actor) 182 | from( 183 | select case when Occupation='Doctor' then (@r1:=@r1+1) 184 | when Occupation='Professor' then (@r2:=@r2+1) 185 | when Occupation='Singer' then (@r3:=@r3+1) 186 | when Occupation='Actor' then (@r4:=@r4+1) end as RowNumber, 187 | case when Occupation='Doctor' then Name end as Doctor, 188 | case when Occupation='Professor' then Name end as Professor, 189 | case when Occupation='Singer' then Name end as Singer, 190 | case when Occupation='Actor' then Name end as Actor 191 | from OCCUPATIONS 192 | order by Name 193 | ) Temp 194 | group by RowNumber 195 | 196 | Binary Tree Nodes 197 | You are given a table, BST, containing two columns: N and P, where N represents the value of a node in Binary Tree, and P is the parent of N. 198 | Write a query to find the node type of Binary Tree ordered by the value of the node. Output one of the following for each node: 199 | Root: If node is root node. 200 | Leaf: If node is leaf node. 201 | Inner: If node is neither root nor leaf node. 202 | SELECT N, 203 | CASE 204 | WHEN P IS NULL THEN 'Root' 205 | WHEN N IN (SELECT P FROM BST) THEN 'Inner' 206 | ELSE 'Leaf' 207 | END 208 | FROM BST 209 | ORDER BY N; 210 | 211 | New Companies 212 | Amber's conglomerate corporation just acquired some new companies. Each of the companies follows this hierarchy: 213 | Founder -> Lead Manager -> Senior Manager -> Manager -> Employee 214 | Given the table schemas below, write a query to print the company_code, founder name, total number of lead managers, total number of senior managers, total number of managers, and total number of employees. Order your output by ascending company_code. 215 | Note: 216 | The tables may contain duplicate records. 217 | The company_code is string, so the sorting should not be numeric. For example, if the company_codes are C_1, C_2, and C_10, then the ascending company_codes will be C_1, C_10, and C_2. 218 | select c.company_code, c.founder, count(distinct lm.lead_manager_code), 219 | count(distinct sm.senior_manager_code), count(distinct m.manager_code), 220 | count(distinct e.employee_code) 221 | from Company c, Lead_Manager lm, Senior_Manager sm, Manager m, Employee e 222 | where c.company_code = lm.company_code 223 | and lm.lead_manager_code = sm.lead_manager_code 224 | and sm.senior_manager_code = m.senior_manager_code 225 | and m.manager_code = e.manager_code 226 | group by c.company_code, c.founder 227 | order by c.company_code 228 | 229 | 230 | 231 | ## Aggregation 232 | 233 | Revising Aggregations - The Count Function 234 | Query a count of the number of cities in CITY having a Population larger than 100,000. 235 | SELECT COUNT(*) 236 | FROM CITY 237 | WHERE POPULATION > 100000; 238 | 239 | Revising Aggregations - The Sum Function 240 | Query the total population of all cities in CITY where District is California. 241 | SELECT SUM(POPULATION) 242 | FROM CITY 243 | WHERE DISTRICT = 'California'; 244 | 245 | Revising Aggregations - Averages 246 | Query the average population of all cities in CITY where District is California. 247 | SELECT AVG(POPULATION) 248 | FROM CITY 249 | WHERE DISTRICT = 'California'; 250 | 251 | Average Population 252 | Query the average population for all cities in CITY, rounded down to the nearest integer. 253 | SELECT FLOOR(AVG(POPULATION)) 254 | FROM CITY; 255 | 256 | Japan Population 257 | Query the sum of the populations for all Japanese cities in CITY. The COUNTRYCODE for Japan is JPN. 258 | SELECT SUM(POPULATION) 259 | FROM CITY 260 | WHERE COUNTRYCODE = 'JPN'; 261 | 262 | Population Density Difference 263 | Query the difference between the maximum and minimum populations in CITY. 264 | SELECT MAX(POPULATION) - MIN(POPULATION) 265 | FROM CITY; 266 | 267 | The Blunder 268 | Samantha was tasked with calculating the average monthly salaries for all employees in the EMPLOYEES table, but did not realize her keyboard's 0 key was broken until after completing the calculation. She wants your help finding the difference between her miscalculation (using salaries with any zeroes removed), and the actual average salary. 269 | Write a query calculating the amount of error (i.e.: actual - miscalculated average monthly salaries), and round it up to the next integer. 270 | SELECT CEIL(AVG(Salary) - AVG(REPLACE(Salary, '0', ''))) 271 | FROM EMPLOYEES; 272 | 273 | Top Earners 274 | We define an employee's total earnings to be their monthly salary * months worked, and the maximum total earnings to be the maximum total earnings for any employee in the Employee table. Write a query to find the maximum total earnings for all employees as well as the total number of employees who have maximum total earnings. Then print these values as 2 space-separated integers. 275 | SELECT salary * months AS total_earnings, 276 | COUNT(*) 277 | FROM Employee 278 | GROUP BY total_earnings 279 | ORDER BY total_earnings DESC 280 | LIMIT 1; 281 | 282 | output: 283 | 108064 7 284 | 285 | Weather Observation Station 2 286 | Query the following two values from the STATION table: 287 | The sum of all values in LAT_N rounded to a scale of 2 decimal places. 288 | The sum of all values in LONG_W rounded to a scale of 2 decimal places. 289 | SELECT ROUND(SUM(LAT_N), 2), 290 | ROUND(SUM(LONG_W), 2) 291 | FROM STATION; 292 | 293 | Weather Observation Station 13 294 | Query the sum of Northern Latitudes (LAT_N) from STATION having values greater than 38.7880 and less than 137.2345. Truncate your answer to 4 decimal places. 295 | SELECT TRUNCATE(SUM(LAT_N), 4) 296 | FROM STATION 297 | WHERE LAT_N BETWEEN 38.7880 AND 137.2345; 298 | 299 | Weather Observation Station 14 300 | Query the greatest value of the Northern Latitudes (LAT_N) from STATION that is less than 137.2345. Truncate your answer to 4 decimal places. 301 | SELECT TRUNCATE(MAX(LAT_N), 4) 302 | FROM STATION 303 | WHERE LAT_N < 137.2345; 304 | 305 | Weather Observation Station 15 306 | Query the Western Longitude (LONG_W) for the largest Northern Latitude (LAT_N) in STATION that is less than 137.2345. Round your answer to 4 decimal places. 307 | SELECT ROUND(LONG_W, 4) 308 | FROM STATION 309 | WHERE LAT_N < 137.2345 310 | ORDER BY LAT_N DESC 311 | LIMIT 1; 312 | 313 | output: 314 | 117.2465 315 | 316 | Weather Observation Station 16 317 | Query the smallest Northern Latitude (LAT_N) from STATION that is greater than 38.7780. Round your answer to 4 decimal places. 318 | SELECT ROUND(MIN(LAT_N), 4) 319 | FROM STATION 320 | WHERE LAT_N > 38.7780; 321 | 322 | output: 323 | 38.8526 324 | 325 | Weather Observation Station 17 326 | Query the Western Longitude (LONG_W)where the smallest Northern Latitude (LAT_N) in STATION is greater than 38.7780. Round your answer to 4 decimal places. 327 | SELECT ROUND(LONG_W, 4) 328 | FROM STATION 329 | WHERE LAT_N > 38.7780 330 | ORDER BY LAT_N 331 | LIMIT 1; 332 | 333 | output: 334 | 70.1378 335 | 336 | Weather Observation Station 18 337 | Consider P1(a,b) and P2(c,d) to be two points on a 2D plane. 338 | a happens to equal the minimum value in Northern Latitude (LAT_N in STATION). 339 | b happens to equal the minimum value in Western Longitude (LONG_W in STATION). 340 | c happens to equal the maximum value in Northern Latitude (LAT_N in STATION). 341 | d happens to equal the maximum value in Western Longitude (LONG_W in STATION). 342 | Query the Manhattan Distance between points P1 and P2 and round it to a scale of 4 decimal places. 343 | SELECT ROUND(ABS(MIN(LAT_N) - MAX(LAT_N)) + ABS(MIN(LONG_W) - MAX(LONG_W)), 4) 344 | FROM STATION; 345 | 346 | output: 347 | 259.6859 348 | 349 | Weather Observation Station 19 350 | Consider P1(a,c) and P2(b,d) to be two points on a 2D plane where (a,b) are the respective minimum and maximum values of Northern Latitude (LAT_N) and (c,d) are the respective minimum and maximum values of Western Longitude (LONG_W) in STATION. 351 | Query the Euclidean Distance between points P1 and P2 and format your answer to display 4 decimal digits. 352 | SELECT ROUND(SQRT(POW(MAX(LAT_N) - MIN(LAT_N), 2) + 353 | POW(MAX(LONG_W) - MIN(LONG_W), 2)), 4) 354 | FROM STATION; 355 | 356 | output: 357 | 184.1616 358 | 359 | Weather Observation Station 20 360 | A median is defined as a number separating the higher half of a data set from the lower half. Query the median of the Northern Latitudes (LAT_N) from STATION and round your answer to 4 decimal places. 361 | SELECT ROUND(S.LAT_N, 4) 362 | FROM STATION S 363 | WHERE (SELECT COUNT(LAT_N) FROM STATION WHERE LAT_N < S.LAT_N) 364 | = (SELECT COUNT(LAT_N) FROM STATION WHERE LAT_N > S.LAT_N); 365 | 366 | output: 367 | 83.8913 368 | 369 | 370 | 371 | ## Basic Join 372 | 373 | Asian Population 374 | Given the CITY and COUNTRY tables, query the sum of the populations of all cities where the CONTINENT is 'Asia'. 375 | Note: CITY.CountryCode and COUNTRY.Code are matching key columns. 376 | 377 | 378 | 379 | 380 | African Cities 381 | 382 | Average Population of Each Continent 383 | 384 | The Report 385 | 386 | Top Competitors 387 | 388 | Ollivander's Inventory 389 | 390 | Challenges 391 | 392 | Contest Leaderboard 393 | 394 | 395 | 396 | 397 | ## Advanced Join 398 | 399 | SQL Project Planning 400 | 401 | Placements 402 | 403 | Symmetric Pairs 404 | 405 | Interviews 406 | 407 | 15 Days of Learning SQL 408 | 409 | 410 | 411 | 412 | ## Alternative Queries 413 | 414 | Draw The Triangle 1 415 | 416 | Draw The Triangle 2 417 | 418 | Print Prime Numbers 419 | 420 | 421 | 422 | 423 | 424 | 425 | 426 | 427 | 428 | 429 | 430 | ## end ## 431 | -------------------------------------------------------------------------------- /30_Days_of_Code: -------------------------------------------------------------------------------- 1 | ## Hackerrank 2 | ## 30 Days of Code 3 | 4 | 5 | 6 | 7 | # Day 0: Hello, World. 8 | # Read a full line of input from stdin and save it to our dynamically typed variable, input_string. 9 | input_string = input() 10 | 11 | # Print a string literal saying "Hello, World." to stdout. 12 | print('Hello, World.') 13 | 14 | # TODO: Write a line of code here that prints the contents of input_string to stdout. 15 | print(input_string) 16 | 17 | 18 | 19 | 20 | # Day 1: Data Types 21 | # Declare second integer, double, and String variables. 22 | int_2 = input() 23 | double_2 = input() 24 | string_2 = input() 25 | 26 | # Read and save an integer, double, and String to your variables. 27 | sum_int = i + int(int_2) 28 | sum_double = d + float(double_2) 29 | sum_string = s + str(string_2) 30 | 31 | # Print the sum of both integer variables on a new line. 32 | print(sum_int) 33 | 34 | # Print the sum of the double variables on a new line. 35 | print(sum_double) 36 | 37 | # Concatenate and print the String variables on a new line 38 | # The 's' variable above should be printed first. 39 | print(sum_string) 40 | 41 | 42 | 43 | 44 | # Day 2: Operators 45 | import math 46 | import os 47 | import random 48 | import re 49 | import sys 50 | 51 | # Complete the solve function below. 52 | def solve(meal_cost, tip_percent, tax_percent): 53 | a = meal_cost 54 | b = a*tip_percent/100 55 | c = a*tax_percent/100 56 | total = a+b+c 57 | print('{:.0f}'.format(total)) 58 | return 59 | 60 | if __name__ == '__main__': 61 | meal_cost = float(input()) 62 | tip_percent = int(input()) 63 | tax_percent = int(input()) 64 | solve(meal_cost, tip_percent, tax_percent) 65 | 66 | 67 | 68 | 69 | # Day 3: Intro to Conditional Statements 70 | import math 71 | import os 72 | import random 73 | import re 74 | import sys 75 | 76 | if __name__ == '__main__': 77 | N = int(input()) 78 | 79 | if N % 2 == 1: 80 | print('Weird') 81 | elif N % 2 == 0: 82 | if N >=6 and N <= 20: 83 | print('Weird') 84 | elif N == 2 or N == 4 or N > 20: 85 | print('Not Weird') 86 | 87 | # If is odd, print Weird 88 | # If is even and in the inclusive range of 2 to 5, print Not Weird 89 | # If is even and in the inclusive range of 6 to 20, print Weird 90 | # If is even and greater than 20, print Not Weird 91 | 92 | 93 | 94 | 95 | # Day 4: Class vs. Instance 96 | class Person: 97 | def __init__(self, initialAge): 98 | # to run some checks on initialAge 99 | if initialAge < 0: 100 | print("Age is not valid, setting age to 0.") 101 | else: 102 | self.age = initialAge 103 | 104 | def amIOld(self): 105 | # print out the correct statement to the console 106 | if age < 13: 107 | print("You are young.") 108 | elif 13 <= age < 18: 109 | print("You are a teenager.") 110 | elif age >= 18: 111 | print("You are old.") 112 | 113 | def yearPasses(self): 114 | # Increment the age of the person in here 115 | global age 116 | age += 1 117 | 118 | 119 | 120 | 121 | # Day 5: Loops 122 | import math 123 | import os 124 | import random 125 | import re 126 | import sys 127 | 128 | if __name__ == '__main__': 129 | n = int(input()) 130 | 131 | for i in range(1,11): 132 | print(n, 'x', i, '=', n*i) 133 | 134 | 135 | # Day 6: Let's Review 136 | n = int(input()) # number of strings 137 | for _ in range(n): 138 | word = input() 139 | print(word[::2], word[1::2]) # print even letters, odd letters 140 | 141 | 142 | 143 | 144 | # Day 7: Arrays 145 | import math 146 | import os 147 | import random 148 | import re 149 | import sys 150 | 151 | if __name__ == '__main__': 152 | n = int(input()) 153 | arr = list(map(str, input().rstrip().split())) 154 | new_arr = [] 155 | for element in arr: 156 | new_arr.insert(0, element) 157 | print(' '.join(new_arr)) 158 | 159 | 160 | 161 | 162 | # Day 8: Dictionaries and Maps 163 | # n = int(input()) 164 | # phonebook = {} 165 | # for _ in range(n): 166 | # input_list = input().split() 167 | # phonebook[input_list[0]] = input_list[1] 168 | # 169 | # for _ in range(n): 170 | # try: 171 | # name = input() 172 | # except: 173 | # break 174 | # 175 | # if name in phonebook: 176 | # print(name, '=', phonebook[name], sep='') 177 | # else : print('Not found') 178 | 179 | phonebook={} 180 | for _ in range(int(input())): 181 | name, num = input().split() 182 | # if type(name)==int: 183 | # print("Not found") 184 | # else: 185 | phonebook[name] = int(num) 186 | 187 | while 1: 188 | try: 189 | name = input() 190 | print(f"{name}={phonebook[name]}") 191 | except KeyError: 192 | print(f"Not found") 193 | except EOFError: 194 | break 195 | 196 | 197 | 198 | 199 | # Day 9: Recursion 3 200 | import math 201 | import os 202 | import random 203 | import re 204 | import sys 205 | 206 | # Complete the factorial function below. 207 | def factorial(n): 208 | if n == 1 or n == 0: 209 | return 1 210 | else: 211 | return n * factorial(n-1) 212 | 213 | if __name__ == '__main__': 214 | fptr = open(os.environ['OUTPUT_PATH'], 'w') 215 | n = int(input()) 216 | result = factorial(n) 217 | fptr.write(str(result) + '\n') 218 | fptr.close() 219 | 220 | 221 | 222 | 223 | # Day 10: Binary Numbers 224 | import math 225 | import os 226 | import random 227 | import re 228 | import sys 229 | 230 | if __name__ == '__main__': 231 | n = int(input()) 232 | b = bin(n)[2:] 233 | #print(b) 234 | b = b.split('0') 235 | #print(b) 236 | print(len(max(b))) 237 | 238 | 239 | 240 | 241 | # Day 11: 2D Arrays 242 | import math 243 | import os 244 | import random 245 | import re 246 | import sys 247 | 248 | arr = [] 249 | for _ in range(6): 250 | arr.append(list(map(int, input().rstrip().split()))) 251 | 252 | hourglass_sum = [] 253 | for i in range(0,4): 254 | for j in range(0,4): 255 | total = sum([sum(x[i:i+3]) for x in arr[j:j+3]]) - arr[j+1][i] - arr[j+1][i+2] 256 | hourglass_sum.append(total) 257 | 258 | print(max(hourglass_sum)) 259 | 260 | 261 | 262 | 263 | # Day 12: Inheritance 264 | class Person: 265 | def __init__(self, firstName, lastName, idNumber): 266 | self.firstName = firstName 267 | self.lastName = lastName 268 | self.idNumber = idNumber 269 | def printPerson(self): 270 | print("Name:", self.lastName + ",", self.firstName) 271 | print("ID:", self.idNumber) 272 | 273 | class Student(Person): 274 | # Class Constructor 275 | # 276 | # Parameters: 277 | # firstName - A string denoting the Person's first name. 278 | # lastName - A string denoting the Person's last name. 279 | # id - An integer denoting the Person's ID number. 280 | # scores - An array of integers denoting the Person's test scores. 281 | # 282 | # Write your constructor here 283 | def __init__(self, firstName, lastName, idNumber,scores): 284 | self.firstName = firstName 285 | self.lastName = lastName 286 | self.idNumber = idNumber 287 | self.scores = scores 288 | # 289 | # Function Name: calculate 290 | # Return: A character denoting the grade. 291 | # 292 | # Write your function here 293 | def calculate(self): 294 | av = sum(self.scores)/len(self.scores) 295 | return { 296 | av < 40: 'T', 297 | 40 <= av < 55: 'D', 298 | 55 <= av < 70: 'P', 299 | 70 <= av < 80: 'A', 300 | 80 <= av < 90: 'E', 301 | 90 <= av <= 100: 'O' 302 | }[True] 303 | 304 | line = input().split() 305 | 306 | 307 | 308 | 309 | # Day 13: Abstract Classes 310 | from abc import ABCMeta, abstractmethod 311 | class Book(object, metaclass=ABCMeta): 312 | def __init__(self,title,author): 313 | self.title=title 314 | self.author=author 315 | @abstractmethod 316 | def display(): pass 317 | 318 | #Write MyBook class 319 | class MyBook(Book): 320 | def __init__(self, title, author, price): 321 | super(Book, self).__init__() 322 | self.price = price 323 | def display(self): 324 | print('Title: ' + title) 325 | print('Author: ' + author) 326 | print('Price: ' + str(price)) 327 | 328 | title=input() 329 | author=input() 330 | price=int(input()) 331 | new_novel=MyBook(title,author,price) 332 | new_novel.display() 333 | 334 | 335 | 336 | 337 | # Day 14: Scope 338 | class Difference: 339 | def __init__(self, a): 340 | self.__elements = a 341 | 342 | def computeDifference(self): 343 | self.maximumDifference = abs( sorted(a)[0] - sorted(a)[-1] ) 344 | # End of Difference class 345 | 346 | _ = input() 347 | a = [int(e) for e in input().split(' ')] 348 | 349 | d = Difference(a) 350 | d.computeDifference() 351 | 352 | print(d.maximumDifference) 353 | 354 | 355 | 356 | 357 | # Day 15: Linked List 358 | class Node: 359 | def __init__(self,data): 360 | self.data = data 361 | self.next = None 362 | class Solution: 363 | def display(self,head): 364 | current = head 365 | while current: 366 | print(current.data,end=' ') 367 | current = current.next 368 | 369 | def insert(self,head,data): 370 | if head == None: 371 | self.head=Node(data) 372 | else: 373 | temp = self.head 374 | while self.head.next != None: 375 | self.head = self.head.next 376 | self.head.next = Node(data) 377 | self.head = temp 378 | return self.head 379 | 380 | mylist= Solution() 381 | T=int(input()) 382 | head=None 383 | for i in range(T): 384 | data=int(input()) 385 | head=mylist.insert(head,data) 386 | mylist.display(head); 387 | 388 | 389 | 390 | 391 | # Day 16: Exceptions - String to Integer 392 | import sys 393 | S = input().strip() 394 | try: 395 | print(int(S)) 396 | except: 397 | print("Bad String") 398 | 399 | 400 | 401 | 402 | # Day 17: More Exceptions 403 | #Write your code here 404 | class Calculator(object): 405 | def power(self, n, p): 406 | if n<0 or p<0: 407 | raise Exception('n and p should be non-negative') 408 | else: 409 | return n**p 410 | 411 | myCalculator=Calculator() 412 | T=int(input()) 413 | for i in range(T): 414 | n,p = map(int, input().split()) 415 | try: 416 | ans=myCalculator.power(n,p) 417 | print(ans) 418 | except Exception as e: 419 | print(e) 420 | 421 | 422 | 423 | 424 | # Day 18: Queues and Stacks 425 | import sys 426 | from queue import Queue 427 | 428 | class Solution: 429 | # Write your code here 430 | stck = [] 431 | q = Queue() 432 | 433 | def pushCharacter(self, ch): 434 | self.stck.append(ch) 435 | 436 | def enqueueCharacter(self, ch): 437 | self.q.put(ch) 438 | 439 | def popCharacter(self): 440 | return self.stck.pop() 441 | 442 | def dequeueCharacter(self): 443 | return self.q.get() 444 | 445 | # read the string s 446 | s=input() 447 | #Create the Solution class object 448 | obj=Solution() 449 | 450 | l=len(s) 451 | # push/enqueue all the characters of string s to stack 452 | for i in range(l): 453 | obj.pushCharacter(s[i]) 454 | obj.enqueueCharacter(s[i]) 455 | 456 | isPalindrome=True 457 | ''' 458 | pop the top character from stack 459 | dequeue the first character from queue 460 | compare both the characters 461 | ''' 462 | for i in range(l // 2): 463 | if obj.popCharacter()!=obj.dequeueCharacter(): 464 | isPalindrome=False 465 | break 466 | #finally print whether string s is palindrome or not. 467 | if isPalindrome: 468 | print("The word, "+s+", is a palindrome.") 469 | else: 470 | print("The word, "+s+", is not a palindrome.") 471 | 472 | 473 | 474 | 475 | # Day 19: Interfaces 476 | class AdvancedArithmetic(object): 477 | def divisorSum(n): 478 | raise NotImplementedError 479 | 480 | class Calculator(AdvancedArithmetic): 481 | def divisorSum(self, n): 482 | factor_sum = 0 483 | for i in range(1, n + 1): 484 | if n % i == 0: 485 | factor_sum += i 486 | return factor_sum 487 | 488 | n = int(input()) 489 | my_calculator = Calculator() 490 | s = my_calculator.divisorSum(n) 491 | print("I implemented: " + type(my_calculator).__bases__[0].__name__) 492 | print(s) 493 | 494 | 495 | 496 | 497 | # Day 20: Sorting 498 | import sys 499 | 500 | n = int(input().strip()) 501 | a = list(map(int, input().strip().split(' '))) 502 | # Write Your Code Here 503 | num_swap = 0 504 | 505 | while a != sorted(a): 506 | for i in range(n - 1): 507 | tmp = 0 508 | if a[i] > a[i + 1]: 509 | tmp = a[i] 510 | a[i] = a[i + 1] 511 | a[i + 1] = tmp 512 | num_swap += 1 513 | 514 | print('Array is sorted in {} swaps.'.format(num_swap)) 515 | print('First Element:', a[0]) 516 | print('Last Element:', a[-1]) 517 | 518 | 519 | 520 | 521 | # Day 21: Generics 522 | #include 523 | #include 524 | #include 525 | 526 | using namespace std; 527 | 528 | /** 529 | * Name: printArray 530 | * Print each element of the generic vector on a new line. Do not return anything. 531 | * @param A generic vector 532 | **/ 533 | 534 | // Write your code here 535 | template 536 | void printArray(vector v) 537 | { 538 | for(T t : v) 539 | cout << t << endl; 540 | } 541 | 542 | int main() { 543 | int n; 544 | 545 | cin >> n; 546 | vector int_vector(n); 547 | for (int i = 0; i < n; i++) { 548 | int value; 549 | cin >> value; 550 | int_vector[i] = value; 551 | } 552 | 553 | cin >> n; 554 | vector string_vector(n); 555 | for (int i = 0; i < n; i++) { 556 | string value; 557 | cin >> value; 558 | string_vector[i] = value; 559 | } 560 | 561 | printArray(int_vector); 562 | printArray(string_vector); 563 | 564 | return 0; 565 | } 566 | 567 | 568 | 569 | 570 | # Day 22: Binary Search Trees 571 | class Node: 572 | def __init__(self,data): 573 | self.right=self.left=None 574 | self.data = data 575 | class Solution: 576 | def insert(self,root,data): 577 | if root==None: 578 | return Node(data) 579 | else: 580 | if data<=root.data: 581 | cur=self.insert(root.left,data) 582 | root.left=cur 583 | else: 584 | cur=self.insert(root.right,data) 585 | root.right=cur 586 | return root 587 | 588 | def getHeight(self,root): 589 | #Write your code here 590 | if root == None: 591 | return -1 592 | return 1 + max(self.getHeight(root.left), self.getHeight(root.right)) 593 | 594 | T=int(input()) 595 | myTree=Solution() 596 | root=None 597 | for i in range(T): 598 | data=int(input()) 599 | root=myTree.insert(root,data) 600 | height=myTree.getHeight(root) 601 | print(height) 602 | 603 | 604 | 605 | 606 | # Day 23: BST Level-Order Traversal 607 | import sys 608 | 609 | class Node: 610 | def __init__(self,data): 611 | self.right=self.left=None 612 | self.data = data 613 | class Solution: 614 | def insert(self,root,data): 615 | if root==None: 616 | return Node(data) 617 | else: 618 | if data<=root.data: 619 | cur=self.insert(root.left,data) 620 | root.left=cur 621 | else: 622 | cur=self.insert(root.right,data) 623 | root.right=cur 624 | return root 625 | 626 | def levelOrder(self,root): 627 | #Write your code here 628 | queue = [root] if root else [] 629 | while queue: 630 | node = queue.pop() 631 | print(node.data, end=" ") 632 | if node.left: 633 | queue.insert(0, node.left) 634 | if node.right: 635 | queue.insert(0, node.right) 636 | 637 | T=int(input()) 638 | myTree=Solution() 639 | root=None 640 | for i in range(T): 641 | data=int(input()) 642 | root=myTree.insert(root,data) 643 | myTree.levelOrder(root) 644 | 645 | 646 | 647 | 648 | # Day 24: More Linked Lists 649 | class Node: 650 | def __init__(self,data): 651 | self.data = data 652 | self.next = None 653 | class Solution: 654 | def insert(self,head,data): 655 | p = Node(data) 656 | if head==None: 657 | head=p 658 | elif head.next==None: 659 | head.next=p 660 | else: 661 | start=head 662 | while(start.next!=None): 663 | start=start.next 664 | start.next=p 665 | return head 666 | def display(self,head): 667 | current = head 668 | while current: 669 | print(current.data,end=' ') 670 | current = current.next 671 | 672 | def removeDuplicates(self,head): 673 | #Write your code here 674 | curr = head 675 | while curr.next: 676 | if curr.data == curr.next.data: 677 | curr.next = curr.next.next 678 | else: 679 | curr = curr.next 680 | return head 681 | 682 | mylist= Solution() 683 | T=int(input()) 684 | head=None 685 | for i in range(T): 686 | data=int(input()) 687 | head=mylist.insert(head,data) 688 | head=mylist.removeDuplicates(head) 689 | mylist.display(head); 690 | 691 | 692 | 693 | 694 | # Day 25: Running Time and Complexity 695 | """ 696 | If a number x is divisable by another number less or equal to the square root of x... it is NOT prime. That is the reason for O(sqrt(n)) run time. 697 | """ 698 | # Enter your code here. Read input from STDIN. Print output to STDOUT 699 | def is_prime(n): 700 | if n==2: 701 | return 'Prime' 702 | elif n==1 or n%2==0: # 1 or any even number 703 | return 'Not prime' 704 | # iterate through for all odd numbers from 3 to int(square root of n) 705 | for i in range(3, int(n**0.5) + 1, 2): # 2 step increment, even numbers are not prime 706 | if n%i==0: 707 | return 'Not prime' 708 | return 'Prime' 709 | 710 | T = int(input()) 711 | for _ in range(T): 712 | n = int(input()) 713 | print(is_prime(n)) 714 | 715 | 716 | 717 | 718 | # Day 26: Nested Logic 719 | # Enter your code here. Read input from STDIN. Print output to STDOUT 720 | d1, m1, y1 = map(int, input().split()) 721 | d2, m2, y2 = map(int, input().split()) 722 | 723 | if y1 > y2: 724 | print(10000) 725 | elif m1>m2 and y1==y2: 726 | print((m1-m2) * 500) 727 | elif d1>d2 and m1==m2 and y1==y2: 728 | print((d1-d2) * 15) 729 | else: 730 | print(0) 731 | 732 | 733 | 734 | 735 | # Day 27: Testing 736 | def minimum_index(seq): 737 | if len(seq) == 0: 738 | raise ValueError("Cannot get the minimum value index from an empty sequence") 739 | min_idx = 0 740 | for i in range(1, len(seq)): 741 | if seq[i] < seq[min_idx]: 742 | min_idx = i 743 | return min_idx 744 | 745 | class TestDataEmptyArray(object): 746 | 747 | @staticmethod 748 | def get_array(): 749 | # complete this function 750 | return [] 751 | 752 | class TestDataUniqueValues(object): 753 | 754 | @staticmethod 755 | def get_array(): 756 | # complete this function 757 | return [1, 2, 3, -4, 5] 758 | 759 | @staticmethod 760 | def get_expected_result(): 761 | # complete this function 762 | return 3 763 | 764 | class TestDataExactlyTwoDifferentMinimums(object): 765 | 766 | @staticmethod 767 | def get_array(): 768 | # complete this function 769 | return [1, -3, 2, 57, -3] 770 | 771 | @staticmethod 772 | def get_expected_result(): 773 | # complete this function 774 | return 1 775 | 776 | def TestWithEmptyArray(): 777 | try: 778 | seq = TestDataEmptyArray.get_array() 779 | result = minimum_index(seq) 780 | except ValueError as e: 781 | pass 782 | else: 783 | assert False 784 | 785 | def TestWithUniqueValues(): 786 | seq = TestDataUniqueValues.get_array() 787 | assert len(seq) >= 2 788 | 789 | assert len(list(set(seq))) == len(seq) 790 | 791 | expected_result = TestDataUniqueValues.get_expected_result() 792 | result = minimum_index(seq) 793 | assert result == expected_result 794 | 795 | 796 | def TestiWithExactyTwoDifferentMinimums(): 797 | seq = TestDataExactlyTwoDifferentMinimums.get_array() 798 | assert len(seq) >= 2 799 | tmp = sorted(seq) 800 | assert tmp[0] == tmp[1] and (len(tmp) == 2 or tmp[1] < tmp[2]) 801 | 802 | expected_result = TestDataExactlyTwoDifferentMinimums.get_expected_result() 803 | result = minimum_index(seq) 804 | assert result == expected_result 805 | 806 | TestWithEmptyArray() 807 | TestWithUniqueValues() 808 | TestiWithExactyTwoDifferentMinimums() 809 | print("OK") 810 | 811 | 812 | 813 | 814 | # Day 28: RegEx, Patterns, and Intro to Databases 815 | #!/bin/python3 816 | 817 | import math 818 | import os 819 | import random 820 | import re 821 | import sys 822 | 823 | if __name__ == '__main__': 824 | name_list = [] 825 | N = int(input()) 826 | for _ in range(N): 827 | firstNameEmailID = input().split() 828 | firstName = firstNameEmailID[0] 829 | emailID = firstNameEmailID[1] 830 | 831 | if emailID[-10:] == '@gmail.com': 832 | name_list.append(firstName) 833 | 834 | for e in sorted(name_list): 835 | print(e) 836 | 837 | 838 | 839 | 840 | # Day 29: Bitwise AND 841 | #!/bin/python3 842 | 843 | import math 844 | import os 845 | import random 846 | import re 847 | import sys 848 | 849 | if __name__ == '__main__': 850 | t = int(input()) 851 | for _ in range(t): 852 | nk = input().split() 853 | n = int(nk[0]) 854 | k = int(nk[1]) 855 | print(k-1 if ((k-1) | k) <= n else k-2) 856 | 857 | 858 | 859 | 860 | ## end ## 861 | -------------------------------------------------------------------------------- /10_Days_of_Javascript: -------------------------------------------------------------------------------- 1 | 10 days of Java Script 2 | 3 | 4 | 5 | 6 | Day 0 a: Hello, World! 7 | function greeting(parameterVariable) { 8 | // This line prints 'Hello, World!' to the console: 9 | console.log('Hello, World!'); 10 | // Write a line of code that prints parameterVariable to stdout using console.log: 11 | console.log(parameterVariable); 12 | } 13 | function main() { 14 | const parameterVariable = readLine(); // Welcome to 10 Days of JavaScript! 15 | greeting(parameterVariable); 16 | } 17 | output: 18 | Hello, World! 19 | Welcome to 10 Days of JavaScript! 20 | 21 | 22 | 23 | 24 | Day 0 b: Data Types 25 | function performOperation(secondInteger, secondDecimal, secondString) { 26 | // Declare a variable named 'firstInteger' (integer) 27 | const firstInteger = 4; 28 | // Declare a variable named 'firstDecimal' (floating-point) 29 | const firstDecimal = 4.0; 30 | // Declare a variable named 'firstString' (string) 31 | const firstString = 'HackerRank '; 32 | // sum of the 'firstInteger' and 'secondInteger' (converted type) 33 | console.log(firstInteger+parseInt(secondInteger)); 34 | // sum of 'firstDecimal' and 'secondDecimal' (converted type) 35 | console.log(firstDecimal+parseFloat(secondDecimal)); 36 | // print the concatenation of 'firstString' and 'secondString' 37 | console.log(firstString.concat(secondString)); 38 | } 39 | function main() { 40 | const secondInteger = readLine(); // 12 41 | const secondDecimal = readLine(); // 4.32 42 | const secondString = readLine(); // is the best place to learn and practice coding! 43 | performOperation(secondInteger, secondDecimal, secondString); 44 | } 45 | output: 46 | 16 47 | 8.32 48 | HackerRank is the best place to learn and practice coding! 49 | 50 | 51 | 52 | 53 | Day 1 a: Arithmetic Operators 54 | function getArea(length, width) { 55 | let area; 56 | area = length*width; 57 | return area; 58 | } 59 | function getPerimeter(length, width) { 60 | let perimeter; 61 | perimeter= 2*(length+width); 62 | return perimeter; 63 | } 64 | function main() { 65 | const length = +(readLine()); // 3 66 | const width = +(readLine()); // 4.5 67 | console.log(getArea(length, width)); 68 | console.log(getPerimeter(length, width)); 69 | } 70 | output: 71 | 13.5 72 | 15 73 | 74 | 75 | 76 | 77 | Day 1 b: Functions 78 | function factorial(n){ // int n between 1 and 10 79 | if(n === 0){ 80 | return 1; 81 | } else{ 82 | return n * factorial(n-1); // return the value of n! 83 | } 84 | } 85 | function main() { 86 | const n = +(readLine()); // 4 87 | console.log(factorial(n)); 88 | } 89 | output: 90 | 24 91 | 92 | 93 | 94 | 95 | Day 1 c: Let and Const 96 | function main() { 97 | const PI = Math.PI; 98 | let r = readLine(); // 2.6 99 | // Print the area of the circle: 100 | console.log(PI*r*r); 101 | // Print the perimeter of the circle: 102 | console.log(PI*2*r); 103 | 104 | try { 105 | // Attempt to redefine the value of constant variable PI 106 | PI = 0; 107 | // Attempt to print the value of PI 108 | console.log(PI); 109 | } catch(error) { 110 | console.error("You correctly declared 'PI' as a constant."); 111 | } 112 | } 113 | output: 114 | 21.237166338267002 115 | 16.336281798666924 116 | 117 | 118 | 119 | 120 | Day 2 a: Conditional Statements: If-Else 121 | function getGrade(score) { 122 | let grade; 123 | 124 | if(score <=5){ 125 | grade = 'F'; 126 | } else if(score <= 10){ 127 | grade = 'E'; 128 | } else if(score <= 15){ 129 | grade = 'D'; 130 | } else if(score <= 20){ 131 | grade = 'C'; 132 | } else if(score <= 25){ 133 | grade = 'B'; 134 | } else 135 | grade = 'A'; 136 | 137 | return grade; 138 | } 139 | function main() { 140 | const score = +(readLine()); 141 | 142 | console.log(getGrade(score)); 143 | } 144 | 145 | 146 | 147 | 148 | Day 2 b: Conditional Statements: Switch 149 | function getLetter(s) { 150 | let letter; 151 | 152 | switch (true) { 153 | case 'aeiou'.includes(s[0]): 154 | letter = 'A'; 155 | break; 156 | case 'bcdfg'.includes(s[0]): 157 | letter = 'B'; 158 | break; 159 | case 'hjklm'.includes(s[0]): 160 | letter = 'C'; 161 | break; 162 | case 'npqrstvwxyz'.includes(s[0]): 163 | letter = 'D'; 164 | break; 165 | } 166 | return letter; 167 | } 168 | function main() { 169 | const s = readLine(); // adfgt 170 | console.log(getLetter(s)); 171 | } 172 | output: 173 | A 174 | 175 | 176 | 177 | 178 | Day 2 c: Loops 179 | function vowelsAndConsonants(s) { 180 | let vowels = ["a", "e", "i", "o", "u"]; 181 | for (let v of s) { // print vowels first 182 | if(vowels.includes(v)) 183 | console.log(v); 184 | } 185 | for (let v of s) { // next print consonants 186 | if(!vowels.includes(v)) 187 | console.log(v); 188 | } 189 | } 190 | function main() { 191 | const s = readLine(); // javascriptloops 192 | vowelsAndConsonants(s); 193 | } 194 | output: 195 | a 196 | a 197 | i 198 | o 199 | o 200 | j 201 | v 202 | s 203 | c 204 | r 205 | p 206 | t 207 | l 208 | p 209 | s 210 | 211 | 212 | 213 | 214 | Day 3 a: Try, Catch, and Finally 215 | function reverseString(s) { // to reverse string s using the split, reverse, and join methods 216 | try{ 217 | console.log( s.split('').reverse().join('') ) 218 | } 219 | catch(e){ 220 | console.log(e.message); // If an exception is thrown, catch it and print the contents of the exception's messaage 221 | console.log(s); // If no exception was thrown, then this should be the reversed string; 222 | } // if an exception was thrown, this should be the original string. 223 | } 224 | function main() { 225 | const s = eval(readLine()); // "1234", Number(1234) 226 | reverseString(s); 227 | } 228 | output: 4321, 229 | s.split is not a function 230 | 1234 231 | 232 | 233 | 234 | 235 | Day 3 b: Arrays 236 | /** 237 | * Return the second largest number in the array. 238 | * @param {Number[]} nums - An array of numbers. 239 | * @return {Number} The second largest number in the array. 240 | **/ 241 | 242 | function getSecondLargest(nums) { 243 | let first = nums[0]; 244 | let second = -1; 245 | for (let i = 0; i < nums.length; i++) { 246 | if (nums[i] > first) { 247 | second = first; 248 | first = nums[i] 249 | } 250 | if (nums[i] > second && nums[i] < first) { 251 | second = nums[i]; 252 | } 253 | } 254 | return second; 255 | } 256 | function main() { 257 | const n = +(readLine()); // 5 258 | const nums = readLine().split(' ').map(Number); // 2 3 6 6 5 259 | 260 | console.log(getSecondLargest(nums)); 261 | } 262 | output: 263 | 5 264 | 265 | 266 | 267 | 268 | Day 3 c: Throw 269 | /* 270 | * Complete the isPositive function. 271 | * If 'a' is positive, return "YES". 272 | * If 'a' is 0, throw an Error with the message "Zero Error" 273 | * If 'a' is negative, throw an Error with the message "Negative Error" 274 | */ 275 | function isPositive(a) { 276 | if (a == 0) 277 | throw Error('Zero Error'); 278 | if (a < 0) 279 | throw Error('Negative Error'); 280 | return 'YES'; 281 | } 282 | function main() { 283 | const n = +(readLine()); // 5 284 | for (let i = 0; i < n; i++) { // 1, 0, -5, 10, 3 285 | const a = +(readLine()); 286 | try { 287 | console.log(isPositive(a)); 288 | } catch (e) { 289 | console.log(e.message); 290 | } 291 | } 292 | } 293 | output: 294 | YES 295 | Zero Error 296 | Negative Error 297 | YES 298 | YES 299 | 300 | 301 | 302 | 303 | Day 4 a: Create a Rectangle Object 304 | function Rectangle(a, b) { 305 | this.length = a; 306 | this.width = b; 307 | this.area = a * b; 308 | this.perimeter = 2 * (a + b); 309 | } 310 | function main() { 311 | const a = +(readLine()); // 4 312 | const b = +(readLine()); // 5 313 | const rect = new Rectangle(a, b); 314 | console.log(rect.length); // 4 315 | console.log(rect.width); // 5 316 | console.log(rect.perimeter); // 18 317 | console.log(rect.area); // 20 318 | } 319 | output: 320 | 4 321 | 5 322 | 18 323 | 20 324 | 325 | 326 | 327 | 328 | Day 4 b: Count Objects 329 | /* 330 | * Return a count of the total number of objects 'o' satisfying o.x == o.y. 331 | * Parameter(s): 332 | * objects: an array of objects with integer properties 'x' and 'y' 333 | */ 334 | function getCount(objects) { 335 | var ctr = 0; 336 | for (var i=0; i 0; b--) { 510 | for (let a = b-1; a > 0; a--) { 511 | if ((a & b) < k && (a & b) > max_anb) { 512 | max_anb = (a&b); 513 | } 514 | } 515 | } 516 | return max_anb; 517 | } 518 | function main() { 519 | const q = +(readLine()); // 3 520 | for (let i = 0; i < q; i++) { 521 | const [n, k] = readLine().split(' ').map(Number); 522 | 5 2 523 | 8 5 524 | 2 2 525 | console.log(getMaxLessThanK(n, k)); 526 | } 527 | } 528 | output: 529 | 1 530 | 4 531 | 0 532 | 533 | 534 | 535 | 536 | Day 6 b: JavaScript Dates 537 | // The days of the week are: "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" 538 | 539 | function getDayName(dateString) { 540 | let dayName; 541 | const date = new Date(dateString); 542 | const options = { weekday: 'long' }; 543 | dayName = new Intl.DateTimeFormat('en-Us', options).format(date); 544 | return dayName; 545 | } 546 | function main() { 547 | const d = +(readLine()); // 2 548 | for (let i = 0; i < d; i++) { 549 | const date = readLine(); 550 | 10/11/2009 551 | 11/10/2010 552 | console.log(getDayName(date)); 553 | } 554 | } 555 | output: 556 | Sunday 557 | Wednesday 558 | 559 | 560 | 561 | 562 | Day 7 a: Regular Expressions I 563 | function regexVar(str) { 564 | // ^ => first item matches: 565 | // () => stores matching value captured within 566 | // [aeiou] => matches any of the characters in the brackets 567 | // . => matches any character: 568 | // + => for 1 or more occurrances (this ensures str length > 3) 569 | // \1 => matches to previously stored match. 570 | // \2 looks for matched item stored 2 instances ago 571 | // \3 looks for matched item stored 3 ago, etc 572 | // $ ensures that matched item is at end of the sequence 573 | 574 | let re = /^([aeiou]).+\1$/; 575 | return re; 576 | } 577 | function main() { 578 | const re = regexVar(); 579 | const s = readLine(); // abcd, abca, abco 580 | console.log(re.test(s)); // match a string that starts and ends with the same vowel (a, e, i, o, u) 581 | } 582 | output: 583 | false, true, false 584 | 585 | 586 | 587 | 588 | Day 7 b: Regular Expressions II 589 | function regexVar() { 590 | /* 591 | * Declare a RegExp object variable named 're' 592 | * It must match a string that starts with 'Mr.', 'Mrs.', 'Ms.', 'Dr.', or 'Er.', 593 | * followed by one or more letters. 594 | */ 595 | let re = new RegExp('^(Mr|Mrs|Ms|Dr|Er)(\\.)([a-zA-Z])*$'); 596 | return re; 597 | } 598 | function main() { 599 | const re = regexVar(); 600 | const s = readLine(); // Mr.X, Mrs.Y, Dr#Joseph, Er.Abc 601 | console.log(!!s.match(re)); 602 | } 603 | output: true, true, false, false 604 | 605 | 606 | 607 | 608 | Day 7 c: Regular Expressions III 609 | function regexVar() { 610 | /* 611 | * Declare a RegExp object variable named 're' 612 | * It must match ALL occurrences of numbers in a string. 613 | */ 614 | // let re = RegExp('\\d+', 'g'); // is compiled every time it is called 615 | // let re = /([0-9])+/g; 616 | let re = /\d+/g; 617 | return re; 618 | } 619 | function main() { 620 | const re = regexVar(); 621 | const s = readLine(); // 102, 1948948 and 1.3 and 4.5 622 | const r = s.match(re); 623 | for (const e of r) { 624 | console.log(e); 625 | } 626 | } 627 | output: 628 | 102 629 | 1948948 630 | 1 631 | 3 632 | 4 633 | 5 634 | 635 | 636 | 637 | 638 | Day 8 a: Create a Button 639 | css/button.css 640 | #btn { 641 | width: 96px; 642 | height: 48px; 643 | font-size: 24px; 644 | } 645 | 646 | js/button.js 647 | /* Create a button */ 648 | var buttonCounter = document.getElementById('btn'); 649 | 650 | /* What to do when the button is clicked */ 651 | buttonCounter.addEventListener('click', function() { 652 | /* Increment number on button's label by 1 */ 653 | buttonCounter.innerHTML = +(buttonCounter.innerHTML) + 1; 654 | }); 655 | 656 | index.html 657 | 658 | 659 | 660 | 661 | 662 | Button 663 | 664 | 665 | 666 | 667 | 669 | 670 | 671 | 672 | 673 | 674 | 675 | Day 8 b: Buttons Container 676 | css/buttonsGrid.css 677 | .buttonContainer { 678 | width: 75%; 679 | } 680 | .buttonContainer > .button { 681 | width: 30%; 682 | height: 48px; 683 | font-size: 24px; 684 | } 685 | 686 | js/buttonsGrid.js 687 | /* Create the button container */ 688 | var container = document.createElement('div'); 689 | /* Set the container's style class */ 690 | container.className = 'buttonContainer'; 691 | /* Set the container id */ 692 | container.id = 'btns'; 693 | 694 | /* Create an array of references to the buttons */ 695 | var buttons = [9]; 696 | for (var i = 0; i < 9; i++) { 697 | /* Create a button */ 698 | buttons[i] = document.createElement('button'); 699 | /* Set the button's id */ 700 | buttons[i].id = 'btn' + (i + 1); 701 | /* Set the button's display label */ 702 | buttons[i].innerHTML = (i + 1); 703 | /* Set the button's style class */ 704 | buttons[i].className = 'button'; 705 | /* Add button to div container */ 706 | container.appendChild(buttons[i]); 707 | } 708 | /* Add div container to document */ 709 | document.body.appendChild(container); 710 | 711 | /* Get next label in circular rotation */ 712 | function getNextLabel(currentLabel) { 713 | /* The list of values to iterate circularly */ 714 | var labels = [1, 4, 7, 8, 9, 6, 3, 2]; 715 | 716 | /* Get the index of the button's next label in labels */ 717 | var index = (labels.indexOf(+(currentLabel)) + 1) % labels.length; 718 | 719 | /* Return next label */ 720 | return labels[index]; 721 | } 722 | 723 | /* Update the label's innerHTML on click */ 724 | function updateLabel() { 725 | for (var i = 0; i < 4; i++) { 726 | buttons[i].innerHTML = getNextLabel(buttons[i].innerHTML); 727 | } 728 | for (var i = 5; i < 9; i++) { 729 | buttons[i].innerHTML = getNextLabel(buttons[i].innerHTML); 730 | } 731 | } 732 | 733 | btn5.addEventListener("click", function() { 734 | /* Rotate button labels */ 735 | updateLabel(); 736 | }); 737 | 738 | index.html 739 | 740 | 741 | 742 | 743 | Buttons Grid 744 | 745 | 746 | 747 | 748 | 749 | 750 | 751 | 752 | 753 | 754 | Day 9: Binary Calculator 755 | css/binaryCalculator.css 756 | body { 757 | width: 33% 758 | } 759 | #res { 760 | background-color: lightgray; 761 | border: solid; 762 | height: 48px; 763 | font-size: 20px; 764 | } 765 | #btns > .binaryButton { 766 | background-color: lightgreen; 767 | color: brown; 768 | } 769 | #btns > .operatorButton { 770 | background-color: black; 771 | color: red; 772 | } 773 | #btns > .utilityButton { 774 | background-color: darkgreen; 775 | color: white; 776 | } 777 | #btns > .button { 778 | width: 25%; 779 | height: 36px; 780 | font-size: 18px; 781 | /* This is just here to create the even spacing you'd see with HTML buttons */ 782 | margin: 0px; 783 | } 784 | 785 | js/binaryCalculator.js 786 | /* Creates Buttons and Lays Them Out */ 787 | 788 | var resultDiv = document.createElement('div'); 789 | resultDiv.id = 'res'; 790 | resultDiv.addEventListener('click', buttonClick); 791 | document.body.appendChild(resultDiv); 792 | 793 | var buttonsDiv = document.createElement('div'); 794 | buttonsDiv.id = 'btns'; 795 | document.body.appendChild(buttonsDiv); 796 | 797 | var ids = ['btn0', 'btn1', 'btnClr', 'btnEql', 'btnSum', 'btnSub', 'btnMul', 'btnDiv']; 798 | var innerHTMLs = ['0', '1', 'C', '=', '+', '-', '*', '/']; 799 | var styles = ['binaryButton', 'binaryButton', 'utilityButton', 'utilityButton', 'operatorButton', 'operatorButton', 'operatorButton', 'operatorButton']; 800 | 801 | for (var i = 0; i < ids.length; i++) { 802 | var button = document.createElement('button'); 803 | button.innerHTML = innerHTMLs[i]; 804 | button.id = ids[i]; 805 | button.className = 'button ' + styles[i]; 806 | button.addEventListener('click', buttonClick); 807 | buttonsDiv.appendChild(button); 808 | } 809 | 810 | 811 | /* Implements Calculator */ 812 | 813 | var operator = ''; 814 | 815 | function buttonClick(e) { 816 | var button = e.target || e.srcElement; 817 | 818 | /* If CLEAR, empty result box and last operator */ 819 | if (button.id == 'btnClr') { 820 | operator = ''; 821 | resultDiv.innerHTML = ''; 822 | } 823 | /* If not CLEAR and not EQUALS, add to expression */ 824 | else if (button.id != 'btnEql') { 825 | 826 | /* If operator was clicked */ 827 | if (button.id != 'btn0' && button.id != 'btn1') { 828 | /* If operator was previously clicked, evaluate expression */ 829 | if (operator != '') { 830 | evaluate(); 831 | } 832 | /* Set current operator */ 833 | operator = button.innerHTML; 834 | } 835 | 836 | /* Append pressed button to expression */ 837 | resultDiv.innerHTML += button.innerHTML; 838 | } 839 | // else btnEeql, evaluate expression 840 | else { 841 | evaluate(); 842 | } 843 | } 844 | 845 | function evaluate() { 846 | var operands = resultDiv.innerHTML.split(operator); 847 | /* */ 848 | resultDiv.innerHTML = ( 849 | Math.floor( 850 | eval(parseInt(operands[0], 2) 851 | + operator 852 | + parseInt(operands[1], 2)) 853 | ) 854 | ).toString(2); 855 | 856 | /* Clear previous operator */ 857 | operator = ''; 858 | } 859 | 860 | index.html 861 | 862 | 863 | 864 | 865 | 866 | Binary Calculator 867 | 868 | 869 | 870 | 871 | 872 | 873 | 874 | 875 | 876 | 877 | 878 | /* end */ 879 | --------------------------------------------------------------------------------