Blockchain Technology Assignments
Blockchain Technology Assignments
Registration number:23RP00980
Here are three Python classes with methods:
class Student:
def __init__(self, name, age):
self.name = name
self.age = age
def display_info(self):
print(f"Name: {self.name}, Age: {self.age}")
def greet(self):
print(f"Hello, my name is {self.name}!")
class Car:
def __init__(self, make, model, year):
self.make = make
self.model = model
self.year = year
def display_info(self):
print(f"Car: {self.year} {self.make} {self.model}")
def start(self):
print(f"{self.make} {self.model} started.")
def stop(self):
print(f"{self.make} {self.model} stopped.")
class Circle:
def __init__(self, radius):
self.radius = radius
def area(self):
return 3.14 * self.radius ** 2
def perimeter(self):
return 2 * 3.14 * self.radius
def display_info(self):
print(f"Circle with radius {self.radius}:")
print(f"Area: {self.area()}")
print(f"Perimeter: {self.perimeter()}")
circle1 = Circle(5)
circle1.display_info()
OUTPUT
Here are three Python classes, Manipulate Class Variables vs Instance Variables:
class MyClass:
class_variable = 0 # Class variable
def manipulate_class_instance_variables(self):
MyClass.class_variable += 1
self.instance_variable += 1
class Dog:
total_dogs = 0 # Class variable
def display_info(self):
print(f"Name: {self.name}, Total Dogs: {Dog.total_dogs}")
class BankAccount:
interest_rate = 0.05 # Class variable
def add_interest(self):
self.balance += self.balance * self.interest_rate
@classmethod
def change_interest_rate(cls, new_rate):
cls.interest_rate = new_rate
dog1 = Dog("Buddy")
dog2 = Dog("Max")
dog1.display_info()
dog2.display_info()
account1 = BankAccount(1000)
account1.add_interest()
print("Balance with interest:", account1.balance)
BankAccount.change_interest_rate(0.06)
account2 = BankAccount(2000)
account2.add_interest()
print("Balance with new interest rate:", account2.balance)
OUTPUT
here are three Python classes, Manipulate Data Types and Variables
class DataManipulator:
def __init__(self):
self.number = 0
self.string = ""
def manipulate_data_types(self):
# Manipulating integer and string data types
self.number = 42
self.string = "Hello, world!"
def manipulate_variables(self):
# Manipulating variables
a=5
b = 10
print("Initial values: a =", a, ", b =", b)
# Swapping variables
a, b = b, a
print("After swapping: a =", a, ", b =", b)
class ListManipulator:
def __init__(self):
self.my_list = []
def manipulate_lists(self):
# Manipulating lists
self.my_list = [1, 2, 3, 4, 5]
# Appending to list
self.my_list.append(6)
print("List after appending:", self.my_list)
# List slicing
print("Slice of the list:", self.my_list[1:3])
list_manipulator = ListManipulator()
list_manipulator.manipulate_lists()
OUTPUT
def to_decimal(self):
return int(self.value, 2)
def display_info(self):
print(f"Binary number: {self.value}")
print(f"Decimal equivalent: {self.to_decimal()}")
class BinaryCalculator:
@staticmethod
def add(binary1, binary2):
decimal_sum = BinaryNumber(binary1).to_decimal() +
BinaryNumber(binary2).to_decimal()
return bin(decimal_sum)[2:]
@staticmethod
def subtract(binary1, binary2):
decimal_difference = BinaryNumber(binary1).to_decimal() -
BinaryNumber(binary2).to_decimal()
return bin(decimal_difference)[2:]
@staticmethod
def multiply(binary1, binary2):
decimal_product = BinaryNumber(binary1).to_decimal() *
BinaryNumber(binary2).to_decimal()
return bin(decimal_product)[2:]
@staticmethod
def divide(binary1, binary2):
decimal_quotient = BinaryNumber(binary1).to_decimal() //
BinaryNumber(binary2).to_decimal()
return bin(decimal_quotient)[2:]
class BinaryOperations:
@staticmethod
def bitwise_and(binary1, binary2):
decimal_result = BinaryNumber(binary1).to_decimal() &
BinaryNumber(binary2).to_decimal()
return bin(decimal_result)[2:]
@staticmethod
def bitwise_or(binary1, binary2):
decimal_result = BinaryNumber(binary1).to_decimal() |
BinaryNumber(binary2).to_decimal()
return bin(decimal_result)[2:]
@staticmethod
def bitwise_xor(binary1, binary2):
decimal_result = BinaryNumber(binary1).to_decimal() ^
BinaryNumber(binary2).to_decimal()
return bin(decimal_result)[2:]
binary_calc = BinaryCalculator()
print("Addition:", binary_calc.add('1010', '1101'))
print("Subtraction:", binary_calc.subtract('1010', '1101'))
print("Multiplication:", binary_calc.multiply('1010', '1101'))
print("Division:", binary_calc.divide('1010', '1101'))
binary_ops = BinaryOperations()
print("Bitwise AND:", binary_ops.bitwise_and('1010', '1101'))
print("Bitwise OR:", binary_ops.bitwise_or('1010', '1101'))
print("Bitwise XOR:", binary_ops.bitwise_xor('1010', '1101'))
OUTPUT
@staticmethod
def reverse_list(input_list):
return input_list[::-1]
@staticmethod
def sort_list(input_list):
return sorted(input_list)
@staticmethod
def merge_lists(list1, list2):
return list1 + list2
@staticmethod
def find_intersection(list1, list2):
return list(set(list1) & set(list2))
class ListStatistics:
@staticmethod
def get_sum(input_list):
return sum(input_list)
@staticmethod
def get_average(input_list):
return sum(input_list) / len(input_list) if len(input_list) > 0 else 0
@staticmethod
def get_max(input_list):
return max(input_list) if input_list else None
@staticmethod
def get_min(input_list):
return min(input_list) if input_list else None
class ListOperations:
@staticmethod
def multiply_by_scalar(input_list, scalar):
return [item * scalar for item in input_list]
@staticmethod
def filter_even_numbers(input_list):
return [item for item in input_list if item % 2 == 0]
@staticmethod
def find_index(input_list, item):
try:
return input_list.index(item)
except ValueError:
return -1
# Example usage
if __name__ == "__main__":
my_list = [1, 2, 3, 4, 5, 3, 2, 1]
# List manipulation
print("Original list:", my_list)
print("List with duplicates removed:", ListManipulator.remove_duplicates(my_list))
print("Reversed list:", ListManipulator.reverse_list(my_list))
print("Sorted list:", ListManipulator.sort_list(my_list))
print("Merged list:", ListManipulator.merge_lists([1, 2, 3], [4, 5, 6]))
print("Intersection of lists:", ListManipulator.find_intersection([1, 2, 3, 4], [3, 4, 5]))
# List statistics
print("Sum of list:", ListStatistics.get_sum(my_list))
print("Average of list:", ListStatistics.get_average(my_list))
print("Max of list:", ListStatistics.get_max(my_list))
print("Min of list:", ListStatistics.get_min(my_list))
# List operations
print("List multiplied by 3:", ListOperations.multiply_by_scalar(my_list, 3))
print("Even numbers in the list:", ListOperations.filter_even_numbers(my_list))
print("Index of 4 in the list:", ListOperations.find_index(my_list, 4))
OUTPUT
def display_series(self):
print("Number Series:")
for num in range(self.start, self.end + 1):
print(num, end=" ")
print()
class WordAnalyzer:
def __init__(self, word):
self.word = word
def analyze_word(self):
print("Analyzing word:", self.word)
vowels = 0
consonants = 0
for char in self.word:
if char.lower() in "aeiou":
vowels += 1
elif char.isalpha():
consonants += 1
print("Vowels:", vowels)
print("Consonants:", consonants)
class ShoppingList:
def __init__(self, items):
self.items = items
def display_list(self):
print("Shopping List:")
for index, item in enumerate(self.items, start=1):
print(f"{index}. {item}")
# Creating objects and using for loops
series = NumberSeries(1, 5)
series.display_series()
OUTPUT
here are three Python classes, Manipulate While Loops in Python
class NumberCounter:
def __init__(self, start, end):
self.start = start
self.end = end
def count(self):
current = self.start
while current <= self.end:
print(current)
current += 1
class FactorialCalculator:
def __init__(self, n):
self.n = n
def calculate_factorial(self):
result = 1
current = 1
while current <= self.n:
result *= current
current += 1
return result
class GuessingGame:
def __init__(self):
import random
self.secret_number = random.randint(1, 100)
def play_game(self):
guess = 0
attempts = 0
while guess != self.secret_number:
guess = int(input("Guess the number (1-100): "))
attempts += 1
if guess < self.secret_number:
print("Too low!")
elif guess > self.secret_number:
print("Too high!")
else:
print(f"Congratulations! You guessed it in {attempts} attempts.")
break
game = GuessingGame()
game.play_game()
OUTPUT
def reverse(self):
return self.string[::-1]
def is_palindrome(self):
return self.string == self.string[::-1]
def count_vowels(self):
vowels = "aeiouAEIOU"
count = sum(1 for char in self.string if char in vowels)
return count
def count_consonants(self):
consonants = "bcdfghjklmnpqrstvwxyzBCDFGHJKLMNPQRSTVWXYZ"
count = sum(1 for char in self.string if char in consonants)
return count
def capitalize_words(self):
return self.string.title()
class StringTransformer:
def __init__(self, string):
self.string = string
def remove_whitespace(self):
return "".join(self.string.split())
def to_uppercase(self):
return self.string.upper()
def to_lowercase(self):
return self.string.lower()
def swap_case(self):
return self.string.swapcase()
class StringAnalyzer:
def __init__(self, string):
self.string = string
def word_count(self):
return len(self.string.split())
def character_count(self):
return len(self.string)
def longest_word(self):
words = self.string.split()
return max(words, key=len)
def shortest_word(self):
words = self.string.split()
return min(words, key=len)
# Example usage
string1 = "Hello World!"
string2 = "A man, a plan"
string3 = "Blockchain is fun"
# StringManipulator
manipulator = StringManipulator(string1)
print("Reversed string:", manipulator.reverse())
print("Is palindrome:", manipulator.is_palindrome())
print("Number of vowels:", manipulator.count_vowels())
print("Number of consonants:", manipulator.count_consonants())
print("Capitalized words:", manipulator.capitalize_words())
# StringTransformer
transformer = StringTransformer(string2)
print("String without whitespace:", transformer.remove_whitespace())
print("Uppercase string:", transformer.to_uppercase())
print("Lowercase string:", transformer.to_lowercase())
print("String with swapped case:", transformer.swap_case())
print("String with replaced vowels:", transformer.replace_vowels("*"))
# StringAnalyzer
analyzer = StringAnalyzer(string3)
print("Word count:", analyzer.word_count())
print("Character count:", analyzer.character_count())
print("Longest word:", analyzer.longest_word())
print("Shortest word:", analyzer.shortest_word())
OUTPUT
here are three Python classes, writing a Simple hash Program using Python
class SimpleHash:
def __init__(self):
self.hash_table = {}
def display_table(self):
print("Hash Table:")
for key, value in self.hash_table.items():
print(f"Key: {key}, Value: {value}")
hash_program.add_item("apple", 10)
hash_program.add_item("banana", 20)
hash_program.add_item("cherry", 30)
hash_program.display_table()
OUTPUT
here are three Python classes, Manipulate Recursive Factorial Function
class MathOperations:
@staticmethod
def factorial(n):
if n == 0:
return 1
else:
return n * MathOperations.factorial(n - 1)
class MyClass:
def __init__(self, name):
self.name = name
def greet(self):
print("Hello,", self.name)
class AnotherClass:
def __init__(self, number):
self.number = number
def display_factorial(self):
fact = MathOperations.factorial(self.number)
print(f"Factorial of {self.number} is {fact}")
# Example usage
obj1 = MyClass("Alice")
obj1.greet()
obj2 = AnotherClass(5)
obj2.display_factorial ()
OUTPUT
@staticmethod
def selection_sort(arr):
n = len(arr)
for i in range(n):
min_index = i
for j in range(i + 1, n):
if arr[j] < arr[min_index]:
min_index = j
arr[i], arr[min_index] = arr[min_index], arr[i]
@staticmethod
def merge_sort(arr):
if len(arr) > 1:
mid = len(arr) // 2
left_half = arr[:mid]
right_half = arr[mid:]
SortFunctions.merge_sort(left_half)
SortFunctions.merge_sort(right_half)
i=j=k=0
# Example usage:
my_list = [12, 11, 13, 5, 6, 7]
SortFunctions.bubble_sort(my_list)
print("Bubble sorted array:", my_list)
OUTPUT
here are three Python classes, Write a Sorting Function
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def __str__(self):
return f"Name: {self.name}, Age: {self.age}"
class Car:
def __init__(self, make, model, year):
self.make = make
self.model = model
self.year = year
def __str__(self):
return f"Make: {self.make}, Model: {self.model}, Year: {self.year}"
class Book:
def __init__(self, title, author, year):
self.title = title
self.author = author
self.year = year
def __str__(self):
return f"Title: {self.title}, Author: {self.author}, Year: {self.year}"
Parameters:
objects (list): List of objects to be sorted.
key (str): Key to sort the objects by.
Returns:
list: Sorted list of objects.
"""
return sorted(objects, key=lambda x: getattr(x, key))
# Example usage
if __name__ == "__main__":
people = [Person("Alice", 30), Person("Bob", 25), Person("Charlie", 35)]
sorted_people = sort_objects(people, "age")
print("Sorted People:")
for person in sorted_people:
print(person)
OUTPUT
class SortingUtil:
@staticmethod
def insertion_sort(arr):
for i in range(1, len(arr)):
key = arr[i]
j=i-1
while j >= 0 and arr[j] > key:
arr[j + 1] = arr[j]
j -= 1
arr[j + 1] = key
class Array:
def __init__(self, data=None):
if data is None:
data = []
self.data = data
def display(self):
print(self.data)
class InsertionSort:
@staticmethod
def sort(array):
SortingUtil.insertion_sort(array.data)
# Example usage
if __name__ == "__main__":
arr = Array([12, 11, 13, 5, 6])
print("Array before sorting:")
arr.display()
InsertionSort.sort(arr)
print("Array after sorting:")
arr.display()
class Array:
def __init__(self, data=None):
if data is None:
data = []
self.data = data
def display(self):
print(self.data)
class InsertionSort:
def sort(array):
SortingUtil.insertion_sort(array.data)
if __name__ == "__main__":
arr = Array([12, 11, 13, 5, 6])
print("Array before sorting:")
arr.display()
InsertionSort.sort(arr)
print("Array after sorting:")
arr.display()
OUTPUT