Problem 1
When the user gives an input, make the uppercase characters lowercase and vice versa.
Solution 1
We use isupper()
and islower()
to detect if the characters are upper or lower respectively. Then we concatenate the opposite to the final string and return it.
def case(string):
final_string = ""
for (char in string):
(final_string += char.lower()) if (char.isupper()) else (final_string += char.upper())
return final_string
s = input()
print(case(s))
Problem 2
When user gives a string and a substring as input, find the number of times the given substring occurs in that string
Solution 2
We use a while loop. In it, we invoke string.find()
with our substring and the starting index, which will find the first occurrence of the substring and returns its index. If not found, it returns -1 which breaks the loop.
If found, we increment our accumulator as well as the starting index to search once again.
def find_str(string, substring):
count = 0
starting_index = 0
while True:
starting_index = string.find(substring, starting_index)
if (starting_index==-1): break
count+=1
starting_index+=1
return count
s = input()
substr = input()
print(find_str(s, substr))
Problem 3
Given a string input, return True if it satisfies the following conditions, else print false :
- If it has any alphanumeric characters.
- If it has any alphabetical characters.
- If it has any digits.
- If it has any lowercase characters.
- If it has any uppercase characters.
Solution 3
s = input()
print(True if (s.isalnum()) else False)
print(True if (s.isalpha()) else False)
print(True if (s.isdigit()) else False)
print(True if (s.islower()) else False)
print(True if (s.isupper()) else False)
Problem 4
Solution 4
def average(array):
array = set(array)
nums = len(array)
total = sum(array)
avg = f"{(total/nums):.3f}"
return avg
if __name__ == '__main__':
n = int(input())
arr = list(map(int, input().split()))
result = average(arr)
print(result)
Problem 5
Solution 5
test_cases = int(input())
for i in range(1, test_cases + 1):
try:
a, b = map(int, input().split())
print(a//b)
except Exception as e:
print("Error Code:", e)
Problem 6
Solution 6
import re
test_cases = int(input()) + 1
for i in range(1, test_cases):
s = input()
try:
if(re.compile(s)):
print(True)
except:
print(False)
Problem 7
Solution 7
import math
ab_side = int(input())
bc_side = int(input())
#ac square = ab square + bc square
ac_side = math.sqrt(ab_side**2 + bc_side**2)
#am = mc = mb
#we need the theta in degrees so...
tangent = math.degrees(math.atan2(ab_side, bc_side))
#rounding the degrees
tangent = int(round(tangent))
print(f"{tangent}{chr(176)}")
Problem 8
Solution
from collections import Counter
s = Counter(sorted(input())).most_common(3)
for i in s:
print(*i)
Problem 9
Solution
n = int(input())
li = list(map(int, input().split()))
one = all((i>=0) for i in li)
two = any([str(x) == str(x)[::-1] for x in li])
print(one & two)