Skip to content

Commit

Permalink
Merge pull request #99 from icelal-kskn/master
Browse files Browse the repository at this point in the history
Create types_ikram_celal_keskin.py
  • Loading branch information
canbula authored Oct 19, 2024
2 parents 1dc7239 + 9e1b528 commit fd3aa6e
Show file tree
Hide file tree
Showing 4 changed files with 230 additions and 0 deletions.
5 changes: 5 additions & 0 deletions Week02/types_ikram_celal_keskin.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
my_int=19
my_float=0.6
my_bool=True
my_complex=2000+2j

50 changes: 50 additions & 0 deletions Week03/sequences_ikram_celal_keskin.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@


def remove_duplicates(seq:list) -> list:
'''
This function removes duplicates from a list
Args:
seq (list): Input list with potential duplicates
Returns:
list (list): List with duplicates removed
'''
return list(set(seq))

def list_counts(seq:list) -> dict:
'''
This function counts the occurences of each element in a list
Args:
seq (list): Input list to count occurences of each element
Returns:
dict (dict): Dictionary with elements as keys and occurences as values
'''
count={}

for i in seq:
count[i]=seq.count(i)

return count
#{i: seq.count(i) for i in seq}

def reverse_dict(d:dict) -> dict:
'''
This function reverses the keys and values of a dictionary
Args:
d (dict): Input dictionary to reverse keys and values
Returns:
dict (dict): Dictionary with keys and values reversed
'''

reversed={}

for key, value in d.items():
reversed[value] = key

return reversed
#return {v: k for k, v in d.items()}
28 changes: 28 additions & 0 deletions Week04/arrays_ikram_celal_keskin.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
import numpy as np


def replace_center_with_minus_one(d:int, n:int, m:int)-> np.ndarray:
""" This function creates a n x n array of random integers with d digits.
Then it replaces the centr m x m size of the array with -1.
Args:
d (int): number of digits of the random integers
n (int): size of the array
m (int): size of the center to be want to replaced with -1
Returns:
np.ndarray: n x n array with the m x m center replaced with -1
"""
if n < 0 or m > n or d <= 0 or m < 0 or m > n:
raise ValueError("Something went wrong")

numpy_nxn_array = np.random.randint(10*(d-1), 10**d , (n, n))

shape_x , shape_y = numpy_nxn_array.shape
operational_x = ( shape_x - m ) // 2
operational_y = ( shape_y - m ) // 2

numpy_nxn_array[operational_x:operational_x+m,
operational_y:operational_y+m] = -1

return numpy_nxn_array
147 changes: 147 additions & 0 deletions Week05/bra_ikram_celal_keskin.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,147 @@
from flask import Flask, request, jsonify
import numpy as np

app = Flask(__name__)


class BinaryRepresentation:
"""
This class converts a given number into its binary representation.
Attributes:
number (float): The number to convert to binary. Must be a valid int or float.
Raises:
TypeError: If the input is not a number (int or float).
ValueError: If the input is NaN or infinite.
"""

def __init__(self, _number:float):
if isinstance(_number, bool):
raise TypeError("Invalid input type, expected int or float")
if not isinstance(_number, (int, float)):
raise TypeError("Invalid input type, expected int, float, or bool")
if np.isnan(_number) or np.isinf(_number):
raise ValueError("Input cannot be NaN or infinite")

try:
self.number = float(_number)
except Exception as e:
raise TypeError("Input {} cannot be converted to a float".format(e.args[0]))

def __str__(self):
"""
Returns the binary representation of the number as a string.
Returns:
str: Binary representation of the number.
"""

return self.__get_binary_representation()

def __get_binary_representation(self):
"""
Generates the binary representation of the number, including
both integer and decimal parts.
Returns:
str: Complete binary representation.
"""

sign= False

if self.number < 0:
sign = True
self.number = -self.number

integer_part,decimal_part = f"{self.number:.20f}".split(".")

merged_brep= f"{self.__integer2binary(integer_part)}.{self.__decimal2binary(decimal_part)}"

merged_brep = "-" + merged_brep if sign else merged_brep
return merged_brep

def __decimal2binary(self, number:str):
"""
Converts the decimal part of the number to its binary representation.
Args:
number (str): The decimal part of the number as a string.
Returns:
str: Binary representation of the decimal part.
"""

number=float(f"0.{number.split("0")[0]}")

if number == 0:
return ''

binary = ''
while number > 0 and len(binary) < 10:

number *= 2
if number >= 1:
binary += '1'
number -= 1
else:
binary += '0'

return binary

def __integer2binary(self, number:str):
"""
Converts the integer part of the number to its binary representation.
Args:
number (str): The integer part of the number as a string.
Returns:
str: Binary representation of the integer part.
"""

result = ""
number = int(number)

if number == 0:
return "0"

while number != 0:
remainder = number % 2
result += str(remainder)
number //= 2

return result[::-1]



@app.route('/', methods=['GET'])
def binary_representation_api():
# Get the 'number' parameter from the query string
number = request.args.get('number')
# Check if 'number' parameter is missing
if number is None:
return jsonify({"error": "Please send a GET request to /?number=<number>"}), 400

try:
number = float(number)
except ValueError:
return jsonify({"error": "Please send a GET request to /?number=<number> with a valid number"}), 400
except TypeError:
return jsonify({"error": "Invalid input type, expected a valid number"}), 400

binary_representation = BinaryRepresentation(number)

binary_string = str(binary_representation)
return jsonify({"binary_representation": binary_string}), 200

@app.errorhandler(400)
def bad_request(e):
if isinstance(e, TypeError):
return jsonify({"error": "Invalid input type, expected a valid number"}), 400
else:
return jsonify({"error": str(e)}), 400


if __name__== '__main__':
app.run(debug=True)

0 comments on commit fd3aa6e

Please sign in to comment.