Python codes
Python codes
WEEK-1
Kartikeya
Roll no.:- 2300971520103
Question 1:
• Task: Python installation, environment setup, and introduction to an IDE.
• Required IDEs: (anyone from) IDLE, Jupyter Notebook, PyCharm, Spider, etc.
Answer:
1. Python Installation:
To install Python:
1. Visit the official Python website.
2. Download the latest version of Python for your operating system (Windows, macOS, or Linux).
3. Run the installer and check the box that says "Add Python to PATH."
4. Complete the installation process.
2. Environment Setup:
Once Python is installed, you can verify the installation by opening the command prompt (or terminal)
and typing:
python --version
This should display the version of Python installed.
3. Choosing an IDE:
An Integrated Development Environment (IDE) allows you to write, test, and debug Python code
efficiently. Here’s a brief introduction to the recommended IDEs:
• IDLE: Comes bundled with Python. It's simple and lightweight for beginners.
• Jupyter Notebook: A web-based tool used for interactive computing. Ideal for data science
and scripting tasks.
• PyCharm: A powerful IDE from JetBrains with advanced features like code completion,
debugging, and version control.
• Spyder: Popular in the scientific community, designed for data science and engineering.
To install Jupyter Notebook, you can use the following commands (assuming pip is installed):
Question 2:
Write a Python program to compute the future value of a specified principal amount, rate of
interest, and number of years.
Code:
# Input from user
amt = float(input("Enter the principal amount: "))
rate = float(input("Enter the rate of interest: "))
years = int(input("Enter the number of years: "))
# Formula to calculate future value
future_value = amt * ((1 + (rate / 100)) ** years)
# Output
print("Future value:", round(future_value, 2))
Output:
Question 3:
The target is to compute the distance between two points accepted from the user.
Code:
# Input from user
x1, y1 = map(float, input("Enter x1, y1 separated by a comma: ").split(","))
x2, y2 = map(float, input("Enter x2, y2 separated by a comma: ").split(","))
Output:
Question 4:
Given two int values, return their sum. Unless the two values are the same, then return double
their sum.
Code:
# Input from user
a = int(input("Enter first number: "))
b = int(input("Enter second number: "))
# Sum calculation
if a == b:
result = 2 * (a + b)
else:
result = a + b
# Output
print("Result:", result)
Output:
Question 5:
We are in trouble if the parrot is talking, and the hour is before 7 or after 20. Return True if we are
in trouble.
Code:
# Input from user
talking = input("Is the parrot talking? (True/False): ").lower() == 'true'
hour = int(input("Enter the current hour (0-23): "))
# Trouble check
if talking and (hour < 7 or hour > 20):
print("We are in trouble: True")
else:
print("We are in trouble: False")
Output:
Question 6:
Given 2 int values, return True if one is negative and one is positive. If "negative" parameter is
True, return True only if both are negative.
Code:
# Input from user
a = int(input("Enter first number: "))
b = int(input("Enter second number: "))
negative = input("Is negative parameter True or False? ").lower() == 'true'
# Condition check
if negative:
result = a < 0 and b < 0
else:
result = (a < 0 and b >= 0) or (a >= 0 and b < 0)
# Output
print("Result:", result)
Output:
Question 7:
Given an int n, return True if it is within 10 of 100 or 200.
Code:
# Input from user
n = int(input("Enter a number: "))
# Condition check
result = abs(100 - n) <= 10 or abs(200 - n) <= 10
# Output
print("Result:", result)
Output:
Question 8:
Given an int n, return the absolute difference between n and 21, except return double the
absolute difference if n is over 21.
Code:
# Input from user
n = int(input("Enter a number: "))
# Condition check
if n > 21:
result = 2 * abs(n - 21)
else:
result = abs(n - 21)
# Output
print("Result:", result)
Output:
WEEK-2
Question 1:
Basic Calculator
Code:
# Input from user
num1 = float(input("Enter the first number: "))
num2 = float(input("Enter the second number: "))
operator = input("Enter an operator (+, -, *, /): ")
# Calculator logic
if operator == '+':
result = num1 + num2
elif operator == '-':
result = num1 - num2
elif operator == '*':
result = num1 * num2
elif operator == '/':
if num2 != 0:
result = num1 / num2
else:
result = "Cannot divide by zero"
else:
result = "Invalid operator"
# Output
print("Result:", result)
Output:
Question 2:
Discount Calculation
Code:
# Input from user
total_amount = float(input("Enter the total purchase amount: "))
# Discount calculation
if total_amount > 100:
discount = 0.10
else:
discount = 0.05
# Output
print("Final amount after discount:", round(final_amount, 2))
Output:
Question 3:
Grade Assignment
Code:
# Input from user
score = int(input("Enter the score: "))
# Grade assignment
if score >= 90:
grade = 'A'
elif score >= 80:
grade = 'B'
elif score >= 70:
grade = 'C'
elif score >= 60:
grade = 'D'
else:
grade = 'F'
# Output
print("Grade:", grade)
Output:
Question 4:
Century Year and Leap Year Check
Code:
# Input from user
year = int(input("Enter a year: "))
# Output
print(f"{year} is a century year:", is_century)
print(f"{year} is a leap year:", is_leap)
Output:
Question 5:
GCD Calculation (Euclidean Algorithm)
Code:
# Input from user
a = int(input("Enter the first number: "))
b = int(input("Enter the second number: "))
# Output
print("GCD:", a)
Output:
WEEK-3
Question 1:
Interest Percentage Based on Gender and Age
Code:
# Input from user
gender = input("Enter gender (Male/Female): ").capitalize()
age = int(input("Enter age: "))
# Output
print(f"Interest rate: {interest}%")
Output:
Question 2:
Print Corresponding Month Name
Code:
# Input from user
month_num = int(input("Enter month number (1-12): "))
# Output logic
if month_num in months:
print(f"The month is: {months[month_num]}")
elif 1 <= month_num <= 12:
print("Please enter the month in numbers")
else:
print("Invalid month")
Output:
Question 3:
Sum of Digits of a Given Number
Code:
# Input from user
number = input("Enter a number: ")
# Sum calculation
sum_of_digits = sum(int(digit) for digit in number)
# Output
print(f"Sum of digits: {sum_of_digits}")
Output:
Question 4:
Print * in Floyd's Triangle Format
Code:
# Input from user
n = int(input("Enter an integer number: "))
# Floyd's triangle using for loop
for i in range(1, n+1):
print("* " * i)
Output:
Question 5:
Palindrome Check
Code:
# Input from user
number = input("Enter a number: ")
# Palindrome check
if number == number[::-1]:
print(f"{number} is a palindrome")
else:
print(f"{number} is not a palindrome")
Output:
WEEK-5
Question 1:
Extract Elements with Frequency Greater than K
Code:
from collections import Counter
# Input from user
test_list = list(map(int, input("Enter the list of numbers: ").split()))
K = int(input("Enter the value of K: "))
# Count frequency of elements
frequency = Counter(test_list)
# Extract elements with frequency greater than K
result = [key for key, value in frequency.items() if value > K]
# Output
print("Elements with frequency greater than K:", result)
Output:
Question 2:
Check for Three Consecutive Common Numbers
Code:
# Input from user
test_list = list(map(int, input("Enter the list of numbers: ").split()))
# Output
print("Numbers occurring 3 consecutive times:", result)
Output:
Question 3:
Character Position of Kth Word in a List of Strings
Code:
# Input from user
test_list = input("Enter the list of strings: ").split(", ")
K = int(input("Enter the character position (K): "))
Output:
Question 4:
Extract Words Starting with a Specific Character (K)
Code:
# Input from user
test_list = input("Enter the list of phrases: ").split(", ")
K = input("Enter the character to check for: ").lower()
# Output
print("Words starting with", K, ":", result)
Output:
Question 5:
Replace All Characters of a List Except Given Character
Code:
# Input from user
test_list = input("Enter the list of characters: ").split()
repl_chr = input("Enter the character to replace others with: ")
ret_chr = input("Enter the character to retain: ")
# Replace characters
result = [repl_chr if char != ret_chr else ret_chr for char in test_list]
# Output
print("Modified list:", result)
Output:
Question 6:
Add Space Between Capital Letters in a String List
Code:
import re
# Input from user
test_list = input("Enter the list of strings: ").split(", ")
# Add space between capital letters
result = [re.sub(r'([a-z])([A-Z])', r'\1 \2', phrase) for phrase in test_list]
# Output
print("Modified list:", result)
Output:
Question 7:
Filter List Based on Substring in Corresponding Index of Second List
Code:
# Input from user
test_list1 = input("Enter the first list: ").split(", ")
test_list2 = input("Enter the second list: ").split(", ")
sub_str = input("Enter the substring to check for: ")
# Filter list
result = [test_list1[i] for i in range(len(test_list2)) if sub_str in test_list2[i]]
# Output
print("Filtered list:", result)
Output:
Question 8:
Convert Character Matrix to Single String
Code:
# Input from user
test_list = [list(input(f"Enter row {i+1} elements separated by spaces: ").split()) for i in range(3)]
# Output
print("Single string:", result)
Output:
WEEK-4
Question 1:
Count the Occurrence of an Item in the List
Code:
# Input from user
lst = list(map(int, input("Enter the list of numbers: ").split()))
x = int(input("Enter the number to count occurrences of: "))
# Count occurrences
count = lst.count(x)
# Output
print(f"Occurrences of {x}: {count}")
Output:
Question 2:
Find Second Largest Number in a List
Code:
# Input from user
lst = list(map(int, input("Enter the list of numbers: ").split()))
# Output
if len(unique_lst) > 1:
print("Second largest number:", unique_lst[-2])
else:
print("No second largest number found")
Output:
Question 3:
Remove Multiple Elements from List
Code:
# Input from user
lst = list(map(int, input("Enter the list of numbers: ").split()))
# Condition: Remove all odd numbers
result = [x for x in lst if x % 2 == 0]
# Output
print("List after removing odd numbers:", result)
Output:
Question 4:
Print Duplicates from a List
Code:
from collections import Counter
# Input from user
lst = list(map(int, input("Enter the list of numbers: ").split()))
# Find duplicates
count = Counter(lst)
duplicates = [item for item, freq in count.items() if freq > 1]
# Output
print("Duplicate elements:", duplicates)
Output:
Question 5:
Find Uncommon Elements in Lists of Lists
Code:
# Input from user
list1 = [list(map(int, input(f"Enter elements for sublist {i+1} in list1: ").split())) for i in range(3)]
list2 = [list(map(int, input(f"Enter elements for sublist {i+1} in list2: ").split())) for i in range(3)]
# Output
print("Uncommon elements:", result)
Output:
Question 6:
Extract Elements with Frequency Greater than K
Code:
from collections import Counter
# Input from user
test_list = list(map(int, input("Enter the list of numbers: ").split()))
K = int(input("Enter the value of K: "))
# Output
print("Elements with frequency greater than K:", result)
Output:
Question 7:
Check for Three Consecutive Common Numbers
Code:
# Input from user
test_list = list(map(int, input("Enter the list of numbers: ").split()))
Question 8:
Find the Strongest Neighbour
Code:
# Input from user
arr = list(map(int, input("Enter the array elements: ").split()))
# Output
print("Strongest neighbours:", result)
Output:
Question 9:
Find All Possible Combinations from Three Digits
Code:
from itertools import permutations
# Input from user
digits = list(map(int, input("Enter three digits: ").split()))
# Generate all permutations
result = list(permutations(digits))
# Output
for perm in result:
print(' '.join(map(str, perm)))
Output:
Question 10:
Retain Records with N Occurrences of K
Code:
# Input from user
test_list = [tuple(map(int, input(f"Enter elements for tuple {i+1}: ").split())) for i in range(2)]
K = int(input("Enter the value of K: "))
N = int(input("Enter the value of N: "))
# Output
print("Retained records:", result)
Output:
WEEK-6
Question 1:
Sorting Dictionary By Key Using sort()
Code:
# Input
input_dict = {'ravi': '10', 'rajnish': '9', 'abc': '15'}
# Output
print("Sorted dictionary:", sorted_dict)
Output:
Question 2:
Merging or Concatenating Two Dictionaries in Python
Code:
# Input
d1 = {'x': 10, 'y': 8}
d2 = {'a': 6, 'b': 4}
# Merging dictionaries
merged_dict = {**d1, **d2}
# Output
print("Merged dictionary:", merged_dict)
Output:
Question 3:
Find Common Elements in Three Sorted Arrays by Dictionary Intersection
Code:
# Input
ar1 = [1, 5, 10, 20, 40, 80]
ar2 = [6, 7, 20, 80, 100]
ar3 = [3, 4, 15, 20, 30, 70, 80, 120]
# Output
print("Common elements:", common_elements)
Output:
Question 4:
Dictionary and Counter in Python to Find Winner of Election
Code:
# Input
votes = ["john", "johnny", "jackie", "johnny", "john", "jackie", "jamie", "jamie", "john", "johnny", "jamie",
"johnny", "john"]
# Counting votes
from collections import Counter
vote_count = Counter(votes)
# Output
print("Winner:", winner)
Output:
Question 5:
Python Dictionary to Find Mirror Characters in a String
Code:
# Input
N=3
string = "paradox"
# Mirroring characters
mirrored_string = string[:N] + ''.join(chr(219 - ord(c)) for c in string[N:])
# Output
print("Mirrored string:", mirrored_string)
Output:
Question 6:
Count Distinct Substrings of a String Using Rabin Karp Algorithm
Code:
# Input
s = "aba"
# Output
print("Number of distinct substrings:", len(distinct_substrings))
Output:
Question 7:
Print Anagrams Together in Python Using List and Dictionary
Code:
# Input
arr = ['cat', 'dog', 'tac', 'god', 'act']
# Grouping anagrams
from collections import defaultdict
anagrams = defaultdict(list)
for word in arr:
anagrams[tuple(sorted(word))].append(word)
# Output
print("Anagrams together:", ' '.join([word for group in anagrams.values() for word in group]))
Output:
Question 8:
Similar Characters Strings Comparison
Code:
# Input
test_str1 = 'e!e!k!s!g'
test_str2 = 'g!e!e!k!s'
delim = '!'
# Output
print("Same characters:", same_chars)
Output:
Question 9:
Longest Substring Length of K
Code:
# Input
test_str = 'abcaaaacbbaa'
K = 'b'
# Finding longest substring length
longest_length = test_str.count(K)
# Output
print("Longest substring length of", K, ":", longest_length)
Output:
Question 10:
Find Minimum Number of Rotations to Obtain Actual String
Code:
# Input
s1 = 'eeksg'
s2 = 'geeks'
# Finding minimum rotations
n = len(s1)
rotations = s1 + s1
min_rotations = next((i for i in range(n) if rotations[i:i+n] == s2), -1)
# Output
print("Minimum number of rotations:", min_rotations)
Output: