[go: up one dir, main page]

0% found this document useful (0 votes)
99 views8 pages

Hackerrank Answers

Uploaded by

Mudadla.Poornima
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
99 views8 pages

Hackerrank Answers

Uploaded by

Mudadla.Poornima
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 8

1.

python if else:
n=int(input())
if(n%2==0 and 2<n<5):
print("Not Weird")
elif(n%2==0and 6<n<20):
print("Weird")
elif(n%2==1):
print("Weird")
elif(n%2==0 and n>20):
print("Not Weird")
else:
print("Weird")

2.Arithmetic operators:
a=int(input())
b=int(input())
print(a+b)
print(a-b)
print(a*b)

3.python:division
a=int(input())
b=int(input())
print(a//b)
print(a/b)

4.loops
a=int(input())
for i in range(a):
print(i*i)

5.write a function
def is_leap(year):
leap = False

# Write your logic here


if(year%400==0 or((year%100!=0)and (year%4==0))):
return True
return leap

print function:

n = int(input())
for i in range(1,n+1):
print(i,end="")

6.list comprehensions:
x = int(input())
y = int(input())
z = int(input())
n = int(input())

coordinates = [[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(coordinates)

7.find the runner up score


n = int(input())
list1= list(map(int, input().split()))
res_list1 = set(list1)
#removing the maximum element
res_list1.remove(max(res_list1))

#printing the second largest element


print(max(res_list1))

8.finding the percentage:


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()
average=sum(student_marks[query_name])/len(student_marks[query_name])
print("{:.2f}".format(average))
9.lists
N = int(input())
list_ = []
for _ in range(N):
command, *args = input().split()
if command == 'insert':
list_.insert(int(args[0]), int(args[1]))
elif command == 'print':
print(list_)
elif command == 'remove':
list_.remove(int(args[0]))
elif command == 'append':
list_.append(int(args[0]))
elif command == 'sort':
list_.sort()
elif command == 'pop':
list_.pop()
elif command == 'reverse':
list_.reverse()

10.tuples:
n = int(input())
integer_list = map(int, input().split())
tuple=tuple(integer_list)
print(hash(tuple))

11.swap case:
def swap_case(s):
swap=""
for char in s:
if char.islower():
swap+=char.upper()
elif char.isupper():
swap+=char.lower()
else:
swap+=char
return swap

12.string split and join:

def split_and_join(line):
# write your code here
b=line.split(" ")
result="-".join(b)
print(result)

if __name__ == '__main__':
line = input()
result = split_and_join(line)

13.what’s your name:


def print_full_name(first, last):
# Write your code here
print("Hello", first_name, last_name + "! You just delved into python.")
14.find a string:
def count_substring(string, sub_string):
c=0
for i in range(len(string)):
if (string[i:i+len(sub_string)] == sub_string):
c += 1
return c

15.the minion game


def minion_game(string):
vowels = 'AEIOU'
length = len(string)
stuart_score = 0
kevin_score = 0
for i in range(length):
if string[i] in vowels:
# If the current character is a vowel, Kevin gets points for substrings starting from this position
kevin_score += length - i
else:
# If the current character is a consonant, Stuart gets points for substrings starting from this
position
stuart_score += length - i

# Determine the winner and print the result


if stuart_score > kevin_score:
print("Stuart", stuart_score)
elif kevin_score > stuart_score:
print("Kevin", kevin_score)
else:
print("Draw")

16. merge the tools:


def merge_the_tools(string, k):
# Divide the string into equal parts of length k
substrings = [string[i:i+k] for i in range(0, len(string), k)]
# Process each substring
for substring in substrings:
# Create a set to keep track of characters encountered
seen = set()
# Construct the resulting string
result = ''
for char in substring:
# If the character is not already encountered, add it to the result string
if char not in seen:
result += char
seen.add(char)
# Print the resulting string
print(result)

17.calender module
from datetime import datetime
def get_day_of_week(date):
date_obj = datetime.strptime(date, "%m %d %Y")
day_of_week = date_obj.strftime("%A")
return day_of_week.upper()
# Test the function with sample input
date = input()
day_of_week = get_day_of_week(date)
print(day_of_week)

18.exceptions
n=int(input())
for _ in range(n):
try:
a, b = map(int, input().split())
result = a // b
print(result)
except ZeroDivisionError as e:
print("Error Code:", e)
except ValueError as e:
print("Error Code:", e)

19.Time delta
from datetime import datetime, timedelta
# Function to convert the timestamp string to a datetime object
def parse_timestamp(timestamp):
return datetime.strptime(timestamp, "%a %d %b %Y %H:%M:%S %z")

# Function to calculate the time difference in seconds


def time_difference(timestamp1, timestamp2):
dt1 = parse_timestamp(timestamp1)
dt2 = parse_timestamp(timestamp2)
diff = abs(dt1 - dt2)
return int(diff.total_seconds())
# Read the number of testcases
num_testcases = int(input())
# Process each testcase
for _ in range(num_testcases):
timestamp1 = input().strip()
timestamp2 = input().strip()
diff_seconds = time_difference(timestamp1, timestamp2)
print(diff_seconds)

20.No idea!
def calculate_happiness(array, set_A, set_B):
happiness = 0
for num in array:
if num in set_A:
happiness += 1
elif num in set_B:
happiness -= 1
return happiness
# Read input from stdin
n, m = map(int, input().split())
array = list(map(int, input().split()))
set_A = set(map(int, input().split()))
set_B = set(map(int, input().split()))

21.collections ordered dict()


def net_prices(n):
item_prices = {}
for _ in range(n):
item_info = input().split()
item_name = " ".join(item_info[:-1]) # Join all but the last element to form the item name
price = int(item_info[-1])
item_prices[item_name] = item_prices.get(item_name, 0) + price
return item_prices

# Test the function with sample input


n = int(input())
net_prices = net_prices(n)
for item_name, net_price in net_prices.items():
print(item_name, net_price)

22.symmetric difference
M = int(input())
set_a = set(map(int, input().split()))
N = int(input())
set_b = set(map(int, input().split()))
# Calculate the symmetric difference
symmetric_diff = set_a.symmetric_difference(set_b)
# Sort the symmetric difference in ascending order
sorted_diff = sorted(symmetric_diff)
# Print the symmetric difference, one per line
for num in sorted_diff:
print(num)

23.itertools().combinations:
from itertools import combinations
# Read input from stdin
string, size = input().split()
size = int(size)
# Sort the string
string = sorted(string)
# Generate and print the combinations
for r in range(1, size+1):
for comb in combinations(string, r):
print(''.join(comb))

24.set.add()
def count_stamps(n):
stamps=set()
for i in range(n):
country=input()
stamps.add(country)
return len(stamps)
n=int(input())
b=count_stamps(n)
print(b)

25.maximize it:
from itertools import product
n, m = map(int, input().split())
lists = []
for _ in range(n):
lists.append(list(map(int, input().split()[1:])))
max_value = 0
for elements in product(*lists):
value = sum(x**2 for x in elements) % m
max_value = max(max_value, value)
print(max_value)

You might also like