blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
22c6d3a818769a9b51fee5bbfde6476608777b78 | shadydealer/Python-101 | /Solutions/week02/sum_numbers_in_string.py | 267 | 4.21875 | 4 | def sum_of_numbers(string):
number = "0"
sum = 0
for char in string:
if char >= '0' and char <= '9':
number+=char
elif len(number) > 0:
sum += int(number)
number = "0"
sum += int(number)
return sum
string = input()
print(sum_of_numbers(string)) |
43d30be740e379db309263a7f60904bb50fb240e | shadydealer/Python-101 | /Solutions/week01/prime_fact.py | 628 | 4.21875 | 4 | from math import sqrt
def prime_factorization(number):
prime_facts = []
#since 2 is the only even prime,
#we can skill other even numbers
#in the next iteration of we divide by 2 beforehand.
if number > 1:
counter = 0
if (number % 2) == 0:
while (number % 2) == 0:
counter +=1
number //=2
... |
97a415cb25c7d54294183762fe70aab7a3bb5287 | shadydealer/Python-101 | /Solutions/week10/VehicleManager/src/queries/inserter.py | 836 | 4.34375 | 4 | import sqlite3
from queries.sqlite3_handler import execute_and_commit
"""
A class that is used to insert values into a table by given database.
"""
class Inserter:
def __init__(self,*,dbName):
self.dbName = dbName
"""
Inserts a row with given values into the passed in table.
"""
... |
2f4d09340057692656273bd7d37451bd4d123794 | qione/pre-education | /quiz/algorithm_quiz3.py | 707 | 3.90625 | 4 | '''
3.
앞뒤로 이웃한 숫자를 비교하여 크기가 큰 숫자가 작은숫자보다 앞에 있을
경우 서로 위치를 바꿔 가며 정렬하는 것을 버블정렬이라고 합니다.
주어진 리스트를 버블정렬함수(bubble_sort)를 생성하여 오름차순으로 정렬하시오.
'''
# <입력>
ls=[4,3,2,1,8,7,5,10,11,16,21,6] # 12개
def bubble_sort(ls):
for i in range(len(ls) - 1, 0, -1): # range(11,0,-1), 역순
for j in range(0, i): # i : 11~0
... |
1740d0dae220df09e31fceff16acedc4269e7d8f | skrskr66/python | /2020-1-20/dictionary.py | 424 | 3.671875 | 4 | scores = {'骆昊':95,'白元芳':78,'狄仁杰':82}
print(scores)
#
# items1 = dict(one = 1,two = 2,three = 3,four = 4)
# items2 = dict(zip(['a','b','c'],'123'))
# items3 = {num:num ** 2 for num in range(1,10)}
# print(items1,items2,items3)
# print(scores['骆昊'])
#
# for key in scores:
# print(f'{key} : {scores[key... |
80a0823ba5f70cfbe470fe9fbc735b6650125c10 | skrskr66/python | /2020-1-20/Student.py | 1,634 | 4.3125 | 4 | class Student(object):
def __init__(self,name,age):
self.name = name
self.age = age
def study(self,course_name):
print('%s正在学习%s。' % (self.name,course_name))
def watch_movie(self):
if self.age < 18:
print('%s只能看熊出没哦' % self.name)
else:
... |
7ca5fc1c89d8cf9d75ad605b9aa2fba179e6b9ce | RiswanBasha/iQube_Task | /import_from_csv.py | 2,396 | 3.984375 | 4 | '''
This task deals with recieving a mail from the defined user when the current date matches with the given CSV file's date
and Body of the mail will be the attachments of the particular date.
'''
#importing some modeules for this particular task
import sqlite3,csv
import os
import smtplib
import imghdr
from datetime... |
4daf668ea81f9d5ca62dd427bc1d87b39dd726ff | Spiritual-Programmer/Python-Course | /functions.py | 393 | 3.65625 | 4 | #Writing functions
#must use def for function use
def say_hi():
print("hello user")
say_hi()
#including parameters in functions
#Parameter is additional piece of information
def say_hello(name):
print("Hello " + name)
say_hello("Mike")
say_hello("Singh")
def say_hello2(name, age):
print("Hello "... |
cae93941ad6fe635b3d55a8b1c6a57e26cc84cfa | Spiritual-Programmer/Python-Course | /exponent_function.py | 273 | 4.25 | 4 | #exponent function
# create a function that does this (2**3)
def raise_to_power(base_num, pow_num):
result = 1
for index in range(pow_num):
result = result * base_num
return result
input(raise_to_power(int(input()),int(input())))
|
0f3b50e6a9200c0399c65ba68bee248c7b45b6ef | Spiritual-Programmer/Python-Course | /other examples/practice.py | 472 | 4.125 | 4 | print("Hello, this is the first line")
name = 'Kamaljot Singh'
#Practice putting varableis in strings
print("My name is {}" .format(name))
lang = "python"
feel = "awesome"
#practice usign two variables or more in strings
print("I am learning {} and I feel {}".format(lang, feel))
#Another way of outputting variables... |
ade2028f888c361aee03001fc66f3e99cf0ffa0d | Noba1anc3/Company-Articles-PDF-SemSeg | /semseg/text/tools.py | 527 | 3.515625 | 4 |
def overlap(lineA, lineB):
lengthA = lineA[1] - lineA[0]
lengthB = lineB[1] - lineB[0]
if lineA[1] <= lineB[0]:
return 0
if lineA[0] >= lineB[1]:
return 0
if lineA[0] <= lineB[0] and lineB[1] <= lineA[1]:
return 1
if lineB[0] <= lineA[0] and lineA[1] <= lineB[1]:
... |
c3353b6b2e1c39f1b1b943596f7a7e95320a47a0 | sophiecwebster/spelling-bee | /spelling-bee-scorer.py | 2,690 | 4 | 4 | # read in file of words (can be in a column separated by linebreaks)
samplefile = open("./sample-words.txt", "r+")
# at this point, they're in a string
L = samplefile.read()
# remove linebreaks and replace with a classic comma and space
M = L.replace("\n", ", ")
# make them into a list, delineated by comma and space
... |
870a689310ce664fee7d1e8201a86a28a27e9426 | fieryjoy/pybitset | /test.py | 820 | 3.546875 | 4 | from bitset import *
import sys
def print_list(lst):
n = len(lst)
for j in range(n):
print lst[j],
if j != n-1:
sys.stdout.write(', ')
def merge(a, b):
i = j = 0
merged = []
while i < len(a) and j < len(b):
if a[i].lower(b[j]):
merged.append(a[i]); i+=1
elif b[j].lower(a[i]):
merged.append(b[j]... |
ac4065c06c5b81ac5879c1f355e8982375697a59 | marinella2012/python_tasks_ibs | /task6.py | 943 | 3.921875 | 4 | # Есть класс Animal c одним методом voice().
# class Animal:
# def voice(self):
# pass
# 1. Создать от него три класса наследника и для каждого сделать свою
# реализацию метода voice().
# 2. Создать по одному экземпляру всех наследников и вызвать для каждого
# переопределенный метод voice().
class Animal():
def __i... |
ac570b462d1d6523f7e02aac9015fa69371f4e0e | Gootle/Python | /HOMEWORK/ENG DICT.py | 1,759 | 4.125 | 4 | MyDict = {
'apple': ['red fruit','蘋果'],
'orange': ['orange fruit','橘子'],
'banana': ['yallow fruit', '香蕉']
}
def list_all_words():
print('Your word list\n')
for key, value in MyDict.items():
print('{} ({})\n {}'.format(key, value[1], value[0]))
d... |
377775dc14fb9c40cac4674a72ac73dfd57b2496 | AtulRaj151/Python-Interview-Algorithms | /permutation.py | 274 | 3.671875 | 4 | def swap(l,x,y):
l[x],l[y]=l[y],l[x]
def perm(l,i):
l2=dict()
if i == len(l):
print(l)
else:
for j in range(i,len(l)):
swap(l,i,j)
perm(l,i+1)
swap(l,i,j)
l=['ab','ab','cd']
print(perm(l,0))
|
2eca9e792b816fd220762c40abf03fe6a63804d6 | hrishikeshpandit/Twitter-Data | /cn_mini project.py | 2,077 | 3.5625 | 4 | from twython import Twython
import json
APP_KEY='RRhgPJ9*******l6mJ2zgK' #enter your own account details from apps.twitter.com here all the secret keys are scrambled :)
APP_SECRET= 'zV*******IbcqfneNWEtsGikr8H6kZStymt8vR9IvD5zon4'
OAUTH_TOKEN= '20005**/*/*/*/**YhhizaUE1lYlmvsWwLKCTPkFyiQ'
OAUTH_TOKEN_SECRET= 'rZiM... |
8f81396523fcb323bcbc5ec5f9a8757b72d6f3d7 | sailor09088/python-learning | /RE_ex/KeyMatchReplaceOrAddPrefixSuffixFunc.py | 1,084 | 3.9375 | 4 | #Rev 0.1
#Python3 exercise code
#Search string with key match
#Add prefix/suffix to string
#Recursive or limited iterations
#Support wildcard symbol
#Print warnings if number of augment is less or more
#Break any line to strings
#!/usr/bin/env python3
import re
import sys
def rpls_func(key, rpls, prefix, suffix, lin... |
36c5f9762ca31596da64ec644276269d68aa11be | AlanJYLi/leetcode_practice_python | /week_11/2020_07_30.py | 2,404 | 3.546875 | 4 | # 1408. String Matching in an Array
class Solution:
def stringMatching(self, words: List[str]) -> List[str]:
words.sort(key=lambda x: len(x))
res = []
for i in range(len(words)-1):
sub = words[i]
remain = '_'.join(words[i+1:])
if sub in remain:
... |
91675a4da299a7d70adac40d236e890674f592c0 | AlanJYLi/leetcode_practice_python | /week_9/2020_07_13.py | 2,683 | 3.640625 | 4 | # 1119. Remove Vowels from a String
class Solution:
def removeVowels(self, S: str) -> str:
a = {'a','e','i','o','u'}
res = ''
for s in S:
if s not in a:
res += s
return res
# 1122. Relative Sort Array
class Solution:
def relativeSortArray(self, arr1: ... |
d1c3a034985da4dab6e9593d31be6d57706d51e5 | AlanJYLi/leetcode_practice_python | /week_14/2020_08_22.py | 3,262 | 3.65625 | 4 | # 418. Sentence Screen Fitting
class Solution: # exceed time limit
def wordsTyping(self, sentence: List[str], rows: int, cols: int) -> int:
idx = 0
n = len(sentence)
i = 1
j = 0
while i <= rows:
w = sentence[idx%n]
if j+len(w) <= cols:
... |
b06e1d407b215e2e1f08079ebbb21dfc902739b4 | AlanJYLi/leetcode_practice_python | /week_3/2020_06_02.py | 10,090 | 3.765625 | 4 | # 346. Moving Average from Data Stream
class MovingAverage:
def __init__(self, size: int):
"""
Initialize your data structure here.
"""
self.windowsize = size
self.nums = []
def next(self, val: int) -> float:
if len(self.nums) < self.windowsize:
... |
f279e956cc7c993906ef7fa9f0c918a75fee2945 | AlanJYLi/leetcode_practice_python | /week_4/2020_06_09.py | 11,084 | 3.546875 | 4 | # 687. Longest Univalue Path
class Solution:
def longestUnivaluePath(self, root: TreeNode) -> int:
self.path = 0
def process(root):
if root is None:
return 0
left = process(root.left)
right = process(root.right)
left_... |
9bf5d5b20784d969118f2f7fb84315b969ff686a | chlgudrbdn/ABMS_practice | /discrete event simulation/queue 2 line with choose min people.py | 4,158 | 3.5 | 4 |
import numpy as np
import math
import random
import scipy
from scipy.stats import poisson
from scipy.stats import expon
# np.random.seed(seed=42)
start = 0
end = 1000
# rand_pois = np.random.poisson(lam=2., size=end)
# # 출처: http://rfriend.tistory.com/284 [R, Python 분석과 프로그래밍 (by R Friend)]
# print(rand_pois)
# for... |
ccf0c0c3a937c5a46b58df37820c7286c2625055 | jinchenglee/grid_search | /tmp.py | 2,645 | 3.578125 | 4 | # ----------
# User Instructions:
#
# Create a function compute_value which returns
# a grid of values. The value of a cell is the minimum
# number of moves required to get from the cell to the goal.
#
# If a cell is a wall or it is impossible to reach the goal from a cell,
# assign that cell a value of 99.
# -------... |
ede4ff86aaa6af40118b1c947dcee802ccc61bd8 | optimalprimate/magicmirror | /fan_ctrl.py | 881 | 3.515625 | 4 | #!/usr/bin/python
# -*- coding: utf-8 -*-
import RPi.GPIO as GPIO
import time
import sys
# Configuration
FAN_PIN = 21 # BCM pin used to drive transistor's base
WAIT_TIME = 10 # [s] Time to wait between each refresh
# Setup GPIO pin
GPIO.setmode(GPIO.BCM)
GPIO.setup(FAN_PIN, GPIO.OUT, initial=GPIO.LOW)
cpuTemp = 0
... |
49d05cb9647d9427abe078f651aee7b94dc9cca2 | matti-matti/crypto_projects | /sources/algorithms/prime_factorization/prime_factorization.py | 339 | 4.15625 | 4 | def find_prime_factors(num):
factors = []
for i in range(2, (num // 2)):
if(num % i == 0):
return [i] + find_prime_factors(num // i)
factors.append(num)
return factors
def main():
num = int(input('Find prime factors of: '))
print(find_prime_factors(num))
if __name__ == "__... |
64093be7e0fe1758ee6e8ba20da0b351b738575e | RasulKg/intro2python | /slovar'1.py | 910 | 3.8125 | 4 | D = {'cat':'koshka','dog':'sobaka','snake':'zmeya'}
print D
print "Dlya prosmotra slovorya najmite 1"
print "Dlya dobavleniya slova najmite 2"
print "dlya samoproverki najmite 3"
choise = raw_input (">>>")
add = "1"
if choise == "1":
for key in D:
print key,"-",D[key]
elif choise == "2":
while add == "1":
print "... |
b1c7c88ba4918fb6775122961498e70ab3dd3a82 | RasulKg/intro2python | /python/chisla.py | 139 | 3.53125 | 4 | print "vvedite 4islo"
n=raw_input(">>>")
if (int(n)%2==0):
print "eto polojitel'noe 4islo"
else:
print "eto otricatel'noe 4islo"
print n |
43d5b83069d93598c5a44af51c1d12985401690f | zcollin/TechDegree_Project3 | /TechDegree Project3/work_log.py | 9,976 | 3.921875 | 4 | """
A terminal application for logging what work someone did on a certain day.
The data is collected in a CSV document
Author: Zachary Collins
Date: July, 2018
"""
import csv
import os
import re
import sys
# Creates the csv file if it doesn't exist already
try:
file = open("log.csv", "r")
except IOError:
w... |
7fd4c57b94acafb4780cf62827f2b6fd888600c2 | alexa182/askiseis | /Math_Strings_Exception_Handling.py | 513 | 4.03125 | 4 | while True: #<- anagazw to input na einai number(int) gia na sunexisei
try: #<- kanw try giat kserw oti mporei na yparxei periptosi error
number = int(input("PLS ENTER A NUMBER: "))
break #<- an valei noumero vgenei apo while loop
except ValueError: #<-- an yparxei VALUERROR(an afisw mono ... |
fe4f89b5c51b71d765f0bc8908eb8bbb7131e0be | alexa182/askiseis | /float_point_numbers.py | 231 | 4.03125 | 4 | your_float = input("Enter a float: ")
your_float = float(your_float)
#or your_float = float(input("Enter a float: ")
print ("Round to 2 decimals : {:.2f}".format(your_float)) # {:.2f} = akolothoun (:) 2 dekadika (.2) f(float)
|
9dd873301838394aa66ac9ec466046ca3bb5bc17 | cathyleong88/hi | /celsiuschange.py | 128 | 3.65625 | 4 | celsius = input('請輸入攝氏温度: ')
fahrenheit = (float(celsius) * 9 / 5) + 32
print('華氏温度為: ', fahrenheit) |
451bae16885bc4bd8016cee739de4e1dfd887fe9 | kaamesh17/Assignment | /hello1.py | 205 | 3.859375 | 4 | a= "hello"
f = {}
for i in a:
if i in f:
f[i] += 1
else:
f[i] = 1
print ("Count of all characters in hello is :\n "
+ str(f))
|
924ec4740661ae01b2999b7c70ff696b2785430b | mcculleydj/boston-property-value | /source/cells_within.py | 503 | 3.578125 | 4 | from get_adjacent import get_adj
# recursively discovers the cells within
# n hops from center_cell
def cells_within(cells, center_cell, cell_set, n):
if n > 0:
new_cells = []
for cell in cells:
adj_cells = [str(c) for c in get_adj(int(cell))]
for adj_cell in adj_cells:
if adj_cell not in cell_set:
... |
30a0722c9197bc849a7e7bd4952c2ff7daa96bd4 | akuppala21/Fundamentals-of-CS | /lab8/list_comp/list_comp_tests.py | 655 | 3.734375 | 4 | import unittest
from list_comp import *
from objects import *
class TestCases(unittest.TestCase):
def test_distance_1(self):
p1 = Point(0,0)
p2 = Point(3,4)
self.assertTrue(distance(p1,p2),5)
def test_1(self):
point_list = [Point(1,0),Point(0,1),Point(0,0)]
distances = [1,1,0]
... |
e4457041586d31f456030c82a2f287741b49397f | akuppala21/Fundamentals-of-CS | /lab2/funcs/funcs.py | 249 | 3.640625 | 4 | import math
def f(x):
output = 7*(x**2)+2*(x)
return output
def g(x,y):
output = ((x**2)+(y**2))/(3*x)
return output
def hypotenuse(x,y):
length = math.sqrt((x**2)+(y**2))
return length
def is_positive(x):
value = x
return(value >= 0)
|
6748b1775a2ea72d7082f13df8fc35408138a122 | dTenebrae/Python | /lesson1/lesson1_4.py | 529 | 4.15625 | 4 | # Пользователь вводит целое положительное число. Найдите самую большую цифру
# в числе. Для решения используйте цикл while и арифметические операции.
user_int = int(input('Введите целое положительное число: '))
l_part = user_int % 10
f_part = user_int // 10
while f_part > 0:
if f_part % 10 > l_part:
l_part... |
880d786fda5f9f8c9a3092e25292f7f73f15e5aa | dTenebrae/Python | /lesson2/lesson2_4.py | 514 | 4.1875 | 4 | # Пользователь вводит строку из нескольких слов, разделённых пробелами.
# Вывести каждое слово с новой строки. Строки необходимо пронумеровать.
# Если в слово длинное, выводить только первые 10 букв в слове.
str_list = input('Введите несколько слов: ').split()
for ind, word in enumerate(str_list, 1):
print(ind, wo... |
6943437ff6d1961649feb392f0571ad4cca725d7 | dTenebrae/Python | /lesson4/lesson4_3.py | 264 | 4.03125 | 4 | # Для чисел в пределах от 20 до 240 найти числа, кратные 20 или 21.
# Необходимо решить задание в одну строку.
print([num for num in range(20, 241) if (num % 20 == 0) or (num % 21 == 0)])
|
fb1f1a4eaa9595cf1f370508a05da78ee13c6034 | GasumSam/carrera | /ejemploGetterSetter.py | 1,506 | 3.671875 | 4 | class ClaseConGetterySetter():
def __init__(self):
self.__propiedad_privada = None #No me muestra valor al ser None #Privado, no puedo involarlo desde fuera salgo si genero función
def setPropiedadPrivada(self, valor): #genero una función para fijar (setter) el valor de propiedad privada, ya q... |
3f042bd51cbe79ba693c7a8111b7b23e64df2995 | sov1k/hz | /61A.py | 185 | 3.859375 | 4 | s=input("Введите имя:\n")
print (s)
s1=""
for z in s:
if z=="а": z="б"
elif z=="б": z="а"
elif z=="А": z="Б"
elif z=="Б": z="А"
s1=s1+z
print (s1)
|
a4a0987d27c6b84a302c4352ac76b967107d7233 | 2113vm/dl_course_ai | /assignments/assignment3/layers.py | 12,808 | 3.59375 | 4 | import numpy as np
from assignments.assignment1.linear_classifer import softmax, cross_entropy_loss
def l2_regularization(W, reg_strength):
"""
Computes L2 regularization loss on weights and its gradient
Arguments:
W, np array - weights
reg_strength - float value
Returns:
loss, s... |
2905cd50405289c76ef52fd6ef00f078b9812a7b | Darmaiad/mit-602-computational-thinking | /Unit3/l3/l3e1.py | 639 | 4.34375 | 4 | # You are given the following partially completed function and a file julytemps.txt containing
# the daily maximum and minimum temperatures for each day in Boston for the 31 days of July 2012.
# In the loop, we need to make sure we ignore all lines that don't contain the relevant data.
def loadFile():
inFile = o... |
b51ff4fd211add6e9f631e08918d25be2d63b523 | Darmaiad/mit-602-computational-thinking | /Unit1/l3e2.py | 1,715 | 4.21875 | 4 | """
Consider our representation of permutations of students
in a line from Exercise 1. (The teacher only swaps the
positions of two students that are next to each other in
line.) Let's consider a line of three students, Alice, Bob,
and Carol (denoted A, B, and C). Using the Graph class
created in the lecture, we c... |
0eb776044423f5f1a02246d2c3e2a02a5589ecc8 | Ribeiro-R/FastApi-Tutorial | /Tutorial/22-JSON-Compatible-Encoder/01-jsonable_encoder/main.py | 1,803 | 3.984375 | 4 | '''
There are some cases where you might need to convert a data
type (like a Pydantic model) to something compatible with JSON
(like a dict, list, etc).
For example, if you need to store it in a database.
For that, FastAPI provides a jsonable_encoder() function.
Using the jsonable_encoder
Let's imagine that you hav... |
d143b52fac8bc177715fc7d1554f8de93d42a269 | ponypaver/checkio | /Tic_Tac_Toe.py | 839 | 3.71875 | 4 | #! /usr/bin/env python3
def checkio(l):
for mark in 'XO':
for p in range(3):
if (
all(c == mark for c in l[p])
or all(c == mark for c in [l[i][p] for i in range(3)])
):
return mark
if (
all(c == mark for c ... |
68e0c592c5b4acb9677fd7fa7e1f805a594b3c0b | GIDA-Ibero/Python-basics | /01-Listas.py | 1,208 | 3.71875 | 4 | # En python hay tres tipos manejar datos con [] se crea una lista
# Es una estructura facil de manejar a parte de que es mutable
# no esta reservado para solo un tipo de dato (se puede combinar strings y numeros)
mi_lista1 = [1,2,3]
mi_lista2 = ["Hola","estoy",'en',"una",'lista']
mi_lista3 = [12,"teclado",5632.156,'k'... |
32cda06d0f7da3b981aa0d0550102cd54a804c9c | roliver7878/project2 | /main.py | 676 | 3.703125 | 4 | import addressfind
import addresstotext
import converttoaudio
# This is my main method
def main():
# here we ask for postalCode from user
cepcodevalue = input('Write here your postal code: ')
# the function above send the postalcode writed by User
# addressfind use a free api for serach the address by... |
6036ffb7eb6b1e5ecc566bec6ce28dd563e5324c | PatrikHlobil/Eliminate-Newlines-After-Function-Definition | /eliminate_newlines/core.py | 2,483 | 3.734375 | 4 | import re
from pathlib import Path
from typing import Union
import click
def eliminate_newlines_after_function_definition_in_string(code: str) -> str:
"""Eliminates all newlines after the function definition in a string, e.g.
def foo(a):
return a + 1
will become:
def foo(a):
retur... |
d6c61efb01d4e84ea2a471ccb3ecd23f8e5af513 | sharvilshah1994/LeetCode | /Apple/CountNumOf1s.py | 170 | 3.546875 | 4 | def countOnes(num):
num = '{0:10b}'.format(num)
count = 0
for _ in str(num):
if _ == '1':
count += 1
return count
print(countOnes(2)) |
3856a2ba7525a64a4c32021cda1f04502f1aa4bd | sharvilshah1994/LeetCode | /GoDaddy/MergeInBetween.py | 1,041 | 3.96875 | 4 | class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
def Init():
node1 = ListNode(1)
node2 = ListNode(2)
node3 = ListNode(3)
node4 = ListNode(4)
node5 = ListNode(5)
node6 = ListNode(6)
node1.next = node2
node2.next = node3
node3.next = no... |
a599d5da58c615b922ff9e1c310c2f37ceac907f | sharvilshah1994/LeetCode | /LinkedLists/HasCycle.py | 684 | 3.640625 | 4 | class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
def build_linked_list():
l = ListNode(1)
l1 = ListNode(2)
l2 = ListNode(3)
l3 = ListNode(4)
l4 = ListNode(5)
l.next = l1
l1.next = l2
l2.next = l3
l3.next = l4
l4.next = l
retur... |
f812881054abbd3dccd9637aba229333162b96d9 | sharvilshah1994/LeetCode | /BinaryTree/CheckForCycleBinaryTree.py | 1,117 | 3.890625 | 4 | class BinaryTreeNode(object):
def __init__(self, x):
self.data = x
self.left = None
self.right = None
def build_tree():
t = BinaryTreeNode(1)
t1 = BinaryTreeNode(2)
t2 = BinaryTreeNode(3)
t3 = BinaryTreeNode(4)
t4 = BinaryTreeNode(5)
t.left = t1
t.right = t2
... |
989d8522337aa4a474a31fe105ae2cec643881f4 | sharvilshah1994/LeetCode | /Apple/MergeTwoListsSorted.py | 870 | 4 | 4 | class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
def build_first_list():
l = ListNode(1)
l1 = ListNode(4)
l2 = ListNode(5)
l.next = l1
l1.next = l2
return l
def build_second_list():
l = ListNode(2)
l1 = ListNode(3)
l2 = ListNode(6)
... |
537af13438c670f92588a12bb7195ffd5d740527 | sharvilshah1994/LeetCode | /IndexDiffEqualToKHashMap.py | 339 | 3.53125 | 4 | def containsCloseNums(nums, k):
dic = {}
for i in range(len(nums)):
if nums[i] in dic:
if (i - dic[nums[i]]) <= k:
return True
else:
dic[nums[i]] = i
else:
dic[nums[i]] = i
return False
print(containsCloseNums(nums=[0, 1, ... |
3c4a95472e96446837a684eac1fe2ea9559112ee | sharvilshah1994/LeetCode | /Apple/FindIfLoopExistsInLinkedList.py | 641 | 3.890625 | 4 | class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
def build_linked_list():
l = ListNode(1)
l1 = ListNode(2)
l2 = ListNode(3)
l3 = ListNode(4)
l.next = l1
l1.next = l2
l2.next = l3
l3.next = l2
return l
class Solution(object):
def... |
c93a46ba340e71e0b1bd3af6ad708b6bf1498667 | sharvilshah1994/LeetCode | /Apple/LCA.py | 886 | 3.84375 | 4 | class BinaryTreeNode(object):
def __init__(self, x):
self.data = x
self.left = None
self.right = None
def build_tree():
t = BinaryTreeNode(1)
t1 = BinaryTreeNode(2)
t2 = BinaryTreeNode(3)
t3 = BinaryTreeNode(4)
t4 = BinaryTreeNode(5)
t.left = t1
t.right = t2
... |
c3fc45d6d1792385c26be283e51c20c0078e176e | AbhinavTalari/Games-in-Python | /TicTacToe Game/src/rungame.py | 2,920 | 3.5 | 4 |
# run_tic_tac_toe.py
import pygame
import sys
from tic_tac_toe import *
from algos import *
# import time
pygame.init()
print("\nWelcome to Abhinav's\'s TicTacToe!\n")
while True:
window = open_window() # open window
create_board(window) # create board
state = ["0", "1", "2", "3", "4", "5", "6", "... |
30ede3e3440d3e4bbb10657d3a5578812b747b9e | ndelafuente/class-projects | /Moving Circles/moving_circles.py | 7,210 | 4.09375 | 4 | """
File: moving_circles.py
Author: Katrina Baha and Nicolas de la Fuente
Date: 10 March 2020
Description: Program that gets two circle locations from the
user, then draws a line between them, and
displays the distance between them midway along
the line. The user can drag either circle around,
and the distance is... |
1e7f670dcaf51117dc2cc96b29e963e9205d38aa | AlexGordienko/MITx-6.00.1x | /Midterm/problem_5.py | 1,107 | 4.3125 | 4 | '''
Write a Python function that takes in a string and prints out a version of this string that does not contain any vowels, according to the specification below. Vowels are uppercase and lowercase 'a', 'e', 'i', 'o', 'u'.
For example, if s = "This is great!" then print_without_vowels will print Ths s grt!. If s = "a"... |
dfa3489a7068366fe6216b7a130846bac7ca9cd9 | wmarshall484/DSI_LECTURES_2 | /high-performance-python/ryan_henning/hpp/3_processes.py | 2,144 | 3.90625 | 4 | '''
This script uses multiple processes to compute the number of factors of a given
integer. This script does not consider 1 and n to be factors of n (even though
they technically are). We're only interested in finding the number of factors
between 1 and n.
Run the script as: `python 3_processes.py <number_to_factoriz... |
6352f107813977262d8e3936e7b23260e93b7925 | wmarshall484/DSI_LECTURES_2 | /clustering/elliot_cohen/kmeans/src/kmeans_plots.py | 4,553 | 3.78125 | 4 | '''
code used to make the plots for kmeans lecture
'''
from sklearn.cluster import KMeans
import numpy as np
import matplotlib.pyplot as plt
from sklearn.metrics import silhouette_score
def plot_iterations(iterations, data, plotname = None):
'''
iterations is a list, data is a np array
'''
fig, ax = pl... |
48cd23f7823d71c3bb1d6040ad9ecd3afdb9eb30 | wmarshall484/DSI_LECTURES_2 | /graphs/michael_jancsy/bfs.py | 1,963 | 4.03125 | 4 | from collections import deque
def bfs_connected_components(graph, starting_node):
'''
Returns the connected component of a graph containing the starting_node
'''
visited = set()
queue = deque([starting_node])
while queue:
node = queue.popleft()
if node not in visited:
... |
ce6701f9aa84276e8d1a5507339bce6ec6a269a0 | wmarshall484/DSI_LECTURES_2 | /probability/ryan_henning/prob_program.py | 3,412 | 4.4375 | 4 | """
Matthew Drury's Probabilty Problem:
You have a shuffled deck of 60 cards containing the following cards of special interest:
- Three of the cards in the deck are marked with a diamond.
- Three of the cards are marked with a star.
- The remaining cards are nothing special.
You draw an initial hand of five cards, a... |
697ad0f3713b7485643fc9f88b3b119bcfd5015c | wmarshall484/DSI_LECTURES_2 | /high-performance-python/jGartner/4.py | 2,720 | 4.375 | 4 | '''
This scripts brings all these concepts together. Here's how to
use multiprocessing and multithreading together: first create
several processes, then in each of those create several threads.
This is just a template.
When would creating several processes be a good idea? Here's a
few reasons:
- If one process die... |
3b6793b94c98d439c79295558284dfce3d989861 | wmarshall484/DSI_LECTURES_2 | /python-intro/michael_jancsy/fibonacci.py | 244 | 3.96875 | 4 | def fibonacci(n):
'''
INPUT: n
OUTPUT: the nth fibonacci number
'''
f1, f2 = 0, 1
i = 1
while i < n:
f1, f2 = f2, f1 +f2
i += 1
return f2
if __name__ == '__main__':
print fibonacci(29)
|
e7b2e765e3bf9b7c7004790a8755b225752d7b59 | wmarshall484/DSI_LECTURES_2 | /OOP/isaac_laughlin/example/card.py | 379 | 3.546875 | 4 |
class Card():
def __init__(self, num, suit):
self.num = num
self.suit = suit
self.card_values = {'A':13, 'K':12, 'Q':11, 'J':10, '7': 6}
def value(self):
return self.card_values[self.num]
def __gt__(self, other):
return self.value() > other.value()
def __eq__(... |
b02744ae6987f74e264a7cd8c95e25e788318045 | wmarshall484/DSI_LECTURES_2 | /graphs/ryan_henning/linked_list.py | 2,953 | 4.53125 | 5 |
class Node:
'''
This class represents a node in a linked list.
Every node contains a value and a reference to the
next node in the list (or None if this node is the
last node in the list).
'''
def __init__(self, value, next_node=None):
'''Initializes this node with a value and a ne... |
15d6616ad8580b50c407604738a87e15e511e86a | honeywang991/test01 | /python9/class_0721_list_tuple_dict/class_tuple.py | 709 | 4.15625 | 4 | __author__ = 'zz'
#元祖 tuple 标识符()
#特性: 1:他可以包含任何类型的数据,数据之间用逗号隔开
#2:元组取值的方式: 元组名[索引的值]
#3: 他的索引是从0开始的
#4:元组的值一旦确定,就不能修改也不能删除也不能增加
# tuple_1 = (1,'hello',8.6,(1,2,3,4))
#
# #先学习一个算术运算符 = 赋值运算符
# tuple_1[1]='555'
# #取(1,2,3,4)的值?
# print(tuple_1[3])
# #取(1,2,3,4)中的3的值?
# print(tuple_1[3][2])
tuple_1 = (1,'hello',8.6,... |
941ba71075fa33186f395c51c1a74955127a439c | honeywang991/test01 | /python9/class_0721_list_tuple_dict/class_str.py | 730 | 3.71875 | 4 | __author__ = 'zz'
#常用的基础数据类型 int float str boolean
#字符串 切片 讲了拼接 格式化输出
str_1 = 'python9'
#升级版本 请把str_1这个字符串 倒序输出
# print(str_1[-1:-9:-1])
# print(str_1[-1::-1])
# print(str_1[::-1])#比较常用的
#切片 截断 取值
#切片用法 字符串名[起始位置:结束位置:步长]
#结束位置的那个元素 不会取 #切片步长默认为1
#1: 取所有的元素
# print(str_1[0:10:3])
# print(str_1[0:10])
# print(str_1... |
3e1ab9e2578041d26cd076fbb75133489ed1a200 | honeywang991/test01 | /python9/class_0805_object/class_0805_1.py | 3,332 | 4.46875 | 4 | #类 人类 动物类 植物类 妖类
#人以群分 物以类聚
#具有共同的属性,特性这些事物
#谁来定义类,怎么来划分类。
#python类的语法
#关键字 class
#定义一个类:
#class 类名:
#这一类 共同的属性
#这一类 共同的方法/行为(用函数来表达)--->类函数 or 类方法
#类名的规范:驼峰 手字符大写 jina见名知意
#BoyFriend
#MyGirl
# girl 你理想中的男朋友是怎么样的?
#帅的 高富帅 1.8 有内涵 支持你 幽默
#有钱 阳光 成熟 潜力股 有上进心
#会做饭 会Python
#男朋友类
class BoyFriend:
#共同的属性
... |
b1c4d60f712ce6ed39aee4886811b40608e74844 | honeywang991/test01 | /python9/class_0724_if_while/class_3_for.py | 940 | 3.96875 | 4 | #for循环 关键字 90%
#第一个作用 : 遍历元素
#for item in 数据范围: #str list dict tuple 其他类型的数据范围
#str_1='python9'
#list_1=[1,3,4,5]
# tuple_1 = (1,3,4,5)
# dict_1 = {'date':'2018-7-24','class':'python9'}
# print(dict_1.keys())#访问字典里的key
# print(dict_1.values())#访问字典里的值
# for i in dict_1.values():
# print(i)
#range函数 range(m,n,k)起... |
4746e6f1caf5a937cd8ad16cc8c6ffb02446b469 | amisha-28/Hacktoberfest-2020 | /greet.py | 79 | 3.921875 | 4 |
name=input("Hey! Please type your name: ")
print("Hello, {}".format(name))
|
8c7d25dfa0d4f4c9cc63fe5dc6b3acb92d3aed91 | blane612/dto | /example.py | 1,716 | 4.625 | 5 | # arithmetic operators - integers and floats
# + | addition
# - | subtraction
# * | multiplication
# / | true division
# // | floor division
# ** | exponentiation
# % | modulus
# addition
print('the sum of 5 + 7 =', 5 + 7)
print('the sum of 5 + 2 + -4 + 11 =', 5 + 2 + -4 + 11)
# subtraction
print('... |
051421a5e1145afc1ecfb4e2e0275b8285cdbd2d | EggplantElf/chinese_idioms | /freq.py | 478 | 3.59375 | 4 | import sys
def freq(filename):
dic = {}
for line in open(filename):
line = line.strip()
for i in range(len(line) / 3):
zi = line[i *3:i*3+3]
if zi not in dic:
dic[zi] = 1
else:
dic[zi] += 1
# print len([k for k in dic if d... |
8dffe34bb5562d75b53feec8b90e337e6a70ebbb | FlongyDev/py-intro | /part4_1-types.py | 1,435 | 4.15625 | 4 | """ ======================================= """
""" Типы данных, Ч1: None, bool, int, float """
""" ======================================= """
""" Целое число - int """
# x = 69
# print(type(x)) # Функция для определения типа некоторой переменной
""" Булевое значение - bool """
# a = 16
# print(type(a > 5))
... |
21659763fa120be11566de5e466238be1462f50b | shoredata/dojo-python | /dojo-python-flask-misc/hello_flask/playground.py | 3,761 | 3.90625 | 4 | # Assignment: Playground
# =======================
# Objectives:
# ------------
# Get comfortable passing information from the route to the template
# Understand how to display information passed from the route in the template file
# Get comfortable with using for loops in the template file
# Get comfortable with usin... |
80e0a1ed3e7f738c28ef63b7e3e71f7c23d4562e | shoredata/dojo-python | /dojo-python-flask-misc/html_table/table_server.py | 2,660 | 3.875 | 4 | # Assignment: HTML Table
# ======================
# Objectives:
# -----------
# Get comfortable passing information from the route to the template
# Get very comfortable iterating through a list of dictionaries to generate a html output.
# This is very important for all web development as records returned from a da... |
2affc7a43aa542535d3a84d73c36eb16db8af3e3 | shoredata/dojo-python | /dojo-python-misc/slists.py | 9,465 | 4.28125 | 4 | # SLists
# ======
# Objectives:
# -----------
# Understand how Singly Linked List works
# Understand how pointers work
# Understand how to traverse and add node to the linked list
# Implementation
# --------------
# class Node:
# def __init__(self, value):
# self.value = value
# self.next = None
... |
dc916948b6814f71832e0ecb74cdefaffee458ea | shoredata/dojo-python | /dojo-python-misc/clsProduct.py | 3,933 | 4.34375 | 4 | # Assignment: Product
# ==================
# Objectives:
# -----------
# Practice creating a class and making instances from it
# Practice accessing the methods and attributes of different instances
# Practice altering an instance's attributes
# The owner of a store wants a program to track products.
# Create a prod... |
020b7b0bfe466ac0e6cb7ec55bb98ed0f18a1074 | shoredata/dojo-python | /dojo-python-misc/clsCar.py | 2,561 | 4.3125 | 4 | # Assignment: Car
# Objectives:
# Practice creating a class and making instances from it
# Practice accessing the methods and attributes of different instances
# Create a class called Car.
# In the __init__(), allow the user to specify the following attributes:
# price, speed, fuel, mileage.
# If the price is g... |
a063e35a31c7a672b1914db46992b226b0604ce9 | LucianoAlbanes/AyEDII | /TP3/redblacktree.py | 14,082 | 3.5625 | 4 | # Red-Black Tree implementation
from mybinarytree import getNode, insertAux, searchAux, moveNode, search, access, update, traverseInPreOrder
# Define classes
class RedBlackTree:
root = None
class RedBlackNode:
parent = None
leftnode = None
rightnode = None
key = None
red = No... |
d0acbccb4df156712169a85dcb579f1e40c9581b | LucianoAlbanes/AyEDII | /TP1/4-sortMiddle.py | 2,144 | 3.90625 | 4 | '''
Implementar un algoritmo que ordene una lista de elementos donde siempre el elemento del
medio de la lista contiene antes que él en la lista la mitad de los elementos menores que él.
Explique la estrategia de ordenación utilizada.
'''
from linkedlist import length, getNode, swapNodes
from quickSort import qui... |
aa17342033e5b0083834d2ff732fadc275418788 | LucianoAlbanes/AyEDII | /TP7/lib/mydictionaryChar.py | 5,560 | 4.21875 | 4 | from lib import linkedlist as LL
# Def dictionaryNode (analog to linkedlist's node)
class dictionaryNode:
key = None
value = None
nextNode = None
# Define functions
def h(key, m):
'''
Explanation:
Generates a hash for a given character.
Info:
This hash function uses 'The div... |
2772a9a138ce48b83760b9bbadb26a75b5f4fb9d | LucianoAlbanes/AyEDII | /TP8/P2_E5.py | 2,923 | 3.78125 | 4 | # Part 2 of 'Análisis y Diseño de Algoritmos'
# Greedy
from lib.algo1 import *
from lib import linkedlist as LL
# Exercise 5
def adminActividades(tasks, start, end):
'''
Explanation:
Select the largest possible set of activities that do not overlap and optimize the use of the resource
... |
17efbf8e3d5dee905620a8eaa7ef7472a0c112c7 | JiaqiuWang/Yanglao | /Learn/learn_graph.py | 921 | 3.59375 | 4 | import networkx
G = networkx.Graph() # 建立一个空的无项图
Gdi = networkx.DiGraph() # 建立一个有向图
G.add_node(1) # 添加一个节点1
G.add_edge(2, 3) # 添加一条边2-3(隐含添加了两个节点2,3)
G.add_edge(3, 2) # 对于无向图,边3-2和2-3被认为是一条边
G.add_edge(1, 2) # 添加一条边2-3(隐含添加了两个节点2,3)
print("输出全部的节点:", G.nodes())
print("输出全部的边:", G.edges())
print("输出边的数量:", G.num... |
a35d2241d06903e92ab11038d8a02d3d9c2cdaf1 | jenniejh/SI507_project_final_final | /proj_final_test.py | 7,535 | 3.65625 | 4 | import unittest
from proj_final import *
### Test data access from the data source about US universities and GPS coordinate
class TestSchoolAccess(unittest.TestCase):
def school_is_in_list(self, school_name, school_list):
for i in school_list:
if school_name == i.name:
return ... |
91af618609ffb11f71ceb5cc5f91fc161de3bb4f | rpryzant/code-doodles | /interview_problems/2018/reverse_integer/int_reverse.py | 281 | 4.09375 | 4 |
def reverse(x):
out = 0
neg = False
if x < 0:
neg = True
x = abs(x)
while x > 0:
out += x % 10
x /= 10
if x > 0:
out *= 10
if neg:
return -out
return out
print reverse(123)
print reverse(-123)
|
d725fedb5bf2d260ae91cda80f7ab824c767f426 | rpryzant/code-doodles | /interview_problems/2019/cracking/10.8.py | 705 | 3.53125 | 4 | """find dups
N = max num (unknown)
A = array size (known...big)
M = memory (4kb ~ 4k numbers if short)
O(A * (N/M)):
for each pass of array look for numbers in [i*m, (i+1)*m]
what can i use the mem for? holding
indices
numbers from A
^^ similar, but not identical as dups have same number but dif index
co... |
f8eb32b484eea1e819043286053f633279cfae0a | rpryzant/code-doodles | /interview_problems/2018/reverse_nodes_k_group/revKGroup2.py | 918 | 3.625 | 4 | """
GO THROUGH EXAMPLES
1 > 2 > 3 > 4 > 5 > N
h t post
2 > 1 > 3 > 4 > 5 > N
t h post
2 > 1 > 3 > 4 > 5 > N
prev t post
h
2 > 1 > 4 > 3 > 5 > N
prev h post
t
"""
def reverse(pre, head, tail, post):
cur = head
prev = pre
while True:
tmp = cur.next... |
dceada12414082a7107731797522bcc6f36f924e | rpryzant/code-doodles | /interview_problems/2018/CRACKING/17.6.py | 1,526 | 3.765625 | 4 | """
this is NOT correct :((
number of 2s between 1 and n
1 bf: count up, getting 2's as you go
at each order of magnitude M, you'll get
M-1^10 2's (+ M-1^10 + that -1)?
e.g.
M = 0 ==> 0
M = 1 ==> 1
M = 2 ==> 10 + 9
M = 3 ==> 100 + (10*10 - 10) + (100*1 - 10 - 9)
^ all the xx2s ... |
b81167df39d0bc8ecffd86f2540ea70f42caceb7 | rpryzant/code-doodles | /interview_problems/2019/pramp/paris.py | 673 | 3.515625 | 4 | """
arr
k pos int
findPairsWithGivenDifference
=> [x, y] : x, y in arr and x - y = k
[0 0 0 0 0 0]
i j
x - y = k
x - k = y
[i j] [j i]
1) brute force
for i in arr
for j in arr
if j - i == k:
add pair
2)
d = {} # {y => x}
for x in arr:
d[x - k] = x
out = []
fo... |
f22a2938a228bbcdf524ee5fe88eeb5199594e11 | rpryzant/code-doodles | /interview_problems/2018/CRACKING/8.5_v2.py | 666 | 4.125 | 4 |
"""
recursive multiply
break into cases
x * y
if y == 0: return 0
if y == 1: return x
if y is a power of 2: return x << log(y, 2)
if y is divisible by 2:
xy = x((y/2) (y/2)) = 2 * x(y/2)
when all else fails:
xy = x * (x(y-1))
"""
import math
def mul(a, b):
def recurse(x, y):
if y == 0: retu... |
f675ba42f53fc71ee4d3d5e392f6630c05f43d0f | rpryzant/code-doodles | /interview_problems/2019/pramp/root.py | 2,154 | 3.765625 | 4 | """
Root of Number
Many times, we need to re-implement basic functions without using any standard library functions already implemented. For example, when designing a chip that requires very little memory space.
In this question we’ll implement a function root that calculates the n’th root of a number. The function ta... |
e128e3f842e36533b95d0fcf52498f1c63129c7d | rpryzant/code-doodles | /purely_random/mutate_sentances.py | 1,434 | 4.09375 | 4 | def mutateSentences(sentence):
"""
High-level idea: generate sentences similar to a given sentence.
Given a sentence (sequence of words), return a list of all possible
alternative sentences of the same length, where each pair of adjacent words
also occurs in the original sentence. (The words within ... |
038d96a405c79d34877033e9b9cb692480564c17 | rpryzant/code-doodles | /interview_problems/2018/plus_one/increment2.py | 940 | 3.6875 | 4 | """
non-negative number
most sig least sig
e.g.
[1 2 4 9 9]
want to add 1
decimals?
limit to list?
each elemnt guarenteed 0<x<10
are elments decimals?
no, each is a whole digit
1)
listify(numberfy(list)) + 1)
O(n)
O(n)
2) do the addition manually
init carry to first digit
init i one from back
loop... |
77f70ec529c6f621b7b7467a044a2b12b21cf201 | rpryzant/code-doodles | /data_structures/trie.py | 2,083 | 3.765625 | 4 | """
Implementation of a trie
- this isn't very compressed...inits 26 blank children for each node.
TODO init as you go!
"""
import Queue
ANYTHING = '.'
class TrieNode:
def __init__(self, letter):
self.children = [None for _ in range(26)]
self.letter = letter.lower()
def cont... |
82c312b85086664cf8ca290045ada6302f86f2f9 | rpryzant/code-doodles | /interview_problems/2018/CRACKING/2.8_v2.py | 781 | 3.6875 | 4 | """
can we assume this directed graph has a loop? yes
1) O(n) space O(n) time: track id(node) as you go, return first repeat :)
2) runner that moves 2x the speed of lagger, find where they meet
k nodes before loop
when slow enters loop, runner is K steps ahead, and
the two are LOOP_SIZE - mod(l... |
994203595c0f7d8fa25fe1ba7d15c3409146cd48 | rpryzant/code-doodles | /interview_problems/2018/2d_matrix_search/search2.py | 825 | 4.03125 | 4 | """
(m x n) matrix search
rows are sorted left to right
rows above are larger than rows below
1) bf:
O(mn) try everything!
2) binary search
locate insertion row
= row with greatest starting value less than T
search that row
O(log m + log n)
( O(m) space because of the way i'll implement ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.