0% found this document useful (0 votes)
4 views9 pages

Python Assignment 1

The document contains various Python programs that demonstrate fundamental programming concepts such as finding minimum and maximum values, checking for positive or negative numbers, generating Fibonacci sequences, and performing matrix operations. It also includes string manipulation techniques like reversing strings, merging characters, and removing duplicates. Each program is accompanied by example inputs and outputs to illustrate their functionality.

Uploaded by

324203359002
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)
4 views9 pages

Python Assignment 1

The document contains various Python programs that demonstrate fundamental programming concepts such as finding minimum and maximum values, checking for positive or negative numbers, generating Fibonacci sequences, and performing matrix operations. It also includes string manipulation techniques like reversing strings, merging characters, and removing duplicates. Each program is accompanied by example inputs and outputs to illustrate their functionality.

Uploaded by

324203359002
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/ 9

#read two numbers from keyboard and print minimum value

a = int(input("enter the number a: "))


b=int(input("enter the number b: "))
if a<b:
minimum = a
else:
minimum = b
print("The minimum value is : ",minimum)

The minimum value is : 11

#read the number whether positive or negative


a = int(input("enter the number a: "))
if a<0:
print(a," is negative number")
else:
print(a," is positive number")

11 is positive number

#find largest among three numbers


a = int(input("enter the number a: "))
b = int(input("enter the number b: "))
c = int(input("enter the number c: "))
if a>c:
print(a," is greatest number")
elif b>c:
print(b," is greatest number")
else:
print(c,"is greatest number")

72 is greatest number

#Python Program to Print the sum o all the even numbers in the range 1-50 and Print the even sum.
even_sum = 0
for number in range(1, 51):
if number % 2 == 0:
even_sum += number
print("The sum of all even numbers from 1 to 50 is:", even_sum)

The sum of all even numbers from 1 to 50 is: 650

#Python Program to swap two numbers without using temporary variable.


a = int(input("enter the number a: "))
b = int(input("enter the number b: "))
a = a + b
b = a - b
a = a - b
print("After swapping: ")
print("A: ",a)
print("B: ",b)

After swapping:
A: 45
B: 18

#Python Program to display all prime numbers within an interval of 20 and 50.
for num in range(20,51):
is_prime = True
for i in range(2, int(num ** 0.5) + 1):
if num % i == 0:
is_prime = False
break
if is_prime:
print(num, end=' ')

23 29 31 37 41 43 47

#Python Program to generate the first n terms of Fibonacci sequence. The first two terms are 0 and 1.
n = int(input("enter the no.of terms: "))
a,b = 0,1
count = 0
while count < n:
print(a,end=' ')
a,b=b,a+b
count += 1

0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181

#Python Program to determine whether the given number is ‘ARMSTRONG’.


num = int(input("Enter a number: "))
num_str = str(num)
num_digits = len(num_str)
sum_of_powers = sum(int(digit) ** num_digits for digit in num_str)
if num == sum_of_powers:
print(num, "is an Armstrong number.")
else:
print(num, "is not an Armstrong number.")

153 is an Armstrong number.

#Python Program to generate pascal triangle.


def generate_pascals_triangle(n):
for i in range(n):
print(' ' * (n - i), end='')
value = 1
for j in range(i + 1):
print(value, end=' ')
value = value * (i - j) // (j + 1)
print()
rows = int(input("Enter the number of rows for Pascal's Triangle: "))
generate_pascals_triangle(rows)

1
1 1
1 2 1
1 3 3 1

#Python Program to generate pyramid of numbers.


rows = int(input("Enter the number of rows: "))
for i in range(1, rows + 1):
print(' ' * (rows - i), end='')
for j in range(1, i + 1):
print(j, end=' ')
print()

1
1 2
1 2 3
1 2 3 4
1 2 3 4 5

#Python function to read two numbers , x and n (no. of terms ) and then compute sin(x) and cos(x).
def factorial(num):
result = 1
for i in range(2, num + 1):
result *= i
return result

def compute_sin_cos(x, n):


sin_x = 0
cos_x = 0

for i in range(n):
sin_term = ((-1)**i) * (x**(2*i + 1)) / factorial(2*i + 1)
cos_term = ((-1)**i) * (x**(2*i)) / factorial(2*i)

sin_x += sin_term
cos_x += cos_term
print(f"sin({x}) ≈ {sin_x}")
print(f"cos({x}) ≈ {cos_x}")
x = float(input("Enter value of x (in radians): "))
n = int(input("Enter number of terms (n): "))
compute_sin_cos(x, n)

