blob_id
stringlengths
40
40
repo_name
stringlengths
5
127
path
stringlengths
2
523
length_bytes
int64
22
3.06M
score
float64
3.5
5.34
int_score
int64
4
5
text
stringlengths
22
3.06M
00379b5d5552e67855b1ecc2287b79aa84c78ac5
bluefly/university
/ex2.py
1,828
3.71875
4
import math import mpmath import sys def usage(): print "%s <precision, e.g. 10**-2> <value of function to compute> <highest Taylor degree to try>" % __file__ sys.exit(1) def main(): func = lambda x: mpmath.exp(mpmath.power(x, 2)) precision = sys.argv[1].split('**') precision = math.pow(int(precision[0]), int(precision[1])) x = mpmath.mpf(float(sys.argv[2])) print "expected value = %f" % mpmath.quad(func, [0, x]) print "precision = %f" % precision print "x = %f" % x print "max Taylor degree to try = %s" % sys.argv[3] print "" upperbound = int(sys.argv[3]) lowerbound = 0 lowestn = 0 # find the degree logarithmically, this is usually faster than trying 0..n while lowerbound < upperbound: n = (lowerbound + upperbound) / 2 # estimate the remainder diff = mpmath.diff(func, x, n) rn = diff / mpmath.factorial(n + 1) rn = rn * mpmath.power(x, n + 1) # is it good enough? if rn < precision: upperbound = n lowestn = n else: lowerbound = n + 1 if lowestn: print "lowest Taylor degree needed = %d" % lowestn coefficients = [] # find the coefficients of our Taylor polynomial for k in reversed(range(lowestn + 1)): if k > 0: coefficients.append(mpmath.diff(func, 0, k - 1) / mpmath.factorial(k)) # compute the value of the polynomial (add 0 for the free variable, the value of the indefinite integral at 0) p = mpmath.polyval(coefficients + [0], x) print "computed value = %f" % p else: print "max n is too low" if __name__ == "__main__": if len(sys.argv) < 4: usage() main()
8a4a0d2cbc31d8648dca73518bd16f73db3327ad
eunjeeSung/modu-ps
/week2_linked_list/copy_list_with_random_pointer.py
1,057
3.609375
4
""" # Definition for a Node. class Node: def __init__(self, x: int, next: 'Node' = None, random: 'Node' = None): self.val = int(x) self.next = next self.random = random """ # Time: O(N), Space: O(N) class Solution: def copyRandomList(self, head: 'Node') -> 'Node': ans_head = prev = Node(-1, None, None) original = head nodes = {} while original: if original.random is None: rand = None elif original.random in nodes: rand = nodes[original.random] else: rand = Node(original.random.val, None, None) nodes[original.random] = rand if original in nodes: prev.next = nodes[original] prev.next.random = rand else: prev.next = Node(original.val, None, rand) nodes[original] = prev.next prev, original = prev.next, original.next return ans_head.next
d33e9cbae379ac3eedf0402ac50bb93f46866c7b
mcgrathcuindy/Database-Querying-Integration
/Database_creation_Querying/MongoDB_Queries_JSON/statsPrice.py
2,295
3.578125
4
""" Name: Christopher McGrath Date: 4/21/2020 Desc: Project 2 python script to find the min, max, and avg of the prices """ import pymongo from pymongo import MongoClient client = MongoClient('mongodb://localhost:27017/') listOfEveryTransaction = [] listOfStrings = [] listOfAllKeysAndValues = [] listOfPriceValues = [] charactersToDelete = "])" db = client.project thing = db.transactions.find() #Loop to copy every Transaction from the "thing" cursor to a list for i in thing: listOfEveryTransaction.append(i["Transaction"]) #Loop to populate a new list with a string of Each transaction, I do this so i can use the split function for i in range(6): for j in range(2): listOfStrings.append(str(listOfEveryTransaction[i][j].values())) #Loop to split the string of each transaction into separate strings, and add the separate strings into a new list for i in range(len(listOfStrings)): listOfAllKeysAndValues.append(listOfStrings[i].split()) #Loop to form a new list with the desired values of 'price' for i in range(len(listOfAllKeysAndValues)): for j in range(2): #this if condition is used to filter out the Id key and values that we don't need, We just want price values if j == 1: listOfPriceValues.append(listOfAllKeysAndValues[i][j]) #Loop to delete the ending characters of each string of values ']' ')' for char in charactersToDelete: for i in range(0,len(listOfPriceValues)): listOfPriceValues[i] = listOfPriceValues[i].replace(char,"") #Loop to typecast each price value from a string to an int so we can find the avg, min, and max for i in range(0,len(listOfPriceValues)): listOfPriceValues[i] = int(listOfPriceValues[i]) #declaring the variables needed to find the avg, min, and max of prices avg = 0 sum = 0 max = listOfPriceValues[0] min = listOfPriceValues[0] #loop that finds the avg, min, and max for i in range(len(listOfPriceValues)): if listOfPriceValues[i] > max: max = listOfPriceValues[i] if listOfPriceValues[i] < min: min = listOfPriceValues[i] sum = sum + listOfPriceValues[i] avg = sum / len(listOfPriceValues) print("The avg of all prices is: {}".format(avg)) print("The min of all prices is: {}".format(min)) print("The max of all prices is: {}".format(max))
a0272e6ef1c0eec97a47ff6f49ebf6d3e4b9ebd2
sudozyq/DBAccessor
/Accessor.py
8,010
3.90625
4
class Accessor(object): ''' summary: This is a class for operate database include method: readConnectTime(): A method to read the time span of connection getTimezone(): A method to get the now time zone setTimezone():A method to set new timezone createDatabase():A method to create a database dropDatabase():A method to delete the database dropTable():A method to drop the table addKey():A method to add key for table updateTable():A method to update the selected table readOneColumn():A method to read one column deleteData():A method to delete a element sqlOperation():A method to receive a sql sentence and execute searchTable():A method to determine if a table exists in a database printMember(): A method to print all method and member variables Attributes: databaseType: A string of database type include MySQL and PostgreSQL timezone: A string of your timezone ''' def __init__(self, databaseType): self.databaseType = databaseType def readConnectedTime(self): """read the time span of connection""" timeSpan = time.time() - self.connectTime print("The time span of the database connection is: %ss" % timeSpan) def getTimeZone(self): """get the time zone""" print(datetime.datetime.now(self.timezone)) def setTimeZone(self): """set the time zone""" self.timezone = pytz.timezone(input("input the new area of time zone(like Asia/Shanghai):")) def createDatabase(self, databaseName): """create a database Args: databaseName: the name of database wait for create""" try: # use cursor() method to get cursor of operation cursor = self.conn.cursor() # use _query() method to get version-number database cursor._query('CREATE DATABASE %s' % databaseName) # commit the operation self.conn.commit() print("create a new database %s successful" % databaseName) return True except self.databaseType.Error as error: # if there is error rollback the operation self.conn.rollback() print('Error: %s' % error) choice = input("If you want to rename or drop the database or do nothing?(r/d/n):") if choice == 'r': # rename the database rename = input("Input the rename:") self.createDatabase(rename) elif choice == 'd': # delete the database self.dropDatabase(databaseName) else: # do nothing print("Nothing has been done.") def dropDatabase(self, databaseName): """delete the database Args: databaseName: the name of database wait for delete""" try: sqlSentence = "DROP DATABASE %s" % (databaseName,) cursor = self.conn.cursor() cursor.execute(sqlSentence) self.conn.commit() print("Drop successful!") return True except self.databaseType.Error as error: # if there is error rollback the operation self.conn.rollback() print('Error: %s' % error) def dropTable(self, tableName): """drop the table Args: tableName: the name of table wait for delete""" try: sqlSentence = "DROP TABLE %s" % (tableName,) cursor = self.conn.cursor() cursor.execute(sqlSentence) self.conn.commit() print("Drop successful!") return True except self.databaseType.Error as error: # if there is error rollback the operation self.conn.rollback() print('Error: %s' % error) def addKey(self, tableName, key): """add the key in table Args: tableName: A String of tableName waiting for operate key: A string of key waiting for add""" try: sqlSentence = "alter table %s add column %s Decimal(16, 6) default \'0\'"% (tableName, key) cursor = self.conn.cursor() cursor.execute(sqlSentence) self.conn.commit() print("Key add success!") return True except self.databaseType.Error as error: # if there is error rollback the operation self.conn.rollback() print('Error: %s' % error) return False def updateTable(self, operateTable, afterTable, regular): """update the selected table Args: operateTable: A String of tableName waiting for operate afterTable: A string of tablename after operate regular: A string of selection""" try: sqlSentence = "updata %s set %s where %s"% (operateTable, afterTable, regular) cursor = self.conn.cursor() cursor.execute(sqlSentence) self.conn.commit() print("updata success!") return True except self.databaseType.Error as error: # if there is error rollback the operation self.conn.rollback() print('Error: %s' % error) return False def readOneColumn(self, columnName, tableName): """read one column Args: columnName: A String of columnName waiting for read tableName: A string of tablename waiting for read""" try: sqlSentence = "SELECT %s FROM %s"% (columnName, tableName) cursor = self.conn.cursor() cursor.execute(sqlSentence) self.conn.commit() return True except self.databaseType.Error as error: # if there is error rollback the operation self.conn.rollback() print('Error: %s' % error) return False def deleteData(self, tableName, element): """delete a element Args: tableName: A String of tableName waiting for delete element: A string of element waiting for delete""" try: sqlSentence = "delete from %s where %s"% (tableName, element) cursor = self.conn.cursor() cursor.execute(sqlSentence) self.conn.commit() return True except self.databaseType.Error as error: # if there is error rollback the operation self.conn.rollback() print('Error: %s' % error) return False def sqlOperation(self): """input a sql sentence and execute""" try: sqlSentence = input("input the createSentence: ") cursor = self.conn.cursor() cursor.execute(sqlSentence) self.conn.commit() print("success execute") return True except self.databaseType.Error as error: # if there is error rollback the operation self.conn.rollback() print('Error: %s' % error) return False def searchTable(self, tableName): """Determine if a table exists in a database Args: tableName: the name of table wait for search""" try: sqlSentence = "select * from %s "% (tableName,) cursor = self.conn.cursor() cursor.execute(sqlSentence) self.conn.commit() print("The table exists in database!") return True except self.databaseType.Error as error: # if there is error rollback the operation self.conn.rollback() print('Error: %s' % error) return False def printMember(self): """print all method and member variables""" print(Accessor.__doc__)
89eea6c879275bbcf393fa9cc29c43cc77178869
louissobel/cryptbox
/file_structures/decrypted_file_handle.py
1,871
3.71875
4
""" handle pointing to an open decrypted file """ import os class DecryptedFileHandle(object): def __init__(self, decrypted_file, fd, **kwargs): """ decrypted file is the OpenDecryptedFile holding the contents TODO: maintains a position within the file? """ self.decrypted_file = decrypted_file self.fd = fd self.readable = kwargs['readable'] self.writable = kwargs['writable'] self.open = True def is_read_only(self): """ useful """ return self.readable is True and self.writable is False def read(self, size, offset): """ reads """ if not self.readable: raise exceptions.CannotRead('from fd %d' % self.fd) with self.decrypted_file.rwlock: # TODO errors? they bubble right now fd = self.decrypted_file.fd os.lseek(fd, offset, os.SEEK_SET) return os.read(fd, size) def write(self, data, offset): """ write! """ if not self.writable: raise exceptions.CannotWrite('to fd %d' % self.fd) if len(data) > 0: with self.decrypted_file.rwlock: # TODO errors? let em bubble fd = self.decrypted_file.fd os.lseek(fd, offset, os.SEEK_SET) result = os.write(fd, data) self.decrypted_file.changed() return result def truncate(self, length): """ truncate """ if not self.writable: raise exceptions.CannotWrite('to fd %d' % self.fd) with self.decrypted_file.rwlock: # TODO errors? let em bubble result = os.ftruncate(self.decrypted_file.fd, length) self.decrypted_file.changed() return result
97061f9a6cb4f636f03e353638534db97b4815a9
azmove/learnpy
/py_file/functions.py
2,165
3.984375
4
#coding=utf-8 student = [{'name': 'admin', 'sex': 'man', 'phone': '110'}, {'name': 'user1', 'sex': 'male', 'phone': '119'}, {'name': 'usr', 'sex': 'female', 'phone': '333'}] def printMenu(): print("*"*30) print(" Stutents System V6.8.1") print("1.Add new student") print("2.Delect student") print("3.change name") print("4.search name in student") print("Press q to quit") print("Note:You need to add info first to test this student_system.py") print("*"*30) #add student Function def addStu(): userName = input("Please Enter the name you want to op:") newSex = input("Enter your Sex:") newPhone = input("Please enter you phone number:") info = {} info['name'] = userName info['sex'] = newSex info['phone'] = newPhone student.append(info) def deleteStu(): stuId = int(input("Plese Enter ID you wanan to DELETE:")) if stuId < int(len(student)): del student[stuId] else: print("ID incorrect!") def changeStu(): stuId = int(input("Please Enter ID you wanna to change:")) if stuId < len(student): userName = input("plese enter which name you wana to change:") newSex = input("Enter your Sex:") newPhone = input("Please enter you phone number:") student[stuId - 1]['name'] = userName student[stuId - 1]['sex'] = newSex student[stuId - 1]['phone'] = newPhone else: print("Your ID incorrect !") def searchStu(): print("You select for search function to find student") userName = input("plese enter the name you wana to search:") for x in student: if userName == x['name']: print("Found it! lists are %s" % x['name']) print(" Name Sex Phone") print("%s %s %s" % (x['name'], x['sex'], x['phone'])) break if userName != x['name']: print("No Record!") def ls_Stu_Info(): # print("Student Lists:%s"%student) print("No Name Sex Phone ") i = 1 for allist in student: print("%d %s %s %s" % (i, allist['name'], allist['sex'], allist['phone'])) i += 1
996520dcd43c24c0391fc8767ee4eb9f8f3d309e
AdityaChavan02/Python-Data-Structures-Coursera
/8.6(User_input_no)/8.6.py
481
4.3125
4
#Rewrite the program that prompts the user for a list of numbers and prints the max and min of the numbers at the end when the user presses done. #Write the program to store the numbers in a list and use Max Min functions to compute the value. List=list() while True: no=input("Enter the no that you so desire:\n") if no=='done': break List.append(no) print(List) print("The MAX value is %d",max(List)) print("The MIN value is %d",min(List))
0ac525f075a96f8a749ddea35f8e1a59775217c8
ZoranPandovski/al-go-rithms
/sort/selection_sort/python/selection_sort.py
873
4.125
4
#defines functions to swap two list elements def swap(A,i,j): temp = A[i] A[i] = A[j] A[j] = temp #defines functions to print list def printList(A,n): for i in range(0,n): print(A[i],"\t") def selectionSort(A,n): for start in range(0,n-1): min=start #min is the index of the smallest element in the list during the iteration #Scan from A[min+1] to A[n-1] to find a list element that is smaller than A[min] for cur in range(min+1,n): #if A[cur] is smaller than A[min] min is updated if A[cur]<A[min]: min = cur #the two elements are swapped swap(A,start,min) def test(): A = [38,58,13, 15,21,27,10,19,12,86,49,67,84,60,25] n = len(A) print("Selection Sort: ") selectionSort(A,n) print("Sorted List: ") printList(A,n) test()
80d24d256bad937b89cce23abf06354308975ed3
ZoranPandovski/al-go-rithms
/data_structures/Linked_list/Python/Odd_Even_Linked_List.py
709
3.875
4
''' Given the head of a singly linked list, group all the nodes with odd indices together followed by the nodes with even indices, and return the reordered list. ''' class Solution(object): def oddEvenList(self, head): if head is None: return None if head.next is None: return head o = head p = o.next ehead = p while p.next is not None: o.next = p.next p.next = p.next.next o = o.next p = p.next if p is None: break o.next = ehead return head ''' Input: head = [1,2,3,4,5] Output: [1,3,5,2,4] ---------------------- Input: head = [1,2,3,4,5] Output: [1,3,5,2,4] '''
96c3edcd33251c322b2141d60ed3bbd569321de0
ZoranPandovski/al-go-rithms
/math/Matrix/Python/poly_regression.py
1,011
3.578125
4
from __future__ import division from math import exp import numpy as np import sys def poly_regression (arr_x, arr_y, k): #find the k-th degree regression polynomial using matrices #context: arr_x is a list of independent variables and arr_y is a list of dependent variables #constraint: arr_x and arr_y are of the same size, and the elements of arr_x are pairwise distinct #reference: https://www.varsitytutors.com/hotmath/hotmath_help/topics/quadratic-regression A1=[] for i in range (0, k + 1): temp=[] for m in range (0, k + 1): #the elements are in the form of sum of x^(2k-i-m) sum = 0 for j in range (0, len(arr_x)): sum += (arr_x[j]) ** (2 * k - i - m) temp.append(sum) A1.append(temp) B1=[] for i in range (0, k + 1): for j in range (0, len(arr_x)): sum += (arr_x[j] ** (k - i)) * (arr_y[j]); B1.append(sum) A=np.array(A1) B=np.array(B1) #print (A) A_inv=np.linalg.inv(A) C=np.dot(A_inv, B) #C = [a_k, a_{k-1}, ...] represents a_kx^k+a_kx^(k-1)+... return C
379c87d8341e89aba6125e59f8132782128a9f7e
ZoranPandovski/al-go-rithms
/math/Matrix multiplication/python/Strassen's Algorithm.py
5,170
4.0625
4
def iterative_matrix_multiplication(matrix_1,matrix_2): #Iterative Multiplication O(n^3) """ input: (matrix_1, matrix_2) of dimensions lxm and mxn respectively output (matrix) of dimensions lxn, the product of the two input matrices """ product=[[0 for c in range (len(matrix_2[0]))]for r in range(len(matrix_1))] for i in range (len(matrix_1)): for j in range (len(matrix_2[0])): for k in range(len(matrix_2)): product[i][j]+=matrix_1[i][k]*matrix_2[k][j] return product ################################################################################################ def r_m_m(matrix_1,matrix_2): #Recursive Matrix Multiplication O(n^log7) """ input: (matrix_1, matrix_2) of dimensions lxm and mxn respectively -and in case of using Strassen's optimization, nxn and nxn respectively where n is a power of two-. output (matrix) of dimensions lxn -and in case of Strassen's optimization, nxn- the product of the two input matrices. """ #Finding the number of rows and coloumns of each matrix rows_1,rows_2,columns_1,columns_2=len(matrix_1),len(matrix_2),0,0 if matrix_1: columns_1=len(matrix_1[0]) if matrix_2: columns_2=len(matrix_2[0]) #Dividing each matrix into four sub-matrices #Set the value the sub=matrix to [] in case of [[]] A=[matrix_1[r][:columns_1//2] for r in range(rows_1//2)] if len(A)==1 and len(A[0])==0: A=[] B=[matrix_1[r][columns_1//2:] for r in range(rows_1//2)] if len(B)==1 and len(B[0])==0: B=[] C=[matrix_1[r][:columns_1//2] for r in range(rows_1//2,rows_1)] if len(C)==1 and len(C[0])==0: C=[] D=[matrix_1[r][columns_1//2:] for r in range(rows_1//2,rows_1)] if len(D)==1 and len(D[0])==0: D=[] E=[matrix_2[r][:columns_2//2] for r in range(rows_2//2)] if len(E)==1 and len(E[0])==0: E=[] F=[matrix_2[r][columns_2//2:] for r in range(rows_2//2)] if len(F)==1 and len(F[0])==0: F=[] G=[matrix_2[r][:columns_2//2] for r in range(rows_2//2,rows_2)] if len(G)==1 and len(G[0])==0: G=[] H=[matrix_2[r][columns_2//2:] for r in range(rows_2//2,rows_2)] if len(H)==1 and len(H[0])==0: H=[] #Base Case: All sub-matrices are empty except D,H ie. the product of two 1x1 matrices if not (len(A) or len(B) or len(C) or len(E) or len(F) or len(G)): #De Morgan's Theorem if len(D)==1 and len(H)==1: return [[D[0][0]*H[0][0]]] else: return [] #Regular Divide and conquer approach O(n^3) # I=m_a(r_m_m(A,E),r_m_m(B,G)) # II=m_a(r_m_m(A,F),r_m_m(B,H)) # III=m_a(r_m_m(C,E),r_m_m(D,G)) # IV=m_a(r_m_m(C,F),r_m_m(D,H)) # return combine(I,II,III,IV) #Optimized Strassen's Algorithm O(n^log7) works for SQUARE MATRICES (n x n) with n equal to 2^m only P1=r_m_m(A,m_s(F,H)) P2=r_m_m(m_a(A,B),H) P3=r_m_m(m_a(C,D),E) P4=r_m_m(D,m_s(G,E)) P5=r_m_m(m_a(A,D),m_a(E,H)) P6=r_m_m(m_s(B,D),m_a(G,H)) P7=r_m_m(m_s(A,C),m_a(E,F)) I=m_a(m_a(P6,m_s(P4,P2)),P5) II=m_a(P1,P2) III=m_a(P3,P4) IV=m_a(P1,m_s(P5,m_a(P3,P7))) return combine(I,II,III,IV) def m_a(matrix_1,matrix_2): #Matrix Addition """ A helper function for the r_m_m() function input: Two matrices of the same dimensions output: A matrix, the summation of these two matrices """ #If both lists are non-empty: if matrix_1 and matrix_2: return [[matrix_1[i][j]+matrix_2[i][j] for j in range (len(matrix_1[0]))]for i in range (len(matrix_1))] #Else: One of them is empty or both are empty else: return matrix_2 or matrix_1 def m_s(matrix_1,matrix_2): #Matrix Subtraction """ A helper function for the r_m_m() function input: Two matrices of the same dimensions output: A matrix, the subtraction of these two matrices """ if matrix_1 and matrix_2: return [[matrix_1[i][j]-matrix_2[i][j] for j in range (len(matrix_1[0]))]for i in range (len(matrix_1))] else: return matrix_2 or matrix_1 def combine(matrix_1,matrix_2,matrix_3,matrix_4): #Combine the four sub-matrices into one matrix #Declare combined_matrix and initialize the num of rows of combined_matrix combined_matrix=[] num_rows_combined=max(len(matrix_1),len(matrix_2))+max(len(matrix_3),len(matrix_4)) #Using max to avoid considering the empty matrix rows #Merge matrix_1 and matrix_2 into combined_matrix for i in range (num_rows_combined//2): if len(matrix_1)==0: temp_1=[] else: temp_1=matrix_1[i] if len(matrix_2)==0: temp_2=[] else: temp_2=matrix_2[i] if len(temp_1+temp_2): combined_matrix.append(temp_1+temp_2) #Merge matrix_3 and matrix_4 into combined_matrix for i in range (num_rows_combined//2+(num_rows_combined&1)): if len(matrix_3)==0: temp_1=[] else: temp_1=matrix_3[i] if len(matrix_4)==0: temp_2=[] else: temp_2=matrix_4[i] if len(temp_1+temp_2): combined_matrix.append(temp_1+temp_2) return combined_matrix ################################################################################################ def main(): matrix_1,matrix_2=[[1,2,3,4],[5,6,7,8],[9,10,11,12],[13,14,15,16]],[[0,1,2,3],[4,5,6,7],[8,9,10,11],[12,13,14,15]] print(r_m_m(matrix_1,matrix_2)) if __name__=="__main__": main()
2c87f85cd2627d5085ffcd3b05ad88e941a57d82
ZoranPandovski/al-go-rithms
/recursive_algorithms/Tower of Hanoi/Python/tower_of_hanoi.py
440
4
4
# Recursive Python function to solve tower of hanoi def TowerOfHanoi(n , from_rod, to_rod, aux_rod): if n == 1: print("Move disk 1 from rod",from_rod,"to rod",to_rod) return TowerOfHanoi(n-1, from_rod, aux_rod, to_rod) print("Move disk",n,"from rod",from_rod,"to rod",to_rod) TowerOfHanoi(n-1, aux_rod, to_rod, from_rod) # Driver code n = 4 TowerOfHanoi(n, 'A', 'C', 'B') # A, C, B are the name of rods # Contributed By Harshit Agrawal
cd94d866092a9267aa954d8824939681fe202ea1
ZoranPandovski/al-go-rithms
/data_structures/Linked_list/Python/Swap_Nodes_Linkedlist.py
878
3.75
4
# Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution: def swapPairs(self, head: Optional[ListNode]) -> Optional[ListNode]: if head==None: return None if head.next==None: return head tmp1=head tmp2=head.next while tmp1: if tmp1 !=None and tmp2 !=None: print(tmp1.val) print(tmp2.val) tmpx_val=tmp1.val tmpx=tmp1 tmp1.val=tmp2.val tmp2.val=tmpx_val tmp1=tmp2.next if tmp2.next!=None: tmp2=tmp2.next.next else: temp2=None else: break return head
608e92193e4b3e0ea5b28d25fada9aa86807c73e
ZoranPandovski/al-go-rithms
/math/factorial/python/factorial.py
163
4.1875
4
def factorial(n): if n <= 1: return 1 else: return n * factorial(n-1) number = int(input("Enter a number: ")) print("Result {}".format(factorial(number)))
fcb476b1fc1b5046b511b381a091894918ee300b
ZoranPandovski/al-go-rithms
/recursive_algorithms/Coin change/python/coin_change_recurse.py
651
3.875
4
""" Coin change problem : Given a set of coins (unlimited supply), find number of ways to make change of n Example : Given coins (1,2), find number of ways of making change 4 Answer : 3 - [(1,1,1,1) (1,1,2) (2,2)] """ def coin_change(change, choices, coin): if change == 0: return 1 elif change<0: return 0 else: t_ch=0 for i in range(coin, len(choices)): if not choices[i]>change: t_ch+=coin_change(change-choices[i], choices, i) return t_ch if __name__ == '__main__': assert coin_change(5, [1,3,5], 0) == 3 assert coin_change(7, [1,3,5], 0) == 4
f3adebbb591a66a652128407fb8f0c950f2c94c2
ZoranPandovski/al-go-rithms
/sort/gnome_sort/py/gnome_sort.py
527
3.640625
4
from __future__ import print_function def gnomeSort( arr, n): index = 0 while index < n: if index == 0: index = index + 1 if arr[index] >= arr[index - 1]: index = index + 1 else: arr[index], arr[index-1] = arr[index-1], arr[index] index = index - 1 return arr # Driver Code arr = [ 34, 2, 10, -9] n = len(arr) arr = gnomeSort(arr, n) print("Sorted seqquence after applying Gnome Sort :", end=' ') for i in arr: print(i, end=' ')
6b2ae13e2f7dfa26c15cef55978cf7e70f4bf711
ZoranPandovski/al-go-rithms
/dp/min_cost_path/python/min_cost_path_.py
809
4.21875
4
# A Naive recursive implementation of MCP(Minimum Cost Path) problem R = 3 C = 3 import sys # Returns cost of minimum cost path from (0,0) to (m, n) in mat[R][C] def minCost(cost, m, n): if (n < 0 or m < 0): return sys.maxsize elif (m == 0 and n == 0): return cost[m][n] else: return cost[m][n] + min( minCost(cost, m-1, n-1), minCost(cost, m-1, n), minCost(cost, m, n-1) ) #A utility function that returns minimum of 3 integers */ def min(x, y, z): if (x < y): return x if (x < z) else z else: return y if (y < z) else z # Driver program to test above functions cost= [ [1, 2, 3], [4, 8, 2], [1, 5, 3] ] print(minCost(cost, 2, 2))
5da0b83d79edd1759e8e89ff0753902e0327c6e8
ZoranPandovski/al-go-rithms
/others/process_scheduling/round robin/python3/round_robin.py
2,113
3.78125
4
#Python program for implementation of RR Scheduling print("Enter Total Process Number: ") total_p_no = int(input()) total_time = 0 total_time_counted = 0 #proc is process list proc = [] wait_time = 0 turnaround_time = 0 for _ in range(total_p_no): #Getting the input for process print("Enter process arrival time and burst time") input_info = list(map(int, input().split(" "))) arrival, burst, remaining_time = input_info[0], input_info[1], input_info[1] #processes are appended to the proc list in following format proc.append([arrival, burst, remaining_time,0]) #total_time gets incremented with burst time of each process total_time += burst print("Enter time quantum") time_quantum = int(input()) print(total_time) #Keep traversing in round robin manner until the total_time == 0 while(total_time != 0): #traverse all the processes for i in range(len(proc)): #proc[i][2] here refers to remaining_time for each process i.e "i" if(proc[i][2] <= time_quantum and proc[i][2] >= 0): total_time_counted += proc[i][2] total_time -= proc[i][2] #the process has completely ended here thus setting it's remaining time to 0. proc[i][2] = 0 elif(proc[i][2] >0): #if process has not finished, decrementing it's remaining time by time_quantum proc[i][2] -= time_quantum total_time -= time_quantum total_time_counted += time_quantum if(proc[i][2] == 0 and proc[i][3]!=1): ''' if remaining time of process is 0 and individual waiting time of process has not been calculated i.e flag ''' wait_time += total_time_counted - proc[i][0] - proc[i][1] turnaround_time += total_time_counted - proc[i][0] #flag is set to 1 once wait time is calculated proc[i][3] = 1 print("\nAvg Waiting Time is ",(wait_time*1.0)/total_p_no) print("Avg Turnaround Time is ",(turnaround_time*1.0)/total_p_no,"\n")
1f2547aa08428209cf4d106ad8361033dd411efc
ZoranPandovski/al-go-rithms
/strings/palindrome/python/palindrome2.py
369
4.53125
5
#We check if a string is palindrome or not using slicing #Accept a string input inputString = input("Enter any string:") #Caseless Comparison inputString = inputString.casefold() #check if the string is equal to its reverse if inputString == inputString[::-1]: print("Congrats! You typed in a PALINDROME!!") else: print("This is not a palindrome. Try Again.")
d93971412e44f4173d7dc287b741e20529ea9c04
ZoranPandovski/al-go-rithms
/games/Python/Pong Game/paddle.py
516
3.71875
4
from turtle import Turtle HEIGHT=5 WEIDTH=1 class Paddle(Turtle): def __init__(self,x_pos,y_pos): super().__init__() self.penup() # self.speed(0) self.goto(x=x_pos,y=y_pos) self.shape("square") self.color("white") self.shapesize(stretch_wid=HEIGHT,stretch_len=WEIDTH) def move_up(self): new_y=self.ycor()+20 self.goto(x=self.xcor(),y=new_y) def move_down(self): new_y=self.ycor()-20 self.goto(x=self.xcor(),y=new_y)
ca66e78bad8634fe436f65a5d9a211688234d9b5
ZoranPandovski/al-go-rithms
/sort/insertion_sort/python/insertion.py
359
4.0625
4
def insertionSort(alist): for index in range(1,len(alist)): currentvalue = alist[index] position = index while position>0 and alist[position-1]>currentvalue: alist[position]=alist[position-1] position = position-1 alist[position]=currentvalue alist = [54,26,93,17,77,31,44,55,20] insertionSort(alist) print(alist)
6c4fabf6697c4072021cd77032685ba063fb8294
ZoranPandovski/al-go-rithms
/math/prime_sieve/python/rabin_miller.py
2,338
3.59375
4
# # author: @AKS1996 # Famous Rabin-Miller Test, determines whether a number is prime or not # Ref: https://en.wikipedia.org/wiki/Miller%E2%80%93Rabin_primality_test # import random import math from large_gcd import mGCD import sys def rabinMiller(n): if pow(2,math.log(n, 2)) == n: # Infinite loop for power of 2 return False s = n-1 t = 0 while s&1 == 0: s = s/2 t +=1 k = 0 while k<128: a = random.randrange(2,n-1) # a^s is computationally infeasible. we need a more intelligent approach # v = (a**s)%n # python's core math module can do modular exponentiation v = mGCD(a,s,n) #where values are (num,exp,mod) if v != 1: i=0 while v != (n-1): if i == t-1: return False else: i = i+1 v = (v**2)%n k+=2 return True def isPrime(n): # lowPrimes is all primes (sans 2, which is covered by the bitwise and operator) # under 1000. taking n modulo each lowPrime allows us to remove a huge chunk # of composite numbers from our potential pool without resorting to Rabin-Miller lowPrimes = [3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73,79,83,89,97 ,101,103,107,109,113,127,131,137,139,149,151,157,163,167,173,179 ,181,191,193,197,199,211,223,227,229,233,239,241,251,257,263,269 ,271,277,281,283,293,307,311,313,317,331,337,347,349,353,359,367 ,373,379,383,389,397,401,409,419,421,431,433,439,443,449,457,461 ,463,467,479,487,491,499,503,509,521,523,541,547,557,563,569,571 ,577,587,593,599,601,607,613,617,619,631,641,643,647,653,659,661 ,673,677,683,691,701,709,719,727,733,739,743,751,757,761,769,773 ,787,797,809,811,821,823,827,829,839,853,857,859,863,877,881,883 ,887,907,911,919,929,937,941,947,953,967,971,977,983,991,997] if (n >= 3): if (n&1 != 0): for p in lowPrimes: if (n == p): return True if (n % p == 0): return False return rabinMiller(n) return False # print rabinMiller(10240)
008ff87cab8866ea2b2b7f60a0281a459de23f33
ZoranPandovski/al-go-rithms
/cryptography/rot13_cipher/python/rot13-brute.py
1,497
3.96875
4
# Caesar Cipher # Source-code from https://inventwithpython.com/chapter14.html """ Usage: python3 rot13-brute.py enter option "e" for encrypt, "d" for decrypt, and "b" for brute/generate """ MAX_KEY_SIZE = 26 def getMode(): while True: print ("Do you wish to encrypt[e] or decrypt[d] or brute[b] force a message?") mode = input().lower() if mode in 'encrypt e decrypt d brute b'.split(): return mode[0] else: print ('Enter either "encrypt" or "e" or "decrypt" or "d" or "brute" or "b".') def getMessage(): print ('Enter your message:') return input() def getKey(): key = 0 while True: print ('Enter the key number(1-%s)' % (MAX_KEY_SIZE)) key = int(input()) if(key >= 1 and key <= MAX_KEY_SIZE): return key def getTranslateMessage(mode, message, key): if mode[0] == 'd': key = -key translated = '' for symbol in message: if symbol.isalpha(): num = ord(symbol) num += key if symbol.isupper(): if num > ord('Z'): num -= 26 elif num < ord('A'): num += 26 elif symbol.islower(): if num > ord('z'): num -= 26 elif num < ord('a'): num += 26 translated += chr(num) else: translated += symbol return translated mode = getMode() message = getMessage() if mode[0] != 'b': key = getKey() print('Your translated text is:') if mode[0] != 'b': print(getTranslateMessage(mode, message, key)) else: for key in range(1, MAX_KEY_SIZE + 1): print(key,getTranslateMessage('decrypt',message,key))
a917ccdaabf72c1def79c2e0bc7ce3e47d73dad7
ZoranPandovski/al-go-rithms
/Computer-Network/Sliding Window/sender_file.py
550
3.546875
4
#!/usr/bin/env python3 # 19BCE245 - Aayush Shah # Importing necessary libraries import socket s = socket.socket() # Initialising a socket s.bind(('localhost', 9999)) s.listen() while True: # Accepting a connection request from client and printing it c, address = s.accept() print('Connection request from {} accepted.'.format(address)) print(c.recv(1024).decode()) # Receiving echo message print('Sending acknowledgement message') c.send('Acknowledgement message received'.encode()) # Sending acknowledgement for the received message c.close()
fc9287fca6c7b390cbd47ae7f70806b10d6114c3
ZoranPandovski/al-go-rithms
/data_structures/b_tree/Python/check_bst.py
1,131
4.28125
4
""" Check whether the given binary tree is BST(Binary Search Tree) or not """ import binary_search_tree def check_bst(root): if(root.left != None): temp = root.left if temp.val <= root.val: left = check_bst(root.left) else: return False else: left = True if(root.right != None): temp = root.right if temp.val > root.val: right = check_bst(root.right) else: return False else: right = True if (left and right): return True else: return False # ### Testcases ### # # root = None # tree = binary_search_tree.Tree() # # # This tree should return Tree # root = tree.insert(root, 6) # root = tree.insert(root,3) # root = tree.insert(root,1) # root = tree.insert(root,4) # root = tree.insert(root,8) # root = tree.insert(root,7) # root = tree.insert(root,9) # tree.preorder(root) # print check_bst(root) # # # This tree should return False # root = tree.not_bst() # print check_bst(root)
02379285e520fde4f4b9e1bbdfdd6140d55c4cb4
ZoranPandovski/al-go-rithms
/search/TreeCommonAncestor/python/TreeCommonAncestor.py
981
3.78125
4
class Node: # A Binary tree node # Constructor to create a new node def __init__(self, data): self.data = data self.left = None self.right = None def lca(root, n1, n2): # Base Case if root is None: return None if(root.data > n1 and root.data > n2): return lca(root.left, n1, n2) if(root.data < n1 and root.data < n2): return lca(root.right, n1, n2) return root if __name__ == "__main__": root = Node(20) root.left = Node(8) root.right = Node(22) root.left.left = Node(4) root.left.right = Node(12) root.left.right.left = Node(10) root.left.right.right = Node(14) n1 = 12 ; n2 = 18 t = lca(root, n1, n2) print(f"LCA of {n1} and {n2} is {t.data}") n1 = 16 ; n2 = 10 t = lca(root, n1, n2) print(f"LCA of {n1} and {n2} is {t.data}") n1 = 18 ; n2 = 22 t = lca(root, n1, n2) print(f"LCA of {n1} and {n2} is {t.data}")
c72118d68c1575d86e3b188dcd26eb9fc52f8338
ZoranPandovski/al-go-rithms
/cryptography/substitution_cipher/python/substitution_cipher.py
961
3.78125
4
def encrypt(plaintext): alphabet=['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'] substitutionarray=['1','4','7','5','F','G','A','B','2','S','N','3','C','T','6','M','6','D','X','R','L','U','K','8','O','9'] ciphertext="" for i in plaintext: ciphertext=ciphertext+substitutionarray[alphabet.index(i)] return ciphertext def decrypt(ciphertext): alphabet=['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'] substitutionarray=['1','4','7','5','F','G','A','B','2','S','N','3','C','T','6','M','6','D','X','R','L','U','K','8','O','9'] reverseplaintext="" for i in ciphertext: reverseplaintext=reverseplaintext+alphabet[substitutionarray.index(i)] return reverseplaintext def test(): cipher = encrypt("youcantbreakme") plain_text = decrypt(cipher) assert plain_text == "youcantbreakme" if __name__ == "__main__": test()
368459afc30ee73a5aedc8f51c0ec22685cde547
ZoranPandovski/al-go-rithms
/machine_learning/python/eval_metrics/performance_metrics.py
2,821
3.875
4
# You must estimate the quality of a set of predictions when training a machine learning model. Performance metrics like classification accuracy and root mean squared error can give you a clear objective idea of how good a set of predictions is, and in turn how good the model is that generated them. # This is important as it allows you to tell the difference and select among: # 1 - Different transforms of the data used to train the same machine learning model. # 2 - Different machine learning models trained on the same data. # 3 - Different configurations for a machine learning model trained on the same data. # As such, performance metrics are a required building block in implementing machine learning algorithms from scratch. # Classification Accuracy: Calculate accuracy percentage between two lists def accuracy_metric(actual, predicted): correct = 0 for i in range(len(actual)): if actual[i] == predicted[i]: correct += 1 return correct / float(len(actual)) * 100.0 # Test accuracy actual = [0,0,0,0,0,1,1,1,1,1] predicted = [0,1,0,0,0,1,0,1,1,1] accuracy = accuracy_metric(actual, predicted) print(accuracy) # Confusion Matrix: calculate a confusion matrix def confusion_matrix(actual, predicted): unique = set(actual) matrix = [list() for x in range(len(unique))] for i in range(len(unique)): matrix[i] = [0 for x in range(len(unique))] lookup = dict() for i, value in enumerate(unique): lookup[value] = i for i in range(len(actual)): x = lookup[actual[i]] y = lookup[predicted[i]] matrix[x][y] += 1 return unique, matrix # pretty print a confusion matrix def print_confusion_matrix(unique, matrix): print('(P)' + ' '.join(str(x) for x in unique)) print('(A)---') for i, x in enumerate(unique): print("%s| %s" % (x, ' '.join(str(x) for x in matrix[i]))) # Test confusion matrix with integers actual = [0,0,0,0,0,1,1,1,1,1] predicted = [0,1,1,0,0,1,0,1,1,1] unique, matrix = confusion_matrix(actual, predicted) print_confusion_matrix(unique, matrix) # Mean Absolute Error: Calculate mean absolute error def mae_metric(actual, predicted): sum_error = 0.0 for i in range(len(actual)): sum_error += abs(predicted[i] - actual[i]) return sum_error / float(len(actual)) # Test RMSE actual = [0.1, 0.2, 0.3, 0.4, 0.5] predicted = [0.11, 0.19, 0.29, 0.41, 0.5] mae = mae_metric(actual, predicted) print(mae) # Root Mean Squared Error: Calculate root mean squared error from math import sqrt def rmse_metric(actual, predicted): sum_error = 0.0 for i in range(len(actual)): prediction_error = predicted[i] - actual[i] sum_error += (prediction_error ** 2) mean_error = sum_error / float(len(actual)) return sqrt(mean_error) # Test RMSE actual = [0.1, 0.2, 0.3, 0.4, 0.5] predicted = [0.11, 0.19, 0.29, 0.41, 0.5] rmse = rmse_metric(actual, predicted) print(rmse)
f52b46e7251d36eef85a839ee05748c4d47d50d2
ZoranPandovski/al-go-rithms
/math/basic/Greatest_digit_in_number/python/Greatest_digit_in_number.py
256
3.859375
4
number = 201328361572 maxDigit = -1 # convert number into unique set of digits and iterate over it for c in set(str(number)): # parse back to int and compare vs known max i = int(c) if i > maxDigit: maxDigit = i print(maxDigit) # > 8
bf23783e9c07a11cdf0a186ab28da4edc1675b54
ZoranPandovski/al-go-rithms
/sort/Radix Sort/Radix_Sort.py
1,369
4.1875
4
# Python program for implementation of Radix Sort # A function to do counting sort of arr[] according to # the digit represented by exp. def countingSort(arr, exp1): n = len(arr) # The output array elements that will have sorted arr output = [0] * (n) # initialize count array as 0 count = [0] * (10) # Store count of occurrences in count[] for i in range(0, n): index = arr[i] // exp1 count[index % 10] += 1 # Change count[i] so that count[i] now contains actual # position of this digit in output array for i in range(1, 10): count[i] += count[i - 1] # Build the output array i = n - 1 while i >= 0: index = arr[i] // exp1 output[count[index % 10] - 1] = arr[i] count[index % 10] -= 1 i -= 1 # Copying the output array to arr[], # so that arr now contains sorted numbers i = 0 for i in range(0, len(arr)): arr[i] = output[i] # Method to do Radix Sort def radixSort(arr): # Find the maximum number to know number of digits max1 = max(arr) # Do counting sort for every digit. Note that instead # of passing digit number, exp is passed. exp is 10^i # where i is current digit number exp = 1 while max1 / exp > 0: countingSort(arr, exp) exp *= 10 # Driver code arr = [170, 45, 75, 90, 802, 24, 2, 66] # Function Call radixSort(arr) for i in range(len(arr)): print(arr[i]) # This code is contributed by Manas Misra
f25f28ff313e184dccedf456019dc6da08110aed
ZoranPandovski/al-go-rithms
/strings/string_search/Tries/python/trie.py
4,113
3.703125
4
from __future__ import print_function class Node: def __init__(self, label=None, data=None): self.label = label self.data = data self.children = dict() def addChild(self, key, data=None): if not isinstance(key, Node): self.children[key] = Node(key, data) else: self.children[key.label] = key def __getitem__(self, key): return self.children[key] class Trie: def __init__(self): self.head = Node() def __getitem__(self, key): return self.head.children[key] def add(self, word): current_node = self.head word_finished = True for i in range(len(word)): if word[i] in current_node.children: current_node = current_node.children[word[i]] else: word_finished = False break # For ever new letter, create a new child node if not word_finished: while i < len(word): current_node.addChild(word[i]) current_node = current_node.children[word[i]] i += 1 # Let's store the full word at the end node so we don't need to # travel back up the tree to reconstruct the word current_node.data = word def has_word(self, word): if word == '': return False if word == None: raise ValueError('Trie.has_word requires a not-Null string') # Start at the top current_node = self.head exists = True for letter in word: if letter in current_node.children: current_node = current_node.children[letter] else: exists = False break # Still need to check if we just reached a word like 't' # that isn't actually a full word in our dictionary if exists: if current_node.data == None: exists = False return exists def start_with_prefix(self, prefix): """ Returns a list of all words in tree that start with prefix """ words = list() if prefix == None: raise ValueError('Requires not-Null prefix') # Determine end-of-prefix node top_node = self.head for letter in prefix: if letter in top_node.children: top_node = top_node.children[letter] else: # Prefix not in tree, go no further return words # Get words under prefix if top_node == self.head: queue = [node for key, node in top_node.children.iteritems()] else: queue = [top_node] # Perform a breadth first search under the prefix # A cool effect of using BFS as opposed to DFS is that BFS will return # a list of words ordered by increasing length while queue: current_node = queue.pop() if current_node.data != None: # Isn't it nice to not have to go back up the tree? words.append(current_node.data) queue = [node for key,node in current_node.children.iteritems()] + queue return words def getData(self, word): """ This returns the 'data' of the node identified by the given word """ if not self.has_word(word): raise ValueError('{} not found in trie'.format(word)) # Race to the bottom, get data current_node = self.head for letter in word: current_node = current_node[letter] return current_node.data if __name__ == '__main__': """ Example use """ trie = Trie() words = 'hello goodbye help gerald gold tea ted team to too tom stan standard money' for word in words.split(): trie.add(word) print("'goodbye' in trie: ", trie.has_word('goodbye')) print(trie.start_with_prefix('g')) print(trie.start_with_prefix('to'))
e1c5b863a65423dccbd55fd8f88de09277c6abcd
ZoranPandovski/al-go-rithms
/sort/selection_sort/python/selection_sort2.py
599
4.0625
4
import sys def selection_sort(items): """Implementation of the selection sort algorithm using Python inside parameter we can pass some items which are heterogeneous comparable """ length = len(items) for i in range(length): least = i for j in range(i + 1, length): if items[j] < items[least]: least = j items[least], items[i] = ( items[i], items[least] ) return items def test(): array = [2, 10, 7, 1] assert selection_sort(array) == [1, 2, 7, 10] if __name__ == '__main__': test()
c924e676d4ba40788e1aa43bc5d52165381d5a33
ZoranPandovski/al-go-rithms
/search/a_star/python/Astar.py
4,529
4.53125
5
#In computer science, A* (pronounced as "A star") is a computer algorithm that is widely used in pathfinding and graph # traversal, which is the process of finding a path between multiple points, called "nodes". It enjoys widespread use due #to its performance and accuracy. However, in practical travel-routing systems, it is generally outperformed by algorithms # which can pre-process the graph to attain better performance, although other work has found A* to be superior to other #approaches. #This algorithm is widely used in the field game development to approximate the shortest path on a map #It is similar to Dijkstra’s Algorithm in the sense that the main objective of both algorithms is to find the shortest path # but it runs much quicker than Dijkstra’s Algorithm class Node(): """A node class for A* Pathfinding""" def __init__(self, parent=None, position=None): self.parent = parent self.position = position self.g = 0 self.h = 0 self.f = 0 def __eq__(self, other): return self.position == other.position def astar(maze, start, end): """Returns a list of tuples as a path from the given start to the given end in the given maze""" # Create start and end node start_node = Node(None, start) start_node.g = start_node.h = start_node.f = 0 end_node = Node(None, end) end_node.g = end_node.h = end_node.f = 0 # Initialize both open and closed list open_list = {} closed_list = set() # Add the start node open_list[start_node.position] = start_node # Loop until you find the end while len(open_list): # Get the current node current_index = min(open_list, key=lambda x: open_list[x].f) current_node = open_list[current_index] # Pop current off open list, add to closed list open_list.pop(current_index) closed_list.add(current_index) # Found the goal if current_node == end_node: path = [] current = current_node while current is not None: path.append(current.position) current = current.parent return path[::-1] # Return reversed path # Generate children children = [] adj = [(0, -1), (0, 1), (-1, 0), (1, 0), (-1, -1), (-1, 1), (1, -1), (1, 1)] for new_position in adj: # Adjacent squares # Get node position node_position = (current_node.position[0] + new_position[0], current_node.position[1] + new_position[1]) # Make sure within range if (node_position[0] > (len(maze) - 1) or node_position[0] < 0 or node_position[1] > (len(maze[len(maze) - 1]) - 1) or node_position[1] < 0): continue # Make sure walkable terrain if maze[node_position[0]][node_position[1]] != 0: continue # Create new node new_node = Node(current_node, node_position) # Append children.append(new_node) # Loop through children for child in children: # Child is on the closed list if child.position in closed_list: continue # Create the f, g, and h values child.g = current_node.g + 1 child.h = ((child.position[0] - end_node.position[0])**2) + ( (child.position[1] - end_node.position[1])**2) child.f = child.g + child.h # Child is already in the open list if child.position in open_list and child.g > open_list[child.position].g: continue # Add the child to the open list open_list[child.position] = child def main(): maze = [[0, 0, 0, 0, 1, 0, 0, 0, 0, 0], [0, 0, 0, 0, 1, 0, 0, 0, 0, 0], [0, 0, 0, 0, 1, 0, 0, 0, 0, 0], [0, 0, 0, 0, 1, 0, 0, 0, 0, 0], [0, 0, 0, 0, 1, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 1, 0, 0, 0, 0, 0], [0, 0, 0, 0, 1, 0, 0, 0, 0, 0], [0, 0, 0, 0, 1, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]] start = (0, 0) end = (7, 6) path = astar(maze, start, end) print(path) if __name__ == '__main__': main()
c6c8c23cdf057fb067c98d95fa7f8ff5dac7e463
ZoranPandovski/al-go-rithms
/data_structures/Graphs/graph/Python/chromatic_number.py
3,227
3.671875
4
from collections import deque import numpy as np from copy import deepcopy import math class Graph: """ Implementation of a graph with Adjacency Matrix """ def __init__(self,size,directed = False): self.size = size self.matrix = [[0 for i in range(self.size)] for j in range(self.size)] self.directed = directed self.Time = 0 self.color = {i:"white" for i in range(self.size)} self.parent = [-1 for i in range(self.size)] self.time = [[0,0] for i in range(self.size)] def has_vertex(self,i): return i>=0 and i<self.size def addEdge(self,i,j,weight=1): if self.has_vertex(i) and self.has_vertex(j): if self.directed: self.matrix[i][j] = weight else: self.matrix[i][j] = weight self.matrix[j][i] = weight def delEdge(self,i,j): if self.directed: self.matrix[i][j] = 0 else: self.matrix[i][j] = 0 self.matrix[j][i] = 0 def adjacent_vertices(self,i): if self.has_vertex(i): w = [] for j in range(self.size): if self.matrix[i][j] != 0: w.append(j) return w def indeg(self): indegree = [0 for i in range(self.size)] for i in range(self.size): l = self.adjacent_vertices(i) for j in l: indegree[j] = indegree[j] + 1 return indegree ## Graph Coloring Using Greedy Algorithm ##1. Color first vertex with first color. ##2. Do following for remaining V-1 vertices. ##….. a) Consider the currently picked vertex and color it with the ##lowest numbered color that has not been used on any previously ##colored vertices adjacent to it. If all previously used colors ##appear on vertices adjacent to v, assign a new color to it. def chromatic_number(self): # Initially all vertices are uncolored color = [-1 for i in range(self.size)] # Initially all colors are available available_color = [True for i in range(self.size)] # Color the 0th vertex color[0] = 0 # Iterate for all other vertices for u in range(1,self.size): for v in self.adjacent_vertices(u): # If the neighbor is colored then make its # color unavailable if color[v] != -1: available_color[color[v]] = False # Find the first available color for vertices u c = 0 for i in range(self.size): if available_color[i]: c = i break # Color the vertex with that color color[u] = c # Make all the colors available available_color = [True for i in range(self.size)] for i in range(self.size): print("Color of vertex",i,"is",color[i]) def main(): g = Graph(6) g.directed = True g.addEdge(5, 2); g.addEdge(5, 0); g.addEdge(4, 0); g.addEdge(4, 1); g.addEdge(2, 3); g.addEdge(3, 1); g.chromatic_number() if __name__ == '__main__': main()
63f4ae359a2cc1b97281c90191a893c0ae546177
ZoranPandovski/al-go-rithms
/data_structures/b_tree/Python/tree_size.py
586
3.9375
4
""" Return the size of the tree (i.e) number of nodes in the tree """ from binary_search_tree import Tree import random class TreeSize(): def tree_size(self,root): if root == None: return 0 return ( 1 + self.tree_size(root.left) + self.tree_size(root.right)) ## Testcases ### # tsize = TreeSize() # root = None # obj = Tree() # # # # Create a sample tree # for i in range(10): # rand = random.randrange(1,20,2) # root = obj.insert(root,rand) # # print tsize.tree_size(root)
eea7ce90eb1bcdd6b962a1bf3b539d1fb4657971
ZoranPandovski/al-go-rithms
/strings/string_fundamental/python/isogram.py
914
3.9375
4
""" AAn isogram is a word that has no repeating letters, consecutive or non-consecutive. For example "something" and "brother" are isograms, where as "nothing" and "sister" are not. Below method compares the length of the string with the length (or size) of the set of the same string. The set of the string removes all duplicates, therefore if it is equal to the original string, then its an isogram """ # Function to check if string is an isogram def check_isogram(string_to_be_evaluated): if len(string_to_be_evaluated) == len(set(string_to_be_evaluated.lower())): return True return False if __name__ == '__main__': string_one = input("Enter string to check if it's an isogram:") is_isogram = check_isogram(string_one) if check_isogram: print("The string has no repeated letters and is therefore an Isogram.") else: print("The string is not an Isogram.")
55cd3cc803653d478e6da1b731c2a27a117fda0e
ZoranPandovski/al-go-rithms
/dynamic_programing/Python/Merge Elements/mergeElements.py
1,608
3.875
4
""" Description You are given N elements, in an array A. You can take any 2 consecutive elements a and b and merge them. On merging you get a single element with value (a+b)%100 and this process costs you a*b. After merging you will place this element in place of those 2 elements. If the sequence is [A1, A2, A3, A4] and you merge A2 and A3, you incur a cost of A2*A3 and the array becomes [A1, (A2+A3)%100, A4]. Find the Minimum cost to merge all the elements into a single element. """ def mergeElements(l, r): if l == r: return 0 if dp[l][r] == -1: total = 0 for i in range(l, r + 1): total += arr[i] summ = 0 for mid in range(l, r): summ += arr[mid] ans = min( ans, mergeElements(l, mid) + mergeElements(mid + 1, r) + (summ) * (total - summ), ) dp[l][r] = ans return dp[l][r] n = int(input()) arr = [int(x) for x in input().split()] dp = [[-1 for i in range(4001)] for j in range(4001)] print(mergeElements(0, n - 1)) """ The nice observation here is the value of the Final element remains fixed and is the sum of the range %100. So we can design a DP with the states DP(l,r) = minimum cost to merge the segment into one element. Now range (l,r) will form one element from 2 elements in the final step. So let's say the (l, mid) and (mid+1,r) range equivalents merge and produce the final element. So DP(l,r) = min(DP(l,mid) + DP(mid+1,r) + (sum(l,mid)%100)*(sum(mid+1,r)%100) ) for all mid in range [l,r). """
3a74ac60744dc09b2459c9555e9989cf1c19731c
ZoranPandovski/al-go-rithms
/sort/python/cyclesort.py
1,607
4.0625
4
# Code contributed by Honey Sharma from __future__ import print_function def cycle_sort(array): ans = 0 # Pass through the array to find cycles to rotate. for cycleStart in range(0, len(array) - 1): item = array[cycleStart] # finding the position for putting the item. pos = cycleStart for i in range(cycleStart + 1, len(array)): if array[i] < item: pos += 1 # If the item is already present-not a cycle. if pos == cycleStart: continue # Otherwise, put the item there or right after any duplicates. while item == array[pos]: pos += 1 array[pos], item = item, array[pos] ans += 1 # Rotate the rest of the cycle. while pos != cycleStart: # Find where to put the item. pos = cycleStart for i in range(cycleStart + 1, len(array)): if array[i] < item: pos += 1 # Put the item there or right after any duplicates. while item == array[pos]: pos += 1 array[pos], item = item, array[pos] ans += 1 return ans # Main Code starts here if __name__ == '__main__': try: raw_input # Python 2 except NameError: raw_input = input # Python 3 user_input = input('Enter numbers separated by a comma:\n') unsorted = [int(item) for item in user_input.split(',')] n = len(unsorted) cycle_sort(unsorted) print("After sort : ") for i in range(0, n): print(unsorted[i], end=' ')
45d1f94946fb66eb792a8dbc8cbdb84c216d381c
ZoranPandovski/al-go-rithms
/math/leapyear_python.py
491
4.25
4
'''Leap year or not''' def leapyear(year): if (year % 4 == 0) and (year % 100 != 0) or (year % 400==0) : #checking for leap year print(year," is a leap year") #input is a leap year else: print(year," is not a leap year") #input is not a leap year year=int(input("Enter the year: ")) while year<=999 or year>=10000: #check whether the year is four digit number or not print("Enter a year having four digits.") year=int(input("Enter the year: ")) leapyear(year)
1ac38039d03e38ccfcc6d5036cb919f6b65bf53d
ZoranPandovski/al-go-rithms
/greedy/knapsack_problem/python/fractional_knapsack.py3
2,286
4.09375
4
# Uses python3 ''' A thief finds much more loot than his bag can fit. Help him to find the most valuable combination of items assuming that any fraction of a loot item can be put into his bag. Problem Description Task. The goal of this code problem is to implement an algorithm for the fractional knapsack problem. Input Format. The first line of the input contains the number 𝑛 of items and the capacity 𝑊 of a knapsack. The next 𝑛 lines define the values and weights of the items. The 𝑖-th line contains integers 𝑣𝑖 and 𝑤𝑖—the value and the weight of 𝑖-th item, respectively. Constraints. 1 ≤ 𝑛 ≤ 10^3 , 0 ≤ 𝑊 ≤2·10^6 ; 0 ≤ 𝑣𝑖 ≤ 2·10^6 , 0 <𝑤𝑖 ≤ 2·10^6 for all 1 ≤ 𝑖 ≤ 𝑛.Allthe numbers are integers. Output Format. Output the maximal value of fractions of items that fit into the knapsack. The absolute value of the difference between the answer of your program and the optimal value should be at most 10−3. To ensure this, output your answer with at least four digits after the decimal point (otherwise your answer, while being computed correctly, can turn out to be wrong because of rounding issues). Sample 1. Input: 3 50 60 20 100 50 120 30 Output: 180.0000 To achieve the value 180, we take the first item and the third item into the bag. Sample 2. Input: 1 10 500 30 Output: 166.6667 Here, we just take one third of the only available item. ''' import sys def get_optimal_value(capacity, weights, values): value = 0 weight = 0 ratio = [] for i in range(len(weights)): ratio.append(values[i]/weights[i]) for i in range(len(weights)): if capacity > 0: if weights[ratio.index(max(ratio))] > 0: weight = min(weights[ratio.index(max(ratio))],capacity) value = value + max(ratio) * weight capacity = capacity - weight weights[ratio.index(max(ratio))] -= weight else: weights.remove(weights[ratio.index(max(ratio))]) ratio.remove(max(ratio)) else: pass return value if __name__ == "__main__": data = list(map(int, sys.stdin.read().split())) n, capacity = data[0:2] values = data[2:(2 * n + 2):2] weights = data[3:(2 * n + 2):2] opt_value = get_optimal_value(capacity, weights, values) print("{:.10f}".format(opt_value))
1662be7bf8c965ecd8f3aadaa27968792f307050
ZoranPandovski/al-go-rithms
/data_structures/Arrays/Python/Sparse_Array.py
2,115
4.03125
4
# Sparse Arrays Hackerrank # There is a collection of input strings and a collections of query strings . For each query strings , determine how many times it occurs in the list of input strings. # For example given input strings =[ab,ab,abc] and queries=[ab,abc,bc], we find 2 instances of ab, 1 instance of abc and 0 instance of bc .For ech query, we add an element to our return array, results =[2,1,0]. # Function Description # Complete the function matchingStrings in the editor below. The function must return an array of integers representing the frequency of occurence of each query string in strings. # matchingStrings has the following parameters # strings- an array of strings to search # queries an array of query strings # Input Format # the first line contains and integer n, the size of strings. Each of the next n lines contains a string strings[i]. The next line line contains q, the size of queries. Each of the next q lines contains a string queries[i]. #Constraints #1<=n,q<=1000 #1<=|strings[i]|,|queries[i]|<=20. #Output Format # Return an internal array of the results of all queries in order. #!/bin/python3 import math import os import random import re import sys from collections import Counter # Complete the matchingStrings function below. def matchingStrings(strings, queries): #result = [] count_dict = Counter(strings) #for k in queries: #if k in count_dict: #result.append(count_dict[k]) #else: #result.append(0) result = [count_dict[x] if x in count_dict else 0 for x in queries ] return result if __name__ == '__main__': fptr = open(os.environ['OUTPUT_PATH'], 'w') strings_count = int(input()) strings = [] for _ in range(strings_count): strings_item = input() strings.append(strings_item) queries_count = int(input()) queries = [] for _ in range(queries_count): queries_item = input() queries.append(queries_item) res = matchingStrings(strings, queries) fptr.write('\n'.join(map(str, res))) fptr.write('\n') fptr.close()
533b8c91219f7c4a2e51f952f88581edb8446fd5
ZoranPandovski/al-go-rithms
/sort/python/merge_sort.py
1,809
4.25
4
""" This is a pure python implementation of the merge sort algorithm For doctests run following command: python -m doctest -v merge_sort.py or python3 -m doctest -v merge_sort.py For manual testing run: python merge_sort.py """ from __future__ import print_function def merge_sort(collection): """Pure implementation of the merge sort algorithm in Python :param collection: some mutable ordered collection with heterogeneous comparable items inside :return: the same collection ordered by ascending Examples: >>> merge_sort([0, 5, 3, 2, 2]) [0, 2, 2, 3, 5] >>> merge_sort([]) [] >>> merge_sort([-2, -5, -45]) [-45, -5, -2] """ length = len(collection) if length > 1: midpoint = length // 2 left_half = merge_sort(collection[:midpoint]) right_half = merge_sort(collection[midpoint:]) i = 0 j = 0 k = 0 left_length = len(left_half) right_length = len(right_half) while i < left_length and j < right_length: if left_half[i] < right_half[j]: collection[k] = left_half[i] i += 1 else: collection[k] = right_half[j] j += 1 k += 1 while i < left_length: collection[k] = left_half[i] i += 1 k += 1 while j < right_length: collection[k] = right_half[j] j += 1 k += 1 return collection if __name__ == '__main__': try: raw_input # Python 2 except NameError: raw_input = input # Python 3 user_input = input('Enter numbers separated by a comma:\n').strip() unsorted = [int(item) for item in user_input.split(',')] print(merge_sort(unsorted))
d27b63e66d6e68682ae87204a60235d0846eb0dc
ZoranPandovski/al-go-rithms
/dp/kadane-_algorithm/py/TrieToSucceed_kadane.py
1,375
4
4
#!/usr/bin/python3 """ This module contains an implementation of Kadane's algorithm to determine the maximum sum of a subarray. Doctests included. Please use docstring as example to use algorithm. """ def kadane(list_obj=None): """ Find maximum sum of a subarray :param list list_int: list of objs :return: maximum sum of subarray :rtype: int DOCTESTS -------- Test 1 (list of ints): >>> print(kadane([-1, 2, 3, -4, 5, -6])) 6 Test 2 (list of ints): >>> print(kadane([-1, 2, 3, -6, 5, -6])) 5 Test 3 (list of ints): >>> print(kadane([3, 2, 3, -7, 5, -6])) 8 Test 4 (invalid argument type): >>> print(kadane()) Traceback (most recent call last): ... TypeError: input must be of type list Test 5 (empty list): >>> print(kadane([])) Traceback (most recent call last): ... ValueError: list must not be empty """ if type(list_obj) is not list: raise TypeError("input must be of type list") if not list_obj: raise ValueError("list must not be empty") max_sum, cur_max = list_obj[0], 0 size = len(list_obj) for idx, val in enumerate(list_obj): cur_max = max(val, val + cur_max) max_sum = max(max_sum, cur_max) return max_sum if __name__ == '__main__': import doctest doctest.testmod()
886bbc01342eb81c8b78ed2f85c20fff0be2144c
ZoranPandovski/al-go-rithms
/dp/sudoku_solver/sudoku-solver.py
2,292
3.59375
4
'''eample input: 1 3 0 6 5 0 8 4 0 0 5 2 0 0 0 0 0 0 0 0 8 7 0 0 0 0 3 1 0 0 3 0 1 0 0 8 0 9 0 0 8 6 3 0 0 5 0 5 0 0 9 0 6 0 0 1 3 0 0 0 0 2 5 0 0 0 0 0 0 0 0 7 4 0 0 5 2 0 6 3 0 0 Output: 3 1 6 5 7 8 4 9 2 5 2 9 1 3 4 7 6 8 4 8 7 6 2 9 5 3 1 2 6 3 4 1 5 9 8 7 9 7 4 8 6 3 1 2 5 8 5 1 7 9 2 6 4 3 1 3 8 9 4 7 2 5 6 6 9 2 3 5 1 8 7 4 7 4 5 2 8 6 3 1 9''' def print_grid(sgrid): for i in range(9): for j in range(9): print(sgrid[i][j],end=" ") return # def print_grid(arr): # for i in range(9): # for j in range(9): # print(arr[i][j],end=" ") def find_empty_location(arr,l): for row in range(9): for col in range(9): if(arr[row][col]==0): l[0]=row l[1]=col return True return False def used_in_row(arr,row,num): for i in range(9): if(arr[row][i] == num): return True return False def used_in_col(arr,col,num): for i in range(9): if(arr[i][col] == num): return True return False def used_in_box(arr,row,col,num): for i in range(3): for j in range(3): if(arr[i+row][j+col] == num): return True return False def check_location_is_safe(arr,row,col,num): return not used_in_row(arr,row,num) and not used_in_col(arr,col,num) and not used_in_box(arr,row - row%3,col - col%3,num) def solve_sudoku(arr): l=[0,0] if(not find_empty_location(arr,l)): return True row=l[0] col=l[1] for num in range(1,10): if(check_location_is_safe(arr,row,col,num)): arr[row][col]=num if(solve_sudoku(arr)): return True arr[row][col] = 0 return False T=int(input()) for cases in range(T): flag=0 grid=[] temp=list(map(int,input().split())) count=0 for i in range(9): tarr=[] for j in range(9): tarr.append(temp[count]) count+=1 grid.append(tarr) # print(sgrid) if solve_sudoku(grid): print_grid(grid) print() else: print("No solution exists")
7e8547992586b2e7459d641d80dfd674e1b60167
ZoranPandovski/al-go-rithms
/math/Solve_and_reduce_expression.py
623
3.6875
4
""" Input: 7/5+13/5 output: 4/1 """ import re def gcd(a, b): if (a == 0): return b; return gcd(b % a, a); def lowest(den3, num3): common_factor = gcd(num3, den3); den3 = int(den3 / common_factor); num3 = int(num3 / common_factor); print(num3, "/", den3,sep=""); def addFraction(num1, den1, num2, den2): den3 = gcd(den1, den2); den3 = (den1 * den2) / den3; num3 = ((num1) * (den3 / den1) + (num2) * (den3 / den2)); lowest(den3, num3); print("write expression:") exp=input() array1 = re.findall(r'[0-9]+', exp) array=list(map(int, array1)) addFraction(array[0], array[1], array[2], array[3]);
9254bf1c91742bbe2e21485f36b37289db10445e
ZoranPandovski/al-go-rithms
/math/is_prime/python/prime.py
199
3.640625
4
def is_prime(n): if n < 2: return False i = 2 while i * i <= n: if n % i == 0: return False i += 1 return True def test(): assert is_prime(1009) if __name__ == "__main__": test()
3f42b4dae4f5c423df9b7b7b7c70024de72860b0
ZoranPandovski/al-go-rithms
/math/armstrong_number/Python/armstrong.py
168
3.984375
4
n = str(input("Enter Number: ")) s = 0 for i in n: s = s + int(i)**3 if(s == int(n)): print("Number is armstrong.") else: print("Number is not armstrong.")
60a865bdf0aae15b18cca5aaffa883f8dd0c5218
ZoranPandovski/al-go-rithms
/data_structures/Graphs/Dijkstras Algorithm/dijkstras-algorithm.py
1,666
3.765625
4
def buildGraph(): graph = {} graph['start'] = {} graph['start']['a'] = 6 graph['start']['b'] = 2 graph['a'] = {} graph['a']['fin'] = 1 graph['b'] = {} graph['b']['a'] = 3 graph['b']['fin'] = 5 graph['fin'] = {} return graph def buildCost(): cost = {} cost['a'] = 6 cost['b'] = 2 cost['fin'] = float('inf') return cost def buildParent(): parent = {} parent['a'] = 'start' parent['b'] = 'start' parent['fin'] = None return parent def findLowestCostNode(cost, processedNodes): lowestCost = float('inf') lowestCostNode = None for node in cost: nodeCost = cost[node] if nodeCost < lowestCost and node not in processedNodes: lowestCost = nodeCost lowestCostNode = node return lowestCostNode def dijkstraAlgo(): graph = buildGraph() cost = buildCost() parent = buildParent() processedNodes = [] node = findLowestCostNode(cost, processedNodes) while node is not None: nodeCost = cost[node] members = graph[node] for member in members: newCost = nodeCost + members[member] if newCost < cost[member]: cost[member] = newCost parent[member] = node processedNodes.append(node) node = findLowestCostNode(cost, processedNodes) return cost, parent cost, parent = dijkstraAlgo() print('Shortest cost is', cost['fin']) finParent = parent['fin'] tree = ['fin', finParent] while parent.get(finParent): finParent = parent[finParent] tree.append(finParent) print('Shortest path is', tree[::-1])
ec1925a19de375e13acf46369c8ffe255f2ea08a
ZoranPandovski/al-go-rithms
/greedy/kruskal's_algorithm/python/ArthurFortes/readFile.py
1,059
3.625
4
""" Computer Science Department (SCC) Mathematics and Computer Science Institute (ICMC) University of Sao Paulo (USP) Algorithms Projects Teacher: Gustavo Batista Author: Arthur Fortes da Costa Method to Read a File """ from math import * def readFile(string): arq = open(string, 'r') text = arq.readlines() l = [] k = [0] p = [0] w = [] distance = [] no = [] for line in text: k = [line[:line.find("\t")].strip(), line[line.find("\t"):].strip()] l.append(k) resp = open("dist.txt", 'w') for i in range(len(l)): no.append(str(i)) a, b = l[i] distance.append((a, b)) for j in range(i, l.__len__()): c, d = l[j] if i != j: d = sqrt(((float(c) - float(a)) ** 2) + ((float(d) - float(b)) ** 2)) p = (str(i), str(j), d) w.append(p) for i in range(len(w)): a, b, c = w[i] resp.write(str(a) + "\t" + str(b) + "\t" + str(c) + "\n") resp.close() arq.close() return w, no, distance
97200bfc7b31240aeef5248db17a801ec55ef68e
ZoranPandovski/al-go-rithms
/math/prime-numbers/prime.py
233
4.0625
4
value = int(input("Enter the value...")) count = 0 print("The prime numbers till ", value ," are ") for i in range(2,value): for j in range(2,value): if(i%j == 0 and i!=j): count = count + 1 if count < 1: print(i) count = 0
cfec1c64f1130d368ee4ca0edc23ff10ea4e7b65
ZoranPandovski/al-go-rithms
/games/Python/Pong Game/ball.py
659
3.75
4
from turtle import Turtle class Ball(Turtle): def __init__(self): super().__init__() self.penup() self.color("blue violet") self.shape("circle") self.move_speed=0.1 self.x_move = 10 self.y_move = 10 def ball_move(self): x_pos=self.xcor() + self.x_move y_pos=self.ycor() + self.y_move self.goto(x=x_pos,y=y_pos) def bounce_y(self): self.y_move *= -1 def bounce_x(self): self.x_move *= -1 self.move_speed *= 0.9 def reset_position(self): self.goto(0,0) self.move_speed=0.1 self.bounce_x()
bb90042ffc1e7d832768e6ee7b639954561e67be
ZoranPandovski/al-go-rithms
/sort/bogo_sort/python/bogoSort.py
425
3.546875
4
from random import shuffle testAr = [1,3,4,5,2,7,6,9,8] flag = False count = 0 while not flag: count += 1 for i in range(len(testAr)): if i == len(testAr) - 1: flag = True print("success", testAr, "run number: ", count) break if testAr[i] > testAr[i+1]: shuffle(testAr) print("failure", testAr, "run number: ", count) break
f8c0f33e64a308696a462957d6dcf9107f3deb2a
ZoranPandovski/al-go-rithms
/sort/bitonic_sort/python/bitonic_sort.py
1,124
3.859375
4
# Author: thisHermit ASCENDING = 1 DESCENDING = 0 N = 5 def main(): input_array = [5, 4, 3, 2, 5] a = input_array.copy() # sort the array sort(a, N) # test and show assert a, sorted(input_array) show(a, N) def exchange(i, j, a, n): a[i], a[j] = a[j], a[i] def compare(i, j, dirr, a, n): if dirr == (a[i] > a[j]): exchange(i, j, a, n) def bitonicMerge(lo, cnt, dirr, a, n): if cnt > 1: k = cnt // 2 for i in range(lo, lo + k): compare(i, i+k, dirr, a, n) bitonicMerge(lo, k, dirr, a, n) bitonicMerge(lo + k, k, dirr, a, n) def bitonicSort(lo, cnt, dirr, a, n): if cnt > 1: k = cnt // 2 # sort in ascending order bitonicSort(lo, k, ASCENDING, a, n) # sort in descending order bitonicSort(lo + k, k, DESCENDING, a, n) # Merge whole sequence in ascendin/ descending order depending on dirr bitonicMerge(lo, cnt, dirr, a, n) def sort(a, n): bitonicSort(0, N, ASCENDING, a, n) def show(a, n): print(a) if __name__ == '__main__': main()
0fbd0364c4afb58c921db8d3a036916e69b5a2b1
ZoranPandovski/al-go-rithms
/sort/bubble_sort/python/capt-doki_bubble_sort.py
652
4.3125
4
# Python program for implementation of Bubble Sort # TIME COMPLEXITY -- O(N^2) # SPACE COMPLEXITY -- O(1) def bubbleSort(arr): n = len(arr) # Traverse through all array elements for i in range(n): # Last i elements are already in place for j in range(0, n-i-1): # traverse the array from 0 to n-i-1 # Swap if the element found is greater # than the next element if arr[j] > arr[j+1] : arr[j], arr[j+1] = arr[j+1], arr[j] arr = [64, 34, 25, 12, 22, 11, 90] bubbleSort(arr) print ("Sorted array is:") for i in range(len(arr)): print (arr[i])
d52e6e5a19e0be8bdc3f7e5ce36b14caff65cc7e
ZoranPandovski/al-go-rithms
/math/perfect_number/python/is_perfect.py
443
3.890625
4
#!/usr/bin/python3 #Written by Grant Hill from math import sqrt def divisorsum(num): divsum = 0 for i in range(1, int(sqrt(num))): #You only have to calculate up to the square rot of the number. if num % i == 0: divsum += i divsum += num // i return divsum - num #Don't count the number itself when you're calculating the sum of its divisors. def is_perfect(num): return num == divisorsum(num)
f075a3e19dfa1616bd62662f72420468d23c62df
ZoranPandovski/al-go-rithms
/data_structures/Linked_list/Python/ZoranPandovski_Singly_linked_list.py
2,853
4.09375
4
# linked list code # creating a node class node: def __init__(self, data): self.data = data self.next = None class linkedlist: def __init__(self): self.head = None #creating a header def search(self,data): #find the node with the given data in the list list_cp = self count = 0 # the first element has index 0 while (list_cp): if list_cp.head.data == data: return count else: list_cp.deletion(0) count = count + 1 return -1 # if not found in the list, return -1 #inserting a new node at the beginning def push_front(self, new_data): new_node = node(new_data) new_node.next = self.head self.head = new_node #inserting a new node after a node def push_after(self, prev_data, new_data): #checking whether previous node exists position = self.search(prev_data) if position == -1: print('Given node is not found in list.\n') return new_node = node(new_data) #Make next of new Node as next of previous node temp = self.head # issue here, the original list copy won't be remembered for i in range(position-1): temp = temp.next #make next of previous node as new node temp.next = new_node # append new node at the end def push_end(self, new_data): new_node = node(new_data) #If the Linked List is empty, then make the new node as head if self.head is None: self.head = new_node return #otherwise traverse to the last node end = self.head while (end.next): end = end.next #Change the next of last node end.next = new_node def deletion(self, position): #check if linked list is empty if self.head == None: return # store header temp = self.head # If header is removed if position == 0: self.head = temp.next temp = None return #previous node to the node to be deleted for i in range(position -1 ): temp = temp.next if temp is None: break # If position is more than number of nodes if temp is None and temp.next is None: return # store pointer to the next of node to be deleted next = temp.next.next # remove node from the linked list temp.next = None temp.next = next def printing(self): temp = self.head while temp is not None: print(temp.data) temp = temp.next
044018b29df8e73d4c64824373622a221ba5854a
ZoranPandovski/al-go-rithms
/data_structures/Stack/Python/Next_Greatest_Element_Using_Stack.py
3,631
4.34375
4
class Stack: def __init__(self, stack = []): """ initialises the stack: 1. if a list of elements is passed --> initailises the stack with list 2. if no parameter is passed --> initailises the stack with empty list """ self.stack = stack def size(self): """ return the size of the stack """ return len(self.stack) def empty(self): """ checks if the stack is empty and returns a boolean value """ if self.size() == 0: return True return False def top(self): """ returns the top element of the stack pre-condition: stack should not be empty returns -1 in case the stack is empty """ if not self.empty(): return self.stack[self.size()-1] return -1 def push(self,element): """ push in stack is used to add element on top of the stack """ self.stack.append(element) def pop(self): """ pop in stack is used to remove element from the top. pre-condition: stack should be empty In case of empty stack return -1 """ removed_element = self.stack.pop() return removed_element def rev(self): """ This method will reverse the stack that is it will bring the bottom element to top and vice versa. pre-conditon: stack should not empty **This method is added to suit the problem(not a part of traditional stack implementation)** """ if self.size!=0: self.stack.reverse() ''' PROBLEM: for given list we have to replace the element with the greatest element closest to it's right otherwise replace it with -1. example: given : [1,5,3,4] for the first element 1(index 0) 5, 3,4 are greater but we replace it with 5 which is the greatest number closest to it. likewise for 5(index 1) 3,4 are not greater than 5 so it will be replaced by -1 and so on.. answer: [5,-1,4,-1] ''' #driver code given_list = [1,5,3,4] #initally give list of element ans_list = [] #initalised answer list comparison_stack= Stack() #empty stack for comparison for i in range(len(given_list)-1,-1,-1): #taking the list is reverse order if comparison_stack.empty()==True: ans_list.append(-1) #empty stack symbolises no element is greater so append -1 else: if comparison_stack.top() > given_list[i]: # check if top is greater ans_list.append(comparison_stack.top()) # top is greater than append top into ans else: while ((not comparison_stack.empty()) and comparison_stack.top()<=given_list[i]): # pop until we reach an element greater than given element # or till the stack is exhausted comparison_stack.pop() if comparison_stack.empty(): ans_list.append(-1) #append -1 if the stack is exhausted else: ans_list.append(comparison_stack.top()) #otherwise append the top element comparison_stack.push(given_list[i]) #append the element from the given_list into the stack for further comparisons ans_list.reverse() #note: ans_list is present in revese form, so reverse it before printing out. print("The given list: ", given_list) print("-----Next Greatest Element(NGE)-----") print("The NGE List: ", ans_list)
af97e6fc6ad3275e8521a9f96732c47c000abe6b
ZoranPandovski/al-go-rithms
/data_structures/avl_tree/Python/avl.py
8,099
3.53125
4
from __future__ import print_function import random import math outputdebug = False def debug(msg): if outputdebug: print(msg) class Node(): def __init__(self, key): self.key = key self.left = None self.right = None class AVLTree(): def __init__(self, *args): self.node = None self.height = -1 self.balance = 0; if len(args) == 1: for i in args[0]: self.insert(i) def height(self): if self.node: return self.node.height else: return 0 def is_leaf(self): return (self.height == 0) def insert(self, key): tree = self.node newnode = Node(key) if tree == None: self.node = newnode self.node.left = AVLTree() self.node.right = AVLTree() debug("Inserted key [" + str(key) + "]") elif key < tree.key: self.node.left.insert(key) elif key > tree.key: self.node.right.insert(key) else: debug("Key [" + str(key) + "] already in tree.") self.rebalance() def rebalance(self): ''' Rebalance a particular (sub)tree ''' # key inserted. Let's check if we're balanced self.update_heights(False) self.update_balances(False) while self.balance < -1 or self.balance > 1: if self.balance > 1: if self.node.left.balance < 0: self.node.left.lrotate() # we're in case II self.update_heights() self.update_balances() self.rrotate() self.update_heights() self.update_balances() if self.balance < -1: if self.node.right.balance > 0: self.node.right.rrotate() # we're in case III self.update_heights() self.update_balances() self.lrotate() self.update_heights() self.update_balances() def rrotate(self): # Rotate left pivoting on self debug ('Rotating ' + str(self.node.key) + ' right') A = self.node B = self.node.left.node T = B.right.node self.node = B B.right.node = A A.left.node = T def lrotate(self): # Rotate left pivoting on self debug ('Rotating ' + str(self.node.key) + ' left') A = self.node B = self.node.right.node T = B.left.node self.node = B B.left.node = A A.right.node = T def update_heights(self, recurse=True): if not self.node == None: if recurse: if self.node.left != None: self.node.left.update_heights() if self.node.right != None: self.node.right.update_heights() self.height = max(self.node.left.height, self.node.right.height) + 1 else: self.height = -1 def update_balances(self, recurse=True): if not self.node == None: if recurse: if self.node.left != None: self.node.left.update_balances() if self.node.right != None: self.node.right.update_balances() self.balance = self.node.left.height - self.node.right.height else: self.balance = 0 def delete(self, key): # debug("Trying to delete at node: " + str(self.node.key)) if self.node != None: if self.node.key == key: debug("Deleting ... " + str(key)) if self.node.left.node == None and self.node.right.node == None: self.node = None # leaves can be killed at will # if only one subtree, take that elif self.node.left.node == None: self.node = self.node.right.node elif self.node.right.node == None: self.node = self.node.left.node # worst-case: both children present. Find logical successor else: replacement = self.logical_successor(self.node) if replacement != None: # sanity check debug("Found replacement for " + str(key) + " -> " + str(replacement.key)) self.node.key = replacement.key # replaced. Now delete the key from right child self.node.right.delete(replacement.key) self.rebalance() return elif key < self.node.key: self.node.left.delete(key) elif key > self.node.key: self.node.right.delete(key) self.rebalance() else: return def logical_predecessor(self, node): ''' Find the biggest valued node in LEFT child ''' node = node.left.node if node != None: while node.right != None: if node.right.node == None: return node else: node = node.right.node return node def logical_successor(self, node): ''' Find the smallese valued node in RIGHT child ''' node = node.right.node if node != None: # just a sanity check while node.left != None: debug("LS: traversing: " + str(node.key)) if node.left.node == None: return node else: node = node.left.node return node def check_balanced(self): if self == None or self.node == None: return True # We always need to make sure we are balanced self.update_heights() self.update_balances() return ((abs(self.balance) < 2) and self.node.left.check_balanced() and self.node.right.check_balanced()) def inorder_traverse(self): if self.node == None: return [] inlist = [] l = self.node.left.inorder_traverse() for i in l: inlist.append(i) inlist.append(self.node.key) l = self.node.right.inorder_traverse() for i in l: inlist.append(i) return inlist def display(self, level=0, pref=''): ''' Display the whole tree. Uses recursive def. TODO: create a better display using breadth-first search ''' self.update_heights() # Must update heights before balances self.update_balances() if(self.node != None): print('-' * level * 2, pref, self.node.key, "[" + str(self.height) + ":" + str(self.balance) + "]", 'L' if self.is_leaf() else ' ') if self.node.left != None: self.node.left.display(level + 1, '<') if self.node.left != None: self.node.right.display(level + 1, '>') # Usage example if __name__ == "__main__": a = AVLTree() print("----- Inserting -------") #inlist = [5, 2, 12, -4, 3, 21, 19, 25] inlist = [7, 5, 2, 6, 3, 4, 1, 8, 9, 0] for i in inlist: a.insert(i) a.display() print("----- Deleting -------") a.delete(3) a.delete(4) # a.delete(5) a.display() print() print("Input :", inlist) print("deleting ... ", 3) print("deleting ... ", 4) print("Inorder traversal:", a.inorder_traverse())
9431f69eefa62014f235d325bfe8e5ca5caaef15
ZoranPandovski/al-go-rithms
/data_structures/Stack/Python/Rain_Water_Trapping_Using_Stack.py
3,764
4.21875
4
class Stack: def __init__(self, stack = []): """ initialises the stack: 1. if a list of elements is passed --> initailises the stack with list 2. if no parameter is passed --> initailises the stack with empty list """ self.stack = stack def size(self): """ return the size of the stack """ return len(self.stack) def empty(self): """ checks if the stack is empty and returns a boolean value """ if self.size() == 0: return True return False def top(self): """ returns the top element of the stack pre-condition: stack should not be empty returns -1 in case the stack is empty """ if not self.empty(): return self.stack[self.size()-1] return -1 def push(self,element): """ push in stack is used to add element on top of the stack """ self.stack.append(element) def pop(self): """ pop in stack is used to remove element from the top. pre-condition: stack should be empty In case of empty stack return -1 """ removed_element = self.stack.pop() return removed_element def rev(self): """ This method will reverse the stack that is it will bring the bottom element to top and vice versa. pre-conditon: stack should not empty **This method is added to suit the problem(not a part of traditional stack implementation)** """ if self.size!=0: self.stack.reverse() """ PROBLEM: Trapping Rainwater Problem states that we need to find the maximum units of rainwater that can be stored between the bars of different sizes where the sizes of bars are given as an input. Example: given input: [3,2,0,2,0,4] ---> answer: 8 0 0 x x x x 0 0 0 x 0 x 0 0 0 x 0 x 0 ----------------------------------- Here 0 represent the blocks and number of x is the total area where water can be trapped. """ #driver code input_height = [3,2,0,2,0,4] #input height water_above_block = [] #water above each block i max_left_height = Stack() #maximum height to the left of each block i max_right_height = Stack([]) #maximum height to right of each black i sum_water_trapped = 0 #sum of the area of trapped water #store all the maximum left height of block i in stack for i in range(len(input_height)): if max_left_height.empty(): #if stack empty append block height max_left_height.push(input_height[i]) else: #if stack not empty append max(top, block height) max_left_height.push(max(max_left_height.top(),input_height[i])) #store all the maximum right height of block i in stack for i in range(len(input_height)-1,-1,-1): #note: reverse travesal if max_right_height.empty(): #if stack empty append black height max_right_height.push(input_height[i]) else: #if stack not empty append max(top, block height) max_right_height.push(max(max_right_height.top(),input_height[i])) max_right_height.rev() #water above block = min(left height, right height) - input height for i in range(len(input_height)): water_above_block.append(min(max_left_height.stack[i], max_right_height.stack[i]) - input_height[i]) #sum up water above each block for i in range(len(water_above_block)): sum_water_trapped+=water_above_block[i] print("Total area of trapped water: ", sum_water_trapped)
2e510f7f607b16dc2c2e5c12f0f087ad49a70b1f
ZoranPandovski/al-go-rithms
/strings/string_search/z_algorithm/python/Z_algorithm.py
3,119
3.796875
4
#!/bin/python3 import sys, string from random import * from timeit import default_timer as timer def randstr(N,alphabet=string.ascii_lowercase): l=len(alphabet) return "".join( alphabet[randint(0,l-1)] for _ in range(N)) def timefunc(func, *args, **kwargs): """Time a function. args: iterations=1 Usage example: timeit(myfunc, 1, b=2) """ try: iterations = kwargs.pop('iterations') except KeyError: iterations = 1 elapsed = sys.maxsize start = timer() for _ in range(iterations): result = func(*args, **kwargs) elapsed = (timer() - start)/iterations print(('{}() : {:.9f}'.format(func.__name__, elapsed))) return result #res=timefunc( searchKMP, S, P, iterations=rep) #if(res!=res0): print("Wrong") def getZ_naive(S): N=len(S) Z=[0]*N for i in range(1,N): k=0 while( i+k<N and S[i+k]==S[k]): k+=1 Z[i]=k return Z #int L = 0, R = 0; #for (int i = 1; i < n; i++) { # if (i > R) { # L = R = i; # while (R < n && s[R-L] == s[R]) R++; # z[i] = R-L; R--; # } else { # int k = i-L; # if (z[k] < R-i+1) z[i] = z[k]; # else { # L = i; # while (R < n && s[R-L] == s[R]) R++; # z[i] = R-L; R--; # } # } #} def getZ_0(S): N=len(S) Z=[0]*N L,R=0,0 for i in range(1,N): if i>R: L=R=i while R<N and S[R-L]==S[R]: R+=1 Z[i]=R-L R-=1 else: k=i-L if Z[k]<R-i+1: Z[i]=Z[k] else: L=i while R<N and S[R-L]==S[R]: R+=1 Z[i]=R-L R-=1 return Z #from rookie rank 4, dna #not optimal.... def getZ_1(S): N=len(S) Z=[0]*N L,R=-1,-1 for i in range(N): if i<R: Z[i]=min(R-i, Z[i-L]) while i+Z[i]<N and S[Z[i]]==S[i+Z[i]]: Z[i]+=1 if i+Z[i]>R: L=i R=i+Z[i] Z[0]=0 #due to it=N as result return Z #void z_func(string s){ # int n = s.length(); # int z[n]; # z[0] = 0; # # for (int i = 1, l = 0, r = 1; i < n; i++, r = i < r ? r : i) # for (z[i] = min(r - i, z[i - l]); i + z[i]<n && s[i + z[i]] == s[z[i]]; z[i]++, r = i + z[i], l = i); # # for (int i = 0; i < n; i++) # cout << z[i] << " "; #} def getZ_2(S): N=len(S) Z=[0]*N i=1 L=0 R=1 while i<N: Z[i]=min(R-i,Z[i-L]) while i+Z[i]<N and S[i+Z[i]]==S[Z[i]]: Z[i]+=1 R=i+Z[i] L=i i+=1 if i>=R: R=i return Z if __name__ == "__main__": alpha="AB" #alpha=string.ascii_lowercase S = randstr(30,alphabet=alpha) #S=['A']*10000 rep=1 print(S) res0=timefunc( getZ_naive, S, iterations=rep) print(res0) res=timefunc( getZ_0, S, iterations=rep) print(res0==res) res=timefunc( getZ_1, S, iterations=rep) print(res0==res) res=timefunc( getZ_2, S, iterations=rep) print(res0==res)
0b275806d4228c967856b0ff6995201b7af57e5e
ZoranPandovski/al-go-rithms
/data_structures/Graphs/graph/Python/closeness_centrality.py
1,585
4.28125
4
""" Problem : Calculate the closeness centrality of the nodes of the given network In general, centrality identifies the most important vertices of the graph. There are various measures for centrality of a node in the network For more details : https://en.wikipedia.org/wiki/Closeness_centrality Formula : let C(x) be the closeness centrality of the node x. C(x) = (N-1) / (sum of shortest paths between x & all nodes in the graph) """ def bfs(x: int) -> int: """ Does BFS traversal from node x Returns the sum of all shortest distances """ sum_d = 0 # store the shortest distance from x d = [-1 for _ in range(len(adj))] # queue queue = [] queue.append(x) d[x] = 0 while len(queue) != 0: front = queue[0] queue.pop(0) for v in adj[front]: if d[v] == -1: queue.append(v) d[v] = d[front] + 1 sum_d += d[v] return sum_d def closeness_centrality(): """ calculates the closeness centrality Returns: A list containing the closeness centrality of all nodes """ n = len(adj) closeness_centrality = [] for i in range(len(adj)): closeness_centrality.append((n - 1) / bfs(i)) return closeness_centrality if __name__ == "__main__": global adj adj = [[] for _ in range(5)] adj[0] = [1, 3] adj[1] = [0, 2, 4] adj[2] = [1] adj[3] = [0, 4] adj[4] = [1, 3] closeness_centrality = closeness_centrality() print("Closeness centrality : {}".format(closeness_centrality))
328bdb24d195acced22c6e29cb020363c28d6873
ZoranPandovski/al-go-rithms
/data_structures/b_tree/Python/binary_search_tree.py
1,810
3.984375
4
""" Binary Search Tree """ from __future__ import print_function import random # Defining node class Node(object): def __init__(self,val=None): self.val = val self.left = None self.right = None # Operations performed on the tree class Tree(object): def insert(self,root,val): if root == None: root = Node(val=val) return root if(root.val >= val): root.left = self.insert(root.left,val) elif (root.val < val): root.right = self.insert(root.right,val) return root def preorder(self,root): if root != None: print(root.val) self.preorder(root.left) self.preorder(root.right) def postorder(self,root): if root != None: self.postorder(root.left) self.postorder(root.right) print(root.val) def inorder(self,root): if root != None: self.inorder(root.left) print(root.val) self.inorder(root.right) def testcaseBST(self): root = None binaryTree = BinaryTree() # noqa: F821 -- Missing imports binaryTree.insert(root, 5) binaryTree.insert(root, 3) binaryTree.insert(root, 2) binaryTree.insert(root, 4) binaryTree.insert(root, 6) return binaryTree def testcaseNonBST(self): root = Node(3) l_h1 = Node(6) r_h1 = Node(8) root.left = l_h1 root.right = r_h1 l1_h2 = Node(7) l_h1.left = l1_h2 l_h1.right = None l1_h2.left = l1_h2.right = None l3_h2 = Node(5) l4_h2 = Node(1) l3_h2.left = l3_h2.right = l4_h2.left = l4_h2.right = None r_h1.left = l3_h2 r_h1.right = l4_h2 return root
9b8696686283cf9e7afea3bf7b1ac976c3233a54
ZoranPandovski/al-go-rithms
/dp/EditDistance/Python/EditDistance.py
1,017
4.15625
4
from __future__ import print_function def editDistance(str1, str2, m , n): # If first string is empty, the only option is to # insert all characters of second string into first if m==0: return n # If second string is empty, the only option is to # remove all characters of first string if n==0: return m # If last characters of two strings are same, nothing # much to do. Ignore last characters and get count for # remaining strings. if str1[m-1]==str2[n-1]: return editDistance(str1,str2,m-1,n-1) # If last characters are not same, consider all three # operations on last character of first string, recursively # compute minimum cost for all three operations and take # minimum of three values. return 1 + min(editDistance(str1, str2, m, n-1), # Insert editDistance(str1, str2, m-1, n), # Remove editDistance(str1, str2, m-1, n-1) # Replace ) # Driver program to test the above function str1 = "sunday" str2 = "saturday" print(editDistance(str1, str2, len(str1), len(str2)))
f8d613b0d04104b43cfbcb315236f24ee81944a2
ZoranPandovski/al-go-rithms
/puzzles/99_Bottles/Python/99_Bottles.py
667
3.71875
4
def Print99Bottles(i): if (i==99) : print("99 bottles of beer on the wall, 99 bottles of beer.") elif (i == 0): print("Take one down and pass it around, no more bottles of beer on the wall.\n" "No more bottles of beer on the wall, no more bottles of beer.\n" "Go to the store and buy some more, 99 bottles of beer on the wall.") return else: print("Take one down and pass it around, {0} bottles of beer on the wall.\n" "{0} bottles of beer on the wall, {0} bottles of beer.".format(i)) Print99Bottles(i-1) Print99Bottles(99)
6ca5f45ba7a6f0ddc1a47345c56b0324b9856b5f
marciogomesfilho/Codes
/ex69.py
883
4.09375
4
#Exercício Python 069: Crie um programa que leia a idade e o sexo de várias pessoas. A cada pessoa cadastrada, # o programa deverá perguntar se o usuário quer ou não continuar. No final, mostre: #A) quantas pessoas tem mais de 18 anos. #B) quantos homens foram cadastrados. #C) quantas mulheres tem menos de 20 anos. idade = 0 sexo = '' continuar = '' maior = homem = mulheres = 0 while True: idade = int(input('Digite sua idade: ')) sexo = str(input('Digite seu sexo: [M/F]: ')).strip().upper() continuar = str(input('Deseja continuar? [S/N]: ')).strip().upper() if idade > 18: maior += 1 if sexo in 'Mm': homem += 1 if sexo in 'Ff' and idade < 20: mulheres += 1 if continuar in 'nN': break print (f'Pessoas com mais de 18 anos: {maior}\nHomens: {homem}\nMulheres com menos de 20 anos: {mulheres}')
4be5dfacfe7bef0176a7be6a3c8fdd7a3a0490a1
marciogomesfilho/Codes
/ex017.py
363
4.03125
4
#Exercício Python 017: Faça um programa que leia o comprimento do cateto oposto e do cateto adjacente de um triângulo retângulo. # Calcule e mostre o comprimento da hipotenusa from math import hypot oposto = float (input('digite o cateto oposto: ')) adja = float (input('digite o cateto adjacente: ')) print ('a hipotenusa é: ', hypot(oposto, adja))
929d70758663d62eef7d69f73ac6bb6c6d6ece9e
marciogomesfilho/Codes
/ex35.py
336
4
4
#Exercício Python 035: #Desenvolva um programa que leia o comprimento de três retas e diga ao usuário se elas podem ou não formar um triângulo. l1 = int (input('digite o comprimento da primeira linha: ')) l2 = int (input('digite o comprimento da segunda linha: ')) l3 = int(input('digite o comprimeto da terceira linha: '))
81807e5f75856d4c7d6e44065c9d13e6d750a75d
marciogomesfilho/Codes
/ex72.py
1,079
4.28125
4
#Exercício Python 072: Crie um programa que tenha uma tupla totalmente preenchida com uma contagem por extenso, de zero até vinte. # Seu programa deverá ler um número pelo teclado (entre 0 e 5) e mostrá-lo por extenso. contagem = ('Zero', 'Um', 'Dois', 'Três', 'Quarto', 'Cinco') numero = int(input('Digite um número entre 0 e 5: ')) while numero not in range (0,6): numero = int(input('Tente novamente: ')) else: print(contagem[numero]) #lanche = ('Hamb', 'suco', 'pizza', 'pudim') #for comida in lanche: # print (f'eu vou comer {comida}') #for cont in range (0,len(lanche)): #print (f'Comi {lanche[cont]}') #for pos, comida in enumerate (lanche): #print (f'eu vou comer {comida} na posicao {pos}') #print (sorted(lanche)) """a = (2,5,4) b = (5,8,1,2) c = a + b print (len(c)) print (c.count(5)) print(c.index(5,1))# o 1 depois, fala pra ele começar a procurar a partir do indx 1 desconsiderando o 0 pessoa = ('gustavo', 39, 'M', 99.88) print (pessoa) del (pessoa) print (pessoa)"""
895d3f62d38d2e1d14df97c53ae74b4df57f684e
marciogomesfilho/Codes
/ex013.py
268
3.78125
4
#Exercício Python 013: Faça um algoritmo que leia o salário de um funcionário e mostre seu novo salário, com 15% de aumento. antigo = float(input('digite seu salário: ')) novo = antigo + (antigo*15/100) print ('seu novo salário é de: {}'.format(novo))
3032a898e64b953ac024bf335623be262c9289f6
marciogomesfilho/Codes
/ex30.py
263
4.03125
4
#Exercício Python 030: Crie um programa que leia um número inteiro e mostre na tela se ele é PAR ou ÍMPAR. numero = int (input('digite um numero inteiro: ')) if numero / 2 % 0 == 0: print ('o numero é par') else: print ('o numero é impar')
acdc8412ad18e3f6fe3bf86a6bf6a2d4bca9aaeb
marciogomesfilho/Codes
/ex023.py
290
3.84375
4
# Exercício Python 023: Faça um programa que leia um número de 0 a 9999 e mostre na tela cada um dos dígitos separados. n = int(input('digite o número: ')) u = n // 1 % 10 d = n // 100 % 10 c = n // 100 % 10 m = n // 1000 % 10 print (u) print (d) print (c) print (m)
bec4691cc3960e641bfaae05bcd7afdce043ffa7
marciogomesfilho/Codes
/ex31.py
420
4.25
4
#Exercício Python 031: Desenvolva um programa que pergunte a distância de uma viagem em Km. # Calcule o preço da passagem, cobrando R$0,50 por Km para viagens de até 200Km e R$0,45 parta viagens mais longas. dist = float(input('digite quantos kms foi a viagem: ')) if dist <= 200: print ('o valor da viagem foi: R${}'.format(dist*0.50)) else: print ('o valor da viagem foi: R${}'.format(dist*0.45))
fb4fc200462f10023d7f470ebd64aadb799c6519
marciogomesfilho/Codes
/ex79.py
627
4.25
4
#Exercício Python 079: Crie um programa onde o usuário possa digitar vários valores numéricos e # cadastre-os em uma lista. Caso o número já exista lá dentro, ele não será adicionado. # No final, serão exibidos todos os valores únicos digitados, em ordem crescente. numeros = list() while True: n = int(input('Digite um numero: ')) if n not in numeros: numeros.append(n) print ('Número adicionado') else: opcao = str(input('Numero repetido! Deseja continuar? [S/N]')) if opcao in 'Nn': break numeros.sort() print (f'Lista de numeros: {numeros}')
916555cdda722fe55eadee5cddd2d3c30e05fae2
marciogomesfilho/Codes
/ex005.py
153
4.0625
4
n = int( (input('digite um número: '))) print ('o sucessor de seu numero é o: ' ,n + 1) print ('o antecessor de seu numero é o : ', n - 1)
399c60589ea352d922f22c5392bb3a41594b6167
marciogomesfilho/Codes
/ex89.py
1,679
4.1875
4
""" """Exercício Python 089: Crie um programa que leia nome e duas notas de vários alunos e guarde tudo em uma lista composta. No final, mostre um boletim contendo a média de cada um e permita que o usuário possa mostrar as notas de cada aluno individualmente. """ """ completa = list() temp = list() resposta = list() media = 0 while True: nome = str(input('Digite o nome do aluno: ')) nota1 = float(input('Digite a 1 nota: ')) nota2 = float(input('Digite a 2 nota: ')) media = (nota1+nota2)/2 temp.append([nome], [nota1, nota2], [media]) completa.append(temp[:]) temp.clear() resposta.append(f'Nome:{nome}||Média:{media}') continuar = str(input('Deseja continuar? (S/N): ')) if continuar in 'Nn': break print (resposta) print(completa) """opcao = str(input('Deseja ver as notas de um aluno em especifico? [S/N]: ')) if opcao in 'Ss': while True: opcao2 = str(input('Digite o nome do aluno ou [N/n] para finalizar: ')).upper() if opcao2 not in 'nN': print (f' O aluno {nome} teve as notas {completa[0][1]} e {completa[0][2]}.') opcao2 = str(input('Digite o nome do aluno ou [N/n] para finalizar: ')).upper() else: break print ('FIM DO PROGRAMA') input() else: print('FIM DO PROGRAMA') input()""""" # ""while True: # opcao3 = str(input('Deseja ver de outro aluno? [S/N]: ')) # opcao3 = str(input('Digite o nome do aluno: ')).upper() # print(f' O aluno {opcao3} teve as notas {completa[0][1]} e {completa[0][2]}.') # if opcao3 in 'Nn': # break""""" """"""
044b06fda913253faaa6ac13b30308aa18c7aa47
th3n0y0u/C2-Random-Number
/main.py
577
4.4375
4
import random print("Coin Flip") # 1 = heads, 2 = tails coin = random.randint(1,2) if(coin == 1): print("Heads") else: print("Tails") # Excecise: Create a code that mimics a dice roll using random numbers. The code of the print what number is "rolled", letting the user what it is. dice = random.randint(1,6) if(dice == 1): print("You rolled a 1") elif(dice == 2): print("You rolled a 2") elif(dice == 3): print("You rolled a 3") elif(dice == 4): print("You rolled a 4") elif(dice == 5): print("You rolled a 5") elif(dice == 6): print("You rolled a 6")
81ceb91cc03c4f87cd556d3458bed0b70547ca59
Android4567/List
/how_many_time_num_occur.py
494
3.890625
4
list1 = [] for i in range(10): val = int(input(f'Enter The {i+1} element to add in the list => ')) list1.append(val) flag = False print(list1) Search_count = int(input('Enter the number to know that occur how many time in thre list => ')) count = 0 for j in list1: if j == Search_count: count += 1 flag = True if flag: print(Search_count,f"accurs, {count} ,in a list") if Search_count not in list1: print('number is not available in list')
95889da882dabe6288fb944360d463ed48d25c1b
shaharavin/FundingSimulator
/landscape_simulator.py
15,277
3.53125
4
from numpy import * from numpy.random import * import matplotlib.pyplot as plt import matplotlib.mlab as mlab import random class BasicLandscape(object): """Base class for landscape simulation. The basic landscape is initialised with random values in the range [0, 1]. Individuals are seeded in random locations and perform countdown-delayed local hill climbing. Individuals contribute to accumulated significance and collective vision. The landscape itself is static, and there is no selection of individuals. """ def __init__(self, size): self.size = size self.matrix = rand((size, size)) self.vision = zeros((size, size)) def generate_countdowns(self, num=1): """Generate num integer countdowns, evenly distributed between [avg_countdown / 2, avg_countdown * 1.5]. """ return randint(max(1, self.avg_countdown/2), int(self.avg_countdown*1.5)+1, size=(num, 1)) def generate_individuals(self, num): """Generate num individuals at random positions with the avg_countdown set by init_individuals.""" return hstack(( randint(self.size-1, size=(num, 2)), # starting positions. self.generate_countdowns(num) # countdowns. )) def set_individual_vision(self, ind): """Update the vision matrix to include the 3*3 area around the individual.""" x = ind[0] y = ind[1] for xi in range(-self.agent_vision, self.agent_vision+1): for yi in range(-self.agent_vision, self.agent_vision+1): if ((x+xi < self.size) and (y+yi < self.size) and (x+xi >= 0) and (y+yi >= 0) and (xi**2 + yi**2 <= (self.agent_vision + 0.5)**2)): self.vision[[x+xi], [y+yi]] = 1 def init_individuals(self, num, avg_countdown=3, agent_vision=1): """Initialise num individuals on the landscape and set their vision.""" self.avg_countdown = avg_countdown self.agent_vision = agent_vision self.individuals = self.generate_individuals(num) self.accumulated_significance = 0 self.step_significance_contributions = [] for ind in self.individuals: self.set_individual_vision(ind) def print_matrix(self): print self.matrix def plot(self, individuals=False): """Plot a gray-scale filled contour map of the landscape, optionally with individual counters at locations.""" m = mgrid[:self.size, :self.size] plt.contourf(m[0], m[1], self.matrix, range(self.size*2), cmap=plt.cm.gray) if individuals: for ind in self.individuals: plt.text(ind[0], ind[1], str(ind[2])) def show(self, individuals=False): """Show the result of plot.""" self.plot(individuals=individuals) plt.colorbar() plt.show() def save(self, filename, individuals=False): """Save the result of plot to a file.""" self.plot(individuals=individuals) plt.colorbar() plt.savefig(filename, bbox_inches=0) plt.show() def plot_vision(self): """Plot the current vision matrix as black/white tiles.""" m = mgrid[:self.size,:self.size] plt.pcolormesh(m[0],m[1],self.vision,cmap=plt.cm.hot) def show_vision(self): """Show the result of plot_vision.""" self.plot_vision() plt.show() def countdown_individual(self,ind): """Reduce all countdowns by 1, generating new countdowns for those that reached zero.""" ind[2] -= 1 # reduce countdown if ind[2]: # countdown not zero return ind, -1 # new_z as -1 indicates the individual hasn't moved # set new countdown ind[2] = self.generate_countdowns(1) # contribute to accumulated significance based on current location ind_z = self.matrix[ind[0], ind[1]] self.accumulated_significance += ind_z self.step_significance_contributions.append(ind_z) return ind, ind_z def move_individual(self,ind): """Move an individual to the highest point in the local 3*3 area.""" end_x = start_x = ind[0] end_y = start_y = ind[1] max_z = self.matrix[start_x, start_y] # move to highest neighbour (including current position) for x_offset in range(-1, 2): cur_x = min(self.size-1, max(0, start_x+x_offset)) for y_offset in range(-1, 2): cur_y = min(self.size-1, max(0, start_y+y_offset)) if self.matrix[cur_x, cur_y] > max_z: max_z = self.matrix[cur_x, cur_y] end_x = cur_x end_y = cur_y ind[0] = end_x ind[1] = end_y self.set_individual_vision(ind) return ind def step(self): """Countdown all individuals and move the ones whose countdown reached zero.""" for i in range(len(self.individuals)): self.individuals[i], ind_z = self.countdown_individual(self.individuals[i]) if ind_z != -1: self.individuals[i] = self.move_individual(self.individuals[i]) def get_peak(size, loc, sig, max_height): """Returns a 2d matrix of size*size with a peak centred at loc, with width sig, of max_height.""" m = mgrid[:size, :size] biv = mlab.bivariate_normal(m[0], m[1], sig[0], sig[1], loc[0], loc[1]) return biv*float(max_height)/biv.max() class GaussianLandscape(BasicLandscape): """A feature-rich landscape simulator. The Gaussian Landscape is initialised by adding bivariate Gaussian hills to a flat landscape (hence the name). Funding: The Gaussian Landscape adds a simulation of funding by selecting from a pool of candidate individuals a subset that will explore the landscape. Various selection mechanisms are modelled (see step). Dynamic significance: The Gaussian Landscape can be deformed as a result of exploration. Various dynamic processes are modelled. """ def __init__(self, size, num_peaks, max_height): self.size = size self.vision = zeros((size, size)) self.matrix = zeros((size, size)) self.max_height = max_height peaks = randint(1, self.size-1, size=(num_peaks, 3)) # randomly generate loc and sig for each peak. for peak in peaks: self.add_gaussian( (peak[0], peak[1]), # location of the peak on the landscape peak[2], # width of the peak along x and y random.random() # peak height ) self.matrix *= max_height / self.matrix.max() # scale landscape to match max_height. def add_gaussian(self, loc, sig, height): # height can be negative self.matrix += get_peak(self.size, loc, (sig, sig), height) # do not allow negative values self.matrix = self.matrix.clip(min=0, max=self.max_height) def winner_takes_all(self, ind): """A dynamic effect, sets significance to zero at individual location (once explored).""" loc = [ind[0], ind[1]] height = self.matrix[loc[0], loc[1]] * -1 # lower current position by its height sig = self.size * 0.01 self.add_gaussian(loc, sig, height) def reduced_novelty(self, ind): """A dynamic effect, lower nearby significance (once a significant location is explored).""" loc = [ind[0], ind[1]] height = self.matrix[loc[0], loc[1]] * -0.5 # lower local neighbourhood by majority of height sig = self.size * 0.05 self.add_gaussian(loc, sig, height) def new_avenue(self): """A dynamic effect, add a peak at a random location (once a significant location is explored).""" loc = randint(self.size-1, size=(2, 1)) height = randint(self.matrix.max()) sig = self.size * 0.06 self.add_gaussian(loc, sig, height) def step(self, cutoff=0.7, funding='best', dynamic=True): """Run through a single simulation step. Each simulation step: 1. Countdown all individuals. 2. Accumulate significance from individuals who reached zero countdown. 3. If a simulation with dynamic significance, alter the landscape with dymanic processes. 4. Generate candidate pool from zero-countdown individuals and new individuals. 5. Select individuals from the candidate pool based on the funding method. 6. Add vision for selected individuals. """ self.step_significance_contributions = [] individual_indexes_to_move = [] for i in range(len(self.individuals)): # update individual's countdown, check if research finished self.individuals[i], ind_z = self.countdown_individual(self.individuals[i]) # Simulate dynamic processes if ind_z != -1: if dynamic: # Effects triggered above cutoff if (float(ind_z)/self.matrix.max()) > cutoff: self.reduced_novelty(self.individuals[i]) self.new_avenue() # Always triggered effects self.winner_takes_all(self.individuals[i]) individual_indexes_to_move.append(i) # move individual on new landscape for i in individual_indexes_to_move: self.individuals[i] = self.move_individual(self.individuals[i]) # --- Funding stage --- if not individual_indexes_to_move: # if there are no candidates there is no free cash self.step_renewal = None return num_total_individuals = len(self.individuals) # remove moved individuals from current individuals, add them to candidate list old_candidates = [] for i in individual_indexes_to_move: old_candidates.append(self.individuals[i]) self.individuals = delete(self.individuals, individual_indexes_to_move, 0) # add new candidates until number of applicants == total num of individuals new_individuals = self.generate_individuals(num_total_individuals - len(individual_indexes_to_move)) candidates = vstack((array(old_candidates), new_individuals)) if funding == 'best': # Select candidates at highest positions, regardless of vision. zs = [self.matrix[ind[0], ind[1]] for ind in candidates] zs.sort() zs.reverse() zs = zs[:len(individual_indexes_to_move)] count = 0 for ind in candidates: if self.matrix[ind[0], ind[1]] in zs: self.individuals = vstack((self.individuals, ind)) self.set_individual_vision(ind) count += 1 if count >= len(individual_indexes_to_move): break elif funding == 'best_visible': # Select highest, only from visible positions (ignore invisible). non_visible_candidate_indexes = [] for i in range(len(candidates)): ind = candidates[i] if not self.vision[ind[0], ind[1]]: non_visible_candidate_indexes.append(i) candidates = delete(candidates, non_visible_candidate_indexes, 0) zs = [self.matrix[ind[0], ind[1]] for ind in candidates] zs.sort() zs.reverse() zs = zs[:len(individual_indexes_to_move)] count = 0 for ind in candidates: if self.matrix[ind[0], ind[1]] in zs: self.individuals = vstack((self.individuals, ind)) self.set_individual_vision(ind) count += 1 if count >= len(individual_indexes_to_move): break elif funding == 'lotto': # Select candidates at random, regardless of height or vision. shuffle(candidates) candidates = candidates[:len(individual_indexes_to_move)] for ind in candidates: self.set_individual_vision(ind) self.individuals = vstack((self.individuals, candidates)) elif funding == 'triage': # Select half by best_visible and half by lotto. non_visible_candidate_indexes = [] for i in range(len(candidates)): ind = candidates[i] if not self.vision[ind[0], ind[1]]: non_visible_candidate_indexes.append(i) # Use lotto on half the candidates non_visible_candidates = candidates[non_visible_candidate_indexes] if non_visible_candidates.size: # For long-running simulations there may be none. shuffle(non_visible_candidates) non_visible_candidates = non_visible_candidates[:len(individual_indexes_to_move)/2] for ind in non_visible_candidates: self.set_individual_vision(ind) self.individuals = vstack((self.individuals, non_visible_candidates)) num_remaining = len(individual_indexes_to_move) - len(non_visible_candidates) # Use best_visible on the remainder visible_candidates = delete(candidates, non_visible_candidate_indexes, 0) zs = [self.matrix[ind[0], ind[1]] for ind in visible_candidates] zs.sort() zs.reverse() zs = zs[:num_remaining] count = 0 for ind in candidates: if self.matrix[ind[0], ind[1]] in zs: self.individuals = vstack((self.individuals, ind)) self.set_individual_vision(ind) count += 1 if count >= num_remaining: break elif funding == 'oldboys': # No new candidates, zero-countdown individuals continue (no selection). self.individuals = vstack((self.individuals, array(old_candidates))) else: raise KeyError('Unknown funding option %s' % str(funding)) self.step_renewal = 0 old_candidates_tuples = [tuple(x) for x in old_candidates] selected_individuals_tuples = [tuple(x) for x in self.individuals] for old_candidate_tuple in old_candidates_tuples: if old_candidate_tuple in selected_individuals_tuples: self.step_renewal += 1 self.step_renewal /= float(len(individual_indexes_to_move)) # 'oldboys' should have 100% renewal if funding == 'oldboys': assert(self.step_renewal == 1.0) # All selection methods keep the active number of individuals fixed. assert(len(self.individuals) == num_total_individuals) if __name__ == '__main__': size = 100 num_peaks = 50 max_height = 200 num_individuals = 30 avg_countdown = 5 landscape = GaussianLandscape(size, num_peaks, max_height) landscape.init_individuals(num_individuals, avg_countdown) landscape.show(individuals=True)
00c05bc14263c4b8906f71b8e09f8cd6d9e3cf51
Boorneeswari/GUVI_PROGRAMS
/sort.py
155
3.65625
4
sizee=int(input()) list1=[] num1=raw_input() num1=num1.split() for i in range(sizee): list1.append(int(num1[i])) list1.sort() for i in list1: print i,
a1dbdb2c77844e6bb4c115dfcce1e19178e824cc
Boorneeswari/GUVI_PROGRAMS
/evenodd3.py
134
3.5
4
inp=raw_input() inp=inp.split() frst=int(inp[0]) sec=int(inp[1]) prod=frst*sec if prod%2==0: print("even") else: print("odd")
b40518a48b78a9815becf7f3ae208c183a51b289
Boorneeswari/GUVI_PROGRAMS
/set2_odd.py
151
3.578125
4
num=raw_input() num=num.split() frst=int(num[0]) scnd=int(num[1]) for i in range(frst+1,scnd): if i%2 !=0: print i, else: pass
25cca4b4384587712b1ad15a02f296f5bfe6dd3f
Boorneeswari/GUVI_PROGRAMS
/firstKsum.py
156
3.53125
4
ran=input() ran=ran.split() num=int(ran[0]) upto=int(ran[1]) arr=input() arr=arr.split() sum=0 for i in range(0,upto): sum=sum+(int(arr[i])) print(sum)
c260ba24d9f915d8e91fb7de5a744112c93849ca
Boorneeswari/GUVI_PROGRAMS
/maxlen.py
138
3.609375
4
num=raw_input() num=num.split() lis=[] for each in num: n=len(each) lis.append(n) #print(lis) ind=lis.index(max(lis)) print(num[ind])
bbf84a077fe9363aac8f07a8e1986313a8c76e14
Boorneeswari/GUVI_PROGRAMS
/set2_palind.py
176
3.5625
4
numb=input() lis=[] num=int(numb) while(num!=0): rem=num%10 lis.append(str(rem)) num=num//10 lis1=list(numb) if lis == lis1: print("yes") else: print("no")
62584a43ee6ccaf3853160054886f455fcacd7c3
Ben-Willis-York/Soft-Arm-Main
/scripts/simulator.py
3,508
3.515625
4
#!/usr/bin/env python from math import * from VectorClass import Vector2, Vector3 import time from Tkinter import * class Link(object): def __init__(self, length, parent): self.length = length self.parent = parent self.angle = 0 self.pos = Vector2(0,0) self.end = Vector2(0, length) self.B = 0 self.minB = 0 class Joint(object): ID = 1 def __init__(self, parent, child, limits=[-150,150]): self.name = "J"+str(Joint.ID) Joint.ID += 1 self.parent = parent self.child = child self.angle = 0 self.targetAngle = 0 self.min = radians(limits[0]) self.max = radians(limits[1]) self.speed = 1 self.targetReached = False def setAngle(self, val): if(val < self.min): val = self.min if(val > self.max): val = self.max self.targetAngle = val def update(self, delta): if(abs(self.angle - self.targetAngle) < 0.05): self.targetReached = True if(self.angle > self.targetAngle): self.angle -= self.speed * delta self.targetReached = False if(self.angle < self.targetAngle): self.angle += self.speed * delta self.targetReached = False class Sim(object): def __init__(self): self.joints = [] self.links = [Link(0,None)] self.target = Vector2(0,0) def getJoints(self): joints = [] for j in self.joints: joints.append([j.name, degrees(j.min), degrees(j.max)]) return joints def addLink(self, length, limits=[-150,150]): print(limits) self.links.append(Link(length, self.links[-1])) self.joints.append(Joint(self.links[-2], self.links[-1], limits=limits)) self.update(0.0) def setJointState(self, angles): for a in range(len(angles)): self.joints[a].setAngle(radians(angles[a])) def getJointState(self): angles = [] reached = [] for j in self.joints: angles.append(j.angle) reached.append(j.targetReached) return angles, reached def getJointDistance(self, name1, name2): for j in self.joints: if(j.name == name1): j1 = j if(j.name == name2): j2 = j p1 = j1.child.pos p2 = j2.child.pos return (p2-p1).Mag() def getJointLength(self, name): for j in self.joints: if(name == j.name): return (j.child.end-j.child.pos).Mag() def update(self, delta): for j in self.joints: j.update(delta) for i in range(1, len(self.links)): l1 = self.links[i - 1] l2 = self.links[i] j = self.joints[i - 1] totalAngle = l1.angle + j.angle l2.pos.x = l1.end.x l2.pos.y = l1.end.y l2.end.x = l2.pos.x + (cos(totalAngle) * l2.length) l2.end.y = l2.pos.y + (sin(totalAngle) * l2.length) l2.angle = totalAngle def draw(self, dis): for l in self.links: dis.drawLine(l.pos.x, l.pos.y, l.end.x, l.end.y) #dis.drawCircle(self.links[-1].end.x, self.links[-1].end.y, 10) dis.drawCircle(self.target.x, self.target.y, 10, fill="red")
4030b0f8e2601b14f6bda575a5fdb1d86b3ecde9
VFerrari/2-TSP_Lagrangian
/src/Lagrangian/lagrangian.py
3,105
3.578125
4
''' Activity 3 - Lagrangian Heuristic for 2-TSP. subgradient.py: Implements the subgradient method for solving the dual lagrangian problem. 2-TSP: find the 2 shortest hamiltonian cycles in a complete graph. Subject: MC859/MO824 - Operational Research. Authors: André Soranzzo Mota - RA 166404 Victor Ferreira Ferrari - RA 187890 Gabriel Oliveira dos Santos - RA 197460 University of Campinas - UNICAMP - 2020 Last Modified: 22/10/2020 ''' from time import time from math import inf # Constants INIT_PI = 2 MIN_PI = 0.005 MAX_ITER_PI = 30 INIT_MULT_VAL = 0 EPS = 0.0005 ''' Generic subgradient method function for a MINIMIZATION problem. Solutions and dual bounds acquired through Lagrangian Relaxation. Takes Problem instance, execution time limit (in seconds). Returns the best solution and dual bound found within time "max_time". Some optimizations are described in the "Lagrangian Relaxation" article by J.E. Beasley, in the "Modern Heuristic Techniques for Combinatorial Problems" book, pages 243-303, 1993. ''' def lagrangian_relaxation(problem, start_time, max_time): # 1 - Initialize lagrange multipliers and other important values/functions. pi, n_iter = INIT_PI, 0 curr_time = lambda x: time() - x mult = problem.init_mult(INIT_MULT_VAL) lower_bound_list, upper_bound_list = [], [] # End conditions: pi too small, too much time elapsed and optimum found. while pi > MIN_PI and curr_time(start_time) < max_time and not problem.optimal(): # 2 - Solve LLBP with lagrangian costs. dual, dual_sol = problem.solve_llbp(mult, max_time-curr_time(start_time)) if dual == inf: break lower_bound_list.append(dual) # 3 - Update best dual if possible n_iter += 1 if dual > problem.dual: problem.dual = dual n_iter = 0 # 3.5 - Half pi after MAX_ITER_PI iterations without improvement. elif n_iter == MAX_ITER_PI: pi /= 2 n_iter = 0 # 4 - Generate primal with lagrangian heuristic, and update. primal, primal_sol = problem.lg_heu(dual_sol, max_time-curr_time(start_time)) if primal == inf: upper_bound_list.append(upper_bound_list[-1]) break upper_bound_list.append(primal) if primal < problem.primal: problem.primal = primal problem.solution = primal_sol # 5 - Calculate subgradients. subgrad, sub_sum = problem.subgradients(mult, dual_sol) # 5.5 - Early stopping. # Finish execution if Gi=0 for every i. # If solution is viable, it's the optimum. if sub_sum == 0: if problem.check_viability(dual_sol): problem.primal = dual problem.solution = dual_sol break # 6 - Update lagrange multipliers step = pi*((1+EPS)*problem.primal - problem.dual)/sub_sum mult = problem.update_mult(mult, subgrad, step) return problem, problem.optimal(), lower_bound_list, upper_bound_list
32099b0948fc860631a8faefa3c7acba3f387032
bijenshresth/Image_Processing
/Lab11/laplacian.py
553
3.5
4
#Laplacian of an Image import cv2 as cv import numpy as np image = cv.imread('brickwall.jpg', 0) image = cv.resize(image, (400, 300)) cv.imshow('Input', image) #Using 2nd order Laplacian Operator without Gaussian Filter imageWob = cv.Laplacian(image, cv.CV_64F, ksize=1) cv.imshow('Output: 2nd Ord Derivative w/o Blur', imageWob) #Using Gaussian Filter to remove Noise blur = cv.GaussianBlur(image, (3,3), 0 ) image_blur = cv.Laplacian(blur, cv.CV_64F, ksize=1) cv.imshow('Output: 2nd Ord Derivative', image_blur) cv.waitKey(0) cv.destroyAllWindows()
aa9576a214a8947825857de0c8bdc4e0ea8f990d
IleanaChamorro/CursoPython
/Modulo5/Tipos y Estructuras/Listas/Tarea8.py
219
3.90625
4
#Consigna => Iterar un rango de 0 a 10 e imprimir sólo los números divisibles entre 3 tupla = (13, 1, 8, 3, 2, 5, 8) lista = [] for elemento in tupla: if elemento < 5: lista.append(elemento) print(lista)
78bea229ea830089160279aac0fd2ce355d575ae
IleanaChamorro/CursoPython
/Modulo1/Ejercicio1.py
133
3.671875
4
#Califica tu día del 1 al 10 calificacion = int(input("Como estuvo tu dia (1 al 10): ")) print("Mi día estuvo de: ", calificacion)
8b16a037d94c15672abe6a336a50da5fe3e08b91
IleanaChamorro/CursoPython
/Modulo2/Tarea3.py
786
4.03125
4
#Consigna #En el siguiente ejercicio se solicita calcular el área y el perímetro de un Rectángulo, para ello deberemos crear las siguientes variables: alto(int), ancho(int). El usuario debe proporcionar los valores de largo y ancho, y despues debe imprimir el resultado en el siguiente formato(no usar acentos y respetar los espacios, mayúsculas, minúsculas y saltos de línea): #Proporciona el alto: #Proporciona el ancho: #Area: <area> #Perímetro: <perimetro> #Las fórmulas para calcular el área y el perímetro de un Rectángulo son: #Área: alto * ancho #Perímetro: (alto + ancho) * 2 alto = int(input("Propociona el alto")) ancho = int(input("proporciona el ancho")) area = alto * ancho perimetro = (alto + ancho) * 2 print("Area: ", area) print("Perimetro:", perimetro)
9ee168ff9d35d0968e709211340358f2b3a1b5ac
IleanaChamorro/CursoPython
/Modulo2/Operadores/operadores.py
456
4.15625
4
#Operadores a = 3 b = 2 resultado = a + b print(f'Resultado suma: {resultado}') resta = a - b print(f'Resultado es: {resta}') multiplicacion = a * b print(f'resultado multiplicacion: {multiplicacion}') division = a / b print(f'resultado division: {division}') division = a // b print(f'resultado division(int): {division}') modulo = a % b print(f'resultado division(modulo): {modulo}') exponente = a ** b print(f'resultado exponente: {exponente}')
9c2356b6ccf403e6c4615d06f7988d3705d54755
IleanaChamorro/CursoPython
/Modulo2/EjerciciosPractica/ejercicio-Rangodeedad.py
452
3.9375
4
#Ejercicio Practica rango entre 20's y 30's edad = int(input('Introduce tu edad: ')) veintes = edad >= 20 and edad <30 print(veintes) treintas = edad >= 30 and edad <40 print(treintas) if veintes or treintas: #print('Dentro de rango (20s) o (30s)') if veintes: print('Dentro de los 20') elif treintas: print('Dentro de los 30') else: print('Fuera de rango') else: print("No esta dentro de los 20 ni 30")
a54440ee6d73d158644143c3b43659a5fca377da
IleanaChamorro/CursoPython
/Modulo4/cicloFor.py
389
4.28125
4
#El bucle for se utiliza para recorrer los elementos de un objeto iterable (lista, tupla, conjunto, diccionario, …) y ejecutar un bloque de código. En cada paso de la iteración se tiene en cuenta a un único elemento del objeto iterable, sobre el cuál se pueden aplicar una serie de operaciones. cadena = 'Hola' for letra in cadena: print(letra) else: print('Fin ciclo For')
e31f6215a6fd9bd830331c783d1533738e3428a9
kkurian/top3
/top3.py
1,180
3.515625
4
#!/usr/bin/env python from collections import defaultdict import csv import pprint import pdb import nltk # What is NN, JJ? See: # https://en.wikipedia.org/wiki/Brown_Corpus#Part-of-speech_tags_used ADJECTIVE = ['JJ'] REVIEW_COLUMN = 4 def _load_text(): text = '' with open('Recommendations.csv') as f: reader = csv.reader(f) # Skip the header row. next(reader, None) for line in reader: text = f'{text} {line[REVIEW_COLUMN]}' return text def _find_top_3_words_per_tag(words_tags): result = defaultdict(list) for v, k in words_tags: result[k].append(v) for k in result.keys(): fdist = nltk.probability.FreqDist(result[k]) result[k] = fdist.most_common(3) return result def main(): """Print top 3 adjectives from LinkedIn recommendations.""" text = _load_text() tokens = nltk.tokenize.word_tokenize(text) adjectives = [x for x, tag in nltk.pos_tag(tokens) if tag in ADJECTIVE] fdist = nltk.probability.FreqDist(adjectives) pp = pprint.PrettyPrinter(indent=4) pp.pprint([x for x, _ in fdist.most_common(3)]) if __name__ == '__main__': main()
2ab16a582abf343116aed4550a801898846e30d5
rogeriopaguilar/Projetos
/projetos/estudos/python/core_python_programming/core_python_programming_cap05.py
1,969
4.03125
4
#!/usr/bin/env python #-*- encoding: utf-8 -*- #from __future__ import division #to turn floor division to true division, as it will be in python 3 from decimal import Decimal def printType(number): "prints the number's type name" print type(number).__name__ if isinstance(number, complex): print "Complex number --> ", number.real, number.imag, number.conjugate() aInt = -1 aLong = -9999999999999999999999L aFloat = 3.14984984398493849348934849348 aComplex = 1.23+4.56J printType(aInt) printType(aLong) printType(aFloat) printType(aComplex) del aInt print 9999 ** 8 print 0b010 #binary print 0o010 #octal print 0x010 #hexadecimal print (2 << 1) #shifting print 1 / 2 #floor division print 1.0 / 2 #true division print 1 // 2 #forces floor division print 3 ** 2 print -3 ** 2 #caution with precedence! print (-3) ** 2 print 4 ** -1 print ~3 # -(num + 1) print 3 << 1 print 3 << 2 print 4 >> 1 print 1 & 0 print 1 ^ 1 #xor print 1 | 1 #or print cmp(1,1) print str(1) print int(2.1) print long(2) print float(2) print complex(2) print int('0b01',2) #(number, base) print abs(-1) print coerce(1.3, 134L) print divmod(10, 3) #will return (classic division, modulos operation) print divmod(2.5, 10) print pow(2, 5) print round(3.49999) print round(3.49999, 1) import math for eachNum in range(10): print round(math.pi, eachNum) for eachNum in (.2, .7, 1.2, 1.7, -.2, -.7, -1.2, -1.7): print "int (%1f)\t%+.1f" % (eachNum, float(int(eachNum))) print "floor (%1f)\t%+.1f" % (eachNum, math.floor(eachNum)) print "round (%1f)\t%+.1f" % (eachNum, round(eachNum)) print "-" * 20 print hex(255) print oct(255) print ord('a') print chr(97) print bool(1), bool(0), bool('1'), bool('0'), bool([]), bool((1,)) class ABC(object): def __nonzero__(self): return False class DEF(object): pass obj = ABC() print bool(obj) obj = DEF() print bool(obj) print Decimal('.1') + Decimal('1.0')
53baae45f2c84859bfcb0ac9d57a907d4d633b25
madlechuck/lpthw
/1st_Time/ex5.py
749
3.9375
4
name = 'Mathieu Langlois' age = 34 # not a lie height = 68 # inches weight = 205 # lbs eyes = 'Brown' teeth = 'White' hair = 'Brown' # This will convert the height in cms height_cm = height * 2.54 #This will convert the weight in KGs weight_kg = weight / 2.2 print "Let's talk about %s." % name print "He's %d inches tall." % height print "That's %d centimetres!" % height_cm print "He's %d pounds heavy." % weight print "That's %d kilograms!" % weight_kg print "Actually that's not too heavy." print "He's got %s eyes and %s hair." % (eyes, hair) print "His teeth are usually %s depending on the coffee." % teeth # This line is tricky, try to get it exactly right print "If I add %d, %d, and %d I get %d." % (age, height, weight, age + height + weight)
b5bc7e66df045b90f3cc269ed459c9f39ff30b52
madlechuck/lpthw
/1st_Time/ex19_Drills.py
645
3.84375
4
def my_first_function(arg1,arg2): return (arg1 * arg2) / 2 print "\n" #1 print my_first_function(8, 4) #2 print my_first_function(4 + 4, 2 + 2) #3 x = 8 y = 4 print my_first_function(x, y) #4 print my_first_function(x + 16 / 2 - 8, y - x + 8) #5 print "Please, tell me what file I should use:" user_input = raw_input("\n>") in_file = open(user_input) argx = int(in_file.readline(1)) argy = int(in_file.readline(2)) print my_first_function(argx, argy) #6 print "Please press 8" arg1a = int(raw_input("Press '8' then enter:")) print "Please press 4" arg1b = int(raw_input("Press '4' then enter:")) print my_first_function(arg1a, arg1b)
f10313907acae4e5e96fcc6d4afe8187a0e9533e
madlechuck/lpthw
/1st_Time/ex9.py
544
3.578125
4
# Here's some new strange stuff, remember type it exactly. # these two define the variables days and months days = "Mon Tue Wed Thu Fri Sat Sun" months = "\n\nJan\nFeb\nMar\nApr\nMay\nJun\nJul\nAug" # these two print two lines of text that end with days and month variable print "Here are the days: ", days print "Here are the months: ", months # this prints a continue flow of text... print """ There's something going on here. With the three double-quotes. We'll be able to type as much as we like. Even 4 lines if we want, or 5, or 6. """
869a95eb86410b60b95c95c08ab58a93193b55e1
thevarungrovers/Area-of-circle
/Area Of Circle.py
209
4.25
4
r = input("Input the radius of the circle:") # input from user r = float(r) # typecasting a = 3.14159265 * (r**2) # calculating area print(f'The area of circle with radius {r} is {a}') # return area
9589fd4d5b1339d4303ad4a8da76cb50ccba8303
Janet-ctrl/python
/Chapter3/try95311.py
144
3.671875
4
fruits = ['bananna', 'strawberry', 'orange', 'kiwi'] #print(fruits[4]) - index error #correct index search print(fruits[-1]) print(fruits[3])