Text Practice Mode
For Programmer - #1 (HARD)
created Dec 27th 2024, 10:14 by Vladik001
2
436 words
3 completed
0
Rating visible after 3 or more votes
00:00
# Importing libraries
import math
import os
import sys
import random
import re
import json
# Defining constants
PI = 3.141592653589793
EULER = 2.718281828459045
# Function definitions
def greet_user(name):
"""Prints a greeting for the user."""
print(f"Hello, {name}! Welcome to Python programming.")
def calculate_area_of_circle(radius):
"""Returns the area of a circle."""
return PI * radius ** 2
def is_prime(number):
"""Checks if a number is a prime."""
if number < 2:
return False
for i in range(2, int(math.sqrt(number)) + 1):
if number % i == 0:
return False
return True
# Using lambda functions
square = lambda x: x ** 2
cube = lambda x: x ** 3
# Working with lists, dictionaries, and sets
fruits = ["apple", "banana", "cherry", "date"]
prices = {"apple": 1.2, "banana": 0.8, "cherry": 2.5, "date": 3.0}
fruit_set = set(fruits)
# List comprehensions
even_numbers = [x for x in range(1, 21) if x % 2 == 0]
prime_numbers = [x for x in range(1, 21) if is_prime(x)]
# Dictionary comprehensions
squared_numbers = {x: x ** 2 for x in range(1, 11)}
cubed_numbers = {x: x ** 3 for x in range(1, 11)}
# Exception handling
try:
result = 10 / 0
except ZeroDivisionError as e:
print(f"Error: {e}")
finally:
print("Execution completed.")
# File operations
with open("example.txt", "w") as file:
file.write("This is a sample text file.\n")
file.write("It contains multiple lines of text.\n")
# Reading files
with open("example.txt", "r") as file:
content = file.readlines()
for line in content:
print(line.strip())
# JSON operations
data = {"name": "Alice", "age": 25, "city": "Wonderland"}
json_data = json.dumps(data)
parsed_data = json.loads(json_data)
# Regular expressions
pattern = r"[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}"
email = "[email protected]"
if re.match(pattern, email):
print(f"Valid email: {email}")
# Random numbers
random_number = random.randint(1, 100)
print(f"Random number: {random_number}")
# Classes and objects
class Animal:
def __init__(self, name, species):
self.name = name
self.species = species
def make_sound(self):
return "Some generic sound"
class Dog(Animal):
def __init__(self, name, breed):
super().__init__(name, "Dog")
self.breed = breed
def make_sound(self):
return "Woof!"
dog = Dog("Buddy", "Golden Retriever")
print(dog.make_sound())
# Decorators
def my_decorator(func):
def wrapper(*args, **kwargs):
print("Before the function call")
result = func(*args, **kwargs)
print("After the function call")
return result
return wrapper
@my_decorator
def say_hello():
print("Hello!")
say_hello()
# Context managers
class MyContextManager:
def __enter__(self):
print("Entering context")
return self
def __exit__(self, exc_type, exc_value, traceback):
print("Exiting context")
with MyContextManager() as cm:
print("Inside context")
# Iterators and generators
class Counter:
def __init__(self, start, end):
self.current = start
self.end = end
def __iter__(self):
return self
def __next__(self):
if self.current > self.end:
raise StopIteration
self.current += 1
return self.current - 1
counter = Counter(1, 10)
for num in counter:
print(num)
def my_generator():
for i in range(5):
yield i * 2
gen = my_generator()
for value in gen:
print(value)
import math
import os
import sys
import random
import re
import json
# Defining constants
PI = 3.141592653589793
EULER = 2.718281828459045
# Function definitions
def greet_user(name):
"""Prints a greeting for the user."""
print(f"Hello, {name}! Welcome to Python programming.")
def calculate_area_of_circle(radius):
"""Returns the area of a circle."""
return PI * radius ** 2
def is_prime(number):
"""Checks if a number is a prime."""
if number < 2:
return False
for i in range(2, int(math.sqrt(number)) + 1):
if number % i == 0:
return False
return True
# Using lambda functions
square = lambda x: x ** 2
cube = lambda x: x ** 3
# Working with lists, dictionaries, and sets
fruits = ["apple", "banana", "cherry", "date"]
prices = {"apple": 1.2, "banana": 0.8, "cherry": 2.5, "date": 3.0}
fruit_set = set(fruits)
# List comprehensions
even_numbers = [x for x in range(1, 21) if x % 2 == 0]
prime_numbers = [x for x in range(1, 21) if is_prime(x)]
# Dictionary comprehensions
squared_numbers = {x: x ** 2 for x in range(1, 11)}
cubed_numbers = {x: x ** 3 for x in range(1, 11)}
# Exception handling
try:
result = 10 / 0
except ZeroDivisionError as e:
print(f"Error: {e}")
finally:
print("Execution completed.")
# File operations
with open("example.txt", "w") as file:
file.write("This is a sample text file.\n")
file.write("It contains multiple lines of text.\n")
# Reading files
with open("example.txt", "r") as file:
content = file.readlines()
for line in content:
print(line.strip())
# JSON operations
data = {"name": "Alice", "age": 25, "city": "Wonderland"}
json_data = json.dumps(data)
parsed_data = json.loads(json_data)
# Regular expressions
pattern = r"[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}"
email = "[email protected]"
if re.match(pattern, email):
print(f"Valid email: {email}")
# Random numbers
random_number = random.randint(1, 100)
print(f"Random number: {random_number}")
# Classes and objects
class Animal:
def __init__(self, name, species):
self.name = name
self.species = species
def make_sound(self):
return "Some generic sound"
class Dog(Animal):
def __init__(self, name, breed):
super().__init__(name, "Dog")
self.breed = breed
def make_sound(self):
return "Woof!"
dog = Dog("Buddy", "Golden Retriever")
print(dog.make_sound())
# Decorators
def my_decorator(func):
def wrapper(*args, **kwargs):
print("Before the function call")
result = func(*args, **kwargs)
print("After the function call")
return result
return wrapper
@my_decorator
def say_hello():
print("Hello!")
say_hello()
# Context managers
class MyContextManager:
def __enter__(self):
print("Entering context")
return self
def __exit__(self, exc_type, exc_value, traceback):
print("Exiting context")
with MyContextManager() as cm:
print("Inside context")
# Iterators and generators
class Counter:
def __init__(self, start, end):
self.current = start
self.end = end
def __iter__(self):
return self
def __next__(self):
if self.current > self.end:
raise StopIteration
self.current += 1
return self.current - 1
counter = Counter(1, 10)
for num in counter:
print(num)
def my_generator():
for i in range(5):
yield i * 2
gen = my_generator()
for value in gen:
print(value)
saving score / loading statistics ...