blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
6846d3a528137ca8786d3fbf4f3279d371c550aa
MsDiala/amman-python-401d2
/class-01/demo/class-one-topics/class_one_topics/topics.py
1,485
4.21875
4
"""Things to cover... * What is a module * What is a script * How to execute it from CLI * print/input * string concatenation * formatted strings * if __name__ == "__main__": snippet """ some_secret_num = 9 def input_output(): print("no console.log for me!") print("that's the standard output") print("b...
4efdee1ac0d8a4d4bfde0687087e198253d3903d
MsDiala/amman-python-401d2
/class-15/demo/binary-tree/binary_tree/binary_tree.py
1,048
4.09375
4
class Node: def __init__(self, value): self.value = value self.right = None self.left = None class BinaryTree: def __init__(self): self.root = None def preorder(self): #1. Initialize output = [] #2. Define the closure def _walk(node): ...
806cb5ff653da0e79eb04fddc42af4b54063ac05
jhonatang1988/holbertonschool-web_back_end
/0x00-python_variable_annotations/8-make_multiplier.py
362
3.625
4
#!/usr/bin/env python3 """ functions that returns another function """ from typing import Callable def make_multiplier(multiplier: float) -> Callable[[float], float]: """ functions that returns another function :param multiplier: float to multiply :return: """ def fun(n: float) -> float: ...
8eb216d1d6965e91d17852dffd558898ecd3b1d9
jhonatang1988/holbertonschool-web_back_end
/0x00-python_variable_annotations/9-element_length.py
469
4.1875
4
#!/usr/bin/env python3 """ converts element_length into annotated function def element_length(lst): return [(i, len(i)) for i in lst] """ from typing import Iterable, List, Tuple, Sequence def element_length(lst: Iterable[Sequence]) -> List[Tuple[Sequence, int]]: """ converts element_length into annotated...
bcb5ea6a9ad7317b4f65bcdfd0d6659e6ec844ef
bolducp/exercism-TDD-solutions
/python/isogram/isogram.py
155
3.578125
4
import re def is_isogram(string): string_no_punct = re.sub(r'[^\w]', '', string).lower() return len(string_no_punct) == len(set(string_no_punct))
01e9fee2dec12453c8ad39956d26e5a8a1d8e6f2
bolducp/exercism-TDD-solutions
/python/palindrome-products/palindrome_products.py
1,099
4.0625
4
def smallest_palindrome(max_factor, min_factor=0): return find_palindrome(max_factor, min_factor, find_largest=False) def largest_palindrome(max_factor, min_factor=0): return find_palindrome(max_factor, min_factor) def find_palindrome(max_factor, min_factor, find_largest=True): if min_factor > max_factor:...
fc57d4c4e28d229d63d1bba181dc147660c2d9e4
bolducp/exercism-TDD-solutions
/python/bob/bob.py
805
3.65625
4
import re def response(hey_bob): if is_silence(hey_bob): return responses["silence"] yelling = is_yelling(hey_bob) questioning = is_question(hey_bob) if yelling and questioning: return responses["question_caps"] elif yelling: return responses["all_caps"] elif questioni...
b8346ef050718df303956b98f1e924ace7938b01
mikedh/trimesh
/trimesh/path/packing.py
23,941
3.5
4
""" packing.py ------------ Pack rectangular regions onto larger rectangular regions. """ import numpy as np from ..util import allclose, bounds_tree from ..constants import log, tol # floating point zero _TOL_ZERO = 1e-12 class RectangleBin: """ An N-dimensional binary space partition tree for packing ...
732597812daa19340fd30487f535b4af90d8beda
mikedh/trimesh
/trimesh/voxel/runlength.py
20,338
3.921875
4
""" Numpy encode/decode/utility implementations for run length encodings. # Run Length Encoded Features Encoding/decoding functions for run length encoded data. We include code for two variations: * run length encoding (RLE) * binary run length encdoing (BRLE) RLE stores sequences of repeated values as the value f...
30f9a17934381525c1f4f7f6dc1bea31a26b7855
mikedh/trimesh
/trimesh/permutate.py
4,570
3.609375
4
""" permutate.py ------------- Randomly deform meshes in different ways. """ import numpy as np from . import transformations from . import triangles as triangles_module from . import util def transform(mesh, translation_scale=1000.0): """ Return a permutated variant of a mesh by randomly reording faces ...
9841e77a5869d37bdbe609e1b29c398223017d91
nataschaschneider/playing_around_with_python
/city_country_river_winner_20210129.py
2,233
4.09375
4
# City country river winner - Helps you win every game! # libraries and modules import pandas as pd from tabulate import tabulate # functions def play(): letter = input("Please enter the required letter and confirm by pressing ENTER:\n") letter = letter.upper() while letter not in alphabet: ...
5a437435f7c73380c5ad08723c674cb991f84c16
d0iasm/CtCI
/Chapter02/04_partition.py
2,764
3.640625
4
import unittest from LinkedList import LinkedList def partition(ll, k): head = ll.head tail = ll.head n = ll.head while n != None: nex = n.next if n.data < k: n.next = head head = n else: tail.next = n tail = n n = nex ...
4b3ee00b50109f4a03aa8b84446572bfdfeecbb0
d0iasm/CtCI
/Chapter04/BinaryHeapTree.py
2,237
3.65625
4
import unittest class BinaryHeapTree(object): def __init__(self, heap): self.heap = list(sorted(heap)) def push(self, data): self.heap.append(data) self.up_heap() def pop(self): if len(self.heap) == 1: return self.heap.pop() min_element = self.heap[0]...
91cfef7dc9a513efbe0a8d416dc229ea8821f3fe
d0iasm/CtCI
/Chapter04/03_create_level_linkedlist.py
1,467
3.71875
4
import unittest from LinkedList import LinkedList class Node(object): def __init__(self, data, left=None, right=None): self.data = data self.left = left self.right = right def create_level_linkedlist(root, lists, level): if root is None: return li = None if len(lists...
4958698d9cf8fb47263f57c56ed0311bee583b34
2guud4u/Python-2021-
/sort algorithm.py
379
3.84375
4
bull = True listy = [1, 878.8, 878.3, 8] num = [] #assignment for n in listy: num.append(n) i = num.index(n) print(i) bull = True #comparison sorting while bull: if i == 0: bull = False elif num[i] > num[i-1]: num[i], num[i-1] = num[i-1], num[i] ...
9fb02bdf6b87b308387425df8e2000e8c1f96672
maxowaxo/AdaptiveGeneticAlgorithmCode
/VectorClass.py
3,017
3.921875
4
class Vector(object): def __init__(self, *data): if type(data[0])==Vector: self.data = list(data[0]) else: self.data = list(data) def __repr__(self): return repr(tuple(self.data)) def print(self, n=0): print("Vector(", end ="") for j in range(len(self.data)-1): print (round(self.data[j],...
382acca5065a58bfb98673c58fa2a19f25a665ae
judening/BasicSorting
/quicksort.py
933
4.1875
4
def quick_sort(teh_list,left,right): if (right-left) <=0: return else: start = left end = right pivot = start while start < end: while(teh_list[start] <= teh_list[pivot]) and start<end: start+=1 while(teh_list[end] > t...
c3deec502be0039f7e04f006ec4a3dd5ef1cbd8d
stephaneAG/Python_tests
/learningpythonthehardway/ex12.py
331
3.828125
4
age = raw_input("How old are you brother ?") # will get some text ;def height = raw_input("How tall are you ?") eat = raw_input("do you eat enough ?") print "So, you're a %r years old and %r tall guy that says : '%r' to the food, right ?" % (age, height, eat) # Nb: to get a number from the return stuff, 'x = int(raw...
e02a2a227bea7bfd6f123cc3cac4232edd5024bb
karanjoshi1206/python_programs
/program7.py
458
4.21875
4
# By Karan joshi # Program7: Create a function that take an integer and return its factorial def factorial(num): fact = 1 if(num < 0): print("Sorry factorial does not exists ") elif (num == 0): print("Factorial of 0 is 1 ") else: for i in range(1, num+1): fact = fact...
853f73a69b58fde4faacddde61053f157d949028
nihalmohammad/Check-Content
/src/applecode.py
1,497
3.890625
4
# Enter your code here. Read input from STDIN. Print output to STDOUT import operator import re fruit_lookup = {} company_lookup = {} N = int(raw_input()) with open('apple-fruit.txt','r') as fruit: for line in fruit: for word in re.split('\W+', line.upper()): if word not in fruit_lookup: ...
4040fbd22eedf2cfcb3b669b3fe0f0c008ce0af2
EricSchles/sqlite_directory_of_friends
/app/models.py
1,730
3.84375
4
import sqlite3 as sql def insert_account_holder(email,username,phone,password): with sql.connect("database.db") as con: cur = con.cursor() cur.execute("INSERT INTO account_holder (email,username,phone,password) VALUES (?,?,?,?)", (email,username,phone,password) ) con.commit() def ins...
f6b755feba52a011005fe0389bd5b259cacdca9d
Ann-Mamaeva/dz
/re.email.py
597
3.890625
4
#сделать программу, которая собирает данные пользователей import re filename = 'program.txt' with open(filename, 'w') as file: file.write('') while True: print('Укажите почту') email = input() a = '\w+@\w+.\w+' #регулярное выражение, что совпадает с почтой вида test@gmail.com if re.match(r...
fc14292e02b86a8afec431eb622a86debcd1e50d
danielmccallion/pands-problems
/labs/Topic03-variables/lab3_07_random_fruit_2.py
281
4.21875
4
# Daniel Mc Callion # Program that prints out a random fruit using tuple and random import random fruits = ("Apple", "Banana", "Orange", "Grape", "Pear", "Mango") # Get a random fruit from tuple random_fruit = random.choice(fruits) # Print output print(f"A random fruit: {random_fruit}")
0c496a76161ec36ce949d9286481ee28e584517f
danielmccallion/pands-problems
/labs/Topic03-variables/lab3_08_dictionaries.py
653
4.71875
5
# Daniel Mc Callion # Program that prints out a dictionary object called current_book # Prints the author of current_book # Adds a new attribute with value called ISBN # Prints out all the values in the current_book using a for loop current_book = { "title": "Harry Skyward", "author": "Brandon Potterson", ...
199befad14ca0e6ea45872a1679d4b77215e3fe4
danielmccallion/pands-problems
/lectures/primes_function.py
268
3.734375
4
# Daniel Mc Callion # Computing the primes from functions import is_prime_func # My list of primes p = [] # Loop through all of the numbers we're checking for primality# for i in range(2, 100000): if is_prime_func(i): p.append(i) # Print out the primes print(p)
c116a1b7f6bee877062d8581d8e99426dc37dc1f
danielmccallion/pands-problems
/lectures/primes.py
616
4.0625
4
# Daniel Mc Callion # Computing the primes # My list of primes p = [] # Loop through all of the numbers we're # checking for primality for i in range (2,10000): # Assume that i is a prime is_prime = True # Look through all values j from 2 up # to but not including i # for j in range(2,i): for...
eec28afcf4d62deb044a811be209e909648958b7
lxndrvn/python-pair-programming-exercises-2nd-tw-szandra-es-fani
/palindrome/palindrome_module.py
247
3.9375
4
import re def palindrome(string): word = string.lower() word = re.sub(' ', '', word) if str(word) == str(word)[::-1]: return True else: return False def main(): return if __name__ == '__main__': main()
105f7f4330667a3064f43a470ea179ea1d984132
paulwithap/MITx6.00x
/Week6/hashSet.py
2,651
3.875
4
class hashSet(object): def __init__(self, numBuckets): ''' numbuckets: int. The number of buckets this hash set will have. Raises ValueError if this value is not an integer, or if it is not greater than zero. Sets up an empty hash set with numBuckets number of buckets. ...
7135914feb263822f83149e0d52d639905b4f753
udacity/AIND-VUI-quizzes
/ngram_quiz_3/gradingcode.py
1,984
4.25
4
""" Grading Code - The Python code responsible for marking submission correct/incorrect and to provide feedback when a student clicks ‘Submit’. To do this, you need to use the dictionary called executor_result which contains the output of the Execution Code. The executor_result dictionary co...
a494da348c0d521e9e7086c8518c112378a9ea17
kevinyangff/Python-programming-exercises
/level0/question36.py
68
3.59375
4
def printList(): print([x**2 for x in range(1, 21)]) printList()
c2ca1b0c3213ecd7106b874a651d4b873309dcf4
kevinyangff/Python-programming-exercises
/level0/question53.py
242
3.828125
4
class Shape: def area(self): return 0 class Square(Shape): def __init__(self, length): self._length = length def area(self): return self._length**2 shape = Shape() square = Square(100) print(square.area())
ed4212b837e639cb8b8049940724f5b4482e219f
kevinyangff/Python-programming-exercises
/level2/question15.py
726
3.578125
4
def genNum(digit, times): result = digit if times>=1 and digit>0 and digit<10: for i in range(1, times): result = result*10+digit return result def sum(digit, num): result = 0 for x in range(1, num+1): result += genNum(digit, x) return result print(sum(1, 3)) def ge...
9475c8c497218232da464f8926f444f4228bc036
kevinyangff/Python-programming-exercises
/level2/question7.py
316
3.6875
4
row, column = [int(i) for i in input("Input two digits for i and j separated by comma: ").split(',')] print("row:{0:d} column:{1:d}".format(row, column)) result = [] temp = [] for i in range(0, row): temp = [] for j in range(0, column): temp.append(i*j) result.append(temp) print(result)
9151a0898ba95480fe244557972f3abe60c0782b
abdullahgulcur/School
/CPU_Simulator/app.py
11,714
3.8125
4
#!/usr/bin/python program_counter = 0 def write_to_file_new_value(all_registers, binary_instruction, registerFile, reg2): count = 0 for line in all_registers: if count != int(binary_instruction[4:8], 2): # if it is not register to write registerFile.write(line) # we only change one regis...
218b7aebb5971eda9eb7089772a1749e19c9029d
kferguson2/text-mining
/assignment2.py
3,260
3.53125
4
from imdbpie import Imdb imdb = Imdb() def get_imdb_reviews(movie_title): """ Function that returns all the reviews for a given movie title """ movie = imdb.search_for_title(movie_title)[0] imdb_id = movie["imdb_id"] reviews = imdb.get_title_user_reviews(imdb_id) return reviews def get_r...
c360a0fb2f7010d6df10aa562c5e447409d54979
rmit-s3716022-Jason/library-iot-management-system
/src/tests/search_test/book.py
741
3.8125
4
""" book.py ======= """ class Book: """ This class will be used to contain the parameters of a book Constructor Creates the variables associated with this class :type book_id: int :param book_id: the unique identifier given to the book :type title: string :param ...
66034652d877f713c0ef0aa4df4fd3aa4e16340a
dperuo/repl
/python.py
184
3.6875
4
#!/usr/bin/env python # -*- coding: UTF-8 -*- array = [1, 2, 3, 0, 4, 5] def main(): for i in array: print 'hello #{0}'.format(i) if __name__ == '__main__': main()
913b8321e38ac80be7166e6e41d4a70ece9924ac
UTEP-Parallel-Computing/parallel-computing-map-reduce-Ricardo-Sillas
/lab_three.py
1,208
3.671875
4
# Parallel computing lab 3 # Ricardo Sillas import pymp import re import time def count_words(doc, word_list, tot_word): f = open(doc, 'r') for word in word_list: tot_word[word] += len(re.findall(word, f.read().lower())) f.seek(0) def map_reduce(doc_list, word_list): tot_word = pymp.share...
ce5ef60ccb38e88d526b270036a6ab9e9a46599a
mohamedScikitLearn/Alg-1
/REGEX/groups.py
2,121
4.28125
4
import re # ^ matches the beginning of a string. # $ matches the end of a string. # \b matches a word boundary. # \d matches any numeric digit. # \D matches any non-numeric character. # (x|y|z) matches exactly one of x, y or z. # (x) in general is a remembered group. We can get the value of what matched by using the...
7576f89e3e5e360b9ecfdc6fa8a117495e9be4b5
mohamedScikitLearn/Alg-1
/SORT/heap.py
1,243
4.125
4
# MergeSort = comparison-based, slower than quicksort but better in worst-case O(n log n) # heap is a specialized tree-based data structure def HeapSort(A): # create a heap out of given array of elements def heapify(A): start = (len(A) - 2) / 2 while start >= 0: siftDown(A, start,...
4e8f49bdd855b29e570ffa4c3eb60a4b27fc92c7
digitalnomd/algorithms
/recursion.py
653
3.765625
4
def allSubstrings(S): found = {} substrings = [] getAllSubstrings(S, found, substrings) for s in substrings: print(s) def getAllSubstrings(S, found, substrings): if (len(S) == 0): return if (S in found): return for i in range(len(S)): if(S not in found): ...
6590def971785be445552a8cf940654eb527d3c7
bornagojsic/bela
/novi_player.py
1,830
3.53125
4
def sortiraj(karta): karta = karta[:-1] if karta in "7 8 9 10".split(): return int(karta)-10 elif karta == "B": return 2 elif karta == "D": return 3 elif karta == "K": return 4 elif karta == "A": return 11 def vrijednost(karta, adut): if karta[-1] == adut: karta = karta[:-1] if karta in ["7", "8"]...
d1b6e5bd8c5e3abd986084fe335f534195b099a2
Beknazar007/PythonLearning
/snakify/04:11/Equal_numbers.py
495
4.15625
4
# Given three integers, determine how many of them are equal to each other. The program must print one of these numbers: 3 (if all are the same), 2 (if two of them are equal to each other and the third is different) or 0 (if all numbers are different). a = int(input()) b = int(input()) c = int(input()) if a > b and c...
6d68e758eee23de5364135b97a352f6dd24190eb
Beknazar007/PythonLearning
/snakify/04:11/rock.py
590
4.0625
4
# Chess rook moves horizontally or vertically. Given two different cells of the chessboard, determine whether a rook can go from the first cell to the second in one move. # The program receives the input of four numbers from 1 to 8, each specifying the column and row number, first two - for the first cell, and then the...
c95c00f8b7b1aebfbb6796acf9196591d53abee1
liyiran/Machine-learning-1
/hw1_perceptron.py
3,479
3.78125
4
from __future__ import division, print_function from typing import List, Tuple, Callable import numpy as np import scipy import matplotlib.pyplot as plt class Perceptron: def __init__(self, nb_features=2, max_iteration=10, margin=1e-4): ''' Args : nb_features : Number of featur...
fc0c55b4df01b311ddde41f981accd3978dc902c
kavinsenthil21/programs
/findstr.py
274
3.921875
4
finding string string = raw_input() substring = raw_input() answer = 0 start = 0 length = len(string) index = string.find(substring, start, length) while index<>-1: answer = answer+1 start = index+1 index = string.find(substring, start, length) print (answer)
85b19e5145eb0bcc970fea56b68c09714bcca753
kavinsenthil21/programs
/primenumlist.py
222
3.625
4
a=int(input("enter starting")) b=int(input("enter ending")) for j in range(a,b): flag=1 for i in range(2,j): if j%i==0: flag=0 if flag==1 and j>1: print("{} ".format(j))
0d9c2c7be12878a6533c5cbc05b1dc8eda35fcdd
Cynaria/daily_programmer
/name_game.py
1,032
3.6875
4
def name_game(name): name = name.replace(name[-1], "") starting_letter = name[0] ending = name.replace(name[0], "", 1) output_rhyme(name, starting_letter, ending) def output_rhyme(name, starting_letter, ending): print b_line(name, ending, starting_letter) print f_line(name, ending, starting_letter) print...
20ca100f65320d6d541360471bad566804fcf5e0
rhedshi/project-euler
/python/problems/034_problem.py
480
3.921875
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Problem 34 - Digit factorials ============================= 145 is a curious number, as 1! + 4! + 5! = 1 + 24 + 120 = 145. Find the sum of all numbers which are equal to the sum of the factorial of their digits. Note: as 1! = 1 and 2! = 2 are not sums they are not ...
7560b8cb95641f8db798275e2a17acf0c29771d3
rhedshi/project-euler
/python/problems/009_problem.py
588
4.21875
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Problem 9 - Special Pythagorean triplet ======================================= A Pythagorean triplet is a set of three natural numbers, a < b < c, for which, a^2 + b^2 = c^2 For example, 3^2 + 4^2 = 9 + 16 = 25 = 5^2. There exists exactly one Pythagorean trip...
11572ed612dbaa4b2cc269dbe28c941801de4e62
rhedshi/project-euler
/python/problems/039_problem.py
708
3.65625
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Problem 39 - Integer right triangles ==================================== If p is the perimeter of a right angle triangle with integral length sides, {a,b,c}, there are exactly three solutions for p = 120. {20,48,52}, {24,45,51}, {30,40,50} For which value of p ≤ 1...
9dda3c635358eaa1db717a23e051c740efa1cfe2
xiaopeng1995/MyFirstPythonProject
/HelloWorld.py
218
3.609375
4
p_name = input("\n\nPress input logonName:") p_pwd = input("\n\nPress input logonPwd:") if p_name == "xiaopeng" and p_pwd == "123456": print("true") print("Welcome To Python World!") else: print("er")
0cadc61298ca535d2be4144f18c5495c0fdf1e8c
v-lai/pythonFundamentals
/dictionary.py
1,564
4.5
4
# Write the following Python code to do the following (Complete ALL of the # following using dictionary comprehension) # 1. Given a list[("name", "Elie"), ("job", "Instructor")], create a dictionary # that looks like this {'job': 'Instructor', 'name': 'Elie'} (the order does not # matter). a_list = [("name", "Elie"), ...
0c6525d7e488e4d5d648848f70ff7f9b3ce7b765
kuanyingchou/learn-raspi-hw
/button.py
250
3.65625
4
import RPi.GPIO as gpio gpio.setmode(gpio.BOARD) gpio.setup(7, gpio.IN) gpio.setup(11, gpio.OUT) while True: input_value = gpio.input(7) if input_value == False: print("pressed!") gpio.output(11, True) else: gpio.output(11, False)
971a8baac7f85e128e3b24584e1e73be5b4dbd51
cjharpe28/na_utils
/mean.py
752
4.0625
4
"""" DNA to RNA converter """ def rna(seq): """will convert DNA to RNA sequence"""" #first detrimen if the sequence is upper case seq_upper = seq.isupper() #convert to lowercase seq = seq.lower() #swao out t for u seq.replace('t','u') #return upper or lower if seq_upper: re...
81db913303286b8e1999fb4d7932b68b158fdb3f
manohar45/100-days-of-python-code
/day_1/day_1.py
190
3.65625
4
print("Welcome to the band name generator") city=input("Whats name of the city you grew up in ?\n") pet=input("Whats your pet name ?\n ") print(f"your band name could be {city} {pet}" )
1c50dc9b94e93d2f1384b14984968f086e2a8d36
manohar45/100-days-of-python-code
/day_4/day_4_1.py
204
3.765625
4
#Write your code below this line 👇 #Hint: Remember to import the random module first. 🎲 import random val=random.randint(0,1) if(val==0): print("Heads") elif(val==1): print("Tails")
86353a9560f5003c093d2d42975b8a04443df6b1
OscarZunigaCordon/EjerciciosPython---Programacion-III
/No.20.py
152
4.0625
4
y = input("Ingresar Numero: ") x = int(y) fact = 1 z = 1 while z <= x: fact = fact * z z = z + 1 print(f"El numero factorial es: {fact}")
5eda49a2dad3eabd6b1fe34844ccce25d977f2da
OscarZunigaCordon/EjerciciosPython---Programacion-III
/No.5.py
131
3.75
4
numero = int(input("Dijite Primer Numero: ")) resultado = 0 for i in range(1, 11): print(f"{numero} * {i} = {numero*i}")
52f126bf7c7a26182b9584c79cc4dc1ac69175b8
HawkinYap/Leetcode
/leetcode812.py
1,102
3.546875
4
class Solution(object): def largestTriangleArea(self, points): """ :type points: List[List[int]] :rtype: float """ # area = 0 # for i in range(len(points)-2): # for k in range(i+1, len(points)-1): # for m in range(k+1, len(points)): ...
f15a730ed0bb71672e4ab5fb271fa6f8e471747c
HawkinYap/Leetcode
/jz_twelve_2.py
699
4.09375
4
# -*- coding:utf-8 -*- class Solution: def Power(self, base, exponent): # write code here if exponent == 0: return 1 if base == 0: return 0 flag = True if exponent < 0: exponent = -exponent flag = False # exponent & 1 =...
02d2e3400ec3eff14d36a0ca4fa0bea00d61d38a
HawkinYap/Leetcode
/0417-10.py
1,159
3.65625
4
class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: def Print(self, pRoot): # write code here if not pRoot: return [] stack = [pRoot] nextLayer = [] result = [] flag ...
a8be40cf14e378a01e534b43f5e11f4cc370d25a
HawkinYap/Leetcode
/leetcode13.py
621
3.5
4
class Solution: def romanToInt(self, s): """ :type s: str :rtype: int """ r_dict = {'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000} num = r_dict[s[0]] sum = 0 if len(s) == 1: print(num) else: for i in s[...
44f86420ec7bafc1ffe6980d71d79e738e10d09c
HawkinYap/Leetcode
/leetcode461.py
328
3.59375
4
class Solution(object): def hammingDistance(self, x, y): """ :type x: int :type y: int :rtype: int """ n = x ^ y n = bin(n) return(n.count('1')) if __name__ == '__main__': x = 1 y = 4 solution = Solution() print(solution.hammingDistanc...
24b594307bf496c728e3f7927009aa8860813098
HawkinYap/Leetcode
/leetcode893.py
468
3.59375
4
class Solution(object): def numSpecialEquivGroups(self, A): """ :type A: List[str] :rtype: int """ res = set() for sub in A: print(sub[::2], sub[1::2]) sub = ''.join(sorted(sub[::2]) + sorted(sub[1::2])) res.add(sub) return ...
1cc725d5a05e308379243fb20a30ea2b253d9add
HawkinYap/Leetcode
/0417-6.py
1,165
3.828125
4
# -*- coding:utf-8 -*- class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: # 返回对应节点TreeNode # def __init__(self): # self.lst = [] def sortn(self, root, s): if not root: return s else: ...
4c7e3e59f204c66b2855c7bcd9791c9c2ab3f724
HawkinYap/Leetcode
/leetcode500.py
839
3.859375
4
class Solution(object): def findWords(self, words): """ :type words: List[str] :rtype: List[str] """ # res = [] # keys = ['QWERTYUIOP', 'ASDFGHJKL', 'ZXCVBNM'] # for word in words: # for key in keys: # word_upper = word.upper() ...
a72e1d5bb21efad92db1469bded591c8f4c91860
HawkinYap/Leetcode
/lz_18th.py
675
3.9375
4
# -*- coding:utf-8 -*- class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: # 返回镜像树的根节点 def Mirror(self, root): # write code here if not root: return None if root: root.left, root.right = s...
26c451d7d7cdbcb367af3667976bd2a763e20d89
HawkinYap/Leetcode
/jz_offer01.py
292
3.609375
4
class Solution: def Find(self, target, array): for row in array: if target in row: return True return False if __name__ == "__main__": a = [[1,2,3,4],[6,7,8,9],[11,12,13,14]] num = 5 s = Solution() print(s.Find(num, a))
a5629af2269e7b57e4c2e223d276b8000065d989
HawkinYap/Leetcode
/jz_offer4.py
566
3.921875
4
# -*- coding:utf-8 -*- class Solution: def __init__(self): self.stackIn = [] self.stackOut = [] def push(self, node): # write code here self.stackIn.append(node) def pop(self): # return xx if not self.stackOut: while self.stackIn: s...
e56a7ea009bc57023582264164b2bd791c51c80c
HawkinYap/Leetcode
/jz_four.py
702
3.625
4
# -*- coding:utf-8 -*- class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: # 返回构造的TreeNode根节点 def reConstructBinaryTree(self, pre, tin): # write code here if not pre: return None root = TreeNode(pr...
f6f5468457ff4f46cc0a0a54c1eb9683354f5717
HawkinYap/Leetcode
/leetcode1047.py
412
3.859375
4
class Solution(object): def removeDuplicates(self, S): """ :type S: str :rtype: str """ ans = [] for s in S: if len(ans)>0 and ans[-1] == s: ans.pop() else: ans.append(s) return "".join(ans) if ...
06ab3d94fa7c41d831898c2ba5cfbce0f04eb6fc
HawkinYap/Leetcode
/leetcode283.py
537
3.59375
4
class Solution(object): def moveZeroes(self, nums): """ :type nums: List[int] :rtype: None Do not return anything, modify nums in-place instead. """ # z = [] # n = [] # for i in nums: # if i == 0: # z.append(i) # else: ...
2d4ee9ea5ba3d20f2bdbd93bce8839593fe132db
HawkinYap/Leetcode
/leetcode-5-2.py
885
3.640625
4
class Solution(object): def longestPalindrome(self, s): size = len(s) if size < 2: return s max_len = 1 res = s[0] for i in range(1, size - 1): palindrome_odd, odd_len = self.center_spread(s, size, i, i) palindrome_even, even_len = self...
e017c7f1b5b7548a579d0f7549115869738decae
jyleehe/CodingTest
/pgmr_word_puzzle_2.py
2,101
3.640625
4
# https://programmers.co.kr/learn/courses/18/lessons/1882 # # BFS 로 풀어보려 했는데 실패함.. # 단어가 완성됐을 때 word 사용 횟수는 카운트 가능. # 여러 단어 후보들에 대해서도 탐색하고 있음. # 문제는, 완성할 수 없는 경우를 고려하지 않고 전부 cnt 하고 있음. # 끝까지 제대로 갔는지를 확인해야 되기 때문에, DFS 로 풀어야 할거 같음. # 아니면 BFS + DFS 로 해야되나? # DFS 방법론을 다시 봐야할듯.. 일단 끝까지 갈수 있는지를 리턴하는 DFS + 현재 BFS 형태로 가봐야할듯. ...
86379a6b59e6e8c12f366d2038fb1d1e46188e03
santeixeira/numerical-methods
/methods/matrix_solver/gauss_elimination.py
1,040
3.796875
4
from matrix import * print(f'\nGauss Elimination method') for i in range(n): try: for j in range(i+1, n): fator = matrix[j][i]/matrix[i][i] for k in range(n+1): matrix[j][k] -= fator*matrix[i][k] except ZeroDivisionError: print('There is no real...
95aab20b75093ddd7a8f16781f96a42141b9ebca
KedarH-449/KH449
/tk15.py
186
3.5625
4
import sqlite3 conn=sqlite3.connect("demo2.db") with conn: cur=conn.cursor() cur.execute("INSERT INTO Doctor(Name,Qualif,Speci)values('kishor','MBBS','CSE')") print("RECORD inserted")
4fbc257be6a6b77d6c4f57f81d31cfb1b2565975
ParthivNaresh/CNN_Models_Parthiv_Naresh
/categorize_data.py
1,982
3.578125
4
# -*- coding: utf-8 -*- import os from shutil import move ''' This categorization class assumes that the data has been presented in the following format: 1 csv file with all the image ids in one column and their corresponding labels in another 2 subfolders (training and testing) that hold a series of images with thei...
91eb1dc153f4e49912e11f4f011b5010a0335378
mhiyer/shuffle_pandas_dataframe
/shuffle_pandas_dataframe.py
860
4.375
4
# -*- coding: utf-8 -*- """ Created on Sun Dec 29 16:21:14 2019 @author: mh iyer Randomly shuffle a pandas dataframe Input: pandas dataframe Output: Shuffled pandas dataframe """ import pandas as pd import random # function to shuffle pandas dataframe def shuffle_data(dataset): # ...
14785f9b38fd290f1e8ea61170f43a808d3e76bb
borislavstoychev/Soft_Uni
/soft_uni_fundamentals/Basic Syntax, Conditional Statements and Loops/EXERCISE/05_can't_sleep_count_sheep.py
160
3.703125
4
num = int(input()) sheep2 = '' sheep = '' for i in range(1, num + 1): sheep2 = 'sheep...' sheep = str(i) + ' ' + sheep2 print(sheep, end='')
6a728dc19abcb51fd32dd733b05dd889b5ab9544
borislavstoychev/Soft_Uni
/soft_uni_advanced/Tuples and Sets/lab/2_average_student_grades.py
362
3.828125
4
n = int(input()) names = {} for _ in range(n): name, grade = input().split() if name not in names: names[name] = [float(grade)] else: names[name].append(float(grade)) for key, value in names.items(): marks = ' '.join(map(lambda f: f"{f:.2f}", value)) print(f"{key} -> {marks...
5e46c27051392b8caa199da0be30b24940891874
borislavstoychev/Soft_Uni
/soft_uni_fundamentals/Text Processing/exercises/10_winning_ticket.py
758
3.625
4
line = input().split(", ") special_symbols = ["@", "#", "$", "^"] for t in line: ticket = t.strip() if len(ticket) == 20: right = ticket[10:] left = ticket[:10] for symbol in special_symbols: if symbol * 6 in right: count_left = left.count(symbol) ...
d22d7fc00fbecff0c1a2047aa504e976b6850237
borislavstoychev/Soft_Uni
/soft_uni_fundamentals/Data Types and Variables/more exercises/05_balanced_brackets.py
363
3.671875
4
number_of_lines = int(input()) left = 0 right = 0 opening = 0 for i in range(number_of_lines): string = input() if string == '(': left += 1 opening += 1 elif string == ')': right += 1 opening = 0 if opening == 2: break if left == right: print(...
663a1cb818e32b5123dc8b666442b47c21ecf99c
borislavstoychev/Soft_Uni
/soft_uni_basic/While Loop/lab/06. Max Number.py
184
3.921875
4
import sys data = input() max_num = -sys.maxsize while data != 'Stop': num = int(data) if num > max_num: max_num = num data = input() print(max_num)
fa21f5f23dd904c4136631357ddc03b17186e33a
borislavstoychev/Soft_Uni
/soft_uni_basic/Nested Loops/lab/07. Cinema Tickets (not included in final score).py
1,005
3.765625
4
comand = input() total_celled_tickets = 0 student_tickets = 0 standard_tickets = 0 kids_tickets = 0 while comand != "Finish": free_sits = int(input()) type_of_ticket = input() ticket_sold = 0 while type_of_ticket != "End": total_celled_tickets += 1 ticket_sold += 1 if...
f16e72376d1ca3fa772a2e02f77e8655deba56c5
borislavstoychev/Soft_Uni
/soft_uni_basic/Conditional Statements/advanced/more_exercise/02. Rectangle of N x N Stars.py
216
3.65625
4
n = int(input()) for i in range(n-1): print(chr(42), end='') for j in range(n-1): print(chr(42)) for k in range(n-1): print(chr(42), end='') for j in range(1): print(chr(42), end="")
0e27791795aa2d7057f3bf83b2b90f3c6dcbf9d5
borislavstoychev/Soft_Uni
/soft_uni_fundamentals/Lists Advanced/exercises/8_moving_target.py
1,142
3.796875
4
targets = list(map(int, input().split())) def shoot_target(nums, i, v): if 0 <= i < len(nums): nums[i] -= v if nums[i] <= 0: nums.pop(i) return nums def add_target(nums, i, v): if 0 <= i < len(nums): nums.insert(i, v) else: print("Invalid pl...
dbd01a9a7cc44810e65b86736306306649f0ab2f
borislavstoychev/Soft_Uni
/soft_uni_fundamentals/Basic Syntax, Conditional Statements and Loops/EXERCISE/07_Maximum_Multiple_2.py
138
3.671875
4
num_1 = int(input()) num_2 = int(input()) for num in range(num_2, 0, -1): if num % num_1 == 0: print(num) break
4bab62a009ce751855f45a2cdcf8e9673ebaceb6
borislavstoychev/Soft_Uni
/soft_uni_basic/While Loop/exercise/04. Walking.py
609
4
4
steps_needed = 10000 steps_counter = 0 steps_home = 0 while steps_counter < steps_needed: command = input() if command == 'Going home': steps_home = int(input()) steps_counter += steps_home if steps_counter < steps_needed: print(f'{steps_needed - steps_counter} mor...
3d403a348fe667593e00c29139742e5ff09d317e
borislavstoychev/Soft_Uni
/soft_uni_fundamentals/Lists Advanced/exercises/02_big_numbers_lover.py
94
3.765625
4
number = input().split() number = int("".join(sorted(number, reverse=True))) print(number)
4a1b21b27cbbbe109861b84b47063b47ff8d098b
borislavstoychev/Soft_Uni
/soft_uni_basic/Conditional Statements/advanced/more_exercise/04. Triangle of Dollars.py
188
3.890625
4
n = int(input()) for row in range(1, n): print(chr(36)) for col in range(1, row + 1): print(chr(36), end=' ') for i in range(1): print(chr(36), end=' ')
439ffc19f49ca4f1ee22f73fe5d4d32584931736
borislavstoychev/Soft_Uni
/soft_uni_fundamentals/Basic Syntax, Conditional Statements and Loops/EXERCISE/04_double_char.py
79
3.828125
4
word = input() for i in range(len(word)): print(f'{word[i] * 2}', end='')
715feec50c0971bf621775e5a2ba90b3338a6610
borislavstoychev/Soft_Uni
/soft_uni_fundamentals/Dictionaries/exercises/4_orders.py
1,030
3.609375
4
products_price = {} products_quantity = {} while True: line = input() if line == "buy": break name = line.split()[0] price = float(line.split()[1]) quantity = int(line.split()[2]) if name not in products_price: products_price[name] = price products_quantity[nam...
e144ec7883eb1e71a67bc469381b3f362b885ba1
borislavstoychev/Soft_Uni
/soft_uni_fundamentals/Dictionaries/exercises/123.py
406
3.734375
4
command = input() courses = {} while not command == "end": course, student = command.split(" : ") if course not in courses: courses[course] = [student] else: courses[course] += [student] command = input() for k, v in dict(sorted(courses.items(), key=lambda x: -len(x[1]))).item...
005015c6b6cc9017f79285cd86744da45af9df70
borislavstoychev/Soft_Uni
/soft_uni_fundamentals/Objects and Classes/lab/03_email.py
738
3.625
4
class Email: def __init__(self, sender, receiver, content): self.sender = sender self.receiver = receiver self.content = content self.is_sent = False def send(self): self.is_sent = True def get_info(self): return f'{self.sender} says to {self.rece...
c98d55f18e3bc4d977bd1b377d128e8ea94a062d
borislavstoychev/Soft_Uni
/soft_uni_OOP/Decorators/lab/example.py
274
3.578125
4
def increment_with(n): def inc(func): def increase(*args, **kwargs): return [num + n for num in func(*args, **kwargs)] return increase return inc @increment_with(5) def get_numbers(): return [1, 2, 3, 4, 5] print(get_numbers())
9bd103d4d6e220157207c2929a471351e8014f93
borislavstoychev/Soft_Uni
/soft_uni_advanced/File Handling/exercise/1_even_lines.py
330
3.53125
4
import re def replace(line): return re.sub(r"[,\.\!\?-]", "@", line) with open("text.txt", "r") as file: lines = file.readlines() for row_number in range(len(lines)): if row_number % 2 == 0: replaced = replace(lines[row_number]).split() print(" ".join(replaced...
a7fa69f8103f8ed7945cde803799ce69de444682
borislavstoychev/Soft_Uni
/soft_uni_advanced/Functions Advanced/exercise/8_even_or_odd.py
377
4.0625
4
def even_odd(*args, command=""): command = args[-1] nums = args[:-1] result = [] if command == "odd": result = [n for n in nums if not n % 2 == 0] elif command == "even": result = [n for n in nums if n % 2 == 0] return result print(even_odd(1, 2, 3, 4, 5, 6, "even"))...
d49c9890df3c989782cc0a78eb011b5415745967
borislavstoychev/Soft_Uni
/soft_uni_fundamentals/Text Processing/exercises/6_replace_repeating_chars.py
174
4.0625
4
line = input() new_str = "" new_letter = "" for letter in line: if not letter == new_letter: new_str += letter new_letter = letter print(new_str)
8b173073a5024c5b6c31d8375e0a4d4998fcbce1
borislavstoychev/Soft_Uni
/soft_uni_fundamentals/Lists Advanced/exercises/05_electron_distribution.py
348
3.78125
4
electrons = int(input()) list_el = [] for index in range(1, electrons + 1): electron = 2 * index ** 2 if electron <= electrons: electrons -= electron list_el.append(electron) else: electron = electrons list_el.append(electron) break print(list(el for el i...