Joy of Computing
Joy of Computing
if
elif
while
for
and
or
not !=
trimmed mean remove 10% smallest and 10% largest values from a given dataset
depends on us the percentage to be taken
sort the data
remove 10% smallest and largest values
floor value
calculate avg of the given set now
list.sort()
#to print the sorted list
l=[100,12,5,56,2456,278,236,59,347,267]
l.sort()
for i in range(len(l)):
print(l[i])
since we just passed one array python generates x values on its own
but here we don't need x or y axis
so we will take list l as x axis and keep y axis constant
l=[1,2,3,4,5,6,7,8,9,10]
y=[]
for i in range(len(l)):
y.append(5)#can take any constant value
plt.plot(l,y)#it shows continuos values since it is discrete we will show it more
properly
plt.plot(l,y,'r--')
#sum of list
def sum_of_list(L):
total=0
for i in range(len(L)):
total=total+L[i]
return total
L=[1,2,3,4,5,6,7,8,9,10]
total_sum=sum_of_list(L)
print(total_sum)
#to check if a is divisible by b
a=int(input("enter 1st no."))
b=int(input("enter 2nd no."))
while(1):
if(a%b==0):
print("Wow...")
break
else:
print("if you want to continue press 1 or else 0")
choice=int(input())
if(choice==1):
b=int(input("enter second number again"))
if(choice==0):
break
#file handling
with open("filename.txt","w") as alias_name:#to open file
print(alias_name.read())#to read the file
alias_name.write("your text")#to write in the file
alias_name.close()#to close the file
#different modes
w-> to write in the file
r-> to read the file
a-> to append at the end of file without truncating it
+-> for updating(reading and writing)
r+-> reading as well as writing
f=open("file_name.txt")#equivalent to "r"
def evolve(x):
index=random.randint(0,len(x)-1)
p=random.randint(1,100)
if (p==1):
if (x[index]=='0'):
x[index]=='1'
else:
s[index]=='0'
with open("dna_data.txt") as myfile:
x=myfile.read()
x=list(x)
for i in range(0,10000):
evolve(x)
print(x)
#You are given a list named L. Print all the elements at odd position of list L.(We
will take care of the input, you just have to print elements present at odd
position)
L = [int(i) for i in input().split()]
for i in range(len(L)):
if(i%2!=0):
print(L[i])
#You are given a list L. Print the list of first 3 smallest elements in ascending
order and last 2 greatest elements in descending order of the list L respectively.
(We will take care of the input)
L=[some list]
L.sort()
print(L[:4])
print(L[-2:])
or
L = [int(i) for i in input().split()]
L.sort()
print(L[0:3])
L.reverse()
print(L[0:2])
#You are given a list L. Write a function all_even that accepts the list L and
print all the even numbers is the list L.(Order of the numbers should be same as
the order present in the list)
def all_even(L):
for i in L:
if i%2 == 0:
print(i)
L = [int(i) for i in input().split()]
all_even(L)
#magic square
def magic_square(n):
magicSquare=[]
for i in range(n ):
l=[]
for j in range(n):
l.append(0)
magicSquare.append(l)
for i in range(n):
#l=[]
for j in range(n):
#l.append(0)
print(magicSquare[i][j],end=" ")
print()
#method 2
magic=[[0 for i in range(3)] for j in range(3)]
print(string.ascii_letters)
#prints all lower case and upper case letters
#import string to use this
#dobble game
import string
import random
symbols=[]
symbols=list(string.ascii_letters)
card1=[0]*5
card2=[0]*5
pos1=random.randint(0,4)
pos2=random.randint(0,4)
print(pos1)
print(pos2)
samesymbol=random.choice(symbols)
symbols.remove(samesymbol)
if(pos1==pos2):
card2[pos1]=samesymbol
card1[pos1]=samesymbol
else:
card1[pos1]=samesymbol
card2[pos2]=samesymbol
card1[pos2]=random.choice(symbols)
symbols.remove(card1[pos2])
card2[pos1]=random.choice(symbols)
symbols.remove(card2[pos1])
i=0
while(i<5):
if(i!=pos1 and i!=pos2):
alphabet1=random.choice(symbols)
symbols.remove(alphabet1)
alphabet2=random.choice(symbols)
symbols.remove(alphabet2)
card1[i]=alphabet1
card2[i]=alphabet2
i+=1
print(card1)
print(card2)
ch=input("spot the similar symbol")
if(ch==samesymbol):
print("right")
else:
print("wrong")
#birthday paradox
import random
import datetime
birthday=[]
i=0
while(i<50):#50 people
year=random.randint(1895,2022)
if(year%4==0 and year%100=0 or year%400==0):
leap=1
else:
leap=0
month=random.randint(1,12)
if(month==2 and leap==1):
day=random.randint(1,29)
elif(month==2 and leap==0):
day=random.randint(1,28)
elif(month==7 or month==8):
day=random.randint(1,31)
elif(month%2!=0 and month<7):
day=random.randint(1,31)
elif(month%2==0 and month>7):
day=random.randint(1,31)
else:
day=random.randint(1,30)
dd=datetime.date(year,month,day)
day_of_year=dd.timetuple().tm_yday
i+=1
birthday.append(day_of_year)
birthday.sort()
i=0
while(i<50):
print(birthday[i])
i+=1
print("day of year",datetime.date.today().strftime("%j"))
print("day of week",datetime.date.today().strftime("%A"))
#current time
datetime.datetime.now()
#print all perfect squares with square roots between 5-19 and divisible by 5
for i in range(5,20):
if(i%5==0):
print(i**2)
#code to replace all the letters of a movie name except speal characters with * in
single line
import string
import random
L=['spider-man','matrix','harry potter','terminator','alien isolation','resident
evil']
sc=string.ascii_letters+'0123456789'
movie=random.choice(L)
for ch in movie:
if(ch in sc):
print('*',end='')
else:
print(ch,end='')
#A perfect number is a number in which the sum of divisors is equal to that number.
For example, 6 is a perfect number as a sum of its divisors 1,2,3 is equal to 6.
Which function returns True if the number is a perfect number?
def perfect_number(num):
ans=0
for i in range(1,num):
if(num%i==0):
ans+=i
if(ans==num):
return True
else:
return False
#You are given an integer n. Write a program to print a right angle triangle.
*
**
***
****
*****
n = int(input())
#Total number of spaces for first line
k = n - 1
for i in range(0, n):
#printing spaces
for j in range(0, k):
print(end=" ")
#decreasing space for every line
k = k - 1
for j in range(0, i+1):
# printing stars
print("*", end="")
# ending line after each row
print()
#You are given a string s. Print the string s with every character except vowels in
s replaced by _
s = input()
a = 'aeiouAEIOU'
for ch in s:
if ch not in a:
print('_', end='')
else:
print(ch, end='')
#You are given a list L. Write a program to print all numbers in the list which are
exactly repeated twice. The order of numbers should be same as in list.(for example
if 3 appeared before 2 3 should be printed first.) If no such number exist do not
print anything.
L = [int(i) for i in input().split()]
support = []
for i in range(len(L)-1):
count = 1
a = L[i]
if(a not in support):
for j in range(i+1, len(L)):
if(a == L[j]):
count = count + 1
if count == 2:
print(a)
if(count > 2):
support.append(a)
import speech_recognition as sr
AUDIO_FILE=("audiofilename.wav")
r=sr.Recognizer()
with sr.AudioFile(AUDIO_FILE) as source:
audio=r.record(source)
try:
print("audio file contains"+r.recognize_google(audio))
except sr.UnknownValueError:
print("Google speech recognition could not understand audio")
except sr.RequestError:
print("couldn't get the results from google speech recognition")
#bubble sort
def bubble(a):
n=len(a)
for i in range(n):
for j in range(0,n-i-1):
if(a[j]>a[j+1]):
temp=a[j]
a[j]=a[j+1]
a[j+1]=temp
a=[5,1,4,2,8]
bubble(a)
for i in a:
print(i)
#linear search
def linear_search(n,x):
element=[]
for i in range(1,n):
element.append(i)
count=0
flag=0
for i in element:
count+=1
if(i==x):
print("I found my number at position"+str(i))
flag=1
break
if(flag==0):
print("number not found")
print("number of iterations",count)
#choose rock,paper,scissor
d={0:'rock',1:'paper',2:'scissor'}
choice=int(input())
game_choice=d[choice%3]
#You are given a string S. Write a function count_letters which will return a
dictionary containing letters (including special character) in string S as keys and
their count in string S as values.
def count_letters(S):
d={}
for i in S:
d[i]=0
for i in S:
d[i]+=1
return d
S = input()
d = count_letters(S)
d1 = {}
for i in S:
try:
d1[i]+=1
except KeyError:
d1[i]=1
if d1 == d:
print('yes')
else:
print('no')
#ou are given a list L. Write a function uniqueE which will return a list of unique
elements is the list L in sorted order. (Unique element means it should appear in
list L only once.)
def uniqueE(L):
d = {}
for i in L:
d[i]=0
for i in L:
d[i]+=1
res = []
for key, value in d.items():
if value==1:
res.append(key)
res.sort()
return res
L = [int(i) for i in input().split()]
print(uniqueE(L))
#You are given a list L. Write a program to print first prime number encountered in
the list L.(Treat numbers below and equal to 1 as non prime)
L = [int(i) for i in input().split()]
def isprime(num):
if num<=1:
return False
if num==2:
return True
for i in range(3,num-1):
if num%i == 0:
return False
return True
for k in L:
if isprime(k):
print(k)
break
else:
continue
#strings
import string
s_name.upper()
s_name.replace("H","J")
#substitution cipher
import string
dict={}
data=""
file=open("op_file.txt","w")
for i in range(len(string.ascii_letters)):
dic[string.ascii_letters[i]]=string.ascii_letters
print(dict)
with open("ip_file.txt") as f:
while True:
c=f.read(1)
if not c:
print("end of file")
break
if c in dict:
data=dict[c]
else:
data=c
print(data)
file.close()
5-1=4+5=9-1=8+5=13-1=12+5=17-1=16+5=21-1=20+5=25-1=24+5=29-1=28+5=33-1=32+5=37-
1=36+5=41-1=40
#print 2d array
row_num = int(input("Input number of rows: "))
col_num = int(input("Input number of columns: "))
multi_list = [[0 for col in range(col_num)] for row in range(row_num)]
# Initialize matrix
matrix = []
#print("Enter the entries rowwise:")
for i in range(R):
for j in range(C):
print(matrix[i][j], end = " ")
print()
d=np.diag(matrix)
print(d)