sin(90.0) ≈ -121410.0
cos(90.0) ≈ -4049.0

#Python Program to Write a Program to Reverse the given String


#Input: name
#Output: eman
string = input("Enter a string: ")
reversed_string = string[::-1]
print("Reversed string:", reversed_string)

Reversed string: eman

#Write a Python Program to Reverse Order of Words


#Input: Learning Python is very Easy
#Output: Easy Very is Python Learning
string = input("Enter a string: ")
reversed_string = ' '.join(string.split()[::-1])
print("Reversed string:", reversed_string)

Reversed string: Easy very is Python Learning

#Program to Reverse Internal Content of each Word


#Input: Learning Python is very Easy
#Output: gninraeL nohtyP si yrev ysaE
sentence = input("Enter a sentence: ")
reversed_words_sentence = ' '.join([word[::-1] for word in sentence.split()])
print("Reversed internal content of each word:", reversed_words_sentence)

Reversed internal content of each word: gninraeL nohtyP si yrev ysaE

#Program to Print Characters at Odd Position and Even Position for the given String?
string = input("Enter a string: ")
odd_position_chars = ""
even_position_chars = ""
for i in range(len(string)):
if i % 2 == 0:
even_position_chars += string[i]
else:
odd_position_chars += string[i]
print("Characters at even positions:", even_position_chars)
print("Characters at odd positions:", odd_position_chars)

Characters at even positions: Lann yhni eyEs


Characters at odd positions: erigPto svr ay

#Python Program to Merge Characters of 2 Strings into a Single String by taking Characters alternatively
#Input: s1 = ravi
#s2 = teja
#Output: rtaevjia
s1 = input("Enter first string: ")
s2 = input("Enter second string: ")
merged = ""
max_len = max(len(s1), len(s2))
for i in range(max_len):
if i < len(s1):
merged += s1[i]
if i < len(s2):
merged += s2[i]

print("Merged string:", merged)

Merged string: rtaevjia

