0% found this document useful (0 votes)
34 views16 pages

Joy of Computing

This document contains code snippets and explanations related to various Python concepts like: - Calculating trimmed mean by removing top and bottom 10% of values from a dataset - Plotting graphs using Matplotlib - Working with dates and times using the datetime module - Generating random numbers using the random module - A guessing game example to demonstrate string manipulation

Uploaded by

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

Joy of Computing

This document contains code snippets and explanations related to various Python concepts like: - Calculating trimmed mean by removing top and bottom 10% of values from a dataset - Plotting graphs using Matplotlib - Working with dates and times using the datetime module - Generating random numbers using the random module - A guessing game example to demonstrate string manipulation

Uploaded by

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

def

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])

#to get 10% values including floor


l1=int(0.1*len(l))

#to delete smallest 10% values


l=l[l1:]

#to delete largest 10% values


l=l[:len(l)-l1]

#to calculate the mean for these values


from statistics import mean
print(mean(l))

#method1 to calculate trimmed mean is shown above


from statistics import mean
l=[100,12,5,56,2456,278,236,59,347,267]
l.sort()
l1=int(0.1*len(l))
l=[l1:]
l=[:len(l)-l1]
print(mean(l))

#method 2 to print trimmed mean


from statistics import mean
from scipy import stats
l=[100,12,5,56,2456,278,236,59,347,267]
l.sort()
mean=stats.trim_mean(l,0.1)#in brackets give list and percentage of values to be
removed from top and bottom of the list like 10% or 20% whatever it may be
print(mean)

to plot values in python we use matplotlib.pyplot

import matplotlib.pyplot as plt


plt.plot([1,2,3,4])
#the given list will be plotted on y-axis, if you do not pass any x-axis values
python automatically generates x values
#passing both x and y values
plt.plot([1,2,3],[4,5,6])
first list will be taken as x and second will be taken as y

#labelling x and y axes


import matplotlib.pyplot as plt
plt.plot([1,2,3],[4,5,6])
plt.ylabel("values on y-axis")
plt.xlabel("values on x-axis")

#to plot in dots or other formats with color you want


plt.plot([1,2,3],[4,5,6],'ro')#red dots
plt.plot([1,2,3],[4,5,6],'r--')#red dashes
plt.plot([1,2,3],[4,5,6],'bs')#blue squares
plt.plot([1,2,3],[4,5,6],'g^')#green triangles

#plot graph for the given list


import matplotlib.pyplot as plt
l=[1,2,3,4,5,6,7,8,9,10]
plt.plt(l)

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--')

#to show mean and median on a graph


import matplotlib.pyplot as plt
from statistics import mean
l=[100,12,5,56,2456,278,236,59,347,267]
y=[]
l.sort()
l1=int(0.1*len(l))
l=[l1:]
l=[:len(l)-l1]
for i in range(len(l)):
y.append(5)
plt.plot(l,y,'r--')
plt.plot([statistics.mean(l)],[5],'ro')#mean
plt.plot([statistics.median(l)],[5],'bs')#median
print(mean(l))

#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"

#random library is used to generate random numbers


#functions of random
random.randint(start,end)#used to generate random numbers from given size list
start and stop both are inclusive
random.randrange(start,end,stepsize)#includes lower limit and upper limit minus one
and can include stepsize
random.random()#generates decimal number from 0 to 1
random.choice([1,2,3,4])#chooses a random number from a given list of values

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)

#sorted list(L) containing random elements between 0-10 in descending order


import random
L=[]
for i in range(10):
L.append(random.randint(0,10))
L.sort()
L.reverse()
print(L)

#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")

#leap year or not


import random
year=random.randint(1998,2018)
if(year%4==0 and year%100!=0 or year%400==0):
print(year,"is a leap year")
else:
print(year,"is not a leap year")

#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

#to display today's date


datetime.date.today()

#to display today's year


datetime.date.today().strftime("%Y")

#to display today's month


datetime.date.today().strftime("%B")

#to display today's date


datetime.date.today().strftime("%d")

print("week number of the month",datetime.date.today().strftime("%W"))

print("week day of the week ",datetime.date.today().strftime("%w"))

print("day of year",datetime.date.today().strftime("%j"))

print("day of week",datetime.date.today().strftime("%A"))

#current time
datetime.datetime.now()

#guess the movie


