0% found this document useful (0 votes)
20 views

Program 1

Uploaded by

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

Program 1

Uploaded by

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

PYTHON

PROGRAM 01
1. Write a program to show whether entered
numbers are prime or not in the given range .
lower=int(input("Enter lowest number as lower bound to check : "))
upper=int(input("Enter highest number as upper bound to check: "))
c=0
for i in range(lower, upper+1):
if (i == 1):
continue

# flag variable to tell if i is prime or not


flag = 1

for j in range(2, i // 2 + 1):


if (i % j == 0):
flag = 0
break

# flag = 1 means i is prime


# and flag = 0 means i is not prime
if (flag == 1):
print(i, end = " ")

OUTPUT 01
PROGRAM 02
2. Write a program to input a string and
determine whether it is a palindrome or not.
string=input('Enter a string:')
length=len(string)
mid=length//
rev=-1
for a in range(mid):
if string[a]==string[rev]:
print(string,'is a palindrome.')
break
else :
print(string,'is not a palindrome.')

OUTPUT 02
PROGRAM 03
3. Write a program to read a text file and
display the number of vowels/ consonants/
uppercase/ lowercase characters and other
than character and digit in the file.

filein = open("Mydoc1.txt",'r')

line = filein.read()

count_vow = 0

count_con = 0

count_low = 0

count_up = 0

count_digit = 0

count_other = 0

print(line)

for ch in line:

if ch.isupper():

count_up +=1

if ch.islower():

count_low += 1

if ch in 'aeiouAEIOU':

count_vow += 1

if ch.isalpha():

count_con += 1

if ch.isdigit():

count_digit += 1

if not ch.isalnum() and ch !=' ' and ch !='\n':


count_other += 1

print("Digits",count_digit)

print("Vowels: ",count_vow)

print("Consonants: ",count_con-count_vow)

print("Upper Case: ",count_up)

print("Lower Case: ",count_low)

print("other than letters and digit: ",count_other)

filein.close()

FILE
OUTPUT 03

PROGRAM 04
4. Write a recursive code to compute the nth
Fibonacci number.
def fibonacci(n):
if n == 0:
return 0
elif n == 1:
return 1
else:
return(fibonacci(n-2) + fibonacci(n-1))

nterms = int(input("Please enter the Range Number: "))

# check if the number of terms is valid


if nterms <= 0:
print("Plese enter a positive integer")
else:
print("Fibonacci sequence:")
for i in range(nterms):
print(fibonacci(i),end=' ')

OUTPUT 04
PROGRAM 05
5. Write a program to read a text file line by line
and display each word separated by a #.

filein = open("Mydoc.txt",'r ')


line =" "
while line:
line = filein.readline()
#print(line)
for w in line:
if w == ' ':
print('#',end = '')
else:
print(w,end = '')
filein.close()

FILE

OUTPUT 05
PROGRAM 06
6. Write a program to perform read and write
operation onto a student.csv file having fields
as roll number, name, stream and percentage.

import csv
with open('Student_Details.csv','w',newline='') as csvf:
writecsv=csv.writer(csvf,delimiter=',')
choice='y'
while choice.lower()=='y':
rl=int(input("Enter Roll No.: "))
n=input("Enter Name: ")
p=float(input("Enter Percentage : "))
r=input("Enter Remarks: ")
writecsv.writerow([rl,n,p,r])
print(" Data saved in Student Details file..")
choice=input("Want add more record(y/n).....")

with open('Student_Details.csv','r',newline='') as fileobject:


readcsv=csv.reader(fileobject)
for i in readcsv:
print(i)
OUTPUT 06
PROGRAM 07
7. Write a python program for Binary Search
(Recursive and Iterative).
def binary_search(arr, low, high, x):

# Check base case

if high >= low:

mid = (high + low) // 2

# If element is present at the middle itself

if arr[mid] == x:

return mid

# If element is smaller than mid, then it can only

# be present in left subarray

elif arr[mid] > x:

return binary_search(arr, low, mid - 1, x)

def binary_search(arr, low, high, x):

# Check base case

if high >= low:

mid = (high + low) // 2

# If element is present at the middle itself

if arr[mid] == x:

return mid

# If element is smaller than mid, then it can only

# be present in left subarray


elif arr[mid] > x:

return binary_search(arr, low, mid - 1, x)

# Else the element can only be present in right subarray

else:

return binary_search(arr, mid + 1, high, x)

else:

# Element is not present in the array

return -1

# Test array

arr = [ 2, 3, 4, 10, 40 ]

x = 10

# Function call

result = binary_search(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")


OUTPUT 07
PROGRAM 08
8. Write a python program for Bubble Sort.
def bubble_sort(arr):

# Outer loop to iterate through the list n times


for n in range(len(arr) - 1, 0, -1):

# Initialize swapped to track if any swaps occur


swapped = False

# Inner loop to compare adjacent elements


for i in range(n):
if arr[i] > arr[i + 1]:

# Swap elements if they are in the wrong order


arr[i], arr[i + 1] = arr[i + 1], arr[i]

# Mark that a swap has occurred


swapped = True

# If no swaps occurred, the list is already sorted


if not swapped:
break
# Sample list to be sorted
arr = [39, 12, 18, 85, 72, 10, 2, 18]
print("Unsorted list is:")
print(arr)
bubble_sort(arr)
print("Sorted list is:")
print(arr)
OUTPUT 08
PROGRAM 09
9. Write a python program for Insertion Sort.
def insertionSort(arr):
n = len(arr) # Get the length of the array

if n <= 1:
return # If the array has 0 or 1 element, it is already sorted, so return

for i in range(1, n): # Iterate over the array starting from the second element
key = arr[i] # Store the current element as the key to be inserted in the right
position
j = i-1
while j >= 0 and key < arr[j]: # Move elements greater than key one position
ahead
arr[j+1] = arr[j] # Shift elements to the right
j -= 1
arr[j+1] = key # Insert the key in the correct position

# Sorting the array [12, 11, 13, 5, 6] using insertionSort


arr = [12, 11, 13, 5, 6]
insertionSort(arr)
print(arr)
OUTPUT 09
PROGRAM 10
10. Write a python program for Selection Sort.
def selectionSort(array, size):

for ind in range(size):


min_index = ind

for j in range(ind + 1, size):


# select the minimum element in every iteration
if array[j] < array[min_index]:
min_index = j
# swapping the elements to sort the array
(array[ind], array[min_index]) = (array[min_index], array[ind])

arr = [-2, 45, 0, 11, -9,88,-97,-202,747]


size = len(arr)
selectionSort(arr, size)
print('The array after sorting in Ascending Order by selection sort is:')
print(arr)
OUTPUT 10
PROGRAM 11
11. Write a python program for Linear
Search.
def linear_search(arr, target):
# Traverse through all elements in the array
for index in range(len(arr)):
# If the element is found, return its index
if arr[index] == target:
return index
# If the element is not found, return -1
return -1

# Example usage:
arr = [10, 23, 45, 70, 11, 15]
target = 70

# Function call
result = linear_search(arr, target)

if result != -1:
print(f"Element found at index: {result}")
else:
print("Element not found in the array")
OUTPUT 11
PROGRAM 12
12. Write a python program to find largest
element in an Array.
def largest(arr, n):

# Initialize maximum element


max = arr[0]

# Traverse array elements from second


# and compare every element with
# current max
for i in range(1, n):
if arr[i] > max:
max = arr[i]
return max

# Driver Code
arr = [10, 324, 45, 90, 9808]
n = len(arr)
Ans = largest(arr, n)
print("Largest in given array ", Ans)
OUTPUT 12
PROGRAM 13
13. Write a program to check whether the
number is armstrong number or not.

n = 153 # or n=int(input()) -> taking input from user


s = n # assigning input value to the s variable
b = len(str(n))
sum1 = 0
while n != 0:
r = n % 10
sum1 = sum1+(r**b)
n = n//10
if s == sum1:
print("The given number", s, "is armstrong number")
else:
print("The given number", s, "is not armstrong number ")
OUTPUT 13
PROGRAM 14
14. Write a program with a user-defined
function with string as a parameter which
replaces all vowels in the string with ‘*’.
def strep(str):

# convert string into list

str_lst =list(str)

# Iterate list

for i in range(len(str_lst)):

# Each Character Check with Vowels

if str_lst[i] in 'aeiouAEIOU':

# Replace ith position vowel with'*'

str_lst[i]='*'

#to join the characters into a new string.

new_str = "".join(str_lst)
return new_str

def main():
line = input("Enter string: ")
print("Orginal String")
print(line)
print("After replacing Vowels with '*'")
print(strep(line))
main()
OUTPUT 14
PROGRAM 15

15. Write a recursive code to find the sum


of all elements of a list.

def lstSum(lst,n):
if n==0:
return 0
else:
return lst[n-1]+lstSum(lst,n-1)

mylst = [] # Empty List

#Loop to input in list

num = int(input("Enter how many number :"))


for i in range(num):
n = int(input("Enter Element "+str(i+1)+":"))
mylst.append(n) #Adding number to list
sum = lstSum(mylst,len(mylst))
print("Sum of List items ",mylst, " is :",sum)
OUTPUT 15

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy