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
d57b48fe6ebac8c1770886f836ef17f3cadf16c7
alma-frankenstein/Grad-school-assignments
/montyHall.py
1,697
4.125
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- #to illustrate that switching, counterintuitively, increases the odds of winning. #contestant CHOICES are automated to allow for a large number of test runs, but could be #changed to get user input import random DOORS = ['A', 'B', 'C'] CHOICES = ["stay", "switch"] de...
050b97bea9846acccb6ec7abafbab7505c6fd462
ColinSidberry/Learning-to-Code
/KS2.py
1,208
3.6875
4
import csv with open('Santee-Surrounding-Cities.csv','w',newline = '') as f: thewriter = csv.writer(f) file = input('Please enter raw.csv: ') opened = open(file) file2 = input('Please enter new.txt: ') opened2 = open(file2) s = str() old = ['san diego','santee','del mar','carlsbad','san marcos','encinitas','pen...
141011f37de069a56eb23f0aa5cf9b1c18fa6c72
JMR96/Ciclo2LP
/PalavraContraria.py
263
4.0625
4
# -*- coding: latin1 -*- def fraseInvert(frase): invert = frase.split() for i in xrange(len(invert)): invert[i] = invert[i][::-1] return ' '.join(invert) frase = 'Estou no ciclo 2 fazendo Linguagem de Programacao' print fraseInvert(frase)
b36cc808695e667d53ed0d274ee5faec1dd139ba
skluzada/school_projects
/Image Editor/image_editor/image_editor.py
8,324
3.84375
4
import numpy as np from PIL import Image MIRROR_VERTICAL = 0 MIRROR_HORIZONTAL = 1 # coefficients by which the corresponding channels are multiplied when converting image from rgb to gray TO_GRAY_COEFFICIENTS = { 'RED': 0.2989, 'GREEN': 0.5870, 'BLUE': 0.1140 } class ImageEditor: """ A class use...
31188f137dc8be0688b2a3042f04226bca65e202
mamorales10/Python-Guide-for-Beginners
/SortingAlgorithms/merge_sort.py
674
4.03125
4
def mergeSort(listToSort): if(len(listToSort) > 1): mid = len(listToSort)//2 lower = listToSort[:mid] upper = listToSort[mid:] mergeSort(lower) mergeSort(upper) i = 0 j = 0 k = 0 while(i < len(lower) and j < len(upper)): if(lower[i] < upper[j]): listToSort[k] = lower[i] i = i + 1 els...
f8096a50065547373b754f7c3c3ea43367434d88
psykid/computational-physics
/romberg.py
664
3.5
4
import math import numpy as np fun="1.0/x" lb, ub=1, 2 def f(x): return eval(fun) def T(m,k): if k==0: return T_0(m) return def T_0(m): N=2**m step=(ub-lb)*1.0/N i, summ=lb+step,0 while i<ub: summ+=f(i) i+=step summ+=0.5*(f(lb)+f(ub)) return summ*step #0.69314718055994529 def main(): #_n=int(raw...
ffdba064734aa4cb7193f7121fa5c28cd06a32cc
Shio3001/koneta
/99.py
619
3.6875
4
import random print("九九計算して") def loop(): i1 = random.randint(0, 9) i2 = random.randint(0, 9) m = random.randint(0, 2) correct = 0 if m == 0: correct = i1 * i2 print("{0} x {1}".format(i1, i2)) if m == 1: correct = i1 + i2 print("{0} + {1}".format(i1, i2)) ...
8b8644a5fbc3a44baff3a5ad1156c5a644b60f56
drod1392/IntroProgramming
/Lesson1/exercise1_Strings.py
1,026
4.53125
5
## exercise1_Strings.py - Using Strings # # In this exercise we will be working with strings # 1) We will be reading input from the console (similar to example2_ReadConsole.py) # 2) We will concatenate our input strings # 3) We will convert them to upper and lowercase strings # 4) Print just the last name from the "nam...
df9cea82395dfc4c540ffe7623a0120d2483ea9e
imyogeshgaur/important_concepts
/Python/Exercise/ex4.py
377
4.125
4
def divideNumber(a,b): try: a=int(a) b=int(b) if a > b: print(a/b) else: print(b/a) except ZeroDivisionError: print("Infinite") except ValueError: print("Please Enter an Integer to continue !!!") num1 = input('Enter first number') num2...
abcb2f242d5b48cae08848eba99bec9249cd7f98
servemoseslake/serve
/sml/sml/serve/utils.py
873
3.5
4
from datetime import datetime, date def date_from_string(value, format='%Y-%m-%d'): if type(value) == date: return value return datetime.strptime(value, format).date() def datetime_from_string(value, format='%Y-%m-%dT%H:%M'): alternate_formats = ( '%Y-%m-%dT%H:%M:%S', ) all_fo...
c9586c078a3bd35ebab6a145de6b6a0a934f501f
zmadil/Random_snippets_2019
/bubblesort.py
242
4.0625
4
list1=[5,3,7,22,5,9,1] def bubblesort(list1): for i in range(len(list1)): for j in range(i+1,len(list1)): if list1[j] < list1[i]: temp=list1[j] list1[j]=list1[i] list1[i]=temp return list1 bubblesort(list1) print(list1)
4b8332d14517a5e339ea61207ed710d8e7cd7e78
zmadil/Random_snippets_2019
/fibonacci.py
214
3.8125
4
#0,1,1,2,3,5,8,13,21 print('Please enter how many numbers you want ') user=int(input()) print('----------------------------') a=0 b=1 print(a) print(b) for i in range(2,user): c=a+b a=b b=c print(c)
0953e7600c11fb8059e602fb948107fbc801065b
makstar1/low
/pro4.py
329
3.8125
4
from random import randint as ri a = int(input( "введите длину списка: ")) b = int(input("введите максимальное значение элемента списка: ")) def listFunc (x,y): list = [] for i in range(x): list.append(ri(0,y+1)) return list print(listFunc(a,b))
e822856efebb234650fa9d22e4e233757ec01acb
liweiwei1419/Algorithms-Learning-Python
/binary-search/binary-search-4.py
549
3.890625
4
# 查找最后一个小于等于给定值的元素 def binary_search_4(nums, target): size = len(nums) # 注意,right 向左边减了 1 位,因为 target 可能比 nums[0] 还要小 left = -1 right = size - 1 while left < right: mid = left + (right - left + 1) // 2 if nums[mid] <= target: left = mid else: right = m...
8c83a11c95c69da1e3d09e44130af2457d4bf91b
liweiwei1419/Algorithms-Learning-Python
/unweighted-graph/DenseGraph.py
1,211
3.578125
4
from iterator import DenseGraphIterator class DenseGraph: def __init__(self, n, directed): assert n > 0 # 结点数 self.n = n # 边数 self.m = 0 # 是否是有向图 self.directed = directed # 图的具体数据 self.g = [[False for _ in range(n)] for _ in range(n)] de...
7a6ce3a681aeabe5b7758972546666d6be3ef641
2KNG/old_freshman
/python_source/수업/문제1.py
518
4
4
def calc(a, op, b): x = a y = b if op == "+": print("{:.2f}{}{:.2f}={:.2f}".format(a, op, b, a+b)) elif op == "-": print("{:.2f}{}{:.2f}={:.2f}".format(a, op, b, a-b)) elif op == "*": print("{:.2f}{}{:.2f}={:.2f}".format(a, op, b, a*b)) elif op == "/": print("{:.2...
f092c8017f618eb44d2c6c5a48248909b067eb68
2KNG/old_freshman
/python_source/수업/엑셀입출력.py
835
3.71875
4
import csv # in_file = open("excel_data.csv", "r") # data = csv.reader(in_file) # for i in data : # print(i) # in_file.close() # with open("aa/excel_data2.csv", "w", encoding="utf-8-sig", newline="") as out_file: # newlinee 을 안박으면 개손해 # data = csv.writer(out_file, delimiter=",") # data.writerow([i for i in...
6885e4e26929aae57d69b5db41ca2971aacbf0fd
2KNG/old_freshman
/python_source/수업/문제3.py
198
3.828125
4
def plus(f, t): # from 으로 함수를 작성할 수 없어 f, t로 변경 sum = 0 for i in range(f, t+1): sum += i return sum print(plus(1,10)) print(plus(1, 3) + plus(5, 7))
094c36fab0d52ecac6cdee01896f54c1ec414c10
2KNG/old_freshman
/python_source/딥러닝/문제 210630.py
1,320
3.5
4
import random i = random.randint(1,15) print(i) while x != i : x = int(input('줘요')) k = x if x == i : print('정답띠') elif i < 7 : if 7 < x: print("i는 7보다 작다") elif x < i < 7 : print("i는 7보다 작고 {}보다 커욤".format(x)) elif i < x < 7 : print(...
f2e6ca8c1e4b7f263d07c18e437f7b376498d4c3
jky007/py_learn
/test3-12.py
274
3.78125
4
a = 'hello,world' # hello,world b = 1.414 # 1.414 c = (1 != 2) # True d = (True and False) # False e = (True or False) # True #1 print(a,b,c,d,e) #2 print("a:%s; b:%.2f; c:%s; d:%s; e:%s" % (a,b,c,d,e)) #3 s="\'hello,world\'\n\\\"hello,world\"" print(s)
943aec037efa4704d0d1d5cc47ab6d9698376e3e
ksannedhi/kbyers-free-python-old-syllabus
/week3_part1.py
1,448
3.890625
4
'''Create an IP address converter (dotted decimal to binary). This will be similar to what we did in class2 except: A. Make the IP address a command-line argument instead of prompting the user for it. ./binary_converter.py 10.88.17.23 B. Simplify the script logic by using the flow-control statem...
a1a6050a6712698af759ca98112f3749a19023a9
MLlibfiy/python
/com/shujia/day2/demo2.py
1,013
3.859375
4
# encoding=utf-8 # 函数 def function1(): print "这是一个函数" # 带括号执行函数,不带括号引用变量 function1() function2 = function1 function2() def square(x, n): return x ** n print square(2, 3) def function3(flag): if (flag): return "数加" else: return 1 r = function3(True) print type(r) # 函数简写 lambda1...
cb13b312958e4c73d19afcbb8671dfe629683a12
MLlibfiy/python
/com/shujia/day3/demo2.py
1,231
3.84375
4
# coding=utf-8 class student(): # 对象初始化方法,在创建对象的时候调用 def __init__(self, name, age, gender="男"): self.name = name self.age = age self.gender = gender def print_info(self): print self.name, self.age, self.gender s = student("张三", 23) s.print_info() s.age = 24 # 修改属性值 s.prin...
6957556d6458a9430a4873dfa086269050c50509
ccny-mystery-machine/the-mystery-machine
/story_generator/test_methods.py
14,229
3.71875
4
""" Test file for the different methods that represent events that occur """ from math import isclose from setup import ACTORS, PLACES, ITEMS from state import State from methods import METHODS class TestMove: """ Test class for the move method """ def test_move_works_to_different_location(self): ...
65b40c0bea865e5272618ea3eeba524a0a893ae4
ccny-mystery-machine/the-mystery-machine
/old_work/mcts-approach-2/story.py
1,807
3.5625
4
from methods import * def multiply_ba(newaction_b, story_b): story_b = story_b * newaction_b class Story: """ Story - A path along the tree """ def __init__(self, state): """ Shallow Copy Here """ self.current_state = state self.state_list = [] s...
9be9b482fcf8ceabf355f4c14a020cb1a97fcd9a
ccny-mystery-machine/the-mystery-machine
/story_generator/goals.py
1,121
3.5
4
""" Defining the different goals we are checking for """ from functools import partial def possible(node): return node.believability > 0 def death_occurred(num_deaths, node): """ description: checks if num_deaths deaths occurred returns a boolean indicating so or not """ num_dead = 0 for...
9d1f3be653ceba110b14aef60f8e5038f45bc655
Zhangxq-1/ACCENT-repository
/adversarial examples generation/gnn/replace_and_camelSplit.py
2,514
3.5
4
import re def replace_a_to_b(code,var_a,var_b): str_list=code.split(' ') var_old=var_a var_new=var_b new_str_list=[] for item in str_list: if item == var_old: new_str_list.append(var_new) else: new_str_list.append(item) return new_str_list def replace_...
df3b2547c23c1b3e87874eff18fdc418f430b84b
DenisZaychikov/progi_mk
/task_decor.py
271
3.5
4
from time import time def timer(func): def wrapped(x): new_time = time() func(x) new_time1 = time() return new_time1 - new_time return wrapped @timer def square(x): return x * x print(square(2))
1ecde6b6fbd464e4d86aad5aefcdd551db5ca74c
akshitha111/CSPP-1-assignments
/module 6/p3/digit_product.py
529
3.875
4
""" digit product """ def main(): ''' Read any number from the input, store it in variable int_input. ''' s_inp = int(input()) product = 1 temp = 0 if s_inp < 0: temp = 1 s_inp = -s_inp if s_inp == 0: product = 0 while s_inp != 0: rem = s_inp%10 ...
2d95e7c4a3ff636c2ec5ff400e43d273bc479f48
akshitha111/CSPP-1-assignments
/module 22/assignment5/frequency_graph.py
829
4.40625
4
''' Write a function to print a dictionary with the keys in sorted order along with the frequency of each word. Display the frequency values using “#” as a text based graph ''' def frequency_graph(dictionary): if dictionary == {'lorem': 2, 'ipsum': 2, 'porem': 2}: for key in sorted(dictionary): ...
493e9637244833ca96833182a3ca424beafdd2b7
akshitha111/CSPP-1-assignments
/module 11/p2/assignment2.py
525
3.6875
4
"""Exercise: Assignment-2""" def update_hand(hand_1, word_1): """assign 2""" hand_new = dict(hand_1) for i in word_1: if i in hand_1.keys(): hand_new[i] = hand_new[i] - 1 return hand_new def main(): """assignment 2""" n_1 = input() adict_1 = {} for i in range(int(n_1)...
a8a12197c34c3b053e93b0a8b85027c179370621
jorgealzate/Python_Learning_Book1_
/cap10_Tuplas.py
4,151
4.21875
4
#TUPLAS #las tuplas son inmutables #son parecidas a las listas #pueden ser valores de cualquier tipo #las tuplas son comparables y dispersables (hashables) se pueden ordenar #se pueden usar como valores para las claves en los diccionarios """ t = 'a', 'b', 'c', 'd','e' #es opcional encerrar en parentesis print(t) prin...
ada8a65e4d645deecea02d0772f1476d6f795532
edgeowner/Python-Basic
/codes/9_2_remove_high_and_low.py
450
4.09375
4
numlist = list() while True: inp = input('Enter a number: ') if inp == 'done': break value = float(inp) numlist.append(value) # average = (sum(numlist) - max(numlist) - min(numlist)) / (len(numlist) - 2) # numlist.remove(max(numlist)) # numlist.remove(min(numlist)) # average = sum(numlist)...
a5c6578d3af315b00a5f2c2278d8f3ab1ef969a0
edgeowner/Python-Basic
/codes/3_2_simple_calculator.py
679
4.34375
4
error = False try: num1 = float(input("the first number: ")) except: print("Please input a number") error = True try: num2 = float(input("the second number: ")) except: print("Please input a number") error = True op = input("the operator(+ - * / **):") if error: print("Something Wrong") e...
e51964055f7eea8dc2c8a3d38601dd48aacf7bc1
edgeowner/Python-Basic
/codes/2_exercise_invest.py
211
4.1875
4
money = float(input("How much money")) month = float(input("How many months")) rate = float(input("How much rate")) rate = rate / 100 total = money * (1 + rate) ** month interest = total - money print(interest)
1c3be5bb2fe2c136d0049c80763f79382a345e9e
nf313743/books
/intro_to_algorithms/sorting/merge_sort.py
855
4.0625
4
def merge(left_arr, right_arr, main_arr): left_length = len(left_arr) right_length = len(right_arr) i = 0 j = 0 k = 0 while i < left_length and j < right_length: if left_arr[i] <= right_arr[j]: main_arr[k] = left_arr[i] i += 1 else: main_arr[k]...
7e9c706937ea46bec742b6567805411ba2e874a0
nf313743/books
/intro_to_algorithms/sorting/selection_sort.py
440
3.828125
4
def selection_sort(arr): i = 0 j = 0 while i < len(arr) -1: min_element = i j= i + 1 while j < len(arr): if arr[j] < arr[min_element]: min_element = j j += 1 temp = arr[i] arr[i] = arr[min_element] arr[min_element]...
4a9a97c64fb7a6b52873f5feb49fec459f2b781f
sebvega/pythoninit
/listas.py
895
4
4
lista_combinada=['hola',0,12.2,True,'bienvenido', 'hola'] print(lista_combinada) nueva_lista=[[1,2,3,],[4,5,6],[7,8,9]] print(nueva_lista[1][1]) #comando append agrega lo que sea en una lista nueva_lista.append(lista_combinada) print(nueva_lista) # insert agrega elementos en un listado en la N posicion los que se de...
8537bd3c15a50aa514047459e4008b4fbd774ca5
sebvega/pythoninit
/POO/persona2.py
1,024
3.78125
4
class Usuario: #constructor def __init__(self): self.__nombre='ana' self.__edad=23 #geter and seter def getNombre(self): return self.__nombre def getEdad(self): return self.__edad def setNombre(self, nombre): if nombre== 'ana': self.__n...
a64339130139faedb9b5b79dcbf37ef225689c8c
mirfanmcs/Machine-Learning
/Supervised Learning/Classification/Regularized Logistic Regression/Python/mapFeature.py
745
3.859375
4
import numpy as np def mapFeature(X1, X2): # MAPFEATURE Feature mapping function to polynomial features # MAPFEATURE(X1, X2) maps the two input features # to quadratic features. # # Returns a new feature array with more features, comprising of # X1, X2, X1.^2, X2.^2, X1*X2, X1*X2.^2, e...
1ca24df076f7c2052ded98326bf379336684ba96
mirfanmcs/Machine-Learning
/Supervised Learning/Linear Regression/Regularized Linear Regression and Bias-vs-Variance/Python/validationCurve.py
1,957
3.609375
4
import numpy as np import trainLinearReg as train import linearRegCostFunction as cost import matplotlib.pyplot as plot import learningPolynomialRegression as lpr import loadData as data # %VALIDATIONCURVE Generate the train and validation errors needed to # %plot a validation curve that we can use to select lambda # ...
4ee296650e110658fcb4fac434ff4cadf330e23c
mirfanmcs/Machine-Learning
/Supervised Learning/Linear Regression/Linear Regression with Multiple Variable/Python/normalEqn.py
823
3.96875
4
import numpy as np import loadData as data def calculateNormalEqn(X, y): #NORMALEQN Computes the closed-form solution to linear regression # NORMALEQN(X,y) computes the closed-form solution to linear # regression using the normal equations. #Calculate minimum of theta using Normal Equation. This i...
aa02c84edc8466c7c861a5c90b25b48bce60a974
mirfanmcs/Machine-Learning
/Supervised Learning/Classification/Logistic Regression/Python/plotDecisionBoundary.py
1,015
3.625
4
import plotData as pd import matplotlib.pyplot as plot import numpy as np import loadData as data import optimizeTheta as optTheta def plotDecisionBoundary(p,theta, X): # Plotting the decision boundary: two points, draw a line between # Decision boundary occurs when h = 0, or when # theta0 + theta1*x1 + t...
2765099cda0cb2f269964d92667e4327964ebc9d
paliwalery/PaliiValeriia
/python132083/lecture05_examples/hw5.py
3,600
3.96875
4
#Дан список любых целых чисел. Исключить из него максимальный элемент/минимальный элемент. import random # создаем список случаных 10 элементов num = [random.randint(0, 100) for _ in range(10)] print(num) a = min(num) # a= max(num) for i in range(len(num)): if num[i] == a: num[i] = [] numbers = [elem for ...
987b49fbd4fca75b6afaf8ddad6fb8988ea2ba23
AyberkMunis/WeeklyScheduleAlgorithm
/Classes.py
6,995
4
4
import _sqlite3 from random import * def tuppletolist(tupple): #This custom function converts a tupple to a list liste2=[] for t in tupple: for item in t: liste2.append(item) return liste2 days=['1','2','3','4','5'] #A single number represents a day of a week. Ex:1 is Monday ...
1a231067463d9eb5b408309d27ccaf797e58b360
ramin-karimian/programming_2019_iust
/codes/t02.py
501
3.953125
4
a=float(input("add a ra vared kon:")) b=float(input("add b ra vared kon:")) c=float(input("add c ra vared kon:")) if a<b+c and b<a+c and c<a+b : print("mosalas mitavan sakht") else: print("nemitavan sakht") # # Also this implementation in correct : # a=float(input("add a ra vared kon:")) # b=float(input("add b...
9d53d31acb3bb364e8be1a49a6a322ca16c7dcc8
ekohilas/comp3821
/ass_2/q8.py
205
3.609375
4
from random import shuffle from sys import argv def numbers(n): l = [x for x in range(n*2+1)] shuffle(l) print(*sorted(l[:len(l)//2])) print(*sorted(l[len(l)//2:])) numbers(int(argv[1]))
f0995f652df181115268c78bbb649a6560108f47
ciciswann/interview-cake
/big_o.py
658
4.25
4
''' this function runs in constant time O(1) - The input could be 1 or 1000 but it will only require one step ''' def print_first_item(items): print(items[0]) ''' this function runs in linear time O(n) where n is the number of items in the list if it prints 10 items, it has to run 10 times. If it prints 1,000 it...
495aeb1b054bc1047143abb1ed1560f4c10017dd
amirtl/genetic-algorithm-2
/N-Queens.py
5,691
3.734375
4
#solving TSP using genetic algorithm import random #generates a random number between 1 and the number of cities minus 1. def Rand_City(size): return random.randint(0, size-1) #checks if a city was seen before of not. def Is_New(Gene, city): for c in Gene: if c == city: return False ...
77047e19385045ca862c1e7860664ba0ba35183e
lambda-projects-ak/data-structures-sprint
/names/names.py
1,100
3.6875
4
import time from binary_search_tree import BinarySearchTree start_time = time.time() f = open('names_1.txt', 'r') names_1 = f.read().split("\n") # List containing 10000 names f.close() f = open('names_2.txt', 'r') names_2 = f.read().split("\n") # List containing 10000 names f.close() # binary search tree solutio...
29a21b7d3b694268ebc6362f1dc4bb044c2b3883
luispaulojr/cursoPython
/semana_01/aula01/parte02_condicionais.py
309
4.1875
4
""" Estrutura de decisão if, elseif(elif) e else """ # estrutura composta idade = 18 if idade < 18: print('Menor de idade') elif idade == 18: print('Tem 18 anos') elif idade < 90: print('Maior de 18 anos') else: print('Já morreu') # switch case # https://www.python.org/dev/peps/pep-0634/
28773cc4eaa5297aae60a2dc1acc20eb2c05bf21
luispaulojr/cursoPython
/semana_01/exercicios/exercicio_12.py
227
3.6875
4
distancia = float(input( 'Informe a distância em milhas para ser convertida em quilometros: ').replace(',', '.')) print( f'A conversão da distancia {distancia} em milhas para quilometros é: {(distancia * 1.61)} km')
a39d746b7b7b615e54c0266aba519956a96c492c
luispaulojr/cursoPython
/semana_02/aula/tupla.py
871
4.40625
4
""" Tuplas são imutáveis arrays - listas são mutáveis [] utilizado para declaração de lista () utilizado para declaração de tupla """ """ # declaração de uma tupla utilizando parenteses """ tupla1 = (1, 2, 3, 4, 5, 6) print(tupla1) """ # declaração de uma tupla não utilizando parenteses """ tupla2 = 1...
9f09ea8be016ddd8d651fdf91381e826abb9788d
luispaulojr/cursoPython
/semana_01/exercicios/exercicio_19.py
221
3.78125
4
volume = float(input( 'Informe o volume em litros para ser convertido em metros cubicos (m³): ').replace(',', '.')) print( f'A conversão do volume {volume} litros para metros cubicos é: {(volume / 1000)}m³')
ca10ff118b97f6e0b3f5fd6bd62dbebea98b230a
zongxinwu92/leetcode
/CombinationSumIii.py
473
3.6875
4
''' Created on 1.12.2017 @author: Jesse '''''' Find all possible combinations of k numbers that add up to a number n, given that only numbers from 1 to 9 can be used and each combination should be a unique set of numbers. Example 1: Input: k = 3, n = 7 Output: [[1,2,4]] Example 2: Input: k = ...
5ea3f9bd83548d755afa8c5ab0a4c940b41fab68
zongxinwu92/leetcode
/ValidateBinarySearchTree.py
578
3.59375
4
''' Created on 1.12.2017 @author: Jesse '''''' Given a binary tree, determine if it is a valid binary search tree (BST). Assume a BST is defined as follows: The left subtree of a node contains only nodes with keys less than the node s key. The right subtree of a node contains only nodes with keys greater ...
1bb6b866223412e18ffe84f85031b02342cde01a
zongxinwu92/leetcode
/FindAllDuplicatesInAnArray.py
352
3.609375
4
''' Created on 1.12.2017 @author: Jesse '''''' Given an array of integers, 1 &le; a[i] &le; n (n = size of array), some elements appear twice and others appear once. Find all the elements that appear twice in this array. Could you do it without extra space and in O(n) runtime? Example: Input: [4,3,2,7,8,2...
acf4f0a175a94b5018db65165371936c07522515
zongxinwu92/leetcode
/BurstBalloons.py
978
3.796875
4
''' Created on 1.12.2017 @author: Jesse '''''' Given n balloons, indexed from 0 to n-1. Each balloon is painted with a number on it represented by array nums. You are asked to burst all the balloons. If the you burst balloon i you will get nums[left] * nums[i] * nums[right] coins. Here left ...
f2b92a220d6de5472fe1e3cbfbd1e375f3212397
zongxinwu92/leetcode
/FindTheDifference.py
382
3.765625
4
''' Created on 1.12.2017 @author: Jesse '''''' Given two strings s and t which consist of only lowercase letters. String t is generated by random shuffling string s and then add one more letter at a random position. Find the letter that was added in t. Example: Input: s = "abcd" t = "abcde" Output: ...
f6e831f5b6d40a09a10f174f4ee1f6211ff56ebb
zongxinwu92/leetcode
/AddStrings.py
410
3.703125
4
''' Created on 1.12.2017 @author: Jesse '''''' Given two non-negative integers num1 and num2 represented as string, return the sum of num1 and num2. Note: The length of both num1 and num2 is < 5100. Both num1 and num2 contains only digits 0-9. Both num1 and num2 does not contain any leading zero. You must not...
6d519be24d58b2bef610f2fd28248a7724eeb5fb
zongxinwu92/leetcode
/UniqueSubstringsInWraparoundString.py
975
3.828125
4
''' Created on 1.12.2017 @author: Jesse '''''' Consider the string s to be the infinite wraparound string of "abcdefghijklmnopqrstuvwxyz", so s will look like this: "...zabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcd....". Now we have another string p. Your job is to find out how many unique non-empty sub...
b9c060c072cbe48f0762f2d07fe5d28ed1f6b6e3
zongxinwu92/leetcode
/FractionToRecurringDecimal.py
839
3.515625
4
''' Created on 1.12.2017 @author: Jesse '''''' Given two integers representing the numerator and denominator of a fraction, return the fraction in string format. If the fractional part is repeating, enclose the repeating part in parentheses. For example, Given numerator = 1, denominator = 2, return "0.5". Gi...
d0249ae72e0a0590cffda71a48c5df0993d1ee18
zongxinwu92/leetcode
/CountTheRepetitions.py
788
4.125
4
''' Created on 1.12.2017 @author: Jesse '''''' Define S = [s,n] as the string S which consists of n connected strings s. For example, ["abc", 3] ="abcabcabc". On the other hand, we define that string s1 can be obtained from string s2 if we can remove some characters from s2 such that it becomes s1. For example, “abc...
b6516ea8f501f2041d8ca93640ee566bd5551b2c
zongxinwu92/leetcode
/AddDigits.py
701
3.65625
4
''' Created on 1.12.2017 @author: Jesse '''''' Given a non-negative integer num, repeatedly add all its digits until the result has only one digit. For example: Given num = 38, the process is like: 3 + 8 = 11, 1 + 1 = 2. Since 2 has only one digit, return it. Follow up: Could you do it without any...
56e51b84f4c740eeed8f8882968e7f12f06c98f6
zongxinwu92/leetcode
/PartitionList.py
358
3.5625
4
''' Created on 1.12.2017 @author: Jesse '''''' Given a linked list and a value x, partition it such that all nodes less than x come before nodes greater than or equal to x. You should preserve the original relative order of the nodes in each of the two partitions. For example, Given 1->4->3->2->5->2 and x =...
4f52b64412a86577dd635a47ff9c589a1e4f98d3
jamalshah5111996/Py-Assignment-3
/Assignment#3.py
2,795
3.875
4
#!/usr/bin/env python # coding: utf-8 # In[9]: #TASK1: print("\nTASK1:\n"); Poem= "Twinkle, twinkle, little star,\n\t How I wonder what you are! \n\t\t Up above the world so high,\n\t\t Like a diamond in the sky.\nTwinkle, twinkle, little star,\n\t How I wonder what you are!\n" print(Poem); #TASK2: print("\nTASK2:\n...
096ea5546286513cd271082345a9522c9426dfab
bhawanabhatt538/numpy
/numpy_exercise.py
1,576
4
4
import pandas as pd import numpy as np # Create an array of 10 zeros print('array of 10 zeros=',np.zeros(10)) print('array of 10 ones=',np.ones(10)) #Create an array of 10 fives print('an array of 10 fives=',np.ones(10)*5) print('array of the integers from 10 to 50=',np.arange(10,51)) print('array of all the even in...