import random
movies=['taare zameen par','black friday','dangal','golmaal','drishyam']
def create_question(movie):
n=len(movie)
letters=list(movie)
temp=[]
for i in range(n):
if letters[i]==' ':
temp.append(' ')
else:
temp.append('*')
qn=''.join(str(x) for x in temp)
return qn
def is_present(letter,movie):
c=movie.count(letter)
ifc==0:
return False
else:
return True
def unlock(qn,movie,letter):
ref=list(movie)
qn_list=list(qn)
temp=[]
n=len(movie)
for i in range(n):
if ref[i]==' ' or ref[i]==letter:
temp.append(ref[i])
else:
if qn_list[i]=='*':
temp.append('*')
else:
temp.append(ref[i])
qn_new=''.join(str(x) for x in temp)
return qn_new
def play():
p1name=input("enter your name")
p2name=input("enter your name")
pp1=0
pp2=0
turn=0
willing=True
while willing:
if turn%2==0:
print(p1name,"your turn")
picked_movie=random.choice(movies)
qn=create_question(picked)
print(qn)
modified_qn=qn
not_said=True
while not_said:
letter=input("your letter")
if(is_present(letter,picked_movie)):
modified_qn=unlock(modified_qn,picked_movie,ch)
print(modified_qn)
d=int(input("press1 to guess the movie or 2 to unlock another letter"))
if d==1:
ans=input("your answer: ")
if ans==picked_moive:
pp1+=1
print("correct")
not_said=False
print(p1name,"your score: ",pp1)
else:
print(letter,'not found')
c=input("press 1 to continue or 0 to quit")
if c==0:
print(p1name,"your score: ",pp1)
print(p2name,"your score: ",pp2)
print("thanks for playing")
print("have a nice day")
willing=False
else:
print(p2name,"your turn")
picked_movie=random.choice(movies)
qn=create_question(picked)
print(qn)
modified_qn=qn
not_said=True
while not_said:
letter=input("your letter")
if(is_present(letter,picked_movie)):
modified_qn=unlock(modified_qn,picked_movie,ch)
print(modified_qn)
d=input("press1 to guess the movie or 2 to unlock another letter")
if d==1:
ans=input("your answer: ")
if ans==picked_moive:
pp1+=1
print("correct")
not_said=False
print(p2name,"your score: ",pp2)
else:
print(letter,'not found')
c=input("press 1 to continue or 0 to quit")
if c==0:
print(p1name,"your score: ",pp1)
print(p2name,"your score: ",pp2)
print("thanks for playing")
print("have a nice day")
willing=False
turn+=1
play()

#magic square of size n


import string
import random
A=string.ascii_letters
n=int(input())
for i in range(n):
L=[]
for j in range(n):
L.append(random.choice(A))
for element in L:
print(element,end=('\t'))
print()

#to display whether the entered year is leap year or not


def leap_year(year):
if(year%400==0 or year%4==0):
print("leap")
return
else:
print("not leap")
return
year=int(input("enter year:"))
leap_year(year)

#print unique movies of list l1


l1=['harry potter','matrix','spiderman','avengers','john wick']
l2=['drishyam','spiderman','bahubali','dhoom','race','matrix']
l=[]
for i in range(len(l1)):
flag=0
for j in range(len(l2)):
if(l1[i]==l2[j]):
flag=1
break
else:
flag=0
if(flag==0):
l.appemd(l1[i])
print(l)

#display number of vowels and the name of the movie


import random
l=['harry potter','matrix','spiderman','terminator']
movie=random.choice(l)
count=0
for character in movie:
if(character=='a' or character=='A'):
count+=1
elif(character=='e' or character=='E'):
count+=1
elif(character=='i' or character=='I'):
count+=1
elif(character=='o' or character=='O'):
count+=1
elif(character=='u' or character=='U'):
count+=1
print(count,movie)

#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 generate all prime numbers between 0-100


for i in range(2,101):
flag=0
for j in range(2,i):
if(i%j==0):
flag=1
break
if(flag==0):
print(i)

#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='')

#list of squares of even numbers


print([i**2 for i in range(10) if i%2==0])

#calculate sum of series 1+(1+2)+(1+2+3)+(1+2+3+4)+...+n terms


num=int(input())
total=0
for i in range(1,num+1):
for j in range(1,i+1):
total+=j
print(total)

