PI = 3.1416
r = float(input("Radius of a circle: "))
area = PI * r * r
print("Area of a circle is: %.2f" %area)
name = input("Enter your name: ")
print("Hello "+ name)
r_s = float(input("Radius of a sphere: "))
vol = 4/3 * PI * r * r * r
print("Volume of a sphere is: %.2f" %vol)
str = input("Enter a string: ")
number = int(input("Enter a number: "))
str*number
base = float(input("Enter a number: "))
height = float(input("Enter a number: "))
area = base*height/2
print(f"Area of the triangle: {area: .2f}")
# Dont know :/
a1 = 2
a2 = 5
b1 = 4
b2 = 5
print("Euclidean distance between a and b is:", math.sqrt((b1-a1)**2 + (b2-a2)**2))
feet = float(input("Enter feet: "))
print("Centimeter:", feet*30.48)
height = float(input("Enter your height: "))
weight = float(input("Enter your weight: "))
bmi = weight / (height/100)**2
print(f"Your BMI is:{bmi: .2f}")
binary = input('Enter a binary number: ')
decimal = 0
for digit in binary:
decimal = decimal*2 + int(digit)
print("Decimal is:", decimal)
num1 = input('Enter num1: ')
num2 = input('Enter num2: ')
# type(num1)
print(int(num1)+int(num2))
x=10 # 0000 1010
y=4 # 0000 0100
print(x&y)
print(x|y)
print(~x)
print(x^y)
print(x>>2)
print(x<<2)
str1 = "this is a sample daTaa to test for the task"
if "is" not in str1:
print("not found")
else:
print("found")
if "was" not in str1:
print("not found")
else:
print("found")
print(str1.upper())
print(str1.title())
str1 = "this is a sample daTaa to test for the task"
print(str1.replace("daTaa", "Data"))
str1.replace(" a ", " ")
str2 = "this is another sample string"
loc = str2.find("sample")
print(str2[loc:loc+6])
date = "21-oct-2020"
date2 = date.split("-")
print(date2)
print('Date: {0}\nMonth: {1}\nYear: {2}'.format(*date2))
arr = [10,20,30,40,50,60,70]
arr[4:6]
arr[-3:-1]
credit_str = "xxxx----xxxx-8888------xxxx"
loc = credit_str.find("8888")
print(credit_str[loc:loc+4])
credit_str = "1234-5678-9878-0434"
loc = credit_str.find("0")
print(credit_str[loc:loc+1])
number = 1
convert_to_string = str(number)
print(convert_to_string)
str1 = input('Enter str1: ')
str2 = input('Enter str2: ')
print(str1, str2)
given_string = "Apples is differnt from Apple Inc"
print(given_string.split(" "))
a = {(1,2):1,(2,3):2}
print(type(a))
a[(1,2)]
a = [1,2,3,4,5]
for i in range(len(a)):
print(a[i])
a=[1,2,3,4,5,6,7,8,9]
print(a[1:8:2])
ans = (1,2)*5
print(ans)
gadgets = ["Mobile", "Laptop", 100, "Camera", 310.28, "Speakers", 27.00, "Television", 1000, "Laptop Case", "Camera Lens"]
list_str = []
list_int = []
for i in gadgets:
t = type(i)==str
if t:
list_str.append(i)
else:
list_int.append(i)
print(list_str)
# Dont understand the question
# Dont understand the question
for i in range(1,10):
if i%2==0 and i%5!=0:
print(i)
# Dont understand the question
arr = [[1, 2, 3, 4], [4, 5, 6, 7], [8, 9, 10, 11], [12, 13, 14, 15]]
for i in range(len(arr)):
arr[i].pop()
print(arr)
dict = {'c': 97, 'a': 96, 'b': 98}
print(sorted(dict.values()))
dict = {1:'a', 2: 'b', 3: 'c'}
print(dict)
dict = {1:'a', 'new': 23, 3: 'c', 'another_key': 'this is a value of string'}
print(dict)
ans = {}
ans = dict()
# Dont understand the question
ans = dict()
for i in range(6):
ans[i] = i**2
print(ans)
n = 10
ans = dict()
for i in range(n+1):
if i%2!=0:
ans[i] = i**2
print(ans)
d = {1: 'a', 2: 'b', 3: 'c'}
res = dict()
for key, val in d.items():
res[val] = key
print(res)
d = {'k1':[{'nest_key':['this is deep','hello']}]}
print(d.get('k1')[0].get('nest_key')[1])
num1 = int(input('Enter num1: '))
num2 = int(input('Enter num2: '))
if(num1%num2 == 0):
print("Divisible")
else:
print("Not Divisible")
num1 = int(input('Enter num1: '))
if(num1%2 == 0):
print("Even number")
else:
print("Odd Number")
char = input('Enter a character: ')
if(char == 'a' or char == 'e' or char =='i' or char =='o' or char =='u'):
print("Vowel")
else:
print("Not Vowel")
num = int(input('Enter num: '))
print("Sum is:", int(num*(num+1)/2))
num = input('Enter num: ')
sum = 0
for i in range(len(num)):
sum = sum + int(num[i])
print(sum)
str2 = input('Enter string: ')
num = 0
alpha = 0
spec = 0
for i in range(len(str2)):
if(str2[i].isalpha()):
alpha+=1
elif(str2[i].isdigit()):
num+=1
else:
spec+=1
print("Numbers:", num, ", Alphabets:", alpha, ", Special:", spec)
n = int(input())
num = n
for i in range(n):
for j in range(i):
print("*", end=' ')
print('')
for i in range(n, 0, -1):
for j in range(0, i):
print("*", end=' ')
print('')
from collections import Counter
print(Counter('This is a string'))
try:
x=5/0
except:
print("Error: Cannot divide a number by 0, please try to divide without zero")
try:
li=["hello","class"]
for i in li:
print (i**2)
except TypeError as type_err:
print(type_err)
print("typeError")
def input_sqr():
while True:
try:
val=int(input("Enter a number:"))
print("Thank you, you number squared is:", val**2)
except:
print("An error occurred! Please try again!")
continue
else:
break
a=input_sqr()
res = []
test_str = "population of finland test1 is mmn-437 5000000 and area is 12345 sq km"
temp = test_str.split()
for idx in temp:
if any(chr.isalpha() for chr in idx) and any(chr.isdigit() for chr in idx):
res.append(idx)
res
# Dont understanhd
dna="ATTGC"
dict_ = {'A':'T','T':'A','C':'G','G':'C'}
"".join((dict_[i]) for i in dna)
num = int(input("Enter a number: "))
fac = 1
i = 1
while i <= num:
fac = fac * i
i+=1
print("Factorial: ",fac)
num = int(input("Enter a number: "))
color = ['Blue', 'Green', 'Orange', 'Red']
for i in range(len(color)):
if(i==(num)):
print(color[i])
a = 2
sum = 0
j = 1
for i in range(4):
sum = sum + (a**j)
# print(a**j)
j+=1
print(sum)
num_=input("enter a number:")
sum_=0
for i in range(1,int(num_)+1):
sum_= sum_ + int(num_*i)
print(num_*i)
print("+\n---------")
print(sum_)
comma_text = input("Enter text with comma: ")
comma_text = comma_text.split(',')
result = []
for i in comma_text:
result.append(i)
print(result)
import math
numbers_list = input("D: ")
c = 50
h = 30
numbers_list = numbers_list.split(',')
result = []
for D in numbers_list:
Q = round(math.sqrt(2 * c * int(D) / h))
result.append(Q)
print(result)
str3 = input("Enter text:")
str_splited = str3.split(' ')
word_list = []
for i in str_splited:
if i not in word_list:
word_list.append(i)
else:
continue
word_list.sort()
print((' ').join(word_list))
binary_input = input("Enter numbers:")
bin_splited = binary_input.split(',')
number_list = []
for i in bin_splited:
number_list.append(i)
for i in number_list:
# print(int(i,2))
if(int(i, 2)%5 == 0):
print(i)
num = [10,13,15,5,4,1,2,3,7,8]
li = []
for i in range(10):
if(i%2!=0):
li.append(num[i])
print(li)
sum_num = lambda x,y: x+y
sum_num(4,5)
year = int(input("Enter year:"))
if (year%4 == 0):
if (year%100 == 0):
if (year%400 == 0):
print("leap year")
else:
print("leap year")
else:
print("leap year")
else:
print("not a leap year")
b = lambda x:x.count('1')
b(input("enter bit strearm: "))
import math
area = lambda x: math.pi * x * x
area(4)
def factorial(n):
if n == 1:
return n
else:
return n*factorial(n-1)
factorial(4)
str1 = "I love my country and I love my mother"
lst = str1.split()
# print(lst)
lst2 = []
for i in lst:
if (str1.count(i)>=1 and (i not in lst2)):
lst2.append(i)
# print(lst2)
print(' '.join(lst2))
num=10
def fibo(n):
if n <= 1:
return n
else:
return(fibo(n-1) + fibo(n-2))
for i in range(num):
print(fibo(i))
from itertools import permutations
from itertools import combinations
perm = permutations([1, 2, 3, 4], 2)
print("permutations:")
for i in list(perm):
print (i)
comb = combinations([1, 2, 3, 4], 2)
print("combinations:")
for i in list(comb):
print (i)
n = int(input("Enter an odd number:"))
rows = math.ceil(n/2)
for i in range(1, rows+1):
for j in range (1, rows-i+1):
print(end = " ")
for k in range(2*i-1):
print("*", end = "")
print()
k = 1
n = 1
for i in range(1, rows):
# loop to print spaces
for j in range (1, k + 1):
print(end = " ")
k = k + 1
# loop to print star
while n <= (2 * (rows - i) - 1):
print("*", end = "")
n = n + 1
n = 1
print()
def draw_diamond(size=5):
for i in range(size):
print(" "*(size-i), "*"*(i*2+1))
for i in range(size-2,-1,-1):
print(" "*(size-i), "*"*(i*2+1))
draw_diamond(11)
num = 9
for i in range(1, num+1):
i = i - (num//2 +1)
if i < 0:
i = -i
print(" " * i + "*" * (num - i*2) + " "*i)
def add(num1, num2):
return num1 + num2
def sub(num1, num2):
return num1 - num2
def multi(num1, num2):
return num1 * num2
def div(num1, num2):
return num1 / num2
print("Please select: -\n" \
"1. Add\n" \
"2. Subtract\n" \
"3. Multiply\n" \
"4. Divide\n")
n = int(input("Enter any one number: 1, 2, 3, 4 :"))
number_1 = int(input("Enter Number 1: "))
number_2 = int(input("Enter Number 2: "))
if n == 1:
print(number_1, "+", number_2, "=", add(number_1, number_2))
elif n == 2:
print(number_1, "-", number_2, "=", sub(number_1, number_2))
elif n == 3:
print(number_1, "*", number_2, "=", multi(number_1, number_2))
elif n == 4:
print(number_1, "/", number_2, "=", div(number_1, number_2))
else:
print("Invalid input")
def rev(string):
if len(string)==1:
return(string[0])
if len(string)!=0:
return string[-1]+ rev(string[:-1])
string1 = input()
rev(string1)
str1 = "naeem"
for i in range(len(str1)):
new_str = str1[i:]+ str1[:i]
print(new_str)
def gcd(a, b):
if(b == 0):
return a;
else:
return gcd(b, a%b)
num1 = int(input("Please Enter Num1 : "))
num2 = int(input("Please Enter Num2 : "))
gcd_val = gcd(num1, num2)
print(gcd_val)
text = input()
import string
def is_pangram(s, alphabet = string.ascii_lowercase):
return set(alphabet) == set(s.replace(" ", "").lower())
# The quick brown fox jumps over the lazy dog
is_pangram(text)
def find_sum(target, lst):
indices = {x1: i for i, x1 in enumerate(lst)}
for i, x1 in enumerate(lst):
x2 = target - x1
if x2 in indices:
print(lst[i],"+",lst[indices[x2]],"=",target)
return [i, indices[x2]]
return None
lst = [1,2,3,4,5,6,7,8]
print(find_sum(5, lst))
def gcd(a, b):
if(b == 0):
return a;
else:
return gcd(b, a%b)
num1 = int(input("Please Enter Num1 : "))
num2 = int(input("Please Enter Num2 : "))
gcd_val = gcd(num1, num2)
print(num1*num2/gcd_val)
def prime_factor(num):
for x in range(2, num+1):
if(num%x == 0):
print(x)
chk_prime = 1
for y in range(2, (x//2+1)):
if(x%y == 0):
chk_prime = 0
break
if (chk_prime == 1):
print(" %d is a Prime Factor of %d" %(x, num))
n = int(input())
prime_factor(n)
def prime_factor(num):
i = 2
prime = []
while i * i <=num:
if num % i == 0:
prime.append(i)
num//=i
else:
i+=1
if num>1:
prime.append(num)
return prime
prime_factor(45)
def NotRepeatChar(my_string):
for c in my_string:
if my_string.index(c) == my_string.rindex(c):
return c
NotRepeatChar("hhaaaabbbbggcdfg")
arr = [1,2,3,4,5]
sum_=0
for i in range(1,len(arr)-1):
sum_+=arr[i]
print(sum_)
def Five_convert(str_):
li=[]
for i in str_:
if int(i)<5:
li.append(0)
elif int(i)>=5:
li.append(1)
return ' '.join([str(j) for j in li]).replace(' ','')
Five_convert("123456789")
"""
from Geeks for Geeks I understand the maths :)
14/09/1998
dd=14
mm=09
yyyy=1998 //non-leap year
Step 1: Informations to be remembered.
Magic Number Month array.
For Year: {0,3,3,6,1,4,6,2,5,0,3,5}
DAY array starting from 0-6: {Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday}
Century Year Value: 1600-1699 = 6
1700-1799 = 4
1800-1899 = 2
1900-1999 = 0
2000-2099 = 6..
Step 2: Calculations as per the steps
Last 2 digits of the year: 98
Divide the above by 4: 24
Take the date(dd): 14
Take month value from array: 5 (for September month number 9)
Take century year value: 0 ( 1998 is in the range 1900-1999 thus 0)
-----
Sum: 141
Divide the Sum by 7 and get the remainder: 141 % 7 = 1
Check the Day array starting from index 0: Day[1] = Monday
**If leap year it will be the remainder-1
"""
def dayofweek(d, m, y):
t = [ 0, 3, 2, 5, 0, 3, 5, 1, 4, 6, 2, 4 ]
y -= m < 3
return (( y + int(y / 4) - int(y / 100)
+ int(y / 400) + t[m - 1] + d) % 7)
day = dayofweek(30, 8, 2010)
print(day)
def permute(li):
if len(li) <= 1:
yield li
else:
for n in range(0,len(li)):
for end in permute( li[:n] + li[n+1:] ):
yield li[n] + end
for i in permute('abc'):
print(i)
def all_subsets(list_items):
subsets = [[]]
for i in list_items:
items = subsets[:]
for j in range(len(subsets)):
subsets[j] = subsets[j] + [i]
subsets = items + subsets
return subsets[1:]
all_subsets('abc')
def lengthOfLastWord(s):
str_arr = s.split()
if len(str_arr) == 0:
return 0
else:
return len(str_arr[-1])
s=input('Enter a string: ')
lengthOfLastWord(s)
def tower_of_hanoi(disks, source, auxiliary, target):
if(disks == 1):
print('Move disk 1 from {} to {}.'.format(source, target))
return
tower_of_hanoi(disks-1, source, target, auxiliary)
print('Move disk {} from {} to {}.'.format(disks, source, target))
tower_of_hanoi(disks-1, auxiliary, source, target)
disks = int(input('Enter the number of disks: '))
tower_of_hanoi(disks, 'A', 'B', 'C')
import math
series = 0
for k in range(20):
series += math.pow(-3, -k) / (2*k+1)
pi = math.sqrt(12)*series
print('pi=', pi)
num = input()
l=[int(num[x]) for x in range(len(num))]
print(l)
if(int(num)%sum(l)==0):
print("Harshed")
else:
print("Not Harshed")
import random
random_word_list = ["I", "learning", "python", "datascience", "machinelearning"]
random_word = random.choice(random_word_list)
print(random_word)
def hang_man(word,clue,letter,try_left):
# create a variable "try" and set it to True
# your code
Try = True
#--------------------------------
# loop through the length of the word
# your code
# check condition if word is equal to letter
#the set clue= clue from o to current index of loop + letter + clue from current index +1 to last
# your code
#set try to false
# your code
#---------------------------------------------------
# check condition if try is true then decrease the try_left by 1
# your code
print("wrong try", try_left)
print("you got so far",clue)
# check if word is equal to clue:
if word == clue:
print("you win")
# check is try_left is 0:
elif try_left==0:
print("you lost")
else:
# ask user to input next letter
#next_letter="your code"
# call the recursive function of itself
word=# call a function select word
clue= blank(word)
call a function hang_man() where set letter to word[0] and try_left to=5
my_list = [ 2, 3, 4, 5, 6]
print(list(map(lambda x:x*5, my_list)))
my_list = [ 2, 3, 4, 5, 6]
print(list(map(lambda x:x*5, filter(lambda i:i%2, my_list))))
x=[2,3,4]
y=[4,5]
li=[]
for i in x:
li.append([i,i])
for i in range(len(li)):
print([a+b for a,b in zip(li[i],y)])
a = [1,2,3]
b = [4,5,6]
print(list(map(lambda x,y: x+y, a, b)))
a = [1,2]
b = [3,4]
c = [5,6]
print(list(map(lambda x,y,z: x+y+z, a, b, c)))
a = [1,2,3]
b = [4,5,6]
print(sum(list(map(lambda x,y: x*y, a, b))))
a = [1,2]
b = [3,4]
c = [5,6]
print(list(map(lambda x,y,z: x+y+z, a, b, c)))
def pythagorean(c):
for b in range(1,c):
# print(b)
for a in range(1,b):
# print(a)
if ((a**2 + b**2) == c**2):
print(a, b)
pythagorean(5)
import random
guessesTaken = 0
print("I am guessing a number between 1 to 30, what is that?")
number = random.randint(1, 30)
while True:
user_num = int(input())
if user_num == 0:
break
if user_num < number:
print('Your guess is too low.')
if user_num > number:
print('Your guess is too high.')
if user_num == number:
print('Perfect')
break
import math
def babylonian(num):
x = num
y = 1
error = 0.000000001
while x-y > error:
x = (x + y)/2;
y = num/x;
return x
print(math.sqrt(9))
print(babylonian(9))
def pascals(n):
if n == 1:
return [[1]]
else:
result = pascals(n-1)
current = [1]
previous = result[-1]
for i in range(len(previous)-1):
current.append(previous[i] + previous[i+1])
current += [1]
result.append(current)
return result
triangle = pascals(10)
for row in triangle:
print(row)
def fib(n):
if n <=1:
return n
else:
return fib(n-1) + fib(n-2)
n = int(input("Enter a number: "))
for i in range(n):
print(fib(i),end=" ")
# I am not sure about the question :/
from collections.abc import Iterable
n = input()
if isinstance(n, Iterable):
print("Iterable")
else:
print("Not iterable")