blob_id
stringlengths
40
40
repo_name
stringlengths
5
127
path
stringlengths
2
523
length_bytes
int64
22
545k
score
float64
3.5
5.34
int_score
int64
4
5
text
stringlengths
22
545k
0038dc7cda1b5f67dd6fba82dbaf99379dfcbab3
podnebesnoe/podnebom
/byte_x.py
2,729
3.796875
4
from typing import List # 29. Divide Two Integers # https://leetcode.com/problems/divide-two-integers/ def divide(dividend: int, divisor: int) -> int: # first step: find smallest divisor * 2^n which is greater than dividend (lets call it accumulator) # second step: keep deducting accumulator from dividend and...
a3da5455a00c5ca1879a190da8476ca260ac93b6
podnebesnoe/podnebom
/greedy.py
662
3.65625
4
from typing import List # 134. Gas Station (not 100) # https://leetcode.com/problems/gas-station/ def canCompleteCircuit(gas: List[int], cost: List[int]) -> int: # iterate through array twice and keep best local solution # if local solution fails, reset it to another local solution # iterate until actual ...
926305c87133c5a9c0c68141165a384df04a120e
marianadick/projeto-poo-1
/GUI/database/main.py
619
3.84375
4
import sqlite3 from sqlite3.dbapi2 import connect class Database(): def __init__(self, name) -> None: self.database = sqlite3.connect('GUI/database/' + name) self.cursor = self.database.cursor() self.cursor.execute(""" CREATE TABLE IF NOT EXISTS list ( id INTEGER PRIMARY KEY AUTOINCREMENT,...
3065c9862e46d9d67a264715a65a186dde032ccd
yusukekyokawa/shogi_camera
/shogi_camera/learn/model.py
1,096
3.609375
4
from keras.layers import Dense, Dropout, Activation, Flatten from keras.layers import Conv2D, MaxPooling2D, BatchNormalization, PReLU from keras.models import Sequential def my_model(NUM_CLASSES, input_shape): model = Sequential() model.add(Conv2D(32, kernel_size=(3, 3), input_shape=input_shape)) model.a...
911f65f6917f1b17ebc6cb8c325e650549fe2bc3
sapphacs13/python_basics
/syntax/functions.py
722
4.125
4
# Python uses white space. Everything you define or use has # to have the correct indentation. def adder(a, b): return a + b print adder(1, 2) # runs adder(1,2) and prints it (should print 3) def subtracter(a, b): return a - b print subtracter(3, 2) # runs the subtracter and prints (should print 1) # lets ...
5e99a7b51a52f5301a2cb3bc65f019d52051982e
bigcat2014/Cloud_Computing
/Assignment 2/step2.py
615
4.21875
4
#!/usr/bin/python3 # # Logan Thomas # Cloud Computing Lab # Assignment 2 # # Capitalize the first letter of each word in the string and # take the sum of all numbers, not contained in a word, and # print the new string and the sum. def main(): total = 0.0 user_input = input("Please enter a string\n>> ") user_in...
028f52f7e8a2633ba868029ca06263e993e9ca20
bigcat2014/Cloud_Computing
/Assignment 2/shape.py
889
4.125
4
#!/usr/bin/python3 # # Logan Thomas # Cloud Computing Lab # Assignment 2 # from math import sqrt class Shape: sides = [] name = '' def __init__(self): self.name = 'Shape' def area(self): pass class Rectangle(Shape): def __init__(self, x, y): super().__init__() self.name = 'Rectangle' self.side...
8f3c7a301805aa181a20051729fd5d5447ec13bf
chungjen/Python
/conditionals1.py
154
3.71875
4
direction = input("Do you want to go (N)orth, (S)ourth, (E)ast, or (W)est?") if direction == "n": print("You head north, into the forest.")
1d92d87875f37503b14413d484e8656e426ac5d1
JoelBrice/PythonForEveryone
/ex3_03.py
439
4.21875
4
"""Check that the score is between the range and display the score level according to the score""" score = input("Enter Score: ") s = 0.0 try: s = float(score) except: print("Error out of range!") if s >=0 and s<=1: if s>= 0.9: print("A") elif s >=0.8: print("B") elif s>=0.7: ...
100411002a94bb334ceb8de85b536ad3421b65a3
angelapopa/thesis-practical-part-python
/src/at/uibk/epc/clustering/kmeans/elbow_plot.py
2,595
3.609375
4
import numpy as np import pandas as pd from sklearn.cluster import KMeans from sklearn.preprocessing import StandardScaler import matplotlib.pyplot as plt from sklearn import metrics import os from pathlib import Path # https://towardsdatascience.com/clustering-with-k-means-1e07a8bfb7ca def calculate_metrics(slim_da...
027b5eb94cd7f561bc804381b41108d72a055f2f
charan556/52-week-challenge
/PythonLab/mySource/ScopeAndNamespacesEx.py
245
3.609375
4
a = 0 if a == 0: b = 1 def my_func(c): d = 3 print(c) print(d) def my_func2(): global a a = 3 print(a) # my_func(7) my_func2() print("Step1: ", a) print("Step2: ", b) print("step3: ", a)
189e9e833a502f067b5de3a8eb235fe01bd59489
charan556/52-week-challenge
/PythonLab/mySource/static.py
734
3.71875
4
class Person: TITLES = ('Dr', 'Mr', 'Mrs', 'Ms') def __init__(self, name, surname): self.name = name self.surname = surname def fullname(self): return "%s %s" % (self.name, self.surname) @classmethod def allowed_titles_starting_with(cls, key): retur...
9490d80d91acab08242f5aee29a3b9ce4aebfeee
dgfwork/mooc_algorithm_python
/DS/BFS.py
910
3.546875
4
# -*- coding: utf-8 -*- # @Time : 2019/5/2 9:16 # @Author : Scavenger # @FileName: BFS.py # @Software: PyCharm # @Github : https://github.com/dgfwork/ # @Blog : https://www.cnblogs.com/gaofeng-d/ def BFS(graph, start): queue = [] queue.append(start) memo = set() # 小本本记录是否访问过 memo.add(start) ...
370cb729981a0577fff17158ebfef41e1e43df4f
dgfwork/mooc_algorithm_python
/hanoi.py
686
3.953125
4
# -*- coding: utf-8 -*- # @Time : 2019/7/24 18:55 # @Author : Scavenger # @FileName: hanoi.py # @Software: PyCharm # @Github : https://github.com/dgfwork/ # @Blog : https://www.cnblogs.com/gaofeng-d/ count = 0 def hanoi(level, A, B, C): global count if level == 1: count += 1 print("%s...
811a958fdd265dde5dff30293084e7c8817caa8f
olorin-grey/computer_science
/practice/booleans.py
912
3.734375
4
my_baby_bool = "true" type(my_baby_bool) print(type(my_baby_bool)) # <class 'str'> my_baby_bool_two = True type(my_baby_bool_two) print(type(my_baby_bool_two)) # <class 'bool'> # Using AND as the operator def graduation_reqs(gpa, credits): if gpa >= 2.0 and credits >= 120: return "You meet the requirements...
6d0c97ca1443ae864b9a8424469d1062207ba95e
AmeerYHassan/CS435-Project_One
/SortedBST.py
361
3.859375
4
from RecursiveBST import * def bstSort(arr): # Create a BST sortedBST = BST() # Add all the values from the array into the BST. for num in arr: sortedBST.insertRec(num) # Generate the inOrder traversal for the tree. sortedBST.inOrder() return sortedBST.inOrderList p...
bd049cc2b69f214e75eaef6ca8779e8f3a18125d
nathanzilgo/Python-Ransomware
/src/Crypter.py
1,134
3.828125
4
#!/usr/bin/python3.6 # utilizando criptografia de bloco assimétrica # Função de mudança de arquivo. def cryptAndDecryptFiles(filename, cryptoFn, blockSize=16): # Abre o arquivo 'filename' a ser criptografado no modo de leitura 'r+b' binário # Salva o arquivo aberto em _file with open(filename, 'r+b') as _...
6e21f238b83e720549d3e1e2e84f15c099da29b5
duyhdb/check-daily-lottery
/lotto.py
3,150
3.84375
4
#!/usr/bin/env python3 """A simple script does two things: 1. Crawls lottery results from ketqua1.net 2. Checks daily lottery as arguments win or not (2 last digit on lottery ticket). If there is no argument then: Print all the winning numbers. Usage: $ python3 lotto.py [NUMBER1] [NUMBER2] [...] """ import ...
c6c4daa64a0b902a4474dfb6de64cae0f5b3f944
paty0504/nguyentienthanh-fundamental-c4e13
/ss2/homework/BMIhw.py
328
4.03125
4
h = (int(input('Your heigth in centimeter? '))*0.01) w = int(input('Your weight in kilogram? ')) bmi = w/(h*h) print('Your BMI is: ', bmi) if bmi < 16: print('Severely underweight') elif bmi < 18.5: print('Underweight ') elif bmi < 25: print('Normal') elif bmi < 30: print('Overweight') else: print('...
270c5c788c1fdad02806b75d3e693ef7de6c1974
paty0504/nguyentienthanh-fundamental-c4e13
/ss5/dict1.py
445
4.1875
4
dic = { "eny" : "Em người yêu", "any" : "Anh người yêu", "cl" : "con lợn", "hc" : "học", "ik" : "đi", } while True: search = input('Your code: ') if search in dic: print(dic[search]) else: print('Not found') choice = input(' Would you like to update? Y or N?:').lower() if cho...
9e5bb154e2d978f8ddb2a2614a8f53989474885e
paty0504/nguyentienthanh-fundamental-c4e13
/ss4/homework/number2.py
122
3.515625
4
money = int(input('Enter your balance: ')) update = '{:,}'.format(money) print('Your updated money: ${0}'.format(update))
3c97e56800e271ce069bdf4a38d151b0c6d6b19b
paty0504/nguyentienthanh-fundamental-c4e13
/ss4/login.py
414
4.09375
4
username = input('Enter your username: ') count = 0 while count < 3: if username == 'tienthanh': password = input('Enter your password: ') if password == 'thanhnguyen': print('Welcome') break else: print('Wrong password!') else: print('No such ...
f7b41189bafddb95a0b7a1803ac5c0f6ed855892
rozenborg/learning-projects
/Python/days-alive-test.py
3,735
4.15625
4
# def isLeapYear(year): # result = False # if year % 4 == 0: # if year % 100 == 0: # common year # if year % 400 == 0: # # daysOfMonths[1] = 29 # leap year # result = True # else: # # daysOfMonths[1] = 29 #leap year # result = True # return result #common year # def daysOfMonths(result): # day...
11bdaddcea737bb0e21a06dce8162e0a18ebaf09
feifanrensheng/dmp_writing
/code/segmentation.py
1,874
3.59375
4
import math import numpy as np import matplotlib.pyplot as plt class Segmentation: def __init__(self, traj, dtraj, ddtraj): self.traj = traj self.dtraj = dtraj self.ddtraj = ddtraj self.strokes = [] self.Len = len(traj[0]) def segmentate_three(self): i = 100 ...
f0722a47f7382e25da4c5623e8ee54a16b4193df
jacob-emerson07/tic_tac_toe
/tic_tac_toe.py
1,919
3.90625
4
BOARD = [[" "," "," "], [" "," "," "], [" "," "," "]] PLAYERS = {1: "X", 2: "O"} TURN = 1 TURNS_LEFT = 9 def validate_type(prop_type): return _validate_type(prop_type) def validate_turn(row, column): return _validate_turn(row,column) def add_piece(coords): # Adds the...
7974347c2cf095bce216fae6fbf2ad5c66d97905
svspeybr/lessons
/LesConditions/max.py
480
3.609375
4
# Vraag drie getallen op (werk met variabelen a, b,c ) a = float(input("Geef een getal:")) b = float(input("Geef een tweede getal:")) c = float(input("Geef een derde getal:")) # Werk met een 4de variabele 'maximum' die de grootste waarde bijhoudt maximum = a # Vergelijk nu b en c met maximum( =a) en pas maximum aan in...
732e09d4daceef9d2701875aaf807555f4fb3bc1
svspeybr/lessons
/Cryptography/Caesar Cipher.py
3,536
3.65625
4
#### Caesar cipher: ### Volgende code beschrijft een programma waarbij de gebruiker een tekst ingeeft die geëncrypteerd ### of gedecodeerd wordt volgens de 'Caesarcijfer': ### Het porgramma vraagt of: ### 1) de tekst geëncrypteerd ('encrypt' of 'e') moet worden of gedecrypteerd ('decrypt' of 'd') ### 2) het Caesarcijfe...
e8d0a793606bc13c89d4e740946c5964eb93a0fd
singh2407shubham/Coding-Challenges
/broken_keyboard.py
523
3.90625
4
def brokenKeyboard(string, letters): avaialable = set() for char in letters: if char not in avaialable: avaialable.add(char) string = string.split() count = 0 for word in string: present = True for char in word: if char.lower() not in avaialable and ord(char.lower())>= ord('a'...
ce70dd31fc3b3668a5225f2f62ac069576cc2c17
LeoLozano10/Tema-2_Estructura_De_Datos
/Monedas/CambiodeMonedas.py
885
3.921875
4
dinero = int(input("Cantidad:")) uno = dinero // 200 restouno = dinero % 200 dos = restouno // 100 restodos = restouno % 100 tres = restodos // 50 restotres = restodos % 50 cuatro = restotres // 20 restocuatro = restotres % 20 cinco = restocuatro // 10 restocinco = restocuatro % 10 seis = restocinco // 5 restoseis = r...
9b5a3f8a72f612e3d9d55e330cd1d30719507c2e
t4d-classes/python_03222021_afternoon
/language_demos/data_vars.py
418
3.96875
4
first_name = "Bob" first_name2 = "Bob" print(first_name == first_name2) print(id(first_name)) print(id(first_name2)) age = 34 age2 = 34 print(age == age2) print(age is age2) print(id(age)) print(id(age2)) nums = [1, 2, 3, 4, 5] nums2 = [1, 2, 3, 4, 5] print(nums == nums2) print(nums is nums2) print(id(nums)) ...
d2e86bdbdf4e8f83d7febd486f94a4a8700519f2
t4d-classes/python_03222021_afternoon
/language_demos/boolean_demo.py
254
3.875
4
from operator import xor print(True or False) print(True and False) print(not True) print(xor(True, False)) print("Test" or 2) # falsy # 0 print("truthy" if 2 else "falsy") # "" print("truthy" if "something" else "falsy") # False # None # [] # ()
8c605c13c8538880985b22013038839aa627f464
kippig/Python_Practice
/src/LeetCode/number_of_islands.py
1,161
3.75
4
def numIslands(grid) -> int: if len(grid) == 0: return 0 elif len(grid[0]) == 0: return 0 counter = 0 # iterate through the grid for row in range(len(grid)): for col in range(len(grid[0])): if grid[row][col] == 1: flood_fill(grid, row, col) ...
810feb66fa582ba84af9f80c5a54c0ce063a8e0a
kippig/Python_Practice
/src/Cracking_the_coding_interview/Chapter_16_Moderate/16.11.py
611
4.03125
4
# Diving Board: You are building a diving board by placing a bunch of planks of wood end-to-end. There are two types of # planks, one of length shorter and one of length longer. You must use exactly K planks of wood. Write a method to # generate all possible lengths for the diving board. def diving_board(len1, len2, ...
1891f9460ed43cc7385880f9326c25a6caef2ab7
kippig/Python_Practice
/src/Cracking_the_coding_interview/Chapter_16_Moderate/16.3.py
1,412
3.90625
4
# Intersection: Given two straight line segments (represented as a start point and an end point), # compute the point of intersection, if any. # construct the lines in point slope form class Line: def __init__(self, p1, p2=None, slope=None): if p2 is None and slope is None: raise ValueError(...
27a96d3f6e45c2fb92bb79907f4ef9cfc33cc1d8
kippig/Python_Practice
/src/Cracking_the_coding_interview/Chatper_17_Hard/17.10.py
1,172
3.546875
4
def partition(arr, low, high): pivot = arr[low + (high - low)//2] while True: while arr[low] < pivot: low += 1 while arr[high] > pivot: high -= 1 if low >= high: return high arr[low], arr[high] = arr[high], arr[low] low += 1 hig...
100594501752c83d93dab98d18a5723f1c4564d6
kippig/Python_Practice
/src/Cracking_the_coding_interview/Chapter_16_Moderate/16.10.py
956
4.09375
4
# Living People: Given a list of people with their birth and death years, implement a method to compute the year with # the most number of people alive. You may assume that all people were born between 1900 and 2000 (inclusive). If a # person was alive during any portion of that year, they should be included in that ye...
d2af04215058fbb4cf6fab09b1ac46b6d7665d27
kippig/Python_Practice
/src/Cracking_the_coding_interview/Chapter_10_Sorting_and_Searching/10.5.py
961
4.0625
4
def find_nearest_left(arr, index): while arr[index] == '': index -= 1 return index def sparse_search(arr: list, target: str, low=0, high=None): """ modified binary search where you need logic to handle hitting empty string. Time: log(n), n is number of non sparse values, but due to find ne...
a4f402c6d89dfb98756266a8431a2602260f6e7c
kippig/Python_Practice
/src/Cracking_the_coding_interview/Chapter_10_Sorting_and_Searching/10.10.bucket.fail.py
1,618
3.671875
4
# Rank from Stream:Imagineyouarereadinginastreamofintegers.Periodically,youwishtobeable to look up the rank of a numberx # (the number of values less than or equal tox). lmplement the data structures and algorithms to support these # operations. That is, implement the method track ( int x), which is called when each nu...
1aa22d435eda3d81f12764f51da62f2cb3a3f22e
kippig/Python_Practice
/src/Cracking_the_coding_interview/Chapter_16_Moderate/16.13.py
1,751
3.9375
4
# Bisect Squares: Given two squares on a two-dimensional plane, find a line that would cut these two squares in half. # Assume that the top and the bottom sides of the square run parallel to the x-axis. # Math problem! do on paper and pencil first # first find the middle of each square, then find the line the intersec...
12592a75124cc4134f7735551c94594da9c6093e
kippig/Python_Practice
/src/Cracking_the_coding_interview/Chapter_1_Arrays_And_Strings/1.5.py
938
3.71875
4
def levenshtein_distance(s1, s2): """ Space: O(n*k) Time: O(n*k) :param s1: :param s2: :return: """ array_map = [[0 for x in range(len(s1))] for y in range(len(s2))] array_map[0][0] = int(s1[0] != s2[0]) for col in range(1, len(s1)): array_map[0][col] = array_map[0][col ...
bcc25fa4698e6c2e3d8bdef4290d8cdbc90bc7bc
alberico04/Test
/main.py
2,845
4.25
4
#### Describe each datatype below:(4 marks) ## 4 = integer ## 5.7 = float ## True = boolean ## Good Luck = string #### Which datatype would be useful for storing someone's height? (1 mark) ## Answer: FLOAT #### Which datatype would be useful for storing someone's hair colour?(1 mark) ## Answer: ST...
d3129bfb1fd079a4c064944113425d1ee4f43a61
SadiaaSharmin/Python_50_Problems
/22th.py
130
4.15625
4
num = float(input("Enter a number: ")) if num < 10: print(num, "is less than 10") else: print(num, "is not less than 10")
74c5870af03025ca9a71a3bddb29d572a5b628fc
SadiaaSharmin/Python_50_Problems
/3rd.py
158
4.4375
4
#Find power of any number x = int(input("Enter a number: ")) y = int(input("Enter an another number: ")) power = x**y print("Power of any number x^y:",power)
112af65be7f00b2a1ab901ed50899550b612d6c8
Mohnish226/Computer-vision-learn
/GrayScale.py
550
3.5625
4
#!/usr/bin/env python2 # -*- coding: utf-8 -*- """ Created on Mon May 1 16:44:47 2017 @author: Mohnish_Devadiga """ import cv2 # Load our input image image = cv2.imread('./images/input.jpg') cv2.imshow('Original', image) cv2.waitKey() # We use cvtColor, to convert to grayscale gray_image = cv2.cvtColor(image, cv2....
cf264e53f4e4bc11c330f5afbc3fcd5088c27cdc
irazakharchenko/Classroom
/Classroom.py
856
3.734375
4
class Classroom: def __init__(self, number, capacity, equipment): self.assig(number, capacity, equipment) def assig(self, num, cap, equip): self.number = num self.capacity = int(cap) self.equipment = equip def is_larger(self, other): return self.capacity > other.cap...
6bb878e782d8bdc68163c316b0078dd2e3021f01
fushar/cp-problems
/topcoder/tco-2017-2b/DengklekGaneshAndChains/gen.py
3,530
3.515625
4
import random import itertools def printTestCase(chains, lengths): print('{' + ', '.join(map(lambda s: '"' + s + '"', chains)) + '}') print('{' + ', '.join(map(str, lengths)) + '}') def comper(n): s = [chr(ord('a')+i) for i in range(n)] chains = [''.join(t) for t in itertools.permutations(s)] leng...
c0e16c20ed00559811cc9dc8a1f8f7bf1425d709
jeffzhangding/study
/letcode/字节跳动章节/挑战字符串/复原IP地址.py
1,366
3.59375
4
""" 给定一个只包含数字的字符串,复原它并返回所有可能的 IP 地址格式。 示例: 输入: "25525511135" 输出: ["255.255.11.135", "255.255.111.35"] """ from collections import deque class Solution: def restoreIpAddresses(self, s: str): """""" res_list = self.get_sub_string(s, sub_number=4) res = [] for i in res_list: ...
195462a22c36d1d58f21ef2ee20303b10075034d
jeffzhangding/study
/letcode/基础算法/最小栈.py
1,383
3.703125
4
""" 最小栈 """ from collections import deque from math import floor class MinStack: def __init__(self): """ initialize your data structure here. """ #self.stack = deque() self.stack = [] def push(self, x: int) -> None: self.stack.append(x) def pop(self) -> ...
ef2725ede782e52aef43a232849f1d8af18b86e6
Zepho39/advent-of-code-2019
/aoc2019_20_1.py
4,376
3.734375
4
INPUT = '' def buildDonut(file): donut = {} portals = {} portalPieces = {} donutGraph = {} y = 0 width = 0 start = (0, 0) end = (0, 0) with open(file) as donutMap: donutLine = donutMap.readline().strip('\n') width = len(donutLine) while donutLine: for x in range(width): donut[(x, y)] = donutLin...
102a6330ebb0316e47b278399b1d3ae48b0ba54d
Pariasrz/N-Puzzle-solver-with-Search-Algorithms
/Main.py
1,970
3.765625
4
from Search_Algorithms import BFS, DFS, Greedy, AStar_search #initial state n = int(input("Enter n\n")) print("Enter your" ,n,"*",n, "puzzle") root = [] for i in range(0,n*n): p = int(input()) root.append(p) print("The given state is:", root) #count the number of inversions def inv_num(...
82c0034b4eb270eb863e71892a5206d37c6a40b5
qwerthjkl45/Deep-Learning
/assignment_1/code/ponpon (2)/modules.py
11,333
3.546875
4
""" This module implements various modules of the network. You should fill in code into indicated sections. """ import numpy as np class LinearModule(object): """ Linear module. Applies a linear transformation to the input data. """ def __init__(self, in_features, out_features): """ Initializes the pa...
1fd45b3a589952ecd6c139c96bb8bff806865798
qwerthjkl45/Deep-Learning
/assignment_1/code/modules.py
7,336
3.78125
4
""" This module implements various modules of the network. You should fill in code into indicated sections. """ import numpy as np class LinearModule(object): """ Linear module. Applies a linear transformation to the input data. """ def __init__(self, in_features, out_features): """ Initializes the pa...
ca2e80663596afd193a19956f3b3bee37b0b9976
gaberani/AlgorithmStudy
/0419/[1차] 캐시_김현성.py
984
3.625
4
def solution(cacheSize, cities): answer = 0 cache = [] for word in cities: word = word.lower() if len(cache) < cacheSize: if word not in cache: answer += 5 cache.append(word) else: answer += 1 cache.pop(c...
dc09e1a0c600db2fe9462b8c7a73aa394d1fb9ed
gaberani/AlgorithmStudy
/1215/1462. Course Schedule IV.py
1,423
3.96875
4
# There are a total of n courses you have to take, labeled from 0 to n-1 # Some courses may have direct prerequisites, for example, # to take course 0 you have first to take course 1, # which is expressed as a pair: [1,0] # 코스 0을 타기 위해선 코스 1을 먼저 타야함. # Given the total number of courses n, # a list of direct prerequis...
0139caa7f479b9219c63a6765ab25e39e7b68a4b
gaberani/AlgorithmStudy
/0628/2020-06-28/종이접기_김현준.py
378
3.546875
4
def solution(n): shape = '' ''' n=1 0 n=2 0 0 1 n=3 0 0 1 0 0 1 1 ''' for _ in range(n): tmp = '0' for i in range(len(shape)): if i%2: tmp += shape[i]+'0' else: tmp += shape[i]+'1' shape = tmp ret...
694b7b73b83d5b91d4de5218e4d80acd65b746a1
gaberani/AlgorithmStudy
/0510/RGB거리_김현성.py
704
3.90625
4
def color(result_lst, n, cost): for i in range(1, n): # 각각 첫 집 이 R, G, B 칠하고 시작한 것 result_lst[i][0] = cost[i][0] + min(result_lst[i-1][1], result_lst[i-1][2]) result_lst[i][1] = cost[i][1] + min(result_lst[i-1][0], result_lst[i-1][2]) result_lst[i][2] = cost[i][2] + min(result_lst[i-...
b0de09c29bc968a9f9efd15ec7e1f1c274cb19dc
gaberani/AlgorithmStudy
/1220/120. Triangle.py
2,023
3.875
4
# Given a triangle, find the minimum path sum from top to bottom. # Each step you may move to adjacent numbers on the row below. # For example, given the following triangle # [ # [2], # [3,4], # [6,5,7], # [4,1,8,3] # ] # The minimum path sum from top to bottom is 11 (i.e., 2 + 3 + 5 + 1 = 1 class Solu...
429db445cc6c7304ffb72dde5b40c6a9612818e3
gaberani/AlgorithmStudy
/1206/49. Group Anagrams.py
1,267
3.5
4
class Solution(object): # 3320 def groupAnagrams(self, strs): """ :type strs: List[str] :rtype: List[List[str]] """ str_dic = [] for str in strs: s_dic = {} # 한글자씩 따기 for s in str: s_dic[s] = 1 if s_dic.get(s) ==...
5bd642759c9a62929984854c5dbad8726d5eaf0c
gaberani/AlgorithmStudy
/1210/357. Count Numbers with Unique Digits.py
832
3.5
4
# Given a non-negative integer n, # count all numbers with unique digits, x, where 0 ≤ x < 10^n. # 0 <= n <= 8 class Solution(object): def countNumbersWithUniqueDigits(self, n): """ :type n: int :rtype: int """ # n과 같은 길이를 갖고 있고 # set를 써서 중복없애면 길이가 1인 경우 전부 제외 ...
800cacb0771972168907cf68429d6ebaf2f57ea0
KrzysztofKostecki/aoc2020
/day05.py
3,905
4.15625
4
from typing import Tuple, List from functools import reduce from operator import add, mul import re """ --- Part One --- Instead of zones or groups, this airline uses binary space partitioning to seat people. A seat might be specified like FBFBBFFRLR, where F means "front", B means "back", L means "left", and R means ...
78408abb947546de492fbe9b76c95939c505aceb
arnabs542/leetcode_solutions
/binary_search/related/search_in_rotated_sorted_array/solution.py
814
3.640625
4
class Solution: """https://www.lintcode.com/problem/62/?_from=collection&fromId=161 Description Suppose a sorted array is rotated at some pivot unknown to you beforehand. (i.e., 0 1 2 4 5 6 7 might become 4 5 6 7 0 1 2). You are given a target value to search. If found in the array return its index, otherwise...
f7c105b69d36ba6de3cee2533c06361b8a2b1f3f
arnabs542/leetcode_solutions
/bfs/required/word_ladder/solution.py
2,747
3.625
4
from collections import deque class Solution: """https://www.lintcode.com/problem/120/?_from=collection&fromId=161 Description Given two words (start and end), and a dictionary, find the shortest transformation sequence from start to end, output the length of the sequence. Transformation rule such that: ...
e0a9468f907c3c8cbd012051b83c69f4043c82d2
arnabs542/leetcode_solutions
/string/required/longest_palindromic_substring/solution.py
1,682
3.640625
4
class Solution: """https://www.lintcode.com/problem/200/?_from=collection&fromId=161 Description Given a string S, find the longest palindromic substring in S. You may assume that the maximum length of S is 1000, and there exists one unique longest palindromic substring. Example Example 1: Input:"abcdzdcab" O...
98828993f10f8b746593d66f53addff33aadcc6c
arnabs542/leetcode_solutions
/two_pointers/related/kth_largest_element/solution.py
1,326
3.640625
4
class Solution: """ O(n) O(1) @param k: An integer @param nums: An array @return: the Kth largest element """ def quick_select(self, nums, start, end, k): # quick select k-th smallest element pivot_index = self.partition(nums, start, end) if k - 1 == pivot_index:...
289d6da77b42ff77760fdb4a0d28335e980aded5
arnabs542/leetcode_solutions
/binary_search/related/search_in_a_big_sorted_array/solution.py
1,747
3.609375
4
class Solution: """ https://www.lintcode.com/problem/447/?_from=ladder&fromId=161 Given a big sorted array with non-negative integers sorted by non-decreasing order. The array is so big so that you can not get the length of the whole array directly, and you can only access the kth number by ArrayReader.g...
d4f1ec07ddd9cdb5d2065e15965640a3dccc883d
arnabs542/leetcode_solutions
/dfs/required/letter_combinations_of_a_phone_number/solution.py
1,975
4.03125
4
KEYBOARD = ["", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"] class Solution: """https://www.lintcode.com/problem/425/?_from=collection&fromId=161 Description Given a digit string excluded 0 and 1, return all possible letter combinations that the number could represent. A mapping of d...
8558dc24b359cc17caad695cfe25394cb2bce134
arnabs542/leetcode_solutions
/two_pointers/required/two_sum_iii_data_structure_design/solution.py
1,473
3.953125
4
class TwoSum: """ This naive solution will exceed timeout limit Description Design and implement a TwoSum class. It should support the following operations: add and find. add - Add the number to an internal data structure. find - Find if there exists any pair of numbers which sum is equa...
b5d89c1756d6fc366ab86a9361427131b10579de
urbrob/programming
/Python/Others/RomanToArabic/roman.py
838
3.9375
4
# Created By: Robert Urbaniak 215904 @ 04.10.2018 roman = 'MCMDXXXIII' arabic = 1997 roman_dict = { 'M': 1000, 'CM': 900, 'D': 500, 'CD': 400, 'C': 100, 'XC': 90, 'L': 50, 'XL': 40, 'X': 10, 'IX': 9, 'V': 5, 'IV': 4, 'I': 1 } def roman_to_arabic(number): resul...
82575d812269b58cb220e0e5c9218d5e9f5d4d11
christophercalle/Tues_Sept_18
/calculator.py
581
4.21875
4
def add(num1,num2): print(num1 + num2) def subtract(num1,num2): print(num1 - num2) def multiply(num1,num2): print(num1 * num2) def divide(num1,num2): print(num1 / num2) first_number = int(input("Give me a number: ")) operator = input("Give me a math operator: ") second_number = int(input("Give me a...
1c732d9e7d47b5553bd80b7fe2cdb85223102a3e
Dickens-odera/python-udemy
/main.py
1,128
3.890625
4
from strings import * from login import login from SalariedEmployee import * # Working with Numbers def calculate_result(): print(f'2 to the power of 3 is {2 ** 3}') print(f'21 modulo 2 is {21 % 2}') print(f'First Value {2 + 2 * 5 - 1}') print(f'Second value with parenthesis {(2 + 2) * (5 - 1)}') i...
27a81702e4e85e49a0214a5ebb858957a2f24446
yashverma9/HashByte
/speechToText/appFile.py
851
3.734375
4
#import library import speech_recognition as sr # Initialize recognizer class (for recognizing the speech) r = sr.Recognizer() # Reading Audio file as source # listening the audio file and store in audio_text variable cnt = 1 while (cnt <= 1): # with sr.AudioFile('output{}.wav'.format(cnt)) as source: with sr...
18a519fd54d496dbf75ffc9b98beb0d9ad93c2cb
asafmenn/fibonacci
/fibonacci.py
668
3.984375
4
def fibonacci(num): if num <= 1: return num else: return fibonacci(num-1)+fibonacci(num - 2) number = input('please enter a number: ') while True: if number.isdigit(): print(fibonacci(int(number))) break else: number = input('please enter a VALID nu...
6f996ac10a8d1671d0e3704d18ac0f9bf3295538
barmath/ProjectEuler
/Multiples.py
159
3.625
4
def main(): list = [] for i in range(1,1000): if (i%3 == 0 or i%5 == 0): list.append(i) return sum(list) if __name__ == '__main__': print(main())
b5d7d61af0cb5d8de7a83faebfb8d22848e50f62
muditabysani/Design-4
/Twitter1.py
2,813
3.90625
4
import heapq class Tweet(): def __init__(self, tweetid, time): self.tweetid = tweetid self.time = time def __lt__(self, other): return self.time < other.time class Twitter(object): def __init__(self): """ Initialize your data structure here. """ ...
45932ddd36dd554da89ddfd44ba8b57b652263cc
henrikmathiesen/python-first-step
/iv_gr.py
545
3.578125
4
# # Input print("Enter name") name = input() print("Enter EPS") eps = input() print("Enter growth rate") gr = input() print("Enter current PPS") pps = input() # # Constants noGrPe = 0.085 rrOfR = 0.03 # # Convert input eps = float(eps) gr = float(gr) gr = gr / 100 pps = float(pps) # # Calculate iv = (eps * (n...
a53f49f1af5bfb1f8cb0fda00df194349e869f94
karimov/rpn-calc
/rpn/funcs.py
8,402
3.59375
4
''' This module containts implementations of trigonometric, mathematical functions, as well as numeric utilities. ''' from math import atan, cosh from os import terminal_size import random from .operators import Operator import math # Trigonometric operators class Cos(Operator): def __call__(self, x): ...
afc73d040bf1e93368b47eccc6f9c64f11ab7696
L200190180/Praktikum-Algopro
/Praktikum 8/kegiatan2.py.py
1,667
3.59375
4
data = {'nama':'fakhri', 'nim':'L200190180', 'umur':'18', 'hobi':'ngegame', 'asal':'purwodadi', 'sekolah':'ums', 'golongan_darah':'A'} def nama(): print('nama:',data['nama']) def nim(): print('nim:',data ['nim']) def umur(): print('umur:',data['umur']) def hobi(): print('hobi:',data ['hobi']) d...
5f8895477b3126ef448a0ff2ef145386eb13b33a
fatedglory14/Computational-Physics
/trapezint.py
1,915
3.78125
4
#Exercise 3.6: Integrate a function by the Trapezoidal rule #Andrew Turner from math import * from scipy.integrate import quad #Part a print 'Parts A + B:\n' def trapezint1(f, a, b): return (b-a) / 2. * (f(a) + f(b)) #Part b f1 = (cos, 0, pi) f2 = (sin, 0, pi) f3 = (sin, 0, pi / 2) functions = [f1, f2, f3] ...
67854b3ddb30a13ae2dba3fab87ffcdea76f227a
fatedglory14/Computational-Physics
/pi_approx.py
682
3.734375
4
#Exercise 3.13 Approximate pi #Andrew Turner from math import * #First call the path length function from before def pathlength(x, y): L = 0. for i in range(1, len(x)): dlength = sqrt((x[i] - x[i - 1]) ** 2. + (y[i] - y[i - 1]) ** 2.) L += dlength return L #Now we can define a function f...
f4f131f11cb1905e2d484b8b504dfe9944b7c000
fatedglory14/Computational-Physics
/hooking_rule.py
908
3.6875
4
#Homework 7 Problem 5 Dimension of Symmetric Partition #Andrew Turner from numpy import * from math import * n = 4 sym_partition = [[1,1],[1,1]] hooking_factor = 1 for i in range(len(sym_partition)): for j in sym_partition[i]: hook = sum(sym_partition[i][j:]) + sum(sym_partition[i:][j]) -1 hookin...
0cfe7683b9600863795cca7bf77c8546375433a7
fatedglory14/Computational-Physics
/check_symmetric_group.py
2,426
3.5625
4
#Exercise 3 Homework 8 #Andrew Turner from math import * '''In this code I used previous coding provided by the professor''' def transpose_partition(p): longest_height=len(p) column_height = [longest_height]*p[-1] # there are p[-1] columns with the maximum height length_of_prior_row = p[-1] ind = -2 ...
73e2d80fbbbd2d85096800735077cdb25f3b78e6
fatedglory14/Computational-Physics
/f2c_cml.py
149
3.59375
4
#Exercise 4.2 #Andrew Turner import sys F = float(sys.argv[1]) C = (5. / 9) * (F - 32) print '%5.2f degrees Farenheit is %5.2f degrees Celsius.' % (F, C)
5e533bb83b3ec16a413d61ca04c2e3d65193e15f
abhilash1392/pythonBasicExercisesPart1
/exercise_20.py
485
3.890625
4
"20. Write a Python program to get a string which is n (non-negative integer) copies of a given string." def multipleString(sentence,n): """Assumes n is (non-negative integer) Returns multiple copies of sentence sentence[str]:[The sentence you input] n [int]:[Non-negative number] """ return ...
4cb82d079ffac6a7d07d598ab27ebb14d840f9b7
abhilash1392/pythonBasicExercisesPart1
/exercise_5.py
292
4.25
4
"""5. Write a Python program which accepts the user's first and last name and print them in reverse order with a space between them.""" first_name=input('Please enter your first name: ') last_name=input('Please enter your last name: ') print('Hello {} {}'.format(last_name,first_name))
8b92982b89f15d8c800f9b13517b1bb952b235a6
Zahidsqldba07/coding-problems-2
/leetcode/leetcode-monthly-challenges/leetcode_30-may-2020/22-sort-characters-by-frequency.py
309
3.53125
4
class Solution: def frequencySort(self, s: str) -> str: counts = {} for c in s: counts[c] = counts.get(c, 0) + 1 counts_sorted = sorted(counts.items(), key=lambda c: c[1], reverse=True) result = "".join(c[0]*c[1] for c in counts_sorted) return result
6ea305dabf92902b15b0962ce7872cd90a5b3b35
Zahidsqldba07/coding-problems-2
/hackerrank/interview-preparation-kit/linked-list/01_insert_a_node_at_specific_position.py
541
3.640625
4
class SinglyLinkedListNode: def __init__(self, node_data): self.data = node_data self.next = None def insertNodeAtPosition(head, data, position): new_node = SinglyLinkedListNode(data) if head is None: return new_node if position == 0: new_node.next = head retu...
2da8dc8b2982888ef6014b4898b2a1f2a329976c
Zahidsqldba07/coding-problems-2
/leetcode/patterns/06-in-place-reversal-linked-list/02_reverse_linked_list_II.py
672
3.609375
4
class Solution: def reverseBetween(self, head, m, n): if m == n: return head prev = None cur = head for _ in range(m-1): prev = cur cur = cur.next last_node_left_part = prev last_node_sub_list = cur next_n...
24637e80cbd08b7755f7ea6eecf5830036ac1d19
Zahidsqldba07/coding-problems-2
/leetcode/top-interview-questions/01_easy_collection/02_strings/09_longest_common_prefix.py
393
3.625
4
class Solution: def longestCommonPrefix(self, strs): if not strs: return '' res = [] for i in range(len(strs[0])): char = strs[0][i] for j in range(1, len(strs)): if i >= len(strs[j]) or char != strs[j][i]: return ''.join(r...
f7efa155bf749b9ed949bfdc05459818062b69f1
Zahidsqldba07/coding-problems-2
/prynatas/0021_binary_tree_level_order_traversal.py
1,335
4.0625
4
# Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right from collections import deque class Solution: def levelOrder(self, root): if not root: return None ...
7ff1b84e03d0d63fcba001131f1cbb7618edef05
Zahidsqldba07/coding-problems-2
/leetcode/learn-cards/binary-search-trees/02_BST_iterator.py
1,517
4
4
class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right from collections import deque # Method 1: in-order traversal and queue to store nodes class BSTIterator: def __init__(self, root: TreeNode): self.roots = deque()...
bfb5e9ddf6a7aedd11de623f78d4f1b22d57e7b5
Zahidsqldba07/coding-problems-2
/dynamic-programming/Andrey-Grehov/0006_climbing_stairs_k_steps_space_optimized.py
885
4
4
import unittest ''' Climbing Stairs (k steps, space optimized) You are climbing a stair case. It takes n steps to reach to the top. Each time you can climb 1..k steps. In how many distinct ways can you climb to the top? ''' # TC: O(nk) # SC: O(k) def climb_stairs_k_steps(n, k): dp = [0] * k dp[0]...
1b18488860be1b0436f34b9ef742b9920e36a830
Zahidsqldba07/coding-problems-2
/leetcode/learn-cards/array-101/16_find_all_nums_disappeared_in_an_array.py
243
3.65625
4
class Solution: def findDisappearedNumbers(self, nums): nums_set = set(nums) result = [] for num in range(1, len(nums)+1): if num not in nums_set: result.append(num) return result
c9193407ca0ab7aa0246981dada747624ded3a29
Zahidsqldba07/coding-problems-2
/dynamic-programming/Andrey-Grehov/0020_coin_change_unique_ways.py
2,718
3.84375
4
import unittest ''' Link: https://youtu.be/g0VjciqYeDU Problem: Coin change Given an unlimited supply of coins of given denominations, find the unique number of ways to make a change of size n. Denominations: coins = [1, 2, 3, 5] Transition Function: i >= 1: f[i][1] = f[i-1][1] i >= 2: f[i][2] = f...
e42af591685f9719ae9a7767c3544e4a4b71b6ce
Zahidsqldba07/coding-problems-2
/dynamic-programming/Andrey-Grehov/0019_coin_change_even.py
1,556
3.71875
4
import unittest ''' Problem: Coin change Given an unlimited supply of coins of given denominations, find the total number of ways to make a change of size n, by using an even number of coins. # 1, 3, 5, 10 # 0 -> odd, 1 -> even f[i][0] = f[i-1][1] + f[i-3][1] + f[i-5][1] + f[i-10][1] f[i][1] = f[i-1][0] + f...
12fed6907f14c7d18163aabb0ebd12261d17f958
Zahidsqldba07/coding-problems-2
/leetcode/top-interview-questions/01_easy_collection/04-trees/02_validate_bst.py
458
3.65625
4
class Solution: def isValidBST(self, root): if not root: return True return self.helper(root, float('-inf'), float('inf')) def helper(self, node, low, high): if not node: return True if node.val <= low or node.val >= high: return False l...
e2d013437ecf0e91f9413f339911186698255b60
Zahidsqldba07/coding-problems-2
/leetcode/learn-cards/binary-tree/07_path_sum.py
391
3.609375
4
class Solution: def hasPathSum(self, root, sum): def traverse(node, cur_sum): if not node: return False cur_sum += node.val if not node.left and not node.right: return cur_sum == sum return traverse(node.left, cur_...
6d85532d6a477d7913b2ce9f99cce4cc96b22b4c
Zahidsqldba07/coding-problems-2
/leetcode/top-interview-questions/02_medium_collection/04_backtracking/01_letter_combinations_of_a_phone_number.py
796
3.609375
4
class Solution: def letterCombinations(self, digits: str) -> List[str]: if len(digits) == 0: return [] self.letters = { "2": "abc", "3": "def", "4": "ghi", "5": "jkl", "6": "mno", "7": "pqrs", "8": "tuv", ...
472270427da85c8a131fc0c138a957288811c8c0
Zahidsqldba07/coding-problems-2
/leetcode/learn-cards/n-ary-trees/02_postorder_n-ary_traversal.py
1,227
3.625
4
class Solution: def postorder(self, root: 'Node') -> List[int]: self.res = [] if not root: return self.res self.traverse(root) return self.res def traverse(self, node): if not node: return for child in node.children: self.traverse(child)...
ce101e452f7d61b865aa2f6263398a18a7733ef2
Zahidsqldba07/coding-problems-2
/leetcode/learn-cards/n-ary-trees/01_preorder_n-ary_traversal.py
734
3.59375
4
class Solution: def preorder(self, root: 'Node') -> List[int]: self.res = [] if not root: return self.res self.traverse(root) return self.res def traverse(self, node): if not node: return self.res.append(node.val) for child in node.children: ...
152a758c78c9153b261fe96ce36aa5ec4f2c4a2c
wiichis/ahorcado_game
/ahorcado_game.py
2,546
3.609375
4
import random import os from functools import reduce #Leyendo el archivo def read(): words = [] with open("./archivos/data.txt", "r", encoding="utf-8") as f: for line in f: words.append(line) #Seleccionado Palabra global random_word_uper random_word = words[random.randint(0,len...