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

# Python3 Program To Swap First and Last Element of A List

The program takes in two strings and displays the larger string without using built-in functions. It initializes count variables to store the length of each string. It then traverses each string and increments the corresponding count variable. The counts are then compared and the larger string is printed, or a message is displayed if they are equal length. If neither is larger, it indicates the strings are the same length.

Uploaded by

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

# Python3 Program To Swap First and Last Element of A List

The program takes in two strings and displays the larger string without using built-in functions. It initializes count variables to store the length of each string. It then traverses each string and increments the corresponding count variable. The counts are then compared and the larger string is printed, or a message is displayed if they are equal length. If neither is larger, it indicates the strings are the same length.

Uploaded by

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

# Python3 program to swap first and last

element of a list

def swapList(newList):

size = len(newList)

# Swapping

temp = newList[0]

newList[0] = newList[size - 1]

newList[size - 1] = temp

return newList

newList = [12, 35, 9, 56, 24]

print(swapList(newList))

You are given a square matrix A with dimensions N


X N. Your task is to find the determinant. Note:
Round the answer to 2 places after the decimal.
# A simple Python 3 program to find sum
# of all subsquares of size k x k

# Size of given matrix


n=5

# A simple function to find sum of all


# sub-squares of size k x k in a given
# square matrix of size n x n
def printSumSimple(mat, k):

# k must be smaller than or equal to n


if (k > n):
return

# row number of first cell in current


# sub-square of size k x k
for i in range(n - k + 1):

# column of first cell in current


# sub-square of size k x k
for j in range(n - k + 1):

# Calculate and print sum of


# current sub-square
sum = 0
for p in range(i, k + i):
for q in range(j, k + j):
sum += mat[p][q]
print(sum, end = " ")

# Line separator for sub-squares


# starting with next row
print()

# Driver Code
if __name__ == "__main__":

mat = [[1, 1, 1, 1, 1],


[2, 2, 2, 2, 2],
[3, 3, 3, 3, 3],
[4, 4, 4, 4, 4],
[5, 5, 5, 5, 5]]
k=3
printSumSimple(mat, k)

# This code is contributed by ita_c


.) Write the program, takes a string and
checks whether a string is a palindrome
or not using recursion.

def is_palindrome(s):
if len(s) < 1:
return True
else:
if s[0] == s[-1]:
return is_palindrome(s[1:-1])
else:
return False
a=str(input("Enter string:"))
if(is_palindrome(a)==True):
print("String is a palindrome!")
else:
print("String isn't a palindrome!")

1. User must enter a string.


2. The string is passed as an
argument to a recursive function.
3. In the function, if the length of
the string is less than 1, True is
returned.
4. If the last letter is equal to the
first letter, the function is called
recursively with the argument as
the sliced list with the first
character and last character
removed, else return False.
5. The if statement is used to
check if the returned value is True
or False and the final result is
printed.
def is_palindrome(s):

if len(s) < 1:

return True

if s[0] == s[-1]:

return is_palindrome(s[1:-1])

else:

return False

# Get user input

input_string = input("Enter a string: ")

# Call the recursive function

result = is_palindrome(input_string)

# Print the result

if result:
print(f"{input_string} is a palindrome!")

else:

print(f"{input_string} is not a palindrome.")

Write the program, takes two strings


and displays which letters are in the
two strings but not in both.

string1 = input("Enter the first string: ")

string2 = input("Enter the second string: ")


# Get the set of unique letters in each string

set1 = set(string1)

set2 = set(string2)

# Get the letters that are in both sets but not in their
intersection

unique_letters = (set1 | set2) - (set1 & set2)

# Print the unique letters

if len(unique_letters) == 0:

print("There are no unique letters in the two strings.")

else:

print("The unique letters in the two strings are:")

print(" ".join(sorted(unique_letters)))
5.) Write the problem to display all
permutations of a string in
lexicographic or dictionary order.

def print_permutations_lexicographic_order(s):

"""

Print all permutations of the string s in lexicographic order.

"""

# Convert the string to a list of characters

s = list(s)

# Sort the list in lexicographic order

s.sort()

# Loop over all permutations of the sorted list and print them

while True:
print("".join(s))

# Find the largest index k such that s[k] < s[k+1]

k = None

for i in range(len(s)-1):

if s[i] < s[i+1]:

k=i

if k is None:

# No such index exists, so we're done

break

# Find the largest index l greater than k such that s[k] < s[l]

l = None

for i in range(k+1, len(s)):

if s[k] < s[i]:

l=i

# Swap s[k] and s[l]

s[k], s[l] = s[l], s[k]

# Reverse the suffix s[k+1:]

s[k+1:] = s[k+1:][::-1]
# Get user input

s = input("Enter a string: ")

# Call the permutation function

print_permutations_lexicographic_order(s)

6.) Write the program, takes a list and


finds the second largest number in
the list using bubble sort.

# Get the number of elements in the list

