August 17, 2022
input_string
to stdout.1
2
3
4
5
6
7
8
9
#!/bin/python3
# Read a full line of input from stdin and save it to our dynamically typed variable, input_string.
input_string = input()
# Print a string literal saying "Hello, World." to stdout.
print('Hello, World.')
# TODO: Write a line of code here that prints the contents of input_string to stdout.
1
2
3
4
5
6
7
8
9
10
#!/bin/python3
# Read a full line of input from stdin and save it to our dynamically typed variable, input_string.
input_string = input()
# Print a string literal saying "Hello, World." to stdout.
print('Hello, World.')
# TODO: Write a line of code here that prints the contents of input_string to stdout.
print(input_string)
i
, d
, and s
i
plus your int variable on a new lined
plus your double variable to a scale of one decimal place on a new lines
with the string you read as input and print the result on a new line.1
2
3
4
5
6
7
8
9
10
11
12
13
i = 4
d = 4.0
s = 'HackerRank '
# Declare second integer, double, and String variables.
# Read and save an integer, double, and String to your variables.
# Print the sum of both integer variables on a new line.
# Print the sum of the double variables on a new line.
# Concatenate and print the String variables on a new line
# The 's' variable above should be printed first.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#!/bin/python3
i = 4
d = 4.0
s = 'HackerRank '
# Declare second integer, double, and String variables.
# Read and save an integer, double, and String to your variables.
int_eger = input()
dou_ble = input()
str_ing = input()
# Print the sum of both integer variables on a new line.
print(i + int(int_eger))
# Print the sum of the double variables on a new line.
print(round(d + float(dou_ble),1))
# Concatenate and print the String variables on a new line
# The 's' variable above should be printed first.
print(s + str_ing)
solve
function
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#!/bin/python3
import math
import os
import random
import re
import sys
# Complete the 'solve' function below.
# The function accepts following parameters:
# 1. DOUBLE meal_cost
# 2. INTEGER tip_percent
# 3. INTEGER tax_percent
def solve(meal_cost, tip_percent, tax_percent):
# Write your code here
if __name__ == '__main__':
meal_cost = float(input().strip())
tip_percent = int(input().strip())
tax_percent = int(input().strip())
solve(meal_cost, tip_percent, tax_percent)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
#!/bin/python3
import math
import os
import random
import re
import sys
# Complete the 'solve' function below.
# The function accepts following parameters:
# 1. DOUBLE meal_cost
# 2. INTEGER tip_percent
# 3. INTEGER tax_percent
def solve(meal_cost, tip_percent, tax_percent):
tip = meal_cost/100*tip_percent
tax = tax_percent/100*meal_cost
total = round(meal_cost + tip + tax)
print(total)
if __name__ == '__main__':
meal_cost = float(input().strip())
tip_percent = int(input().strip())
tax_percent = int(input().strip())
solve(meal_cost, tip_percent, tax_percent)
n
perform the following conditional actions:
Weird
Not Weird
Weird
1 <= n <= 100
1
2
3
4
5
6
7
8
9
10
#!/bin/python3
import math
import os
import random
import re
import sys
if __name__ == '__main__':
N = int(input().strip())
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#!/bin/python3
import math
import os
import random
import re
import sys
# function that checks to see if a number is even and returns True, False otherwise
def is_even(num):
if (num % 2) == 0:
return True
else:
return False
if __name__ == '__main__':
N = int(input().strip())
if 1 <= N <= 100:
if (is_even(N)==False) or ((is_even(N)==True) and (6<=N<=20)):
print("Weird")
if (is_even(N)==True) and ((2<=N<=5) or (N>20)):
print("Not Weird")
initialAge
initialAge
is negative, print Age is not valid, setting age to 0.
and set the instance variable age
to 0amIOld
method
age < 13
print You are young.
13 <= age < 18
print You are a teenager.
You are old.
yearPasses
method by incrementing the age instance variable by 11 <= t <= 4
5 <= age <= 30
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class Person:
def __init__(self,initialAge):
# Add some more code to run some checks on initialAge
def amIOld(self):
# Do some computations in here and print out the correct statement to the console
def yearPasses(self):
# Increment the age of the person in here
t = int(input())
for i in range(0, t):
age = int(input())
p = Person(age)
p.amIOld()
for j in range(0, 3):
p.yearPasses()
p.amIOld()
print("")
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
#!/bin/python3
class Person:
def __init__(self,initialAge):
# Add some more code to run some checks on initialAge
if initialAge < 0:
print("Age is not valid, setting age to 0.")
self.age = 0
else:
self.age = initialAge
def amIOld(self):
# Do some computations in here and print out the correct statement to the console
if self.age < 13:
print("You are young.")
elif 13 <= self.age < 18:
print("You are a teenager.")
else:
print("You are old.")
def yearPasses(self):
# Increment the age of the person in here
self.age+=1
t = int(input())
for i in range(0, t):
age = int(input())
p = Person(age)
p.amIOld()
for j in range(0, 3):
p.yearPasses()
p.amIOld()
print("")
1 <= i <= 10
2 <= n <= 20
1
2
3
4
5
6
7
8
9
10
#!/bin/python3
import math
import os
import random
import re
import sys
if __name__ == '__main__':
n = int(input().strip())
1
2
3
4
5
6
7
8
9
10
11
12
#!/bin/python3
import math
import os
import random
import re
import sys
if __name__ == '__main__':
n = int(input().strip())
for i in range(1,11):
print("{} x {} = {}".format(n,i,n * i))
s
of length N
that is indexed from 0
to N - 1
, print it’s even-indexed and odd-indexed characters as space-separated strings on a single lines = adbecf
prints out: abc def
1 <= t <= 10 : (t is number of test cases)
2 < length of s <= 10000
1
# Enter your code here. Read input from STDIN. Print output to STDOUT
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
#!/bin/python3
if __name__ == '__main__':
# number of strings user will provide
numStrings = int(input())
count = 0
strings = []
# get strings from user and append to strings array
while count != numStrings:
s = str(input())
strings.append(s)
count+=1
x = 0
evens = ""
odds = ""
# loop through elements in strings array
while x < len(strings):
y = 0
# loop through characters in element
while y < len(strings[x]):
if y%2==0:
evens+=strings[x][y]
else:
odds+=strings[x][y]
y+=1
print("{} {}".format(evens,odds))
evens = ""
odds = ""
x+=1
1 <= N <= 1000
1 <= A[i] <= 1000, where A[i] is the i'th integer of the array
1
2
3
4
5
6
7
8
9
10
11
12
#!/bin/python3
import math
import os
import random
import re
import sys
if __name__ == '__main__':
n = int(input().strip())
arr = list(map(int, input().rstrip().split()))
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#!/bin/python3
import math
import os
import random
import re
import sys
if __name__ == '__main__':
n = int(input().strip())
arr = list(map(int, input().rstrip().split()))
x = len(arr)-1
s = ""
while x >= 0:
s+= "{} ".format(arr[x])
x-=1
print(s)
n
names and phone numbers, assemble a phone book that maps friends’ names to their respective phone numbers.name=phoneNumber
name
is not found, print Not found
1 <= n <= 10^5
1 <= queries <= 10^5
1
# Enter your code here. Read input from STDIN. Print output to STDOUT
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#!/bin/python3
# Enter your code here. Read input from STDIN. Print output to STDOUT
if __name__ == '__main__':
n = int(input())
phoneBook=dict(input().split(' ',2) for _ in range(n))
while True:
try:
name = str(input())
if name in phoneBook.keys():
print("{}={}".format(name,phoneBook[name]))
else:
print("Not found")
except:
break
factorial
that recursively calculates factorial of given integer n
2 <= n <= 12
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#!/bin/python3
import math
import os
import random
import re
import sys
# Complete the 'factorial' function below.
# The function is expected to return an INTEGER.
# The function accepts INTEGER n as parameter.
def factorial(n):
# Write your code here
if __name__ == '__main__':
fptr = open(os.environ['OUTPUT_PATH'], 'w')
n = int(input().strip())
result = factorial(n)
fptr.write(str(result) + '\n')
fptr.close()
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
#!/bin/python3
import math
import os
import random
import re
import sys
# Complete the 'factorial' function below.
# The function is expected to return an INTEGER.
# The function accepts INTEGER n as parameter.
def factorial(n):
if n > 1:
n = n * factorial(n-1)
return n
if __name__ == '__main__':
fptr = open(os.environ['OUTPUT_PATH'], 'w')
n = int(input().strip())
result = factorial(n)
fptr.write(str(result) + '\n')
fptr.close()
n
convert it to base-2 (binary)1
2
3
4
5
6
7
8
9
10
#!/bin/python3
import math
import os
import random
import re
import sys
if __name__ == '__main__':
n = int(input().strip())
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
#!/bin/python3
import math
import os
import random
import re
import sys
def binary(decimal,string):
while decimal != 0:
string+=str(decimal % 2)
decimal = decimal//2
binary(decimal,string)
return string
def count_ones(binary):
count = 0
max_count = 0
for x in range(0,len(binary)):
if binary[x] == '1':
count+=1
if count > max_count:
max_count = count
elif binary[x] == '0':
count = 0
return max_count
if __name__ == '__main__':
n = int(input().strip())
s = ''
b = binary(n,s)
number_of_ones = count_ones(b)
print(number_of_ones)
1 1 1 0 0 0
0 1 0 0 0 0
1 1 1 0 0 0
0 0 2 4 4 0
0 0 0 2 0 0
0 0 1 2 4 0
1 1 1
1
1 1 1
2 4 4
2
1 2 4
9 <= A[i][j] <= 9
0 <= i,j <= 5
1
2
3
4
5
6
7
8
9
10
11
12
13
14
#!/bin/python3
import math
import os
import random
import re
import sys
if __name__ == '__main__':
arr = []
for _ in range(6):
arr.append(list(map(int, input().rstrip().split())))
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
#!/bin/python3
import math
import os
import random
import re
import sys
def findMax(array):
d ={}
for n in range(1,17):
d['hourglass{}'.format(n)] = 0
x = 0
y = 0
while y < 6:
while x < 6:
n = array[y][x]
if 0 <= x <= 2 and 0 <= y <= 2:
if y == 1 and x != 1:
pass
else:
d['hourglass1'] += n
if 1 <= x <= 3 and 0 <= y <= 2:
if y == 1 and x != 2:
pass
else:
d['hourglass2'] += n
if 2 <= x <= 4 and 0 <= y <= 2:
if y == 1 and x != 3:
pass
else:
d['hourglass3'] += n
if 3 <= x <= 5 and 0 <= y <= 2:
if y == 1 and x != 4:
pass
else:
d['hourglass4'] += n
if 0 <= x <= 2 and 1 <= y <= 3:
if y == 2 and x != 1:
pass
else:
d['hourglass5'] += n
if 1 <= x <= 3 and 1 <= y <= 3:
if y == 2 and x != 2:
pass
else:
d['hourglass6'] += n
if 2 <= x <= 4 and 1 <= y <= 3:
if y == 2 and x != 3:
pass
else:
d['hourglass7'] += n
if 3 <= x <= 5 and 1 <= y <= 3:
if y == 2 and x != 4:
pass
else:
d['hourglass8'] += n
if 0 <= x <= 2 and 2 <= y <= 4:
if y == 3 and x != 1:
pass
else:
d['hourglass9'] += n
if 1 <= x <= 3 and 2 <= y <= 4:
if y == 3 and x != 2:
pass
else:
d['hourglass10'] += n
if 2 <= x <= 4 and 2 <= y <= 4:
if y == 3 and x != 3:
pass
else:
d['hourglass11'] += n
if 3 <= x <= 5 and 2 <= y <= 4:
if y == 3 and x != 4:
pass
else:
d['hourglass12'] += n
if 0 <= x <= 2 and 3 <= y <= 5:
if y == 4 and x != 1:
pass
else:
d['hourglass13'] += n
if 1 <= x <= 3 and 3 <= y <= 5:
if y == 4 and x != 2:
pass
else:
d['hourglass14'] += n
if 2 <= x <= 4 and 3 <= y <= 5:
if y == 4 and x != 3:
pass
else:
d['hourglass15'] += n
if 3 <= x <= 5 and 3 <= y <= 5:
if y == 4 and x != 4:
pass
else:
d['hourglass16'] += n
x+=1
y+=1
x=0
allValues = d.values()
return(max(allValues))
if __name__ == '__main__':
arr = []
for _ in range(6):
arr.append(list(map(int, input().rstrip().split())))
print(findMax(arr))
Person
and Student
where:
Person
is the base class and Student
is the derived classStudent
constructor with 4 parameters:firstName
& lastName
idNumber
scores
calculate()
method that calculates a Student object’s average and returns the grade character representative of their calculated average1 <= length of firstName
length of lastName <= 10
length of idNumber <= 7
0 <= score <= 100
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
class Person:
def __init__(self, firstName, lastName, idNumber):
self.firstName = firstName
self.lastName = lastName
self.idNumber = idNumber
def printPerson(self):
print("Name:", self.lastName + ",", self.firstName)
print("ID:", self.idNumber)
class Student(Person):
# Class Constructor
# Parameters:
# firstName - A string denoting the Person's first name.
# lastName - A string denoting the Person's last name.
# id - An integer denoting the Person's ID number.
# scores - An array of integers denoting the Person's test scores.
# Write your constructor here
# Function Name: calculate
# Return: A character denoting the grade.
#
# Write your function here
line = input().split()
firstName = line[0]
lastName = line[1]
idNum = line[2]
numScores = int(input()) # not needed for Python
scores = list( map(int, input().split()) )
s = Student(firstName, lastName, idNum, scores)
s.printPerson()
print("Grade:", s.calculate())
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
class Person:
def __init__(self, firstName, lastName, idNumber):
self.firstName = firstName
self.lastName = lastName
self.idNumber = idNumber
def printPerson(self):
print("Name:", self.lastName + ",", self.firstName)
print("ID:", self.idNumber)
class Student(Person):
# Class Constructor
#
# Parameters:
# firstName - A string denoting the Person's first name.
# lastName - A string denoting the Person's last name.
# id - An integer denoting the Person's ID number.
# scores - An array of integers denoting the Person's test scores.
#
# Write your constructor here
def __init__(self,firstName,lastName,idNumber, scores):
super().__init__(firstName, lastName, idNumber)
self.scores = scores
# Function Name: calculate
# Return: A character denoting the grade.
#
# Write your function here
def calculate(self):
average = sum(self.scores)/len(self.scores)
if 90 <= average <=100:
return('O')
elif 80 <= average < 90:
return('E')
elif 70 <= average < 80:
return('A')
elif 55 <= average < 70:
return('P')
elif 40 <= average < 55:
return('D')
elif average < 40:
return('T')
line = input().split()
firstName = line[0]
lastName = line[1]
idNum = line[2]
numScores = int(input()) # not needed for Python
scores = list( map(int, input().split()) )
s = Student(firstName, lastName, idNum, scores)
s.printPerson()
print("Grade:", s.calculate())
Book
class and a Solution class, write a MyBook class that does the following:
title
& author
price
display()
method so it prints 3 lines:
title
author
price
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
from abc import ABCMeta, abstractmethod
class Book(object, metaclass=ABCMeta):
def __init__(self,title,author):
self.title=title
self.author=author
@abstractmethod
def display(): pass
#Write MyBook class
title=input()
author=input()
price=int(input())
new_novel=MyBook(title,author,price)
new_novel.display()
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
from abc import ABCMeta, abstractmethod
class Book(object, metaclass=ABCMeta):
def __init__(self,title,author):
self.title=title
self.author=author
@abstractmethod
def display(): pass
#Write MyBook class
class MyBook(Book):
def __init__(self,title,author,price):
super().__init__(title,author)
self.price = price
def display(self):
print("Title: {}".format(self.title))
print("Author: {}".format(self.author))
print("Price: {}".format(self.price))
title=input()
author=input()
price=int(input())
new_novel=MyBook(title,author,price)
new_novel.display()
__elements
instance variable__elements
and stores it in the maximumDifference
instance variableelements
for storing N
non-negative integers, and a public integer maximumDifference
for storing the maximum absolute difference
|a - b|
between any two integers, a and b, in __elements
.1 <= N <= 10
1 <= __elements[i] <= 100 where 0 <= i <= N-1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Difference:
def __init__(self, a):
self._elements = a
# Add your code here
# End of Difference class
_ = input()
a = [int(e) for e in input().split(' ')]
d = Difference(a)
d.computeDifference()
print(d.maximumDifference)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class Difference:
def __init__(self, a):
self.__elements = a
# Add your code here
def computeDifference(self):
smallest = self.__elements[0]
largest = self.__elements[0]
for x in range(0,len(self.__elements)):
if self.__elements[x] < smallest:
smallest = self.__elements[x]
if self.__elements[x] > largest:
largest = self.__elements[x]
self.maximumDifference = abs(smallest - largest)
# End of Difference class
_ = input()
a = [int(e) for e in input().split(' ')]
d = Difference(a)
d.computeDifference()
print(d.maximumDifference)
insert
function such that it creates a new Node (data is passed as Node constructor argument) and inserts it at the tail end of the linked list referenced by the head
parameter.1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
class Node:
def __init__(self,data):
self.data = data
self.next = None
class Solution:
def display(self,head):
current = head
while current:
print(current.data,end=' ')
current = current.next
def insert(self,head,data):
#Complete this method
mylist= Solution()
T=int(input())
head=None
for i in range(T):
data=int(input())
head=mylist.insert(head,data)
mylist.display(head);
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#!/bin/python3
class Node:
def __init__(self,data):
self.data = data
self.next = None
class Solution:
def display(self,head):
current = head
while current:
print(current.data,end=' ')
current = current.next
def insert(self,head,data):
#Complete this method
print(data, end= ' ')
mylist= Solution()
T=int(input())
head=None
for i in range(T):
data=int(input())
head=mylist.insert(head,data)
mylist.display(head);
S
and print it’s integer valueS
cannot be converted to an integer, print Bad String
1 <= |S| <= 6
: |S|
is length of string SS
is composed of either lowercase letters (a-z) or decimal digits (0-9)1
2
3
4
5
6
7
8
9
10
#!/bin/python3
import math
import os
import random
import re
import sys
if __name__ == '__main__':
S = input()
1
2
3
4
5
6
7
8
9
10
11
12
13
#!/bin/python3
import math
import os
import random
import re
import sys
S = input().strip()
try:
print(int(S))
except ValueError:
print("Bad String")
int power(int,int)
n
& p
as parameters and returns the integer result of n^p
n
or p
is negative, then the method must throw an exception with the message: n and p should be non-negative
1
2
3
4
5
6
7
8
9
10
11
#Write your code here
myCalculator=Calculator()
T=int(input())
for i in range(T):
n,p = map(int, input().split())
try:
ans=myCalculator.power(n,p)
print(ans)
except Exception as e:
print(e)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#!/bin/python3
#Write your code here
class Calculator:
def power(self,n,p):
Error = ValueError('n and p should be non-negative')
self.n = n
self.p = p
if self.n < 0 or self.p < 0:
raise Error
else:
return n ** p
myCalculator=Calculator()
T=int(input())
for i in range(T):
n,p = map(int, input().split())
try:
ans=myCalculator.power(n,p)
print(ans)
except Exception as e:
print(e)
s
is a palindrome (word, phrase, number, or other sequence of characters which reads the same backwards and forwards)s
, enqueue it in a queue, and also push that same character onto a stack.s
is composed of lowercase English letters.1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
import sys
class Solution:
# Write your code here
# read the string s
s=input()
#Create the Solution class object
obj=Solution()
l=len(s)
# push/enqueue all the characters of string s to stack
for i in range(l):
obj.pushCharacter(s[i])
obj.enqueueCharacter(s[i])
isPalindrome=True
'''
pop the top character from stack
dequeue the first character from queue
compare both the characters
'''
for i in range(l // 2):
if obj.popCharacter()!=obj.dequeueCharacter():
isPalindrome=False
break
#finally print whether string s is palindrome or not.
if isPalindrome:
print("The word, "+s+", is a palindrome.")
else:
print("The word, "+s+", is not a palindrome.")
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
import sys
class Solution:
# Write your code here
def __init__(self):
self.stack = []
self.queue = []
def pushCharacter(self, char):
self.stack.insert(0,char)
def popCharacter(self):
return self.stack.pop(0)
def enqueueCharacter(self,char):
self.queue.append(char)
def dequeueCharacter(self):
return self.queue.pop(0)
# read the string s
s=input()
#Create the Solution class object
obj=Solution()
l=len(s)
# push/enqueue all the characters of string s to stack
for i in range(l):
obj.pushCharacter(s[i])
obj.enqueueCharacter(s[i])
isPalindrome=True
'''
pop the top character from stack
dequeue the first character from queue
compare both the characters
'''
for i in range(l // 2):
if obj.popCharacter()!=obj.dequeueCharacter():
isPalindrome=False
break
#finally print whether string s is palindrome or not.
if isPalindrome:
print("The word, "+s+", is a palindrome.")
else:
print("The word, "+s+", is not a palindrome.")
Calculator
class, which implements the AdvancedArithmetic
interface.divisorSum(n)
method must return the sum of all divisors of n
n = 20
, The divisors of 20 are 1,2,4,5,10,201 <= n <= 1000
1
2
3
4
5
6
7
8
9
10
11
12
13
14
class AdvancedArithmetic(object):
def divisorSum(n):
raise NotImplementedError
class Calculator(AdvancedArithmetic):
def divisorSum(self, n):
pass
n = int(input())
my_calculator = Calculator()
s = my_calculator.divisorSum(n)
print("I implemented: " + type(my_calculator).__bases__[0].__name__)
print(s)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class AdvancedArithmetic(object):
def divisorSum(n):
raise NotImplementedError
class Calculator(AdvancedArithmetic):
def divisorSum(self, n):
if n == 0 or n==1:
return n
else:
list_of_divisors = []
list_of_divisors.extend([1,n])
max_divisor = n//2
for i in range(2,max_divisor+1):
if n%i == 0:
list_of_divisors.append(i)
return sum(list_of_divisors)
n = int(input())
my_calculator = Calculator()
s = my_calculator.divisorSum(n)
print("I implemented: " + type(my_calculator).__bases__[0].__name__)
print(s)
a
of size n
distinct elements, sort the array in ascending order using the Bubble Sort algorithmnumSwaps
is the number of swaps that took place.firstElement
is the first element in the sorted array.lastElement
is the last element in the sorted array.n
, the number of elements in array a
a[0],a[1],...,a[n-1]
2 <= n <= 600
1 <= a[i] <= 2 x 10^6
, where 0 <= i < n1
2
3
4
5
6
7
8
9
10
11
12
13
14
#!/bin/python3
import math
import os
import random
import re
import sys
if __name__ == '__main__':
n = int(input().strip())
a = list(map(int, input().rstrip().split()))
# Write your code here
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#!/bin/python3
import math
import os
import random
import re
import sys
if __name__ == '__main__':
n = int(input().strip())
a = list(map(int, input().rstrip().split()))
# Write your code here
iteration_count = 0
for i in range(n):
for idx in range(n - i - 1):
if a[idx] > a[idx+1]:
a[idx], a[idx+1] = a[idx+1], a[idx]
iteration_count += 1
print("Array is sorted in {0} swaps.".format(iteration_count))
print("First Element:",a[0])
print("Last Element:",a[-1])
getHeight
function provided in your editor so that it returns the height of the binary search tree.n
, denoting the number of nodes in the tree.data
, denoting the value of an element that must be added to the BST.1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
class Node:
def __init__(self,data):
self.right=self.left=None
self.data = data
class Solution:
def insert(self,root,data):
if root==None:
return Node(data)
else:
if data<=root.data:
cur=self.insert(root.left,data)
root.left=cur
else:
cur=self.insert(root.right,data)
root.right=cur
return root
def getHeight(self,root):
#Write your code here
T=int(input())
myTree=Solution()
root=None
for i in range(T):
data=int(input())
root=myTree.insert(root,data)
height=myTree.getHeight(root)
print(height)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
class Node:
def __init__(self,data):
self.right=self.left=None
self.data = data
class Solution:
def insert(self,root,data):
if root==None:
return Node(data)
else:
if data<=root.data:
cur=self.insert(root.left,data)
root.left=cur
else:
cur=self.insert(root.right,data)
root.right=cur
return root
def getHeight(self,root,height=0, a_set=None):
if root is None:
return "None"
root.height = height
if a_set == None:
a_set = set()
a_set.add(height)
if root.left is not None:
root.left.height = height + 1
a_set.add(root.left.height)
self.getHeight(root.left, root.left.height,a_set)
if root.right is not None:
root.right.height = height + 1
a_set.add(root.right.height)
self.getHeight(root.right, root.right.height,a_set)
if root.height == 0:
return max(a_set)
T=int(input())
myTree=Solution()
root=None
for i in range(T):
data=int(input())
root=myTree.insert(root,data)
height=myTree.getHeight(root)
print(height)
levelOrder
function provided in your editor so that it prints the level-order traversal of the binary search tree.T
(the number of test cases).T
subsequent lines each contain an integer, data
, denoting the value of an element that must be added to the BST.1 <= N <= 20
1 <= node.data[i] <= 100
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
import sys
class Node:
def __init__(self,data):
self.right=self.left=None
self.data = data
class Solution:
def insert(self,root,data):
if root==None:
return Node(data)
else:
if data<=root.data:
cur=self.insert(root.left,data)
root.left=cur
else:
cur=self.insert(root.right,data)
root.right=cur
return root
def levelOrder(self,root):
#Write your code here
T=int(input())
myTree=Solution()
root=None
for i in range(T):
data=int(input())
root=myTree.insert(root,data)
myTree.levelOrder(root)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
import sys
class Node:
def __init__(self,data):
self.right=self.left=None
self.data = data
class Solution:
def insert(self,root,data):
if root==None:
return Node(data)
else:
if data<=root.data:
cur=self.insert(root.left,data)
root.left=cur
else:
cur=self.insert(root.right,data)
root.right=cur
return root
def levelOrder(self,root,lst=None):
print(root.data)
if lst == None:
lst = []
lst.append(root.data)
if root.left is not None:
lst.append(root.left.data)
if root.right is not None:
lst.append(root.right.data)
if root.left is not None:
self.levelOrder(root.left, lst)
if root.right is not None:
self.levelOrder(root.right, lst)
print(lst)
T=int(input())
myTree=Solution()
root=None
for i in range(T):
data=int(input())
root=myTree.insert(root,data)
myTree.levelOrder(root)
data
, and a Node instance pointer, next
, pointing to another node (i.e.: the next node in a list).removeDuplicates
function is declared in your editor, which takes a pointer to the node of a linked list as a parameter.removeDuplicates
so that it deletes any duplicate nodes from the list and returns the head of the updated list.N
, the number of nodes to be inserted.N
subsequent lines each contain an integer describing the data
value of a node being inserted at the list’s tail.1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
class Node:
def __init__(self,data):
self.data = data
self.next = None
class Solution:
def insert(self,head,data):
p = Node(data)
if head==None:
head=p
elif head.next==None:
head.next=p
else:
start=head
while(start.next!=None):
start=start.next
start.next=p
return head
def display(self,head):
current = head
while current:
print(current.data,end=' ')
current = current.next
def removeDuplicates(self,head):
#Write your code here
mylist= Solution()
T=int(input())
head=None
for i in range(T):
data=int(input())
head=mylist.insert(head,data)
head=mylist.removeDuplicates(head)
mylist.display(head);
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
class Node:
def __init__(self,data):
self.data = data
self.next = None
class Solution:
def insert(self,head,data):
p = Node(data)
if head==None:
head=p
elif head.next==None:
head.next=p
else:
start=head
while(start.next!=None):
start=start.next
start.next=p
return head
def display(self,head):
current = head
while current:
print(current.data,end=' ')
current = current.next
def removeDuplicates(self,head):
current = head
while current:
if current.next != None:
if current.next.data != current.data:
current = current.next
else:
next_node = current.next.next
current.next = None
current.next = next_node
else:
return head
mylist= Solution()
T=int(input())
head=None
for i in range(T):
data=int(input())
head=mylist.insert(head,data)
head=mylist.removeDuplicates(head)
mylist.display(head);