Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
5 views19 pages

Answer Sheet

Python

Uploaded by

dallanamikas
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)
5 views19 pages

Answer Sheet

Python

Uploaded by

dallanamikas
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/ 19

Question 1: Basic Operations and Type Casting (Easy)

Answer:
Birth_year = int (input ("Enter your birth year: "))
Current_year = date.today().year
Current_age = Current_year - Birth_year
Days_lived = Current_age * 365
is_eligible_to_vote = Current_age >= 18

print(f"You are {Current_age} years old")


print(f"You have lived approximately {Days_lived} days")
if is_eligible_to_vote:
print("Voting eligibility: Eligible")
else:
print ("Voting eligibility: Ineligible")

OUTPUT

Question 2: String Manipulation and Conditionals (Easy Medium)


Answer:

def check_password_strength(password):
special_characters = "!@#$%^&*"
length_check = len(password) >= 8
uppercase_check = any(char.isupper() for char in password)
digit_check = any(char.isdigit() for char in password)
special_check = any(char in special_characters for char in password)
print ("✓ Length requirement met" if length_check else "✗ Minimum 8 characters required")
print ("✓ Uppercase letter found" if uppercase_check else "✗ At least one uppercase letter
required") print ("✓ Digit found" if digit_check else "✗ At least one digit required")
print ("✓ Special character found" if special_check else "✗ At least one special character
(!@#$%^&*) required")
criteria_met = sum ([length_check, uppercase_check, digit_check, special_check])
if criteria_met == 4:
strength = "Strong"
elif criteria_met == 3:
strength = "Medium"
else:
strength = "Weak"
print (f"\nPassword strength: {strength}")
password = input ("Enter password: ")
check_password_strength (password)

OUTPUT

Question 3: Lists and Basic Algorithms (Medium)


Answer:
input_str = input ("Enter numbers: ")
numbers = list (map (int, input_str.strip().split()))
print ("Original list:", numbers)
largest = None
second_largest = None
for num in numbers:
if largest is None or num > largest:
second_largest = largest
largest = num
elif num != largest and (second_largest is None or num > second_largest):
second_largest = num

if second_largest is None:
print("Not enough unique numbers to find the second largest.")
else:
print("Largest:", largest)
print ("Second largest:", second_largest)

OUTPUT

Question 4: Dictionary Operations and Data Analysis (Medium)


Answer:
students = {}
while True:
data = input("Enter student data (name:score): ")
if not data:
print("(empty input)")
break
try:
name, score = data.split(":")
students[name.strip()] = int(score.strip())
except:
print("Invalid format. Use name:score")

if students:
scores = list(students.values())
avg = sum(scores) / len(scores)
max_score = max(scores)
min_score = min(scores)

highest = [k for k, v in students.items() if v == max_score][0]


lowest = [k for k, v in students.items() if v == min_score][0]

grade_count = {"A": 0, "B": 0, "C": 0, "D": 0, "F": 0}


above_avg = []

for name, score in students.items():


if score >= 90:
grade_count["A"] += 1
elif score >= 80:
grade_count["B"] += 1
elif score >= 70:
grade_count["C"] += 1
elif score >= 60:
grade_count["D"] += 1
else:
grade_count["F"] += 1

if score > avg:


above_avg.append(name)

print ("\nClass Report:")


print (f"Average score: {avg:.1f}")
print (f"Highest: {highest} ({max_score})")
print (f"Lowest: {lowest} ({min_score})")
print (f"Grade distribution: A={grade_count['A']}, B={grade_count['B']}, C={grade_count['C']},
D={grade_count['D']}, F={grade_count['F']}")
print (f"Above average: {', '.join(above_avg)}")

OUTPUT

Question 5: Nested Data Structures and Pattern Recognition


(Medium-Hard)
Answer:
def display_board(board): print("\
nBoard:")
for i, row in enumerate(board):
print(" | ".join(row))
if i < 2:
print("-" * 9)

def check_winner(board):
for i in range(3):
if board[i][0] == board[i][1] == board[i][2] and board[i][0] != ' ':
return board[i][0], f"Horizontal win in row {i+1}"
for j in range(3):
if board[0][j] == board[1][j] == board[2][j] and board[0][j] != ' ':
return board[0][j], f"Vertical win in column {j+1}"

if board[0][0] == board[1][1] == board[2][2] and board[0][0] != '


': return board[0][0], "Diagonal win (top-left to bottom-right)"

if board[0][2] == board[1][1] == board[2][0] and board[0][2] != '


': return board[0][2], "Diagonal win (top-right to bottom-left)"

return None, None

def is_draw(board):
for row in board:
if ' ' in row:
return False
return True

board = [
['X', 'O', 'X'],
['O', 'X', 'O'],
['O', 'X', 'X']
]
display_board(board)
winner, win_type = check_winner(board)
if winner:
print(f"\nResult: {winner} wins ({win_type})")
elif is_draw(board):
print("\nResult: Draw")
else:
print ("\nResult: Game not finished")
OUTPUT

Question 6: Set Operations and Advanced Logic (Hard)


Answer:
emails1 = ["[email protected]", "[email protected]", "[email protected]", "[email protected]",
"[email protected]"]
emails2 = ["[email protected]", "[email protected]", "[email protected]"]

def extract_unique_domains(email_list):
"""
Extracts unique domains from a list of email addresses,
handling invalid email formats.

Args:
email_list: A list of email addresses (strings).

Returns:
A set of unique domains (strings).
"""
unique_domains = set()
for email in email_list:
if "@" in email:
try:
domain = email.split("@")[1]
unique_domains.add(domain)
except IndexError:
print(f"Warning: Invalid email format (missing domain): {email}")
else:
print(f"Warning: Invalid email format (missing @): {email}")
return unique_domains

unique_domains1 = extract_unique_domains(emails1)
unique_domains2 = extract_unique_domains(emails2)
print("Domain Analysis:")
print("Unique domains in emails1:",
unique_domains1) print("Unique domains in
emails2:", unique_domains2)

common_domains = unique_domains1.intersection(unique_domains2)
print("Common domains:", common_domains)

all_unique_domains = unique_domains1.union(unique_domains2)
suspicious_domains = set()

for domain in all_unique_domains:


if (domain in unique_domains1 and domain not in unique_domains2) or (domain not in
unique_domains1 and domain in unique_domains2):
suspicious_domains.add(domain)

print("Suspicious domains (appear only once):", suspicious_domains)

from collections import Counter

all_emails = emails1 + emails2


domain_counts = Counter()

for email in all_emails:


if "@" in email:
try:
domain = email.split("@")[1]
domain_counts[domain] += 1
except IndexError:
print(f"Warning: Invalid email format (missing domain): {email}")
else:
print(f"Warning: Invalid email format (missing @): {email}")

if domain_counts:
most_popular_domain, most_popular_count = domain_counts.most_common(1)[0]
else:
most_popular_domain = None
most_popular_count = 0

print("Domain counts:", domain_counts)


print(f"Most popular domain: {most_popular_domain} ({most_popular_count} occurrences)")

OUTPUT

Question 7: Brain Teaser - Number Pattern Detective (Hard)


Answer:
def detect_arithmetic(seq):
"""
Detects an arithmetic progression.
Returns ("Arithmetic", [next 3 numbers]) if found, otherwise None.
"""
if len(seq) < 2:
return None
diff = seq[1] - seq[0]

is_arithmetic = True
for i in range(len(seq) - 1):
if abs((seq[i + 1] - seq[i]) - diff) > 1e-9:
is_arithmetic = False
break

if is_arithmetic:
next_values = []
last_num = seq[-1]
for i in range(1, 4):
last_num += diff
next_values.append(last_num)

return (f"Arithmetic: {'+' if diff >= 0 else ''}{diff}", next_values)


return None

def detect_geometric(seq):
"""
Detects a geometric progression.
Returns ("Geometric", [next 3 numbers]) if found, otherwise None.
"""
if len(seq) < 2:
return None

if 0 in seq:
return None

ratio = seq[1] / seq[0]

is_geometric = True
for i in range(len(seq) - 1):

if seq[i] == 0:
is_geometric = False
break
if abs((seq[i + 1] / seq[i]) - ratio) > 1e-9:
is_geometric = False
break

if is_geometric:
next_values = []
last_num = seq[-1]
for i in range(1, 4):
last_num *= ratio
next_values.append(last_num)

return (f"Geometric: x{ratio}", next_values)


return None

def detect_fibonacci(seq):
"""
Detects a Fibonacci-like sequence.
Returns ("Fibonacci", [next 3 numbers]) if found, otherwise None.
"""
if len(seq) < 3:
return None

is_fibonacci = True
for i in range(2, len(seq)):

if seq[i] != seq[i - 1] + seq[i - 2]:


is_fibonacci = False
break

if is_fibonacci:
next_values = []

a, b = seq[-2], seq[-1]
for _ in range(3):
next_num = a + b
next_values.append(next_num)

a=b
b = next_num
return ("Fibonacci", next_values)
return None

def detect_squares(seq):
"""
Detects a sequence of perfect squares starting from 1^2.
Returns ("Squares", [next 3 numbers]) if found, otherwise None.
"""
if len(seq) == 0:
return None

is_squares = True
for i, x in enumerate(seq):
expected_square_root = i + 1

if x < 0:
is_squares = False
break

actual_square_root = round(math.sqrt(x))
if not math.isclose(x, actual_square_root ** 2) or actual_square_root != expected_square_root:
is_squares = False
break

if is_squares:
next_values = []

start_root_for_next = len(seq) + 1
for i in range(3):
next_values.append((start_root_for_next + i) ** 2)
return ("Squares", next_values)
return None

def detect_cubes(seq):
"""
Detects a sequence of perfect cubes starting from 1^3.
Returns ("Cubes", [next 3 numbers]) if found, otherwise None.
"""
if len(seq) == 0:
return None

is_cubes = True
for i, x in enumerate(seq):
expected_cube_root = i + 1

if x < 0:
actual_cube_root = round((-x)**(1/3)) * -1
else:
actual_cube_root = round(x**(1/3))
if not math.isclose(x, actual_cube_root ** 3) or actual_cube_root != expected_cube_root:
is_cubes = False
break
if is_cubes:
next_values = []
start_root_for_next = len(seq) + 1
for i in range(3):
next_values.append((start_root_for_next + i) ** 3)
return ("Cubes", next_values)
return None

def detect_power_minus1(seq):
"""
Detects a sequence following the 2^n - 1 pattern.
Returns ("Pattern: 2^n - 1", [next 3 numbers]) if found, otherwise None.
"""
if len(seq) == 0:
return None
is_power_minus1 = True
for i, x in enumerate(seq):
expected_value = (2**(i + 1)) - 1
if x != expected_value:
is_power_minus1 = False
break
if is_power_minus1:
next_values = []
start_n_for_next = len(seq) + 1
for i in range(3):
next_values.append((2**(start_n_for_next + i)) - 1)
return ("Pattern: 2^n - 1", next_values)
return None
def detect_pattern(seq):
"""
Tries to detect various patterns in the sequence in a specific order.
"""
detectors = [
detect_arithmetic,
detect_geometric,
detect_fibonacci,
detect_squares,
detect_cubes,
detect_power_minus1
]
for detect_func in detectors:
result = detect_func(seq)
if result:
return result

return ("No clear pattern", [])


# --- Main execution block ---
print(f"{'Number Pattern Detector':-^100}")
print("Enter sequences to see their patterns and next numbers.")
print("Type 'exit' to quit.")

while True:
try:
user_input = input("\nEnter the sequence (space-separated numbers): ")
if user_input.lower() == 'exit':
break

sequence_str = user_input.split()
sequence = []
for s in sequence_str:
try:
sequence.append(int(s))
except ValueError:
try:
sequence.append(float(s))
except ValueError:
print(f"Invalid input: '{s}' is not a valid number. Please enter numbers
only.") sequence = []
break
if not sequence:
continue
pattern_type, next_values = detect_pattern(sequence)
print(f"Input: {sequence} -> {pattern_type}, Next: {next_values}")

except Exception as e:
print (f"An error occurred: {e}")
print ("Please ensure your input is a valid sequence of space-separated numbers.")

OUTPUT
Question 8: Brain Teaser - Text Cipher Decoder (Hard)
Answer:
def caesar_decode(text, shift):
result = []
for char in text:
if char.isalpha():
base = ord('A') if char.isupper() else ord('a')
result.append(chr((ord(char) - base - shift) % 26 + base))
else:
result.append(char)
return ''.join(result)

def reverse_decode(text):
return text[::-1]

def vowel_decode(text):
rev_map = {'1': 'a', '2': 'e', '3': 'i', '4': 'o', '5': 'u'}
return ''.join(rev_map[c] if c in rev_map else c for c in text)

def unscramble_word(word):
if len(word) <= 3:
return word
middle = list(word[1:-1])
middle.sort()
return word[0] + ''.join(middle) + word[-1]

def word_unscramble(text):
return ' '.join(unscramble_word(word) for word in text.split())

def detect_caesar(text):
for shift in range(1,
26):
decoded = caesar_decode(text, shift)
if "hello" in decoded.lower():
return ("Caesar", shift, decoded)
return None

def auto_decode(text):
candidates = []

caesar = detect_caesar(text)
if caesar:
candidates.append(f"Detected: Caesar cipher (shift={caesar[1]}), Decoded: {caesar[2]}")

reversed_text = reverse_decode(text)
if "hello" in reversed_text.lower():
candidates.append(f"Detected: Reverse cipher, Decoded: {reversed_text}")

vowel_decoded = vowel_decode(text)
if "hello" in vowel_decoded.lower():
candidates.append(f"Detected: Vowel cipher, Decoded: {vowel_decoded}")

scrambled = word_unscramble(text)
if "hello" in scrambled.lower():
candidates.append(f"Detected: Word Scramble (guess), Decoded: {scrambled}")

if not candidates:
return "No known cipher detected with high confidence."
else:
return "\n".join(candidates)

encoded_text = input("Enter encoded text: ")


print("\n" + auto_decode(encoded_text))
OUTPUT

You might also like