#Python Program to Sort the Characters of the String and First Alphabet Symbols followed by Numeric Values
`#Input: B4A1D3
#output: ABD134
s = input("Enter the string: ")
letters = []
digits = []
for ch in s:
if ch.isalpha():
letters.append(ch)
elif ch.isdigit():
digits.append(ch)

letters.sort()
digits.sort()
sorted_string = ''.join(letters + digits)
print("Sorted output:", sorted_string)

Sorted output: ABD134

#Python Program for the following Requirement


#Input: a4b3c2
#Output: aaaabbbcc
s = input("Enter the encoded string: ")
result = ""
i = 0
while i < len(s):
char = s[i]
i += 1
num = ""
while i < len(s) and s[i].isdigit():
num += s[i]
i += 1
result += char * int(num)
print("Decoded output:", result)

Decoded output: aaaabbbcc

#Python Program to Remove Duplicate Characters from the given Input String?
#Input: ABCDABBCDABBBCCCDDEEEF
#Output: ABCDEF
s = input("Enter the string: ")
result = ""
for char in s:
if char not in result:
result += char
print("Output after removing duplicates:", result)

Output after removing duplicates: ABCDEF


#Python Program to find the Number of Occurrences of each Character present in the given String?
#Input: ABCABCABBCDE
#Output: A-3,B-4,C-3,D-1,E-1
s = input("Enter the string: ")
char_count = {}
for char in s:
if char in char_count:
char_count[char] += 1
else:
char_count[char] = 1
output = []
for char in char_count:
output.append(f"{char}-{char_count[char]}")
print("Output:", ",".join(output))

Output: A-3,B-4,C-3,D-1,E-1

#Python Program to find the largest and smallest number in a list of integers.
def find_largest_and_smallest(numbers):
if not numbers:
return None, None
largest = smallest = numbers[0]
for num in numbers[1:]:
if num > largest:
largest = num
elif num < smallest:
smallest = num
return largest, smallest
numbers = [12, 45, 2, 9, 67, 34, 1]
largest, smallest = find_largest_and_smallest(numbers)
print(f"Largest number: {largest}")
print(f"Smallest number: {smallest}")

Largest number: 67
Smallest number: 1

#Python Program to compute transpose of a matrix


def transpose_matrix(matrix):
rows = len(matrix)
cols = len(matrix[0])
transpose = [[0 for _ in range(rows)] for _ in range(cols)]
for i in range(rows):
for j in range(cols):
transpose[j][i] = matrix[i][j]
return transpose
matrix = [
[1, 2, 3],
[4, 5, 6]
]
transposed = transpose_matrix(matrix)
print("Original Matrix:")
for row in matrix:
print(row)
print("\nTransposed Matrix:")
for row in transposed:
print(row)

Original Matrix:
[1, 2, 3]
[4, 5, 6]

Transposed Matrix:
[1, 4]
[2, 5]
[3, 6]

#Python Program to perform Matrix Addition.


def add_matrices(matrix1, matrix2):
result = []

if len(matrix1) != len(matrix2) or len(matrix1[0]) != len(matrix2[0]):


return "Error: Matrices must have the same dimensions for addition."

for i in range(len(matrix1)):
row = []
for j in range(len(matrix1[0])):
row.append(matrix1[i][j] + matrix2[i][j])
result.append(row)

return result

matrix1 = [
[1, 2, 3],
[4, 5, 6]
]

matrix2 = [
[7, 8, 9],
[10, 11, 12]
]

result = add_matrices(matrix1, matrix2)

print("Matrix 1:")
for row in matrix1:
print(row)

print("\nMatrix 2:")
for row in matrix2:
print(row)

print("\nSum of Matrices:")
if isinstance(result, str):
print(result)
else:
for row in result:
print(row)

Matrix 1:
[1, 2, 3]
[4, 5, 6]

Matrix 2:
[7, 8, 9]
[10, 11, 12]

Sum of Matrices:
[8, 10, 12]
[14, 16, 18]

# Python Program to perform matrix multiplication


def multiply_matrices(matrix1, matrix2):
if len(matrix1[0]) != len(matrix2):
return "Error: Number of columns in Matrix 1 must equal number of rows in Matrix 2."
result = []
for i in range(len(matrix1)):
row = []
for j in range(len(matrix2[0])):
total = 0
for k in range(len(matrix2)):
total += matrix1[i][k] * matrix2[k][j]
row.append(total)
result.append(row)
return result

matrix1 = [
[1, 2],
[3, 4],
[5, 6]
]

matrix2 = [
[7, 8, 9],
[10, 11, 12]
]

result = multiply_matrices(matrix1, matrix2)

print("Matrix 1:")
for row in matrix1:
print(row)

print("\nMatrix 2:")
for row in matrix2:
print(row)

print("\nProduct of Matrices:")
if isinstance(result, str):
print(result)
else:
for row in result:
print(row)
Matrix 1:
[1, 2]
[3, 4]
[5, 6]

Matrix 2:
[7, 8, 9]
[10, 11, 12]

Product of Matrices:
[27, 30, 33]
[61, 68, 75]
[95, 106, 117]

#Python Program to determine whether a given list is Palindrome or not.


def is_palindrome(lst):
return lst == lst[::-1]

sample_list = [1, 2, 3, 2, 1]

if is_palindrome(sample_list):
print("The list is a palindrome.")
else:
print("The list is not a palindrome.")

The list is a palindrome.

#Python Program to insert a sub-list in to given main list from a given position.
def insert_sublist(main_list, sub_list, position):
if position < 0 or position > len(main_list):
return "Error: Position out of range."

return main_list[:position] + sub_list + main_list[position:]

main_list = [1, 2, 3, 7, 8]
sub_list = [4, 5, 6]
position = 3

result = insert_sublist(main_list, sub_list, position)

print("Main List:", main_list)


print("Sub List:", sub_list)
print("Position:", position)
print("Resulting List:", result)

Main List: [1, 2, 3, 7, 8]


Sub List: [4, 5, 6]
Position: 3
Resulting List: [1, 2, 3, 4, 5, 6, 7, 8]

#Python Program to delete n Characters from a given position in a given list.


def delete_n_elements(lst, position, n):
if position < 0 or position >= len(lst):
return "Error: Position out of range."

return lst[:position] + lst[position + n:]

sample_list = ['a', 'b', 'c', 'd', 'e', 'f', 'g']


position = 2
n = 3

result = delete_n_elements(sample_list, position, n)

print("Original List:", sample_list)


print(f"Deleting {n} elements from position {position}...")
print("Updated List:", result)

Original List: ['a', 'b', 'c', 'd', 'e', 'f', 'g']


Deleting 3 elements from position 2...
Updated List: ['a', 'b', 'f', 'g']

#Python Program to replace a character of string either from beginning or ending or at a specified location.
def replace_char(string, new_char, position_type='beginning', index=None):
if not string:
return "Error: Empty string."

if position_type == 'beginning':
return new_char + string[1:]
elif position_type == 'ending':
return string[:-1] + new_char
elif position_type == 'specific':
if index is None or index < 0 or index >= len(string):
return "Error: Invalid index for replacement."
return string[:index] + new_char + string[index + 1:]
else:
return "Error: Invalid position type. Use 'beginning', 'ending', or 'specific'."

original_string = "hello"
print("Replace from beginning:", replace_char(original_string, 'H', 'beginning'))
print("Replace from ending:", replace_char(original_string, 'O', 'ending'))
print("Replace at index 1:", replace_char(original_string, 'A', 'specific', index=1))

Replace from beginning: Hello


Replace from ending: hellO
Replace at index 1: hAllo

# Python Program to create tuples (name, age, address, college) for at least two numbers and concatenate the tuples a
person1 = ("Alice", 21, "123 Main St", "Harvard University")
person2 = ("Bob", 22, "456 Oak Ave", "Stanford University")

combined_tuple = person1 + person2

print("Person 1 Tuple:", person1)


print("Person 2 Tuple:", person2)
print("\nConcatenated Tuple:")
print(combined_tuple)

Person 1 Tuple: ('Alice', 21, '123 Main St', 'Harvard University')


Person 2 Tuple: ('Bob', 22, '456 Oak Ave', 'Stanford University')

Concatenated Tuple:
('Alice', 21, '123 Main St', 'Harvard University', 'Bob', 22, '456 Oak Ave', 'Stanford University')

# Python Program to generate a dictionary that contains numbers between 1 and n) in the form of (x, x*x).
def generate_square_dict(n):
return {x: x*x for x in range(1, n+1)}

n = 5
square_dict = generate_square_dict(n)
print(f"Dictionary of (x, x*x) from 1 to {n}:")
print(square_dict)

Dictionary of (x, x*x) from 1 to 5:


{1: 1, 2: 4, 3: 9, 4: 16, 5: 25}

# Python Program to check if a given key exists in a dictionary or not.


# Sample dictionary
my_dict = {
"name": "Alice",
"age": 25,
"city": "New York"
}

key_to_check = "age"

if key_to_check in my_dict:
print(f"Key '{key_to_check}' exists in the dictionary with value: {my_dict[key_to_check]}")
else:
print(f"Key '{key_to_check}' does NOT exist in the dictionary.")

Key 'age' exists in the dictionary with value: 25

# Python Program to add a new key-value pair to an existing dictionary.


my_dict = {
"name": "Alice",
"age": 25,
"city": "New York"
}

new_key = "college"
new_value = "Harvard University"

my_dict[new_key] = new_value

print("Updated Dictionary:")
print(my_dict)

Updated Dictionary:
{'name': 'Alice', 'age': 25, 'city': 'New York', 'college': 'Harvard University'}

# Python Program to sum all the items in a given dictionary.


my_dict = {
"item1": 10,
"item2": 20,
"item3": 30,
"item4": 40
}

total_sum = sum(my_dict.values())
print("Sum of all the items in the dictionary:", total_sum)

Sum of all the items in the dictionary: 100

# Python Program to sort words in a file and put them in another file in lowercase.
def sort_words_in_file(input_file, output_file):
try:
with open(input_file, 'r') as f:
text = f.read()

words = text.split()
words = [word.lower() for word in words]

words.sort()

with open(output_file, 'w') as f:


for word in words:
f.write(word + '\n')

print("Words sorted and written to", output_file)

except FileNotFoundError:
print("Input file not found.")

input_file = 'input.txt'
output_file = 'output.txt'
sort_words_in_file(input_file, output_file)

Words sorted and written to output.txt

#Python Program to create, display, append, insert, reverse the order of items in the array.
import array

def main():
arr = array.array('i', [10, 20, 30, 40])
print("Initial array:")
display_array(arr)

arr.append(50)
print("\nAfter appending 50:")
display_array(arr)

arr.insert(2, 25)
print("\nAfter inserting 25 at index 2:")
display_array(arr)

arr.reverse()
print("\nAfter reversing the array:")
display_array(arr)

def display_array(arr):
for item in arr:
print(item, end=' ')
print()

main()

Initial array:
10 20 30 40

After appending 50:


10 20 30 40 50

After inserting 25 at index 2:


10 20 25 30 40 50

After reversing the array:


50 40 30 25 20 10

# Open the file to read from


file_in = open("input.txt", "r")
text = file_in.read()
file_in.close()

# Make all letters small and split into words


words = text.lower().split()

# Sort the words


words.sort()

# Open a file to write the sorted words


file_out = open("output.txt", "w")
for word in words:
file_out.write(word + "\n")
file_out.close()
print("Done! Sorted words are saved in output.txt")

Done! Sorted words are saved in output.txt


Loading [MathJax]/jax/output/CommonHTML/fonts/TeX/fontdata.js

You might also like