SlideShare a Scribd company logo
1 of 13
1. a. Write a program to get the list of even numbers upto a given number
# Python program to print Even Numbers in a List
# list of numbers
list1 = [10, 21, 4, 45, 66, 93]
# iterating each number in list
for num in list1:
# checking condition
if num % 2 == 0:
print(num, end=" ")
Output
10 4 66
b. Write a program to get the ASCII distance between two characters
print ("Please enter the String: ", end = "")
string = input()
string_length = len(string)
for K in string:
ASCII = ord(K)
print (K, "t", ASCII)
Output:
Please enter the String:
"JavaTpoint#
" 34
J 74
a 97
v 118
a 97
T 84
p 112
o 111
i 105
n 110
t 116
# 35
c. Write a program to get the binary form of a given number.
n=int(input("Enter a number: "))
a=[]
while(n>0):
dig=n%2
a.append(dig)
n=n//2
a.reverse()
print("Binary Equivalent is: ")
for i in a:
print(i,end=" ")
d. Write a program to convert base 36 to octal
def convert_to_other_bases(decimal):
# Convert to binary
binary = "{0:b}".format(decimal)
# Convert to octal
octal = "{0:o}".format(decimal)
# Convert to hexadecimal
hexadecimal = "{0:x}".format(decimal)
# Print results
print(f"{decimal} in binary: {binary}")
print(f"{decimal} in octal: {octal}")
print(f"{decimal} in hexadecimal: {hexadecimal}")
convert_to_other_bases(55)
Output
55 in binary: 110111
55 in octal: 67
55 in hexadecimal: 37
2 a. Write a program to get the number of vowels in the input string (No control flow allowed)
string=raw_input("Enter string:")
vowels=0
for i in string:
if(i=='a' or i=='e' or i=='i' or i=='o' or i=='u' or i=='A' or i=='E'
or i=='I' or i=='O' or i=='U'):
vowels=vowels+1
print("Number of vowels are:")
print(vowels)
b. Write a program to check whether a given number has even number of 1's in its binary
representation (No control flow, thenumbercanbein any base)
class Solution(object):
def hammingWeight(self, n):
"""
:type n: int
:rtype: int
"""
n = str(bin(n))
print(n)
one_count = 0
for i in n:
if i == "1":
one_count+=1
return one_count
num = "000000101101"
ob1 = Solution()
print(ob1.hammingWeight(num))
Input
num = "000000101101"
Output
4
c. Write a program to sort given list of strings in the order of their vowel counts.
def Check_Vow(string, vowels):
# The term "casefold" has been used to refer to a method of ignoring
cases.
string = string.casefold()
count = {}.fromkeys(vowels, 0)
# To count the vowels
for character in string:
if character in count:
count[character] += 1
return count
# Driver Code
vowels = 'aeiou'
string = "Hi, I love eating ice cream and junk food"
print (Check_Vow(string, vowels))
Output:
{'a': 3, 'e':3 , 'i':2 , 'o':3 , 'u':1}
3 a. Write a program to return the top 'n' most frequently occurring chars and their respective
counts. E.g. aaaaaabbbbcccc, 2 should return [(a5) (b 4)
def top_chars(input, n):
list1=list(input)
list3=[]
list2=[]
list4=[]
set1=set(list1)
list2=list(set1)
def count(item):
count=0
for x in input:
if x in input:
count+=item.count(x)
list3.append(count)
return count
list2.sort(key=count)
list3.sort()
list4=list(zip(list2,list3))
list4.reverse()
list4.sort(key=lambda list4: ((list4[1]),(list4[0])), reverse=True)
return list4[0:n]
pass
o/p:[('a', 2), ('c', 1)]
b. Write a program to convert a given number into a given base.
# Python program to convert any base
# number to its corresponding decimal
# number
# Function to convert any base number
# to its corresponding decimal number
def any_base_to_decimal(number, base):
# calling the builtin function
# int(number, base) by passing
# two arguments in it number in
# string form and base and store
# the output value in temp
temp = int(number, base)
# printing the corresponding decimal
# number
print(temp)
# Driver's Code
if __name__ == '__main__' :
hexadecimal_number = '1A'
base = 16
any_base_to_decimal(hexadecimal_number, base)
Output: 26
4 a. Write a program to convert a given iterable into a list. (Using iterator
# Sample built-in iterators
# Iterating over a list
print("List Iteration")
l = ["geeks", "for", "geeks"]
for i in l:
print(i)
# Iterating over a tuple (immutable)
print("nTuple Iteration")
t = ("geeks", "for", "geeks")
for i in t:
print(i)
# Iterating over a String
print("nString Iteration")
s = "Geeks"
for i in s :
print(i)
# Iterating over dictionary
print("nDictionary Iteration")
d = dict()
d['xyz'] = 123
d['abc'] = 345
for i in d :
print("%s %d" %(i, d[i]))
Output :
List Iteration
geeks
for
geeks
Tuple Iteration
geeks
for
geeks
String Iteration
G
e
e
k
s
Dictionary Iteration
xyz 123
abc 345
b. Write a program to implement user defined map() function
# Python program to demonstrate working
# of map.
# Return double of n
def addition(n):
return n + n
# We double all numbers using map()
numbers = (1, 2, 3, 4)
result = map(addition, numbers)
print(list(result))
Output :
[2, 4, 6, 8]
c. Write a program to generate an infinite number of even numbers (Use generator)
def number_gen(start=0, step=1):
while True:
yield start
start += step
d. Write a program to get a list of even numbers from a given list of numbers. (use only
comprehensions
Python program to print Even Numbers in given range
start = int(input("Enter the start of range: "))
end = int(input("Enter the end of range: "))
# iterating each number in list
for num in range(start, end + 1):
# checking condition
if num % 2 == 0:
print(num, end=" ")
Output:
Enter the start of range: 4
Enter the end of range: 10
3 6 8 10
5 Write a program to implement round robin
Python3 program for implementation of
# RR scheduling
# Function to find the waiting time
# for all processes
def findWaitingTime(processes, n, bt, wt, quantum):
rem_bt = [0] * n
# Copy the burst time into rt[]
for i in range(n):
rem_bt[i] = bt[i]
t = 0 # Current time
# Keep traversing processes in round
# robin manner until all of them are
# not done.
while(1):
done = True
# Traverse all processes one by
# one repeatedly
for i in range(n):
# If burst time of a process is greater
# than 0 then only need to process further
if (rem_bt[i] > 0) :
done = False # There is a pending process
if (rem_bt[i] > quantum) :
# Increase the value of t i.e. shows
# how much time a process has been processed
t += quantum
# Decrease the burst_time of current
# process by quantum
rem_bt[i] -= quantum
# If burst time is smaller than or equal
# to quantum. Last cycle for this process
else:
# Increase the value of t i.e. shows
# how much time a process has been processed
t = t + rem_bt[i]
# Waiting time is current time minus
# time used by this process
wt[i] = t - bt[i]
# As the process gets fully executed
# make its remaining burst time = 0
rem_bt[i] = 0
# If all processes are done
if (done == True):
break
# Function to calculate turn around time
def findTurnAroundTime(processes, n, bt, wt, tat):
# Calculating turnaround time
for i in range(n):
tat[i] = bt[i] + wt[i]
# Function to calculate average waiting
# and turn-around times.
def findavgTime(processes, n, bt, quantum):
wt = [0] * n
tat = [0] * n
# Function to find waiting time
# of all processes
findWaitingTime(processes, n, bt, wt, quantum)
# Function to find turn around time
# for all processes
findTurnAroundTime(processes, n, bt, wt, tat)
# Display processes along with all details
print("Processes Burst Time Waiting",
"Time Turn-Around Time")
total_wt = 0
total_tat = 0
for i in range(n):
total_wt = total_wt + wt[i]
total_tat = total_tat + tat[i]
print(" ", i + 1, "tt", bt[i],
"tt", wt[i], "tt", tat[i])
print("nAverage waiting time = %.5f "%(total_wt /n) )
print("Average turn around time = %.5f "% (total_tat / n))
# Driver code
if __name__ =="__main__":
# Process id's
proc = [1, 2, 3]
n = 3
# Burst time of all processes
burst_time = [10, 5, 8]
# Time quantum
quantum = 2;
findavgTime(proc, n, burst_time, quantum)
# This code is contributed by
# Shubham Singh(SHUBHAMSINGH10)
Output
PN BT WT TAT
1 10 13 23
2 5 10 15
3 8 13 21
Average waiting time = 12, Average turn around time = 19.6667
6 a. Write a program to sort words in a file and put them in another file. The output file
shouldhave only lower case words, so any upper case words from source must be lowered.
(Handle exceptions
open both files
with open('first.txt','r') as firstfile, open('second.txt','a') as
secondfile:
# read content from first file
for line in firstfile:
# append content to second file
secondfile.write(line)
b. Write a program return a list in which the duplicates are removed and the items are sorted from
a given input list of strings.
Python 3 code to demonstrate
# removing duplicated from list
# using set()
# initializing list
test_list = [1, 5, 3, 6, 3, 5, 6, 1]
print ("The original list is : "
+ str(test_list))
# using set()
# to remove duplicated
# from list
test_list = list(set(test_list))
# printing list after removal
# distorted ordering
print ("The list after removing duplicates : "
+ str(test_list))
Output
The original list is : [1, 5, 3, 6, 3, 5, 6, 1]
The list after removing duplicates : [1, 3, 5, 6]
7.a. Write a programto test whether given strings are anagrams are not
s1=raw_input("Enter first string:")
s2=raw_input("Enter second string:")
if(sorted(s1)==sorted(s2)):
print("The strings are anagrams.")
else:
print("The strings aren't anagrams.")
b. Write a program to implement left binary search.
def binarySearchAppr (arr, start, end, x):
# check condition
if end >= start:
mid = start + (end- start)//2
# If element is present at the middle
if arr[mid] == x:
return mid
# If element is smaller than mid
elif arr[mid] > x:
return binarySearchAppr(arr, start, mid-1, x)
# Else the element greator than mid
else:
return binarySearchAppr(arr, mid+1, end, x)
else:
# Element is not found in the array
return -1
arr = sorted(['t','u','t','o','r','i','a','l'])
x ='r'
result = binarySearchAppr(arr, 0, len(arr)-1, x)
if result != -1:
print ("Element is present at index "+str(result))
else:
print ("Element is not present in array")
Element is present at index 4
8. a. writea class Person with attributes name, age, weight (kgs), height (ft) and takes them
through the constructor and exposes a method get_bmi_result() which returns one of
"underweight", "healthy", "obese"
# asking for input from the users
the_height = float(input("Enter the height in cm: "))
the_weight = float(input("Enter the weight in kg: "))
# defining a function for BMI
the_BMI = the_weight / (the_height/100)**2
# printing the BMI
print("Your Body Mass Index is", the_BMI)
# using the if-elif-else conditions
if the_BMI <= 18.5:
print("Oops! You are underweight.")
elif the_BMI <= 24.9:
print("Awesome! You are healthy.")
elif the_BMI <= 29.9:
the_print("Eee! You are over weight.")
else:
print("Seesh! You are obese.")
Output:
Enter the height in cm: 160
Enter the weight in kg: 61
Your Body Mass Index is 23.828124999999996
Awesome! You are healthy.
Next Topi
cb. Write a program to convert the passed in positive integer number into its prime factorization
form
import math
# Below function will print the
# all prime factor of given number
def prime_factors(num):
# Using the while loop, we will print the number of two's that divide n
while num % 2 == 0:
print(2,)
num = num / 2
for i in range(3, int(math.sqrt(num)) + 1, 2):
# while i divides n , print i ad divide n
while num % i == 0:
print(i,)
num = num / i
if num > 2:
print(num)
# calling function
num = 200
prime_factors(num)
Output:
2
2
2
5
5

More Related Content

Similar to Python programs to print even numbers, ASCII distance, binary form and base conversionTITLEPython programs to count vowels, check binary 1s, sort by vowel count and find frequent charactersTITLEPython programs to implement top N characters, base conversion, generator, list comprehensionTITLEPython programs to iterate over iterables, map, round robin scheduling and file sorting TITLEPython programs for binary search, anagram check, exception handling and class implementation

Or else the work is fine only. Lot to learn buddy.... Improve your basics in ...
Or else the work is fine only. Lot to learn buddy.... Improve your basics in ...Or else the work is fine only. Lot to learn buddy.... Improve your basics in ...
Or else the work is fine only. Lot to learn buddy.... Improve your basics in ...Yashpatel821746
 
PYTHONOr else the work is fine only. Lot to learn buddy.... Improve your basi...
PYTHONOr else the work is fine only. Lot to learn buddy.... Improve your basi...PYTHONOr else the work is fine only. Lot to learn buddy.... Improve your basi...
PYTHONOr else the work is fine only. Lot to learn buddy.... Improve your basi...Yashpatel821746
 
solution-of-practicals-class-xii-comp.-sci.-083-2021-22 (1).pdf
solution-of-practicals-class-xii-comp.-sci.-083-2021-22 (1).pdfsolution-of-practicals-class-xii-comp.-sci.-083-2021-22 (1).pdf
solution-of-practicals-class-xii-comp.-sci.-083-2021-22 (1).pdfparthp5150s
 
Computer programming subject notes. Quick easy notes for C Programming.Cheat ...
Computer programming subject notes. Quick easy notes for C Programming.Cheat ...Computer programming subject notes. Quick easy notes for C Programming.Cheat ...
Computer programming subject notes. Quick easy notes for C Programming.Cheat ...DR B.Surendiran .
 
PCA-2 Programming and Solving 2nd Sem.pdf
PCA-2 Programming and Solving 2nd Sem.pdfPCA-2 Programming and Solving 2nd Sem.pdf
PCA-2 Programming and Solving 2nd Sem.pdfAshutoshprasad27
 
PCA-2 Programming and Solving 2nd Sem.docx
PCA-2 Programming and Solving 2nd Sem.docxPCA-2 Programming and Solving 2nd Sem.docx
PCA-2 Programming and Solving 2nd Sem.docxAshutoshprasad27
 
All important c programby makhan kumbhkar
All important c programby makhan kumbhkarAll important c programby makhan kumbhkar
All important c programby makhan kumbhkarsandeep kumbhkar
 
Python programming workshop
Python programming workshopPython programming workshop
Python programming workshopBAINIDA
 
CBSE Class 12 Computer practical Python Programs and MYSQL
CBSE Class 12 Computer practical Python Programs and MYSQL CBSE Class 12 Computer practical Python Programs and MYSQL
CBSE Class 12 Computer practical Python Programs and MYSQL Rishabh-Rawat
 
Basic c programs updated on 31.8.2020
Basic c programs updated on 31.8.2020Basic c programs updated on 31.8.2020
Basic c programs updated on 31.8.2020vrgokila
 
python file for easy way practicle programs
python file for easy way practicle programspython file for easy way practicle programs
python file for easy way practicle programsvineetdhand2004
 
1sequences and sampling. Suppose we went to sample the x-axis from X.pdf
1sequences and sampling. Suppose we went to sample the x-axis from X.pdf1sequences and sampling. Suppose we went to sample the x-axis from X.pdf
1sequences and sampling. Suppose we went to sample the x-axis from X.pdfrushabhshah600
 
Python programming workshop session 3
Python programming workshop session 3Python programming workshop session 3
Python programming workshop session 3Abdul Haseeb
 
Operating system labs
Operating system labsOperating system labs
Operating system labsbhaktisagar4
 

Similar to Python programs to print even numbers, ASCII distance, binary form and base conversionTITLEPython programs to count vowels, check binary 1s, sort by vowel count and find frequent charactersTITLEPython programs to implement top N characters, base conversion, generator, list comprehensionTITLEPython programs to iterate over iterables, map, round robin scheduling and file sorting TITLEPython programs for binary search, anagram check, exception handling and class implementation (20)

Or else the work is fine only. Lot to learn buddy.... Improve your basics in ...
Or else the work is fine only. Lot to learn buddy.... Improve your basics in ...Or else the work is fine only. Lot to learn buddy.... Improve your basics in ...
Or else the work is fine only. Lot to learn buddy.... Improve your basics in ...
 
PYTHONOr else the work is fine only. Lot to learn buddy.... Improve your basi...
PYTHONOr else the work is fine only. Lot to learn buddy.... Improve your basi...PYTHONOr else the work is fine only. Lot to learn buddy.... Improve your basi...
PYTHONOr else the work is fine only. Lot to learn buddy.... Improve your basi...
 
solution-of-practicals-class-xii-comp.-sci.-083-2021-22 (1).pdf
solution-of-practicals-class-xii-comp.-sci.-083-2021-22 (1).pdfsolution-of-practicals-class-xii-comp.-sci.-083-2021-22 (1).pdf
solution-of-practicals-class-xii-comp.-sci.-083-2021-22 (1).pdf
 
Computer programming subject notes. Quick easy notes for C Programming.Cheat ...
Computer programming subject notes. Quick easy notes for C Programming.Cheat ...Computer programming subject notes. Quick easy notes for C Programming.Cheat ...
Computer programming subject notes. Quick easy notes for C Programming.Cheat ...
 
PCA-2 Programming and Solving 2nd Sem.pdf
PCA-2 Programming and Solving 2nd Sem.pdfPCA-2 Programming and Solving 2nd Sem.pdf
PCA-2 Programming and Solving 2nd Sem.pdf
 
PCA-2 Programming and Solving 2nd Sem.docx
PCA-2 Programming and Solving 2nd Sem.docxPCA-2 Programming and Solving 2nd Sem.docx
PCA-2 Programming and Solving 2nd Sem.docx
 
Python Day1
Python Day1Python Day1
Python Day1
 
All important c programby makhan kumbhkar
All important c programby makhan kumbhkarAll important c programby makhan kumbhkar
All important c programby makhan kumbhkar
 
Python programming workshop
Python programming workshopPython programming workshop
Python programming workshop
 
python.pdf
python.pdfpython.pdf
python.pdf
 
Loops in Python
Loops in PythonLoops in Python
Loops in Python
 
CBSE Class 12 Computer practical Python Programs and MYSQL
CBSE Class 12 Computer practical Python Programs and MYSQL CBSE Class 12 Computer practical Python Programs and MYSQL
CBSE Class 12 Computer practical Python Programs and MYSQL
 
Basic c programs updated on 31.8.2020
Basic c programs updated on 31.8.2020Basic c programs updated on 31.8.2020
Basic c programs updated on 31.8.2020
 
python file for easy way practicle programs
python file for easy way practicle programspython file for easy way practicle programs
python file for easy way practicle programs
 
1sequences and sampling. Suppose we went to sample the x-axis from X.pdf
1sequences and sampling. Suppose we went to sample the x-axis from X.pdf1sequences and sampling. Suppose we went to sample the x-axis from X.pdf
1sequences and sampling. Suppose we went to sample the x-axis from X.pdf
 
Python programming workshop session 3
Python programming workshop session 3Python programming workshop session 3
Python programming workshop session 3
 
Array Cont
Array ContArray Cont
Array Cont
 
PRACTICAL FILE(COMP SC).pptx
PRACTICAL FILE(COMP SC).pptxPRACTICAL FILE(COMP SC).pptx
PRACTICAL FILE(COMP SC).pptx
 
Data Handling
Data Handling Data Handling
Data Handling
 
Operating system labs
Operating system labsOperating system labs
Operating system labs
 

Recently uploaded

BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdfSoniaTolstoy
 
Hybridoma Technology ( Production , Purification , and Application )
Hybridoma Technology  ( Production , Purification , and Application  ) Hybridoma Technology  ( Production , Purification , and Application  )
Hybridoma Technology ( Production , Purification , and Application ) Sakshi Ghasle
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️9953056974 Low Rate Call Girls In Saket, Delhi NCR
 
Science 7 - LAND and SEA BREEZE and its Characteristics
Science 7 - LAND and SEA BREEZE and its CharacteristicsScience 7 - LAND and SEA BREEZE and its Characteristics
Science 7 - LAND and SEA BREEZE and its CharacteristicsKarinaGenton
 
Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon AUnboundStockton
 
_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting Data_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting DataJhengPantaleon
 
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17Celine George
 
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdfssuser54595a
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfsanyamsingh5019
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactdawncurless
 
Mastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionMastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionSafetyChain Software
 
CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxGaneshChakor2
 
mini mental status format.docx
mini    mental       status     format.docxmini    mental       status     format.docx
mini mental status format.docxPoojaSen20
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxpboyjonauth
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentInMediaRes1
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Sapana Sha
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxNirmalaLoungPoorunde1
 

Recently uploaded (20)

BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
 
Staff of Color (SOC) Retention Efforts DDSD
Staff of Color (SOC) Retention Efforts DDSDStaff of Color (SOC) Retention Efforts DDSD
Staff of Color (SOC) Retention Efforts DDSD
 
Hybridoma Technology ( Production , Purification , and Application )
Hybridoma Technology  ( Production , Purification , and Application  ) Hybridoma Technology  ( Production , Purification , and Application  )
Hybridoma Technology ( Production , Purification , and Application )
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
 
Science 7 - LAND and SEA BREEZE and its Characteristics
Science 7 - LAND and SEA BREEZE and its CharacteristicsScience 7 - LAND and SEA BREEZE and its Characteristics
Science 7 - LAND and SEA BREEZE and its Characteristics
 
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdfTataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
 
Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon A
 
_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting Data_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting Data
 
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
 
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdf
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impact
 
Mastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionMastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory Inspection
 
Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1
 
CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptx
 
mini mental status format.docx
mini    mental       status     format.docxmini    mental       status     format.docx
mini mental status format.docx
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptx
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media Component
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptx
 

Python programs to print even numbers, ASCII distance, binary form and base conversionTITLEPython programs to count vowels, check binary 1s, sort by vowel count and find frequent charactersTITLEPython programs to implement top N characters, base conversion, generator, list comprehensionTITLEPython programs to iterate over iterables, map, round robin scheduling and file sorting TITLEPython programs for binary search, anagram check, exception handling and class implementation

  • 1. 1. a. Write a program to get the list of even numbers upto a given number # Python program to print Even Numbers in a List # list of numbers list1 = [10, 21, 4, 45, 66, 93] # iterating each number in list for num in list1: # checking condition if num % 2 == 0: print(num, end=" ") Output 10 4 66 b. Write a program to get the ASCII distance between two characters print ("Please enter the String: ", end = "") string = input() string_length = len(string) for K in string: ASCII = ord(K) print (K, "t", ASCII) Output: Please enter the String: "JavaTpoint# " 34 J 74 a 97 v 118 a 97 T 84 p 112 o 111 i 105 n 110 t 116 # 35 c. Write a program to get the binary form of a given number. n=int(input("Enter a number: ")) a=[] while(n>0): dig=n%2 a.append(dig) n=n//2 a.reverse() print("Binary Equivalent is: ") for i in a: print(i,end=" ")
  • 2. d. Write a program to convert base 36 to octal def convert_to_other_bases(decimal): # Convert to binary binary = "{0:b}".format(decimal) # Convert to octal octal = "{0:o}".format(decimal) # Convert to hexadecimal hexadecimal = "{0:x}".format(decimal) # Print results print(f"{decimal} in binary: {binary}") print(f"{decimal} in octal: {octal}") print(f"{decimal} in hexadecimal: {hexadecimal}") convert_to_other_bases(55) Output 55 in binary: 110111 55 in octal: 67 55 in hexadecimal: 37
  • 3. 2 a. Write a program to get the number of vowels in the input string (No control flow allowed) string=raw_input("Enter string:") vowels=0 for i in string: if(i=='a' or i=='e' or i=='i' or i=='o' or i=='u' or i=='A' or i=='E' or i=='I' or i=='O' or i=='U'): vowels=vowels+1 print("Number of vowels are:") print(vowels) b. Write a program to check whether a given number has even number of 1's in its binary representation (No control flow, thenumbercanbein any base) class Solution(object): def hammingWeight(self, n): """ :type n: int :rtype: int """ n = str(bin(n)) print(n) one_count = 0 for i in n: if i == "1": one_count+=1 return one_count num = "000000101101" ob1 = Solution() print(ob1.hammingWeight(num)) Input num = "000000101101" Output 4 c. Write a program to sort given list of strings in the order of their vowel counts. def Check_Vow(string, vowels): # The term "casefold" has been used to refer to a method of ignoring cases.
  • 4. string = string.casefold() count = {}.fromkeys(vowels, 0) # To count the vowels for character in string: if character in count: count[character] += 1 return count # Driver Code vowels = 'aeiou' string = "Hi, I love eating ice cream and junk food" print (Check_Vow(string, vowels)) Output: {'a': 3, 'e':3 , 'i':2 , 'o':3 , 'u':1}
  • 5. 3 a. Write a program to return the top 'n' most frequently occurring chars and their respective counts. E.g. aaaaaabbbbcccc, 2 should return [(a5) (b 4) def top_chars(input, n): list1=list(input) list3=[] list2=[] list4=[] set1=set(list1) list2=list(set1) def count(item): count=0 for x in input: if x in input: count+=item.count(x) list3.append(count) return count list2.sort(key=count) list3.sort() list4=list(zip(list2,list3)) list4.reverse() list4.sort(key=lambda list4: ((list4[1]),(list4[0])), reverse=True) return list4[0:n] pass o/p:[('a', 2), ('c', 1)] b. Write a program to convert a given number into a given base. # Python program to convert any base # number to its corresponding decimal # number # Function to convert any base number # to its corresponding decimal number def any_base_to_decimal(number, base): # calling the builtin function # int(number, base) by passing # two arguments in it number in # string form and base and store # the output value in temp temp = int(number, base) # printing the corresponding decimal # number print(temp) # Driver's Code if __name__ == '__main__' : hexadecimal_number = '1A' base = 16 any_base_to_decimal(hexadecimal_number, base) Output: 26
  • 6. 4 a. Write a program to convert a given iterable into a list. (Using iterator # Sample built-in iterators # Iterating over a list print("List Iteration") l = ["geeks", "for", "geeks"] for i in l: print(i) # Iterating over a tuple (immutable) print("nTuple Iteration") t = ("geeks", "for", "geeks") for i in t: print(i) # Iterating over a String print("nString Iteration") s = "Geeks" for i in s : print(i) # Iterating over dictionary print("nDictionary Iteration") d = dict() d['xyz'] = 123 d['abc'] = 345 for i in d : print("%s %d" %(i, d[i])) Output : List Iteration geeks for geeks Tuple Iteration geeks for geeks String Iteration G e e k s Dictionary Iteration xyz 123 abc 345
  • 7. b. Write a program to implement user defined map() function # Python program to demonstrate working # of map. # Return double of n def addition(n): return n + n # We double all numbers using map() numbers = (1, 2, 3, 4) result = map(addition, numbers) print(list(result)) Output : [2, 4, 6, 8] c. Write a program to generate an infinite number of even numbers (Use generator) def number_gen(start=0, step=1): while True: yield start start += step d. Write a program to get a list of even numbers from a given list of numbers. (use only comprehensions Python program to print Even Numbers in given range start = int(input("Enter the start of range: ")) end = int(input("Enter the end of range: ")) # iterating each number in list for num in range(start, end + 1): # checking condition if num % 2 == 0: print(num, end=" ") Output: Enter the start of range: 4 Enter the end of range: 10 3 6 8 10
  • 8. 5 Write a program to implement round robin Python3 program for implementation of # RR scheduling # Function to find the waiting time # for all processes def findWaitingTime(processes, n, bt, wt, quantum): rem_bt = [0] * n # Copy the burst time into rt[] for i in range(n): rem_bt[i] = bt[i] t = 0 # Current time # Keep traversing processes in round # robin manner until all of them are # not done. while(1): done = True # Traverse all processes one by # one repeatedly for i in range(n): # If burst time of a process is greater # than 0 then only need to process further if (rem_bt[i] > 0) : done = False # There is a pending process if (rem_bt[i] > quantum) : # Increase the value of t i.e. shows # how much time a process has been processed t += quantum # Decrease the burst_time of current # process by quantum rem_bt[i] -= quantum # If burst time is smaller than or equal # to quantum. Last cycle for this process else: # Increase the value of t i.e. shows # how much time a process has been processed t = t + rem_bt[i] # Waiting time is current time minus # time used by this process wt[i] = t - bt[i] # As the process gets fully executed # make its remaining burst time = 0 rem_bt[i] = 0 # If all processes are done if (done == True): break # Function to calculate turn around time def findTurnAroundTime(processes, n, bt, wt, tat):
  • 9. # Calculating turnaround time for i in range(n): tat[i] = bt[i] + wt[i] # Function to calculate average waiting # and turn-around times. def findavgTime(processes, n, bt, quantum): wt = [0] * n tat = [0] * n # Function to find waiting time # of all processes findWaitingTime(processes, n, bt, wt, quantum) # Function to find turn around time # for all processes findTurnAroundTime(processes, n, bt, wt, tat) # Display processes along with all details print("Processes Burst Time Waiting", "Time Turn-Around Time") total_wt = 0 total_tat = 0 for i in range(n): total_wt = total_wt + wt[i] total_tat = total_tat + tat[i] print(" ", i + 1, "tt", bt[i], "tt", wt[i], "tt", tat[i]) print("nAverage waiting time = %.5f "%(total_wt /n) ) print("Average turn around time = %.5f "% (total_tat / n)) # Driver code if __name__ =="__main__": # Process id's proc = [1, 2, 3] n = 3 # Burst time of all processes burst_time = [10, 5, 8] # Time quantum quantum = 2; findavgTime(proc, n, burst_time, quantum) # This code is contributed by # Shubham Singh(SHUBHAMSINGH10) Output PN BT WT TAT 1 10 13 23 2 5 10 15 3 8 13 21 Average waiting time = 12, Average turn around time = 19.6667
  • 10. 6 a. Write a program to sort words in a file and put them in another file. The output file shouldhave only lower case words, so any upper case words from source must be lowered. (Handle exceptions open both files with open('first.txt','r') as firstfile, open('second.txt','a') as secondfile: # read content from first file for line in firstfile: # append content to second file secondfile.write(line) b. Write a program return a list in which the duplicates are removed and the items are sorted from a given input list of strings. Python 3 code to demonstrate # removing duplicated from list # using set() # initializing list test_list = [1, 5, 3, 6, 3, 5, 6, 1] print ("The original list is : " + str(test_list)) # using set() # to remove duplicated # from list test_list = list(set(test_list)) # printing list after removal # distorted ordering print ("The list after removing duplicates : " + str(test_list)) Output The original list is : [1, 5, 3, 6, 3, 5, 6, 1] The list after removing duplicates : [1, 3, 5, 6]
  • 11. 7.a. Write a programto test whether given strings are anagrams are not s1=raw_input("Enter first string:") s2=raw_input("Enter second string:") if(sorted(s1)==sorted(s2)): print("The strings are anagrams.") else: print("The strings aren't anagrams.") b. Write a program to implement left binary search. def binarySearchAppr (arr, start, end, x): # check condition if end >= start: mid = start + (end- start)//2 # If element is present at the middle if arr[mid] == x: return mid # If element is smaller than mid elif arr[mid] > x: return binarySearchAppr(arr, start, mid-1, x) # Else the element greator than mid else: return binarySearchAppr(arr, mid+1, end, x) else: # Element is not found in the array return -1 arr = sorted(['t','u','t','o','r','i','a','l']) x ='r' result = binarySearchAppr(arr, 0, len(arr)-1, x) if result != -1: print ("Element is present at index "+str(result)) else: print ("Element is not present in array") Element is present at index 4
  • 12. 8. a. writea class Person with attributes name, age, weight (kgs), height (ft) and takes them through the constructor and exposes a method get_bmi_result() which returns one of "underweight", "healthy", "obese" # asking for input from the users the_height = float(input("Enter the height in cm: ")) the_weight = float(input("Enter the weight in kg: ")) # defining a function for BMI the_BMI = the_weight / (the_height/100)**2 # printing the BMI print("Your Body Mass Index is", the_BMI) # using the if-elif-else conditions if the_BMI <= 18.5: print("Oops! You are underweight.") elif the_BMI <= 24.9: print("Awesome! You are healthy.") elif the_BMI <= 29.9: the_print("Eee! You are over weight.") else: print("Seesh! You are obese.") Output: Enter the height in cm: 160 Enter the weight in kg: 61 Your Body Mass Index is 23.828124999999996 Awesome! You are healthy. Next Topi cb. Write a program to convert the passed in positive integer number into its prime factorization form import math # Below function will print the # all prime factor of given number def prime_factors(num): # Using the while loop, we will print the number of two's that divide n while num % 2 == 0: print(2,) num = num / 2 for i in range(3, int(math.sqrt(num)) + 1, 2): # while i divides n , print i ad divide n while num % i == 0: print(i,) num = num / i
  • 13. if num > 2: print(num) # calling function num = 200 prime_factors(num) Output: 2 2 2 5 5