blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
274aa2b7785d14dd8578224b2efd33533f34e63b
qcarlox/leetCode
/python/Counting Bits.py
343
3.625
4
class Solution: import math def countBits(self, num): """ :type num: int :rtype: List[int] """ counts = [0] for i in range(1, num+1): if i%2 == 0: counts.append(counts[i//2]) else: counts.append(counts[i-1]+1) return counts
6239fd9c1ad88b4639000ab9b8f7ba0a342e153f
qcarlox/leetCode
/python/Longest Palindromic Substring.py
2,862
3.625
4
class Solution(object): def longestPalindrome(self, s): """ :type s: str :rtype: str """ evenPalindromes = self.scanStringUsingWindow(s, 2) oddPalindromes = self.scanStringUsingWindow(s, 3) longestSubstring = '' #print(evenPalindromes) if len(s) > 0: longestSubstring = s[0] if len(evenPalindromes) != 0: longestSubstring = list(evenPalindromes.keys())[0] if len(oddPalindromes) != 0: longestSubstring = list(oddPalindromes.keys())[0] while len(evenPalindromes) != 0: evenPalindromes = self.expandPalindromes(evenPalindromes, s) #print(evenPalindromes) if len(evenPalindromes) != 0: longestSubstring = list(evenPalindromes.keys())[0] while len(oddPalindromes) != 0: oddPalindromes = self.expandPalindromes(oddPalindromes, s) if len(oddPalindromes) != 0: longestOddSubstring = list(oddPalindromes.keys())[0] if len(longestOddSubstring) > len(longestSubstring): longestSubstring = longestOddSubstring return longestSubstring def expandPalindromes(self, palindromeDictionary, s): tempDic = {} for substring in palindromeDictionary: startList = palindromeDictionary[substring] for i in startList: start = i-1 end = start+len(substring)+1 #print("start: " + str(start)) #print("end: " + str(end)) if(end < len(s) and start >= 0): if(s[start] == s[end]): newSubstring = s[start:end+1] #print(newSubstring) if newSubstring in tempDic: tempDic[newSubstring].append(start) else: tempDic[newSubstring] = [start] return tempDic def scanStringUsingWindow(self, s, windowLength): start = 0 end = start+windowLength palindromeDictionary = {} while end <= len(s): substring = s[start:end] if self.isPalindrome(substring): if substring in palindromeDictionary: palindromeDictionary[substring].append(start) else: palindromeDictionary[substring] = [start] start += 1 end += 1 return palindromeDictionary def isPalindrome(self, substring): end = len(substring) for i in range(end//2): if(substring[i] != substring[end-1-i]): return False return True
af17dd69510758bd78a448158f1a4b5934a94318
qcarlox/leetCode
/python/Reverse Integer.py
1,003
3.5625
4
class Solution: def reverse(self, x): """ :type x: int :rtype: int """ digits = self.intToList(x) if x == 0: return x reversedNumber = self.listToReversedInt(digits) return reversedNumber def intToList(self, num): digits = [] if num < 0: digits.append('-') num = abs(num) while num > 0: digits.append(num%10) num = num//10 return digits def listToReversedInt(self, digits): negative = False if digits[0] == '-': negative = True del digits[0] num = 0 for i, digit in enumerate(reversed(digits)): if (num > (2**31-1 - digit * 10**i) and not negative) or (num > (2**31 - digit * 10**i) and negative): return 0 num += digit * 10**i if negative: return -1*num else: return num
4010f67814de11e00e21a554b8e605427e911fe5
IonesioJunior/Data-Structures
/Python/SkipList/Node.py
2,257
4.09375
4
#coding: utf-8 __author__ = "Ionesio Junior" class Node(object): ''' Node class implementation for skip list structure Attributes: data(optional) : data value to be stored in this node key(optional) : key determine the position of node in skiplist structure forward[Node] : list with all of possible neighbors ''' __data = None __key = None __forward = None def __init__(self,key,height,data): ''' Node constructor,initalize attributes Args: key(optional) : key value of this node height(int) : number of neighbors of this node data(optional) : data value stored in this node ''' self.__data = data self.__key = key self.__forward = [None] * height def height(self): ''' Get height of forward attribute Returns: height(int) : height of forward list ''' return len(self.__forward) def getValue(self): ''' Return data value of this node Returns: data(optional) : return data value of this node ''' return self.__data def setValue(self,newValue): ''' Change data value of this node Args: newDataValue(optional) : new data value of this node ''' self.__data = newValue def getKey(self): ''' Return key of this node Returns: key(optional) : return key of this node ''' return self.__key def setKey(self,newKey): ''' Change key value of this node Args: newKey(optional) : new value of key ''' self.__key = newKey def getForward(self): ''' Return forward list of this node Returns: forward[Nodes] : return forward list of this node ''' return self.__forward def getForwardNode(self,level): ''' Return node of forward list in specific position Args: level(int) : specific position of node Returns: Node : node in specific position ''' return self.__forward[level] def setForwardNode(self,level,newNode): ''' Change node of forward list in specific position Args: level(int) : specific position newNode(Node) : node to be changed ''' self.__forward[level] = newNode def setForward(self,newForward): ''' Change all forward List Args: newForward[] : new forward list ''' self.__forward = newForward
3d13c6b110cce229493499e32527dc087670c2ba
IonesioJunior/Data-Structures
/Python/Heap/BinaryHeap.py
4,420
4.125
4
#coding: utf-8 __author__ = "Ionesio Junior" class BinaryHeap(): ''' Heap is a priority queue data-structure in tree format. Attributes: heapArray[elements] : store elements of data structure index(int) : index of last element stored in heap array ''' __heapArray = None; __index = None; def __init__(self): ''' Default heap constructor initialize your attributes ''' self.__heapArray = [] self.__index = -1 def insert(self,element): ''' Insert new element in last position of heap tree,after correct your position by value (Max->root) Args: element(optional) : element to be inserted ''' if(element != None): self.__index = self.__index + 1 self.__heapArray.insert(self.__index,element) i = self.__index while(i > 0 and self.__heapArray[self.__parent(i)] < self.__heapArray[i]): aux = self.__heapArray[i] self.__heapArray[i] = self.__heapArray[self.__parent(i)] self.__heapArray[self.__parent(i)] = aux i = self.__parent(i) def extractRoot(self): ''' Remove and return element in root position or raise exception if heap is empty Returns: element(optional) : root element to be removed Raises: Exception : when heap is empty ''' if(self.isEmpty()): raise Exception("Heap is Empty!!") else: removedElement = self.__heapArray[0] self.__heapArray[0] = self.__heapArray[self.__index] self.__index = self.__index - 1 self.__heapify(self.__heapArray,0) return removedElement def rootElement(self): ''' Return element in root position without removed it, or return None if heap is empty Returns: element(optional) : current root element / None ''' if(self.isEmpty()): return None else: return self.__heapArray[0] def heapSort(self,array): ''' Sort an list using heap structure (Destruction of current heap!) Args: array[] : list to be sorted Returns: array[] : sorted list ''' self.buildHeap(array) for i in range(self.__index,0,-1): aux = self.__heapArray[0] self.__heapArray[0] = self.__heapArray[i] self.__heapArray[i] = aux self.__index = self.__index - 1 self.__heapify(self.__heapArray,0) return self.__heapArray def buildHeap(self,array): ''' Build a heap structure using an list of elements (Destruction of current heap) Args: array[] : list to construct a new heap ''' self.__heapArray = [] self.__index = -1 for i in range(len(array)): self.insert(array[i]) def toArray(self): ''' Return all of heap elements in list structure Returns: array[] : list of heap elements ''' return self.__heapArray def size(self): ''' Return how many elements have in current heap Returns: size(int) : number of elements in heap structure ''' return self.__index + 1 def isEmpty(self): ''' Return true if heap is empty or false,otherwise Returns: boolean ''' return (self.__index < 0) ############################ AUXILIAR METHODS ######################################################## def __parent(self,index): ''' Return parent of some node element Args: index(int) :index of some node Returns: index(int) : index of parent node ''' return index / 2 def __left(self,index): ''' Return left son of some node element Args: index(int) : index of some node Retuns: index(int) : index of left son ''' return (2 * index) def __right(self,index): ''' Return right son of some node element Args: index(int) : index of some node Returns: index(int) :index of right son ''' return (2 * index) + 1 def __heapify(self,array,index): ''' Correct node positions when some node is inserted or removed Args: array[elements] = heap array index(int) = index of inserted/removed node ''' left = self.__left(index) right = self.__right(index) largest = 0 if(left <= self.__index and self.__heapArray[left] > self.__heapArray[index]): largest = left else: largest = index if(right <= self.__index and self.__heapArray[right] > self.__heapArray[largest]): largest = right if(largest != index): aux = self.__heapArray[index] self.__heapArray[index] = self.__heapArray[largest] self.__heapArray[largest] = aux self.__heapify(self.__heapArray,largest)
6bab3c6677cc6fc77fb4739bd10023e42eb8ef12
CJosephides/traders_vs_pirates
/tvp/core/deck.py
515
3.5625
4
""" deck.py The Deck class. """ import numpy as np class Deck: """ A deck of cards. Initialization creates a new deck. """ def __init__(self): self.deck = [] for t in ('i', 's', 'p'): for i in range(1, 11): self.deck.append(t + str(i)) def deal_card(self): # Pick card. card = np.random.choice(self.deck, replace=False) # Remove from deck. self.deck.remove(card) # Return. return card
34ef087033311b123195a49337098a80d87d6fa4
zootechdrum/algorithms
/post-bootcamp/algo-array-sorted/algo-array-sorted.py
1,270
4.28125
4
def sort(arr , cond): for i in range(0, len(arr)): for j in range(i + 1, len(arr)): if( cond == 'even'): if(arr[i] > arr[j]): temp = arr[i] arr[i] = arr[j] arr[j] = temp else: if(arr[i] < arr[j]): temp = arr[i] arr[i] = arr[j] arr[j] = temp return arr #The below function takes an array and checks if numbers are devided by 2 def up_down_start(arr): evenlist = [] oddlist = [] # Depending if number is even or odd the numbers will be added to even or odd list for x in arr: if x % 2 == 0: evenlist.append(x) else: oddlist.append(x) #Helper function gets called with appropriate second para assortedEven = sort(evenlist, 'even') assortedOdd = sort(oddlist,"odd") joined_list = assortedEven + assortedOdd print(joined_list) #Concat the two lists. return joined_list testArr1 = [5, 32, 9, 47, 22, 6, 33, 17, 20, 73] # console.log("The following should be [6, 20, 22, 32, 73, 47, 33, 17, 9, 5]"); up_down_start(testArr1) # // ------------------------------------------------------------------
774f9514aca7a92fb1bfa67bd552caec5af11861
khemasree/CSEE5590_Lab
/Lab1/Source/Lab1/lab4a.py
495
3.859375
4
# List of students attending python class pythonlist={'Bob','Billy','Sara'} # List of students attending web applications class webApplicationlist={'John','James','Bob'} # List of students attending both attendingboth = pythonlist & webApplicationlist print("The students attending both the classes are: ", attendingboth) # List of students not common in both the classes notcommon=pythonlist ^ webApplicationlist print("The students who are not common in both the classes are: ", notcommon)
a722dfbc62fa87e96495bb9e90567e4c5b01204e
khemasree/CSEE5590_Lab
/Lab1/Source/Lab1/lab5a.py
5,382
3.875
4
class Customer:#class creation __days_31 = [1,3,5,7,8,10,12]#private variable (encapsulation) days_30 = [4,6,9,11] days_28 = [2] dep_year = None dep_month = None dep_day = None #created a constructor and passed values into it def __init__(self,year, month, day, name,num_of_rooms,occupants,date_duration): self.year = year self.month = month self.day = day self.name = name self.num_of_rooms = num_of_rooms self.date_duration = date_duration #arrival date self.arrival_date = str(self.year) + "-" + str(self.month) + "-" + str(self.day) self.occupants = occupants Customer.dep_day = self.day + self.date_duration Customer.dep_month = self.month Customer.dep_year = self.year #logic to find departure date if self.month == 2 and self.day == 29: Customer.dep_day = Customer.dep_day - 29 Customer.dep_month = self.month + 1 if self.month in Customer.__days_31: if Customer.dep_day > 31: Customer.dep_day = Customer.dep_day - 31 Customer.dep_month = self.month + 1 if Customer.dep_month > 12: Customer.dep_month = 1 Customer.dep_year = self.year + 1 elif self.month in Customer.days_30: if Customer.dep_day > 30: Customer.dep_day = Customer.dep_day - 30 Customer.dep_month = self.month + 1 if self.month == 13: self.month = 1 Customer.dep_year = self.year + 1 else: if Customer.dep_day > 28: Customer.dep_day = Customer.dep_day - 28 Customer.dep_month = self.month + 1 self.year = str(Customer.dep_year) self.month = str(Customer.dep_month) self.day = str(Customer.dep_day) #departure date self.departure_date = self.year + "-" + self.month + "-" + self.day print("Booking Details:") print("-----------------") print(" Name:", self.name, "\n", "Number of rooms:", self.num_of_rooms, "\n", "Number of people:" ,self.occupants, "\n", "Number of days:", self.date_duration, "\n", "Arrival Date:", self.arrival_date,"\n", "Departure Date:", self.departure_date) class Room_selection:#class creation def __init__(self,no_of_people,no_of_rooms): self.no_of_people = no_of_people self.no_of_rooms = no_of_rooms self.twin_bed_price = 1000 self.tax = 14 self.price = (self.twin_bed_price + ((self.twin_bed_price * self.tax) *100)) #display ordinary room price def get_bed_price(self): self.price = self.price * self.no_of_rooms if self.no_of_people > 2: self.price = self.price + self.no_of_people * 50 print("ordinary room", self.price) def set_tax(self): self.tax = 14 def get_no_of_people(self): return self.no_of_people def get_no_of_rooms(self): return self.no_of_rooms def get_tax(self): return self.tax def set_twin_bed_size(self): self.twin_bed_price = 1000 def get_twin_bed_size(self): return self.twin_bed_price class Deluxe_Room(Room_selection):#inheritance def __init__(self, no_of_people, no_of_rooms): super().__init__(no_of_people, no_of_rooms)#super class self.no_of_people = no_of_people self.no_of_rooms = no_of_rooms self.price = (Room_selection.get_twin_bed_size(self) + 250) + ((Room_selection.get_twin_bed_size(self) + 250) / Room_selection.get_tax(self)) * 100 self.price = self.price * self.no_of_rooms if self.no_of_people > 2: self.price = self.price + self.no_of_people *50 #deluxe room price method def get_bed_price(self):#polymorphism print("Deluxe room price ;", self.price) class Luxury_Room(Room_selection):#inheritance def __init__(self,no_of_people, no_of_rooms): super().__init__(no_of_people, no_of_rooms)#super class self.no_of_people = no_of_people self.no_of_rooms = no_of_rooms self.price = (Room_selection.get_twin_bed_size(self) + 300) + ((Room_selection.get_twin_bed_size(self) + 300) / Room_selection.get_tax(self)) * 100 self.price = self.price * self.no_of_rooms if self.no_of_people > 2: self.price = self.price + self.no_of_people * 50 #luxury room price method def get_bed_price(self):#polymorphism print("Luxury room price", self.price) class Booking_Information(Luxury_Room,Deluxe_Room,Customer):#multiple inheritance def __init__(self,no_of_people, no_of_rooms): self.no_of_people = no_of_people self.no_of_rooms = no_of_rooms super().__init__(no_of_people, no_of_rooms)#super class #calling deluxe_room class, Luxury room class and room selection class to print its price based on number of people and number of rooms Deluxe_Room.get_bed_price(self) Luxury_Room.get_bed_price(self) Room_selection.get_bed_price(self) #creating objects for customer class and room class customer_1 = Customer(2018,2,29,"Bob",2,4,4) room_preference = Luxury_Room(3,4) details = Booking_Information(2,3)
2b7e702bb7c4b35b60487ff68a1b4443e27f3d10
khemasree/CSEE5590_Lab
/ICP3/icp2a.py
1,288
3.921875
4
from bs4 import BeautifulSoup import urllib.request import os # Set the url to variable and open it url="https://en.wikipedia.org/wiki/List_of_state_and_union_territory_capitals_in_India" urllib.request.urlopen(url) source_code = urllib.request.urlopen(url) plain_text = source_code # parse the html content using Beautiful soup library soup = BeautifulSoup(plain_text, "html.parser") # print the title of the page print(soup.title) # find all the elements with tag <a> atag=soup.find_all('a') # iterate each <a> tag and get the elements with href attribute for eachtag in atag: href=eachtag.get('href') print(href) #print(atag) # create an empty list, th_list = [] # Find the table with specified class iterate through each row for rows in soup.find_all('table', class_='wikitable sortable plainrowheaders') : rows_1 = rows.find_all('tr') # Find the data tag td in each row and print the text in it for row in rows_1: td = row.find_all("td") for i in td: print(i.text) # Find the header tag and print the text that is not already in th text th = row.find("th") if th.text not in th_list: th_list.append(th.text) print("State or Union Territory: ", th.text)
2b467490a578f764e825c0f0c99169ab328fcdfc
chsafouane/algorithms_illuminated_the_basics
/merge_sort.py
1,601
4.09375
4
def split(a): ''' This function splits the input into two lists - Inputs: a: the list to be splitted. ''' n = len(a) if n <= 1: return({}, a) return(a[:int(n/2)], a[int(n/2):]) def merge(b, c): ''' This function merges two sorted lists The result is a sorted list. ''' b_counter = 0 c_counter = 0 d = list() total_length = len(b) + len(c) for k in range(total_length): # If all b's elements have already been added # We just have to add c's left elements if b_counter == len(b): d.extend(c[c_counter:]) return(d) # If all c's elements have already been added # We just have to add b's left elements elif c_counter == len(c): d.extend(b[b_counter:]) return(d) # Naive comparison elif b[b_counter] <= c[c_counter]: d.append(b[b_counter]) b_counter += 1 elif c[c_counter] <= b[b_counter]: d.append(c[c_counter]) c_counter += 1 return(d) def merge_sort(a): ''' This function takes a list as an input and returns a sorted list. This is done following these steps: - split the input array => b and c - Recursively sort b and c - Merge the result ''' # Base case if len(a) <= 1: return(a) # First, we split a b, c = split(a) # We recursively sort b and c # and then we merge the result return(merge(merge_sort(b), merge_sort(c))) merge_sort([4,1,5,6,3,2])
a942c98a6b91878fb851a494bc68acb6cb18d2fb
alexzywiak/mit-ocw-intro-to-comp-sci
/00.1ps.py
199
3.984375
4
#!/usr/bin/env python -tt def main(): last = raw_input('What is your last name?') first = raw_input('What is your first name?') print first + ' ' + last if __name__ == "__main__": main()
79235b80a0ea9fdd377175f309c67f07ce75f8c5
rfshiroma/Data_Structures_Algo
/Priority_Queue/PriorityQueueBase.py
820
4.46875
4
# python3 '''Implementation of a Priority Queue''' # How to implement a priority queue by storing its entries in a positional list L. (see Section 7.4.) We provide two realizations, depending on whether or not we keep the entries in L sorted by key. class PriorityQueueBase: ''' Abstract base class for a priority queue.''' class _Item: ''' Lightweight composite to store priority queue items.''' __slots__ = '_key', '_value' def __init__(self, k, v): self._key = k self._value = v def __lt__(self, other): return self._key < other._key # compare items based on their keys # concrete method assuming abstract len def is_empty(self): ''' Return True if the priority queue is empty.''' return len(self) == 0
ebdcadf4e75465954d16e1906fccfc7a7b1b69e9
takeuchisatoshi/data_analyzer
/app.py
1,005
4.03125
4
from calculation import * if __name__ == '__main__': # ユーザーからの入力を受け取る input_data = input("データを入力してください(スペース区切り) > ") # print(input_data) # 文字列リストに変換 numbers_as_str = input_data.split(" ") # print(numbers_as_str) # 整数リストに変換する numbers = [] # 空のリストを作成 for number_as_str in numbers_as_str: int_num = int(number_as_str) numbers.append(int_num) # print(numbers) # 各統計量を計算する(合計, 最大値, 最小値) total_number = cal_total(numbers) max_number = cal_max(numbers) minimum_number = cal_minimum(numbers) average_number = cal_average(numbers) # ユーザーに見やすいようにフォーマットする # 出力する print(f"合計: {total_number}") print(f"最大値: {max_number}") print(f"最小値: {minimum_number}") print(f"平均値: {average_number}")
0968e4dbfcf0a48c2508b871d955846950f38f84
DawnGnius/MyLeetCode
/Palindrome_number_20181101.py
647
3.515625
4
class Solution: def isPalindrome(self, x): """ :type x: int :rtype: bool """ if x < 0: return False else: y = [int(i) for i in str(x)] #y doesn't have to be a list, y could just be str(x) length = (len(y)-1)/2 #This num I thought for a long time, it should be an easy problem stack = [] for index, item in enumerate(y): if index < length: stack.append(item) if index > length: if item != stack.pop(): return False return True
bfa5682115d596c94bcfeb46d273919470b9d6f7
CompOpt4Apps/Thesis
/python/factorial.py
187
3.515625
4
import sys #to = int(sys.argv[1]) #line = sys.stdin.readline() f = open("num.txt", "r") line = f.readline() to = int(line) fact = 1 for i in range(to,1,-1): fact *= i print fact
9cee2a96306926116328cd31559e6fdf39e1843e
petervenables/fun-py
/word-morph/morph.py
1,096
4.03125
4
import random def morph_count(first, second): count = 0 if first == second: return count if len(second) > len(first): count += len(second) - len(first) second = remove_added(first, second) elif len(first) > len(second): count += len(first) - len(second) first = remove_added(second, first) for i in range(len(first)): if first[i] == second[i]: continue else: count += 1 return count def remove_added(shorter, longer): # Remove the characters from the longer string to # account for those changes while len(longer) > len(shorter): idx = random.randrange(len(longer)) if longer[idx] not in shorter: longer = longer.replace(longer[idx], '', 1) else: continue return longer def main(): print("Morph count of CAT->FAT:", morph_count("CAT", "FAT")) print("Morph count of AFT->FAT:", morph_count("AFT", "FAT")) print("Morph count of FART->FLEET", morph_count("FART", "FLEET")) if __name__ == "__main__": main()