0% found this document useful (0 votes)
21 views

Blockchain Technology Assignments

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)
21 views

Blockchain Technology Assignments

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/ 33

DEPARTMENT: INFORMATION AND COMMUNICATION TECHNOLOGY

Program: Bachelor of Technology in Information Technology

Academic year: 2023/2024

Blockchain Technology Assignment about Manipulating Classes using Python

Name: Isaie UWIZEYIMANA

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()}")

student1 = Student("Isaie", 30)


student1.display_info()
student1.greet()

car1 = Car("Toyota", "Camry", 2024)


car1.display_info()
car1.start()
car1.stop()

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 __init__(self, instance_variable):


self.instance_variable = instance_variable # Instance variable

def manipulate_class_instance_variables(self):
MyClass.class_variable += 1
self.instance_variable += 1

class Dog:
total_dogs = 0 # Class variable

def __init__(self, name):


self.name = name # Instance variable
Dog.total_dogs += 1

def display_info(self):
print(f"Name: {self.name}, Total Dogs: {Dog.total_dogs}")

class BankAccount:
interest_rate = 0.05 # Class variable

def __init__(self, balance):


self.balance = balance # Instance 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

# Manipulating class and instance variables


obj1 = MyClass(10)
obj2 = MyClass(20)
obj1.manipulate_class_instance_variables()
obj2.manipulate_class_instance_variables()
print("Class variable in MyClass:", MyClass.class_variable)
print("Instance variable in obj1:", obj1.instance_variable)
print("Instance variable in obj2:", obj2.instance_variable)

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!"

# Concatenating string and converting number to string


concatenated = self.string + " The answer is " + str(self.number)
print(concatenated)

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)

# Removing from list


self.my_list.remove(3)
print("List after removing element 3:", self.my_list)

# Accessing list elements


print("First element of the list:", self.my_list[0])

# List slicing
print("Slice of the list:", self.my_list[1:3])

# Creating objects and calling methods


data_manipulator = DataManipulator()
data_manipulator.manipulate_data_types()
data_manipulator.manipulate_variables()

list_manipulator = ListManipulator()
list_manipulator.manipulate_lists()

OUTPUT

here are three Python classes, Manipulate Binary Numbers


class BinaryNumber:
def __init__(self, value):
self.value = value

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:]

# Creating objects and performing binary operations


binary_num = BinaryNumber('1010')
binary_num.display_info()

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

here are three Python classes, Manipulate Python Lists


class ListManipulator:
@staticmethod
def remove_duplicates(input_list):
return list(set(input_list))

@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

here are three Python classes, Manipulate for Loops in Python


class NumberSeries:
def __init__(self, start, end):
self.start = start
self.end = end

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()

analyzer = WordAnalyzer("Hello World")


analyzer.analyze_word()

shopping_list = ShoppingList(["Apples", "Bananas", "Milk", "Bread"])


shopping_list.display_list()

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

# Example usage of classes with while loops


counter = NumberCounter(1, 5)
counter.count()
factorial_calculator = FactorialCalculator(5)
print("Factorial of 5:", factorial_calculator.calculate_factorial())

game = GuessingGame()
game.play_game()

OUTPUT

here are three Python classes, Fun with Strings manipulations


class StringManipulator:
def __init__(self, string):
self.string = string

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()

def replace_vowels(self, replacement):


vowels = "aeiouAEIOU"
return "".join(replacement if char in vowels else char for char in self.string)

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 add_item(self, key, value):


hashed_key = hash(key)
self.hash_table[hashed_key] = value

def get_item(self, key):


hashed_key = hash(key)
return self.hash_table.get(hashed_key)

def display_table(self):
print("Hash Table:")
for key, value in self.hash_table.items():
print(f"Key: {key}, Value: {value}")

# Creating and using the hash program


hash_program = SimpleHash()

hash_program.add_item("apple", 10)
hash_program.add_item("banana", 20)
hash_program.add_item("cherry", 30)

hash_program.display_table()

print("Value for 'apple':", hash_program.get_item("apple"))

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

here are three Python classes, Manipulate Sort Functions


class SortFunctions:
@staticmethod
def bubble_sort(arr):
n = len(arr)
for i in range(n - 1):
for j in range(0, n - i - 1):
if arr[j] > arr[j + 1]:
arr[j], arr[j + 1] = arr[j + 1], arr[j]

@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

while i < len(left_half) and j < len(right_half):


if left_half[i] < right_half[j]:
arr[k] = left_half[i]
i += 1
else:
arr[k] = right_half[j]
j += 1
k += 1

while i < len(left_half):


arr[k] = left_half[i]
i += 1
k += 1

while j < len(right_half):


arr[k] = right_half[j]
j += 1
k += 1

# Example usage:
my_list = [12, 11, 13, 5, 6, 7]
SortFunctions.bubble_sort(my_list)
print("Bubble sorted array:", my_list)

my_list = [12, 11, 13, 5, 6, 7]


SortFunctions.selection_sort(my_list)
print("Selection sorted array:", my_list)

my_list = [12, 11, 13, 5, 6, 7]


SortFunctions.merge_sort(my_list)
print("Merge 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}"

def sort_objects(objects, key):


"""
Function to sort a list of objects by a specified key.

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)

cars = [Car("Toyota", "Camry", 2015), Car("Honda", "Accord", 2018), Car("Ford",


"Focus", 2016)]
sorted_cars = sort_objects(cars, "year")
print("\nSorted Cars:")
for car in sorted_cars:
print(car)

books = [Book("Python Crash Course", "Eric Matthes", 2015), Book("Clean Code",


"Robert C. Martin", 2008),
Book("Design Patterns", "Erich Gamma", 1994)]
sorted_books = sort_objects(books, "year")
print("\nSorted Books:")
for book in sorted_books:
print(book)

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 insert(self, value):


self.data.append(value)

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()

here are three Python classes, Insertion Sort in Python


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 insert(self, value):


self.data.append(value)

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

You might also like