n = int(input("Enter the number of elements: "))


# Get the elements of the list from the user

a = []

for i in range(n):

element = int(input(f"Enter element {i+1}: "))

a.append(element)

# Sort the list using bubble sort

for i in range(n-1):

for j in range(n-1-i):

if a[j] > a[j+1]:

a[j], a[j+1] = a[j+1], a[j]

# Print the second largest element

if n < 2:

print("The list has less than 2 elements.")

else:

print(f"The second largest element in the list is {a[-2]}.")


7.) Fibonacci numbers are defined
by the sequence f(0) = 0, f(1) = 1
and f(n) = f(n – 1) + f(n – 2) for n >=
2. The program prompts the user
to enter n and it prints the nth
Fibonacci number.

def fibonacci(n):
"""
Compute the nth Fibonacci number.
"""
if n <= 1:
return n
else:
return fibonacci(n-1) + fibonacci(n-2)

# Prompt the user to enter n


n = int(input("Enter n: "))

# Compute the nth Fibonacci number


fib_n = fibonacci(n)

# Display the result


print(f"The {n}th Fibonacci number is {fib_n}.")

8.) The program takes a list


and i as input and prints
the ith smallest element in
the list.

def select(a, i):

"""

Find the ith smallest element in the list a using the


quickselect algorithm.

"""

# If the list has only one element, return it


if len(a) == 1:

return a[0]

# Pick a pivot element and partition the list

pivot = a[0]

left = [x for x in a if x < pivot]

mid = [x for x in a if x == pivot]

right = [x for x in a if x > pivot]

# Recurse on the appropriate partition

if i < len(left):

return select(left, i)

elif i < len(left) + len(mid):

return mid[0]

else:
return select(right, i - len(left) - len(mid))

# Prompt the user to enter a list of numbers

a = list(map(int, input("Enter a list of numbers: ").split()))

# Prompt the user to enter i

i = int(input("Enter i: "))

# Find the ith smallest element

ith_smallest = select(a, i-1)

# Display the result

print(f"The {i}th smallest element in the list is


{ith_smallest}.")
9.) Example to check whether an integer is a
prime number or not using for loop and if...else
statement. If the number is not prime, it's
explained in output why it is not a prime
number.

# Prompt the user to enter an integer

n = int(input("Enter an integer: "))

# Check if the number is prime

if n <= 1:

print(f"{n} is not a prime number.")

else:

for i in range(2, int(n**(1/2))+1):

if n % i == 0:

print(f"{n} is not a prime number. It is divisible by {i}.")


break

else:

print(f"{n} is a prime number.")

10.) Write the program, takes a string


and counts the number of lowercase
letters and uppercase letters in the
string.

# Prompt the user to enter a string

string = input("Enter a string: ")

# Initialize count variables

uppercase_count = 0
lowercase_count = 0

# Traverse through the characters in the string

for char in string:

# Increment the count of uppercase characters if char is uppercase

if char.isupper():

uppercase_count += 1

# Increment the count of lowercase characters if char is lowercase

elif char.islower():

lowercase_count += 1

# Print the total count of uppercase and lowercase characters

print(f"Uppercase characters: {uppercase_count}")

print(f"Lowercase characters: {lowercase_count}")


11.) write the program, takes a string
and determines how many times a
given letter occurs in a string
recursively.

def count_char(string, char):

if not string: # Base condition: if string is empty

return 0

if string[0] == char:

return 1 + count_char(string[1:], char) # Progress the string


recursively
return count_char(string[1:], char) # Progress the string recursively

# Prompt the user to enter a string and a character

string = input("Enter a string: ")

char = input("Enter a character to count: ")

# Call the recursive function to count the number of times the


character appears in the string

count = count_char(string, char)

# Print the result

print(f"The character '{char}' appears {count} times in the string.")


12.) write the program, takes in two
strings and display the larger string
without using built-in function.

# Prompt the user to enter two strings

string1 = input("Enter the first string: ")

string2 = input("Enter the second string: ")

# Initialize count variables

count1 = 0

count2 = 0

# Traverse through the characters in string1 and increment count1

for char in string1:

count1 += 1

# Traverse through the characters in string2 and increment count2


for char in string2:

count2 += 1

# Compare the count variables and print the larger string

if count1 > count2:

print("The first string is larger.")

elif count2 > count1:

print("The second string is larger.")

else:

print("Both strings are of equal length.")

13.) Write a Python program to create a


file where all letters of English alphabet
are listed by specified number of letters
on each line.
import string

# Define the number of letters on each line

letters_per_line = 5

# Open a new file for writing

with open("alphabet.txt", "w") as file:

# Get all letters of the English alphabet

alphabet = string.ascii_lowercase

# Loop through the alphabet and write to the file

for i in range(0, len(alphabet), letters_per_line):

# Get the letters for this line

letters = alphabet[i:i+letters_per_line]

# Write the letters to the file, followed by a new line character

file.write(letters + '\n')

You might also like