diff --git a/HackerRank Python Solutions/BasicDataTypes/Findingthepercentage.py b/HackerRank Python Solutions/BasicDataTypes/Findingthepercentage.py new file mode 100644 index 0000000..4ceabdc --- /dev/null +++ b/HackerRank Python Solutions/BasicDataTypes/Findingthepercentage.py @@ -0,0 +1,10 @@ +if __name__ == '__main__': + n = int(input()) + student_marks = {} + for _ in range(n): + name, *line = input().split() + scores = list(map(float, line)) + student_marks[name] = scores + query_name = input() + res = sum(student_marks[query_name]) / len(student_marks[name]) + print("{:.2f}".format(res)) diff --git a/HackerRank Python Solutions/BasicDataTypes/FindtheSecondLargestNumber.py b/HackerRank Python Solutions/BasicDataTypes/FindtheSecondLargestNumber.py new file mode 100644 index 0000000..4ed3a0e --- /dev/null +++ b/HackerRank Python Solutions/BasicDataTypes/FindtheSecondLargestNumber.py @@ -0,0 +1,5 @@ + +if __name__ == '__main__': + n = int(input()) + arr = map(int, input().split()) + print(sorted(set(arr), reverse=True)[1]) diff --git a/HackerRank Python Solutions/BasicDataTypes/ListComprehensions.py b/HackerRank Python Solutions/BasicDataTypes/ListComprehensions.py new file mode 100644 index 0000000..a37f8f0 --- /dev/null +++ b/HackerRank Python Solutions/BasicDataTypes/ListComprehensions.py @@ -0,0 +1,9 @@ + +if __name__ == '__main__': + x = int(input()) + y = int(input()) + z = int(input()) + n = int(input()) + ar = [[i, j, k] for i in range(x + 1) for j in range(y + 1) for k in + range(z + 1) if i + j + k != n] + print(ar) diff --git a/HackerRank Python Solutions/BasicDataTypes/Lists.py b/HackerRank Python Solutions/BasicDataTypes/Lists.py new file mode 100644 index 0000000..8a17443 --- /dev/null +++ b/HackerRank Python Solutions/BasicDataTypes/Lists.py @@ -0,0 +1,33 @@ + + +if __name__ == '__main__': + N = int(input()) + ar = [] + for i in range(0, N): + tmp_str = input() + tmp_str_ar = tmp_str.strip().split(" ") + cmd = tmp_str_ar[0] + if cmd == "print": + print(ar) + elif cmd == "sort": + ar.sort() + elif cmd == "reverse": + ar.reverse() + elif cmd == "pop": + ar.pop() + elif cmd == "count": + val = int(tmp_str_ar[1]) + ar.count(val) + elif cmd == "index": + val = int(tmp_str_ar[1]) + ar.index(val) + elif cmd == "remove": + val = int(tmp_str_ar[1]) + ar.remove(val) + elif cmd == "append": + val = int(tmp_str_ar[1]) + ar.append(val) + elif cmd == "insert": + pos = int(tmp_str_ar[1]) + val = int(tmp_str_ar[2]) + ar.insert(pos, val) diff --git a/HackerRank Python Solutions/BasicDataTypes/NestedLists.py b/HackerRank Python Solutions/BasicDataTypes/NestedLists.py new file mode 100644 index 0000000..9bb3039 --- /dev/null +++ b/HackerRank Python Solutions/BasicDataTypes/NestedLists.py @@ -0,0 +1,14 @@ + +if __name__ == '__main__': + students = [] + scores = [] + for _ in range(int(input())): + name = input() + score = float(input()) + student = [name, score] + students.append(student) + scores.append(score) + second_min_score = sorted(set(scores))[1] + student_names = sorted( + [student[0] for student in students if student[1] == second_min_score]) + print("\n".join(student_names)) diff --git a/HackerRank Python Solutions/BasicDataTypes/Tuples.py b/HackerRank Python Solutions/BasicDataTypes/Tuples.py new file mode 100644 index 0000000..9a5ddb5 --- /dev/null +++ b/HackerRank Python Solutions/BasicDataTypes/Tuples.py @@ -0,0 +1,6 @@ + +if __name__ == '__main__': + n = int(input()) + integer_list = map(int, input().split()) + t = tuple(integer_list) + print(hash(t)) diff --git a/HackerRank Python Solutions/BuiltIns/AnyorAll.py b/HackerRank Python Solutions/BuiltIns/AnyorAll.py new file mode 100644 index 0000000..593e37b --- /dev/null +++ b/HackerRank Python Solutions/BuiltIns/AnyorAll.py @@ -0,0 +1,4 @@ + +n = input() +ar = input().split() +print(all([int(i)>0 for i in ar]) and any([i==i[::-1] for i in ar])) diff --git a/HackerRank Python Solutions/BuiltIns/AthleteSort.py b/HackerRank Python Solutions/BuiltIns/AthleteSort.py new file mode 100644 index 0000000..e8cc88a --- /dev/null +++ b/HackerRank Python Solutions/BuiltIns/AthleteSort.py @@ -0,0 +1,14 @@ + + +if __name__ == '__main__': + n, m = map(int, input().split()) + + arr = [] + + for _ in range(n): + arr.append(list(map(int, input().rstrip().split()))) + + k = int(input()) + + for i in sorted(arr, key= lambda x: x[k]): + print(*i) diff --git a/HackerRank Python Solutions/BuiltIns/Input.py b/HackerRank Python Solutions/BuiltIns/Input.py new file mode 100644 index 0000000..e4a1b39 --- /dev/null +++ b/HackerRank Python Solutions/BuiltIns/Input.py @@ -0,0 +1,5 @@ + +if __name__ == "__main__": + x, k = map(int, input().strip().split()) + equation = input().strip() + print(eval(equation) == k) diff --git a/HackerRank Python Solutions/BuiltIns/PythonEvaluation.py b/HackerRank Python Solutions/BuiltIns/PythonEvaluation.py new file mode 100644 index 0000000..96e7d4e --- /dev/null +++ b/HackerRank Python Solutions/BuiltIns/PythonEvaluation.py @@ -0,0 +1,2 @@ + +eval(input()) diff --git a/HackerRank Python Solutions/BuiltIns/Zipped.py b/HackerRank Python Solutions/BuiltIns/Zipped.py new file mode 100644 index 0000000..f92b63c --- /dev/null +++ b/HackerRank Python Solutions/BuiltIns/Zipped.py @@ -0,0 +1,8 @@ + + +N, X = map(int, input().split()) +scores = [] +for _ in range(X): + scores.append(list(map(float, input().split()))) +for i in zip(*scores): + print(sum(i)/len(i)) diff --git a/HackerRank Python Solutions/BuiltIns/ginortS.py b/HackerRank Python Solutions/BuiltIns/ginortS.py new file mode 100644 index 0000000..2dfc323 --- /dev/null +++ b/HackerRank Python Solutions/BuiltIns/ginortS.py @@ -0,0 +1,4 @@ + + +s = input() +print(''.join(sorted(s, key=lambda x: (x.isdigit() and int(x)%2==0, x.isdigit(), x.isupper(), x.islower(), x)))) diff --git a/HackerRank Python Solutions/Classes/Class2FindtheTorsionalAngle.py b/HackerRank Python Solutions/Classes/Class2FindtheTorsionalAngle.py new file mode 100644 index 0000000..3f54b73 --- /dev/null +++ b/HackerRank Python Solutions/Classes/Class2FindtheTorsionalAngle.py @@ -0,0 +1,37 @@ +import math + + + +class Points: + def __init__(self, x, y, z): + self.x = x + self.y = y + self.z = z + + def __sub__(self, other): + return Points(self.x - other.x, self.y - other.y, self.z - other.z) + + def dot(self, other): + return self.x * other.x + self.y * other.y + self.z * other.z + + def absolute(self): + return math.sqrt(self.x * self.x + self.y * self.y + self.z * self.z) + + def cross(self, other): + return Points(self.y * other.z - self.z * other.y, + self.z * other.x - self.x * other.z, + self.x * other.y - self.y * other.x) + + +if __name__ == '__main__': + points = list() + for i in range(4): + a = list(map(float, input().split())) + points.append(a) + + a, b, c, d = Points(*points[0]), Points(*points[1]), Points(*points[2]), Points(*points[3]) + x = (b - a).cross(c - b) + y = (c - b).cross(d - c) + angle = math.acos(x.dot(y) / (x.absolute() * y.absolute())) + + print("%.2f" % math.degrees(angle)) diff --git a/HackerRank Python Solutions/Classes/ClassesDealingwithComplexNumbers.py b/HackerRank Python Solutions/Classes/ClassesDealingwithComplexNumbers.py new file mode 100644 index 0000000..c7fe76c --- /dev/null +++ b/HackerRank Python Solutions/Classes/ClassesDealingwithComplexNumbers.py @@ -0,0 +1,46 @@ + +import math + + + +class Complex(): + def __init__(self, real, imaginary): + self.real = real + self.imaginary = imaginary + + def __add__(self, no): + return Complex(self.real + no.real, self.imaginary + no.imaginary) + + def __sub__(self, no): + return Complex(self.real - no.real, self.imaginary - no.imaginary) + + def __mul__(self, no): + return Complex(self.real * no.real - self.imaginary * no.imaginary, self.real * no.imaginary + self.imaginary * no.real) + + def __truediv__(self, no): + divider = no.real ** 2 + no.imaginary ** 2 + return Complex((self.real * no.real + self.imaginary * no.imaginary)/divider, (self.imaginary * no.real - self.real * no.imaginary)/divider) + + def mod(self): + return Complex(math.sqrt(self.real ** 2 + self.imaginary ** 2), 0.00) + + def __str__(self): + if self.imaginary == 0: + result = "%.2f+0.00i" % (self.real) + elif self.real == 0: + if self.imaginary >= 0: + result = "0.00+%.2fi" % (self.imaginary) + else: + result = "0.00-%.2fi" % (abs(self.imaginary)) + elif self.imaginary > 0: + result = "%.2f+%.2fi" % (self.real, self.imaginary) + else: + result = "%.2f-%.2fi" % (self.real, abs(self.imaginary)) + return result + +if __name__ == '__main__': + c = map(float, input().split()) + d = map(float, input().split()) + x = Complex(*c) + y = Complex(*d) + print(*map(str, [x+y, x-y, x*y, x/y, x.mod(), y.mod()]), sep='\n') diff --git a/HackerRank Python Solutions/ClosuresandDecorators/Decorators2NameDirectory.py b/HackerRank Python Solutions/ClosuresandDecorators/Decorators2NameDirectory.py new file mode 100644 index 0000000..9273bbd --- /dev/null +++ b/HackerRank Python Solutions/ClosuresandDecorators/Decorators2NameDirectory.py @@ -0,0 +1,15 @@ + + +import operator +def person_lister(func): + def inner(people): + return [func(p) for p in sorted(people, key = lambda x: (int(x[2])))] + return inner + +@person_lister +def name_format(person): + return ("Mr. " if person[3] == "M" else "Ms. ") + person[0] + " " + person[1] + +if __name__ == '__main__': + people = [input().split() for i in range(int(input()))] + print(*name_format(people), sep='\n') diff --git a/HackerRank Python Solutions/ClosuresandDecorators/StandardizeMobileNumberUsingDecorators.py b/HackerRank Python Solutions/ClosuresandDecorators/StandardizeMobileNumberUsingDecorators.py new file mode 100644 index 0000000..9312b0f --- /dev/null +++ b/HackerRank Python Solutions/ClosuresandDecorators/StandardizeMobileNumberUsingDecorators.py @@ -0,0 +1,12 @@ + +# Enter your code here. Read input from STDIN. Print output to STDOUT +n=int(raw_input()) +ar=[] +for i in range(0,n): + tmp_str=raw_input() + tmp_str=tmp_str[len(tmp_str)-10:] + ar.append(tmp_str) + +ar.sort() +for i in range(0,len(ar)): + print "+91 "+ar[i][:5]+" "+ar[i][5:] diff --git a/HackerRank Python Solutions/Collections/CollectionsOrderedDict.py b/HackerRank Python Solutions/Collections/CollectionsOrderedDict.py new file mode 100644 index 0000000..b928bd9 --- /dev/null +++ b/HackerRank Python Solutions/Collections/CollectionsOrderedDict.py @@ -0,0 +1,15 @@ + +import collections, re +n = int(input()) +item_od = collections.OrderedDict() +for i in range(n): + record_list = re.split(r'(\d+)$',input().strip()) + item_name = record_list[0] + item_price = int(record_list[1]) + if item_name not in item_od: + item_od[item_name]=item_price + else: + item_od[item_name]=item_od[item_name]+item_price + +for i in item_od: + print(i+str(item_od[i])) diff --git a/HackerRank Python Solutions/Collections/Collectionsdeque.py b/HackerRank Python Solutions/Collections/Collectionsdeque.py new file mode 100644 index 0000000..181b277 --- /dev/null +++ b/HackerRank Python Solutions/Collections/Collectionsdeque.py @@ -0,0 +1,19 @@ + +import collections +n = int(input()) +d = collections.deque() +for i in range(n): + cmd = list(input().strip().split()) + opt = cmd[0] + if opt == 'pop': + d.pop() + elif opt == 'popleft': + d.popleft() + elif opt == 'append': + d.append(int(cmd[1])) + elif opt == 'appendleft': + d.appendleft(int(cmd[1])) +for i in d: + print(i,end=' ') + + diff --git a/HackerRank Python Solutions/Collections/Collectionsnamedtuple.py b/HackerRank Python Solutions/Collections/Collectionsnamedtuple.py new file mode 100644 index 0000000..64c1aa3 --- /dev/null +++ b/HackerRank Python Solutions/Collections/Collectionsnamedtuple.py @@ -0,0 +1,9 @@ + +n = int(input()) +col_list = list(input().split()) +marks_col = col_list.index("MARKS") +marks_list = [] +for i in range(n): + info_list = list(input().split()) + marks_list.append(float(info_list[marks_col])) +print(sum(marks_list)/n) diff --git a/HackerRank Python Solutions/Collections/DefaultDictTutorial.py b/HackerRank Python Solutions/Collections/DefaultDictTutorial.py new file mode 100644 index 0000000..cb78a3c --- /dev/null +++ b/HackerRank Python Solutions/Collections/DefaultDictTutorial.py @@ -0,0 +1,10 @@ + +from collections import defaultdict +d = defaultdict(list) +n,m=map(int,input().split()) +for i in range(n): + w = input() + d[w].append(str(i+1)) +for j in range(m): + w = input() + print(' '.join(d[w]) or -1) diff --git a/HackerRank Python Solutions/Collections/MostCommon.py b/HackerRank Python Solutions/Collections/MostCommon.py new file mode 100644 index 0000000..f255866 --- /dev/null +++ b/HackerRank Python Solutions/Collections/MostCommon.py @@ -0,0 +1,14 @@ + +import collections +s = sorted(input().strip()) +s_counter = collections.Counter(s).most_common() +''' +s_counter_length = len(s_counter) +for i in range(0,s_counter_length,1): + for j in range(i+1,s_counter_length,1): + if (s_counter[i][1] == s_counter[j][1]) and (ord(s_counter[j][0]) < ord(s_counter[i][0])): + s_counter[i],s_counter[j] = s_counter[j],s_counter[i] +''' +s_counter = sorted(s_counter,key = lambda x: (x[1] * -1,x[0])) +for i in range(0,3): + print(s_counter[i][0],s_counter[i][1]) diff --git a/HackerRank Python Solutions/Collections/PilingUp.py b/HackerRank Python Solutions/Collections/PilingUp.py new file mode 100644 index 0000000..306afda --- /dev/null +++ b/HackerRank Python Solutions/Collections/PilingUp.py @@ -0,0 +1,22 @@ + +from collections import deque +cas = int(input()) +for t in range(cas): + n = int(input()) + dq = deque(map(int,input().split())) + possible = True + element = (2**31)+1 + while dq: + left_element = dq[0] + right_element = dq[-1] + if left_element>=right_element and element>=left_element: + element = dq.popleft() + elif right_element>=left_element and element>=right_element: + element = dq.pop() + else: + possible = False + break + if possible: + print('Yes') + else: + print('No') diff --git a/HackerRank Python Solutions/Collections/WordOrder.py b/HackerRank Python Solutions/Collections/WordOrder.py new file mode 100644 index 0000000..c80aa8f --- /dev/null +++ b/HackerRank Python Solutions/Collections/WordOrder.py @@ -0,0 +1,13 @@ + +from collections import Counter, OrderedDict +class OrderedCounter(Counter,OrderedDict): + pass + +word_ar = [] +n = int(input()) +for i in range(n): + word_ar.append(input().strip()) +word_counter = OrderedCounter(word_ar) +print(len(word_counter)) +for word in word_counter: + print(word_counter[word],end=' ') diff --git a/HackerRank Python Solutions/Collections/collectionsCounter.py b/HackerRank Python Solutions/Collections/collectionsCounter.py new file mode 100644 index 0000000..145d33a --- /dev/null +++ b/HackerRank Python Solutions/Collections/collectionsCounter.py @@ -0,0 +1,11 @@ + +x = int(input()) +shoe_size = list(map(int,input().split())) +n = int(input()) +sell = 0 +for i in range(n): + s, p = map(int,input().split()) + if s in shoe_size: + sell = sell + p + shoe_size.remove(s) +print(sell) diff --git a/HackerRank Python Solutions/DateandTime/CalendarModule.py b/HackerRank Python Solutions/DateandTime/CalendarModule.py new file mode 100644 index 0000000..6969a50 --- /dev/null +++ b/HackerRank Python Solutions/DateandTime/CalendarModule.py @@ -0,0 +1,6 @@ + +import datetime +import calendar +m,d,y=map(int,input().split()) +input_date = datetime.date(y,m,d) +print(calendar.day_name[input_date.weekday()].upper()) diff --git a/HackerRank Python Solutions/DateandTime/TimeDelta.py b/HackerRank Python Solutions/DateandTime/TimeDelta.py new file mode 100644 index 0000000..7822bd6 --- /dev/null +++ b/HackerRank Python Solutions/DateandTime/TimeDelta.py @@ -0,0 +1,10 @@ + +import datetime +cas = int(input()) +for t in range(cas): + timestamp1 = input().strip() + timestamp2 = input().strip() + time_format = "%a %d %b %Y %H:%M:%S %z" + time_second1 = datetime.datetime.strptime(timestamp1,time_format) + time_second2 = datetime.datetime.strptime(timestamp2,time_format) + print(int(abs((time_second1-time_second2).total_seconds()))) diff --git a/HackerRank Python Solutions/Debugging/DefaultArguments.py b/HackerRank Python Solutions/Debugging/DefaultArguments.py new file mode 100644 index 0000000..5384fa4 --- /dev/null +++ b/HackerRank Python Solutions/Debugging/DefaultArguments.py @@ -0,0 +1,5 @@ + +def print_from_stream(n, stream=EvenStream()): + stream.__init__() + for _ in range(n): + print(stream.get_next()) diff --git a/HackerRank Python Solutions/Debugging/WordsScore.py b/HackerRank Python Solutions/Debugging/WordsScore.py new file mode 100644 index 0000000..b567198 --- /dev/null +++ b/HackerRank Python Solutions/Debugging/WordsScore.py @@ -0,0 +1,16 @@ + +def is_vowel(letter): + return letter in ['a', 'e', 'i', 'o', 'u', 'y'] + +def score_words(words): + score = 0 + for word in words: + num_vowels = 0 + for letter in word: + if is_vowel(letter): + num_vowels += 1 + if num_vowels % 2 == 0: + score += 2 + else: + score += 1 + return score diff --git a/HackerRank Python Solutions/ErrorsandExceptions/Exceptions.py b/HackerRank Python Solutions/ErrorsandExceptions/Exceptions.py new file mode 100644 index 0000000..fc3fc99 --- /dev/null +++ b/HackerRank Python Solutions/ErrorsandExceptions/Exceptions.py @@ -0,0 +1,8 @@ + +n = int(input()) +for i in range(n): + a,b=input().split() + try: + print(int(a)//int(b)) + except Exception as e: + print("Error Code: "+str(e)) diff --git a/HackerRank Python Solutions/ErrorsandExceptions/IncorrectRegex.py b/HackerRank Python Solutions/ErrorsandExceptions/IncorrectRegex.py new file mode 100644 index 0000000..b580d5d --- /dev/null +++ b/HackerRank Python Solutions/ErrorsandExceptions/IncorrectRegex.py @@ -0,0 +1,10 @@ + +import re +n = int(input()) +for i in range(n): + s = input() + try: + re.compile(s) + print(True) + except Exception as e: + print(False) diff --git a/HackerRank Python Solutions/HackerrankUtility/Hackerrank_Solution_Blank_File_Creator.py b/HackerRank Python Solutions/HackerrankUtility/Hackerrank_Solution_Blank_File_Creator.py new file mode 100644 index 0000000..abbb85b --- /dev/null +++ b/HackerRank Python Solutions/HackerrankUtility/Hackerrank_Solution_Blank_File_Creator.py @@ -0,0 +1,54 @@ + +import re,os,datetime,sys + +extension = '.py' +domain = 'Python' +author = 'JAPJEET SINGH' +created_date = datetime.datetime.today().strftime("%d %B %Y") +info_file_name = 'python_info.txt' + +def valid_name(given_name): + return re.sub(r'[^\w]','',given_name) + +def write_file_header(title, subdomain): + header_str = '\'\'\'\n' + header_str += 'Title : '+title+'\n' + header_str += 'Subdomain : '+subdomain+'\n' + header_str += 'Domain : '+domain+'\n' + header_str += 'Author : '+author+'\n' + header_str += 'Created : '+created_date+'\n' + header_str += '\'\'\'\n' + return header_str + +problem_list = '' +subdomain_name = '' + +info_file = open(info_file_name,"r") +info_file_lines = info_file.readlines() +info_file.close() +for line in info_file_lines: + line = line.strip() + if line == '': + continue + elif line[0] == '[': + problem_list = line + else: + subdomain_name = line + if subdomain_name != '' and problem_list != '': + folder_name = valid_name(subdomain_name) + if not os.path.exists(folder_name): + os.makedirs(folder_name) + title_ar = re.findall(r'("[^"]*")',problem_list) + title_ar_len = len(title_ar) + + for title in title_ar: + file_header_str = write_file_header(title[1:-1], subdomain_name) + title_valid = valid_name(title) + f = open(folder_name+'\\'+title_valid+extension,'w') + f.write(file_header_str) + f.close() + + print('Folder: '+str(folder_name)+'. Total files: '+str(title_ar_len)) + subdomain_name = '' + problem_list = '' + diff --git a/HackerRank Python Solutions/HackerrankUtility/Hackerrank_Solution_Lister.py b/HackerRank Python Solutions/HackerrankUtility/Hackerrank_Solution_Lister.py new file mode 100644 index 0000000..9bc9917 --- /dev/null +++ b/HackerRank Python Solutions/HackerrankUtility/Hackerrank_Solution_Lister.py @@ -0,0 +1,39 @@ + +import re,os,sys + +info_file_name = 'python_info.txt' + +def get_valid_name(given_name): + return re.sub(r'[^\w]','',given_name) + +problem_list = '' +subdomain_name = '' +extension = '.py' + +info_file = open(info_file_name,"r") +info_file_lines = info_file.readlines() +info_file.close() +output_file_name = 'solution_list.html' +f = open(output_file_name,'w') +f.write('\n') +for line in info_file_lines: + line = line.strip() + if line == '': + continue + elif line[0] == '[': + problem_list = line + else: + subdomain_name = line + if subdomain_name != '' and problem_list != '': + folder_name = get_valid_name(subdomain_name) + title_ar = re.findall(r'("[^"]*")',problem_list) + title_ar_len = len(title_ar) + f.write('- '+subdomain_name+'\n') + for title in title_ar: + filename = get_valid_name(title[1:-1]) + filepath = folder_name + '/' + filename+extension + f.write(' - ['+title[1:-1]+']('+filepath+')\n') + subdomain_name = '' + problem_list = '' +f.close() +print('List generated successfully. Open '+output_file_name+' to view.') diff --git a/HackerRank Python Solutions/HackerrankUtility/js_code.txt b/HackerRank Python Solutions/HackerrankUtility/js_code.txt new file mode 100644 index 0000000..ca7fec2 --- /dev/null +++ b/HackerRank Python Solutions/HackerrankUtility/js_code.txt @@ -0,0 +1,10 @@ +$ar = [] +$('.challengecard-title>.js-track-click').each(function(){ + $title = $(this).html().trim(); + $title = $title.toString().replace(/"/g,''); + $title = $title.replace(/'/g,''); + $ar.push($title); +}) +$subdomain = $('.current>a').html().trim(); +console.log($subdomain); +console.log($ar); diff --git a/HackerRank Python Solutions/HackerrankUtility/python_info.txt b/HackerRank Python Solutions/HackerrankUtility/python_info.txt new file mode 100644 index 0000000..eeafc4a --- /dev/null +++ b/HackerRank Python Solutions/HackerrankUtility/python_info.txt @@ -0,0 +1,51 @@ +Introduction +["Say Hello, World! With Python", "Reading Raw Input", "Python If-Else", "Arithmetic Operators", "Python: Division", "Loops", "Write a function", "Print Function"] + +Basic Data Types +["Lists", "Tuples", "List Comprehensions", "Find the Second Largest Number", "Nested Lists", "Finding the percentage"] + +Strings +["sWAP cASE", "String Split and Join", "Whats Your Name?", "Mutations", "Find a string", "String Validators", "Text Alignment", "Text Wrap", "Designer Door Mat", "String Formatting", "Alphabet Rangoli", "Capitalize!", "The Minion Game"] + +Sets +["Introduction to Sets", "Symmetric Difference", "No Idea!", "Set .add()", "Set .discard(), .remove() & .pop()", "Set .union() Operation", "Set .intersection() Operation", "Set .difference() Operation", "Set .symmetric_difference() Operation", "Set Mutations", "The Captains Room", "Check Subset", "Check Strict Superset"] + +Math +["Polar Coordinates", "Find Angle MBC", "Triangle Quest 2", "Mod Divmod", "Power - Mod Power", "Integers Come In All Sizes", "Triangle Quest"] + +Itertools +["itertools.product()", "itertools.permutations()", "itertools.combinations()", "itertools.combinations_with_replacement()", "Compress the String!", "Iterables and Iterators", "Maximize It!"] + +Collections +["collections.Counter()", "DefaultDict Tutorial", "Collections.namedtuple()", "Collections.OrderedDict()", "Word Order", "Collections.deque()", "Piling Up!", "Most Common"] + +Date and Time +["Calendar Module", "Time Delta"] + +Errors and Exceptions +["Exceptions", "Incorrect Regex"] + +Classes +["Classes: Dealing with Complex Numbers", "Class 2 - Find the Torsional Angle"] + +Built-Ins +["Zipped!", "Input()", "Python Evaluation", "Sort Data", "Any or All", "ginortS"] + +Python Functionals +["Map and Lambda Function", "Validating Email Addresses With a Filter"] + +Regex and Parsing +["Introduction to Regex Module", "Re.split()", "Group(), Groups() & Groupdict()", "Re.findall() & Re.finditer()", "Re.start() & Re.end()", "Regex Substitution", "Validating Roman Numerals", "Validating phone numbers", "Validating and Parsing Email Addresses", "Hex Color Code", "HTML Parser - Part 1", "HTML Parser - Part 2", "Detect HTML Tags, Attributes and Attribute Values", "Validating UID", "Validating Credit Card Numbers", "Validating Postal Codes", "Matrix Script"] + +XML +["XML 1 - Find the Score", "XML2 - Find the Maximum Depth"] + +Closures and Decorators +["Standardize Mobile Number Using Decorators", "Decorators 2 - Name Directory"] + +Numpy +["Arrays", "Shape and Reshape", "Transpose and Flatten", "Concatenate", "Zeros and Ones", "Eye and Identity", "Array Mathematics", "Floor, Ceil and Rint", "Sum and Prod", "Min and Max", "Mean, Var, and Std", "Dot and Cross", "Inner and Outer", "Polynomials", "Linear Algebra"] + +Debugging +["Words Score", "Default Arguments"] + diff --git a/HackerRank Python Solutions/HackerrankUtility/solution_list.html b/HackerRank Python Solutions/HackerrankUtility/solution_list.html new file mode 100644 index 0000000..4188a75 --- /dev/null +++ b/HackerRank Python Solutions/HackerrankUtility/solution_list.html @@ -0,0 +1,132 @@ + +- Introduction + - [Say Hello, World! With Python](Introduction/SayHelloWorldWithPython.py) + - [Reading Raw Input](Introduction/ReadingRawInput.py) + - [Python If-Else](Introduction/PythonIfElse.py) + - [Arithmetic Operators](Introduction/ArithmeticOperators.py) + - [Python: Division](Introduction/PythonDivision.py) + - [Loops](Introduction/Loops.py) + - [Write a function](Introduction/Writeafunction.py) + - [Print Function](Introduction/PrintFunction.py) +- Basic Data Types + - [Lists](BasicDataTypes/Lists.py) + - [Tuples](BasicDataTypes/Tuples.py) + - [List Comprehensions](BasicDataTypes/ListComprehensions.py) + - [Find the Second Largest Number](BasicDataTypes/FindtheSecondLargestNumber.py) + - [Nested Lists](BasicDataTypes/NestedLists.py) + - [Finding the percentage](BasicDataTypes/Findingthepercentage.py) +- Strings + - [sWAP cASE](Strings/sWAPcASE.py) + - [String Split and Join](Strings/StringSplitandJoin.py) + - [Whats Your Name?](Strings/WhatsYourName.py) + - [Mutations](Strings/Mutations.py) + - [Find a string](Strings/Findastring.py) + - [String Validators](Strings/StringValidators.py) + - [Text Alignment](Strings/TextAlignment.py) + - [Text Wrap](Strings/TextWrap.py) + - [Designer Door Mat](Strings/DesignerDoorMat.py) + - [String Formatting](Strings/StringFormatting.py) + - [Alphabet Rangoli](Strings/AlphabetRangoli.py) + - [Capitalize!](Strings/Capitalize.py) + - [The Minion Game](Strings/TheMinionGame.py) +- Sets + - [Introduction to Sets](Sets/IntroductiontoSets.py) + - [Symmetric Difference](Sets/SymmetricDifference.py) + - [No Idea!](Sets/NoIdea.py) + - [Set .add()](Sets/Setadd.py) + - [Set .discard(), .remove() & .pop()](Sets/Setdiscardremoveamppop.py) + - [Set .union() Operation](Sets/SetunionOperation.py) + - [Set .intersection() Operation](Sets/SetintersectionOperation.py) + - [Set .difference() Operation](Sets/SetdifferenceOperation.py) + - [Set .symmetric_difference() Operation](Sets/Setsymmetric_differenceOperation.py) + - [Set Mutations](Sets/SetMutations.py) + - [The Captains Room](Sets/TheCaptainsRoom.py) + - [Check Subset](Sets/CheckSubset.py) + - [Check Strict Superset](Sets/CheckStrictSuperset.py) +- Math + - [Polar Coordinates](Math/PolarCoordinates.py) + - [Find Angle MBC](Math/FindAngleMBC.py) + - [Triangle Quest 2](Math/TriangleQuest2.py) + - [Mod Divmod](Math/ModDivmod.py) + - [Power - Mod Power](Math/PowerModPower.py) + - [Integers Come In All Sizes](Math/IntegersComeInAllSizes.py) + - [Triangle Quest](Math/TriangleQuest.py) +- Itertools + - [itertools.product()](Itertools/itertoolsproduct.py) + - [itertools.permutations()](Itertools/itertoolspermutations.py) + - [itertools.combinations()](Itertools/itertoolscombinations.py) + - [itertools.combinations_with_replacement()](Itertools/itertoolscombinations_with_replacement.py) + - [Compress the String!](Itertools/CompresstheString.py) + - [Iterables and Iterators](Itertools/IterablesandIterators.py) + - [Maximize It!](Itertools/MaximizeIt.py) +- Collections + - [collections.Counter()](Collections/collectionsCounter.py) + - [DefaultDict Tutorial](Collections/DefaultDictTutorial.py) + - [Collections.namedtuple()](Collections/Collectionsnamedtuple.py) + - [Collections.OrderedDict()](Collections/CollectionsOrderedDict.py) + - [Word Order](Collections/WordOrder.py) + - [Collections.deque()](Collections/Collectionsdeque.py) + - [Piling Up!](Collections/PilingUp.py) + - [Most Common](Collections/MostCommon.py) +- Date and Time + - [Calendar Module](DateandTime/CalendarModule.py) + - [Time Delta](DateandTime/TimeDelta.py) +- Errors and Exceptions + - [Exceptions](ErrorsandExceptions/Exceptions.py) + - [Incorrect Regex](ErrorsandExceptions/IncorrectRegex.py) +- Classes + - [Classes: Dealing with Complex Numbers](Classes/ClassesDealingwithComplexNumbers.py) + - [Class 2 - Find the Torsional Angle](Classes/Class2FindtheTorsionalAngle.py) +- Built-Ins + - [Zipped!](BuiltIns/Zipped.py) + - [Input()](BuiltIns/Input.py) + - [Python Evaluation](BuiltIns/PythonEvaluation.py) + - [Sort Data](BuiltIns/SortData.py) + - [Any or All](BuiltIns/AnyorAll.py) + - [ginortS](BuiltIns/ginortS.py) +- Python Functionals + - [Map and Lambda Function](PythonFunctionals/MapandLambdaFunction.py) + - [Validating Email Addresses With a Filter](PythonFunctionals/ValidatingEmailAddressesWithaFilter.py) +- Regex and Parsing + - [Introduction to Regex Module](RegexandParsing/IntroductiontoRegexModule.py) + - [Re.split()](RegexandParsing/Resplit.py) + - [Group(), Groups() & Groupdict()](RegexandParsing/GroupGroupsampGroupdict.py) + - [Re.findall() & Re.finditer()](RegexandParsing/RefindallampRefinditer.py) + - [Re.start() & Re.end()](RegexandParsing/RestartampReend.py) + - [Regex Substitution](RegexandParsing/RegexSubstitution.py) + - [Validating Roman Numerals](RegexandParsing/ValidatingRomanNumerals.py) + - [Validating phone numbers](RegexandParsing/Validatingphonenumbers.py) + - [Validating and Parsing Email Addresses](RegexandParsing/ValidatingandParsingEmailAddresses.py) + - [Hex Color Code](RegexandParsing/HexColorCode.py) + - [HTML Parser - Part 1](RegexandParsing/HTMLParserPart1.py) + - [HTML Parser - Part 2](RegexandParsing/HTMLParserPart2.py) + - [Detect HTML Tags, Attributes and Attribute Values](RegexandParsing/DetectHTMLTagsAttributesandAttributeValues.py) + - [Validating UID](RegexandParsing/ValidatingUID.py) + - [Validating Credit Card Numbers](RegexandParsing/ValidatingCreditCardNumbers.py) + - [Validating Postal Codes](RegexandParsing/ValidatingPostalCodes.py) + - [Matrix Script](RegexandParsing/MatrixScript.py) +- XML + - [XML 1 - Find the Score](XML/XML1FindtheScore.py) + - [XML2 - Find the Maximum Depth](XML/XML2FindtheMaximumDepth.py) +- Closures and Decorators + - [Standardize Mobile Number Using Decorators](ClosuresandDecorators/StandardizeMobileNumberUsingDecorators.py) + - [Decorators 2 - Name Directory](ClosuresandDecorators/Decorators2NameDirectory.py) +- Numpy + - [Arrays](Numpy/Arrays.py) + - [Shape and Reshape](Numpy/ShapeandReshape.py) + - [Transpose and Flatten](Numpy/TransposeandFlatten.py) + - [Concatenate](Numpy/Concatenate.py) + - [Zeros and Ones](Numpy/ZerosandOnes.py) + - [Eye and Identity](Numpy/EyeandIdentity.py) + - [Array Mathematics](Numpy/ArrayMathematics.py) + - [Floor, Ceil and Rint](Numpy/FloorCeilandRint.py) + - [Sum and Prod](Numpy/SumandProd.py) + - [Min and Max](Numpy/MinandMax.py) + - [Mean, Var, and Std](Numpy/MeanVarandStd.py) + - [Dot and Cross](Numpy/DotandCross.py) + - [Inner and Outer](Numpy/InnerandOuter.py) + - [Polynomials](Numpy/Polynomials.py) + - [Linear Algebra](Numpy/LinearAlgebra.py) +- Debugging + - [Words Score](Debugging/WordsScore.py) + - [Default Arguments](Debugging/DefaultArguments.py) diff --git a/HackerRank Python Solutions/Introduction/ArithmeticOperators.py b/HackerRank Python Solutions/Introduction/ArithmeticOperators.py new file mode 100644 index 0000000..1354f5a --- /dev/null +++ b/HackerRank Python Solutions/Introduction/ArithmeticOperators.py @@ -0,0 +1,7 @@ + +if __name__ == '__main__': + a = int(input()) + b = int(input()) + print(a + b) + print(a - b) + print(a * b) diff --git a/HackerRank Python Solutions/Introduction/Loops.py b/HackerRank Python Solutions/Introduction/Loops.py new file mode 100644 index 0000000..9e14d97 --- /dev/null +++ b/HackerRank Python Solutions/Introduction/Loops.py @@ -0,0 +1,5 @@ + +if __name__ == '__main__': + n = int(input()) + for i in range(n): + print(i * i) diff --git a/HackerRank Python Solutions/Introduction/PrintFunction.py b/HackerRank Python Solutions/Introduction/PrintFunction.py new file mode 100644 index 0000000..dbea702 --- /dev/null +++ b/HackerRank Python Solutions/Introduction/PrintFunction.py @@ -0,0 +1,9 @@ + + +if __name__ == '__main__': + n = int(input()) + ar = range(1, n + 1) + for i in ar: + print(i, end="") + + diff --git a/HackerRank Python Solutions/Introduction/PythonDivision.py b/HackerRank Python Solutions/Introduction/PythonDivision.py new file mode 100644 index 0000000..f90e570 --- /dev/null +++ b/HackerRank Python Solutions/Introduction/PythonDivision.py @@ -0,0 +1,6 @@ + +if __name__ == '__main__': + a = int(input()) + b = int(input()) + print(a // b) + print(a / b) diff --git a/HackerRank Python Solutions/Introduction/PythonIfElse.py b/HackerRank Python Solutions/Introduction/PythonIfElse.py new file mode 100644 index 0000000..88b59d0 --- /dev/null +++ b/HackerRank Python Solutions/Introduction/PythonIfElse.py @@ -0,0 +1,10 @@ + +# !/bin/python3 + +import sys + +n = int(input()) +if n % 2 == 1 or n in range(5, 21): + print("Weird") +else: + print("Not Weird") diff --git a/HackerRank Python Solutions/Introduction/SayHelloWorldWithPython.py b/HackerRank Python Solutions/Introduction/SayHelloWorldWithPython.py new file mode 100644 index 0000000..d2c66e8 --- /dev/null +++ b/HackerRank Python Solutions/Introduction/SayHelloWorldWithPython.py @@ -0,0 +1,2 @@ + +print("Hello, World!") diff --git a/HackerRank Python Solutions/Introduction/Writeafunction.py b/HackerRank Python Solutions/Introduction/Writeafunction.py new file mode 100644 index 0000000..825c8f7 --- /dev/null +++ b/HackerRank Python Solutions/Introduction/Writeafunction.py @@ -0,0 +1,10 @@ + + +def is_leap(year): + leap = False + leap = (year % 400 == 0) or (year % 4 == 0 and year % 100 != 0) + return leap + + +year = int(input()) +print(is_leap(year)) diff --git a/HackerRank Python Solutions/Itertools/CompresstheString.py b/HackerRank Python Solutions/Itertools/CompresstheString.py new file mode 100644 index 0000000..58bfb44 --- /dev/null +++ b/HackerRank Python Solutions/Itertools/CompresstheString.py @@ -0,0 +1,13 @@ + +import itertools +s = input().strip() +s_unique_element = list(set(s)) +group = [] +key = [] +for k,g in itertools.groupby(s): + group.append(list(g)) + key.append(k) +for i in range(len(group)): + group_length = len(group[i]) + k = int(key[i]) + print(tuple((group_length,k)),end=' ') diff --git a/HackerRank Python Solutions/Itertools/IterablesandIterators.py b/HackerRank Python Solutions/Itertools/IterablesandIterators.py new file mode 100644 index 0000000..71dc9f5 --- /dev/null +++ b/HackerRank Python Solutions/Itertools/IterablesandIterators.py @@ -0,0 +1,8 @@ + +from itertools import combinations +n = int(input()) +ar = input().split() +k = int(input()) +comb_list = list(combinations(ar,k)) +a_list = [e for e in comb_list if 'a' in e] +print(len(a_list) / len(comb_list)) diff --git a/HackerRank Python Solutions/Itertools/MaximizeIt.py b/HackerRank Python Solutions/Itertools/MaximizeIt.py new file mode 100644 index 0000000..686ef44 --- /dev/null +++ b/HackerRank Python Solutions/Itertools/MaximizeIt.py @@ -0,0 +1,15 @@ + +import itertools + +k, m = map(int,input().split()) + +main_ar = [] +for i in range(k): + ar = list(map(int,input().split())) + main_ar.append(ar[1:]) + +all_combination = itertools.product(*main_ar) +result = 0 +for single_combination in all_combination: + result = max(sum([x*x for x in single_combination])%m,result) +print(result) diff --git a/HackerRank Python Solutions/Itertools/itertoolscombinations.py b/HackerRank Python Solutions/Itertools/itertoolscombinations.py new file mode 100644 index 0000000..cb20ae1 --- /dev/null +++ b/HackerRank Python Solutions/Itertools/itertoolscombinations.py @@ -0,0 +1,8 @@ + +from itertools import * +s,n = input().split() +n = int(n) + 1 +s = sorted(s) +for i in range(1,n): + for j in combinations(s,i): + print(''.join(j)) diff --git a/HackerRank Python Solutions/Itertools/itertoolscombinations_with_replacement.py b/HackerRank Python Solutions/Itertools/itertoolscombinations_with_replacement.py new file mode 100644 index 0000000..85cbeb8 --- /dev/null +++ b/HackerRank Python Solutions/Itertools/itertoolscombinations_with_replacement.py @@ -0,0 +1,7 @@ + +from itertools import * +s,n = input().split() +n = int(n) +s = sorted(s) +for j in combinations_with_replacement(s,n): + print(''.join(j)) diff --git a/HackerRank Python Solutions/Itertools/itertoolspermutations.py b/HackerRank Python Solutions/Itertools/itertoolspermutations.py new file mode 100644 index 0000000..b1c5e1b --- /dev/null +++ b/HackerRank Python Solutions/Itertools/itertoolspermutations.py @@ -0,0 +1,6 @@ + +import itertools +s,n = list(map(str,input().split(' '))) +s = sorted(s) +for p in list(itertools.permutations(s,int(n))): + print(''.join(p)) diff --git a/HackerRank Python Solutions/Itertools/itertoolsproduct.py b/HackerRank Python Solutions/Itertools/itertoolsproduct.py new file mode 100644 index 0000000..e9e3ea5 --- /dev/null +++ b/HackerRank Python Solutions/Itertools/itertoolsproduct.py @@ -0,0 +1,7 @@ + +import itertools +ar1 = list(map(int,input().split())) +ar2 = list(map(int,input().split())) +cross = list(itertools.product(ar1,ar2)) +for i in cross: + print(i,end=' ') diff --git a/HackerRank Python Solutions/Math/FindAngleMBC.py b/HackerRank Python Solutions/Math/FindAngleMBC.py new file mode 100644 index 0000000..ccbd49a --- /dev/null +++ b/HackerRank Python Solutions/Math/FindAngleMBC.py @@ -0,0 +1,16 @@ + +import math +ab = float(input()) +bc = float(input()) +ac = math.sqrt((ab*ab)+(bc*bc)) +bm = ac / 2.0 +mc = bm +#let, +b = mc +c = bm +a = bc +#where b=c +angel_b_radian = math.acos(a / (2*b)) +angel_b_degree = int(round((180 * angel_b_radian) / math.pi)) +output_str = str(angel_b_degree)+'°' +print(output_str) diff --git a/HackerRank Python Solutions/Math/IntegersComeInAllSizes.py b/HackerRank Python Solutions/Math/IntegersComeInAllSizes.py new file mode 100644 index 0000000..290d98a --- /dev/null +++ b/HackerRank Python Solutions/Math/IntegersComeInAllSizes.py @@ -0,0 +1,7 @@ + +# Enter your code here. Read input from STDIN. Print output to STDOUT +a=int(raw_input()) +b=int(raw_input()) +c=int(raw_input()) +d=int(raw_input()) +print pow(a,b)+pow(c,d) diff --git a/HackerRank Python Solutions/Math/ModDivmod.py b/HackerRank Python Solutions/Math/ModDivmod.py new file mode 100644 index 0000000..507221e --- /dev/null +++ b/HackerRank Python Solutions/Math/ModDivmod.py @@ -0,0 +1,8 @@ + +# Enter your code here. Read input from STDIN. Print output to STDOUT +a=int(raw_input()) +b=int(raw_input()) +d=divmod(a,b) +print d[0] +print d[1] +print d diff --git a/HackerRank Python Solutions/Math/PolarCoordinates.py b/HackerRank Python Solutions/Math/PolarCoordinates.py new file mode 100644 index 0000000..49e24dc --- /dev/null +++ b/HackerRank Python Solutions/Math/PolarCoordinates.py @@ -0,0 +1,6 @@ + +import cmath +z = complex(input()) +p = cmath.polar(z) +print(p[0]) +print(p[1]) diff --git a/HackerRank Python Solutions/Math/PowerModPower.py b/HackerRank Python Solutions/Math/PowerModPower.py new file mode 100644 index 0000000..4f45728 --- /dev/null +++ b/HackerRank Python Solutions/Math/PowerModPower.py @@ -0,0 +1,7 @@ + +# Enter your code here. Read input from STDIN. Print output to STDOUT +a=int(raw_input()) +b=int(raw_input()) +c=int(raw_input()) +print pow(a,b) +print pow(a,b,c) diff --git a/HackerRank Python Solutions/Math/TriangleQuest.py b/HackerRank Python Solutions/Math/TriangleQuest.py new file mode 100644 index 0000000..3970da3 --- /dev/null +++ b/HackerRank Python Solutions/Math/TriangleQuest.py @@ -0,0 +1,3 @@ + +for i in range(1,input()): #More than 2 lines will result in 0 score. Do not leave a blank line also + print i*((10**i-1)//9) diff --git a/HackerRank Python Solutions/Math/TriangleQuest2.py b/HackerRank Python Solutions/Math/TriangleQuest2.py new file mode 100644 index 0000000..6efe3f7 --- /dev/null +++ b/HackerRank Python Solutions/Math/TriangleQuest2.py @@ -0,0 +1,3 @@ + +for i in range(1,int(raw_input())+1): #More than 2 lines will result in 0 score. Do not leave a blank line also + print(((10**i - 1)//9)**2