14 min readJun 27, 2023
HackerRank Python | Easy
1. Python If-Else
Solution:
import math
import os
import random
import re
import sys
if __name__ == '__main__':
n = int(input().strip())
if n % 2 == 1:
print("Weird")
elif n % 2 == 0 and n in range(2,5) :
print("Not Weird")
elif n % 2 == 0 and n in range(6, 21):
print("Weird")
elif n % 2 == 0 and n > 20:
print("Not Weird")
else:
pass
2. Arithmetic Operators
Solution:
if __name__ == '__main__':
a = int(input())
b = int(input())
print(a+b)
print(a-b)
print(a*b)
3. Python: Division
Solution:
if __name__ == '__main__':
a = int(input())
b = int(input())
print(a//b) #integer division
print(a/b) #float division
4.Loops
Solution:
if __name__ == '__main__':
n = int(input())
for i in range(n) :
print(i**2)
5. Print Function
Solution:
if __name__ == '__main__':
n = int(input())
if n>=1 and n<=150:
for i in range(1,n+1):
print(i, end="")
else:
pass
6. Find the Runner-Up Score!
Solution:
if __name__ == '__main__':
n = int(input())
arr = map(int, input().split())
nlist = list(arr)
score = []
for i in nlist:
if i < max(nlist):
score.append(i)
score.sort(reverse=True) #sorting list in descending order
print(score[0])
7. Nested Lists
Solution:
if __name__ == '__main__':
l = []
for _ in range(int(input())):
name = input()
score = float(input())
l.append([name,score]) #nested list [[],[],..,[]]
l2=[]
for i in l: #as l is a nested list, i would be a list
l2.append(i[1]) #i[1] represents the score in a list
l2=sorted(list(set(l2))) #set removes the duplicates->sorted them in descending order
l3=[]
for i in l:
if i[1] == l2[1]: #if score(i[1]) equals the second highest score(l2[1])
l3.append(i[0]) #add the name according to the score
print(*sorted(l3), sep='\n') #* unpacks iterable arguments.
8. Finding the percentage
Solution:
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()
marks = student_marks[query_name]
avg_marks = sum(marks)/ len(marks)
print('{:.2f}'.format(avg_marks))
9. Lists
Solution:
if __name__ == '__main__':
N = int(input())
inputlist = []
for i in range (N):
cmmd = input()
lst = cmmd.split()
if lst[0]=="insert":
inputlist.insert(int(lst[1]),int(lst[2]))
elif lst[0]=="remove":
inputlist.remove(int(lst[1]))
elif lst[0]=="append":
inputlist.append(int(lst[1]))
elif lst[0]=="sort":
inputlist.sort()
elif lst[0]=="pop":
inputlist.pop()
elif lst[0]=="reverse":
inputlist.reverse()
elif lst[0]=="print":
print(inputlist)
10. Tuples
Solution:
#Pypy3
if __name__ == '__main__':
n = int(input())
integer_list = map(int, input().split())
print(hash(tuple(integer_list)))
11. sWAP cASE
Solution:
def swap_case(s):
return s.swapcase()
if __name__ == '__main__':
s = input()
result = swap_case(s)
print(result)
12. String Split and Join
Solution:
def split_and_join(line):
# write your code here
L = line.split()
return "-".join(L)
if __name__ == '__main__':
line = input()
result = split_and_join(line)
print(result)
13. What’s Your Name?
Solution:
#
# Complete the 'print_full_name' function below.
#
# The function is expected to return a STRING.
# The function accepts following parameters:
# 1. STRING first
# 2. STRING last
#
def print_full_name(first, last):
# Write your code here
print("Hello "+first+" "+last+"! You just delved into python.")
if __name__ == '__main__':
first_name = input()
last_name = input()
print_full_name(first_name, last_name)
14. Mutations
Solution:
def mutate_string(string, position, character):
# Write your code here
l = list(string)
l[position] = character
string = ''.join(l)
return string
if __name__ == '__main__':
s = input()
i, c = input().split()
s_new = mutate_string(s, int(i), c)
print(s_new)
15. Find a string
Solution:
def count_substring(string, sub_string):
return
if __name__ == '__main__':
string = input().strip()
sub_string = input().strip()
count = count_substring(string, sub_string)
print(count)
def count_substring(string, sub_string, res=0):
if sub_string not in string:
return res
res = res + 1
return count_substring(string[string.index(sub_string)+1:], sub_string, res)
if __name__ == '__main__':
string = input().strip()
sub_string = input().strip()
count = count_substring(string, sub_string)
print(count)
16. Text Alignment
Solution:
#Replace all ______ with rjust, ljust or center.
thickness = int(input()) #This must be an odd number
c = 'H'
#Top Cone
for i in range(thickness):
print((c*i).______(thickness-1)+c+(c*i).______(thickness-1))
#Top Pillars
for i in range(thickness+1):
print((c*thickness).______(thickness*2)+(c*thickness).______(thickness*6))
#Middle Belt
for i in range((thickness+1)//2):
print((c*thickness*5).______(thickness*6))
#Bottom Pillars
for i in range(thickness+1):
print((c*thickness).______(thickness*2)+(c*thickness).______(thickness*6))
#Bottom Cone
for i in range(thickness):
print(((c*(thickness-i-1)).______(thickness)+c+(c*(thickness-i-1)).______(thickness)).______(thickness*6))
thickness = int(input()) #This must be an odd number
c = 'H'
#Top Cone
for i in range(thickness):
print((c*i).rjust(thickness-1)+c+(c*i).ljust(thickness-1))
#Top Pillars
for i in range(thickness+1):
print((c*thickness).center(thickness*2)+(c*thickness).center(thickness*6))
#Middle Belt
for i in range((thickness+1)//2):
print((c*thickness*5).center(thickness*6))
#Bottom Pillars
for i in range(thickness+1):
print((c*thickness).center(thickness*2)+(c*thickness).center(thickness*6))
#Bottom Cone
for i in range(thickness):
print(((c*(thickness-i-1)).rjust(thickness)+c+(c*(thickness-i-1)).ljust(thickness)).rjust(thickness*6))
17. Text Wrap
Solution:
import textwrap
def wrap(string, max_width):
return
if __name__ == '__main__':
string, max_width = input(), int(input())
result = wrap(string, max_width)
print(result)
import textwrap
def wrap(string, max_width):
result = textwrap.fill(string,width=max_width)
return result
if __name__ == '__main__':
string, max_width = input(), int(input())
result = wrap(string, max_width)
print(result)
18. Designer Door Mat
Solution:
# Enter your code here. Read input from STDIN. Print output to STDOUT
M,N = map(int, input().split())
for i in range(M):
if i < (M/2)-1: print(('.|.'*(2*i+1)).center(N, '-'))
elif i > (M/2): print(('.|.'*(2*(M-i)-1)).center(N, '-'))
else: print(('WELCOME').center(N, '-'))
19. String Formatting
def print_formatted(number):
# your code goes here
len_rjust = len(bin(number)[2:])
for i in range(1, number+1):
decimal = str(i).rjust(len_rjust)
octal = str(oct(i)[2:]).rjust(len_rjust)
hexadecimal = str(hex(i)[2:]).upper().rjust(len_rjust)
binary = str(bin(i)[2:]).rjust(len_rjust)
print(f"{decimal} {octal} {hexadecimal} {binary}")
if __name__ == '__main__':
n = int(input())
print_formatted(n)
20. Alphabet Rangoli
Solution:
def print_rangoli(size):
# your code goes here
w = (size - 1) * 4 + 1
for i in range(1, 2 * size + 1, 2):
r = int((i-1)/2)
x = ''
for j in range(-r, r+1):
x += chr(96 + size - r + abs(j))
res = '-'.join(x)
print(res.center(w, '-'))
for i in range(7, 2 * size + 5, 2):
r = int(size - (i - 1) / 2 + 1)
x = ''
for j in range(-r, r + 1):
x += chr(96 + size - r + abs(j))
res = '-'.join(x)
print(res.center(w, '-'))
if __name__ == '__main__':
n = int(input())
print_rangoli(n)
21. Capitalize!
#!/bin/python3
import math
import os
import random
import re
import sys
# Complete the solve function below.
def solve(s):
names_list = s.split()
cap_name = s
for name in names_list:
cap_name = cap_name.replace(name,name.capitalize())
return cap_name
if __name__ == '__main__':
fptr = open(os.environ['OUTPUT_PATH'], 'w')
s = input()
result = solve(s)
fptr.write(result + '\n')
fptr.close()
22. itertools.product()
Solution:
# Enter your code here. Read input from STDIN. Print output to STDOUT
from itertools import product
A = list(map(int,input().split()))
B = list(map(int,input().split()))
A = set(A)
B = set(B)
print(*product(A,B))
23. collections.Counter()
Solution:
# Enter your code here. Read input from STDIN. Print output to STDOUT
num_shoes = int(input())
num_size = list(map(int, input().split()))
num_cust = int(input())
count = 0
for i in range(num_cust):
m, n = map(int, input().split())
if m in num_size:
count = n + count
num_size.remove(m)
print(count)
24. itertolls.permutations()
Solution:
# Enter your code here. Read input from STDIN. Print output to STDOUT
from itertools import permutations
S,k = input().split()
k = int(k)
for i in sorted(list(permutations(S,k))) :
print(''.join(i))
25. Polar Coordinates
Solution:
# Enter your code here. Read input from STDIN. Print output to STDOUT
import cmath
a = complex(input())
print(abs(a))
print(cmath.phase(a))
26. Introduction to Sets
Solution:
def average(array):
# your code goes here
return round(sum(set(array))/len(set(array)),3)
if __name__ == '__main__':
n = int(input())
arr = list(map(int, input().split()))
result = average(arr)
print(result)
27. DefaultDict Tutorial
Solution:
# Enter your code here. Read input from STDIN. Print output to STDOUT
from collections import defaultdict
n, m = list(map(int, input().split()))
A = defaultdict(list)
for i in range(n):
A[input()].append(i + 1)
for _ in range(m):
print(*A.get(input(), [-1]))
28. Calendar Module
Solution:
# Enter your code here. Read input from STDIN. Print output to STDOUT
import calendar
m, d , y = map(int,input().split())
name = calendar.day_name[calendar.weekday(y,m,d)]
print(name.upper())
29. Exception
Solution:
# Enter your code here. Read input from STDIN. Print output to STDOUT
h=int(input())
for i in range(h):
try:
a, b = map(int,input().split())
print(a//b)
except ValueError as e:
print("Error Code:",e)
except ZeroDivisionError as e:
print("Error Code:",e)
30. Collections.namedtuple()
Solution:
from collections import namedtuple
n = int(input())
heading = namedtuple('heading', input().split())
total_marks = 0
for i in range(n):
xyz = heading(*input().split())
total_marks += int(xyz.MARKS)
print(round(total_marks/n, 2))
31. Collections.OrderedDict()
Solution:
# Enter your code here. Read input from STDIN. Print output to STDOUT
from collections import OrderedDict
sales = OrderedDict()
for _ in range(int(input())):
name, price = input().rsplit(" ", 1)
sales[name] = sales.get(name, 0) + int(price)
for name, price in sales.items():
print(f"{name} {price}")
32. Symmetric Difference
Solution:
# Enter your code here. Read input from STDIN. Print output to STDOUT
m = input()
M = set(map(int,input().split()))
n = input()
N = set(map(int,input().split()))
O = M.symmetric_difference(N)
O = sorted(O)
for i in O :
print(i)
33. itertools.combinations()
Solution:
# Enter your code here. Read input from STDIN. Print output to STDOUT
from itertools import combinations
S,K = input().split()
K = int(K)
S = sorted(S)
for i in range(1,K+1):
for combination in combinations(S,i):
print("".join(combination))
34. Incorrect Regex
Solution:
# Enter your code here. Read input from STDIN. Print output to STDOUT
#Pypy3
import re
for _ in range(int(input())):
try:
re.compile(input())
print("True")
except re.error:
print("False")
35. Set .add()
Solution:
# Enter your code here. Read input from STDIN. Print output to STDOUT
n = int(input())
S = set()
for _ in range(n) :
c = input()
S.add(c)
print(len(S))
36. itertools.combinations_with_replacement()
Solution:
# Enter your code here. Read input from STDIN. Print output to STDOUT
from itertools import combinations_with_replacement
S, k = input().split()
S = S.upper()
k = int(k)
for i in list(combinations_with_replacement(sorted(S),k)) :
print(''.join(i))
37. Set .discard(), .remove() & .pop()
Solution:
n = int(input())
s = set(map(int, input().split()))
# Enter your code here.
N = int(input())
for _ in range(N) :
c = input().split()
if c[0] == 'pop':
s.pop()
elif c[0] == 'remove':
s.remove(int(c[1]))
elif c[0] == 'discard':
s.discard(int(c[1]))
print(sum(s))
38. Collections.deque()
Solution:
# Enter your code here. Read input from STDIN. Print output to STDOUT
from collections import deque
d = deque()
for i in range(int(input())):
a,*n = input().split()
exec(f'd.{a}({str(*n)})')
print(*d)
39. Set .union() Operation
Solution:
# Enter your code here. Read input from STDIN. Print output to STDOUT
n = int(input())
N = set(map(int,input().split()))
m = int(input())
M = set(map(int,input().split()))
print(len(N.union(M)))
40. Set .intersection() Operation
Solution:
n = int(input())
N = set(map(int,input().split()))
m = int(input())
M = set(map(int,input().split()))
print(len(N.intersection(M)))
41. Mov Divmod
Solution:
# Enter your code here. Read input from STDIN. Print output to STDOUT
a, b = int(input()), int(input())
print(a//b, a%b, divmod(a,b), sep = '\n')
42. Power — Mod Power
Solution:
# Enter your code here. Read input from STDIN. Print output to STDOUT
a = int(input())
b = int(input())
m = int(input())
print(pow(a,b))
print(pow(a,b,m))
43. Set .difference() Operation
Solution:
# Enter your code here. Read input from STDIN. Print output to STDOUT
n = int(input())
N = set(map(int,input().split()))
m = int(input())
M = set(map(int,input().split()))
print(len(N.difference(M)))
44. Integers Come In All Sizes
Solution:
# Enter your code here. Read input from STDIN. Print output to STDOUT
print(int(input())** int(input())+int(input())** int(input()))
45. Set .symmetric_difference() Operation
Solution:
# Enter your code here. Read input from STDIN. Print output to STDOUT
n = int(input())
N = set(map(int,input().split()))
m = int(input())
M = set(map(int,input().split()))
print(len(N.symmetric_difference(M)))
46. Set Mutations
Solution:
# Enter your code here. Read input from STDIN. Print output to STDOUT
A = int(input())
A_list = set(input().split())
N = int(input())
for i in range(N):
cmd,arg_len = input().split()
arg = set(input().split())
if cmd =="intersection_update":
A_list.intersection_update(arg)
elif cmd == "update":
A_list.update(arg)
elif cmd == "symmetric_difference_update":
A_list.symmetric_difference_update(arg)
elif cmd == "difference_update":
A_list.difference_update(arg)
print(sum(int(i) for i in A_list))
47. The Captain’s Room
Solution:
# Enter your code here. Read input from STDIN. Print output to STDOUT
K = int(input())
rooms = list(map(int,input().split()))
from collections import Counter
num_count = Counter(rooms)
for n,c in num_count.items() :
if c == 1 :
print(n)
48. Check Subset
Solution:
# Enter your code here. Read input from STDIN. Print output to STDOUT
T = int(input())
for _ in range(T) :
NA = int(input())
A = set(map(int,input().split()))
NB = int(input())
B = set(map(int,input().split()))
if A.issubset(B) :
print('True')
else :
print('False')
49. Check Strict Superset
Solution:
# Enter your code here. Read input from STDIN. Print output to STDOUT
A = set(map(int,input().split()))
n = int(input())
for _ in range(n) :
B = set(map(int,input().split()))
if (A > B) == False :
print('False')
break
else :
print('True')
50. Class 2 — Find the Torsional Angle
Solution:
import math
class Points(object):
def __init__(self, x, y, z):
self.x=x
self.y=y
self.z=z
def __sub__(self, no):
return Points(self.x - no.x, self.y - no.y,self.z - no.z)
def dot(self, no):
return self.x*no.x + self.y*no.y + self.z*no.z
def cross(self, no):
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))
def absolute(self):
return pow((self.x ** 2 + self.y ** 2 + self.z ** 2), 0.5)
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))
51. Zipped!
Solution:
# Enter your code here. Read input from STDIN. Print output to STDOUT
import math
N , X = list(map(int , input().split(" ")))
temp = []
for i in range(X):
temp.append( list(map(float , input().split(" "))) )
for j in range(N):
sum = 0
for i in range(X):
sum = sum + temp[i][j]
print(sum/X)
52. Input()
Solution:
# Enter your code here. Read input from STDIN. Print output to STDOUT
x, k = input().split()
result = eval(input().replace("x", x))
print(result == int(k))
53. Python Evaluation
Solution:
# Enter your code here. Read input from STDIN. Print output to STDOUT
eval(input())
54. Any or All
Solution:
# Enter your code here. Read input from STDIN. Print output to STDOUT
print(input() and (lambda ns: all(int(n) > 0 for n in ns) and
any(n == n[::-1] for n in ns))(input().split()))
55. Delete Floating Point Number
Solution:
# Enter your code here. Read input from STDIN. Print output to STDOUT
T = int(input())
for i in range(T):
try:
checkfloat = float(input())
if checkfloat == 0:
a = float("big brain time")
except:
print(False)
else:
print(True)
56. Map and Lambda Function
Solution:
cube = lambda x:x**3 # complete the lambda function
def fibonacci(n):
# return a list of fibonacci numbers
lis = [0, 1]
for i in range(2, n):
lis.append(lis[i - 2] + lis[i - 1])
return (lis[0:n])
if __name__ == '__main__':
n = int(input())
print(list(map(cube, fibonacci(n))))
57. Re.split()
Solution:
regex_pattern = r"[,.]" #just added [,.] between r""
import re
print("\n".join(re.split(regex_pattern, input())))
58. Group(), Groups() & Groupdict()
Solution:
# Enter your code here. Read input from STDIN. Print output to STDOUT
S = input()
x = ''
num = False
for i in S:
if i.isalnum() == True:
if i == x:
print(x)
num = True
break
else:
x = i
if num == False:
print("-1")
59. Re.findall() & Re.finditer()
Solution:
# Enter your code here. Read input from STDIN. Print output to STDOUT
import re
r = re.findall(r"(?<=[qwrtypsdfghjklzxcvbnm])[AEIOUaeiou]{2,}(?=[qwrtypsdfghjklzxcvbnm])",input())
print("\n".join(r) if r else "-1")
60. Re.start() & Re.end()
Solution:
# Enter your code here. Read input from STDIN. Print output to STDOUT
import re
s = input()
k = input()
m = re.finditer(f"(?=({k}))", s)
if re.search(k, s):
for x in m:
print((x.start(1), x.end(1)-1))
else:
print((-1, -1))
61. Validating Roman Numerals
Solution:
regex_pattern = r"M{,3}(D?C{,3}|C[DM])?(L?X{,3}|X[LC])?(V?I{,3}|I[VX])?$"
# Do not delete 'r'.
#Just added strings between r""
import re
print(str(bool(re.match(regex_pattern, input()))))
62. Validating phone numbers
Solution:
# Enter your code here. Read input from STDIN. Print output to STDOUT
import re
regex_pattern = r"^[789]\d{9}$"
for i in range(int(input())):
number = input()
# print(number)
if bool(re.match(regex_pattern,number)):
print("YES")
else:
print("NO")
63. Validating and Parsing Email Addresses
Solution:
# Enter your code here. Read input from STDIN. Print output to STDOUT
import re
n = int(input())
pattern = r'[a-zA-Z]+\s<[a-z]+[\w._-]{0,}@[a-z]+\.[a-z]{1,3}>'
for line in range(n):
line = input()
r = re.search(pattern, line)
if r:
print(line)
64. Hex Color Code
Solution:
# Enter your code here. Read input from STDIN. Print output to STDOUT
import re
n = int(input())
pattern = r'\#[a-fA-F0-9]{3,6}(?=[;,)])'
for _ in range(n):
line = input()
match = re.findall(pattern, line)
if match:
print(*match, sep='\n')
65. HTML Parser — Part 1
Solution:
# Enter your code here. Read input from STDIN. Print output to STDOUT
from html.parser import HTMLParser
class MyHTMLParser(HTMLParser):
def handle_starttag(self, tag, attrs):
print("Start :", tag)
[print(f'-> {i[0]} > {i[1]}') for i in attrs]
def handle_endtag(self, tag):
print ("End :", tag)
def handle_startendtag(self, tag, attrs):
print ("Empty :", tag)
[print(f'-> {i[0]} > {i[1]}') for i in attrs]
parser = MyHTMLParser()
for _ in range(int(input())):
parser.feed(input())
66. HTML Parser — Part 2
Solution:
from html.parser import HTMLParser
class MyHTMLParser(HTMLParser):
def handle_comment(self, data):
if '\n' in data:
print('>>> Multi-line Comment', data, sep='\n')
else:
print('>>> Single-line Comment', data, sep='\n')
def handle_data(self, data):
if data != '\n':
print('>>> Data', data, sep='\n')
html = ""
for i in range(int(input())):
html += input().rstrip()
html += '\n'
parser = MyHTMLParser()
parser.feed(html)
parser.close()
67. Detect HTML Tags, Attributes and Attribute Values
Solution:
# Enter your code here. Read input from STDIN. Print output to STDOUT
from html.parser import HTMLParser
class MyHTMLParser(HTMLParser):
def handle_starttag(self, tag, attrs):
print(tag)
[print(f'-> {i[0]} > {i[1]}') for i in attrs]
def handle_startendtag(self, tag, attrs):
print (tag)
[print(f'-> {i[0]} > {i[1]}') for i in attrs]
parser = MyHTMLParser()
for _ in range(int(input())):
parser.feed(input())
68. XML 1 — Find the Score
Solution:
import sys
import xml.etree.ElementTree as etree
def get_attr_number(node):
# your code goes here
count=0
for child in node.iter():
count+=len(child.attrib)
return count
if __name__ == '__main__':
sys.stdin.readline()
xml = sys.stdin.read()
tree = etree.ElementTree(etree.fromstring(xml))
root = tree.getroot()
print(get_attr_number(root))
69. Validating UID
Solution:
import re
pattern = r'^(?=(?:.*[A-Z]){2,})(?=(?:.*\d){3,})(?!.*(.).*\1)[\w]{10}$'
for _ in range(int(input())):
i = input()
print('Valid' if re.fullmatch(pattern, i)
else 'Invalid')
70. XML2 — Find the Maximum Depth
Solution:
import xml.etree.ElementTree as etree
maxdepth = 0
def depth(elem, level):
global maxdepth
# your code goes here
level += 1
if level > maxdepth:
maxdepth = level
for e in elem:
depth(e, level)
if __name__ == '__main__':
n = int(input())
xml = ""
for i in range(n):
xml = xml + input() + "\n"
tree = etree.ElementTree(etree.fromstring(xml))
depth(tree.getroot(), -1)
print(maxdepth)
71. Standardize Mobile Number Using Decorators
Solution:
def wrapper(f):
def fun(l):
# complete the function
l = ['+91 '+i[-10:-5]+' '+i[-5:] for i in l]
f(l)
return fun
@wrapper
def sort_phone(l):
print(*sorted(l), sep='\n')
if __name__ == '__main__':
l = [input() for _ in range(int(input()))]
sort_phone(l)
72. Decorators 2 — Name Directory
Solution:
import operator
def person_lister(f):
def inner(people):
# complete the function
people.sort(key=lambda x: int(x[2]))
return (f(p) for p in people)
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')
73. Arrays
Solution:
import numpy
def arrays(arr):
# complete this function
# use numpy.array
arr = numpy.array(arr,float)
arr = arr[::-1]
return arr
arr = input().strip().split(' ')
result = arrays(arr)
print(result)
74. Shape and Reshape
Solution:
import numpy as np
one_d_array = np.fromstring(input(), dtype=int, sep=' ')
print(np.reshape(one_d_array, (3,3)))
75. Transpose and Flatten
Solution:
import numpy as np
n, m = map(int, input().split())
data = np.array([input().split() for _ in range(n)], int)
print(np.transpose(data))
print(data.flatten())
76. Concatenate
Solution:
import numpy as np
N,M,P = map(int,input().split())
A1 = np.array([input().split() for _ in range(N)],int)
A2 = np.array([input().split() for _ in range(M)],int)
print(np.concatenate((A1,A2)))
#By convention _ means to other developers that the variable is unused.
#On that note linters such as pylint will not emit "unused variable" warnings for this symbol
77. Zeros and Ones
Solution:
import numpy
t = tuple(map(int , input().split(" ")))
print(numpy.zeros(t, dtype = int))
print(numpy.ones(t, dtype = int))
78. Eye and Identity
Solution:
import numpy as np
np.set_printoptions(legacy='1.13')
print(np.eye(*map(int, input().split())))
79. Array Mathematics
Solution:
import numpy
rows, cols = map(int, input().split())
attrs = ['add', 'subtract', 'multiply',
'floor_divide', 'mod', 'power']
a = numpy.array([input().split() for row in range(rows)], int)
b = numpy.array([input().split() for row in range(rows)], int)
for attr in attrs:
print(getattr(numpy, attr)(a, b))
80. Floor, Ceil and Rint
Solution:
import numpy as np
np.set_printoptions(legacy='1.13')
arr = np.array(input().split(),float)
print(np.floor(arr))
print(np.ceil(arr))
print(np.rint(arr))
81. Sum and Prod
Solution:
import numpy as np
N, M = map(int, input().split())
arr = np.array([input().split() for _ in range(N)], int)
print(np.product(np.sum(arr, axis=0)))
82. Min and Max
Solution:
import numpy
N, M = map(int, input().split())
arr = []
for i in range(N):
f = list(map(int, input().split()))
arr.append(f)
print(numpy.max(numpy.min(numpy.array(arr), axis=1)))
83. Mean, Var, and Std
Solution:
import numpy
n ,m = map(int, input().split())
l = numpy.array([input().split() for i in range(n)], int)
print(numpy.mean(l, axis = 1))
print(numpy.var(l, axis =0 ))
print(round(numpy.std(l),11))
84. Dot and Cross
Solution:
import numpy
n = int(input())
na =numpy.array([input().split()for i in range(n)],int)
nb =numpy.array([input().split()for i in range(n)],int)
print(numpy.dot(na,nb))
85. Inner and Outer
Solution:
import numpy as np
arr1 = np.array(list(map(int, input().strip().split(' '))))
arr2 = np.array(list(map(int, input().strip().split(' '))))
print(np.inner(arr1, arr2))
print(np.outer(arr1, arr2))
86. Polynomials
Solution:
import numpy as np
print(np.polyval(list(map(float, input().split())), float(input())))
87. Linear Algebra
Solution:
import numpy as np
print(round(np.linalg.det(np.array([input().split() for _ in range(int(input()))], float)),2))
88. List Comprehensions
Solution:
if __name__ == '__main__':
x = int(input())
y = int(input())
z = int(input())
n = int(input())
list = []
for i in range(x+1):
for j in range(y+1):
for k in range(z+1):
if i+j+k != n:
list.append([i,j,k])
print(list)
89. String Validators
Solution:
if __name__ == '__main__':
s = input()
print(any(i.isalnum() for i in s))
print(any(i.isalpha() for i in s))
print(any(i.isdigit() for i in s))
print(any(i.islower() for i in s))
print(any(i.isupper() for i in s))
90. Mod Divmod
Solution:
# Enter your code here. Read input from STDIN. Print output to STDOUT
a, b = int(input()), int(input())
print(a//b, a%b, divmod(a,b), sep = '\n')