PI = 3.1416
r = float(input("Radius of a circle: "))
area = PI * r * r
print("Area of a circle is: %.2f" %area)
Area of a circle is: 113.10
name = input("Enter your name: ")
print("Hello "+ name)
Enter your name: Samia
Hello Samia
r_s = float(input("Radius of a sphere: "))
vol = 4/3 * PI * r * r * r
print("Volume of a sphere is: %.2f" %vol)
Radius of a sphere: 3
Volume of a sphere is: 50.97
str = input("Enter a string: ")
number = int(input("Enter a number: "))
str*number
Enter a string: we
Enter a number: 6
base = float(input("Enter a number: "))
height = float(input("Enter a number: "))
area = base*height/2
print(f"Area of the triangle: {area: .2f}")
Enter a number: 4
Enter a number: 7
Area of the triangle: 14.00
# 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))
Euclidean distance between a and b is: 2.0
feet = float(input("Enter feet: "))
print("Centimeter:", feet*30.48)
Enter feet: 3
Centimeter: 91.44
height = float(input("Enter your height: "))
weight = float(input("Enter your weight: "))
bmi = weight / (height/100)**2
print(f"Your BMI is:{bmi: .2f}")
Enter your height: 155
Enter your weight: 50
Your BMI is: 20.81
binary = input('Enter a binary number: ')
decimal = 0
for digit in binary:
decimal = decimal*2 + int(digit)
print("Decimal is:", decimal)
Enter a binary number: 11
Decimal is: 3
num1 = input('Enter num1: ')
num2 = input('Enter num2: ')
# type(num1)
print(int(num1)+int(num2))
Enter num1: 2
Enter num2: 3
5
x=10 # 0000 1010
y=4 # 0000 0100
print(x&y)
print(x|y)
print(~x)
print(x^y)
0
14
-11
14
print(x>>2)
print(x<<2)
2
40
str1 = "this is a sample daTaa to test for the task"
if "is" not in str1:
print("not found")
else:
print("found")
found
if "was" not in str1:
print("not found")
else:
print("found")
not found
print(str1.upper())
THIS IS A SAMPLE DATAA TO TEST FOR THE TASK
print(str1.title())
This Is A Sample Dataa To Test For The Task
str1 = "this is a sample daTaa to test for the task"
print(str1.replace("daTaa", "Data"))
this is a sample Data to test for the task
str1.replace(" a ", " ")
str2 = "this is another sample string"
loc = str2.find("sample")
print(str2[loc:loc+6])
sample
date = "21-oct-2020"
date2 = date.split("-")
print(date2)
print('Date: {0}\nMonth: {1}\nYear: {2}'.format(*date2))
['21', 'oct', '2020']
Date: 21
Month: oct
Year: 2020
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])
8888
credit_str = "1234-5678-9878-0434"
loc = credit_str.find("0")
print(credit_str[loc:loc+1])
0
number = 1
convert_to_string = str(number)
print(convert_to_string)
1
str1 = input('Enter str1: ')
str2 = input('Enter str2: ')
print(str1, str2)
Enter str1: hey
Enter str2: samia
hey samia
given_string = "Apples is differnt from Apple Inc"
print(given_string.split(" "))
['Apples', 'is', 'differnt', 'from', 'Apple', 'Inc']
a = {(1,2):1,(2,3):2}
print(type(a))
a[(1,2)]
<class 'dict'>
a = [1,2,3,4,5]
for i in range(len(a)):
print(a[i])
1
2
3
4
5
a=[1,2,3,4,5,6,7,8,9]
print(a[1:8:2])
[2, 4, 6, 8]
ans = (1,2)*5
print(ans)
(1, 2, 1, 2, 1, 2, 1, 2, 1, 2)
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)
['Mobile', 'Laptop', 'Camera', 'Speakers', 'Television', 'Laptop Case', 'Camera Lens']
# Dont understand the question
# Dont understand the question
for i in range(1,10):
if i%2==0 and i%5!=0:
print(i)
2
4
6
8
# 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)
[[1, 2, 3], [4, 5, 6], [8, 9, 10], [12, 13, 14]]
dict = {'c': 97, 'a': 96, 'b': 98}
print(sorted(dict.values()))
[96, 97, 98]
dict = {1:'a', 2: 'b', 3: 'c'}
print(dict)
{1: 'a', 2: 'b', 3: 'c'}
dict = {1:'a', 'new': 23, 3: 'c', 'another_key': 'this is a value of string'}
print(dict)
{1: 'a', 'new': 23, 3: 'c', 'another_key': 'this is a value of string'}
ans = {}
ans = dict()
# Dont understand the question
ans = dict()
for i in range(6):
ans[i] = i**2
print(ans)
{0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
n = 10
ans = dict()
for i in range(n+1):
if i%2!=0:
ans[i] = i**2
print(ans)
{1: 1, 3: 9, 5: 25, 7: 49, 9: 81}
d = {1: 'a', 2: 'b', 3: 'c'}
res = dict()
for key, val in d.items():
res[val] = key
print(res)
{'a': 1, 'b': 2, 'c': 3}
d = {'k1':[{'nest_key':['this is deep','hello']}]}
print(d.get('k1')[0].get('nest_key')[1])
hello
num1 = int(input('Enter num1: '))
num2 = int(input('Enter num2: '))
if(num1%num2 == 0):
print("Divisible")
else:
print("Not Divisible")
Enter num1: 10
Enter num2: 5
Divisible
num1 = int(input('Enter num1: '))
if(num1%2 == 0):
print("Even number")
else:
print("Odd Number")
Enter num1: 4
Even 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")
Enter a character: e
Vowel
num = int(input('Enter num: '))
print("Sum is:", int(num*(num+1)/2))
Enter num: 4
Sum is: 10
num = input('Enter num: ')
sum = 0
for i in range(len(num)):
sum = sum + int(num[i])
print(sum)
Enter num: 1231
7
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)
Enter string: samia12356&
Numbers: 5 , Alphabets: 5 , Special: 1
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('')
5
*
* *
* * *
* * * *
* * * * *
* * * *
* * *
* *
*
from collections import Counter
print(Counter('This is a string'))
Counter({'i': 3, 's': 3, ' ': 3, 'T': 1, 'h': 1, 'a': 1, 't': 1, 'r': 1, 'n': 1, 'g': 1})
try:
x=5/0
except:
print("Error: Cannot divide a number by 0, please try to divide without zero")
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")
unsupported operand type(s) for ** or pow(): 'str' and 'int'
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()
Enter a number:r
An error occurred! Please try again!
Enter a number:4
Thank you, you number squared is: 16
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)
Enter a number: 4
Factorial: 24
num = int(input("Enter a number: "))
color = ['Blue', 'Green', 'Orange', 'Red']
for i in range(len(color)):
if(i==(num)):
print(color[i])
Enter a number: 3
Red
a = 2
sum = 0
j = 1
for i in range(4):
sum = sum + (a**j)
# print(a**j)
j+=1
print(sum)
30
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_)
enter a number:2
2
22
+
---------
24
comma_text = input("Enter text with comma: ")
comma_text = comma_text.split(',')
result = []
for i in comma_text:
result.append(i)
print(result)
Enter text with comma: I, have, a, pen
['I', ' have', ' a', ' pen']
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)
D: 100,150,180
[18, 22, 24]
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))
Enter text:I have my have banana
I banana have my
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)
Enter numbers:0100,0011,1010,1001
1010
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)
[13, 5, 1, 3, 8]
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")
Enter year:2016
leap year
b = lambda x:x.count('1')
b(input("enter bit strearm: "))
enter bit strearm: 1010
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))
I love my country and mother
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))
0
1
1
2
3
5
8
13
21
34
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)
permutations:
(1, 2)
(1, 3)
(1, 4)
(2, 1)
(2, 3)
(2, 4)
(3, 1)
(3, 2)
(3, 4)
(4, 1)
(4, 2)
(4, 3)
combinations:
(1, 2)
(1, 3)
(1, 4)
(2, 3)
(2, 4)
(3, 4)
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()
Enter an odd number:11
*
***
*****
*******
*********
***********
*********
*******
*****
***
*
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")
Please select: -
1. Add
2. Subtract
3. Multiply
4. Divide
Enter any one number: 1, 2, 3, 4 :4
Enter Number 1: 5
Enter Number 2: 6
5 / 6 = 0.8333333333333334
def rev(string):
if len(string)==1:
return(string[0])
if len(string)!=0:
return string[-1]+ rev(string[:-1])
string1 = input()
rev(string1)
nafisa
str1 = "naeem"
for i in range(len(str1)):
new_str = str1[i:]+ str1[:i]
print(new_str)
naeem
aeemn
eemna
emnae
mnaee
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)
Please Enter Num1 : 10
Please Enter Num2 : 45
5
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)
The quick brown fox jumps over the lazy dog
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))
1 + 4 = 5
[0, 3]
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)
Please Enter Num1 : 54
Please Enter Num2 : 24
216.0
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)
45
3
3 is a Prime Factor of 45
5
5 is a Prime Factor of 45
9
15
45
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_)
9
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)
1
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)
abc
acb
bac
bca
cab
cba
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)
Enter a string: it is.
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')
Enter the number of disks: 3
Move disk 1 from A to C.
Move disk 2 from A to B.
Move disk 1 from C to B.
Move disk 3 from A to C.
Move disk 1 from B to A.
Move disk 2 from B to C.
Move disk 1 from A to 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)
pi= 3.1415926535714034
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")
4565
[4, 5, 6, 5]
Not Harshed
import random
random_word_list = ["I", "learning", "python", "datascience", "machinelearning"]
random_word = random.choice(random_word_list)
print(random_word)
python
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)))
[10, 15, 20, 25, 30]
my_list = [ 2, 3, 4, 5, 6]
print(list(map(lambda x:x*5, filter(lambda i:i%2, my_list))))
[15, 25]
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)])
[6, 7]
[7, 8]
[8, 9]
a = [1,2,3]
b = [4,5,6]
print(list(map(lambda x,y: x+y, a, b)))
[5, 7, 9]
a = [1,2]
b = [3,4]
c = [5,6]
print(list(map(lambda x,y,z: x+y+z, a, b, c)))
[9, 12]
a = [1,2,3]
b = [4,5,6]
print(sum(list(map(lambda x,y: x*y, a, b))))
32
a = [1,2]
b = [3,4]
c = [5,6]
print(list(map(lambda x,y,z: x+y+z, a, b, c)))
[9, 12]
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)
3 4
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
I am guessing a number between 1 to 30, what is that?
20
Your guess is too high.
10
Your guess is too high.
5
Your guess is too low.
7
Perfect
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))
3.0
3.0
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)
[1]
[1, 1]
[1, 2, 1]
[1, 3, 3, 1]
[1, 4, 6, 4, 1]
[1, 5, 10, 10, 5, 1]
[1, 6, 15, 20, 15, 6, 1]
[1, 7, 21, 35, 35, 21, 7, 1]
[1, 8, 28, 56, 70, 56, 28, 8, 1]
[1, 9, 36, 84, 126, 126, 84, 36, 9, 1]
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=" ")
Enter a number: 6
0 1 1 2 3 5
# I am not sure about the question :/
from collections.abc import Iterable
n = input()
if isinstance(n, Iterable):
print("Iterable")
else:
print("Not iterable")
samia
Iterable