0% found this document useful (0 votes)
7 views8 pages

Python Programs for Basic Algorithms

The document contains multiple Python programs written by Vasu Mittal, showcasing various functionalities such as checking for palindromes, swapping list elements, finding the second largest number, and calculating factorials. Each program is accompanied by its source code and expected output. The programs demonstrate fundamental programming concepts and operations on lists and numbers.

Uploaded by

arjit Kumar
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)
7 views8 pages

Python Programs for Basic Algorithms

The document contains multiple Python programs written by Vasu Mittal, showcasing various functionalities such as checking for palindromes, swapping list elements, finding the second largest number, and calculating factorials. Each program is accompanied by its source code and expected output. The programs demonstrate fundamental programming concepts and operations on lists and numbers.

Uploaded by

arjit Kumar
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

Name - Vasu Mittal

University roll no. 2222148


Roll no.- 69
Program 1: To check the number is palindrome or not

Source code:

a=int(input("enter a number"))
t=a
p=0
while a>0:
n=a%10
p=p*10+n
a=a/10
if t==p:
print("number is
palindrome") else:
print("number is not palindrome")

Output:
Program 2:Program to swap two elements from the list

Source code:

a=[1,2,3,4,5,6]
print("values before swap",a)
t=a[4]
a[4]=a[0]
a[0]=t
print("values after swap",a)

Output:
Program 3:To find the second largest number

Source code:

a=[10,20,30,40,50]
b=sorted(a,reverse=True)
sl=b[1]
print(a)
print("second largest in the list is",sl)

Output:
Program 4: To find the index of an item

Source code:

a=[2,3,4,5,7,6,9]
b=[Link](5)
print(a)
print("index of number is",b)

Output:
Program 5: Wap to find the sum and average of list items

Source Code:

L = [4, 5, 1, 2, 9, 7, 10, 8]
count = 0
for i in
L:
count += i
avg = count/len(L)
print("sum = ", count)
print("average = ", avg)

Output:
Program 6: Consider a number entered by a [Link] calculate the factorial of this number.

Source Code:

num = 7
factorial = 1
if num < 0:
print("Sorry, factorial does not exist for negative numbers")
elif num == 0:
print("The factorial of 0 is
1") else:
for i in range(1,num + 1):
factorial = factorial*i
print("The factorial of",num,"is",factorial)

Output:
Program 7: Wap to print the fibonacci sequence upto the range entered by user.

Source Code:

nterms = int(input("How many terms? "))


n1, n2 = 0, 1
count = 0
if nterms <= 0:
print("Please enter a positive
integer") elif nterms == 1:
print("Fibonacci sequence
upto",nterms,":") print(n1)
else:
print("Fibonacci sequence:")
while count < nterms:
print(n1)
nth = n1 + n2
# update values
n1 = n2
n2 = nth
count += 1

Output:
Program 8: Wap to check whether a number entered by the user is a perfect number or not.

Source Code:

num=int(input("Enter the number: "))


sum_v=0
for i in range(1,num):
if (num%i==0):
sum_v=sum_v+i
if(sum_v==num):
print("The entered number is a perfect
number") else:
print("The entered number is not a perfect number")

Output:

Common questions

Powered by AI

To handle negative numbers in a palindrome check program, you should first check if the number is negative and, in such cases, directly return that it is not a palindrome. This is because negative numbers cannot be palindromes when considering the most common definition of palindromes in numbers as having symmetry in positive integer contexts .

Logical errors in the perfect number program may arise, for example, when input 0 is considered. Since the sum of its divisors (which are none) is 0, it might falsely be labeled as a perfect number. This can be mitigated by excluding zero or handling edge cases separately, ensuring that only positive integers are checked for perfection .

Changing the division operation from 'a/10' to 'a//10' would impact the program by ensuring that 'a' remains an integer through the iterations. Using '//' for floor division avoids any potential issues arising from converting 'a' to a float, preserving the precision necessary for an accurate palindrome check .

The code for generating Fibonacci sequence can be extended to handle invalid inputs by incorporating exception handling, ensuring that non-integer inputs trigger an informative error message or a prompt to re-enter the value. Moreover, additional checks can ensure the input is a positive integer, as negative or zero terms do not logically fit the sequence requirements .

Optimizing the process of finding an index might involve leveraging data structures like hash tables or dictionaries to store indices, allowing O(1) time complexity lookups if list modification is infrequent. Additionally, if the list is sorted, binary search can be applied for faster retrieval of indices than linear search .

In the Fibonacci sequence generation program, two variables n1 and n2 are used to store the two preceding numbers necessary to calculate the next number in the sequence. If only one variable were used, it would not be possible to maintain both previous numbers simultaneously, as each term relies on the sum of the two preceding terms. This would prevent the accurate generation of the sequence .

The sum and average program computes the total sum by iterating through each item in the list and incrementing a counter variable, then divides this sum by the number of elements to find the average. However, it might not handle edge cases like an empty list, where dividing by zero would cause an error. Proper error handling should be added to manage such cases .

The factorial program includes a check for negative numbers because factorials are mathematically defined only for non-negative integers. Removing this check would lead to incorrect calculations or infinite loops, as attempting to calculate factorials of negative numbers does not make sense within the standard mathematical definition .

The swap function in the program works by using a temporary variable to store the value of one element (a[4]), then assigning the element at index 0 to index 4, and finally assigning the temporary value to index 0. This successfully swaps the two elements. An improvement could be to use tuple unpacking, such as 'a[0], a[4] = a[4], a[0]', which eliminates the need for a temporary variable .

Sorting the list in descending order and picking the second element is one way to find the second largest number, as seen in the code provided. However, this method is not the most efficient because sorting incurs a time complexity of O(n log n). A more efficient approach would be to iterate through the list once with a time complexity of O(n), keeping track of the largest and second largest numbers found .

You might also like