# https://www.hackerrank.com/challenges/default-arguments/problem
class EvenStream(object):
def __init__(self):
self.current = 0
def get_next(self):
to_return = self.current
self.current += 2
return to_return
class OddStream(object):
def __init__(self):
self.current = 1
def get_next(self):
to_return = self.current
self.current += 2
return to_return
# stream.__init__() is added because if we use an object as a default argument in python it's only initialised once when the function is
# defined and is reused every time there is need for the default argument. hence only the odd function's variable was resetting, While
# the even's was adding up as the object for even was created at the first use and so the init was only invoked once. so invoking the
# constructor every time the streams are called will reset the class variable everytime.
def print_from_stream(n, stream=EvenStream()):
stream.__init__()
for _ in range(n):
print(stream.get_next())
queries = int(input())
for _ in range(queries):
stream_name, n = input().split()
n = int(n)
if stream_name == "even":
print_from_stream(n)
else:
print_from_stream(n, OddStream())
# https://www.hackerrank.com/challenges/ginorts/problem
S = str(input())
k = len(S)
m = []
n = []
p = []
q = []
for i in range (0,k):
if S[i].islower():
m.append(S[i])
m.sort()
if S[i].isupper():
n.extend(S[i])
n.sort()
if S[i].isdecimal():
e = int(S[i])
if e % 2 == 1:
p.extend(S[i])
p.sort()
if S[i].isdecimal():
e = int(S[i])
if e % 2 == 0:
q.extend(S[i])
q.sort()
t = m + n + p + q
r = ''.join(t)
print(r)
# Basic method of setting and getting attributes in Python
class Celsius:
def __init__(self, temperature=0):
self.temperature = temperature
def to_fahrenheit(self):
return (self.temperature * 1.8) + 32
# Create a new object
human = Celsius()
# Set the temperature
human.temperature = 37
# Get the temperature attribute
print(human.temperature)
# Get the to_fahrenheit method
print(human.to_fahrenheit())
# Making Getters and Setter methods
class Celsius:
def __init__(self, temperature=0):
self.set_temperature(temperature)
def to_fahrenheit(self):
return (self.get_temperature() * 1.8) + 32
# getter method
def get_temperature(self):
return self._temperature
# setter method
def set_temperature(self, value):
if value < -273.15:
raise ValueError("Temperature below -273.15 is not possible.")
self._temperature = value
# As we can see, the above method introduces two new get_temperature() and set_temperature() methods.Furthermore, temperature was replaced
# with _temperature. An underscore _ at the beginning is used to denote private variables in Python.
# Create a new object, set_temperature() internally called by __init__
human = Celsius(37)
# Get the temperature attribute via a getter
print(human.get_temperature())
# Get the to_fahrenheit method, get_temperature() called by the method itself
print(human.to_fahrenheit())
# new constraint implementation
human.set_temperature(-300)
# Get the to_fahreheit method
print(human.to_fahrenheit())
# https://www.hackerrank.com/challenges/decorators-2-name-directory/problem
def person_lister(f):
def inner(people):
names = []
people.sort(key=lambda x: int(x[2]))
for person in people:
names.append(f(person))
return names
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')
# https://www.hackerrank.com/challenges/text-alignment/problem
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))
# https://www.hackerrank.com/challenges/text-wrap/problem
import textwrap
def wrap(string, max_width):
q = []
for i in range(0, len(string), max_width):
q. append(string[i:i+max_width])
return ('\n'.join(q))
if __name__ == '__main__':
string, max_width = input(), int(input())
result = wrap(string, max_width)
print(result)
ere
from more_itertools import chunked
list(chunked([1, 2, 3, 4, 5, 6], 3))
list(chunked([1, 2, 3, 4, 'r', 6], 5))
p = peekable(['a', 'b'])
p.peek()
from itertools import count
from more_itertools import ichunked
all_chunks = ichunked(count(), 4)
c_1, c_2, c_3 = next(all_chunks), next(all_chunks), next(all_chunks)
list(c_2)
list(c_1)
list(c_3)
# https://www.hackerrank.com/challenges/designer-door-mat/problem
import sys
import math
n,m = map(int, input().split())
signs = ['.', '|', '-']
h = ''.join(signs[2])
b = ''.join(signs[1])
d = ''.join(signs[0])
for i in range(1, n+1):
if i < (math.ceil((n + 1) // 2)):
r = h*((m-6*i+3) // 2)
s = r + d + (b + 2*d)*(2*i-2) + b + d + r
print_lines.write(s + '\n')
elif i == math.ceil((n + 1) // 2):
c = (h*((m-7) // 2)) + 'WELCOME' + (h*((m-7) // 2))
print_lines.write(c + '\n')
else:
j = n + 1 - i
r = h*((m-6*j+3) // 2)
t = r + d + (b + 2*d)*(2*j-2) + b + d + r
print_lines.write(t + '\n')
---------------.|.--------------- ------------.|..|..|.------------ ---------.|..|..|..|..|.--------- ------.|..|..|..|..|..|..|.------ ---.|..|..|..|..|..|..|..|..|.--- -------------WELCOME------------- ---.|..|..|..|..|..|..|..|..|.--- ------.|..|..|..|..|..|..|.------ ---------.|..|..|..|..|.--------- ------------.|..|..|.------------ ---------------.|.---------------
# v.2
n, m = map(int,input().split())
pattern = [('.|.'*(2*i + 1)).center(m, '-') for i in range(n//2)]
print('\n'.join(pattern + ['WELCOME'.center(m, '-')] + pattern[::-1]))
---------------.|.--------------- ------------.|..|..|.------------ ---------.|..|..|..|..|.--------- ------.|..|..|..|..|..|..|.------ ---.|..|..|..|..|..|..|..|..|.--- -------------WELCOME------------- ---.|..|..|..|..|..|..|..|..|.--- ------.|..|..|..|..|..|..|.------ ---------.|..|..|..|..|.--------- ------------.|..|..|.------------ ---------------.|.---------------
def digits(num):
count = 0
if isinstance(num, int):
while num > 0:
num = num // 10
count = count + 1
return count
num = 45
print(digits(num))
2
# https://www.hackerrank.com/challenges/python-string-formatting/problem
import string
def digits(s):
k = 0
if all(c in string.hexdigits for c in str(s)):
for c in str(s):
k = k + 1
return k
def print_formatted(number):
for i in range (1,n+1):
line = [str(i), str(oct(i)), str(hex(i)), str(bin(i))]
oct2 = line[1].split('0o')
hex2 = line[2].split('0x')
bin2 = line[3].split('0b')
last_line = [str(n), str(oct(n)), str(hex(n)), str(bin(n))]
oct2L = last_line[1].split('0o')
hex2L = last_line[2].split('0x')
bin2L = last_line[3].split('0b')
w = max(digits(n), digits(int(oct2L[1])), digits((hex2L[1])), digits(int(bin2L[1])))
line_new = '{:>{w}} {:>{w}} {:>{w}} {:>{w}}'.format(line[0], oct2[1], hex2[1].upper(), bin2[1], w = w)
print(line_new)
if __name__ == '__main__':
n = int(input())
print_formatted(n)
1 1 1 1 2 2 2 10 3 3 3 11 4 4 4 100 5 5 5 101
# v.2
def print_formatted(number):
for i in range (1,n+1):
line = [str(i), str(oct(i)), str(hex(i)), str(bin(i))]
oct2 = line[1].split('0o')
hex2 = line[2].split('0x')
bin2 = line[3].split('0b')
last_line = [str(n), str(oct(n)), str(hex(n)), str(bin(n))]
w = len((last_line[3].split('0b'))[1])
print('{:>{w}} {:>{w}} {:>{w}} {:>{w}}'.format(line[0], oct2[1], hex2[1].upper(), bin2[1], w = w))
if __name__ == '__main__':
n = int(input())
print_formatted(n)
1 1 1 1 2 2 2 10 3 3 3 11 4 4 4 100 5 5 5 101
n = int(input())
width = len("{0:b}".format(n))
for i in range(1,n+1):
print ("{0:{width}d} {0:{width}o} {0:{width}X} {0:{width}b}".format(i, width=width))
# https://www.hackerrank.com/challenges/python-print/problem
if __name__ == '__main__':
n = int(input())
a = 0
for k in range(1, n+1):
if k >= 10 and k < 100:
a = 100 * a + k
elif k >= 100:
a = 1000 * a + k
else:
a = 10*a + k
print(a)
# https://www.hackerrank.com/challenges/alphabet-rangoli/problem
import string
def print_rangoli(size):
l = list(string.ascii_lowercase)[n-1::-1]
f = '-'.join(l[0]).center(4*n - 3, '-')
v = [('-'.join(l[:i:]) + '-' + '-'.join(l[i]) + '-' + '-'.join(l[(i-1)::-1])).center(4*n - 3, '-') for i in range(1,n)]
if n == 1:
print(f)
elif n == 2:
print(f)
print('\n'.join(v + v[:1:-1]))
print(f)
else:
print(f)
print('\n'.join(v + v[(n-3)::-1]))
print(f)
if __name__ == '__main__':
n = int(input())
print_rangoli(n)
--------e-------- ------e-d-e------ ----e-d-c-d-e---- --e-d-c-b-c-d-e-- e-d-c-b-a-b-c-d-e --e-d-c-b-c-d-e-- ----e-d-c-d-e---- ------e-d-e------ --------e--------
# v.2
import string
alpha = string.ascii_lowercase
n = int(input())
L = []
for i in range(n):
s = "-".join(alpha[i:n])
L.append((s[::-1]+s[1:]).center(4*n-3, "-"))
print('\n'.join(L[:0:-1]+L))
--------e-------- ------e-d-e------ ----e-d-c-d-e---- --e-d-c-b-c-d-e-- e-d-c-b-a-b-c-d-e --e-d-c-b-c-d-e-- ----e-d-c-d-e---- ------e-d-e------ --------e--------
# https://www.hackerrank.com/challenges/capitalize/problem
import math
import os
import random
import re
import sys
def solve(s):
input_name = s.split(' ')
final_name = ''
for i in input_name:
a = ''.join(i)
b = []
for j in a:
b.append(j)
if b[0].islower():
u = b[0].upper()
b.remove(b[0])
b.insert(0, u)
a = ''.join(b)
final_name = final_name + a + ' '
return final_name
if __name__ == '__main__':
os.environ['OUTPUT_PATH'] = 'output.txt'
fptr = open(os.environ['OUTPUT_PATH'], 'w')
s = input()
result = solve(s)
fptr.write(result + '\n')
fptr.close()
# v.2
import math
import os
import random
import re
import sys
def solve(s):
for x in s[:].split():
s = s.replace(x, x.capitalize())
return s
if __name__ == '__main__':
os.environ['OUTPUT_PATH'] = 'output.txt'
fptr = open(os.environ['OUTPUT_PATH'], 'w')
s = input()
result = solve(s)
fptr.write(result + '\n')
fptr.close()
import math
import os
import random
import re
import sys
def solve(s):
return ' '.join(map(str.capitalize, s.split(' ')))
if __name__ == '__main__':
os.environ['OUTPUT_PATH'] = 'output.txt'
fptr = open(os.environ['OUTPUT_PATH'], 'w')
s = input()
result = solve(s)
fptr.write(result + '\n')
fptr.close()
# https://www.hackerrank.com/challenges/merge-the-tools/problem
def merge_the_tools(string, k):
n = len(string)
if n % k != 0:
string, k = input(), int(input())
else:
c = n // k
for i in range(0,c):
e = string[(i*k):(i+1)*k]
l = e.split(' ')
d = []
for j in l[0]:
d.append(j)
for q in range(0,len(d)):
for r in range(0,len(d)):
if q < r and d[q] == d[r]:
del d[r]
print(''.join(d))
if __name__ == '__main__':
string, k = input(), int(input())
merge_the_tools(string, k)
AB CA AD
# v.2
def merge_the_tools(string, k):
for i in range(0, len(string), k):
uniq = ''
for c in string[i : i+k]:
if (c not in uniq):
uniq+=c
print(uniq)
if __name__ == '__main__':
string, k = input(), int(input())
merge_the_tools(string, k)
AB CA AD
# v.3
def merge_the_tools(string, k):
n = len(string)
if n % k != 0:
string, k = input(), int(input())
else:
c = n // k
for i in range(0,c):
e = string[(i*k):(i+1)*k]
uniq = ''
for c in e:
if (c not in uniq):
uniq+=c
print(uniq)
if __name__ == '__main__':
string, k = input(), int(input())
merge_the_tools(string, k)
AB CA AD
S, N = input(), int(input())
for part in zip(*[iter(S)] * N):
d = dict()
print(''.join([ d.setdefault(c, c) for c in part if c not in d ]))
# https://www.hackerrank.com/challenges/write-a-function/problem
def is_leap(year):
return ((year % 4 == 0 and year % 100 != 0) or (year % 4 == 0 and year % 400 == 0))
year = int(input())
print(is_leap(year))
# https://www.hackerrank.com/challenges/validating-uid/problem
T = int(input())
list = []
for i in range(0,T):
list.append((input()))
for uid in list:
u = 0
d = 0
a = 0
r = ''
for c in uid:
if c.isalpha() and c.isupper:
u = u + 1
if c.isnumeric():
d = d + 1
if c.isalnum():
a = a + 1
if c not in r:
r = r + c
if u < 2 or d < 3 or a != len(uid) or len(r) != 10 or len(uid) != 10:
print("Invalid")
else:
print("Valid")
# regex solution 1:
import re
for _ in range(int(input())):
u = ''.join(sorted(input()))
try:
assert re.search(r'[A-Z]{2}', u)
assert re.search(r'\d\d\d', u)
assert not re.search(r'[^a-zA-Z0-9]', u)
assert not re.search(r'(.)\1', u)
assert len(u) == 10
except:
print('Invalid')
else:
print('Valid')
# regex solution 2:
import re
checks = {
"alpha" : lambda uid: re.match(r".*[A-Z].*[A-Z].*", uid),
"num" : lambda uid: re.match(r".*[0-9].*[0-9].*[0-9].*", uid),
"alpha_num" : lambda uid: re.match(r"[A-Za-z0-9]{10}", uid),
"repeat" : lambda uid: not re.match(r".*(.).*\1.*", uid)
}
def main():
for _ in range(int(input())):
uid = input()
print("Valid" if all(checks[check](uid) for check in checks.keys()) else "Invalid")
if __name__ == "__main__":
main()
# regex solution 3:
import re
for _ in range(int(input())):
s = input()
print('Valid' if all([re.search(r, s) for r in [r'[A-Za-z0-9]{10}',r'([A-Z].*){2}',r'([0-9].*){3}']]) and not re.search(r'.*(.).*\1', s) else 'Invalid')
# regex solution 4:
[print('Valid' if all([re.search(r, s) for r in [r'[A-Za-z0-9]{10}',r'([A-Z].*){2}',r'([0-9].*){3}']]) and not re.search(r'.*(.).*\1', s) else 'Invalid') for s in [raw_input() for _ in range(int(raw_input()))]]
# regex solution 5:
import re
MATCH_UPPER = re.compile(r'[A-Z]')
MATCH_DIGIT = re.compile(r'\d')
MATCH_ALPHANUMERIC = re.compile(r'^[a-zA-Z0-9]+$')
MATCH_REPEAT_CHARACTERS = re.compile(r'^.*(.).*(\1).*$')
MATCH_LENGTH_10 = re.compile(r'^.{10}$')
def is_valid(uid):
validators = [
# it must contain at least 2 uppercase characters
contains_match(MATCH_UPPER, count=2, op='>='),
# it must contain at least 3 digits
contains_match(MATCH_DIGIT, count=3, op='>='),
# it should only contain alphanumeric characters
contains_match(MATCH_ALPHANUMERIC),
# no character should repeat
contains_match(MATCH_REPEAT_CHARACTERS, count=0),
# there must be exactly 10 characters
contains_match(MATCH_LENGTH_10)
]
return all(validator(uid) for validator in validators)
def contains_match(regex, count=1, op='=='):
op_def = {
'>=': lambda a, b: a >= b,
'==': lambda a, b: a == b,
}
def validator(uid):
op_compare = op_def[op]
return op_compare(len(regex.findall(uid)), count)
return validator
def main():
from fileinput import input
# get input
uids = [line.rstrip() for line in input()]
n = int(uids.pop(0))
# for each uid ... print (In)Valid
for i in range(n):
uid = uids[i]
print('Valid' if is_valid(uid) else 'Invalid')
if __name__ == '__main__':
main()
# https://www.hackerrank.com/challenges/word-order/problem
f ={}
N = int(input())
for _ in range(N):
s = input()
if s not in f:
f[s] = 1
else:
f[s] = f[s] + 1
print(len(f))
e = ''
for s in f:
e = e + str(f[s]) + ' '
print(e)
from collections import Counter, OrderedDict
class OrderedCounter(Counter, OrderedDict):
pass
d = OrderedCounter(input() for _ in range(int(input())))
print(len(d))
print(*d.values())
from collections import OrderedDict
words = OrderedDict()
for _ in range(int(input())):
word = input()
words.setdefault(word, 0)
words[word] += 1
print(len(words))
print(*words.values())
s = 1
r = 1
n = int(input())
for i in range(0,n):
p,q = map(int, input().split())
s = s * p
r = r * q
print(str(s) + ' ' + str(r))
48 315
# https://www.hackerrank.com/challenges/reduce-function/problem
from fractions import Fraction
from functools import reduce
def product(fracs):
t = reduce(lambda x, y : x*y,fracs)
return t.numerator, t.denominator
if __name__ == '__main__':
fracs = []
for _ in range(int(input())):
fracs.append(Fraction(*map(int, input().split())))
result = product(fracs)
print(*result)
4 21
from fractions import Fraction
fracs = []
for _ in range(int(input())):
fracs.append(Fraction(*map(int, input().split())))
print(fracs)
[Fraction(2, 5), Fraction(2, 3), Fraction(5, 7)]
#!/bin/python3
import math
import os
import random
import re
import sys
def abbreviation(a, b):
e = []
f = []
for i in range(0,len(a)):
e.append(a[i])
for j in range (0,len(b)):
f.append(b[j])
if e[i] == f[j]:
a.remove(a[i])
b.remove(b[j])
if len(a) == len(b) and a.upper() == b:
return 'YES'
elif len(a) != len(b):
for k in (0,len(a)):
if a[k].islower():
a.remove(a[k])
if a == b:
return 'YES'
else:
return 'NO'
if __name__ == '__main__':
os.environ['OUTPUT_PATH'] = 'output.txt'
fptr = open(os.environ['OUTPUT_PATH'], 'w')
q = int(input().strip())
for q_itr in range(q):
a = input()
b = input()
result = abbreviation(a, b)
fptr.write(result + '\n')
fptr.close()
['A', 'B', 'C'] ['e', 'k', 'f', 'G', 'l']
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-31-1731e4cb71a9> in <module> 41 result = abbreviation(a, b) 42 ---> 43 fptr.write(result + '\n') 44 45 fptr.close() TypeError: unsupported operand type(s) for +: 'NoneType' and 'str'
import math
import os
import random
import re
import sys
def avg(*nums):
e = list(nums)
c = 0
for i in range(0,len(e)):
c = c + e[i]
return c / len(e)
if __name__ == '__main__':
os.environ['OUTPUT_PATH'] = 'output.txt'
fptr = open(os.environ['OUTPUT_PATH'], 'w')
nums = map(int, input().split())
res = avg(*nums)
fptr.write('%.2f' % res + '\n')
fptr.close()
nums = map(int, input().split())
import math
import os
import random
import re
import sys
class Car:
def __init__(self, max_speed, speed_unit):
self.max_speed = max_speed
self.speed_unit = speed_unit
def __str__(self):
return f'car with the maximum speed of {self.max_speed} {self.speed_unit}'
class Boat:
def __init__(self, max_speed):
self.max_speed = max_speed
def __str__(self):
return f'boat with the maximum speed of {self.max_speed}'
if __name__ == '__main__':
os.environ['OUTPUT_PATH'] = 'output.txt'
fptr = open(os.environ['OUTPUT_PATH'], 'w')
q = int(input())
queries = []
for _ in range(q):
args = input().split()
vehicle_type, params = args[0], args[1:]
if vehicle_type == "car":
max_speed, speed_unit = int(params[0]), params[1]
vehicle = Car(max_speed, speed_unit)
elif vehicle_type == "boat":
max_speed = int(params[0])
vehicle = Boat(max_speed)
else:
raise ValueError("invalid vehicle type")
fptr.write("%s\n" % vehicle)
fptr.close()