blob_id
stringlengths
40
40
repo_name
stringlengths
5
127
path
stringlengths
2
523
length_bytes
int64
22
545k
score
float64
3.5
5.34
int_score
int64
4
5
text
stringlengths
22
545k
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...
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...
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 = ...
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 me...
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_...
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") pri...
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 des...
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 small...
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 ...
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 s...
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))] ...
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, ...
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: ...
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: ...
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 = i...
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: ...
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 t...
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: ...
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=...
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...
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 po...
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 ...
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 {} accepte...
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: ...
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): r...
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=cipher...
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 importan...
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 ...
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) ...
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): ...
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 system...
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)] ...
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)) ...
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...
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...
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 = cycle...
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>=...
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. Inpu...
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 i...
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 implementa...
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 :r...
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 ...
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...
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'] =...
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(...
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() +...
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]: ...
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...
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): # traver...
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 cou...
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...
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(...
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): ...
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(...
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: iterati...
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 ...
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,ro...
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 #...
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" ...
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. ...
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 h...
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 l...
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 ...
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...
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('D...
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() respost...
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) ...
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: cou...
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 loc...
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...
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 Vict...
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'...
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 respeta...
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): {d...
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 trein...
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 let...
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: ...
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 "...
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...
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_...
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...
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])