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
8a10bbe5993e067ad7c4e05f3afb6f12f898ebcc
Ktsunezawa/Python-practice
/3step/1003/myclass.py
534
3.59375
4
class Person: def __init__(self, name, height, weight): self.name = name self.height = height self.weight = weight def bmi(self): result = self.weight / (self.height*self.height) print(self.name, 'のBMI値は', result, 'です。') class BusinessPerson(Person): def __init__(self, name, height, weight, title): super().__init__(name, height, weight) self.title = title def work(self): print(self.title, 'の', self.name, 'は働いています。')
b46fa4ef979dd954dd3a0f4abc67a8dcdb693897
Ktsunezawa/Python-practice
/3step/0803/date.py
388
3.765625
4
import datetime today = datetime.date.today() print('今日', today, 'です。') birth = datetime.date(today.year, 6, 25) ellap = birth - today if ellap.days == 0: print('今日は誕生日です!') elif ellap.days > 0: print('今年の誕生日まで、あと', ellap.days, '日です。') else: print('今年の誕生日は、', -ellap.days, '日、過ぎました。')
8209ce9707bf756f96a841aebf7e65cb8d719704
snake-enthusiasts/obstacles
/ship.py
2,809
3.90625
4
import pygame from pygame.sprite import Sprite class Ship(Sprite): """A class to manage the ship.""" def __init__(self, ai_game): """Initialize the ship and set its starting position.""" super().__init__() self.screen = ai_game.screen self.settings = ai_game.settings self.screen_rect = ai_game.screen.get_rect() self.obstacles = ai_game.obstacles self.finish = ai_game.finish self.image = pygame.image.load('images/ship.bmp') self.rect = self.image.get_rect() # Start each new ship at the bottom center of the screen. self.rect.midbottom = self.screen_rect.midbottom # Store a decimal value for the ship's horizontal position. self.x = float(self.rect.x) self.y = float(self.rect.y) # Movement flag self.moving_up = False self.moving_right = False self.moving_down = False self.moving_left = False self.collision_with_obstacle = False def update(self): """Update the ship's position based on the movement flag.""" # Update the ship's x and y value, not the rect. x_temp = self.rect.x y_temp = self.rect.y if self.moving_up and self.rect.top > 0: self.y -= self.settings.ship_speed if self.moving_right and self.rect.right < self.screen_rect.right: self.x += self.settings.ship_speed if self.moving_down and self.rect.bottom < self.screen_rect.bottom: self.y += self.settings.ship_speed if self.moving_left and self.rect.left > 0: # działa też self.screen_rect.left self.x -= self.settings.ship_speed self.rect.x = self.x self.rect.y = self.y # If there is no collision with obstace # update rect object from self.x and self.y. self.collision_with_obstacle = pygame.sprite.spritecollideany(self, self.obstacles) self.collision_with_finish = pygame.sprite.collide_rect(self, self.finish) if not self.collision_with_obstacle: if not self.collision_with_finish: print("OK") else: print("Finish") else: self.rect.x = x_temp self.rect.y = y_temp self.x = float(self.rect.x) self.y = float(self.rect.y) print("Obstacle") """ self.x = x_temp self.y = y_temp self.rect.x = self.x self.rect.y = self.y self.collision_with_obstacle = False self.moving_up = False self.moving_right = False self.moving_down = False self.moving_left = False """ def blitme(self): self.screen.blit(self.image, self.rect)
86013c6ed62eff4ef8fac4d5e3cadab1efec86ed
SyeedHasan/DesignPatterns_Stores
/BuilderPattern.py
2,984
3.515625
4
from __future__ import annotations from abc import ABC, abstractmethod, abstractproperty from typing import Any class ManufacturerBuilder(ABC): @abstractproperty def product(self) -> None: pass @abstractmethod def gatherRawMaterials(self) -> None: pass @abstractmethod def stitchAll(self) -> None: pass @abstractmethod def packStuff(self) -> None: pass class ClothesBuilder(ManufacturerBuilder): def __init__(self) -> None: self.reset() def reset(self) -> None: self._product = Clothes() @property def product(self) -> Clothes: product = self._product self.reset() return product def gatherRawMaterials(self) -> None: self._product.add("Cloth: Raw Materials Gathered") def stitchAll(self) -> None: self._product.add("Cloth: Stitched") def packStuff(self) -> None: self._product.add("Cloth: Quality Control Completed and Packed") class ShoeBuilder(ManufacturerBuilder): def __init__(self) -> None: self.reset() def reset(self) -> None: self._product = Clothes() @property def product(self) -> Clothes: product = self._product self.reset() return product def gatherRawMaterials(self) -> None: self._product.add("Shoe: Raw Materials Gathered") def stitchAll(self) -> None: self._product.add("Shoe: Stitched") def packStuff(self) -> None: self._product.add("Shoe: Quality Control Completed and Packed") class Clothes: def __init__(self) -> None: self.parts = [] def add(self, part: Any) -> None: self.parts.append(part) def listSteps(self) -> None: print(f"Steps Completed for {', '.join(self.parts)}", end="") class Shoes: def __init__(self) -> None: self.parts = [] def add(self, part: Any) -> None: self.parts.append(part) def listSteps(self) -> None: print(f"Steps Completed for {', '.join(self.parts)}", end="") class Director: def __init__(self) -> None: self._builder = None @property def builder(self) -> ManufacturerBuilder: return self._builder @builder.setter def builder(self, builder: ManufacturerBuilder) -> None: self._builder = builder def returnRawMaterials(self) -> None: self.builder.gatherRawMaterials() def makeClothes(self) -> None: self.builder.gatherRawMaterials() self.builder.stitchAll() self.builder.packStuff() if __name__ == "__main__": director = Director() builder = ClothesBuilder() shoeBuilder = ShoeBuilder() director.builder = builder print("Standard Raw Materials for Order: ") director.returnRawMaterials() builder.product.listSteps() print("\n") print("Standard Full-featured Product: ") director.makeClothes() builder.product.listSteps() print("\n")
44cc5b20276024979f97fb31cd221b90ba78e351
Mahdee14/Python
/2.Kaggle-Functions and Help.py
2,989
4.40625
4
def maximum_difference(a, b, c) : #def stands for define """Returns the value with the maximum difference among diff1, diff2 and diff3""" diff1 = abs(a - b) diff2 = abs(b - c) diff3 = abs(a - c) return min(diff1, diff2, diff3) #If we don't include the 'return' keyword in a function that requires 'return', then we're going to get a special value #called 'Null' def least_dif(a ,b, c): """Docstring - Finds the minimum value with the least difference between numbers""" diff1 = a - b diff2 = b - c diff3 = a - c return min(diff1, diff2, diff3) print( least_dif(1, 10, 100), least_dif(1, 2, 3), least_dif(10, 20, 30) ) #help(least_dif) print(1, 2, 3, sep=" < ") #Seperate values in between printed arguments #By default sep is a single space ' ' #help(maximum_difference)^^^ #Adding optional arguments with default values to custom made functions >>>>>> def greet(who="Mahdee"): print("Hello ", who) print(who) greet() greet(who="Mahdee") greet("world") #Functions applied on functions def mult_by_five(x, y): return 5 * x + y def call(fn, *arg): """Call fn on arg""" return fn(*arg) print(call(mult_by_five, 1, 1) , "\n\n") example = call(mult_by_five, 1, 3) print(example) def squared_call(fn, a, b, ans): """Call fn on the result of calling fn on arg""" return fn(fn(a, b), ans) print( call(mult_by_five, 3, 6), squared_call(mult_by_five, 1, 1, 1), sep='\n', # '\n' is the newline character - it starts a new line ) def mod_5(x): """Return the remainder of x after dividing by 5""" return x % 5 print( 'Which number is biggest?', max(100, 51, 14), 'Which number is the biggest modulo 5?', max(100, 51, 14, key=mod_5), sep='\n', ) def my_function(): print("Hello From My Function!") my_function() def function_with_args(name, greeting): print("Hello, %s, this is an example for function with args, %s" % (name, greeting)) function_with_args("Mahdee", "Good Morning") def additioner(x, y): return x + y print(additioner(1, 3)) def list_benefits(): return "More organized code", "More readable code", "Easier code reuse", "Allowing programmers to connect and share code together" def build_sentence(info): return "%s , is a benefit of functions" % info def name_the_benefits_of_functions(): list_of_benefits = list_benefits() for benefit in list_of_benefits: print(build_sentence(benefit)) name_the_benefits_of_functions() #Exercise def to_smash(total_candies, n_friends=3): """Return the number of leftover candies that must be smashed after distributing the given number of candies evenly between 3 friends. >>> to_smash(91) 1 """ return total_candies % n_friends print(to_smash(91)) x = -10 y = 5 # # Which of the two variables above has the smallest absolute value? smallest_abs = min(abs(x), abs(y)) def f(x): y = abs(x) return y print(f(0.00234))
22e1c292651076f8759e3c02be9d3be87ddab629
latesandras/presentation
/guess_the_number.py
514
4.09375
4
# guess the number. import random random_num = random.randint(1,10) tipp = -1 for i in range(0,10): print("You have " + str(10 - i) + " try/tries left!") tipp = int(input("Guess a number between one and ten!")) if random_num == tipp: print("YOU WIN!") break else: print("Try again!") if random_num > tipp: print("Guess a bigger number!") if random_num < tipp: print("Guess a smaller number!") if random_num != tipp: print("You Lose!")
1d3d1673beb1ab9484b4d54ee3bdd683830f3cf5
dhanushkumar317/SmallProjects
/Remember the Number.py
6,558
4.0625
4
import random print ("Welcome to the AkTech's new hit game. The game is simple. You are going to enter a number, add to tour previous number and remember it.\n" \ "For example if you said 3 you are going to type 3. on the next turn if you say 4 you are going to type 34. Good Luck :)\n") class Number: def __init__(self): self.Users() def Users(self): self.users = {} while True: self.name1 = input("Please enter the first player's name:") print ("") if self.name1 == "": print ("Your name can not be empty. Please enter a valid name.\n") else: self.users[self.name1] = "" break while True: self.name2 = input("Please enter the second player's name:") print ("") if self.name2 == "": print ("Your name can not be empty. Please enter a valid name.\n") elif self.name2 == self.name1: print (f"{self.name2} is taken. Please enter another name\n") else: self.users[self.name2] = "" break self.Game() def Game(self): self.num = [] self.players = [] for i in self.users: self.players.append(i) for i in range(10): self.num.append(str(i)) print ("Now i'll decide who goes first\n") self.first_player = random.choice(self.players) self.players.remove(self.first_player) self.second_player = random.choice(self.players) print (f"{self.first_player} starts first\n") while True: self.first_number = input(f"{self.second_player} enter {self.first_player}'s first number:") print ("") if len(self.first_number) != 1: print ("Number should be 1 digit. Please enter again\n") elif self.first_number not in self.num: print ("Your input should be an integer. Please enter again.\n") else: self.users[self.first_player]+=self.first_number break i = 0 while True: if i%2==0: print (f"----- {self.first_player}'s Turn -----\n") print ("I'll print your number try to memorize it.*\n") print (f"{self.users[self.first_player]}\n") ready = input("Press Enter when you are ready?:") print("*\n*\n*\n*\n*\n*\n*\n*\n*\n*\n*\n*\n*\n*\n*\n*\n*\n*\n*\n*\n*\n*\n*\n*\n*\n*\n*\n*\n*\n*\n*\n*\n*\n*\n*\n*\n*\n*\n*\n*\n*\n*\n*\n*\n*\n*\n*\n*\n*\n*\n") ask = input("Plese type your number:") print ("") if ask == self.users[self.first_player]: print ("Correct. You entered right. Congratulations. Moving on.\n") while True: self.second_number = input(f"{self.first_player} enter {self.second_player}'s first number:") print ("") if len(self.second_number) != 1: print ("Number should be 1 digit. Please enter again\n") elif self.second_number not in self.num: print ("Your input should be an integer. Please enter again.\n") else: self.users[self.second_player] += self.second_number break else: print (":( unfortunately that is wrong.\n") print (f"print ################################## {self.second_player} Wins !!! ##################################\n") try: print (f"{self.second_player} remembered {self.second_number} digit number\n") except AttributeError: print(f"{self.second_player} could not even play.\n") while True: again = input("Do you want to play again? Y or N:") print ("") if again == "Y" or again == "y": self.users() elif again == "N" or again == "n": exit() else: print ("You have to enter either Y or N") if i%2 == 1: print (f"----- {self.second_player}'s Turn -----") print ("I'll print your number try to memorize it.*\n") print(f"{self.users[self.second_player]}\n") ready = input("Press Enter when you are ready?:") print("*\n*\n*\n*\n*\n*\n*\n*\n*\n*\n*\n*\n*\n*\n*\n*\n*\n*\n*\n*\n*\n*\n*\n*\n*\n*\n*\n*\n*\n*\n*\n*\n*\n*\n*\n*\n*\n*\n*\n*\n*\n*\n*\n*\n*\n*\n*\n*\n*\n*\n") ask = input("Plese type your number:") print ("") if ask == self.users[self.second_player]: print ("Correct. You entered right. Congratulations. Moving on.\n") while True: self.first_number = input(f"{self.second_player} enter {self.first_player}'s first number:") print ("") if len(self.first_number) != 1: print ("Number should be 1 digit. Please enter again\n") elif self.first_number not in self.num: print ("Your input should be an integer. Please enter again.\n") else: self.users[self.first_player] += self.first_number break else: print (":( unfortunately that is wrong.\n") print (f"print ################################## {self.first_player} Wins !!! ##################################\n") print (f"{self.first_player} remembered {self.first_number} digit number\n") while True: again = input("Do you want to play again? Y or N:") print ("") if again == "Y" or again == "y": self.users() elif again == "N" or again == "n": exit() else: print ("You have to enter either Y or N") i+=1 Number()
f7431a123608494028fcd31dfaea3544e0ba0302
dhanushkumar317/SmallProjects
/Rock Paper Scissors.py
2,220
4.0625
4
import random shapes = {"s": "✂", "p": "📄", "r": "🤘"} def gameLogic(): print("Welcome to classic awesome Rock Paper Scissor.\nChoose a shape by entering its initial.\nEx r for Rock, s for Scissors and p for paper.\nGood luck :)\n") playerName = input("Please enter your name: ").capitalize() print("") scores = {playerName: 0, "Computer": 0} state = True while state: items = dict() playerShape = input("Choose a shape on the count of three 1, 2, 3: ") print("") if playerShape not in shapes: print("Please choose Rock (r), Paper (p) or Scissors (s).\n") continue computerShape = random.choice(list(shapes.keys())) items[playerShape], items[computerShape] = playerName, "Computer" print(f"{playerName}: {shapes[playerShape]}{' ' * 10}Computer: {shapes[computerShape]}\n") if playerShape == computerShape: print(f"Its a Withdraw\n\n{playerName}: {scores[playerName]}{' ' * 11}Computer: {scores['Computer']}\n") elif "r" not in items: scores[items['s']] += 1 print(f"{items['s']} gets point !!!\n\n{playerName}: {scores[playerName]}{' ' * 11}Computer: {scores['Computer']}\n") elif "p" not in items: scores[items['r']] += 1 print(f"{items['r']} gets point !!!\n\n{playerName}: {scores[playerName]}{' ' * 11}Computer: {scores['Computer']}\n") elif "s" not in items: scores[items['p']] += 1 print(f"{items['p']} gets point !!!\n\n{playerName}: {scores[playerName]}{' ' * 11}Computer: {scores['Computer']}\n") if 3 in scores.values(): print("#####################################################\n" f"#################### {list(scores.keys())[list(scores.values()).index(3)]} #######################\n" "#####################################################\n") state = False while True: answer = input("Do you want to play again (y or n)?: ") print("") if answer == "y": gameLogic() elif answer == "n": exit() else: print("Please enter y or no\n") if __name__ == '__main__': gameLogic()
f2fb8d9fecc42564d788534f7106dd30a189a5d4
ajitnak/py_pgms_heap
/kth_closest_pts.py
892
3.546875
4
import heapq class PointWithD: def __init__(self, vertex, cord): self.point = cord self.dist = (cord[0]-vertex[0])**2 + (cord[1]-vertex[1])**2 def __cmp__(self, other): return -cmp(self.dist, other.dist) def kth_closest(vertex, points, k): points_with_d = [PointWithD(vertex, point) for point in points] for ptd in points_with_d: print ptd.dist max_heap=points_with_d[:k] heapq.heapify(max_heap) #max_heap=[] #for pt in points_with_d[:k]: # heapq.heappush(max_heap, pt) #while max_heap: # pt = heapq.heappop(max_heap) # print pt.point, pt.dist for pt in points_with_d[k:]: if pt.dist < max_heap[0].dist: print "replace", max_heap[0].point, "with", pt.point heapq.heapreplace(max_heap, pt) print "results" while max_heap: ptd = heapq.heappop(max_heap) print ptd.point kth_closest((0,0), [(7,7), (1,-1), (8,8), (3,3),(10,10), (2,-2), (5,5)], 3)
5497d0f4486bff95cff9edbba6cd4ddeef10e62c
luhang/pythonsample
/chap04/sec02/saveToZip.py
2,876
3.625
4
import zipfile, os # zipfileとosモジュールのインポート def save_zip(folder): ''' 指定されたフォルダーをZIPファイルにバックアップする関数 folder : バックアップするフォルダーのパス ''' # folderをルートディレクトリからの絶対パスにする folder = os.path.abspath(folder) # ZIPファイル末尾に付ける連番 number = 1 # 初期値は1 # ①バックアップ用のZIPファイル名を作成する部分 # ZIPファイル名を作成して、既存のバックアップ用ZIPファイル名を出力 while True: # 「ベースパス_連番.zip」の形式でZIPファイル名を作る zip_filename = os.path.basename(folder) + '_' + str(number) + '.zip' # 作成したZIPファイル名を出力 print("zip = " + zip_filename) # 作成した名前と同じZIPファイルが存在しなければwhileブロックを抜ける if not os.path.exists(zip_filename): break # ファイルが存在していれば連番を1つ増やして次のループへ進む number = number + 1 # ②ZIPファイルを作成する部分 # ZIPファイルの作成を通知 print('Creating %s...' % (zip_filename)) # ファイル名を指定してZIPファイルを書き換えモードで開く backup_zip = zipfile.ZipFile(zip_filename, 'w') # フォルダのツリーを巡回してファイルを圧縮する for foldername, subfolders, filenames in os.walk(folder): # 追加するファイル名を出力 print('ZIPファイルに{}を追加します...'.format(foldername)) # 現在のフォルダーをZIPファイルに追加する backup_zip.write(foldername) # 現在のフォルダーのファイル名のリストをループ処理 for filename in filenames: # folderのベースパスに_を連結 new_base = os.path.basename(folder) + '_' # ベースパス_で始まり、.zipで終わるファイル、 # 既存のバックアップ用ZIPファイルはスキップする if filename.startswith(new_base) and filename.endswith('.zip'): continue # 次のforループに戻る # バックアップ用ZIPファイル以外は新規に作成したZIPファイルに追加する backup_zip.write(os.path.join(foldername, filename)) # ZIPファイルをクローズ backup_zip.close() print('バックアップ完了') # プログラムの実行ブロック if __name__ == '__main__': # バックアップするフォルダーのパスを指定 backup_folder = input('Backupするフォルダーのパスを入力してください >') # ZIPファイルへのバックアップ開始 save_zip(backup_folder)
edaec0f5fdd64b4e85959a15f9845c7790ff136d
wsqy/python_scripts
/codewars/0011.PI approximation.py
1,964
3.5625
4
""" The aim of the kata is to try to show how difficult it can be to calculate decimals of an irrational number with a certain precision. We have chosen to get a few decimals of the number "pi" using the following infinite series (Leibniz 1646–1716): PI / 4 = 1 - 1/3 + 1/5 - 1/7 + ... which gives an approximation of PI / 4. http://en.wikipedia.org/wiki/Leibniz_formula_for_%CF%80 To have a measure of the difficulty we will count how many iterations are needed to calculate PI with a given precision. There are several ways to determine the precision of the calculus but to keep things easy we will calculate to within epsilon of your language Math::PI constant. In other words we will stop the iterative process when the absolute value of the difference between our calculation and the Math::PI constant of the given language is less than epsilon. Your function returns an array or an arryList or a string or a tuple depending on the language (See sample tests) where your approximation of PI has 10 decimals In Haskell you can use the function "trunc10Dble" (see "Your solution"); in Clojure you can use the function "round" (see "Your solution");in OCaml or Rust the function "rnd10" (see "Your solution") in order to avoid discusssions about the result. Example : your function calculates 1000 iterations and 3.140592653839794 but returns: iter_pi(0.001) --> [1000, 3.1405926538] Unfortunately, this series converges too slowly to be useful, as it takes over 300 terms to obtain a 2 decimal place precision. To obtain 100 decimal places of PI, it was calculated that one would need to use at least 10^50 terms of this expansion! About PI : http://www.geom.uiuc.edu/~huberty/math5337/groupe/expresspi.html """ import math def iter_pi(epsilon): sum = count = 0 while abs(4*sum - math.pi) > epsilon: print(sum) sum += (-1) **count / (2*count+1) count += 1 return [count, round(4*sum, 10)] print(iter_pi(0.1))
f6ce6c42eabd1a2e6b8e3f7a8c292342da548e35
Marce104lmeida/uni-dimob
/main.py
1,121
3.703125
4
# Autor: Marcelo Oliveira Almeida # Email: marcelo.almeida1989@bol.com.br # esse projeto te como objetivo unificar dois arquivos de dimob # cada arquivo tem seu propio index iniciando sempre em 1 # para poder unificar corretamente o segundo arquivo precisa iniciar seu index a parti do utimo index no 1º arquivo # então é isso que o código abaixo faz: # abre o aquivo que precisa ser alterado o index, separa ele em listas; # um lista recebe a parte da string que precisamos alterar e file = open('dimob.txt') finalFile = open('final.txt', 'at') list_of_line = [] list_str1 = [] list_str2 = [] list_one_up = [] for line in file.readlines(): list_of_line.append(line) del list_of_line [0:2] for item in list_of_line: str_linha = item list_str1.append(str_linha[0:26]) list_str2.append(str_linha[26:]) i = 436 for l in list_str1: str_up = l str_replace = str_up[0:23] str_up = str_up.replace(str_up, str_replace + str(i)) list_one_up.append(str_up) i = i + 1 l = 0 while l <= len(list_one_up) - 1: final_str = str(list_one_up[l] + list_str2[l]) finalFile.write(final_str) l += 1 finalFile.close() file.close()
907be76ac18404845cd961f9ae0cc81992b11a62
smithhmark/python_code_puzzles
/sequences/greatestspan.py
1,544
3.515625
4
def simplest(vals): sz = len(vals) longest_so_far = 0 for ii, left in enumerate(vals): for jj in range(sz-1, ii, -1): right = vals[jj] if right > left: if jj - ii > longest_so_far: longest_so_far = jj - ii return longest_so_far def linear(vals): sz = len(vals) smallestToLeft = [0] * sz largestToRight = [0] * sz smallestToLeft[0] = vals[0] for ii in range(1, sz): if vals[ii] < smallestToLeft[ii-1]: smallestToLeft[ii] = vals[ii] else: smallestToLeft[ii] = smallestToLeft[ii-1] #print("smallestToLeft:", smallestToLeft) largestToRight[-1] = vals[-1] for ii in range(sz-2,-1,-1): if vals[ii] > largestToRight[ii+1]: largestToRight[ii] = vals[ii] else: largestToRight[ii] = largestToRight[ii+1] #print(" largestToRight:", largestToRight) #print("largestToRight:", largestToRight) #tricky_val = [5,10,0,1,2,3,4] leftidx, rightidx = 0, 0 max = -1 while (leftidx < sz and rightidx < sz): smallestValSoFar = smallestToLeft[leftidx] biggestValToCome = largestToRight[rightidx] if smallestValSoFar < biggestValToCome: # it's safe to look for a further peak span = rightidx - leftidx if span > max: max = span rightidx += 1 else: # looking for an even smaller left value leftidx += 1 return max
c4aa4ca022a5d7f3cfdd56056d3ab2815d19877f
smithhmark/python_code_puzzles
/bst/tree.py
3,558
3.8125
4
from collections import deque class Node(): def __init__(self, val=None): self.left = None self.right = None self.val = val class BST(): def __init__(self, vals=None): self._root = None if vals is not None: for val in vals: #print("inserting ", val) self.insert(val) def insert(self, val): if self._root is None: self._root = Node(val) else: cur = self._root while cur != None: if val < cur.val: if cur.left is None: cur.left = Node(val) break else: cur = cur.left else: if cur.right is None: cur.right = Node(val) break else: cur = cur.right def to_string(self): accum = [] def op(val): accum.append(val) self._inorder(op) return ",".join(str(ii) for ii in accum) def inorder(self): accum = [] def op(val): accum.append(val) self._inorder(op) return accum def _inorder(self, op): stack = [] if self._root is not None: stack.append((self._root, None)) while len(stack) != 0: #print(','.join([str(ii.val) for ii in stack])) # descend left # "visit" # descend right node, val = stack.pop() if node is not None: if node.right is not None: stack.append((node.right, None)) stack.append((None, node.val)) if node.left is not None: stack.append((node.left, None)) else: op(val) def _preorder(self, op): stack = [] if self._root is not None: stack.append((self._root, None)) while len(stack) != 0: #print(','.join([str(ii.val) for ii in stack])) # "visit" # descend left # descend right node, val = stack.pop() if node is not None: if node.right is not None: stack.append((node.right, None)) if node.left is not None: stack.append((node.left, None)) stack.append((None, node.val)) else: op(val) def _postorder(self, op): stack = [] if self._root is not None: stack.append((self._root, None)) while len(stack) != 0: #print(','.join([str(ii.val) for ii in stack])) # descend left # descend right # "visit" node, val = stack.pop() if node is not None: stack.append((None, node.val)) if node.right is not None: stack.append((node.right, None)) if node.left is not None: stack.append((node.left, None)) else: op(val) def _levelorder(self, op): qq = deque() if self._root is not None: qq.append(self._root) while len(qq) > 0: node = qq.popleft() op(node.val) if node.left is not None: qq.append(node.left) if node.right is not None: qq.append(node.right)
521f8e76b5aaedd37c21b034b24acc63d639e551
smithhmark/python_code_puzzles
/hackerrank/buildastring/build.py
9,978
3.71875
4
""" https://www.hackerrank.com/challenges/build-a-string/problem """ import sys import math import bisect """ 012345 ab12ab """ def _find_longest_ending_here(target, idx, min_len=1): found = 0 found_at = -1 ss_len = min_len ss = target[idx - (ss_len - 1):idx + 1] #print(" matching from?", ss) found = target.find(ss, 0, idx - ss_len) matched = '' while found > -1 and ss_len *2 <= idx+1: found_at = found matched = ss ss_len += 1 ss = target[idx - (ss_len - 1):idx + 1] found = target.find(ss, 0, idx - ss_len+1) #print(" matching?", ss) #print(" found?", found) #print(" ss_len", ss_len, "?<=", idx) if found_at > -1: return matched, found_at else: return '', -1 def lcp(left, right): cnt = 0 for li, ri in zip(left, right): if li == ri: cnt += 1 else: return cnt return cnt def _find_longest_starting_here(target, idx, min_len=1): N=len(target) found = 0 found_at = -1 ss_len = min_len ss = target[idx:idx+ss_len] #print(" matching from?", st) found = target.find(ss, 0, idx) matched = '' while found > -1 and ss_len <= idx and idx + ss_len <= N: found_at = found matched = ss ss_len += 1 ss = target[idx:idx+ss_len] found = target.find(ss, found, idx) #print(" matching?", st) #print(" found?", found) #print(" ss_len", ss_len, "?<", ti) #print(" ti+ss_len=", ti+ss_len, " is ", ti+ss_len <= N) if found_at > -1: return matched, found_at else: return None, None def longest_prefix(target, ti, prefs): ss = target[ti] left = bisect.bisect_left(prefs, (ss, ti)) right = bisect.bisect_right(prefs, (chr(ord(ss) + 1),ti)) back = 1 while prefs[left].startswith(ss) : back += 1 ss = target[ti-back:ti+1] ss = ss[::-1] left = bisect.bisect_left(prefs, target[ti], left, right) def build_inv_prefix_array(target): N = len(target) prefs = [] rtarg = target[::-1] for ii in range(N): prefs.append((rtarg[ii:], (N-1) -ii)) prefs.sort() return prefs def build_lcp_array(suffs): lcps = [] for ii in range(1, len(suffs)): lcps.append(lcp(suffs[ii-1], suffs[ii])) return lcps def find_longest_prestring(target, idx, iprefs): N = len(iprefs) #leftward_prefs = list(filter(lambda x: x[1] <= idx, iprefs)) #print("t:", target, "i:", idx) #print("iprefs:", iprefs) cc = target[idx] leftward_prefs =iprefs right_limit = bisect.bisect_right(leftward_prefs, (chr(ord(cc) + 1),idx)) #print("right_limit:", right_limit) #print("initial ri based on", target[:idx+1][::-1]) ri = bisect.bisect_right(leftward_prefs, (target[:idx+1][::-1], )) li = ri -1 #print(" ri:", ri) lcp1 = 0 lcp2 = 0 if ri == 0: #print(" nolonger returning") lcp1 = 0 else: while li >=0 and leftward_prefs[li][1] >= leftward_prefs[ri][1]: li -= 1 #print(" li:", li) lcp1 = lcp(leftward_prefs[li][0], leftward_prefs[ri][0]) pos_dif = leftward_prefs[ri][1] - leftward_prefs[li][1] if lcp1 > pos_dif: # could have overlap lcp1 = pos_dif if li > 0: li -= 1 # try next one while li >=0 and leftward_prefs[li][1] >= leftward_prefs[ri][1]: li -= 1 if li > -1: #print("trying at:", li) hmm = lcp(leftward_prefs[li][0], leftward_prefs[ri][0]) #print("hmm:", hmm) if hmm > pos_dif: lcp1 = hmm li = ri if li == N-1: lcp2 = 0 else: ri = li + 1 while ri < right_limit and leftward_prefs[ri][1] >= leftward_prefs[li][1]: ri += 1 #print(" ri:", ri) if ri == right_limit: lcp2 = 0 else: lcp2 = lcp(leftward_prefs[li][0], leftward_prefs[ri][0]) pos_dif = leftward_prefs[li][1] - leftward_prefs[ri][1] if lcp2 > pos_dif: #could have overlap lcp2 = pos_dif ri += 1 while (ri < right_limit and leftward_prefs[ri][1] >= leftward_prefs[li][1]): ri += 1 if ri < right_limit: hmm = lcp(leftward_prefs[li][0], leftward_prefs[ri][0]) if hmm > pos_dif: lcp2 = hmm #print(" lcp1", lcp1) #print(" lcp2", lcp2) return min(max(lcp1, lcp2), math.ceil(idx/2)) def dp_fw(single, substr, target): N = len(target) ti = 0 dp = [0] * (N+1) iprefs = build_inv_prefix_array(target) #print(single, substr, target) while ti < N: #print(" {} : {}".format(ti,target[ti])) dpi = ti + 1 append_cost = dp[dpi-1] + single #print(" finding longest") #matched, whr = _find_longest_ending_here(target, ti) #matched_len = len(matched) matched_len = find_longest_prestring(target, ti, iprefs) #print("@", ti, "longest:'{}'".format(target[ti-(matched_len-1):ti+1])) if matched_len == 0: #copy_cost = sys.maxsize dp[dpi] = append_cost else: copy_cost = substr + dp[dpi-matched_len] final_cost = min(append_cost, copy_cost) dp[dpi] = final_cost ti += 1 return dp def scan_for_prefix(target): N = len(target) jumps = [-1] * (N) prevs = [-1] * (N) prefs = {} ii = N - 1 longest, whr = _find_longest_ending_here(target, ii) #print(" found:", longest) while ii > 0: if longest: matched_len = len(longest) prev_idx = ii - matched_len for jj in range(ii - matched_len+1, ii+1): jumps[jj] = whr prevs[jj] = prev_idx prefs[jj] = longest[:jj - (ii - matched_len +1) + 1] ii -= matched_len else: ii -= 1 #print(" ii:", ii, "target:", target[:ii+1]) longest, whr = _find_longest_ending_here(target, ii, 1) #print(" found:", longest) return jumps, prefs, prevs def cost_to_build(single, substr, target): table1 = dp_fw(single, substr, target) return table1[-1] #return recursive(single, substr, target) SUBSTR_MEMO = {} COST_MEMO = {} def _recur_append(single, substr, target, idx, cost): #print(" " * idx, "A:",target[idx], idx, cost) cost_id =(target, idx, single, substr, "A") if cost_id in COST_MEMO: prior_cost = COST_MEMO.get(cost_id) return prior_cost tmp = cost + single if idx == len(target) - 1: return tmp next_idx = idx + 1 #print("next idx:", next_idx) final = min( _recur_copy(single, substr, target, next_idx, tmp), _recur_append(single, substr, target, next_idx, tmp)) COST_MEMO[cost_id] = final return final def _recur_copy(single, substr, target, idx, cost): min_width = _min_width(single, substr) longest_here = SUBSTR_MEMO.get((target, idx, min_width)) if not longest_here: tmp = cost + single #print("ahhhh") return sys.maxsize return _recur_append(single, substr, target, idx, tmp) #longest_here, found_at = _find_longest_starting_here(target, idx) #SUBSTR_MEMO[(target, idx)] = longest_here else: #print(" " * idx, "A:",target[idx], idx, cost) tmp = cost + substr llen = len(longest_here) next_idx = idx + llen -1 if next_idx == len(target) -1: return tmp elif next_idx > len(target) -1: #print("ahhhh", longest_here) return tmp else: #print("nxt idx:", next_idx) return min( _recur_copy(single, substr, target, next_idx, tmp), _recur_append(single, substr, target, next_idx, tmp)) def _min_width(single, substr): return math.ceil(substr/single) def recursive_forward(single, substr, target): min_width = _min_width(single, substr) any_usable_substr = False for ii in range(len(target)): longest, whr = _find_longest_starting_here(target, ii, min_width) SUBSTR_MEMO[(target, ii, min_width)] = longest if longest is not None: any_usable_substr = True if any_usable_substr: return min( _recur_copy(single, substr, target, 0, 0), _recur_append(single, substr, target, 0, 0)) else: return len(target) * single COST_MEMO = {} def _recur(single, substr, target, idx): cost_id =(target, idx, single, substr) prior_cost = COST_MEMO.get(cost_id) #prior_cost = None if prior_cost: return prior_cost if idx == 0 : COST_MEMO[cost_id] = single #print(" " * idx,idx, target[idx], "acost:",single) return single append_cost = single + _recur(single, substr, target, idx -1) #print(" " * idx,idx, target[idx], "acost:",append_cost) min_width = _min_width(single, substr) longest, whr = _find_longest_ending_here(target, idx, min_width) if longest: matched_len = len(longest) copy_cost = substr + _recur(single, substr, target, idx-matched_len) #print(" " * idx,idx, target[idx], "ccost:",copy_cost, "l:",longest) else: copy_cost = sys.maxsize final_cost = min(append_cost, copy_cost) COST_MEMO[cost_id] = final_cost return final_cost def recursive_back(single, substr, target): N = len(target) return _recur(single, substr, target, N-1) def recursive(single, substr, target): return recursive_back(single, substr, target)
8e657c30b9eba1c9e8642747ea19eb82ea845a7d
iamsubingyawali/WW84-MSLearn
/quiz.py
3,528
4.09375
4
print("\nWONDER WOMAN 1984 Quiz\n") print("Which WONDER WOMAN 1984 character are you most like?") print("To find out, answer the following questions.\n") # ask the candidate a question activity = input( "How would you like to spend your evening?\n(A) Reading a book\n(B) Attending a party\n\nAnswer: " ) if activity == "A": print( "Reading a book, Nice choice!" ) elif activity == "B": print( "Attending a party? Sounds fun!" ) else: print("You must type A or B, let's just say you like to read.") activity = "A" print(" ") # ask the candidate a second question job = input( "What's your dream job?\n(A) Curator at the Smithsonian\n(B) Running a business\n\nAnswer: " ) if job == "A": print( "Curator, Nice choice!" ) elif job =="B": print( "Running a business? Sounds fun!" ) else: print("You must type A or B, let's just say you want to be a curator at the Smithsonian") job = "A" print(" ") # ask the candidate a third question value = input( "What's more important?\n(A) Money\n(B) Love\n\nAnswer: " ) if value == "A": print( "Money, Nice choice!" ) elif value =="B": print( "Love? Sounds fun!" ) else: print("You must type A or B, let's just say money is more important to you.") value = "A" print(" ") # ask the candidate a fourth question decade = input( "What's your favorite decade?\n(A) 1910s\n(B) 1980s\n\nAnswer: " ) if decade == "A": print( "1910s, Nice choice!" ) elif decade =="B": print( "1980s? Sounds fun!" ) else: print("You must type A or B, let's just say the 1910s is your favorite decade.") decade = "A" print(" ") # ask the candidate a fifth question travel = input( "What's your favorite way to travel?\n(A) Driving\n(B) Flying\n\nAnswer: " ) if travel == "A": print( "Driving, Nice choice!" ) elif travel =="B": print( "Flying? Sound fun!" ) else: print("You must type A or B, let's just say your favorite way to travel is by driving") travel = "A" print(" ") # print out their choices # print( f"You chose {activity}, then {job}, then {value}, then {decade}, then {travel}.\n") # create some variables for scoring diana_like = 0 steve_like = 0 max_like = 0 barbara_like = 0 # update scoring variables based on the weapon choice if activity == "A": diana_like = diana_like + 1 barbara_like = barbara_like + 1 else: max_like = max_like + 1 steve_like = steve_like + 1 # update scoring variables based on the job choice if job == "A": diana_like = diana_like + 2 barbara_like = barbara_like + 2 steve_like = steve_like - 1 else: max_like = max_like + 2 # update scoring variables based on the value choice if value == "A": diana_like = diana_like - 1 max_like = max_like + 2 else: diana_like = diana_like + 1 steve_like = steve_like + 2 barbara_like = barbara_like + 1 # update scoring variables based on the decade choice if decade == "A": steve_like = steve_like + 2 diana_like = diana_like + 1 else: max_like = max_like + 1 barbara_like = barbara_like + 2 # update scoring variables based on the travel choice if travel == "A": max_like = max_like + 2 barbara_like = barbara_like - 1 else: diana_like = diana_like + 1 steve_like = steve_like + 1 # print the results depending on the score if diana_like >= 6: print( "You're most like Wonder Woman!" ) elif steve_like >= 6: print( "You're most like Steve Trevor!" ) elif barbara_like >= 6: print( "You're most like Barbara Minerva!") else: print( "You're most like Max Lord!")
0bd110a06a378f2666c6a2edfbfa365071048368
chiragcj96/Algorithm-Implementation
/Design HashMap/sol.py
3,427
4.125
4
''' Modulo + Array As one of the most intuitive implementations, we could adopt the modulo operator as the hash function, since the key value is of integer type. In addition, in order to minimize the potential collisions, it is advisable to use a prime number as the base of modulo, e.g. 2069. We organize the storage space as an array where each element is indexed with the output value of the hash function. In case of collision, where two different keys are mapped to the same address, we use a bucket to hold all the values. The bucket is a container that hold all the values that are assigned by the hash function. We could use either a LinkedList or an Array to implement the bucket data structure. For each of the methods in hashmap data structure, namely get(), put() and remove(), it all boils down to the method to locate the value that is stored in hashmap, given the key. This localization process can be done in two steps: - For a given key value, first we apply the hash function to generate a hash key, which corresponds to the address in our main storage. With this hash key, we would find the bucket where the value should be stored. - Now that we found the bucket, we simply iterate through the bucket to check if the desired <key, value> pair does exist. Time Complexity: for each of the methods, the time complexity is O( K/N ) where N is the number of all possible keys and K is the number of predefined buckets in the hashmap, which is 2069 in our case. Space Complexity: O(K+M) where K is the number of predefined buckets in the hashmap and M is the number of unique keys that have been inserted into the hashmap. ''' class Bucket: def __init__(self): self.bucket = [] def get(self, key): for (k, v) in self.bucket: if k == key: return v return -1 def update(self, key, value): found = False for i, kv in enumerate(self.bucket): if key == kv[0]: self.bucket[i] = (key, value) found = True break if not found: self.bucket.append((key, value)) def remove(self, key): for i, kv in enumerate(self.bucket): if key == kv[0]: del self.bucket[i] class MyHashMap: def __init__(self): """ Initialize your data structure here. """ self.key_space = 2069 self.hash_table = [Bucket() for i in range(self.key_space)] def put(self, key: int, value: int) -> None: """ value will always be non-negative. """ hash_key = key % self.key_space self.hash_table[hash_key].update(key, value) def get(self, key: int) -> int: """ Returns the value to which the specified key is mapped, or -1 if this map contains no mapping for the key """ hash_key = key % self.key_space return self.hash_table[hash_key].get(key) def remove(self, key: int) -> None: """ Removes the mapping of the specified value key if this map contains a mapping for the key """ hash_key = key % self.key_space self.hash_table[hash_key].remove(key) # Your MyHashMap object will be instantiated and called as such: # obj = MyHashMap() # obj.put(key,value) # param_2 = obj.get(key) # obj.remove(key)
63dd9893db75cab163145a0faea4993ae1735ebd
chiragcj96/Algorithm-Implementation
/Dynamic Programming/Pascal's Triangle/solution2.py
887
3.796875
4
''' Dynamic Programming - Here, instead of a complete n*n matrix, we only use a triangle (or upper diagonal triangle of the n*n matrix) 1 1 1 1 2 1 1 3 3 1 1 4 6 4 1 which is 1 1 1 1 1 1 2 3 4 . 1 3 6 . . 1 4 . . . 1 . . . . And we return the values out Time: O(N^2) Space: O(N^2) ''' class Solution: def generate(self, numRows: int) -> List[List[int]]: triangle = [] for row_num in range(numRows): # The first and last row elements are always 1. row = [None for _ in range(row_num+1)] row[0], row[-1] = 1, 1 # Each triangle element is equal to the sum of the elements # above-and-to-the-left and above-and-to-the-right. for j in range(1, len(row)-1): row[j] = triangle[row_num-1][j-1] + triangle[row_num-1][j] triangle.append(row) return triangle
d9b0b3e681d7b127adeb7a8ac2c546dc907806a4
chiragcj96/Algorithm-Implementation
/Reverse String/solution.py
614
3.9375
4
class Solution: def reverseString(self, s: List[str]) -> None: """ Do not return anything, modify s in-place instead. Here, time complexity - O(n) Space complexity - O(2) or O(1) for i and temp """ temp = 0 i=0 while i<len(s)//2: print(i) # option 1 ---- temp = s[i] s[i] = s[-i-1] s[-i-1] = temp # ------------- # Option 2 ---- # s[i], s[-i-1] = s[-i-1], s[i] # ------------- i+=1 return s
b1a5b4059cab4acacb61663490afa3c912e74a11
chiragcj96/Algorithm-Implementation
/Valid Anagram/solution2.py
1,161
3.59375
4
''' Using one Dictinary Increment by 1 if the key is found in s[i] Decrement by 1 if the key is found in t[i] return if all values of the dictionary are zero ''' class Solution: def isAnagram(self, s: str, t: str) -> bool: if len(s)!=len(t): return False dic1 = {} for i in range(len(s)): dic1[s[i]] = dic1.get(s[i], 0) + 1 dic1[t[i]] = dic1.get(t[i], 0) - 1 # Option 1 ---------------------- # for vals in dic1.values(): # if vals != 0: # return False # return True # ------------------------------- # Option 2 ---------------------- return all(val == 0 for val in dic1.values()) # ------------------------------- ''' Time complexity = More than other option as you loop through dic values Space complexity = It will be better as only one dictionary is reqd Time complexity : O(1). because accessing the dictionary is a constant time operation. Space complexity : O(1). Although we do use extra space, the space complexity is O(1) because the dictionary's size stays constant no matter how large n is. '''
c0fe48dba070c8d9d5992a4c5ed56a1269bf5e37
chiragcj96/Algorithm-Implementation
/Reverse Integer/Solution1.py
1,298
3.71875
4
class Solution(object): def reverse(self, x): """ :type x: int :rtype: int ""By applying mathematical formula and generating the integer back in reverse order"" """ result = 0 #The final result multiplier = 10 #to reconstruct the result from individually extracted digits isNegative = False #find if inout integer is negative, if x<0: #if negative, convert it to positive for further operations x = -1*x isNegative = True #Update isNegative Flag to true to reconvert to negative value while x !=0: result = (multiplier*result) + (x % 10) #construct result by extracting each digit and adding it to the end x = x / 10 #update input x each time to remove last digit if isNegative == True: result = -1*result #if input was negtive, reconvert result to negative if result > (2**31-1) or result < (-2**31): #if the final result is beyond the signed 32-bit integer range return 0 return result
be36b04d4be7bed05e5702384b95d400f94ef12f
abrusebas1997/CS2.2-Module4
/code.py
3,605
4.03125
4
import math def get_min(visited, table, neighbors): #optional helper function to find next neighbor to look AttributeError pass def build_shortest_path(graph, start): #return a shortest path table table = {} # take the form #{vertex: [cost, previous]} #{"Port Sarim": [0, ""],} # Get vertices #Initialize table #vertices #Initial costs, 0 and infinity, math.inf #precious, init as empty strings unvisited = [] for v in graph.keys(): unvisited.append(v) if v == start: table[v] = [0, ""] else: table[v] = [math.inf, ""] print(table) print(unvisited) current = start #look at a vertex (start with the given start) #look at its neighbors (for loop to look at all neighbors) while current != None: visited = [] neighbors = graph[current] print("Current: ", current) print("Neighbors", neighbors) for n in neighbors: if n[0] not in visited: #update costs of neighbors in the table #take the current vertice's know cost from the table #add it to the cost of the neighbor from the graph neighbor_name = n[0] print("Neighbor", neighbor_name) neighbor_cost = n[1] current_cost = table[current][0] print("Neighbor cost", neighbor_cost) print("Current cost", current_cost) distance = current_cost + neighbor_cost print("Distance", distance) #update the table with cost ONLY if the distance is LESS than the recorded distance in the table for the neighbor cost_in_table = table[neighbor_name][0] if distance < cost_in_table: #update the table table[neighbor_name][0] = distance #update the previous vertex in the table table[neighbor_name][1] = current #once I'm done looking at all neighbors print(table) print(unvisited) unvisited.remove(current) if len(unvisited) != 0: current = unvisited[0] else: current = None # print("current") # print(current) #replace current vertex with the lowest cost neighbor #look at neighbors not in visited and pick the one with lowest cost in table to look at next #initial min = infinity #loop through neighbors #if neighbor not in visited #get the neighbor's current cost from the table #if the neighbor's current cost from the table #at end should have neighbor with lowest cost #update current to be that neighbor #keep doing this until all vertices are visited, some way of keeping track of what we've visited #while I len of visited < len of my total list of vertices return table def get_shortest_path(table, start, end): list_of_places = [] list_of_places.append(end) current = end while current != start: # table[current] # print(table[current][1]) current = table[current][1] list_of_places.append(current) print(list_of_places) list_of_places.reverse() return list_of_places #return the shortest path given the table #start at the end and keep looking at previous vertices example_graph = {"Port Sarim":[("Darkmeyer", 10), ("Al Kharid", 4)], "Darkmeyer":[("Port Sarim", 10), ("Al Kharid", 4), ("Varrock", 3), ("Nardah", 2)], "Al Kharid": [("Port Sarim", 4), ("Darkmeyer", 4), ("Varrock", 2)], "Varrock":[("Al Kharid", 2), ("Darkmeyer", 3), ("Nardah", 3)], "Nardah": [("Varrock", 3), ("Darkmeyer", 2)]} table = build_shortest_path(example_graph, "Darkmeyer") print(get_shortest_path(table, "Darkmeyer", "Nardah"))
6b6dae17b4cdb0af548f79350deb1e6657084552
IamHehe/TrySort
/1.bubble_sort.py
603
4.15625
4
# coding=utf-8 # author: dl.zihezhu@gmail.com # datetime:2020/7/25 11:23 """ 程序说明: 冒泡排序法 (目标是从小到大排序时) 最好情况:顺序从小到大排序,O(n) 最坏情况:逆序从大到小排序,O(n^2) 平均时间复杂度:O(n^2) 空间复杂度:O(1) """ def bubbleSort(arr): for i in range(1, len(arr)): for j in range(0, len(arr) - i): if arr[j] > arr[j + 1]: arr[j], arr[j + 1] = arr[j + 1], arr[j] return arr if __name__ == "__main__": lis = [3, 4, 2, 1, 6, 5] print(bubbleSort(lis))
0ab3c263766f174b04f319ba773a14e1e56170da
IamHehe/TrySort
/5.merge_sort.py
2,389
4.15625
4
# coding=utf-8 # author: dl.zihezhu@gmail.com # datetime:2020/7/26 12:31 """ 程序说明: 归并排序 (目标是从小到大排序时) 最好情况:O(n log n) 最坏情况:O(n log n) 平均时间复杂度:O(n log n) 空间复杂度:自上到下:因为需要开辟一个等长的数组以及使用了二分的递归算法,所以空间复杂为O(n)+O(log n)。自下向上:O(1) 稳定 """ # 自上向下分,递归 def merge_sort(arr): if len(arr) < 2: return arr middle = len(arr) // 2 left, right = arr[0:middle], arr[middle:] # 分 return merge(merge_sort(left), merge_sort(right)) # 治:递归而下 # 共有log n +1 层即时间复杂度为# O(n * log n) def merge(left, right): res = [] # 这里相当于开辟了同等大小的空间,使得空间复杂度为O(n) while left and right: # O(n) if left[0] <= right[0]: res.append(left.pop(0)) else: res.append(right.pop(0)) while left: # O(n) res.append(left.pop(0)) while right: # O(n) res.append(right.pop(0)) return res # 归并排序,新增自下至上的迭代,通过扩展步长weight进行 # 参考:https://www.pythonheidong.com/blog/article/453039/ def BottomUp_merge_sort(a): n = len(a) b = a[:] # 深拷贝一个a width = 1 # 步长 while width < n: # 步长小于列表长度 start = 0 # 起始位置 while start < n: mid = min(n, start + width) # n只有在最后start+width超过整个句子的长度的时候才会被选取 end = min(n, start + (2 * width)) BottomUp_Merge(a, b, start, mid, end) start += 2 * width a = b[:] # 使用合并排序后的结果作为下一次迭代的基础 width *= 2 # 2 4 8 16 这样的方式获取 return a def BottomUp_Merge(a, b, start, mid, end): i = start j = mid for k in range(start, end): if i < mid and (j >= end or a[i] <= a[j]): # j>=end 即后面的不尽兴操作,直接复制 b[k] = a[i] i += 1 else: b[k] = a[j] j += 1 if __name__ == "__main__": lis = [3, 4, 2, 1, 6, 5] print(merge_sort(lis)) lis = [3, 4, 2, 1, 6, 5] lis = BottomUp_merge_sort(lis) print(lis)
25f48a1aa35d02ee6707be99e2622968aa01d00a
doudou110975/test
/test.py
702
3.5625
4
#01、环境搭建与检测 import cv2 as cv import numpy as np print("--------------Hi,python--------------") src = cv.imread("D:/Python_instance/pythonface/6.jpg") #打开一个窗口 #cv2.namedWindow(<窗口名>,x) #x=cv2.WINDOW_AUTOSIZE-----默认大小,不能改动 #x=cv2.WINDOW_NORMAL #或cv2.WINDOW_FREERATIO-----可以改动窗口大小 cv.namedWindow("input image",cv.WINDOW_AUTOSIZE) cv.imshow("input image",src) # 简而言之如果有正数x输入则 等待x ms,如果在此期间有按键按下,则立即结束并返回按下按键的ASCII码,否则返回-1 # 如果x=0,那么无限等待下去,直到有按键按下 cv.waitKey(0) cv.destroyAllWindows()
918eb58500dd5f5f90182f78e024835fd69cc003
lucaspereirag/cursosUdemy
/vetores_nao_ordenados.py
1,896
3.5625
4
import numpy as np class VetorNaoOrdenado: def __init__(self, capacidade): self.capacidade = capacidade self.ultima_posicao = -1 # np.empty cria um array vazio e com o tamanho agora definido pela própria capacidade e de nº inteiros self.valores = np.empty(self.capacidade, dtype=int) #imprime os dados do vetor def imprime(self): if self.ultima_posicao == -1: print(f'O vetor está vazio') else: for i in range(self.ultima_posicao + 1): print(f'Na posição [{i}]', '=', self.valores[i]) def imprimir(self): print(self.valores) #insere dados no vetor: def inserir(self, valor): if self.ultima_posicao == self.capacidade - 1: print(f'Capacidade Máxima já foi atingida.') else: self.ultima_posicao += 1 self.valores[self.ultima_posicao] = valor def pesquisa_linear(self, valor): for i in range(self.ultima_posicao + 1): if valor == self.valores[i]: return i #retorna qual posição o nr pesquisado está return -1 #elemento não existe def excluir(self, valor): #encontra se o valor existe: posicao = self.pesquisar(valor) #apaga se encontrar: if posicao == -1: return -1 #não existe else: for i in range(posicao, self.ultima_posicao): self.valores[i] = self.valores[i + 1] self.ultima_posicao -= 1 vetor = VetorNaoOrdenado(5) vetor.inserir(3) vetor.inserir(5) vetor.inserir(8) vetor.inserir(1) vetor.inserir(7) vetor.imprime() print('-' * 30) vetor.excluir(5) vetor.imprime() #vetor.imprime() print('-' * 30) print(f'Na posição: {vetor.pesquisar(300)}') #retorna -1 print(f'Na posição: {vetor.pesquisar(8)}') #retorna 2 print('-' * 30) vetor.imprimir()
479c920dc6027a871e67d2a7f8068a75c157a92b
casualhuman/BasCalcs
/calcs/calculations.py
1,498
4
4
# This is where al the calculations snippets are located # Ohms law calculations def get_resistance(voltage, current): try: resistance_value = int(voltage) / int(current) resistance_value = f'Resistance = {resistance_value:.3f} Ω' except: resistance_value = 'Current should not be 0' return resistance_value # Calculates the current value if current is chosen as value needed def get_current(voltage, resistance): try: current_value = int(voltage) / int(resistance) current_value = f'Current = {current_value:.3f} A' except ZeroDivisionError: current_value = 'Resistance should not be 0' return current_value # Calculates the voltage value if voltage if chosen as value needed def get_voltage(current, resistance): voltage_value = int(current) * int(resistance) return f'Voltage = {voltage_value} v' # Area Calculations def get_square_area(length): # Area of Square square_area = length * 2 return square_area def get_rectangle_area(length, breath): rectangle_area = length * breath return rectangle_area # Perimeter Calculations def get_square_perimeter(length): perimeter = 4 * length return perimeter def get_rectangle_perimeter(length, breath): rectangle_area = length + breath # First find the area of rectangle becuase perimeter = 2(l + b) perimeter = 2 * rectangle_area return perimeter
d990ed78e1ecc5dd47c002e438d23400c72badba
mochadwi/mit-600sc
/unit_1/lec_4/ps1c.py
1,368
4.1875
4
# receive Input initialBalance = float(raw_input("Enter your balance: ")) interestRate = float(raw_input("Enter your annual interest: ")) balance = initialBalance monthlyInterestRate = interestRate / 12 lowerBoundPay = balance / 12 upperBoundPay = (balance * (1 + monthlyInterestRate) ** 12) / 12 while True: balance = initialBalance monthlyPayment = (lowerBoundPay + upperBoundPay) / 2 # bisection search for month in range(1,13): interest = round(balance * monthlyInterestRate, 2) balance += interest - monthlyPayment if balance <= 0: break if (upperBoundPay - lowerBoundPay < 0.005): # TOL (tolerance) # Print result print "RESULT" monthlyPayment = round(monthlyPayment + 0.004999, 2) print "Monthly Payment to pay (1 Year): $", round(monthlyPayment, 2) # recalculate balance = initialBalance for month in range(1,13): interest = round(balance * monthlyInterestRate, 2) balance += interest - monthlyPayment if balance <= 0: break print "Months needed: ", month print "Your balance: $", round(balance, 2) break elif balance < 0: # Paying too much upperBoundPay = monthlyPayment else: # Paying too little lowerBoundPay = monthlyPayment
b6be8e950be89b757dc9aee0552ffc17241ff1a3
yo1995/Daily_agorithm_practices
/190816_ropes/ropes.py
1,354
3.53125
4
from typing import List def combine_ropes(ropes: List[List[str]]) -> bool: count = 0 prev = len(ropes) ropes_remaining = ropes while ropes_remaining: print(ropes_remaining) if count == prev: return False current_rope = [ropes_remaining[0][0], ropes_remaining[0][1]] prev = len(ropes) count = 1 temp = [] for rope in ropes_remaining[1:]: if rope[0] == current_rope[0]: current_rope = [rope[1], current_rope[1]] elif rope[0] == current_rope[1]: current_rope = [current_rope[0], rope[1]] elif rope[1] == current_rope[0]: current_rope = [rope[0], current_rope[1]] elif rope[1] == current_rope[1]: current_rope = [current_rope[0], rope[0]] else: count += 1 temp.append(rope) continue if not temp: return True else: temp.append(current_rope) ropes_remaining = temp return True if __name__ == '__main__': test1 = [['a', 'b'], ['c', 'd'], ['e', 'f'], ['f', 'g'], ['c', 'g'], ['b', 'd']] test2 = [['a', 'a'], ['b', 'b'], ['c', 'd']] test3 = [['a', 'a']] test4 = [['a', 'a'], ['a', 'b'], ['b', 'c']] print(combine_ropes(test2))
00501186586870c783628486cf11ab2c03109d18
yo1995/Daily_agorithm_practices
/190614_HW2_DFS_BFS/level_order_traversal.py
296
3.703125
4
from collections import deque def level_order_traversal(r): q = deque() q.append(r) while q: top = q.popleft() print(top.val) if top.left: q.append(top.left) pass if top.right: q.append(top.right) pass
aff991ee63136e6b3d1a179d715a5ef5ad8ddd30
yo1995/Daily_agorithm_practices
/190623_HW4_Tree_Hash/problem2_check_duplicate_window.py
423
3.6875
4
def check_duplicate(array, k): s = set(array[:k]) if len(s) < k: return True l = len(array) if l < k: return False for i in range(k, l): top = array[i-k] if array[i] in s: return True s.remove(top) s.add(array[i]) return False if __name__ == '__main__': arr = [1, 2, 3, 4, 1, 2, 3, 4] k = 3 print(check_duplicate(arr, k))
966fe0602963d5fcaf9f25afcc9b9e6b97ab52b8
yo1995/Daily_agorithm_practices
/190614_HW2_DFS_BFS/min_depth_btree.py
1,605
3.890625
4
from collections import deque from typing import List class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None def min_depth(root: TreeNode) -> int: if not root: return 0 else: md = 0 q1 = deque() q1.append(root) while q1: q2 = deque() while q1: top = q1.popleft() if (not top.left) and (not top.right): return md if top.left: q2.append(top.left) if top.right: q2.append(top.right) md += 1 q1 = q2 # complete tree, just return the final result return md def min_depth_recursive(self, root: TreeNode) -> int: if root is None: return 0 # if root.left is None and root.right is None: # return 1 left = self.minDepth(root.left) right = self.minDepth(root.right) if left != 0 and right != 0: return min(left, right) + 1 else: return left + right + 1 def min_depth_stack(root: TreeNode) -> int: # since nothing to do with order, stack is better in space complexity if not root: return 0 depth = 1 stack = [root] while stack: next_level = [] for node in stack: if not node.left and not node.right: return depth else: if node.left: next_level.append(node.left) if node.right: next_level.append(node.right) stack = next_level depth += 1
a93e1a26564de8dbffecf7b134ae97c175dd0951
anandababugudipudi/Python-Programs
/Python DS/Generators.py
1,227
3.859375
4
# -*- coding: utf-8 -*- """ Created on Sun Jan 31 16:46:44 2021 @author: anand """ def new(dict): for key, value in dict.items(): return key, value a = {1:"One", 2:"Two", 3:"Three"} b = new(a) # Generators in loops def ex(): n = 3 yield n n = n * n yield n v = ex() for x in v: print (x) # Generators in expressions f = range(6) print ("List comp", end = ":") q = [x+2 for x in f] print(q) print("Generator eXpression ", end =": ") r = (x+2 for x in f) for x in r: print(x) # Using Generators for finding fibonacci series def fibonacci(): f,s = 0,1 while True: yield f f,s = s, s+f for x in fibonacci(): if x > 50: break print(x, end=" ") # Number Stream a = range(100) b = (x for x in a) for i in b: print(i) # Sinewave import numpy as np from matplotlib import pyplot as plt import seaborn as sb def s(flip = 2): x = np.linspace(0, 14, 100) for i in range(1, 10): yield(plt.plot(x,np.sin(x + i * .5)*(7-i) * flip)) sb.set() s = s() plt.show() print(next(s))
e01e1d79e79be4c9f12812f1fc320c34bf1a5df7
anandababugudipudi/Python-Programs
/Python DS/Functions.py
3,395
4.21875
4
# -*- coding: utf-8 -*- """ Created on Sun Jan 31 15:32:19 2021 @author: anand """ # First class objects, using functions as arguments def func1(name): return f"Hello {name}" def func2(name): return f"{name}, how you doing?" def func3(func4): return func4("Dear Learner") print(func3(func1)) print(func3(func2)) # Inner functions or Nested function def func(): print("First function.") def func1(): print("First child function") def func2(): print("Second child function") func2() func1() func() def func(n): def func1(): return "Edureka" def func2(): return "Python" if n == 1: return func1() else: return func2() a = func(1) b = func(3) print (a) print (b) # Decorator functions def header(name): def wrapper(): print("Hello") name() print("Welcome to Python Course.") return wrapper def returnName(): print("User") returnName = header(returnName) #wrapper text returnName() #Using Syntactic Sugar in Decorator def header(name): def wrapper(): print("Hello") name() print("Welcome to Python Course.") return wrapper @header #Syntactic Sugar def returnName(): print("User") returnName() # Using arguments in function def header(name): def wrapper(*args, **kwargs): print("Hello") name(*args, **kwargs) print("Welcome to Python Course.") return wrapper @header #Syntactic Sugar def returnName(name): print(f"{name}") returnName("Google") # Returning arguments def header(name): def wrapper(*args, **kwargs): print("Hello") return wrapper @header #Syntactic Sugar def returnName(name): print(f"{name}") returnName("Google") import functools # Class objects class Square: def __init__(self, side): self._side = side @property def side(self): return self._side @side.setter def side(self, value): if value >= 0: self._side = value else: print("Error") @property def area(self): return self._side ** 2 @classmethod def unit_square(cls): return cls(1) s = Square(5) print (s.side) print (s.area) # Singleton Class def singleton(cls): @functools.wraps(cls) def wrapper(*args, **kwargs): if not wrapper.instance: wrapper.instance = cls(*args, **kwargs) return wrapper.instance wrapper.instance = None return wrapper @singleton class one: pass first = one() second = one() print(first is second) # Nesting Decorators def repeat(num): def decorator_repeat(func): @functools.wraps(func) def wrapper(*args, **kwargs): for _ in range(num): value = func(*args, **kwargs) return value return wrapper return decorator_repeat @repeat(num = 5) def function (name): print(f"{name}") function("Python")
601b2985f4780aee6eb336aefd21182268b3af7d
bledidalipaj/codefights
/challenges/python/awardedprizes.py
4,763
3.515625
4
""" At the county fair there is a contest to guess how many jelly beans are in a jar. Each entrant is allowed to submit a single guess, and cash prizes are awarded to the entrant(s) who come closest without going over. In the event that there are fewer guesses less than or equal to the answer than the number of prizes being awarded, the remaining prizes will be awarded to the remaining entrants who are closest to the correct answer (however, if there are more prizes than entries, the excess prizes will not be awarded). If two or more entrants tie for a finishing position, they will evenly split the sum of the prizes for the range of positions they occupy. Given an array representing the prizes paid for each finishing position, an array of the guesses, and the correct answer, return an array of the prizes awarded to each entrant. If a tie results in a fractional prize amount, round up to the nearest penny (e.g. $10 / 3 = $3.34). Example For prizes = [ [1,1,100], [2,2,50], [3,4,25] ], guesses = [65, 70, 78, 65, 72] and answer = 70, the output should be awardedPrizes(prizes, guesses, answer = [37.5, 100.0, 0.0, 37.5, 25.0]. The prizes represent the following prize structure: 1st place wins $100; 2nd place wins $50; 3rd place wins $25; 4th place wins $25. The entrant who guessed 70 was closest, and wins $100 for 1st place. The two entrants who guessed 65 were next closest (without going over), and so they split the total prizes for 2nd and 3rd place. Thus each wins (50 + 25) / 2 = $37.50. No one else submitted a guess less than the answer, so the entrant who guessed 72 was next closest, and wins $25 for 4th place. The entrant who guessed 78 does not win a prize. The answer is thus [37.5, 100.0, 0.0, 37.5, 25.0]. Input/Output [time limit] 4000ms (py3) [input] array.array.integer prizes An array of prize tiers; each tier is an array with three elements: start_position, end_position, and prize_amount. The tiers are not necessarily provided in order. However, it is guaranteed that these tiers combine such that there is a single prize for each finishing position from 1 through some position k, and no prizes beyond that point (i.e. no gaps in the prize structure). Constraints: 1 ≤ prizes.length ≤ 20, 1 ≤ prizes[i][0] ≤ prizes[i][1] ≤ 20, 1 ≤ prizes[i][2] ≤ 100. [input] array.integer guesses An array of the guesses made by each entrant in the contest. Constraints: 1 ≤ guesses.length ≤ 100. [input] integer answer The actual number of jelly beans in the jar. Constraints: 1 ≤ answer ≤ 100. [output] array.float An array containing the prize awarded to each entrant, in the same order as their guesses. # Challenge's link: https://codefights.com/challenge/FQJuF4Tsz632pcWgX # """ from collections import defaultdict def awardedPrizes(prizes, guesses, answer): res = [0] * len(guesses) # sort prizes prizes.sort(key=lambda el: el[0]) # key: answer - entrant guess # value: a list which holds the indexes of all the entrants # that guessed the same number performanceIndexesDict = defaultdict(list) for index, guess in enumerate(guesses): dist = answer - guess if dist < 0: dist = guess performanceIndexesDict[dist].append(index) positionPrizeDict = {} for prize in prizes: for i in range(prize[0], prize[1] + 1): positionPrizeDict[i] = prize[2] numOfPrizes = len(positionPrizeDict) position = 1 for closestGuess in sorted(performanceIndexesDict.keys()): if position > numOfPrizes: break winners = performanceIndexesDict[closestGuess] cash = 0 for i in range(position, position + len(winners)): if i > numOfPrizes: break cash += positionPrizeDict[i] position += len(winners) # split the total prizes cash /= len(winners) # round up to the second decimal position cash = math.ceil(cash * 100) / 100 for winner in winners: res[winner] = cash return res def awardedPrizes(prizes, guesses, answer): res = [0] * len(guesses) rewards = [0] * 20 for start, end, val in prizes: for i in range(start - 1, end): rewards[i] = val sorted_guesses = list(enumerate(guesses)) sorted_guesses.sort(key=lambda x: (x[1] > answer, abs(x[1] - answer))) i = 0 while i < len(sorted_guesses): val = sorted_guesses[i][1] cnt = guesses.count(val) reward = math.ceil(sum(rewards[i:i + cnt]) / cnt * 100) / 100 for j in range(i, i + cnt): res[sorted_guesses[j][0]] = reward i += cnt return res
2ebfb0660341e2e574d002e7bc7562296b1cb3f2
bledidalipaj/codefights
/challenges/python/sortit.py
1,359
4.09375
4
""" You are given a string, your goal is to rearrange its letters in alphabetical order. If the same letter is present both in lowercase and uppercase forms in the initial string, the uppercase occurrence should go first in the resulting string. Example For str = "Vaibhav", the output should be sortIt(str) = "aabhiVv". [time limit] 4000ms (py) [input] string str A string consisting only of letters. Constraints: 1 ≤ str.length ≤ 20 [output] string # Challenge's link: https://codefights.com/challenge/KBmHkh6b7q68QBiHd/ # """ def sortIt(s): lower = [] upper = [] for char in s: if 'a' <= char <= 'z': lower.append(char) else: upper.append(char) return "".join(sorted(upper + lower, key=lambda s: s.lower())) def sortIt(s): return "".join(sorted(sorted(s), key=lambda s: s.lower())) def sortIt(s): cnt = [0] * 256 for c in s: cnt[ord(c)] += 1 res = "" for i in range(26): for j in range(cnt[ord('A') + i]): res += chr(ord('A') + i) for j in range(cnt[ord('a') + i]): res += chr(ord('a') + i) return res sortIt = lambda s: "".join(sorted(s,key=lambda a: a.lower()+a)) sortIt = lambda S: `sorted(c.lower()+c for c in S)`[4::7] sortIt = lambda S: "".join(sorted(c.lower()+c for c in S))[1::2] sortIt = lambda s: ''.join(sorted(s, key=lambda x: (x.lower(), x)))
c58f61175404a276ee72ec6be4b5f828a4a19f59
bledidalipaj/codefights
/challenges/python/doublethemoneygame.py
2,039
3.640625
4
""" A group of n people played a game in which the loser must double the money of the rest of the players. The game has been played n times, and each player has lost exactly once. Surprisingly, each player ended up with the same amount of money of m dollars. Considering all that, find the amount of money each player had at the very beginning, and return it as an array of n elements sorted in descending order. Example For n = 3 and m = 16, the output should be doubleTheMoneyGame(n, m) = [ 26.0, 14.0, 8.0 ]. Let's say that player A started with $26, player B had $14, and player C had $8. After the first game, player A lost, and had to pay double the amount of players' B and C money. So the amount of money the players had at the end of the game was [ 4.0, 28.0, 16.0 ]. After the second game, player B lost, and the "money array" became [ 8.0, 8.0, 32.0 ]. After the third game, player C lost, the money became [ 16.0, 16.0, 16.0 ]. Input/Output [time limit] 4000ms (py) [input] integer n The number of players, aka the number of played games. Constraints: 2 ≤ n ≤ 7. [input] integer m The same amount of money each player has after n game played. Constraints: 1 ≤ m ≤ 10000. [output] array.float The amount of money each player had in the beginning of the game sorted in descending order. It is guaranteed that the values in the output won't have more than 5 digits after the decimal point. # https://codefights.com/challenge/4Mpg5NjZrFJtqvhGC/main # """ def doubleTheMoneyGame(n, m): res = [m * 1.0] * n for i in range(n): # loser = res[i] for j in range(n): if i != j: res[j] /= 2 res[i] += res[j] return sorted(res, reverse=True) def doubleTheMoneyGame(n, m): res = [m] * n for i in range(n): wasMoney = 0 for j in range(n): if j == i: continue wasMoney += res[j] / 2. res[j] /= 2. res[i] += wasMoney return sorted(res, reverse=True)
73b89ce8f79dfe1a5b1e6ceaa76900c09e420428
bledidalipaj/codefights
/challenges/python/sinarea.py
983
3.890625
4
""" You guys should probably know the simple y = sin(x) equation. Given a range of x [start, end], your mission is to calculate the total signed area of the region in the xy-plane that is bounded by the sin(x) plot, the x-axis and the vertical lines x = start and x = end. The area above the x-asix should be added to the result, and the area below it should be subtracted. Example For start = 0 and end = 10, the output should be sinArea(start, end) = 1.83907. For start = 4 and end = 6, the output should be sinArea(start, end) = -1.61381. Input/Output [time limit] 4000ms (py) [input] integer start Constraints: -3·106 < start < 3·106 [input] integer end Constraints: -3·106 < start ≤ end < 3·106 [output] float The signed area. Your answer will be considered correct if its absolute error doesn't exceed 10-5. # Challenge's link: https://codefights.com/challenge/L7EqDZzBuE5twLtAD # """ def sinArea(start, end): return math.cos(start) - math.cos(end)
ec097380731f8137b8715b214fbeb94a9e054da5
bledidalipaj/codefights
/challenges/python/issentencepalindrome.py
2,120
4.0625
4
""" As a high school student, you naturally have a favourite professor. And, even more natural, you have a least favourite one: professor X! Having heard that you're an experienced CodeFighter, he became jealous and gave you an extra task as a homework. Given a sentence, you're supposed to find out if it's a palindrome or not. The expected output for most of the test cases baffled you, but you quickly realize where the catch is. Looks like your professor assumes that a string is a palindrome if the letters in it are the same when you read it normally and backwards. Moreover, the tests even ignore the cases of the letters! Given the sentence your professor wants you to test, return true if it's considered to be a palindrome by your professor, and false otherwise. Example For sentence = "Bob: Did Anna peep? | Anna: Did Bob?", the output should be isSentencePalindrome(sentence) = true. Input/Output [time limit] 4000ms (py3) [input] string sentence A string consisting of various characters. Constraints: 1 ≤ sentence ≤ 30. [output] boolean true if the sentence is a palindrome according to your professor and false otherwise. """ def isSentencePalindrome(sentence): letters = [] for char in sentence.lower(): if 'a' <= char <= 'z': letters.append(char) left_index = 0 right_index = len(letters) - 1 while left_index <= right_index: if letters[left_index] != letters[right_index]: return False left_index += 1 right_index -= 1 return True def isSentencePalindrome(sentence): letters = [char for char in sentence.lower() if 'a' <= char <= 'z'] return letters == letters[::-1] def isSentencePalindrome(sentence): s = re.sub('\W', '', sentence.lower()) return s == s[::-1] def isSentencePalindrome(sentence): trimmed = ''.join([ch.lower() for ch in sentence if ch.isalpha()]) return trimmed == trimmed[::-1] def isSentencePalindrome(sentence): # remove symbols and punctuation trimmed = re.sub(r'[^a-z]', '', sentence.lower()) return trimmed == trimmed[::-1]
6e9f7ffbe8ffcb7cbc7ddd2d493ee8cbfc1fe126
bledidalipaj/codefights
/challenges/python/flowersandflorets.py
3,618
4.15625
4
""" You would like to create your own little farm. Since you're not an expert (yet!), you bought seeds of just two types of plants: flowers and florets. Each pack of seeds was provided with the instructions, explaining when the plant can be planted. In the instructions two dates are given, to and from, which denote the favorable period for planing the seeds. Note, that to is not necessarily larger than from: if to is less than from, then the period is counted from to to from through the beginning of the new year. It is always assumed that there are 365 days in a year. Given the dates from the flower instructions flowerFrom and flowerTo and from the floret instructions floretFrom and floretTo, calculate the number of days of the year in which both plants can be planted. Example For flowerFrom = 10, flowerTo = 20, floretFrom = 1 and floretTo = 365, the output should be flowersAndFlorets(flowerFrom, flowerTo, floretFrom, floretTo) = 11. Flowers can only be planted in the period from the 10th to the 20th day of the year, and florets can be planted any time. Thus, the output should be equal to the number of days in which flowers can be planted, which is 11. For flowerFrom = 100, flowerTo = 150, floretFrom = 110 and floretTo = 130, the output should be flowersAndFlorets(flowerFrom, flowerTo, floretFrom, floretTo) = 21. The favorable days for planting overlap in the period from the 110th to the 130th day of the year, 21 days in total. For flowerFrom = 360, flowerTo = 10, floretFrom = 1 and floretTo = 365, the output should be flowersAndFlorets(flowerFrom, flowerTo, floretFrom, floretTo) = 16. Flowers can only be planted in the period from the 1th to the 10th day of the year, and from the 360th to the 365th days, and florets can be planted any time. Thus, the output should be equal to the number of days in which flowers can be planted, which is 16. Input/Ouptut [time limit] 4000ms (py) [input] integer flowerFrom The starting day of flowers planting season. Constraints: 1 ≤ flowerFrom ≤ 365. [input] integer flowerTo The last day of flowers planting season. Constraints: 1 ≤ flowerTo ≤ 365, flowerTo ≠ flowerFrom. [input] integer floretFrom The starting day of florets planting season. Constraints: 1 ≤ floretFrom ≤ 365. [input] integer floretTo The last day of florets planting season. Constraints: 1 ≤ floretTo ≤ 365, floretTo ≠ floretFrom. [output] integer The number of days in which both type of seeds can be planted. # Challenge's link: https://codefights.com/challenge/Qk4DePWLz72jnfsXy # """ def flowersAndFlorets(flowerFrom, flowerTo, floretFrom, floretTo): def favorableDays(fromDay, toDay): days = set() day = fromDay while day != toDay: days.add(day) day += 1 if day > 365: day = 1 days.add(toDay) return days flowerFavorableDays = favorableDays(flowerFrom, flowerTo) floretFavorableDays = favorableDays(floretFrom, floretTo) commonDays = flowerFavorableDays.intersection(floretFavorableDays) return len(commonDays) def flowersAndFlorets(flowerFrom, flowerTo, floretFrom, floretTo): def getFineDates(fr, to): res = [False] * 365 if to > fr: res[fr - 1 : to] = [True] * (to - fr + 1) else: res[:to] = [True] * to res[fr - 1:] = [True] * (365 - fr + 1) return res res1 = getFineDates(flowerFrom, flowerTo) res2 = getFineDates(floretFrom, floretTo) return len([1 for i in range(365) if res1[i] and res2[i]])
7ea9ed580687c2d074abc5e1f185350fdbde7bdb
bledidalipaj/codefights
/challenges/python/friendlynumbers.py
1,067
3.875
4
""" Numbers x and y (x ≠ y) are called friendly if the sum of proper divisors of x is equal to y, and the other way round. Given two integers x and y, your task is to check whether they are friendly or not. Example For x = 220 and y = 284, the output should be friendly_numbers(x, y) = "Yes". The proper divisors of 220 are 1, 2, 4, 5, 10, 11, 20, 22, 44, 55 and 110, which add up to 284; and the proper divisors of 284 are 1, 2, 4, 71 and 142, which add up to 220. Input/Output [time limit] 4000ms (py) [input] integer x Constraints: 1 ≤ x ≤ 105. [input] integer y Constraints: 1 ≤ y ≤ 105. [output] string "Yes" if x and y are friendly and "No" otherwise. # Challenge's link: https://codefights.com/challenge/zeS6of248AhuJB3xM # """ def friendly_numbers(x, y): def divisors_sum(n): res = 1 i = 2 while i * i <= n: if n % i == 0: res += n / i + i i += 1 return res return "Yes" if x != y and divisors_sum(x) == y and divisors_sum(y) == x else "No"
fbaf789fbe6bfaede28d2b2d3a6a1673e229f57b
bledidalipaj/codefights
/challenges/python/holidaybreak.py
2,240
4.375
4
""" My kids very fond of winter breaks, and are curious about the length of their holidays including all the weekends. Each year the last day of study is usually December 22nd, and the first school day is January 2nd (which means that the break lasts from December 23rd to January 1st). With additional weekends at the beginning or at the end of the break (Saturdays and Sundays), this holiday can become quite long. The government issued two rules regarding the holidays: The kids' school week can't have less than 3 studying days. The holidays should thus be prolonged if the number of days the kids have to study before or after the break is too little. If January 1st turns out to fall on Sunday, the following day (January 2nd) should also be a holiday. Given the year, determine the number of days the kids will be on holidays taking into account all the rules and weekends. Example For year = 2016, the output should be holidayBreak(year) = 11. First day of the break: Friday December 23rd. Last day of the break: Monday January 2nd. Break length: 11 days. For year = 2019, the output should be holidayBreak(year) = 16. First day of the break: Saturday December 21st. Last day of the break: Sunday January 5th. Break length: 16 days. *** Due to complaints, I've added a hidden Test outside of the range. The Year now goes to 2199 *** [time limit] 4000ms (py) [input] integer year The year the break begins. Constraints: 2016 ≤ year ≤ 2199. [output] integer The number of days in the break. # Challenge's link: https://codefights.com/challenge/yBwcdkwQm5tAG2MJo # """ import calendar def holidayBreak(year): first_day = 23 last_day = 31 + 1 # first day of the break weekday = calendar.weekday(year, 12, 23) if weekday == 0: first_day -= 2 elif weekday == 1: first_day -= 3 elif weekday == 2: first_day -= 4 elif weekday == 6: first_day -= 1 # last day of the break weekday = calendar.weekday(year + 1, 1, 1) if weekday == 6 or weekday == 5: last_day += 1 elif weekday == 4: last_day += 2 elif weekday == 3: last_day += 3 elif weekday == 2: last_day += 4 return last_day - first_day + 1
9d01048c217072623b64718f5b90a747cea12993
shivamt91/theweatherapp
/weather.py
1,288
3.59375
4
import sys import requests import json from today import today from hourbyhour import hourbyhour from monthly import monthly def the_weather(): arguments = sys.argv if len(arguments) == 2: place = arguments[1] type_of_forecast = 'today' elif len(arguments) == 3: place = arguments[1] type_of_forecast = arguments[2] else: return 'Please give valid parameters!' api = 'https://api.weather.com/v3/location/search?apiKey=d522aa97197fd864d36b418f39ebb323&format=json&language=en-IN&locationType=locale&query=' my_api = api + place response = requests.get(my_api) if response.status_code == 200: data = json.loads(response.text) cities = data['location']['city'] i = 0 for i in range(len(cities)): if cities[i].lower() == place.lower(): break place_id = data['location']['placeId'][i] if type_of_forecast == 'hourbyhour': print(hourbyhour(place_id)) elif type_of_forecast == 'today': print(today(place_id)) elif type_of_forecast == 'monthly': print(monthly(place_id)) else: return 'Please enter a valid type_of_forecast!' else: return 'Please enter a valid place!' the_weather()
0bad5a8a7ee86e45043ef0ddf38406a9ee4d1032
pmayd/python-complete
/code/exercises/solutions/words_solution.py
1,411
4.34375
4
"""Documentation strings, or docstrings, are standard ways of documenting modules, functions, methods, and classes""" from collections import Counter def words_occur(): """words_occur() - count the occurrences of words in a file.""" # Prompt user for the name of the file to use. file_name = input("Enter the name of the file: ") # Open the file, read it and store its words in a list. # read() returns a string containing all the characters in a file # and split() returns a list of the words of a string “split out” based on whitespace with open(file_name, 'r') as f: word_list = f.read().split() # Count the number of occurrences of each word in the file. word_counter = Counter(word_list) # Print out the results. print( f'File {file_name} has {len(word_list)} words ({len(word_counter)} are unique).\n' # f-strings dont need a \ character for multiline usage f'The 10 most common words are: {", ".join([w for w, _ in word_counter.most_common(10)])}.' ) return word_counter # this is a very important part of a module that will only be executed # if this file is calles via command line or the python interpreter. # This if statement allows the program to be run as a script by typing python words.py at a command line if __name__ == '__main__': words_occur()
1011b0a5d86b6aeb31c928bea06c55a679e61fa6
pmayd/python-complete
/code/exercises/sum.py
530
3.8125
4
import doctest def mysum(...): """The challenge here is to write a mysum function that does the same thing as the built-in sum function. However, instead of taking a single sequence as a parameter, it should take a variable number of arguments. Thus while we might invoke sum([1,2,3]), we would instead invoke mysum(1,2,3) or mysum(10,20,30,40,50). Examples: >>> mysum(1,2,3) 6 >>> mysum(-1,0,1) 0 >>> mysum(10,20,30,40,50) 150 """ pass if __name__ == "__main__": doctest.testmod()
95b308d6bdb204928c6b014c8339c2cc8693b7d7
pmayd/python-complete
/code/exercises/most_repeating_word.py
870
4.3125
4
import doctest def most_repeating_word(words: list) -> str: """ Write a function, most_repeating_word, that takes a sequence of strings as input. The function should return the string that contains the greatest number of repeated letters. In other words: for each word, find the letter that appears the most times find the word whose most-repeated letter appears more than any other Bonus: - make function robust (empty list, etc) - add parameter to count all leters, only vowels or only consonants Examples: >>> most_repeating_word(['aaa', 'abb', 'abc']) 'aaa' >>> most_repeating_word(['hello', 'wonderful', 'world']) 'hello' >>> words = ['this', 'is', 'an', 'elementary', 'test', 'example'] >>> most_repeating_word(words) 'elementary' """ pass if __name__ == "__main__": doctest.testmod()
e4ae96a91d9ab51a0fe4f82cc06afefe05a8dd77
azapien22/Python3
/sdex5.py
1,099
4.0625
4
# More Variables & Printing # Removed "my_" # Inch to cm & lbs to kg conversion w/ variables # Used Round() Function name = "Amaury Zapien" age = 35 # not a lie height = 74 # inches weight = 180 # lbs eyes = 'Blue' teeth = 'white' hair = 'brown' print(f"let's talk about {name}.") print(f"He's {height} inches tall.") print(f"He's {weight} pounds heavy.") print("Actually that's not too heavy.") print(f"He's got{eyes} eyes and {hair} hair.") print(f"His teeth are usually {teeth} depending on the coffee.") # This line is tricky, try to get it exactly right. total = age + height + weight print(f"If I add {age}, {height}, and {weight} I get {total}.") # Convert inches to centimeters and pounds to kilograms cm_conver = height * 2.54 # cm's kilo_conver = weight * 0.45359237 # kg's total2 = age + cm_conver + kilo_conver print(f"If I add {age}, {cm_conver}, and {kilo_conver} I get {total2}") cm = 2.54 kg = 0.45359237 # Improvised round() function total3 = age + round(height * cm) + round(weight * kg) print(f"If I add {age}, {height} * {cm}, {weight} * {kg} I get {total3}")
59483e49c3cdf8fe1cf1871ec439b25ffd4daf15
lisandroV2000/Recuperatorio-programacion
/ACT3.py
784
4.15625
4
#3. Generar una lista de números aleatoriamente y resuelva lo siguiente: #a. indicar el rango de valores de la misma, diferencia entre menor y mayor #b. indicar el promedio #c. ordenar la lista de manera creciente y mostrar dichos valores #d. ordenar la lista de manera decreciente y mostrar dichos valores #e. hacer un barrido que solo muestre los número impares no múltiplos de 3 from random import randint numeros = [] for i in range (0,100): numero1 = randint(1,100) numeros.append(numero1) numeros.sort() print ("El menor de la lista es",numeros[0]) print ("El mayor de la lista es",numeros[99]) print(numeros) for lista in range (0,99): if (lista % 9==0, lista % 5==0, lista % 7==0,lista % 3==0): print(lista)
d35a2f95bb5ae84a53e6a294a4b4bd0d3257cebf
Rujabhatta22/pythonProject10
/fgedh.py
182
4.21875
4
#what will be the output of following program? Rewrite the code using for loop to display same output. n=6 i=0 for i in range(n): i+=1 if i==3: continue print(i)
bdd724aebcb76e43df558cd91da8659a92b9f119
enderdaniil/Python-Hangman-Game
/Game.py
2,040
3.9375
4
import random cont = True print("H A N G M A N") s = input('Type "play" to play the game, "exit" to quit:') while s == "play": print() lives = 8 words = ['python', 'java', 'kotlin', 'javascript'] current_word = random.choice(words) current_word_cipher = "" for i in range(len(current_word)): current_word_cipher += "-" input_chars = set() existing_chars = set(current_word) while lives > 0: print(current_word_cipher) char = input("Input a letter:") if char not in input_chars: if len(char) == 1: if char.isalpha() and char.islower(): if char in existing_chars: for j in range(len(current_word)): if current_word[j] == char: if j != len(current_word): current_word_cipher = current_word_cipher[:j] + char + current_word_cipher[j + 1:] else: current_word_cipher = current_word_cipher[:j] + char if current_word == current_word_cipher: break else: print("No such letter in the word") lives -= 1 if lives == 0: print("You lost!") input_chars.add(char) else: print("It is not an ASCII lowercase letter") print() continue else: print("You should input a single letter") print() continue else: print("You already typed this letter") print() continue print() if current_word_cipher == current_word: print(current_word) print("You guessed the word!") print("You survived!") s = input('Type "play" to play the game, "exit" to quit:')
f07adcd069502be0f9f1d068efc3450d0476bc8d
paul0920/leetcode
/question_leetcode/1062_4.py
896
3.71875
4
def longestRepeatingSubstring(S): """ :type S: str :rtype: int """ if not S: return 0 n = len(S) dp = [[0] * (n + 1) for _ in range(n + 1)] max_len = 0 for i in range(1, n + 1): for j in range(i + 1, n + 1): if S[i - 1] != S[j - 1]: dp[i][j] = 0 continue # # We need to make sure the distance between i and j are # greater than the length of previous substring. # For example, assuming S is "mississipi, the answer will be 3 instead of 4 as issi with overlapping # character i is not a qualified answer. # # if j - i > dp[i - 1][j - 1]: dp[i][j] = dp[i - 1][j - 1] + 1 max_len = max(max_len, dp[i][j]) return max_len S = "abbaba" S = "mississipi" print longestRepeatingSubstring(S)
5563bdc8958258d54d803bd3ed6fa6b92d25079d
paul0920/leetcode
/question_leetcode/716_1.py
1,868
3.875
4
# pop & top are O(1) average time complexity since every element gets into and out once # of stack/heap/hashset import heapq class MaxStack(object): def __init__(self): """ initialize your data structure here. """ self.stack = [] self.heap = [] self.popped_item = [] self.id_count = 0 def clear_stack(self): while self.stack and self.stack[-1] in self.popped_item: self.popped_item.remove(self.stack[-1]) self.stack.pop() def clear_heap(self): while self.heap and self.heap[0] in self.popped_item: self.popped_item.remove(self.heap[0]) heapq.heappop(self.heap) # O(log n) def push(self, x): """ :type x: int :rtype: None """ # Use negative number and id for min heap item = (-x, -self.id_count) self.stack.append(item) heapq.heappush(self.heap, item) self.id_count += 1 # O(1) def pop(self): """ :rtype: int """ self.clear_stack() item = self.stack.pop() self.popped_item.append(item) return -item[0] # O(1) def top(self): """ :rtype: int """ self.clear_stack() return -self.stack[-1][0] # O(log n) def peekMax(self): """ :rtype: int """ self.clear_heap() return -self.heap[0][0] # O(log n) def popMax(self): """ :rtype: int """ self.clear_heap() item = heapq.heappop(self.heap) self.popped_item.append(item) return -item[0] # Your MaxStack object will be instantiated and called as such: # obj = MaxStack() # obj.push(x) # param_2 = obj.pop() # param_3 = obj.top() # param_4 = obj.peekMax() # param_5 = obj.popMax()
42363a0abd2702eff075bf6562d06d9c5b71b2e3
paul0920/leetcode
/question_leetcode/366_1.py
706
3.75
4
# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right import collections class Solution(object): def findLeaves(self, root): """ :type root: TreeNode :rtype: List[List[int]] """ self.res = collections.defaultdict(list) def dfs(node): if not node: return 0 l = dfs(node.left) r = dfs(node.right) idx = max(l, r) + 1 self.res[idx] += [node.val] return idx dfs(root) return list(self.res.values())
54557b4121d20c5a4e0c9c72de8dd2c0c75c1df9
paul0920/leetcode
/question_leetcode/542_1.py
1,296
3.5625
4
import collections def updateMatrix(mat): """ :type mat: List[List[int]] :rtype: List[List[int]] """ if not mat: return [0] m = len(mat) n = len(mat[0]) res = [[0] * n for _ in range(m)] for i in range(m): for j in range(n): if mat[i][j] == 0: continue res[i][j] = bfs(i, j, mat) return res def bfs(y, x, mat): DIRECTIONS = [[1, 0], [-1, 0], [0, 1], [0, -1]] queue = collections.deque([(y, x)]) visited = {(y, x)} count = 0 while queue: for _ in range(len(queue)): curr_y, curr_x = queue.popleft() if mat[curr_y][curr_x] == 0: return count for dy, dx in DIRECTIONS: next_y, next_x = curr_y + dy, curr_x + dx if not is_valid(next_y, next_x, mat): continue if (next_y, next_x) in visited: continue queue.append((next_y, next_x)) visited.add((next_y, next_x)) count += 1 return count def is_valid(y, x, mat): if y < 0 or y >= len(mat) or x < 0 or x >= len(mat[0]): return False return True mat = [[0, 0, 0], [0, 1, 0], [1, 1, 1]] print updateMatrix(mat)
903d9fd3fb364c3caa5f8d0f8d058ecc43ed4efb
paul0920/leetcode
/question_leetcode/53.py
357
3.96875
4
def maxSubArray(nums): """ :type nums: List[int] :rtype: int """ if not nums: return 0 curr_sum = nums[0] max_sum = nums[0] for num in nums[1:]: curr_sum = max(curr_sum + num, num) max_sum = max(max_sum, curr_sum) return max_sum nums = [-2, 1, -3, 4, -1, 2, 1, -5, 4] print maxSubArray(nums)
39ec479de101f14fe5f5bd374e3913a8889dd240
paul0920/leetcode
/pyfunc/pop_reverse_demo.py
154
3.71875
4
a = list("apple") b = list("apple") arr = "" while a: arr += a.pop()[::-1] print arr[::-1] arr = "" while b: arr = b.pop() + arr print arr
243c538ea6878b65e70871d3efd8979e783f72bd
paul0920/leetcode
/pyfunc/scope_demo.py
697
3.578125
4
# JavaScript also has the following scope and IIFE concept, # which are similar to Python def my_func_a(i): print i def my_func_b(): # i = 3.14 print i def closure(m): def my_func_c(): print m return my_func_c arr2 = [] arr = [] for i in range(2): arr2 += [my_func_a] arr += [my_func_b] # print arr2 # print arr # i = 100 print "the 1st i: ", i arr2[0](1234) arr[0]() print "" i = 200 print "the 2nd i: ", i arr2[1](4321) arr[1]() print "" # my_func_b searches i nearby for j in range(2): arr[j]() print "" # IIFE print (lambda i: i + 2)(123) print "" arr1 = [] for i in range(2): arr1 += [closure(i)] for q in range(2): arr1[q]()
ff2b554660c1cfb2024cfb9ea3189bfd07bc534f
paul0920/leetcode
/question_leetcode/287_1.py
1,024
4
4
# Depending whether there is 0 in the array, # the starting point is either from the largest index # or the smallest index # You must not modify the array (assume the array is read only). # You must use only constant, O(1) extra space. # Your runtime complexity should be less than O(n^2). # There is only one duplicate number in the array, but it could be repeated more than once. # array = [0, 3, 1, 3, 4, 2] # array = [3, 1, 3, 4, 2] array = [3, 1, 1, 4, 1, 2] # slow = len(array) - 1 # fast = len(array) - 1 # finder = len(array) - 1 slow = 0 fast = 0 finder = 0 while True: print "slow:", slow, "fast:", fast slow = array[slow] fast = array[array[fast]] print "slow:", slow, "fast:", fast print "" if slow == fast: break print "" while True: print "slow:", slow, "finder:", finder slow = array[slow] finder = array[finder] print "slow:", slow, "finder:", finder print "" if slow == finder: print "duplicate number:", slow break
732412f6fc5b3ba1866a3f27f2e06f6cdc5c7711
paul0920/leetcode
/question_leetcode/863_2.py
853
3.734375
4
# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None import collections def distanceK(self, root, target, K): adj, res, visited = collections.defaultdict(list), [], set() def dfs(node): if node.left: adj[node].append(node.left) adj[node.left].append(node) dfs(node.left) if node.right: adj[node].append(node.right) adj[node.right].append(node) dfs(node.right) dfs(root) def dfs2(node, d): if d < K: visited.add(node) for v in adj[node]: if v not in visited: dfs2(v, d + 1) else: res.append(node.val) dfs2(target, 0) return res
ca62304801653fafa7fd08be36b4460ca6ab4c2b
paul0920/leetcode
/question_leetcode/96_3.py
339
3.921875
4
# Recursion (Top Down) using LRU cache # import functools from lru_cache import * @lru_cache() def numTrees(n): if n <= 1: return 1 res = 0 for root in range(0, n): # numTrees(left) x numTrees(right) res += numTrees(root) * numTrees(n - 1 - root) return res n = 19 # n = 3 print numTrees(n)
7ac8682141a5227f2f997800d5a79b7014122071
paul0920/leetcode
/pyfunc/list_comprehensions_demo.py
359
3.78125
4
arr = [1, 2, 3] box = [] for a in arr: for b in arr: box.append(a + b) print box print [a + b for a in arr for b in arr] # If & Else print [n if n % 2 else 'N' for n in range(10)] # print [n for n in range(10) if n % 2 else 'N'] # Wrong usage # If print [n for n in range(10) if n % 2] # print [n if n % 2 for n in range(10)] # Wrong usage
60a2f315b6b59ae268775ec8205cdb08c6821fc1
paul0920/leetcode
/question_leetcode/392_3.py
463
3.609375
4
def isSubsequence(s, t): """ :type s: str :type t: str :rtype: bool """ if not s: return True char_to_word = {s[0]: s} for char in t: if char not in char_to_word: continue word = char_to_word[char] char_to_word.pop(char) if len(word) == 1: return True char_to_word[word[1]] = word[1:] return False s = "abc" t = "ahbgdc" print isSubsequence(s, t)
5b5a842aa8be72e45c546b85ac13677048140c8c
paul0920/leetcode
/pyfunc/setdefault_demo.py
513
3.984375
4
# dictionary.setdefault(key name, value) # # key name: Required. # The key name of the item you want to return the value from # # value: Optional. # If the key exists, this parameter has no effect. # If the key does not exist, this value becomes the key's value # Default value None A = [1, 2, 1, 2] first = {} for i, v in enumerate(A): first.setdefault(v, i) print first print "" second = {'a': 123} print second['a'] print second.setdefault('a', 22) print second.setdefault('b', 22) print second
be3aae6fbc28ede4f5567f33a4cdd1e1b7cd7378
paul0920/leetcode
/question_leetcode/90_2.py
745
3.796875
4
# BFS import collections def subsetsWithDup(nums): """ :type nums: List[int] :rtype: List[List[int]] """ if not nums: return [[]] # Need to sort the array first for handling duplicate cases nums.sort() queue = collections.deque([([], nums)]) res = [] while queue: subset, candidates = queue.popleft() # print id(subset) res.append(subset) for i, num in enumerate(candidates): if i > 0 and candidates[i] == candidates[i - 1]: continue subset.append(num) queue.append((list(subset), candidates[i + 1:])) subset.pop() return res nums = [1, 2, 3] nums = [1, 2, 2] print subsetsWithDup(nums)
bd8ecf82b91c96454c3ae44d7cece064a43e16fe
paul0920/leetcode
/question_leetcode/1110_1.py
1,107
3.890625
4
# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right def delNodes(self, root, to_delete): """ :type root: TreeNode :type to_delete: List[int] :rtype: List[TreeNode] """ des = set(to_delete) self.res = [] def find(node): if not node: return None if node.val in des: self.res.append(node.left) node.left = find(node.left) self.res.append(node.right) node.right = find(node.right) return None node.left = find(node.left) node.right = find(node.right) return node self.res.append(find(root)) table = [] # Since there is no information about # whether the parent exists in find(), # code needs to process some cases by removing # elements in self.res in the final stage for n in self.res: if n is not None and not n.val in des: table.append(n) return table
e7d1059bfb6512fa09af065a267c649bc4d35391
paul0920/leetcode
/question_leetcode/120_6_2.py
699
3.5
4
# Top -> down # Time complexity: O(n^2), n: triangle layer counts # Space complexity: O(n) def minimumTotal(triangle): """ :type triangle: List[List[int]] :rtype: int """ n = len(triangle) dp = [[0] * n, [0] * n] # dp = [[0] * (i + 1) for i in range(n)] dp[0][0] = triangle[0][0] for i in range(1, n): dp[i % 2][0] = triangle[i][0] + dp[(i - 1) % 2][0] dp[i % 2][i] = triangle[i][i] + dp[(i - 1) % 2][i - 1] for j in range(1, i): dp[i % 2][j] = triangle[i][j] + min(dp[(i - 1) % 2][j - 1], dp[(i - 1) % 2][j]) return min(dp[(n - 1) % 2]) triangle = [[2], [3, 4], [6, 5, 7], [4, 1, 8, 3]] print minimumTotal(triangle)
2cefa43ce01faae705b776c45df8f589999a37c9
paul0920/leetcode
/question_leetcode/188.py
628
3.8125
4
def maxProfit(k, prices): """ :type k: int :type prices: List[int] :rtype: int """ if not prices or k == 0: return 0 cost = [float("INF")] * k profit = [0] * k for price in prices: for i in range(k): if i == 0: pre_cost = 0 else: pre_cost = profit[i - 1] # reinvest the previous profit to buy stock cost[i] = min(cost[i], price - pre_cost) profit[i] = max(profit[i], price - cost[i]) return profit[-1] k = 3 prices = [2, 6, 8, 7, 8, 7, 9, 4, 1, 2, 4, 5, 8] print maxProfit(k, prices)
c01ad77fcc9f0ebb2dd2df5eeaa46468d949b8a5
paul0920/leetcode
/question_leetcode/120_1.py
565
3.6875
4
# DFS: traverse. TLE # Time complexity: O(2^n), n: triangle layer counts def minimumTotal(triangle): """ :type triangle: List[List[int]] :rtype: int """ return dfs(triangle, 0, 0, 0, float("INF")) def dfs(triangle, x, y, path_sum, min_sum): if x == len(triangle): return min(min_sum, path_sum) path_sum += triangle[x][y] return min(dfs(triangle, x + 1, y, path_sum, min_sum), dfs(triangle, x + 1, y + 1, path_sum, min_sum)) triangle = [[2], [3, 4], [6, 5, 7], [4, 1, 8, 3]] print minimumTotal(triangle)
fa0a2e8e0ec8251c6d735b02dfa1d7a94e09c6b2
paul0920/leetcode
/question_leetcode/1488_2.py
1,538
3.984375
4
import collections import heapq rains = [1, 2, 0, 0, 2, 1] # 0 1 2 3 4 5 rains = [10, 20, 20, 0, 20, 10] # min heap to track the days when flooding would happen (if lake not dried) nearest = [] # dict to store all rainy days # use case: to push the subsequent rainy days into the heap for wet lakes locs = collections.defaultdict(collections.deque) # result - assume all days are rainy res = [-1] * len(rains) # pre-processing - {K: lake, V: list of rainy days} for i, lake in enumerate(rains): locs[lake].append(i) for i, lake in enumerate(rains): print "nearest wet day:", nearest # check whether the day, i, is a flooded day # the nearest lake got flooded (termination case) if nearest and nearest[0] == i: print [] exit() # lake got wet if lake != 0: # pop the wet day. time complexity: O(1) locs[lake].popleft() # prioritize the next rainy day of this lake if locs[lake]: nxt = locs[lake][0] heapq.heappush(nearest, nxt) print "nearest wet day:", nearest # a dry day else: # no wet lake, append an arbitrary value if not nearest: res[i] = 1 else: # dry the lake that has the highest priority # since that lake will be flooded in nearest future otherwise (greedy property) next_wet_day = heapq.heappop(nearest) wet_lake = rains[next_wet_day] res[i] = wet_lake print "" print res
fbf4ae9f1443d6b29e437fa2189dd169c7f3f24c
paul0920/leetcode
/question_leetcode/1269_1.py
525
3.78125
4
def numWays(steps, arrLen): """ :type steps: int :type arrLen: int :rtype: int """ return dfs(0, steps, arrLen) def dfs(pos, steps, arrLen): if pos < 0 or pos >= arrLen: return 0 if steps == 0: if pos == 0: return 1 return 0 return (dfs(pos - 1, steps - 1, arrLen) + dfs(pos, steps - 1, arrLen) + dfs(pos + 1, steps - 1, arrLen)) % (10 ** 9 + 7) steps = 4 arrLen = 2 # steps = 27 # arrLen = 2 print numWays(steps, arrLen)
5684a4252b5323f29d45a8431f20c153303c35c1
paul0920/leetcode
/question_leetcode/81.py
1,242
3.765625
4
# nums = [4, 5, 6, 7, 0, 1, 2] # target = 3 # nums = [4, 5, 6, 7, 0, 1, 2] # target = 0 nums = [1, 1, 3, 1] target = 3 left = 0 right = len(nums) - 1 # "=" needs to be consider to cover the following case: # nums = [1]; target = 1 while left <= right: mid = (left + right) / 2 if nums[mid] == target: print True exit() # fail to estimate which side is sorted if nums[mid] == nums[right]: right -= 1 # check whether this section is sorted, mid -> right elif nums[mid] > nums[right]: # No need to check target == nums[mid] if nums[left] <= target < nums[mid]: if nums[left] == target: print True exit() else: right = mid - 1 # left jumps to mid + 1 instead of mid # since we already checked whether target == nums[mid] previously else: left = mid + 1 # check whether this section is sorted, left -> mid else: if nums[mid] < target <= nums[right]: if nums[right] == target: print True exit() else: left = mid + 1 else: right = mid - 1 print False
67fbaf8aa5039b3aa18ac23e79ff785fb5786a34
paul0920/leetcode
/question_leetcode/208_2.py
1,184
4.09375
4
class Trie(object): def __init__(self): """ Initialize your data structure here. """ self.children = {} self.isWord = False def insert(self, word): """ Inserts a word into the trie. :type word: str :rtype: None """ # Although this changes "self", it won't change the value of self in other methods # self still points to origin instance for c in word: self = self.children.setdefault(c, Trie()) self.isWord = True def search(self, word): """ Returns if the word is in the trie. :type word: str :rtype: bool """ if not self.children: return self.isWord for c in word: if c in self.children: self = self.children[c] else: return False return self.isWord def startsWith(self, prefix): """ Returns if there is any word in the trie that starts with the given prefix. :type prefix: str :rtype: bool """ if not self.children: return self.isWord for c in prefix: if c in self.children: self = self.children[c] else: return False return True # return self trie_tree = Trie() trie_tree.insert("bluebird") print trie_tree.search("bluebird") print trie_tree.startsWith("bl")
94e06ea11880e0b11b09dcb752f1113a4566aad8
paul0920/leetcode
/pyfunc/bisect_demo_1.py
754
3.5625
4
import bisect A = [[[-1, 0], [3, -1], [4, 5]]] print A[0] # [3] always be the smallest one comparing to any [3, x] print bisect.bisect(A[0], [3]) print bisect.bisect(A[0], [3, -2]) print bisect.bisect(A[0], [3, -1]) # print bisect.bisect_left(A[0], [3, -1]) print bisect.bisect(A[0], [3, 0]) print bisect.bisect(A[0], [3, 1]) print "" print bisect.bisect(A[0], [0]) print bisect.bisect(A[0], [1]) print bisect.bisect(A[0], [2]) print bisect.bisect(A[0], [3]) print bisect.bisect(A[0], [4]) print bisect.bisect(A[0], [5]) print "" print bisect.bisect_left(A[0], [0]) print bisect.bisect_left(A[0], [1]) print bisect.bisect_left(A[0], [2]) print bisect.bisect_left(A[0], [3]) print bisect.bisect_left(A[0], [4]) print bisect.bisect_left(A[0], [5])
c019ab5f9757264ecbd971a9f6ade7a679dacdb6
paul0920/leetcode
/question_leetcode/652_1.py
886
3.609375
4
import collections class TreeNode(object): def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right root = TreeNode(1) root.left = TreeNode(2) root.right = TreeNode(3) root.left.left = TreeNode(4) root.right.left = TreeNode(2) root.right.right = TreeNode(4) root.right.left.left = TreeNode(4) box = collections.defaultdict(list) res = [] def walk(node): if not node: return 'Null' # Need to add something such as "-" among nodes to differentiate with the same combinations key = str(node.val) + "-" + str(walk(node.left)) + "-" + str(walk(node.right)) box[key].append(node) # print key return key walk(root) for k, val in box.items(): if len(val) > 1: res.append(box[k][0]) # for k, v in box.items(): # print k # print v # print "" print res
548084267c55bc7288149402ed3b65cd6035c228
paul0920/leetcode
/question_leetcode/98_2.py
689
3.84375
4
# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution(object): def isValidBST(self, root): """ :type root: TreeNode :rtype: bool """ arr = [] self.inorder(root, arr) for i in range(len(arr) - 1): if arr[i] >= arr[i + 1]: return False return True def inorder(self, node, arr): if not node: return self.inorder(node.left, arr) arr.append(node.val) self.inorder(node.right, arr)
da63fed7f0dab65a4f916bad3872b1e59f18ade9
paul0920/leetcode
/question_leetcode/199_1.py
968
3.71875
4
# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right import collections class Solution(object): def rightSideView(self, root): """ :type root: TreeNode :rtype: List[int] """ self.res = [] def bfs(node): if not node: return q = collections.deque() q.append((node, 0)) while q: curr_node, curr_layer = q.popleft() if len(self.res) == curr_layer: self.res.append(curr_node.val) curr_layer += 1 if curr_node.right: q.append((curr_node.right, curr_layer)) if curr_node.left: q.append((curr_node.left, curr_layer)) bfs(root) return self.res
c08331ff1f9872acf02d15b8eeb73bfda6e34cb9
paul0920/leetcode
/question_leetcode/706_3.py
1,724
3.65625
4
class MyHashMap(object): def __init__(self): """ Initialize your data structure here. """ self.size = 1000 # bucket = (key array list, value array list) self.buckets = [([], []) for _ in range(self.size)] def get_hash_code(self, key): return key % self.size def get_bucket(self, key): hash_code = self.get_hash_code(key) bucket = self.buckets[hash_code] for idx, k in enumerate(bucket[0]): if k == key: return idx, bucket return -1, bucket def put(self, key, value): """ value will always be non-negative. :type key: int :type value: int :rtype: None """ idx, bucket = self.get_bucket(key) if idx == -1: bucket[0].append(key) bucket[1].append(value) else: bucket[1][idx] = value def get(self, key): """ Returns the value to which the specified key is mapped, or -1 if this map contains no mapping for the key :type key: int :rtype: int """ idx, bucket = self.get_bucket(key) if idx == -1: return -1 return bucket[1][idx] def remove(self, key): """ Removes the mapping of the specified value key if this map contains a mapping for the key :type key: int :rtype: None """ idx, bucket = self.get_bucket(key) if idx != -1: bucket[0].pop(idx) bucket[1].pop(idx) # Your MyHashMap object will be instantiated and called as such: # obj = MyHashMap() # obj.put(key,value) # param_2 = obj.get(key) # obj.remove(key)
80faff682b05c7b56321b8761d088b062ee0e087
paul0920/leetcode
/question_leetcode/270_2.py
537
3.6875
4
class TreeNode(object): def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right root = TreeNode(4) root.left = TreeNode(2) root.left.left = TreeNode(1) root.left.right = TreeNode(3) root.right = TreeNode(5) target = 3.714286 def find(node): # This is inorder and the result list is sorted return find(node.left) + [node.val] + find(node.right) if node else [] print "This is sorted:", find(root) print min(find(root), key=lambda x: abs(x - target))
64cabc4196e66bf562735ded2c66ed388f39ba09
paul0920/leetcode
/question_leetcode/366_2.py
693
3.78125
4
# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right import collections class Solution(object): def findLeaves(self, root): """ :type root: TreeNode :rtype: List[List[int]] """ res = [] def dfs(root): if not root: return -1 height = max(dfs(root.left), dfs(root.right)) + 1 if height >= len(res): res.append([]) res[height].append(root.val) return height dfs(root) return res
e9c7e2643386e25fb4206e3546af1b7b8fc40c6f
paul0920/leetcode
/question_leetcode/1197_2.py
1,289
3.703125
4
import collections def minKnightMoves(x, y): """ :type x: int :type y: int :rtype: int """ if (x, y) == (0, 0): return 0 forward_queue = collections.deque([(0, 0)]) forward_visited = set([(0, 0)]) backward_queue = collections.deque([(x, y)]) backward_visited = set([(x, y)]) distance = 0 while forward_queue and backward_queue: distance += 1 if bfs(forward_queue, forward_visited, backward_visited): return distance distance += 1 if bfs(backward_queue, backward_visited, forward_visited): return distance def bfs(queue, visited, opposite_visited): DIRECTIONS = [(1, 2), (1, -2), (-1, 2), (-1, -2), (2, 1), (2, -1), (-2, 1), (-2, -1)] # Use the following way to calculate 1 layer only. # DON'T USE "while queue:" for _ in range(len(queue)): curr_x, curr_y = queue.popleft() for x, y in DIRECTIONS: next_x, next_y = curr_x + x, curr_y + y if (next_x, next_y) in visited: continue if (next_x, next_y) in opposite_visited: return True queue.append((next_x, next_y)) visited.add((next_x, next_y)) return False print minKnightMoves(5, 5)
8215c61fb101b6cbc853f5d28e615df960bfc0ab
paul0920/leetcode
/question_leetcode/16_1.py
617
3.53125
4
nums = [0, 1, 2]; target = 0 nums.sort() # Be careful of the last index in sum() # The following is equivalent of nums[0] + nums[1] + nums[2] sum_min = sum(nums[0:3]) for i in range(len(nums) - 2): j, k = i + 1, len(nums) - 1 if i > 0 and nums[i] == nums[i - 1]: continue while j < k: total = nums[i] + nums[j] + nums[k] dis = target - total if dis == 0: print total if abs(dis) < abs(target - sum_min): sum_min = total if total < target: j += 1 elif total > target: k -= 1 print sum_min
3774581fca565cb1c78656e7b20abf79d6833d7c
paul0920/leetcode
/question_leetcode/148_2_1.py
1,153
4
4
# Top-Down method from see_node import * def merge(l, r): dummy = cur = ListNode(0) while l and r: if l.val < r.val: cur.next = l l = l.next else: cur.next = r r = r.next cur = cur.next cur.next = l if l else r p_node(dummy.next) return dummy.next def sort(head): # Be careful about the "not" usage. The following statement is wrong! # if not head or head.next: if not head or not head.next: return head prev, slow, fast = None, head, head while fast and fast.next: prev = slow slow = slow.next fast = fast.next.next print "prev:", prev.val, "-> None" prev.next = None mid = slow print "head:", head.val left = sort(head) print "*************" print "mid:", mid.val if fast: print "fast:", fast.val else: print "fast: None" right = sort(mid) return merge(left, right) # a = [3, 2, 1] a = [5, 4, 3, 2, 1] head = c_node(a) print "Linked List:", p_node(head) print "" cur = sort(head) print "" print "Linked List:", p_node(cur)
ab029089a8b2ab2c6c968fcd4f0b64f4b508c767
paul0920/leetcode
/pyfunc/see_node.py
446
3.6875
4
class ListNode(object): def __init__(self, x): self.val = x self.next = None def c_node(arr): dummy = ListNode(0) dummy.next = node = ListNode(arr[0]) for n in arr[1:]: node.next = ListNode(n) node = node.next return dummy.next def p_node(head): if not head: print "!!! No Nodes !!!" while head: print head.val, "->", head = head.next print "Null"
4550d21f65e6d452062458d1058fa700b9e93103
paul0920/leetcode
/question_leetcode/31_2.py
1,035
3.734375
4
def nextPermutation(nums): """ :type nums: List[int] :rtype: None Do not return anything, modify nums in-place instead. """ if not nums: return [] # [1, 5, 8, 4, 7, 6, 5, 3, 1] # ^ ^ # -> [1, 5, 8, 5, 7, 6, 4, 3, 1] # ^ ^ # -> [1, 5, 8, 5, 1, 3, 4, 6, 7] (next permutation) i = len(nums) - 1 j = i right = i while i > 0 and nums[i - 1] >= nums[i]: i -= 1 if i == 0: # Be careful about the value it pointed to before that assignment # (your original list) will stay unchanged. Use nums[:] instead nums[:] = nums[::-1] return # i --> 7 i -= 1 while nums[i] >= nums[j]: j -= 1 nums[i], nums[j] = nums[j], nums[i] left = i + 1 while left < right: nums[left], nums[right] = nums[right], nums[left] left += 1 right -= 1 nums = [1, 5, 8, 4, 7, 6, 5, 3, 1] for _ in range(10): print nums nextPermutation(nums)
31cbbc0e9340596def44286e41eb1569ae611c07
paul0920/leetcode
/question_leetcode/1644_1.py
1,320
3.78125
4
class TreeNode(object): def __init__(self, val): self.val = val self.left = None self.right = None class Solution(object): def __init__(self): self.res = None def lowestCommonAncestor(self, root, p, q): """ :type root: TreeNode :type p: TreeNode :type q: TreeNode :rtype: TreeNode """ def check_valid(root, node): if not root: return False elif root.val == node.val: return True return check_valid(root.left, node) or check_valid(root.right, node) def search_LCA(root, p, q): if root in (None, p, q): return root left = search_LCA(root.left, p, q) right = search_LCA(root.right, p, q) if left and right: return root elif not left and right: return right elif left and not right: return left if not root or not check_valid(root, p) or not check_valid(root, q): return None return search_LCA(root, p, q) root = TreeNode(3) root.right = TreeNode(1) root.right.right = TreeNode(2) obj = Solution() print obj.lowestCommonAncestor(root, root.right, root.right.right).val
111c536fba28296ec4f2a93ab466360e57d839d6
paul0920/leetcode
/question_leetcode/215_5.py
1,471
4.25
4
# Bucket sort algorithm # Average time complexity: O(n) # Best case: O(n) # Worst case: O(n^2) # Space complexity: O(nk), k: bucket count # Bucket sort is mainly useful when input is uniformly distributed over a range # Choose the bucket size & count, and put items in the corresponding bucket nums = [3, 2, 1, 5, 6, 4] # k = 2 # nums = [3, 2, 3, 1, 2, 4, 5, 5, 6] # k = 4 # nums = [2, 200, 6, 9, 10, 32, 32, 100, 101, 123] def bucket_sort(alist, bk_size): largest = max(alist) length = len(alist) size = bk_size # size = largest / length # if size < 1: # size = 1 print "bucket size:", size buckets = [[] for _ in range(length)] for i in range(length): j = int(alist[i] / size) print "i:", i, "j:", j, "length:", length if j < length: buckets[j].append(alist[i]) elif j >= length: buckets[length - 1].append(alist[i]) print buckets print "" # Use insertion sort to sort each bucket for i in range(length): insertion_sort(buckets[i]) result = [] for i in range(length): result += buckets[i] return result def insertion_sort(alist): for i in range(1, len(alist)): key = alist[i] j = i - 1 while j >= 0 and key < alist[j]: alist[j + 1] = alist[j] j = j - 1 alist[j + 1] = key arr = bucket_sort(nums, 3) print "" print "the sorted array:", arr
0aa9a7c64282a574374fb4b9e9918215f0f013ec
paul0920/leetcode
/question_leetcode/48_2.py
509
4.1875
4
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] for row in matrix: print row m = len(matrix) n = len(matrix[0]) # j only loops until i for i in range(m): for j in range(i): matrix[i][j], matrix[j][i] = matrix[j][i], matrix[i][j] # j only loops until n / 2 for i in range(m): for j in range(n / 2): matrix[i][j], matrix[i][n - j - 1] = matrix[i][n - j - 1], matrix[i][j] # matrix[i][j], matrix[i][~j] = matrix[i][~j], matrix[i][j] print "" for row in matrix: print row
65b13cf4b6251e6060c8ccf34a63ab703f93fd2b
paul0920/leetcode
/pyfunc/lambda_demo_1.py
251
4.15625
4
my_list = [1, 5, 4, 6] print map(lambda x: x * 2, my_list) print (lambda x: x * 2)(my_list) print my_list * 2 # A lambda function is an expression, it can be named add_one = lambda x: x + 1 print add_one(5) say_hi = lambda: "hi" print say_hi()
19b9054f704d916c6d35b6500919397476111ab2
paul0920/leetcode
/question_leetcode/215_2.py
548
3.796875
4
# Bubble sort algorithm # Time complexity: O( k(n - (k+1)/2) ); if k = n, O( n(n-1)/2 ) # Best case: O(n) # Worst case: O(n^2) # Space complexity: O(1) # If j+1 > j, just swap and so on # nums = [3, 2, 1, 5, 6, 4] # k = 2 nums = [3, 2, 3, 1, 2, 4, 5, 5, 6] k = 4 for i in range(k): for j in range(len(nums) - 1 - i): print i, j if nums[j] > nums[j+1]: print nums nums[j], nums[j+1] = nums[j+1], nums[j] print nums print "" print "the Kth largest:", nums[len(nums)-k]
c0c20ac1cb3fbaab0a412421cde30202daf5b808
paul0920/leetcode
/question_leetcode/5_1.py
294
3.671875
4
s = "babad" s = "cbbd" res = "" def find_str(left, right): while 0 <= left and right < len(s) and s[left] == s[right]: left -= 1 right += 1 return s[left + 1: right] for i in range(len(s)): res = max(res, find_str(i, i), find_str(i, i+1), key=len) print res
3f57d2d24f381e2a5aa5ab8509d2ad5e81c98258
paul0920/leetcode
/question_leetcode/1136_1.py
1,245
3.5
4
# Time complexity: O(n + m), m = len(relations) (edges) import collections def minimumSemesters(n, relations): """ :type n: int :type relations: List[List[int]] :rtype: int """ if not relations: return 1 pre_to_current = {i: set() for i in range(1, n + 1)} current_to_pre = {i: set() for i in range(1, n + 1)} for pre_course, course in relations: pre_to_current[pre_course].add(course) current_to_pre[course].add(pre_course) queue = collections.deque() for i in range(1, n + 1): if current_to_pre[i]: continue queue.append(i) total_non_pre_course = len(queue) res = 0 while queue: for _ in range(len(queue)): course = queue.popleft() for next_course in pre_to_current[course]: current_to_pre[next_course].remove(course) if not len(current_to_pre[next_course]): total_non_pre_course += 1 # Remember to add the node into the queue! queue.append(next_course) res += 1 return res if total_non_pre_course == n else -1 n = 3 relations = [[1, 3], [2, 3]] print minimumSemesters(n, relations)
0fa527406b5d00b216e32648cc2991eb61d2b012
paul0920/leetcode
/question_leetcode/254.py
563
3.6875
4
def getFactors(n): """ :type n: int :rtype: List[List[int]] """ if n <= 1: return [] res = [] calculate_factors(res, [], n, 2) return res def calculate_factors(res, path, n, factor): # To prevent from adding the case of number itself if len(path) > 0: res.append(path + [n]) while factor * factor <= n: if n % factor == 0: path.append(factor) calculate_factors(res, path, n // factor, factor) path.pop() factor += 1 n = 32 print getFactors(n)
1d64c975e07beb51dcf12ed83c49b310cfe8f7a4
paul0920/leetcode
/question_leetcode/525.py
516
3.78125
4
def findMaxLength(nums): """ :type nums: List[int] :rtype: int """ if not nums: return 0 count_to_index = {0: -1} count = 0 max_len = 0 for i, num in enumerate(nums): if num == 0: count -= 1 else: count += 1 if count not in count_to_index: count_to_index[count] = i else: max_len = max(max_len, i - count_to_index[count]) return max_len nums = [0, 1, 0] print findMaxLength(nums)
046ca7d8531c5431092eaf09481734f3ed6ef3ab
paul0920/leetcode
/question_leetcode/1380.py
383
3.765625
4
matrix = [[1,10,4,2],[9,18,8,7],[15,16,17,12]] mi = [min(row) for row in matrix] # zip(*zippedList) is a great function to extract columns in 2D matrix # It returns an iterator of tuples with each tuple having elements from all the iterables. mx = [max(col) for col in zip(*matrix)] mx_col = [col for col in zip(*matrix)] print mx_col for i in mi: if i in mx: print i
66228e9d8b171a24213e0b57c73ec63bf27f7054
paul0920/leetcode
/question_leetcode/297_1.py
1,714
3.671875
4
class TreeNode(object): def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right root = TreeNode(-1) root.left = TreeNode(0) # root.left.left = TreeNode(4) # root.left.right = TreeNode(5) # root.left.right.left = TreeNode(7) # root.left.right.right = TreeNode(8) root.right = TreeNode(1) # root.right.left = TreeNode(4) # root.right.right = TreeNode(5) # root.right.left.left = TreeNode(9) # root.right.left.right = TreeNode(10) def serialize(root): """Encodes a tree to a single string. :type root: TreeNode :rtype: str """ if not root: return "None" return str(root.val) + "," + str(serialize(root.left)) + "," + str(serialize(root.right)) def build_tree( arr, i): i += 1 # print i, arr, arr[i] # Don't use (not arr[i]) since number "0" will be counted! # if i >= len(arr) or (not arr[i]): if i >= len(arr) or arr[i] is None: return None, i node = TreeNode(arr[i]) node.left, i = build_tree(arr, i) node.right, i = build_tree(arr, i) return node, i def deserialize( data): """Decodes your encoded data to tree. :type data: str :rtype: TreeNode """ data_arr = data.split(",") for idx, n in enumerate(data_arr): if n == "None": data_arr[idx] = None else: data_arr[idx] = int(n) node, pos = build_tree(data_arr, -1) return node print serialize(root) print "" new = deserialize(serialize(root)) print "" print new.val print new.left.val print new.right.val # print new.val # print new.left.val # print new.right.val # print new.right.left.val # print new.right.right.val
e4c37eee96534a69fb1f98ad244eb97c996da646
paul0920/leetcode
/question_leetcode/207_2.py
679
3.75
4
from collections import defaultdict numCourses = 5 prerequisites = [[1, 0], [0, 1]] g = defaultdict(list) visit = [0 for _ in range(numCourses)] for course, pre in prerequisites: g[course].append(pre) def dfs(course): if visit[course] == 1: return True if visit[course] == -1: return False # The first time seeing this course and # not sure whether there is a loop visit[course] = -1 for pre in g[course]: if not dfs(pre): return False # There is no loop in this branch visit[course] = 1 return True for course in range(numCourses): if not dfs(course): print False print True
8b0d684472ff8ab6fda89b346c3c5b055047b7fc
paul0920/leetcode
/question_leetcode/785_2.py
898
3.671875
4
import collections def isBipartite(graph): """ :type graph: List[List[int]] :rtype: bool """ if not graph: return False node_color_lookup = {} for i in range(len(graph)): if i not in node_color_lookup: node_color_lookup[i] = 1 if not DFS(i, graph, node_color_lookup): return False return True def DFS(curr_node, graph, node_color_lookup): for neighbor_node in graph[curr_node]: if neighbor_node not in node_color_lookup: node_color_lookup[neighbor_node] = node_color_lookup[curr_node] * -1 if not DFS(neighbor_node, graph, node_color_lookup): return False elif node_color_lookup[neighbor_node] == node_color_lookup[curr_node]: return False return True graph = [[1, 3], [0, 2], [1, 3], [0, 2]] print isBipartite(graph)
3050658fcb4ba27e9bf027c0ae6ecfe37b4f6b9b
junior-oliveira/missao-07
/tratamento_dados/normalizacao.py
387
3.515625
4
import numpy as np def normalizar_dados(df): ''' df - dataframe de valores a serem normalizados df_norm - dataframe normalizado pelo mínimo e máximo valor ''' # Normalização dos dados x_float = df.astype('float') norm_min_max = lambda x: (x - np.min(x))/(np.max(x) - np.min(x)) df_norm = x_float.copy().apply(norm_min_max, axis=0) return df_norm
019c38213748b52f591033c022a6bfe7ab613e17
RennanGaio/inteligenciaComputacional
/trabalho1/gradiente_descendente.py
3,528
4.09375
4
# -*- coding: utf-8 -*- """ Aluno: Rennan de Lucena Gaio Codigo referente aos 4 exercícios 11 e 12 da lista 1 de IC2 """ import numpy as np import random import matplotlib.pyplot as plt ''' funções referentes ao gradiente descendente não foi criada uma classe para esse problema por ele ser mais simples e as perguntas serem mais diretas ''' #definição da nossa função de erro dada pelo enunciado def error_function(u,v): return ( u*np.e**(v) - 2*v*np.e**(-u) )**2 #gradiente em relação a variavel u da nossa função de erro def gradiente_u(u,v): return ( 2 * ((u*np.e**(v)) - (2*v*np.e**(-u))) * (np.e**(v) + (2*v*np.e**(-u))) ) #gradiente em relação a variavel v da nossa função de erro def gradiente_v(u,v): #return ( 2*np.e**(-2*u) * (u*np.e**(u+v) - 2) * (u*np.e**(u+v) - 2*v) ) return ( 2 * ((u*np.e**(v)) - (2*np.e**(-u))) * (u*np.e**(v) - (2*v*np.e**(-u))) ) #calcula os gradientes direcionais no ponto atual, e só atualiza o ponto depois das duas operações serem feitas def walk_through_gradient(point, learning_rate): direction_u=gradiente_u(point[0], point[1])*learning_rate direction_v=gradiente_v(point[0], point[1])*learning_rate point[0] -= direction_u point[1] -= direction_v #calcula o gradiente descendente de um função dado um ponto de partida def descendent_gradient(inicial_point, precision, interations, learning_rate): #laço só para depois que é atingido o erro minimo estipulado pelo enunciado while (error_function(inicial_point[0], inicial_point[1]) > precision): #faz a atualização dos pesos walk_through_gradient(inicial_point, learning_rate) interations+=1 #print(error_function(inicial_point[0], inicial_point[1])) return interations #calcula os gradientes direcionais no ponto atual, e atualiza o ponto depois de fazer o gradiente para depois calcular o gradiente na nova direção def walk_through_coordenate_gradient(point, learning_rate): point[0] -= gradiente_u(point[0], point[1])*learning_rate point[1] -= gradiente_v(point[0], point[1])*learning_rate #calcula a função de coordenada descendente a partir de um ponto de partida def descendent_coordenate(inicial_point, precision, learning_rate): i=0 #laço de apenas 15 iterações assim como é mandado no enunciado while i<15: walk_through_coordenate_gradient(inicial_point, learning_rate) i+=1 #print(error_function(inicial_point[0], inicial_point[1])) if __name__ == '__main__': #inicialização do ponto inicial, do learning rate e da precisão que o algoritmo precisa ter para sair do laço while do gradiente inicial_point=np.array([np.float64(1.),np.float64(1.)]) learning_rate=np.float64(0.1) precision=np.float64(10**(-14)) interations=0 #execução do gradiente descendente interations=descendent_gradient(inicial_point, precision, interations, learning_rate) print("exercicio 11") print ("gradient descendent answers:") print("interations: ", interations) #resposta ex 11 = D print("final point: ", inicial_point) #resposta ex 12 = E print("") #execução da coordenada descendente inicial_point=np.array([np.float64(1.),np.float64(1.)]) descendent_coordenate(inicial_point, precision, learning_rate) print("exercicio 12") print ("coordenate descendent answers:") print("final point: ", inicial_point) print("error: ", error_function(inicial_point[0], inicial_point[1])) #resposta ex 13 = A
521cc7aaba06cf5eea97727f96c2dccda656d100
Anubhav27/python_handson
/Python_Smart/python_classes.py
314
3.625
4
__author__ = 'Anubhav' class Student: student_count = 0 def __init__(self,name): self.name = name; Student.student_count += 1 def getName(self): return self.name #s = Student("anubhav") #print s.getName() s = Student("anubh") Student.__init__(s,'a') print s.getName()