#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)

#install speech recognition


sudo pip install SpeechRecognition

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")

#3 doors and a twist


import random
doors=[0]*3
goatdoor=[0]*2
swap=0
dont_swap=0
x=random.randint(0,2)
doors[x]="BMW"
for i in range(0,3):
if(i==x):
continue
else:
doors[i]="goat"
goatdoor.append(i)
choice=int(input("enter your choice "))
door_open=random.choice(goatdoor)
while(door_open==choice):
door_open=random.choice(goatdoor)
ch=input("do you wnat to sway? y/n")
if(ch=='y'):
if(doors[choice]=='goat'):
print("player wins")
swap+=1
else:
print("player lost")
else:
if(doors[choice]=='goat'):
print("player lost")
else:
print("player wins")
dont_swap+=1
print(swap)
print(dont_swap)

#rock paper scissor


def rock_paper_scissor(num1,num2,bit1,bit2):
p1=int(num1[bit1])%3
p2=int(num2[bit2])%3
if(player1[p1]==player2[p2]):
print("draw")
elif(player1[p1]=="rock" and player2[p2]=="scissor"):
print("player one wins!!")
elif(player1[p1]=="rock" and player2[p2]=="paper"):
print("player two wins!!")
elif(player1[p1]=="paper" and player2[p2]=="scissor"):
print("player two wins!!")
elif(player1[p1]=="paper" and player2[p2]=="rock"):
print(player one wins)
elif(player1[p1]=="scissor" and player2[p2]=="rock"):
print(player two wins)
elif(player1[p2]=="scissor" and player2[p2]=="paper"):
print(player one wins!!)
player1={0:'rock',1:'paper',2:'scissor'}
player2={0:'paper',1:'rock',2:'scissor'}
while(1):
num1=input("player 1 enter your choice")
num2=input("player 2 enter your choice")
bit1=int(input("enter the secret bit position"))
bit2=int(input("enter the secret bit position"))
rock_paper_scissor(num1,num2,bit1,bit2)
ch=input("do you want to continue? y/n")
if(ch=='n'):
break

#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)

#binary search log(n)


def binary_search(a,x):
first_pos=0
last_pos=len(a)-1
flag=0
count=0
while(firs_pos<=last_pos and flag==0):
count+=1
mid=(first_pos+last_pos)//2
if(x==a[mid]):
flag=1
print("element is at position ",mid)
print("the number of iterations are ",count)
return
else:
if(x<a[mid]):
last_pos=mid-1
else:
first_pos=mid+1
print("the number is not present")
a=[]
for i in range(1,200):
a.append(i)
binary_search(a,70)

#create a dictionary with key in range a-t and values 0


import string
bags={}
name=string.ascii_letters
for i in range(20):
bags[name[i]]=0
print(bags)

#distribute thousand marbles equally in every bag


import string
import random
bags={}
name=string.ascii_letters
for i in range(20):
bags[name[i]]=0
for i in range(1000):
key=random.choice(list(bags.keys()))
bags[key]=bags[key]+1

#choose rock,paper,scissor
d={0:'rock',1:'paper',2:'scissor'}
choice=int(input())
game_choice=d[choice%3]

#the largest element of the list


def test(L):
for i in range(len(L)-1):
for j in range(len(L)-1):
if(L[j]<L[j+1]):
temp=L[j]
L[j]=L[j+1]
L[j+1]=temp
print(L[0])

#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()

#tic tac toe


import numpy
board=numpy.array([['-','-','-'],['-','-','-'],['-','-','-']])
p1s='X'
p2s='O'
def place(symbol):
print(numpy.matrix(board))
while(1):
row=int(input('Enter row - 1 or 2 or 3: '))
column=

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)]

for row in range(row_num):


for col in range(col_num):
multi_list[row][col]= row*col
print(multi_list)

#print diagnol of a list


import numpy as np
R = int(input())
C = int(input())

# Initialize matrix
matrix = []
#print("Enter the entries rowwise:")

# For user input


for i in range(R): # A for loop for row entries
a =[]
for j in range(C): # A for loop for column entries
a.append(int(input()))
matrix.append(a)

# For printing the matrix

for i in range(R):
for j in range(C):
print(matrix[i][j], end = " ")
print()

d=np.diag(matrix)
print(d)

You might also like