diff --git a/21 BlackJack.py b/21 BlackJack.py index dc93cf4..0c4a9e5 100644 --- a/21 BlackJack.py +++ b/21 BlackJack.py @@ -89,4 +89,4 @@ def calculate_hand(hand): # Dealer hits until their total is 17 or higher while total < 17: - dealer + raise NotImplementedError() diff --git a/27.03 Library Item Inheritance.py b/27.03 Library Item Inheritance.py index 492e103..09612ef 100644 --- a/27.03 Library Item Inheritance.py +++ b/27.03 Library Item Inheritance.py @@ -1,69 +1,84 @@ import datetime import random + class LibraryItem: - def __init__(self, t,a,i): + def __init__(self, t: str, a: str, i: str | int): self.__Title = t self.__AuthorArtist = a self.__ItemID = i self.__OnLoan = False self.__DueDate = datetime.date.today() - def GetTitle(self): + def GetTitle(self) -> str: return (self.__Title) - def GetAuthorArtist(self): + + def GetAuthorArtist(self) -> str: return (self.__AuthorArtist) - def GetItemID(self): + + def GetItemID(self) -> str | int: return (self.__ItemID) -#lend book - - def ShowDetail(self): + #lend book + + def ShowDetail(self) -> None: print("ID: ", self.GetItemID()) print("Title: ", self.GetTitle()) print("Author: ", self.__AuthorArtist) + class Book(LibraryItem): def __init__(self, t, a, i): LibraryItem.__init__(self, t, a, i) self.__IsRequested = False self.__RequestedBy = 0 + def ShowDetail(self): LibraryItem.ShowDetail(self) #print("is requested: ", self.__IsRequested) + class CD(LibraryItem): def __init__(self, t, a, i): LibraryItem.__init__(self, t, a, i) self.__Genre = "" + def GetGenre(self): return (self.__Genre) + def SetGenre(self, g): self.__Genre = g + + class Borrower: def __init__(self, n, e): self.__BorrowerName = n self.__Email = e - self.__BorrowerID = random.randint(100,200) + self.__BorrowerID = random.randint(100, 200) self.__ItemsOnLoan = 0 def GetBorrowerName(self): return self.__BorrowerName + def GetEmail(self): return self.__Email + def GetBorrowerID(self): return self.__BorrowerID + def GetItemsOnLoan(self): return self.__ItemsOnLoan + def UpdateItemsOnLoan(self): self.__ItemsOnLoan += 1 - + def PrintDetail(self): print("ID: ", self.GetBorrowerID()) print("Name: ", self.GetBorrowerName()) print("Email: ", self.GetEmail()) print(f"There are {self.__ItemsOnLoan} items borrowed.") - + + ##Title=input("Enter book title: ") ##Author = input("Enter book author: ") ##ItemID = random.randint(10000, 50000) diff --git a/27.05 Library Item Borrower.py b/27.05 Library Item Borrower.py index 492e103..4b69a77 100644 --- a/27.05 Library Item Borrower.py +++ b/27.05 Library Item Borrower.py @@ -2,23 +2,23 @@ import random class LibraryItem: - def __init__(self, t,a,i): + def __init__(self, t:str,a:str,i:str|int): self.__Title = t self.__AuthorArtist = a self.__ItemID = i self.__OnLoan = False self.__DueDate = datetime.date.today() - def GetTitle(self): + def GetTitle(self) -> str: return (self.__Title) - def GetAuthorArtist(self): + def GetAuthorArtist(self) -> str: return (self.__AuthorArtist) - def GetItemID(self): + def GetItemID(self) -> str | int: return (self.__ItemID) #lend book - def ShowDetail(self): + def ShowDetail(self) -> None: print("ID: ", self.GetItemID()) print("Title: ", self.GetTitle()) print("Author: ", self.__AuthorArtist) diff --git a/27.06 Library Items.py b/27.06 Library Items.py index a1d16b6..40ba65e 100644 --- a/27.06 Library Items.py +++ b/27.06 Library Items.py @@ -19,7 +19,7 @@ def GetItemID(self): def Borrow(self, bid): self.__BorrowerID = bid self.__OnLoan = True - self.__DueDate = datetime.date.today()+7 + self.__DueDate = datetime.date.today() + datetime.timedelta(weeks=1) def Return(self): self.__BorrowerID = 0 self.__OnLoan = False @@ -76,7 +76,7 @@ def PrintDetail(self): print(f"There are {self.__ItemsOnLoan} items borrowed.") def Menu(): - pass + raise NotImplementedError() ##Title=input("Enter book title: ") ##Author = input("Enter book author: ") diff --git a/27.07 Library with Utility.py b/27.07 Library with Utility.py index d6d67c9..43c45b4 100644 --- a/27.07 Library with Utility.py +++ b/27.07 Library with Utility.py @@ -19,7 +19,7 @@ def GetItemID(self): def Borrow(self, bid): self.__BorrowerID = bid self.__OnLoan = True - self.__DueDate = datetime.date.today()+7 + self.__DueDate = datetime.date.today()+datetime.timedelta(weeks=1) def Return(self): self.__BorrowerID = 0 self.__OnLoan = False @@ -77,7 +77,7 @@ def PrintDetail(self): def Menu(): choice = 't' - while choice not in (0,1,2,3,4,5,6,7,8,9): + while choice not in range(0,10): print("1 – Add a new borrower") print("2 – Add a new book") print("3 – Add a new CD") @@ -107,20 +107,8 @@ def main(): name = input("Enter name of borrower ") email = input("Enter email of borrower ") Borrowers.append(Borrower(name,email)) - elif choice ==2: - pass - elif choice==3: - pass - elif choice==4: - pass - elif choice==5: - pass - elif choice==6: - pass - elif choice==7: - pass - elif choice==8: - pass + elif choice in range(2, 9): + print("Not implemented yet") elif choice==9: print(Borrowers[0].GetBorrowerName()) choice = Menu() diff --git a/9 - 17-9 - car record using classes.py b/9 - 17-9 - car record using classes.py index cb6abc5..71b5217 100644 --- a/9 - 17-9 - car record using classes.py +++ b/9 - 17-9 - car record using classes.py @@ -1,5 +1,6 @@ import pickle + class CarRecord: def __init__(self): self.VehicleID = "" @@ -8,11 +9,12 @@ def __init__(self): self.EngineSize = 0 self.PurchaseSize = 0.00 -Car = [None]*10 # Create an empty array of 10 objects called Car + +Car = [CarRecord()] * 10 # Create an empty array of 10 objects called Car for i in range(10): - ThisCar = CarRecord() # Create an instance of class CarRecord named ThisCar - Car[i] = ThisCar # Assign reference of this Car object to array location + ThisCar = CarRecord() # Create an instance of class CarRecord named ThisCar + Car[i] = ThisCar # Assign reference of this Car object to array location Car[1].EngineSize = 2500 Car[5].EngineSize = 3000 @@ -36,17 +38,17 @@ def __init__(self): Car[1].EngineSize = 3500 Car[5].EngineSize = 8000 -Car2 = [None] +Car2 = [CarRecord()] * 10 #for i in range(10): - #ThisCar = CarRecord() - #Car2[i] = ThisCar +#ThisCar = CarRecord() +#Car2[i] = ThisCar CarFile = open('Cars.DAT', 'rb') while True: try: Car2.append(pickle.load(CarFile)) - except (EOFError): + except EOFError: break CarFile.close() @@ -55,5 +57,6 @@ def __init__(self): for i in range(10): print(Car2[i].EngineSize) print("") + #print(Car[1].EngineSize) #print(Car[5].EngineSize) diff --git a/A2 Modular Search and Sort.py b/A2 Modular Search and Sort.py index b753577..c1e90c0 100644 --- a/A2 Modular Search and Sort.py +++ b/A2 Modular Search and Sort.py @@ -1,92 +1,77 @@ import random + SIZE = 7 -data = [random.randint(1,20) for x in range (SIZE)] +data = [random.randint(1, 20) for x in range(SIZE)] + + #print(data) -def LinearSearch(data): +def LinearSearch(data: list) -> None: key = int(input('Enter value to search')) found = False - for x in range (SIZE): + for x in range(SIZE): if key == data[x]: print("found at location: ", x) found = True - if found==False: + if found == False: print('value not found') + def BubbleSort(data): - temp = 0 - n = 30 -1 - for i in range (SIZE): + n = 30 - 1 + for i in range(SIZE): for j in range(n): - if data[j]>data[j+1]: + if data[j] > data[j + 1]: temp = data[j] - data[j] = data [j+1] - data [j+1] = temp - n = n -1 + data[j] = data[j + 1] + data[j + 1] = temp + n = n - 1 + def InsertionSort(data): - ItemToBeInserted = 0 - CurrentItem = 0 - index = 0 - for index in range(len(data)): ItemToBeInserted = data[index] - CurrentItem = index -1 - while (data[CurrentItem]>ItemToBeInserted and - CurrentItem>-1): - data[CurrentItem+1]=data[CurrentItem] - CurrentItem-=1 - data[CurrentItem+1] = ItemToBeInserted + CurrentItem = index - 1 + while (data[CurrentItem] > ItemToBeInserted and + CurrentItem > -1): + data[CurrentItem + 1] = data[CurrentItem] + CurrentItem -= 1 + data[CurrentItem + 1] = ItemToBeInserted #print(data) -def BinarySearch(data): + +def BinarySearch(data:list) -> None: lowerBound = 0 - upperBound = len(data)-1 - + upperBound = len(data) - 1 + mid = -1 + key = int(input("Enter value to search: ")) found = False - searchFailed = False - while not searchFailed and not found: + + while (not found) and lowerBound <= upperBound: mid = lowerBound + (upperBound - lowerBound) // 2 - - if data[mid]==key: + + if data[mid] == key: #print('found at location : ', mid) found = True - elif data[mid]>key: - upperBound = mid - 1 + elif data[mid] > key: + upperBound = mid - 1 else: - lowerBound = mid + 1 - if lowerBound > upperBound: - print('search failed') - searchFailed = True - - if found: + lowerBound = mid + 1 + + if found and mid != -1: print(mid) else: print('value does not exist in the list') + #BubbleSort(data) InsertionSort(data) print(data) BinarySearch(data) - - - - - - - - - - - - - - - #LinearSearch(data) BubbleSort(data) print(data) diff --git a/LinearSearch.py b/LinearSearch.py index b14ab09..6b837f8 100644 --- a/LinearSearch.py +++ b/LinearSearch.py @@ -1,13 +1,15 @@ import random -data = [random.randint(1,20) for x in range (30)] +SIZE = 30 + +data = [random.randint(1,20) for x in range (SIZE)] #print(data) def LinearSearch(data): key = int(input('Enter value to search')) found = False - for x in range (30): + for x in range (SIZE): if key == data[x]: print("found at location: ", x) found = True @@ -16,9 +18,8 @@ def LinearSearch(data): print('value not found') def BubbleSort(data): - temp = 0 - n = 30 -1 - for i in range (30): + n = SIZE - 1 + for i in range (SIZE): for j in range(n): if data[j]>data[j+1]: temp = data[j] @@ -27,10 +28,6 @@ def BubbleSort(data): n = n -1 def InsertionSort(data): - ItemToBeInserted = 0 - CurrentItem = 0 - index = 0 - for index in range(len(data)): ItemToBeInserted = data[index] CurrentItem = index -1 @@ -43,6 +40,7 @@ def InsertionSort(data): def BinarySearch(data): lowerBound = 0 upperBound = len(data)-1 + mid = -1 key = int(input("Enter value to search: ")) found = False diff --git a/LinkedList.py b/LinkedList.py index 593c317..e42f2be 100644 --- a/LinkedList.py +++ b/LinkedList.py @@ -1,73 +1,77 @@ +import dataclasses + SIZE = 12 + +@dataclasses.dataclass class Node: - data = '' + data = None nextP = 0 -myList = [Node() for x in range (SIZE)] +myList = [Node() for x in range(SIZE)] for x in range(SIZE): - myList[x].nextP=x+1 - myList[11].nextP=-1 + myList[x].nextP = x + 1 + myList[11].nextP = -1 freeListPointer = 0 startPointer = -1 - for x in range(SIZE): print(self.thisList[x].data, end=' ') print(self.thisList[x].nextP) -if self.__freeListPointer!= -1: +if self.__freeListPointer != -1: newNodePtr = self.__freeListPointer self.__thisList[newNodePtr] = s self.__freeListPointer = self.__next[freeListPointer] #find insertion point - + def printAll(self): thisPtr = startPointer while self.__next != -1: print(self.__thisList[thisPtr]) - thisPtr+=1 + thisPtr += 1 + def insert(self, s): - if nextFree == 0: - print('List is full') - else: - Node[nextFree].Data = s - if start == 0: + if nextFree == 0: + print('List is full') + else: + Node[nextFree].Data = s + if start == 0: + start = nextFree + temp = Node[nextFree].link + Node[nextFree].link = 0 + nextFree = Temp + else: + #traverse the list - starting at start to find + # the position at which to insert the new item + Temp = Node[nextFree].link + if s < Node[start].data: + #new item will become the start of the list + nodeNext[free].link = start start = nextFree - temp = Node[nextFree].link - Node[nextFree].link =0 - nextFree = Temp + nextFree.Temp else: - #traverse the list - starting at start to find - # the position at which to insert the new item - Temp = Node[nextFree].link - if s < Node[start].data: - #new item will become the start of the list - nodeNext[free].link = start - start = nextFree - nextFree.Temp - else: - #the new item is not at the start of the list - previous = 0 - current = start - found = False - while found == False and current !=0: - if s <= Node[current].data: - Node[previous].link = nextFree - Node[nextFree].link = current - found = True - else: - nextFree = Temp - #move to the next node - previous = current - current = Node[current].link - if current==0: + #the new item is not at the start of the list + previous = 0 + current = start + found = False + while found == False and current != 0: + if s <= Node[current].data: Node[previous].link = nextFree - Node[nextFree].link = 0 + Node[nextFree].link = current + found = True + else: nextFree = Temp + #move to the next node + previous = current + current = Node[current].link + if current == 0: + Node[previous].link = nextFree + Node[nextFree].link = 0 + nextFree = Temp myList = linkedList() diff --git a/PassByVal.py b/PassByVal.py index 31f943b..5929899 100644 --- a/PassByVal.py +++ b/PassByVal.py @@ -5,6 +5,7 @@ def main(): print(m) #10 check(m) print(m) #10 + assert m == 10 def check(n): n+=10 diff --git a/Recursion Binary Conversion.py b/Recursion Binary Conversion.py index 7939293..ad56955 100644 --- a/Recursion Binary Conversion.py +++ b/Recursion Binary Conversion.py @@ -1,9 +1,10 @@ def X(n): - if n==0 or n==1: - print(n,end='') + if n == 0 or n == 1: + print(n, end='') else: - X(n//2) + X(n // 2) print(n % 2, end='') + if __name__ == "__main__": X(36) diff --git a/Recursion/BinarySearchRecursive.py b/Recursion/BinarySearchRecursive.py index 1e7eefd..65c061a 100644 --- a/Recursion/BinarySearchRecursive.py +++ b/Recursion/BinarySearchRecursive.py @@ -7,7 +7,7 @@ def BinarySearch(item, lBound, uBound, myList): if uBound < lBound: return -1 #item not in the list - index = (uBound + lBound) // 2 + index = uBound + (lBound - uBound) // 2 ThisItem = myList[index] if item == ThisItem: #base case 2 item found diff --git a/Recursion/BinaryToDenary Recursive.py b/Recursion/BinaryToDenary Recursive.py index 9fb5915..8e73673 100644 --- a/Recursion/BinaryToDenary Recursive.py +++ b/Recursion/BinaryToDenary Recursive.py @@ -1,16 +1,18 @@ -def DenToBin(n): #recursive - if n==0 or n==1: #base case - print(n,end='') - else: #general case - DenToBin(n//2) +def DenToBin(n): # recursive + if n == 0 or n == 1: # base case + print(n, end='') + else: # general case + DenToBin(n // 2) print(n % 2, end='') -def DenToBinary(n): #iterative solution + +def DenToBinary(n): # iterative solution s = '' - while n !=0: - s=str(n%2)+s - n//=2 + while n != 0: + s = str(n % 2) + s + n //= 2 print(s) + if __name__ == "__main__": DenToBin(12) diff --git a/Recursion/BubbleSortRecursive (2).py b/Recursion/BubbleSortRecursive (2).py index ba78580..8a6af04 100644 --- a/Recursion/BubbleSortRecursive (2).py +++ b/Recursion/BubbleSortRecursive (2).py @@ -27,28 +27,28 @@ print("sorted") print(MyList) - def bubbleSortRecursive(self, n=None): - if n is None: - n = self.length - count = 0 - - # Base case - if n == 1: - return - # One pass of bubble sort. After - # this pass, the largest element - # is moved (or bubbled) to end. - for i in range(n - 1): - if self.array[i] > self.array[i + 1]: - self.array[i], self.array[i + - 1] = self.array[i + 1], self.array[i] - count = count + 1 - - # Check if any recursion happens or not - # If any recursion is not happen then return - if (count==0): - return - - # Largest element is fixed, - # recur for remaining array - self.bubbleSortRecursive(n - 1) +def bubbleSortRecursive(self:list, n=None): + if n is None: + n = len(self) + count = 0 + + # Base case + if n == 1: + return + # One pass of bubble sort. After + # this pass, the largest element + # is moved (or bubbled) to end. + for i in range(n - 1): + if self.array[i] > self.array[i + 1]: + self.array[i], self.array[i + + 1] = self.array[i + 1], self.array[i] + count = count + 1 + + # Check if any recursion happens or not + # If any recursion is not happen then return + if (count==0): + return + + # Largest element is fixed, + # recur for remaining array + self.bubbleSortRecursive(n - 1) diff --git a/Recursion/BubbleSortRecursive.py b/Recursion/BubbleSortRecursive.py index 21bbdb2..913f3c1 100644 --- a/Recursion/BubbleSortRecursive.py +++ b/Recursion/BubbleSortRecursive.py @@ -1,4 +1,7 @@ import random + +from Recursion.BinarySearchRecursive import myList + MaxIndex = 12 MyList = [random.randint(1,100) for x in range(MaxIndex)] @@ -9,7 +12,7 @@ -def bubbleSortRecursive(myList, n): +def bubbleSortRecursive(myList:list, n:int= len(myList)): ## if n is None: ## n = self.length swapped = False diff --git a/Recursion/Factorial.py b/Recursion/Factorial.py index 3b8a2ce..3ecfa93 100644 --- a/Recursion/Factorial.py +++ b/Recursion/Factorial.py @@ -1,11 +1,12 @@ def main(): print(Factorial(100)) -def Factorial(n): - if n==1 : - return n + +def Factorial(n:int): + if n == 0: + return 1 else: - return n*Factorial(n-1) + return n * Factorial(n - 1) main() diff --git a/Recursion/Fibonacci.py b/Recursion/Fibonacci.py index fddb17c..dc8fb77 100644 --- a/Recursion/Fibonacci.py +++ b/Recursion/Fibonacci.py @@ -1,11 +1,12 @@ def main(): print(Fibonacci(5)) -def Fibonacci(n): - if n==1 : - return n + +def Fibonacci(n: int): + if n == 0: + return 0 else: - return n+Fibonacci(n-1) + return n + Fibonacci(n - 1) main() diff --git a/Recursion/GCD.py b/Recursion/GCD.py index a81cde3..3b78943 100644 --- a/Recursion/GCD.py +++ b/Recursion/GCD.py @@ -1,17 +1,21 @@ def main(): - print(HCF(75,30)) - print(GCD(75,30)) + print(HCF(75, 30)) + print(GCD(75, 30)) -def HCF(n1,n2): - if n2!=0 : - return HCF(n2,n1%n2) + +def HCF(n1: int, n2: int): + if n2 != 0: + return HCF(n2, n1 % n2) else: return n1 -def GCD(n1,n2): - while n2!=0: - r = n1 %n2 - n1=n2 + +def GCD(n1: int, n2: int): + while n2 != 0: + r = n1 % n2 + n1 = n2 n2 = r return n1 + + main() diff --git a/Recursion/HexToDenRecursive.py b/Recursion/HexToDenRecursive.py index a642163..561317b 100644 --- a/Recursion/HexToDenRecursive.py +++ b/Recursion/HexToDenRecursive.py @@ -1,21 +1,18 @@ -def HexToDen(HexString): - if len(HexString)==1 - HexDigit = HexString[0] - if HexDigit == 'a': - HexValue = 10 - elif HexDigit == 'b': - HexValue = 11 - elif HexDigit == 'c': - HexValue = 12 - elif HexDigit == 'd': - HexValue = 13 - elif HexDigit == 'e': - HexValue = 14 - elif HexDigit == 'f': - HexValue = 15 - else: - HexValue = int(HexDigit) - ValueSoFar = HexToDen(HexString[1:]) *16 + HexValue - return ValueSoFar +MAP: dict[str, int] = { + 'a':10, 'b':11, 'c':12, 'd':13, 'e':14, 'f':15, +} + +def HexToDen(HexString:str) -> int: + if len(HexString) == 0: + raise ValueError('Hex string must not be empty') + HexDigit = HexString[0] + HexValue = MAP.get(HexDigit, None) + if not HexValue: + HexValue = int(HexDigit) + if len(HexString) == 1: + return HexValue + ValueSoFar = HexToDen(HexString[1:]) * 16 + HexValue + return ValueSoFar + print(HexToDen('ff')) diff --git a/Recursion/Iterative vs Recursive.py b/Recursion/Iterative vs Recursive.py index fc3d36e..78b9d39 100644 --- a/Recursion/Iterative vs Recursive.py +++ b/Recursion/Iterative vs Recursive.py @@ -3,18 +3,16 @@ ## print(x) -def countDown(n): - if n !=-1: +def countDown(n:int): + assert n >= -1 + if n != -1: print(n) - countDown(n-1) + countDown(n - 1) + + countDown(7) -def CountUp(n): - for x in range(n+1): +def CountUp(n:int): + for x in range(n + 1): print(x) - -def CountDown(n): - print(n) - if n!=1: - CountDown(n-1) diff --git a/Recursion/LinkedList2ArrayRecursion.py b/Recursion/LinkedList2ArrayRecursion.py index 225eade..2a818a2 100644 --- a/Recursion/LinkedList2ArrayRecursion.py +++ b/Recursion/LinkedList2ArrayRecursion.py @@ -1,22 +1,24 @@ NULL = -1 SIZE = 7 -#Data = [""]* SIZE +# Data = [""]* SIZE Data = ["Hamza", "Abbad", "Faheem", "Ibbad", "Zeeshan", "Muntazir", "Bashir"] -Next = [3,6,0,5,-1,4,2] -#Next = [0] * SIZE +Next = [3, 6, 0, 5, -1, 4, 2] +# Next = [0] * SIZE Free = 0 -#Start = NULL +# Start = NULL Start = 1 + def init(): global Data global Next global SIZE - + for x in range(SIZE): - Next[x] = x+1 - Next[SIZE-1]=NULL - + Next[x] = x + 1 + Next[SIZE - 1] = NULL + + def output(): global Data global Next @@ -24,39 +26,43 @@ def output(): idx = Start print(Data[idx]) - while Next[idx] !=NULL: + while Next[idx] != NULL: idx = Next[idx] print(Data[idx]) -def outputRecursive(Data , Next , idx): - '''arrat with data array with pointers''' - #idx = Start - if Next[idx]==NULL: - print( Data[idx]) + +def outputRecursive(Data: list, Next: list[int], idx: int): + """arrat with data array with pointers""" + # idx = Start + if Next[idx] == NULL: + print(Data[idx]) else: outputRecursive(Data, Next, Next[idx]) print(Data[idx]) - + + def search(val): global Data global Next global Start - + isFound = False idx = Start - if Data[idx]==val: isFound=True - - while Next[idx] !=NULL: + if Data[idx] == val: isFound = True + + while Next[idx] != NULL: idx = Next[idx] - if Data[idx]==val: isFound=True + if Data[idx] == val: isFound = True return isFound -def main(): - #init() + +def main(): + # init() outputRecursive(Data, Next, Start) print() output() - #print(search("Faheem")) - #print(search("Ali")) + # print(search("Faheem")) + # print(search("Ali")) + main() diff --git a/Recursion/RecursiveCountDown.py b/Recursion/RecursiveCountDown.py index 148cc35..9093360 100644 --- a/Recursion/RecursiveCountDown.py +++ b/Recursion/RecursiveCountDown.py @@ -1,16 +1,16 @@ - -def fibRecursive(n): - if n==1: - return 1 +def fibRecursive(n:int): + if n == 0: + return 0 else: - return n+fibRecursive(n-1) - -def fibIterative(n): + return n + fibRecursive(n - 1) + + +def fibIterative(n:int): total = 0 - for x in range (1,n+1): - total +=x + for x in range(1, n + 1): + total += x return total + print(fibIterative(7)) print(fibRecursive(7)) - diff --git a/Recursion/RecursiveDenToBin.py b/Recursion/RecursiveDenToBin.py index f0f88ca..b3b8d91 100644 --- a/Recursion/RecursiveDenToBin.py +++ b/Recursion/RecursiveDenToBin.py @@ -1,12 +1,12 @@ -def DenToBin(n:int): - b=n%2 - if n==0: - print('0',end='') - elif n==1: - print('1',end='') +def DenToBin(n: int): + b = n % 2 + if n == 0: + print('0', end='') + elif n == 1: + print('1', end='') else: - DenToBin(n//2) - print(str(b),end='') + DenToBin(n // 2) + print(str(b), end='') + DenToBin(121) - diff --git a/Recursion/RecursiveReverseString.py b/Recursion/RecursiveReverseString.py index d7e9608..9b59a30 100644 --- a/Recursion/RecursiveReverseString.py +++ b/Recursion/RecursiveReverseString.py @@ -1,37 +1,34 @@ -def ReverseStrRecursive(s): +def ReverseStrRecursive(s: str) -> str: print(s[-1], end='') - if len(s)>1: + if len(s) > 1: ReverseStrRecursive(s[:-1]) + return "" - -def reverseStr(s): +def reverseStr(s: str) -> str: rs = '' - for x in range(len(s)-1, -1, -1): + for x in range(len(s) - 1, -1, -1): rs += s[x] return rs - -print(ReverseStrRecursive('faheem')) -print(reverseStr('faheem')) -print(CountUp(7)) -print(CountDown(7)) - - - - - - - - - - - - - - +def CountUp(n: int): + for x in range(n + 1): + print(x) +def CountDown(n: int): + """ + In the best programming language, this would be (conceptually): + while (n > 0) + println (n--); + """ + if n > 0: + print(n) + CountDown(n - 1) +print(ReverseStrRecursive('faheem')) +print(reverseStr('faheem')) +CountUp(7) +CountDown(7) diff --git a/Recursion/Total.py b/Recursion/Total.py index da92ace..3363017 100644 --- a/Recursion/Total.py +++ b/Recursion/Total.py @@ -1,12 +1,12 @@ def main(): print(Total()) + def Total(): - x = int(input("Enter a number [0 to end] ")) - if x==0 : #base + x = int(input("Enter a number [0, inf) : ")) + if x == 0: # base return x - else: - return x+Total() + return x + Total() main() diff --git a/Recursion/guess recursive.py b/Recursion/guess recursive.py index a14a42f..0d8000f 100644 --- a/Recursion/guess recursive.py +++ b/Recursion/guess recursive.py @@ -1,13 +1,22 @@ import random -def guess(n): - inp=int(input('Enter a number between 1 and 10: ')) - if(n==inp): + + +def guess(n: int): + try: + inp = int(input('Enter a number between 1 and 10: ')) + except ValueError: + print('Invalid input') + guess(n) + return #unreachable + if (n == inp): print('Congratulation! You guessed it correctly.') return - elif(n>inp): + elif (n > inp): print('Enter a bigger number') guess(n) else: print('Enter a lesser number') guess(n) -guess(random.randint(1,11)) + + +guess(random.randint(1, 11)) diff --git a/Recursion/isPrime.py b/Recursion/isPrime.py index d3be7b2..fa116bc 100644 --- a/Recursion/isPrime.py +++ b/Recursion/isPrime.py @@ -1,25 +1,25 @@ ##student work +#edited slightly -global i i = 2 -global prime prime = True def isPrime(n: int): global prime, i - if n == 1: # base case 1 + if n == 1: # base case 1 prime = False - elif n == 2 or n == 3: # base case 2 + elif n == 2 or n == 3: # base case 2 prime = True elif n > 3: if n > i: - if n%i == 0: + if n % i == 0: prime = False else: - i+=1 + i += 1 isPrime(n) + isPrime(3) print(prime) isPrime(4) diff --git a/Recursion/palindrome recursive.py b/Recursion/palindrome recursive.py index e4dd26b..236e8b4 100644 --- a/Recursion/palindrome recursive.py +++ b/Recursion/palindrome recursive.py @@ -1,4 +1,4 @@ -def is_palindrome(word): +def is_palindrome(word: str): """Return True if word is a palindrome, False if not.""" if len(word) <= 1: return True diff --git a/Recursion/primeRecursive.py b/Recursion/primeRecursive.py index 0c60421..a1e38f4 100644 --- a/Recursion/primeRecursive.py +++ b/Recursion/primeRecursive.py @@ -1,17 +1,17 @@ -def prime(n,d=3): - if n==2 or n==3: +def prime(n: int, d: int = 3): + if n == 2 or n == 3: return True - elif n==1: + elif n == 1: return False - elif n%2==0: + elif n % 2 == 0: return False - elif n%d==0: + elif n % d == 0: return False - elif d>=n//3: + elif d >= n // 3: return True else: - return prime(n,d+2) #general case - + return prime(n, d + 2) # general case + print(prime(1)) print(prime(2)) diff --git a/Recursion/quick sort recursive.py b/Recursion/quick sort recursive.py index 819ccdc..0d4df33 100644 --- a/Recursion/quick sort recursive.py +++ b/Recursion/quick sort recursive.py @@ -1,13 +1,15 @@ import statistics import random -def get_random_numbers(length, minimum=1, maximum=100): + +def get_random_numbers(length: int, minimum: int = 1, maximum: int = 100): numbers = [] for _ in range(length): numbers.append(random.randint(minimum, maximum)) return numbers + def quicksort(numbers): if len(numbers) <= 1: return numbers @@ -26,7 +28,7 @@ def quicksort(numbers): ) return ( - quicksort(items_less) + - pivot_items + - quicksort(items_greater) + quicksort(items_less) + + pivot_items + + quicksort(items_greater) ) diff --git a/Recursion/recursive.py b/Recursion/recursive.py index 2ece8db..b2a8b19 100644 --- a/Recursion/recursive.py +++ b/Recursion/recursive.py @@ -1,10 +1,11 @@ def main(): p(5) -def p(a): + +def p(a: int): print(a) - if a!=1: - p(a-2) + if a >= 1: + p(a - 2) main() diff --git a/Recursion/recursiveString.py b/Recursion/recursiveString.py index 4f3b754..466ee56 100644 --- a/Recursion/recursiveString.py +++ b/Recursion/recursiveString.py @@ -1,9 +1,10 @@ def main(): p('faheem') -def p(a): + +def p(a: str): print(a[-1], end='') - if len(a)>1: + if len(a) > 1: p(a[:-1]) diff --git a/Stack.py b/Stack.py index c1e4754..4fd081b 100644 --- a/Stack.py +++ b/Stack.py @@ -1,59 +1,32 @@ -<<<<<<< HEAD size = 2 -stackArray = ['']*size +stackArray = [''] * size tos = 0 + def push(s): global tos global size global stackArray - if tos==size: + if tos == size: print('stack full.') else: - stackArray[tos]=s - tos+=1 -def pop(): - global tos - global stackArray - if tos==0: - print('no data to show') - else: - tos-=1 - print(stackArray[tos]) + stackArray[tos] = s + tos += 1 -pop() -push('faheem') -push('ali') -push('nadeem') -pop() -pop() -======= -size = 2 -stackArray = ['']*size -tos = 0 -def push(s): - global tos - global size - global stackArray - if tos==size: - print('stack full.') - else: - stackArray[tos]=s - tos+=1 def pop(): global tos global stackArray - if tos==0: + if tos == 0: print('no data to show') else: - tos-=1 + tos -= 1 print(stackArray[tos]) + pop() push('faheem') push('ali') push('nadeem') pop() pop() ->>>>>>> d2ba29fbfd3c554d05834d91472d14f729dcb33b diff --git a/positionInFile.py b/positionInFile.py index 2d52aef..eb50182 100644 --- a/positionInFile.py +++ b/positionInFile.py @@ -4,7 +4,7 @@ print("read string is: ",str) #check current position position=fo.tell(); -print ("current position: ",position +print ("current position: ",position) #reposition pointer at the beginning position=fo.seek(0,0); str=fo.read(10);