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
07999243a551f3948b311e36ed14d6c5129076d9
v0rs4/project_euler_solutions
/python/p004_1.py
212
3.609375
4
def isPalindrome(n): return str(n) == str(n)[::-1] def solve(): return max(x * y for x in range(100, 1000) for y in range(100, 1000) if isPalindrome(x * y)) if __name__ == "__main__": print(solve())
6230fd200e52ea05cb0fc8bb59b14621431607ac
06Prakash/python-training-codes
/iterablesCommon.py
705
4.03125
4
import itertools def sprint(x): ''' Special Print :param x: Any iterable or not will be printed ''' for c in x : try : for v in c : print (v, end=" " ) except : print(c) print("") if __name__ == "__main__" : list1...
143f8ea31c7f3a3255098a375f1b2a2f853902f0
Andross78/Kaizer
/min_max.py
8,361
3.546875
4
def minmax_1(array): if not array: return (None,None) n = len(array) min_int = array[0] for i in range(1,n): next_int = array[i] if min_int > next_int: min_int = next_int max_int = array[0] for i in range(1,n): next_int = array[i] if max_int < ...
2e38b50b436eb0352955cbc69f589bd43f5c25c0
toxa1711/helper
/Input_Audio.py
510
3.515625
4
import speech_recognition as sr def input_audio(): r = sr.Recognizer(language="ru") with sr.Microphone() as source: # use the default microphone as the audio source audio = r.listen(source) # listen for the first phrase and extract it into audio data try: ...
6e3314329a350e7b716b6332fddc713fc464482b
vengadam2001/iot
/hello.py
151
3.890625
4
l = int(input("enter a number")) def oe(n=1): if (n % 2 == 0): return "even" else: return "odd" print(f"{l} is a ", oe(l))
8b0e52b691e3fe832804bbe32847eb97577b1b6b
jguarni/Python-Labs-Project
/Lab 2/testme1.py
82
3.65625
4
def divide_by_5(number): hello = (number/5) print(hello) divide_by_5(3)
2dd5c760bf9cf7b41a808cae47a621981dbb9997
jguarni/Python-Labs-Project
/Lab 6/testclass.py
1,186
4.0625
4
from cisc106 import * class Employee: """ An employee is a person who works for a company. position -- string salary -- integer """ def __init__(self,position,salary,age): self.position = position self.salary = salary self.age = age """ def employee_functio...
075463a7832a8638a6cb22fad6258a401432b9e3
jguarni/Python-Labs-Project
/Lab 4/lab4.py
5,585
4.28125
4
# Lab 4 # CISC 106 6/24/13 # Joe Guarni from cisc106 import * from random import * #Problem 1 def rand(num): """ This function will first set a range from 0 to an input parameter, then prompt the user to guess a number in that range. It will then notify the user weather their input was correct, too ...
bd7938eb01d3dc51b4c5a29b68d9f4518163cc92
jguarni/Python-Labs-Project
/Lab 5/prob2test.py
721
4.125
4
from cisc106 import * def tuple_avg_rec(aList,index): """ This function will take a list of non-empty tuples with integers as elements and return a list with the averages of the elements in each tuple using recursion. aList - List of Numbers return - List with Floating Numbers """ ...
e63dc201a8e29e4227ff4ce0871c3e50377b529e
yveslym/Herd_Immunity_Project
/person.py
3,259
3.703125
4
import random # TODO: Import the virus clase import uuid from randomUser import Create_user import pdb ''' Person objects will populate the simulation. _____Attributes______: _id: Int. A unique ID assigned to each person. is_vaccinated: Bool. Determines whether the person object is vaccinated agai...
bc189bd3a9ffce0d504d932c4a0ff4a2199323a4
donw385/DS-Unit-3-Sprint-2-SQL-and-Databases
/demo_data.py
833
3.984375
4
import sqlite3 conn = sqlite3.connect('demo_data.sqlite3') curs = conn.cursor() curs.execute( """ CREATE TABLE demo ( s str, x int, y int ); """ ) conn.commit() curs.execute( """ INSERT INTO demo VALUES ('g',3,9), ('v',5,7), ('f',8,7); """) conn.commit() # Count how many rows you ...
3e561974952579ce8c2a42e263927912f9e87a53
Sakshi-16-01/CBAP_13DEC
/03PythonBasics.py
4,693
4.03125
4
#Topic : Basic Programming #Numbers: Integers and floats work as you would expect from other languages: x = 3 print(x) print(type(x)) # Prints "3" print(x + 1) # Addition; prints "4" print(x - 1) # Subtraction; prints "2" print(x * 2) # Multiplication; prints "6" print(x ** 2) # Exponentiation; prin...
ef1d6ca5aa113b72984f55a10ddd9cf0561e190f
CHINAJR/Sort
/GenerateRandomArray.py
238
3.546875
4
import random def GenerateRandomArray(size,maxnum): n = [] size = random.randint(1,size) for i in range(size): n.append(random.randint(1,maxnum)) print(n) if __name__ == '__main__': for i in range(10): GenerateRandomArray(5,10)
8656ff504d98876c89ead36e7dd4cc73c3d2249e
jlopezmx/community-resources
/careercup.com/exercises/04-Detect-Strings-Are-Anagrams.py
2,923
4.21875
4
# Jaziel Lopez <juan.jaziel@gmail.com> # Software Developer # http://jlopez.mx words = {'left': "secured", 'right': "rescued"} def anagram(left="", right=""): """ Compare left and right strings Determine if strings are anagram :param left: :param right: :return: """ # anagram: left ...
035899efa2286718b1862f03d39cd36936a2283b
Giioke/SacredTexts_Scraper
/Web_Scrapper.py
1,271
3.703125
4
#Web Scraper for SacredTexts.com # Source - https://www.youtube.com/watch?v=7SWVXPYZLJM&t=397s import requests from bs4 import BeautifulSoup url = "http://www.sacred-texts.com/index.htm" resp = requests.get(url) #Ability to read the HTML in python soup = BeautifulSoup(resp.text, 'lxml') WebCode = soup.prettify() prin...
71e6ac073a1488d1f9ce4abdc86aad30fcd67e25
HannibalCJH/Leetcode-Practice
/002. Add Two Numbers/Python: Recursive Solution.py
921
3.734375
4
# Definition for singly-linked list. # class ListNode(object): # def __init__(self, x): # self.val = x # self.next = None class Solution(object): def addTwoNumbers(self, l1, l2): """ :type l1: ListNode :type l2: ListNode :rtype: ListNode """ def a...
95243651c271a0289c9879e90f86b29f0534cf10
camilooob/pythonisfun
/errores.py
246
3.890625
4
paises = { "colombia": 49, "mexico": 244, "argentina": 20 } while True: country = str(input("Ingrese el pais:")).lower() try: print("El pais {} tiene {}".format(country, paises[country])) except KeyError: print("No tenemos ese dato")
a0ee55e5165643eac48e2701eb0d4690b177df38
camilooob/pythonisfun
/.history/discounted_20191130165043.py
1,100
3.890625
4
def main(): # # Inputs price = 500 # # Process DISCOUNT30 = 0.3 DISCOUNT20 = 0.2 DISCOUNT10 = 0.1 DISCOUNT5 = 0.05 DISCOUNT0 = 0 DISCOUNTO = 0 NEWPRICE = 0 if PRICE >= 300: DESCUENTO = PRICE * DISCOUNT30 NEWPRICE = PRICE - DESCUENTO print("discount= "...
8861ee4af0e8b701eeda7d304a4d2293f67f8132
Pejoicen/CalcRtlCodeLineNumber
/检测有效代码行数.py
5,293
3.796875
4
#open file #read one line contex,judge if code or comment # if '--' in the head this line is comment # if doesn’t has code this line is empty # else this line is code line filename = input('''要求文件编码格式为UTF-8 .vhd文件,支持识别 -- 注释,以及空行 .v 文件,支持识别 // 注释, /**/ 注释,以及空行 输入文件路径(包含文件名和扩展名):''') # open file #f...
f70c55e08d97b515181b42d4f80798bbf7118e0a
hadrizia/coding
/hackerrank-challenges/Warm-up Challenges/Counting Valleys.py
387
3.515625
4
# Complete the countingValleys function below. ''' Time efficienty: O(n) ''' def countingValleys(n, s): count = 0 if n > 1: alt = 0 for step in s: if step == 'U': alt += 1 if alt == 0: count += 1 else: alt -= 1 return count n = 8 s = ["U", "D", "D", "D", "...
5e824e80b1fc165be33154f8d1c69028f5814e3c
hadrizia/coding
/code/advanced_algorithms_problems/list_2/resort.py
1,415
3.78125
4
''' Valera is afraid of getting lost on the resort. So he wants you to come up with a path he would walk along. The path must consist of objects v1, v2, ..., vk (k ≥ 1) and meet the following conditions: Objects with numbers v1, v2, ..., vk - 1 are mountains and the object with number vk is the hotel. For any in...
df3d3df41e0297e35e83104db05f588db460cc8b
hadrizia/coding
/hackerrank-challenges/Dictionaries and Hashmaps/Hash Tables: Ransom Note.py
1,044
3.921875
4
def addWordsToDict(arr): availableDict = {} for word in arr: if word not in availableDict: availableDict[word] = 1 else: availableDict[word] = availableDict[word] + 1 return availableDict ''' Given that o = number of different words in note array Time efficiency: O(m + n + o) '...
392277285a7b7a96b240f6fe2967ea8382bdc168
hadrizia/coding
/code/data_structures/linkedlist/singly_linkedlist.py
3,222
4.0625
4
from code.data_structures.linkedlist.node import Node class LinkedList(object): def __init__(self, head = None): self.head = head def insert(self, data): new_node = Node(data) node = self.head if self.size() == 0: self.head = new_node else: while node.next: node = no...
d4f790b54e2279548c4c00fa1fff63bfc578e2df
hadrizia/coding
/code/cracking-the-coding-interview/cap_1_strings_and_arrays/1.7.rotate-matrix.py
1,309
3.625
4
''' Given a matrix NxN, Time efficiency: O((N / 2) * N) = O(N^2) Memory efficiency: O(1) ''' def rotateMatrix(matrix): n = len(matrix) if n == 0: return False layers = n / 2 for layer in xrange(layers): offset_begin = layer offset_end = n - 1 - layer for i in xrange(offset_begin, offset...
f0ae1b82091f7d4a57ae39e8c2786ca7528db526
hadrizia/coding
/code/data_structures/queue/queue.py
571
4.0625
4
from code.data_structures.linkedlist.node import Node class Queue(object): def __init__(self, head = None, tail = None): self.head = head self.tail = tail def enqueue(self, value): node = Node(value) if self.is_empty(): self.head = node self.tail = node else: n = self.head ...
fbb84944da05457e470013b116dc9bca78423a14
hadrizia/coding
/code/advanced_algorithms_problems/list_2/laser_sculpture.py
1,421
3.8125
4
''' Input The input contains several test cases. Each test case is composed by two lines. The first line of a test case contains two integers A and C, separated by a blank space, indicating, respectively, the height (1 ≤ A ≤ 104) and the length (1 ≤ C ≤ 104) of the block to be sculpted, in milimeters. The second li...
cd9996229b3da37855c54db0bbfd8d404c2c0479
hadrizia/coding
/code/cracking-the-coding-interview/cap_3_stacks_and_queues/3.3.stack_of_plates.py
1,949
3.75
4
from code.data_structures.stack.stack import Stack from code.data_structures.linkedlist.node import Node class SetOfStacks(object): def __init__(self, stacks = [], capacity_of_stacks = 0): self.stacks = stacks self.capacity_of_stacks = capacity_of_stacks def is_empty(self): return len(self.stacks) =...
f3974732df9e9a3124cdffb22f7664f3e35892c1
hadrizia/coding
/code/data_structures/heap/heap.py
881
3.90625
4
class Heap(object): def __init__(self, heap=[]): self.heap = heap def heapify(self, i, n): biggest = i left = i * 2 + 1 right = i * 2 + 2 if left < n and self.heap[left] > self.heap[i]: biggest = left if right < n and self.heap[right] > self.heap[biggest]: biggest = ri...
32235f471cbf55cbe6a643306112c62f66dd756e
hadrizia/coding
/code/advanced_algorithms_problems/list_2/where_are_my_keys.py
1,210
3.890625
4
''' Input The first line contains two integers Q(1 ≤ Q ≤ 1*103) and E(1 ≤ E ≤ Q) representing respectively the number of offices that he was in the last week and the number of offices that he was in the last two days. The second line contains E integers Si (1 ≤ Si ≤ 1000) containing the Identification number of ...
4df464f1545fa3165344654a596eeedf5d78444d
hadrizia/coding
/code/cracking-the-coding-interview/cap_1_strings_and_arrays/1.6.string-compression.py
647
3.875
4
''' Given that: N = len(string), Time efficiency: O(n) Memory efficiency: O(n) ''' def stringCompression(string): occurrences = 0 compressedString = '' for i in range(len(string)): occurrences += 1 if (i + 1 >= len(string)) or string[i] != string[i + 1]: compressedString += string[i] + str...
2bbb704056da71a4f0e76263de4cf58ff9522979
hadrizia/coding
/code/cracking-the-coding-interview/cap_2_linked_lists/2.1.remove_dups.py
757
3.578125
4
from code.data_structures.linkedlist.singly_linkedlist import LinkedList ''' Given that N = linked_list.size(), Time efficiency: O(N) ''' def removeDups(linked_list): node = linked_list.head buffer = [] buffer.append(node) while node: if node.data not in buffer: buffer.append(node.data) else...
9dfd3b48523e12e4bafac6630a48024e03c3bff8
czarny25/pythonStudy
/PythonFundamentals/testingFolder/testnumpy.py
270
3.859375
4
''' Created on 14 Apr 2020 @author: Marty ''' import numpy as np # numpy is external library and need to be imported # simple list list = [1,2,3,4,5,6,7] # variable of numpy array type take list as argument x = np.array(list) print(type(x)) print(x)
723b4825326e39a7c363ea10bab1c4c634945e7a
Flipez/snippets
/python/list_dir.py
784
3.8125
4
#!/usr/bin/env python import os, sys, sqlite3 def get_dirs(dir): path = dir dir_list = os.listdir( path ) return( dir_list ) print("This will list the dirs and save them to a sqlite database") print("Please enter a valid path") dir_list = get_dirs(input()) if os.path.exists("db.db"): print("[db]datab...
846cc6cd0915328b64f83d50883167e0d0910f6a
Teju-28/321810304018-Python-assignment-4
/321810304018-Python assignment 4.py
1,839
4.46875
4
#!/usr/bin/env python # coding: utf-8 # ## 1.Write a python function to find max of three numbers. # In[5]: def max(): a=int(input("Enter num1:")) b=int(input("Enter num2:")) c=int(input("Enter num3:")) if a==b==c: print("All are equal.No maximum number") elif (a>b and a>c): prin...
f65750847bc5cd37f7e53a50469f2db9498f84b4
Ivan395/Python
/rfc.py
961
3.859375
4
#! /usr/bin/python3 # -*- coding: utf-8 -*- import curp def letters(ap): letras = [chr(x) for x in range(65, 91)] + [chr(x) for x in range(97, 123)] numbers = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'] if(len(ap) == 13): if(ap[0] in letras and ap[1] in letras and ap[2] in letras and ap[3] i...
adb2991ea7cc9e8c3a2c35d1698dee8949e84497
NereBM/Python-Pandas
/Working with datasets.py
4,483
4.1875
4
import pandas as pd ########--------------------5:Concatenating and Appending dataframes------------ df1 = pd.DataFrame({'HPI':[80,85,88,85], 'Int_rate':[2, 3, 2, 2], 'US_GDP_Thousands':[50, 55, 65, 55]}, index = [2001, 2002, 2003, 2004]) df2 = pd.DataFrame(...
a843bf881c50bb3f0dda17c4da2dca48d410fce4
Jorgelsl/batchroja
/listas.py
416
3.984375
4
list1 = [2,3,1,4,5] list2 = ["A","B","C","D"] list3 = ["MATEMATICAS", "HISTORIA", 1999, 1992] list4 = [list1, list2, list3] ''' print(list1) print(list2) print(list3) print(list4) for i in list3: print(i) ''' frutas = ['naranja', 'manzana', 'pera', 'fresa', 'banana', 'manzana', 'kiwi'] print(frutas) frutas.append(...
186d9dcc93bb4b20c9f79a3460f00b2e2e0f0728
sanjaylokula/100dayspython
/days/month/day8_23.py
890
3.984375
4
#Given an array of numbers nums, in which exactly two elements appear only once and all the other elements appear exactly twice. Find the two elements that appear only once. #Example: #Input: [1,2,1,3,2,5] #Output: [3,5] #Note: #The order of the result is not important. So in the above example, [5, 3] is also corre...
b973afe64648468eb6bb9e8a83b8cfdba2e4c8b9
CBASoftwareDevolopment2020/Exam-Notes
/Algorithms/Implementations/sorting.py
3,607
3.53125
4
from time import time from random import choice, randint, shuffle def selection_sort(arr, timeout=60): n = len(arr) if 0 <= n <= 1: return start = time() for i in range(n - 1): min_idx = i for j in range(i + 1, n): if arr[j] < arr[min_idx]: min_idx =...
22b5a162408555fa5aea974ebafc6dbd56ea8f18
BercziSandor/pythonCourse_2020_09
/DataTransfer/json_1.py
1,153
4.21875
4
# https://www.w3schools.com/python/python_json.asp # https://www.youtube.com/watch?v=9N6a-VLBa2I Python Tutorial: Working with JSON Data using the json Module (Corey Schaefer) # https://lornajane.net/posts/2013/pretty-printing-json-with-pythons-json-tool # http://jsoneditoronline.org/ JSON online editor ###########...
efca8c666dfa01890679fb36817da3abc2a8c586
BercziSandor/pythonCourse_2020_09
/Lecture_11/mix_11.py
350
3.953125
4
# Else ág ciklusoknál: akkor megy rá a vezérlés, ha nem volt break for i in range(5): print(i) else: print('végigment a for ciklus') for i in range(5): print(i) if i == 3: break else: print('no break') # Üres ciklusnál is működik: for i in range(5,0): print(i) else: print('végigm...
0fd245e6318b5016856b46828f1e397779bf3da6
BercziSandor/pythonCourse_2020_09
/Lecture_3/break_continue_1.py
365
3.9375
4
# Kilépés while és for ciklusból: break utasítás lst = [1, 2, 3, 4, 5, 6] for e in lst: if e > 2: break print(e) # 10 # 20 # while ciklusban ugyanígy működik. lst = [1, 2, 3, 4, 5, 6] # Ciklus folytatása: for e in lst: if e % 3 == 0: continue ...
62b18cc42a6e7a4bbca94ed532807160b5e56cdc
BercziSandor/pythonCourse_2020_09
/Num_py/numpy_8.py
2,047
4.09375
4
# Fancy indexing # Egyes szerzőknél a boolean indexelés (maszkolás) is ezen címszó alá tartozik. # Én csak az integer listával való indexelést hívom így. # http://scipy-lectures.org/intro/numpy/array_object.html#fancy-indexing # https://medium.com/better-programming/numpy-illustrated-the-visual-guide-to-numpy-3b1d4976...
bbd8632e442e9f7ab0812a7a1942e157ecdfc26b
BercziSandor/pythonCourse_2020_09
/Lecture_2/tippmix_2.py
1,719
3.703125
4
# Mi lesz a kimenet? Lehet hibajelzés is. # NE futtassuk le, mielőtt tippelnénk! # Órán a szabályok: # Amikor valaki úgy gondolja, hogy van ötlete a megoldásra, akkor bemondja, hogy: VAN TIPP! # Amikor azt mondom, hogy "Kérem a tippeket" és valaki egy kicsit még gondolkodni szeretne, akkor bemondja, hogy: IDŐT KÉREK! ...
e26bfd8720509b619de1ce671ea3ca273f606b9a
BercziSandor/pythonCourse_2020_09
/Lecture_8/solutions_7.py
2,668
3.515625
4
# Lecture_7\exercises_7.py megoldásai # 1.) # A dict-té alakítás felesleges, ráadásul 3.7-es verzió előtt hibás is lehet az eredmény, # mert a dict-ből kiolvasásnál nincs definiálva a sorrend. names_reversed = [ e[0] for e in sorted(employees, key=lambda x: x[0], reverse=True)] print(names_reversed) # ["Zach","James...
3d72b228e7f5806f8d20bd160fe166ad496f39bc
BercziSandor/pythonCourse_2020_09
/Lecture_13/exercises_13.py
772
3.78125
4
# 1.) # Lecture_12\exercises_12.py 3. feladathoz térünk vissza, módosítjuk egy kicsit. # Írjunk generátor-függvénnyel megvalósított iterátort, amely inicializáláskor egy # iterálható obkektumot és egy egész számot kap paraméterként. Azokat az elemeket # adja vissza a számmal elosztva a bemeneti objektum által szolgál...
f81b9e4fdf5b0d1dc28194beb061bd140d6996b9
BercziSandor/pythonCourse_2020_09
/Functions/scope_2.py
2,977
4.21875
4
# Változók hatásköre 2. # Egymásba ágyazott, belső függvények # global kontra nonlocal # https://realpython.com/inner-functions-what-are-they-good-for/ # Függvényen belül is lehet definiálni függvényt. Ezt sok hasznos dologra fogjuk tudni használni. # Első előny: információrejtés. Ha a belső függvény csak segé...
e7fa14ad1683f757c0af7cb0b591d2e67a9b53df
BercziSandor/pythonCourse_2020_09
/Datastructures/index_2.py
2,457
3.921875
4
# Értékadás slicing segítségével. lst = [10, 20, 30, 40, 50] # Az 1, 2, 3 indexű elemeket le akarjuk cserélni erre: [-2, -3, -4] lst[1:4] = [-2, -3, -4] print(lst) # [10, -2, -3, -4, 50] ####################################### # Ha slicing segítségével végzünk értékadást, akkor az új elemnek egy iterálható # soroz...
fdda3d6a9e9284bf7f2a2379a7a328554c423bbc
BercziSandor/pythonCourse_2020_09
/Datastructures/list_1.py
3,101
4.34375
4
# https://www.python-course.eu/python3_sequential_data_types.php # Listák 1. # append() metódus, for ciklus # elem törlése: del() és lista törlése # memóriacím lekérdezése: id() x = [10, 20, 30] print(x, type(x), len(x)) # [10, 20, 30] <class 'list'> 3 # A hosszat ugyanúgy a len() függvénnyel kérdezzük le, mint a s...
e23b48fd83d62d7cd6c99b18dcb614edcfa61713
BercziSandor/pythonCourse_2020_09
/Num_py/numpy_1.py
6,404
4.1875
4
# numpy tömbök bemutatása # shape, ndim, dtype, slicing # https://www.w3schools.com/python/numpy_intro.asp # https://www.w3schools.com/python/numpy_array_slicing.asp # https://medium.com/better-programming/numpy-illustrated-the-visual-guide-to-numpy-3b1d4976de1d # http://jalammar.github.io/visual-numpy/ # https://stac...
f4b554f911103a63fd1ef840f986af810967c43a
UmaRathore/Regular_Expressions
/Password_Validation.py
863
3.890625
4
# email and password validation import re email_pattern = re.compile(r"(^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$)") while True: email_id = input('Enter email address : ') email_id_object = email_pattern.search(email_id) if email_id_object is None: print('Enter correct email address : ') ...
3fd7d0c449585ee03b8a378486025cf49bf098ac
KarolGOli/Praticas_em_Python
/exercicio_4.py
2,318
3.9375
4
from operator import itemgetter lista = [] cont = 0 int(cont) def cadastro_produto(produto_para_cadastrar: dict): # função que adiciona o objeto produto à lista lista.append(produto_para_cadastrar) # o método append faz com que o produto seja adicionado na lista return while cont >= 0: ...
612686443d9cda5b6aa2766a6a90cc997610abf2
vivek28111992/DailyCoding
/problem_#56_11042019.py
1,952
4.09375
4
""" Good morning! Here's your coding interview problem for today. This problem was asked by Google. Given an undirected graph represented as an adjacency matrix and an integer k, write a function to determine whether each vertex in the graph can be colored such that no two adjacent vertices share the same color using...
39f3c7125d985d4a7d5c494884e16ed2fc27c844
vivek28111992/DailyCoding
/problem_#98.py
2,258
4.0625
4
""" Given a 2D board of characters and a word, find if the word exists in the grid. The word can be constructed from letters of sequentially adjacent cell, where "adjacent" cells are those horizontally or vertically neighboring. The same letter cell may not be used more than once. For example, given the following boa...
c9087ee72e96521122ccb48f9995ab7a8e9e1d39
vivek28111992/DailyCoding
/problem_#26_13032019.py
1,507
3.921875
4
""" Good morning! Here's your coding interview problem for today. This problem was asked by Google. Given a singly linked list and an integer k, remove the kth last element from the list. k is guaranteed to be smaller than the length of the list. The list is very long, so making more than one pass is prohibitively e...
404bdfdf31e4aa00015b74c58ff37c103f84df8f
vivek28111992/DailyCoding
/problem_#48_03042019.py
2,435
3.921875
4
""" Good morning! Here's your coding interview problem for today. This problem was asked by Google. Given pre-order and in-order traversals of a binary tree, write a function to reconstruct the tree. For example, given the following preorder traversal: [a, b, d, e, c, f, g] And the following inorder traversal: [d...
a9169a0606ef75c17087acce0c610bb5aa8e1660
vivek28111992/DailyCoding
/problem_#99.py
624
4.1875
4
""" Given an unsorted array of integers, find the length of the longest consecutive elements sequence. For example, given [100, 4, 200, 1, 3, 2], the longest consecutive element sequence is [1, 2, 3, 4]. Return its length: 4. Your algorithm should run in O(n) complexity. """ def largestElem(arr): s = set(arr) ...
f96e8a52c38e140ecf3863d1ea138e15b78c7aa8
vivek28111992/DailyCoding
/problem_#28_15032019.py
1,687
4.125
4
""" Good morning! Here's your coding interview problem for today. This problem was asked by Palantir. Write an algorithm to justify text. Given a sequence of words and an integer line length k, return a list of strings which represents each line, fully justified. More specifically, you should have as many words as p...
03dc0512b0e47789f95ea5628c4f84f5cfad6b16
vivek28111992/DailyCoding
/#825.py
135
3.9375
4
# [-9, -2, 0, 2, 3] def square(arr): sq_arr = [i * i for i in arr] sq_arr.sort() return sq_arr print(square([-9, -2, 0, 2, 3]))
370ff8761ac2230627a5b2d37ec47c0141c1339b
vivek28111992/DailyCoding
/problem_#62_17042019.py
1,060
3.96875
4
""" Good morning! Here's your coding interview problem for today. This problem was asked by Facebook. There is an N by M matrix of zeroes. Given N and M, write a function to count the number of ways of starting at the top-left corner and getting to the bottom-right corner. You can only move right or down. For exampl...
b19cc3a733b21cb61cf7aaf717e316809ee00220
vivek28111992/DailyCoding
/problem_#70.py
619
3.96875
4
""" A number is considered perfect if its digits sum up to exactly 10. Given a positive integer n, return the n-th perfect number """ def findNthPerfect(n): count = 0 curr = 19 while True: # Find sum of digits in current no. sum = 0 x = curr while x > 0: sum += ...
dc0a57534f9f646355c49d9714ebdbfc14ab5adf
vivek28111992/DailyCoding
/problem_#21_08032019.py
1,236
3.765625
4
""" Good morning! Here's your coding interview problem for today. This problem was asked by Snapchat. Given an array of time intervals (start, end) for classroom lectures (possibly overlapping), find the minimum number of rooms required. For example, given [(30, 75), (0, 50), (60, 150)], you should return 2. https:...
cbb259086c41bdc29d9569b3c4cecebfc355bad9
vivek28111992/DailyCoding
/problem_#101.py
1,336
4.03125
4
""" Given an even number (greater than 2), return two prime numbers whose sum will be equal to the given number. A solution will always exist. See Goldbach’s conjecture. Example: Input: 4 Output: 2 + 2 = 4 If there are more than one solution possible, return the lexicographically smaller solution. If [a, b] is one ...
f6a83bb9d12fae8b81bd522dfec9fcb93952e5a9
vivek28111992/DailyCoding
/problem_#93.py
1,887
4
4
""" Given a tree, find the largest tree/subtree that is a BST. Given a tree, return the size of the largest tree/subtree that is a BST. """ INT_MIN = -2147483648 INT_MAX = 2147483647 # Helper function that allocates a new # node with the given data and None left # and right pointers. class newNode: # Constructo...
4277764dd9fe0ae8877436cd014f4b52e900dfa9
vivek28111992/DailyCoding
/problem_#14_01032019.py
846
3.984375
4
""" Good morning! Here's your coding interview problem for today. This problem was asked by Google. The area of a circle is defined as πr^2. Estimate π to 3 decimal places using a Monte Carlo method. Hint: The basic equation of a circle is x2 + y2 = r2. https://www.geeksforgeeks.org/estimating-value-pi-using-monte-...
140a539e327bd9608796fb12d68d343b4f1a18a8
acneuromancer/problem_solving_python
/graphs_2/word_ladder.py
1,313
3.53125
4
from collections import defaultdict from collections import deque from itertools import product # import os def build_graph(words): buckets = defaultdict(list) graph = defaultdict(set) for word in words: for i in range(len(word)): bucket = '{}_{}'.format(word[:i], word[i+1:]) ...
8a07b97ab69c6716d99564830d3625a9fa9ca17c
acneuromancer/problem_solving_python
/trees/binary_tree/bin_tree_parser.py
3,545
3.984375
4
class BinaryTree: def __init__(self, root): self.key = root self.left_child = None self.right_child = None def insert_left(self, new_node): if self.left_child == None: self.left_child = BinaryTree(new_node) else: t = BinaryTree(new_node) ...
e23bb077affd2781fd36113b03fe55755ae16b9f
acneuromancer/problem_solving_python
/basic_data_structures/queue/queue_test.py
200
3.890625
4
from Queue import Queue q = Queue() q.enqueue('hello') q.enqueue('dog') q.enqueue(3) print("Size of the queue is %d." % q.size()) while not q.is_empty(): print(q.dequeue(), end = " ") print()
9914dde414bc7ad3df7543e58d0e478ecef3b013
acneuromancer/problem_solving_python
/python_basics/list_comprehension.py
621
3.9375
4
def practice_1(): sq_list = [x * x for x in range(1, 11)] print(sq_list) sq_list = [x * x for x in range(1, 11) if x % 2 != 0] print(sq_list) ch_list = [ch.upper() for ch in "Hello World!" if ch not in 'aeiou'] print(ch_list) def method_1(): word_list = ['cat', 'dog', 'rabbit'] lette...
bf7c8573149487a85dbcb6e971ccee8afc0b5e76
acneuromancer/problem_solving_python
/recursion/reverse_string.py
346
3.96875
4
def reverse_str(str): if len(str) == 1: return str[0] last = len(str) - 1 return str[last] + reverse_str(str[0:last]) def reverse_str_2(str): if str == "": return str return reverse_str_2(str[1:]) + str[0] print(reverse_str_2("Hello World!")) print(reverse_str_2("abcdefgh")) pr...
152e728c543b491be4f8b0135ace70778fc6734a
runt1m33rr0r/python_homeworks
/homework_2/F87134_L3_T2.py
668
3.671875
4
import sys import string input = sys.argv[1:] text = input[0].strip().upper().translate(string.maketrans('', ''), string.punctuation) key = input[1].strip().upper().translate(string.maketrans('', ''), string.punctuation) # extend the key initial_len = len(key) current_letter = 0; while len(key) < len(text): key +...
7e9b02feb9177e628d4774559beb4104a0c240de
runt1m33rr0r/python_homeworks
/homework_1/F87134_L2_T1.py
164
3.78125
4
import sys input = sys.argv[1:] for i in range(len(input) - 1): if input[i] > input[i + 1]: print("unsorted") break else: print("sorted")
91d0c13f973959afb4d736ea75bed6043e5d0fec
Brucehanyf/python_tutorial
/base/param.py
888
4.03125
4
# 参数相关语法 def param (param="123456"): print("123123") # 函数的收集参数和分配参数用法(‘*’ 和 ‘**’) # arg传递的是实参, kvargs传递的是带key值的参数 # 函数参数带*的话,将会收集非关键字的参数到一个元组中; # 函数参数带**的话,将会收集关键字参数到一个字典中; # 参数arg、*args、必须位于**kwargs之前 # 指定参数不会分配和收集参数 def param_check(*args,value = 'param', **kvargs): print(value) print(args) print("ar...
f2ddc408fe7ca9f5fc5da16dcdca4a83fbce9c54
Brucehanyf/python_tutorial
/base/day01.py
1,041
3.78125
4
### 字符串相关语法 print('hello,world') message = "hello,message" print(message) message = "hello world" print(message) # 变量名不能以数字开头, 中间不能包含空格,其中可以包含下划线 # 字符串字母首字母大写 字符串大写 字符串小写 name = "hello bruce" print(name.title()) print(name.upper()) print(name.lower()) # 合并字符串 first_name = "Bruce" last_name = "Han" full_name = first...
9ab9305ebf7869b1b9576730ec40163260cd0e12
Brucehanyf/python_tutorial
/api/a_zip.py
672
3.890625
4
# zip函数 # zip() 函数用于将可迭代的对象作为参数, # 将对象中对应的元素打包成一个个元组,然后返回由这些元组组成的对象, # 这样做的好处是节约了不少的内存。 a = [1,2,3] b = [4,5,6] c = [4,5,6,7,9] zipped = zip(c,a) # print(list(zipped)) # 之后取出最小集配对 # 解压 # a1, a2 = zip(*zip(a,b)) a1, a2 = zip(*zipped) print(a1) print(a2) from itertools import groupby # 测试无用变量 y_list = [v for _, v in y]...
c80b26a41d86ec4f2f702aab0922b86eec368e84
Brucehanyf/python_tutorial
/file_and_exception/file_reader.py
917
4.15625
4
# 读取圆周率 # 读取整个文件 # with open('pi_digits.txt') as file_object: # contents = file_object.read() # print(contents) # file_path = 'pi_digits.txt'; # \f要转义 # 按行读取 file_path = "D:\PycharmProjects\practise\\file_and_exception\pi_digits.txt"; # with open(file_path) as file_object: # for line in file_object: # ...
7642b6f57230a3f436cb3bec38286f227b7df9a2
moscowjh/fullstack-nanodegree-vm
/vagrant/tournament/tester.py
2,436
3.671875
4
from tournament import * def test(): """Test various functions of tournament project Most particularly, playerStandings may be tested along with BYE insertion and deletion prior to match results. Also allows clearing of players and/or matches, and registration of players. """ print "" prin...
7bef62a6cee86d61bc1bd5323e7d8c47bbc7f8ae
ardus-uk/anagrams
/anagram2.py
573
3.78125
4
#!/usr/bin/python3 def unique(listx): listy=[] for x in listx: if x not in listy: listy.append(x) return listy with open('./wordsEn.txt') as f: lines = f.readlines() # lines is a list of words word = 'refined' letters = list(word) # letters is a list of the letters unique_letters = unique(letters) n = ...
6669d87b8795e1d8b062f2b25ca4eeea00ecc79f
thekevinsmith/project_euler_python
/9/special_pythagorean_triplet.py
1,238
4.0625
4
# Problem 9 : Statement : 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 triplet for which a + b + c = 1000. # Find the product abc. # Some math and...
62bd9b81b6ace8f9bab84fb293710c50ca0bcf29
thekevinsmith/project_euler_python
/4/largest_palindrome_product.py
1,778
4.125
4
# Problem 4 : Statement: # A palindromic number reads the same both ways. The largest palindrome # made from the product of two 2-digit numbers is 9009 = 91 × 99. # Find the largest palindrome made from the product of two 3-digit numbers. def main(): largest = 0 for i in range(0, 1000, 1): count = 0 ...
c32d0f7b44749e6ae0ecec14ed2a2002e9b8bb7b
rootme254/Python-Projects
/shop.py
3,154
4.21875
4
''' This is a shopping list like ile inatumiwa in jumia the online shopping Create a class called ShoppingCart. Create a constructor that has no arguments and sets the total attribute to zero, and initializes an empty dict attribute named items. Create a method add_item that requires item_name, quantity and pri...
e604fb50261893929a57a9377d7e7b0e11a9b851
georgeyjm/Sorting-Tests
/sort.py
2,686
4.34375
4
def someSort(array): '''Time Complexity: O(n^2)''' length = len(array) comparisons, accesses = 0,0 for i in range(length): for j in range(i+1,length): comparisons += 1 if array[i] > array[j]: accesses += 1 array[i], array[j] = array[j], arr...
c444e7a76a76479c82d08818bcdb38b51cfe073e
4dasha45/COM411
/basics/data_visuialisation/function/ascii_code.py
238
4.09375
4
print("program started") print("Please enter a standard character:") word=input() if (len(word)==1): print("th ascii code for {}is {}".format(word,ord(word))) else: print("A single character was expected") print("end the program")
4f4431799d2dc9cf46e296cf132e3f77bdeffc3d
asiskc/python_assignment_jan5
/student.py
1,030
3.875
4
class CheckError(): def __init__(self,roll): if(roll>24): raise NameError() dict = { 1: "student1", 2: "student2" } choice = 1 while (choice==1): try: choice = int(input("choose an option")) if (choice == 1): roll = int(input("roll no:")) name...
7c314615e75b8f7f02f68c040f50f854bcb8e1cb
jilljenn/tryalgo
/tryalgo/knapsack.py
3,210
3.984375
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """\ Knapsack jill-jênn vie et christoph dürr - 2015-2019 """ # snip{ def knapsack(p, v, cmax): """Knapsack problem: select maximum value set of items if total size not more than capacity :param p: table with size of items :param v: table with value of ...
5f5e2d3f7bf5b6e1553e8c10d331d5d4143346af
jilljenn/tryalgo
/tryalgo/gauss_jordan.py
2,290
3.8125
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """\ Linear equation system Ax=b by Gauss-Jordan jill-jenn vie et christoph durr - 2014-2018 """ __all__ = ["gauss_jordan", "GJ_ZERO_SOLUTIONS", "GJ_SINGLE_SOLUTION", "GJ_SEVERAL_SOLUTIONS"] # snip{ # pylint: disable=chained-comparison def is_zero(x): ...
1204ef8366837b66f591ff142e663df7302c87b5
jilljenn/tryalgo
/tryalgo/graph01.py
1,275
3.625
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """\ Shortest path in a 0,1 weighted graph jill-jenn vie et christoph durr - 2014-2018 """ from collections import deque # snip{ def dist01(graph, weight, source=0, target=None): """Shortest path in a 0,1 weighted graph :param graph: directed graph in listlist...
322e307335af2bdf4474d2f78117c867668243ef
jilljenn/tryalgo
/tryalgo/levenshtein.py
817
3.515625
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """\ Levenshtein edit distance jill-jenn vie et christoph durr - 2014-2018 """ # snip{ def levenshtein(x, y): """Levenshtein edit distance :param x: :param y: strings :returns: distance :complexity: `O(|x|*|y|)` """ n = len(x) m = len(y)...
eea13b5f1c5f7a88cbba2d5a56e5101de59a96dd
jilljenn/tryalgo
/tryalgo/dijkstra.py
2,886
3.5625
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """\ Shortest paths by Dijkstra jill-jênn vie et christoph dürr - 2015-2018 """ # pylint: disable=wrong-import-position from heapq import heappop, heappush from tryalgo.our_heap import OurHeap # snip{ def dijkstra(graph, weight, source=0, target=None): """single s...
1f90271814c98307cdfb0dc1111f011c619498ba
eliaskousk/example-code-2e
/24-class-metaprog/setattr/example_from_leo.py
340
3.71875
4
#!/usr/bin/env python3 class Foo: @property def bar(self): return self._bar @bar.setter def bar(self, value): self._bar = value def __setattr__(self, name, value): print(f'setting {name!r} to {value!r}') super().__setattr__(name, value) o = Foo() o.bar = 8 print(o...
a82eb08a4de5bab1c90099a414eda670219aeb95
eliaskousk/example-code-2e
/21-async/mojifinder/charindex.py
2,445
4.15625
4
#!/usr/bin/env python """ Class ``InvertedIndex`` builds an inverted index mapping each word to the set of Unicode characters which contain that word in their names. Optional arguments to the constructor are ``first`` and ``last+1`` character codes to index, to make testing easier. In the examples below, only the ASC...
a04924cd0fc7da072413c4062f8a2a1258f58e32
eliaskousk/example-code-2e
/05-data-classes/dataclass/coordinates.py
512
3.5625
4
""" ``Coordinate``: simple class decorated with ``dataclass`` and a custom ``__str__``:: >>> moscow = Coordinate(55.756, 37.617) >>> print(moscow) 55.8°N, 37.6°E """ # tag::COORDINATE[] from dataclasses import dataclass @dataclass(frozen=True) class Coordinate: lat: float lon: float def __...
f23ba5514189ed232eeaaf3cd6a4ea8fb799864e
eliaskousk/example-code-2e
/20-executors/getflags/slow_server.py
3,986
3.515625
4
#!/usr/bin/env python3 """Slow HTTP server class. This module implements a ThreadingHTTPServer using a custom SimpleHTTPRequestHandler subclass that introduces delays to all GET responses, and optionally returns errors to a fraction of the requests if given the --error_rate command-line argument. """ import contextl...
d2977b7a63a6f0bebe59544ccaf8fc1763570d1c
eliaskousk/example-code-2e
/05-data-classes/typing_namedtuple/coordinates.py
487
3.765625
4
""" ``Coordinate``: a simple ``NamedTuple`` subclass with a custom ``__str__``:: >>> moscow = Coordinate(55.756, 37.617) >>> print(moscow) 55.8°N, 37.6°E """ # tag::COORDINATE[] from typing import NamedTuple class Coordinate(NamedTuple): lat: float lon: float def __str__(self): ns =...
06b96c803dcc6f53a2db59b8ba48e68c47e4df33
anqi117/py-study
/namecard-func.py
2,341
3.703125
4
card_infor = [] def print_menu(): print("="*50) print(" 名片系统 v1.0") print("1. add a new card") print("2. delete a card") print("3. update a card") print("4. search a card") print("5. show all of cards") print("6. exit") print("="*50) def add_new_card_info(): new_name = input("name: ") new_qq = input("qq: "...
50dc5fc8bf4ec94682c5d984b9e57cb46b35fc28
hcmMichaelTu/python
/lesson08/sqrt_cal2.py
793
3.859375
4
import math def Newton_sqrt(x): y = x for i in range(100): y = y/2 + x/(2*y) return y def cal_sqrt(method, method_name): print(f"Tính căn bằng phương pháp {method_name}:") print(f"a) Căn của 0.0196 là {method(0.0196):.9f}") print(f"b) Căn của 1.21 là {method(1.21):.9f}") ...
dd7145fa02abd11c3490fa783f40f8b696c8261e
hcmMichaelTu/python
/lesson12/turtle_draw.py
336
3.78125
4
import turtle as t t.shape("turtle") d = 20 actions = {"L": 180, "R": 0, "U": 90, "D": 270} while ins := input("Nhập chuỗi lệnh cho con rùa (L, R, U, D): "): for act in ins: if act in actions: t.setheading(actions[act]) else: continue t.forward(d) print("...
01b471090a34326b7c1c1a898ec5a25a9dbb0164
hcmMichaelTu/python
/lesson04/string_format.py
165
3.640625
4
import math r = float(input("Nhập bán kính: ")) c = 2 * math.pi * r s = math.pi * r**2 print("Chu vi là: %.2f" % c) print("Diện tích là: %.2f" % s)
87b04bf978a40493536c104be127f2ff83c55f74
hcmMichaelTu/python
/lesson18/Sierpinski_carpet.py
684
3.71875
4
import pygame def Sierpinski(x0, y0, w, level): if level == stop_level: return for i in range(3): for j in range(3): if i == 1 and j == 1: pygame.draw.rect(screen, WHITE, (x0 + w//3, y0 + w//3, w//3, w//3)) else: Sierpinski(x0 ...
71fb5ab35539839f8d8810bbd26003f5ba605ee2
hcmMichaelTu/python
/lesson12/turtle_escape.py
328
3.828125
4
import turtle as t import random t.shape("turtle") d = 20 actions = {"L": 180, "R": 0, "U": 90, "D": 270} while (abs(t.xcor()) < t.window_width()/2 and abs(t.ycor()) < t.window_height()/2): direction = random.choice("LRUD") t.setheading(actions[direction]) t.forward(d) print("Congratulati...