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 |
|---|---|---|---|---|---|---|
c69f566e521f13554be1e8e659f5169a509dddb2 | daniel-amos/SC-T-201-GSKI | /Timi/Timi_15/PriorityQueue_ADT.py | 1,166 | 4.09375 | 4 | class Node:
def __init__(self, data=None, next=None):
self.data = data
self.next = next
class LinkedListPriority:
def __init__(self):
self.__head = None
self.__tail = None
def add(self, value):
new_node = Node(value)
if self.__head is None:
self... |
eaf4d9a06ba83e6187ffdc75b127679b55765210 | daniel-amos/SC-T-201-GSKI | /Timi/Timi_5/vol_2/length_of_str.py | 135 | 3.796875 | 4 |
def length(my_str):
if len(my_str) == 1:
return 1
else:
return 1 + len(my_str[1::])
print(length("hello"))
|
483f942815407d7890a4547f6ec22a6b2a64e35b | daniel-amos/SC-T-201-GSKI | /Timi/Timi_6/queue.py | 1,033 | 3.765625 | 4 | class Queue:
def __init__(self):
self.front = 0
self.size = 0
self.capacity = 4
self.data = [None] * self.capacity
def add(self, value):
if self.capacity == self.size:
self.resize()
avail = (self.front + self.size) % self.capacity
self.data[av... |
f755fc41343cbb4ca57b42d0f0665874e468d493 | daniel-amos/SC-T-201-GSKI | /Prep_for_test/Test_3/binary_tree.py | 1,804 | 3.828125 | 4 | class BT_Node:
def __init__(self, data=None, left=None, right=None):
self.data = data
self.left = left
self.right = right
def __str__(self):
return str(self.data)
class BT:
def __init__(self):
self.root = None
def populate_tree(self, data):
if self.roo... |
331e1439f5c79508e92a1211985680a5740772e8 | daniel-amos/SC-T-201-GSKI | /Timi/Timi_2/multiplication.py | 231 | 3.8125 | 4 |
def multiplication(a, b):
num = 0
for x in range(b):
num += a
print(num)
multiplication(int(input("A: ")), int(input("B: ")))
# Keirslutíminn er O(n) þar sem input b ræður hversu oft for lykkjan keyrir
|
72084e288e3c0b45ae2437a89900d1cfaa293171 | daniel-amos/SC-T-201-GSKI | /Finals/PracticeExam/PracticeExam/P3/bst_set.py | 3,102 | 3.859375 | 4 | class BSTSetNode:
def __init__(self, value):
self.value = value
self.left = None
self.right = None
def __str__(self):
return str(self.value)
class BSTSet:
def __init__(self):
self.root = None
self.size = 0
def _add(self, value, node):
if node i... |
a9c604ff5e3dc9d341de2d8d04181e422af7c32e | daniel-amos/SC-T-201-GSKI | /PA/PA_1/ArrayListBase/array_list.py | 3,681 | 4.1875 | 4 | class IndexOutOfBounds(Exception):
pass
class NotFound(Exception):
pass
class Empty(Exception):
pass
class ArrayList:
def __init__(self):
self.size = 0
self.capacity = 4
self.data = [0] * self.capacity
# Time complexity: O(n) - linear time in size of list
def print... |
f694a93ecb9144285d689833a2f66f3c3fa03bee | daniel-amos/SC-T-201-GSKI | /Timi/Timi_18/ADT_BST.py | 3,954 | 4 | 4 | class Binary_Node:
def __init__(self, value=None, left=None, right=None):
self.value = value
self.left = left
self.right = right
def __str__(self):
return str(self.value)
class Binary_Tree:
def __init__(self):
self.root = None
self.size = 0
def add(sel... |
4f6dede9ef921914c3ec5fb9eeb81a2e5196e072 | daniel-amos/SC-T-201-GSKI | /Finals/PracticeExam/PracticeExam_solutions/PracticeExam_solutions/P4/hash_map.py | 1,782 | 3.78125 | 4 | from bucket import *
class HashMap:
def __init__(self):
self.bucket_count = 16
self._init_bucket_list()
def _init_bucket_list(self):
self.bucket_list = [Bucket() for _ in range(self.bucket_count)]
self.size = 0
def __setitem__(self, key, data):
bucket_index = hash(... |
abf8bff92d073b907bdade060b38c75e83aed04f | htlcnn/FAMILUG | /Python/onflyfunc.py | 307 | 3.671875 | 4 | #!/usr/bin/env python2
'''
Simple example creates functions and call them on-fly
'''
def create_func(name):
def print_name():
print "hello", name
return print_name
funcs = {i: create_func(i) for i in ('Pichu', 'Pikachu', 'Raichu')}
for fname in funcs:
print fname
funcs[fname]()
|
038654b743ff684fd18c29df22f818d2fbfa60de | htlcnn/FAMILUG | /Python/lessons.py | 380 | 3.734375 | 4 | #!/usr/bin/env python3
# By HVN at http://pymi.vn/
import datetime
print('PyFML 1609 HCM Schedule')
lesson = 1
MONDAY = 0
WEDNESDAY = 2
day = datetime.date(2016, 9, 12)
while lesson <= 12:
if day.weekday() == MONDAY or day.weekday() == WEDNESDAY:
print(lesson, day.strftime('%Y-%m-%d'))
lesson += 1... |
001fafe5e0e3e1b8eb348002849389ca2a489cf8 | htlcnn/FAMILUG | /Python/pascal.py | 613 | 3.59375 | 4 | def pascal_row(row):
ret = []
def one_elem(r, c):
# Vc = Vc-1 * (r - c) / c , r = row + 1, V0 = 1
if c == 0:
return 1
else:
return one_elem(r, c - 1) * (r - c)/ c
r = row + 1
for i in range(r):
ret.append(one_elem(r, i))
return ret
def ... |
6a6f17566837620510cf821e7dceb42608a8a945 | C-CCM-TC1028-111-2113/homework-2-jefloreste | /assignments/02Licencia/src/exercise.py | 419 | 4.0625 | 4 | def main():
return()
age = int(input("Insert your age: "))
if age >= 18:
legal_license = input("Do you have a license? (Y/N): ")
if legal_license == "Y":
print("You're eligible for a license")
elif legal_license == "N":
print("You're not eligible for a license")
else:
print("Incorr... |
aa980f9b50e557a6b4e0e0ead8690fc2b7af4b9a | devConrado/curso_python | /Aula_03/script2.py | 638 | 3.703125 | 4 |
#!/usr/bin/python3
def quadrado(n):
return n**2
def raiz(n):
return n**0.5
funcs = [quadrado,raiz]
[print(list(map(lambda x : x(i), funcs)) for i in range(26))]
exit()
for i in range(26):
valores = list(map(lambda x : x(i), funcs))
print(valores)
exit()
num1 = [1,2,3]
num2 = [4,5,6]
r = list(m... |
53ca55f742bcdb02c19c467249cf26b37e05815e | devConrado/curso_python | /Aula_02/script4.py | 389 | 3.859375 | 4 | #!/usr/bin/python3
while True:
n1 = int(input('1o num: '))
n2 = int(input('2o num: '))
try:
r = n1/n2
except ZeroDivisionError as e:
print(e)
else:
print(r)
finally:
print("fim")
exit()
#####################################################################################################
try:
print(5/0... |
86b03fa6f91ddeb5e08a52140138f41bdf4c60db | bbolelli/pdsnd_github | /bikeshare.py | 9,651 | 4.46875 | 4 | import time
import pandas as pd
CITY_DATA = { 'chicago': 'chicago.csv',
'new york city': 'new_york_city.csv',
'washington': 'washington.csv' }
def get_filters():
"""
Asks user to specify a city, month, and day to analyze.
(str) city - name of the city to analyze
(st... |
1769a219c98ee4dd656b067e2d92bcc5243846ea | carvalhoamc/coding_interview | /code/coin_change.py | 2,889 | 3.625 | 4 | def coin_change(ar1, n, sum1):
# example n=4 ar[4] - so one output
if sum1 == 0:
return 1
# can not take that solution, no solution
if sum1 < 0:
return 0
# no coins but some is greater than 1 no solution
if n <= 0 and sum1 >= 1:
return 0
print(ar1)
print(n)
pr... |
1bd1930f5f4fee61c299ee1b0940de023259d76d | Fastcampus-WPS-9th/Thanksgiving-Homework | /JungMongKyo/functions/character_monster.py | 1,569 | 3.578125 | 4 | import random
class User:
def __init__(self, name, type_of):
self.name = name
self.type_of = type_of
self.hp = 100
self.mp = 80
self.attack = 20
self.result = 0
self.point = 0
def user_info(self):
print(f'유저명: {self.name}',
... |
b2112df656d75f3e6753e0342e472b73bcace180 | jackyeasy/learngit | /python/calculate.py | 216 | 3.765625 | 4 | # Calculate the m=1x2x3x4x5x...xn, n is input by user
m=1
n=int(input('Please input n number?'))
for i in range (1,n+1):
m=m*i
if i==n:
print(str(i),end='')
else:
print(str(i)+'*',end='')
print('=',str(m))
|
2de533309656295ae4a56e4132b904ca9a02d024 | faraday58/pythonbasico | /expendedora1.py | 485 | 3.8125 | 4 | numProducto=input(" Introduzca le número del producto deseado \n 1A)papas \n 2B)Refresco \n 3C)Chocolate \n ")
print("Usted seleccionó el producto: ",numProducto)
if numProducto == "1A":
precio=10
if numProducto == "2B":
precio=12
if numProducto == "3C":
precio=15
print("El precio del producto es: $",preci... |
46d3ac3a7b9a7da290257d28a75152bc8b4f8511 | klaus126/django101 | /python-test.py | 229 | 3.75 | 4 | participant = {'name': 'Ola', 'country': 'Poland', 'favorite_numbers': [7, 42, 92]}
#print(participant)
#for key in participant:
# print(key, ":", participant[key])
for key, value in participant.items():
print(key, ":", value) |
89861964b12883edbce31a9c3c17a5243e6ce9d6 | yeurch/project-euler | /euler36.py | 590 | 3.546875 | 4 | # Double-base palindromes
# Problem 36
# The decimal number, 585 = 10010010012 (binary), is palindromic in both
# bases.
#
# Find the sum of all numbers, less than one million, which are palindromic
# in base 10 and base 2.
#
# (Please note that the palindromic number, in either base, may not include
# leadi... |
dbc48efd125b930d7906d28b4fbe44f407903e75 | yeurch/project-euler | /euler17.py | 1,580 | 3.96875 | 4 | # Number letter counts
# Problem 17
# If the numbers 1 to 5 are written out in words: one, two, three, four,
# five, then there are 3 + 3 + 5 + 4 + 4 = 19 letters used in total.
# If all the numbers from 1 to 1000 (one thousand) inclusive were written out
# in words, how many letters would be used?
# NOTE: ... |
ec8602db7b949353fae1adf91055ed7a5f6aef40 | yeurch/project-euler | /euler79.py | 1,063 | 3.515625 | 4 | # Passcode derivation
# Problem 79
# A common security method used for online banking is to ask the user for three
# random characters from a passcode. For example, if the passcode was 531278,
# they may ask for the 2nd, 3rd, and 5th characters; the expected reply would
# be: 317.
#
# The text file, keylog.txt... |
bb610d381c5afe70931703c0f692ce3d9bc10a98 | yeurch/project-euler | /euler12.py | 1,415 | 3.5625 | 4 | # Highly divisible triangular number
# Problem 12
# The sequence of triangle numbers is generated by adding the natural numbers.
# So the 7th triangle number would be 1 + 2 + 3 + 4 + 5 + 6 + 7 = 28. The
# first ten terms would be:
# 1, 3, 6, 10, 15, 21, 28, 36, 45, 55, ...
#
# Let us list the factors of ... |
5581adf9861ec65de622f7890c516e960326bd93 | yeurch/project-euler | /euler34.py | 740 | 3.734375 | 4 | # Digit Canceling Fractions
# Problem 33
# 145 is a curious number, as 1! + 4! + 5! = 1 + 24 + 120 = 145.
#
# Find the sum of all numbers which are equal to the sum of the factorial
# of their digits.
#
# Note: as 1! = 1 and 2! = 2 are not sums they are not included.
import time, math
start = time.time()... |
43b2bda80fa8ebfebedf9220b8a26c2657280f2a | sboyett31/AdventOfCode2019 | /Day_3/part_2.py | 1,523 | 3.9375 | 4 | # Day 3 part 2
# Wire 1 will have a list of tuples that contains the points it occupies
# Wire 2 will create a list of tuples that contains the points it intersects with Wire 1
# List of intersections will be looped over to find the shortest steps
import time
def main():
path1, path2 = get_paths()
intersections = ge... |
1d16c5bd47e4e2f1d34a5a14b175975944c56aab | sboyett31/AdventOfCode2019 | /Day_4/part_2.py | 901 | 3.5 | 4 | # Day 4 Part 1
# Six-digit number
# Value is within the range vien in puzzle input
# Two adjacent digits are the same like 22 in 122345 but three or more are not
# Going from left to right, the digits never decrease
START = 153512
END = 630395
def main():
ans = 0
for i in range(START, END):
if isIncr(i):... |
6ff097a3ca59c4168b7561d41fac1d80bc935b95 | truboprovod4uk/My-Project | /sitka.py | 4,433 | 4.0625 | 4 | #дана програма рисує координатну сітку, та трубу в розрізі
from tkinter import *
#зміщення полота Canvas та усього що на ньому відображено на величини dx та dy
dx=30
dy=30
HEIGHT = 800 # довжина осі X
WIDTH = 800 # довжина осі Y
#створюємо батьківське вікно, та задаєм його параметри
root = Tk()
root.title("create ci... |
9c350eafd25e8544b908e638430e86f6079b3cd4 | jasmeet0915/MachineLearning-Algos-from-Scratch | /linear_regression/one_var/predict.py | 1,360 | 3.96875 | 4 | import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
import train
dataset = pd.read_csv("/home/singh/PycharmProjects/MachineLearning_from_Scratch/Datasets/linear_regression"+
"/one_var/train.csv")
print("Shape of dataset: " + str(dataset.shape))
data_x = dataset['x'][:50]
data... |
26a487d08e6c8e30f3715818fa18d6f956709937 | caianne/mc102 | /labs/lab16.py | 2,083 | 3.5 | 4 | # Nome: Anne Feng Cai; RA: 261026
# Descrição: Funções da biblioteca de conjuntos
# Funcao: pertence
#
# Parametros:
# conj: vetor contendo o conjunto de entrada
# num: elemento a ser verificado pertinencia
#
# Retorno:
# True se num pertence a conj e False caso contrario
#
def pertence(conj, num):
if num in... |
942883633e4d720270a3a708fbdf9ac30f61f29f | caianne/mc102 | /exercicios/Aula 20/contaletra.py | 561 | 3.8125 | 4 | # Slide 10 e 15 da Aula 20
import string
def verifica(letra,pontuacao):
if letra in pontuacao:
return 2
if letra==' ':
return 2
return 3
stri=input()
stri=stri.lower()
cont={}
pontuacao=string.punctuation
for i in range(len(stri)):
if verifica(stri[i],pontuacao)==3:
if stri[i] in... |
e56b35e7b7792226d0c954861bf61f5c0814b80b | caianne/mc102 | /exercicios/Aula 4/Slide 39.py | 377 | 3.5625 | 4 | #Slide 38 da Aula 4
n1=(input())
n2=(input())
n3=(input())
if n2>n1:
if n3>=n2:
print(n3, n2, n1)
if n2>n3:
if n3>=n1:
print(n2, n3, n1)
if n1>n3:
print(n2, n1, n3)
if n1==n2:
if n3>=n2:
print(n3, n2, n1)
if n2>n3:
print(n2, n1, n3)
if n1>n2:
if n2>=n3:
print(n1, n2, n3)
if n3>n2:
if n3>=n1:... |
c4a29bafc6e4f2823974579a54bc0f1f8530796a | caianne/mc102 | /exercicios/Aula 14/palindromo.py | 1,112 | 3.984375 | 4 | #Slide 18 da Aula 14
def letminmai(str):
str=str.replace('A','a')
str=str.replace('B','b')
str=str.replace('C','c')
str=str.replace('D','d')
str=str.replace('E','e')
str=str.replace('F','f')
str=str.replace('G','g')
str=str.replace('H','h')
str=str.replace('I','i')
str=str.repla... |
af9d27fc03038188f0742a5f3b828bec6cb8dade | caianne/mc102 | /exercicios/Aula 9/Slide_22.py | 286 | 4.03125 | 4 | #Slide 22 da Aula 09
n=int(input('Me diga quantas linhas da escada numérica tu queres: '))
linha=1
while linha<=n:
coluna=0
numero=1
while coluna<linha:
print(str(numero)+' ', end='')
numero=numero+1
coluna=coluna+1
linha=linha+1
print('')
|
012c1220dec85890ce2f35d03fd18b3cbb804edf | caianne/mc102 | /exercicios/Aula 11/Slide_33.py | 307 | 3.6875 | 4 | #Slide 33.py
def fatorial(n):
resultado=1
for i in range(2,n+1):
resultado=resultado*i
return resultado
for n in range(1,21):
if n<=1:
print('1, ', end='')
elif n>1 and n!=20:
print(str(fatorial(n))+', ', end='')
elif n==20:
print(str(fatorial(n)))
|
dbcdd881dba1e3e071c5784c46931a3f6868c7e9 | caianne/mc102 | /exercicios/Aula 8/Slide_28.py | 255 | 3.640625 | 4 | #Slide 28 da Aula 08
C=int(input('Digite o valor da constante C: '))
for x1 in range(0,C+1):
for x2 in range(0,C+1-x1):
for x3 in range(0,C+1-x1-x2):
x4=C-x1-x2-x3
print(str(x1)+', '+str(x2)+', '+str(x3)+', '+str(x4))
|
f4ec75527a590154109325705c90c9192b834349 | caianne/mc102 | /labs/lab20.py | 984 | 4.125 | 4 | # Laboratorio 20 - Sudoku
# Funcao: print_sudoku
# A funcao imprime o tabuleiro atual do sudoku de forma animada, isto e,
# imprime o tabuleiro e espera 0.1s antes de fazer outra modificacao.
# Voce deve chamar essa funcao a cada modificacao na matriz resposta, assim
# voce tera uma animacao similar a apresentada no ... |
72362c959ee3e7895dcc38a93cde35fbdf1d93cf | benochi/18.2python_data_structures.py | /python_challenges31-40.py | 5,468 | 4.21875 | 4 | def truncate(phrase, n):
"""Return truncated-at-n-chars version of phrase. If the phrase is longer than, or the same size as, n make sure it ends with '...'
and is no longer than n. >>> truncate("Hello World", 6)
'Hel...' >>> truncate("Problem solving is the best!", 10)
'Problem...' >>> truncate("Yo", 100) 'Yo'... |
dbc1823387ff1ef86d873f3012db829973979b92 | molssi-seamm/seamm_widgets | /seamm_widgets/scrolled_columns.py | 6,615 | 3.546875 | 4 | # -*- coding: utf-8 -*-
"""A ttk-based widget for columns of widgets, with fixed titles and scrolling
This widgets has two areas: a row of titles across the top and a scrolled frame
below it. It is used to make a table of widgets with fixed column headers.
"""
import seamm_widgets as sw
import tkinter as tk
from tki... |
080245377e876231aea6b5e6570b3a4733115c2b | nineaz/Python | /exo2/t.py | 191 | 3.859375 | 4 | a = input("Entrez un chiffre : ")
b = input("Entrez un autre chiffre : ")
print "La somme de a et b est = ", a+b
#on met un input au lieu dun raw_input sinon il calcule la somme des strings |
8017f573ec46392ab03568ff41881c2e2bf145e2 | saks007/Python-testing | /calling module.py | 399 | 3.9375 | 4 | import calc
x = input('which calculator function would you like to do now? \n 1 for addition \n 2 for sub \n 3 for mul \n 4 for divition:')
# print x
y = int(input('enter value for A:'))
z = int(input('enter value for B:'))
if x == 1:
t = calc.add(y, z)
elif x == 2:
t = calc.sub(y, z)
elif x == 3:
t = c... |
b780a4e4a35357df85faf8ae6fa34ee593346306 | Shehu-Muhammad/Python_College_Stuff | /Python Stuff/WhileProgram.py | 112 | 3.546875 | 4 | #While Program
#Shehu Muhammad
#February 5, 2018
index = 10
i = 0
while(i < index):
print(i, i*i, sep=" ")
i+1
|
5dccb6ae3e41d33d52debb0d3d1dd8e312db7892 | Shehu-Muhammad/Python_College_Stuff | /Python Stuff/DewDrop.py | 522 | 3.984375 | 4 | #Dew Drop
#Shehu Muhammad
#February 2, 2018
cost = float(input("What was the cost of the meal? "))
tip = cost * 0.182
finalCost = cost + tip
print("The tip is 18.2% of $", format(cost,'.2f'), " so it came out to $", format(tip,'.2f'), ".", sep="")
print("The final cost of the meal is ", format(finalC... |
5c4c4b8c30d09c8a7163d24ff3030fa4b3e0ce34 | Shehu-Muhammad/Python_College_Stuff | /Problem4_CupcakeRequest.py | 459 | 4.125 | 4 | # Shehu Muhammad
# Problem 4 -Requests the number of cupcakes ordered and displays the total cost
# May 7, 2018
orders = int(input("What are the total number of cupcake orders? "))
cost = 0
small = 0.75
large = 0.70
if(orders <= 99 and orders>=1):
cost = cost + (orders*small)
elif(orders >= 100):
cost = cost +... |
52f5d2791e39104aba5f6cfcc90a29eac4d8a693 | Shehu-Muhammad/Python_College_Stuff | /Python Stuff/Rowing.py | 543 | 4.28125 | 4 | #Rowing Program
#Shehu Muhammad
#February 5, 2018
rower1 = int(input("Input weight of rower one: "))
rower2 = int(input("Input weight of rower two: "))
weight = rower1 + rower2
#if((weight >= 300) and (weight <=400)):
#print("You are on the team")
#else:
#print("You are not on the team")
#if((weight >= 300... |
05228bb597c8d13f1e2e6427a2a307e0abf2ee02 | Shehu-Muhammad/Python_College_Stuff | /Python Stuff/Guess.py | 1,156 | 4.125 | 4 | # Guess my number
# Shehu Muhammad
import random
import math
random.seed()
randomNumber = math.floor(random.random() * 100) + 1 # generates a random number between 1 and 100
guess = 0 # initializes guess to zero
count = 0 # initiali... |
1e524b0bbf372bc5bf359cbb1aae52c12e73a9f8 | phucle2411/LeetCode | /Python/word-break-ii.py | 786 | 3.578125 | 4 | # https://leetcode.com/problems/word-break-ii/
class Solution(object):
def wordBreak(self, s, wordDict):
"""
:type s: str
:type wordDict: List[str]
:rtype: List[str]
"""
def search(index):
if index == len(s): return [[]]
if index in memo: ret... |
4b602d0278ed4e3ed2cf1e51316438abf6ec573e | phucle2411/LeetCode | /Python/3sum-smaller.py | 698 | 3.71875 | 4 | # https://leetcode.com/problems/3sum-smaller/
class Solution:
def threeSumSmaller(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
def twoSumSmaller(index, target):
triplets = 0
l, r = index, len(nums) - 1
... |
75e5c17431429a7a12de20fe283cf1db823ca9f6 | phucle2411/LeetCode | /Python/divide-two-integers.py | 608 | 3.578125 | 4 | # https://leetcode.com/problems/divide-two-integers
class Solution:
def divide(self, dividend, divisor):
"""
:type dividend: int
:type divisor: int
:rtype: int
"""
neg = (dividend < 0) ^ (divisor < 0)
dividend, divisor = abs(dividend), abs(divisor)
r... |
949710d520f85117c00c29064d989772fb8b236e | phucle2411/LeetCode | /Python/roman-to-integer.py | 584 | 3.65625 | 4 | # https://leetcode.com/problems/roman-to-integer
m = {
'I': 1,
'V': 5,
'X': 10,
'L': 50,
'C': 100,
'D': 500,
'M': 1000
}
class Solution:
def romanToInt(self, s):
"""
:type s: str
:rtype: int
"""
num = 0
highest = 1
for i in rang... |
3022173326f6772d48600dd102018a292d4799a6 | phucle2411/LeetCode | /Python/house-robber-iii.py | 619 | 3.625 | 4 | # https://leetcode.com/problems/house-robber-iii/
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def rob(self, root):
"""
:type root: TreeNode
:rtype: int
... |
ce636c69071b7149c24eb6016ee5c60b46908340 | phucle2411/LeetCode | /Python/longest-substring-with-at-most-two-distinct-characters.py | 804 | 3.5 | 4 | # https://leetcode.com/problems/longest-substring-with-at-most-two-distinct-characters/
class Solution:
def lengthOfLongestSubstringTwoDistinct(self, s):
"""
:type s: str
:rtype: int
"""
l, r = 0, 0
substring_chars = set()
freq = {}
longest_substring... |
c67589b914fcc7d29a08f9b718a00d6027d4054d | phucle2411/LeetCode | /Python/maximize-distance-to-closest-person.py | 1,307 | 3.765625 | 4 | # https://leetcode.com/problems/maximize-distance-to-closest-person/
class Solution:
def maxDistToClosest(self, seats):
"""
:type seats: List[int]
:rtype: int
"""
distance_to_left = [0] * len(seats)
distance_to_right = [0] * len(seats)
dist = 0
seat_... |
cf577e3983b20033ed08a0b9845bdd342444f913 | phucle2411/LeetCode | /Python/strobogrammatic-number-ii.py | 1,025 | 3.546875 | 4 | # https://leetcode.com/problems/strobogrammatic-number-ii/
class Solution:
def findStrobogrammatic(self, n):
"""
:type n: int
:rtype: List[str]
"""
def search(index):
if n % 2 == 0 and index == n // 2:
numbers.append(''.join(number))
... |
627579ff947682fb447d8509b4641d81badd6949 | phucle2411/LeetCode | /Python/cat-and-mouse.py | 1,504 | 3.578125 | 4 | # https://leetcode.com/problems/cat-and-mouse/description/
class Solution:
def catMouseGame(self, graph):
"""
:type graph: List[List[int]]
:rtype: int
"""
mem = {}
optimal_strategy = self.mouse_move(1, 2, mem, graph)
if optimal_strategy == -1: return 2
... |
dc37249b3bfce64f67c89a05096166b0f48ea0f2 | phucle2411/LeetCode | /Python/palindrome-permutation.py | 465 | 3.5 | 4 | # https://leetcode.com/problems/palindrome-permutation/
class Solution:
def canPermutePalindrome(self, s):
"""
:type s: str
:rtype: bool
"""
n = len(s)
odds = 0
freq = {}
for c in s:
if c not in freq:
freq[c] = 0
... |
d86f140ea87fbbea8bdbd5682122ce0a2edc0216 | phucle2411/LeetCode | /Python/kth-largest-element-in-an-array.py | 463 | 3.625 | 4 | # https://leetcode.com/problems/kth-largest-element-in-an-array/
from heapq import *
class Solution(object):
def findKthLargest(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: int
"""
heap = []
for num in nums:
if len(heap) < k: ... |
b2761e8d089da8e1a48e9164c87c58b40c268987 | phucle2411/LeetCode | /Python/max-stack.py | 1,092 | 3.796875 | 4 | # https://leetcode.com/problems/max-stack/
class MaxStack:
def __init__(self):
"""
initialize your data structure here.
"""
self.s = []
def push(self, x):
"""
:type x: int
:rtype: void
"""
if not self.s: self.s.append((x, x))
el... |
516e685372cac627ea2f59cce285d4ac80d71ac2 | phucle2411/LeetCode | /Python/sort-colors.py | 822 | 3.609375 | 4 | # https://leetcode.com/problems/sort-colors/
class Solution:
def sortColors(self, nums):
"""
:type nums: List[int]
:rtype: void Do not return anything, modify nums in-place instead.
"""
if len(nums) < 2: return
l, r = 0, len(nums) - 1
while l < r:
... |
baa9caedb73f4ee117539781fc1f265990885c53 | phucle2411/LeetCode | /Python/insert-delete-getrandom-o1-duplicates-allowed.py | 1,997 | 3.734375 | 4 | # https://leetcode.com/problems/insert-delete-getrandom-o1-duplicates-allowed/
import random
class RandomizedCollection(object):
def __init__(self):
"""
Initialize your data structure here.
"""
self.items = []
self.contained_items = {}
def insert(self, val):
... |
82236885ee1a6d9ae625ca778f238fb7727f279f | phucle2411/LeetCode | /Python/word-search-ii.py | 2,872 | 3.78125 | 4 | # https://leetcode.com/problems/word-search-ii/
class TrieNode:
def __init__(self):
self.children = {}
self.end = False
class Trie:
def __init__(self):
self.root = TrieNode()
def add(self, word):
root = self.root
for c in word:
if c not in root.childr... |
55d3c95334cace430cb98a0fc2bd69d28f724d0b | phucle2411/LeetCode | /Python/add-two-numbers.py | 1,027 | 3.828125 | 4 | # https://leetcode.com/problems/add-two-numbers
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def addTwoNumbers(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ... |
8ae6284b6d9dc674bc132572e2efb3ce5f297561 | phucle2411/LeetCode | /Python/binary-tree-level-order-traversal-ii.py | 809 | 3.953125 | 4 | # https://leetcode.com/problems/binary-tree-level-order-traversal-ii
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
from collections import deque
class Solution:
def levelOrderBottom(self, root):
... |
960a4f9d4d1b7c9c05079cb90c51b714b43a26f9 | phucle2411/LeetCode | /Python/self-dividing-numbers.py | 438 | 3.578125 | 4 | # https://leetcode.com/problems/self-dividing-numbers/
class Solution:
def selfDividingNumbers(self, left, right):
"""
:type left: int
:type right: int
:rtype: List[int]
"""
sdn = []
for i in range(left, right + 1):
for d in map(int, str(i)):
... |
10e438c2f6f4589433b5d7ab0b572dfca1b47a2e | phucle2411/LeetCode | /Python/valid-sudoku.py | 1,397 | 3.671875 | 4 | # https://leetcode.com/problems/valid-sudoku
class Solution:
def isValidSudoku(self, board):
"""
:type board: List[List[str]]
:rtype: bool
"""
for i in range(9):
if not self.is_valid_row(board, i):
return False
if not self.is_valid_co... |
8dbf7c39cc28e7b37dbe31009ab30874e57800fd | bhatvisu1000/uconnect | /myapp/src/com/uconnect/poc/socket_server02.py | 1,927 | 3.90625 | 4 | import socket, sys
# Create a TCP/IP socket
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
#Then bind() is used to associate the socket with the server address. In this case, the address is localhost, referring to the current server, and the port number is 10000.
# Bind the socket to the port
myport = 1000
... |
f11019976e230dcf80a95de2f8ea74583a3ebb35 | rabialex/cryptopal-challenges | /Set_1/challenge6.py | 1,108 | 3.578125 | 4 | def partition(string, keySize):
if type(string) != str or type(keySize) != int:
raise TypeError("Inputs are defined as string and integers not %s and %s" % type(string), type(keySize))
partDict = dict((i, []) for i in range(keySize))
for idx in range(len(string)):
i = idx % keySize
... |
5a1e50c525e772ece7944a9c7609ac8cb5ad79bb | CoderDojoNavan/python | /basics/4_inputs.py | 985 | 4.125 | 4 | """4: Inputs"""
# Sometimes you might want to ask the user a question. To do that, we use
# a special function called `input`. Functions are covered in `5-functions.py`.
# You can ignore the # pylint comment, it is there to tell tools which analyze
# the code that in fact everything is OK with this line.
days = 365 ... |
4c677ac39f92c0590d55c4a6e434dcb1bbbd4810 | Mrliuyuchao/Interview | /面试题整合/对撞指针/三数之和.py | 875 | 3.59375 | 4 | from typing import List
def threeSum(nums:List[int]) -> List:
nums.sort()
result = []
# 固定C位
for i in range(len(nums) - 2):
if i > 0 and nums[i] == nums[i-1]:
continue
left = i+1
right = len(nums) -1
while left < right :
node = nums[i] + nums[left]... |
c849837aa9f45daf973c28c2eeff1de21c2e6ec8 | Mrliuyuchao/Interview | /面试题整合/快慢指针/双指针去掉指定值.py | 444 | 3.84375 | 4 | from typing import List
class Solution:
def removeDuplicated(self,nums:list,val:int):
show = 0
fast = 0
while fast <len(nums):
if nums[fast] == val:
fast += 1
else:
nums[show] = nums[fast]
show += 1
fast ... |
d504574c6777fe91c5d7d21e029e9e4646f008a8 | alabid/simpleskiplist | /skipset.py | 3,032 | 3.53125 | 4 | """
skipset.py
Contains skipset algorithms
all encapsulated in SkipSet
class
"""
import math
import random
from skipnode import *
class SkipSet:
# constants
MAX_LEVEL = 6
p = 0.5
# initializer
def __init__(self):
self.level = 0
self.header = SkipNode(SkipSet.MAX_LEVEL, None)
... |
731f25ff29b0a353699eb1a22f74fc1817036d7c | masood-cloud/Inheritance | /Inheritance.py | 607 | 3.90625 | 4 | class student:
def __init__(self, name, contact):
self.name = name
self.contact = contact
def getdata(self):
print('Accepting Data')
self.name = input("Enter your name")
self.contact = input("Enter Contact")
def putdata(self):
print('this is the... |
188747c9775e2c53ec9e2b4254bb64727d5c32d9 | Bryanromerou/csc401_hw1 | /main.py | 2,662 | 3.6875 | 4 | import sys
import random
def match_maker(men,women):
print("\nBegining the match making")
print("------------------------------------------------------")
matched_women = {}
free_men = []
for man in men:
free_men.append([man,0])
# free_men.append(["M3",0])
while(free_men):
... |
fc675ad893aa55d5373025380ede2064085ddbab | meredithlar/PythonWorkshop | /sd_highs.py | 437 | 3.53125 | 4 | import json
def print_sd_highs(weather_dict):
sd_dict = weather_dict["San Diego, CA"]
july_list = sd_dict["6"]
for day_dict in july_list:
high = str(day_dict["high"])
day = str(day_dict["date"])
print("July " + day + ": High of " + high)
def main():
file = open("we... |
3b3e5828cb47f9ea88b0bca054ac982ac902df30 | ninaReb/ExerciciosPy | /primeiro_desafio.py | 924 | 4.03125 | 4 | # ***Primeiro desafio***
# Você recebe uma lista de 300 números ordenados por ordem crescente.
# Sua tarefa é achar um número aleatório informado pelo usuário da
# maneira mais eficiente possível.
#digitar os números do array. ex: 1,2,3,4
# def get_array():
# text = input("digite os numeros")
# my_array = tex... |
78b7f69d1513f3d252d07e30f3970be2beec094b | benjaminhuanghuang/dl-study | /keras_first_network.py | 2,038 | 4.78125 | 5 | '''
Develop Your First Neural Network in Python With Keras Step-By-Step
https://machinelearningmastery.com/tutorial-first-neural-network-python-keras/
The steps you are going to cover in this tutorial are as follows:
Load Data.
Define Model.
Compile Model.
Fit Model.
E... |
7db5e1d3a7b64c53874f412f470b345b8c3fd67d | Alegruz/Game-AI-Track | /3_2/CSE304_ALGORITHM_ANALYSIS/labs/05_backtracking/m_coloring.py | 1,572 | 3.84375 | 4 | def is_promising(is_connected: list[list[bool]], vertex_colors: list[int], index: int):
is_switch: bool = True
j_index: int = 0
while j_index < index and is_switch:
if is_connected[index][j_index] and vertex_colors[index] == vertex_colors[j_index]:
is_switch = False
j_index += 1... |
cd8688033fe390f2e35b73adfef239305e19871e | omarghar/calculator-python | /new calculator python.py | 880 | 3.671875 | 4 | from tkinter import*
from tkinter import ttk
root=Tk()
root.title("calculator")
def insert (text):
if text != "=":
En.insert("end",text)
else:
try:
operation= eval(En.get())
En.delete(0,"end")
En.insert(0,"{}".format(operation))
except:
En.d... |
d7e7651839e8618083715f3c05d709e4de0824ff | WangQing-hub/CSP-python | /344. 反转字符串.py | 781 | 3.953125 | 4 | """
编写一个函数,其作用是将输入的字符串反转过来。输入字符串以字符数组 s 的形式给出。
不要给另外的数组分配额外的空间,你必须原地修改输入数组、使用 O(1) 的额外空间解决这一问题。
示例 1:
输入:s = ["h","e","l","l","o"]
输出:["o","l","l","e","h"]
示例 2:
输入:s = ["H","a","n","n","a","h"]
输出:["h","a","n","n","a","H"]
题解:
双指针
"""
from typing import List
class Solution:
def reverseString(self, s: List[str]... |
c31a1516079d2f68243566c2b61de40fe436bae7 | Vitali12/FracAnalysis | /Point.py | 9,825 | 4.28125 | 4 | __author__ = 'ryshackleton'
import math
class Point2:
"""Models a point in 2D"""
def __init__(self, x=0.0, y=0.0):
"""
Initializes a 2d point
:param x: x value as a float
:param y: y value as a float
:return: None
"""
self._x = float(x)
self._y ... |
63bf4b1c1052ecc6baf116dea8adbc14df4ae4d2 | Georgemburu/MACHINE-LEARNING | /noframework/py/streetlights/index.py | 1,102 | 3.515625 | 4 | '''
[0,1,0]=>stop
[1,0,1]=>walk
[0,0,1]=>walk
[0,1,1]=>stop
[1,1,1]=>stop
[0,0,0]=>walk
[1,0,0]=>walk
[1,1,0]=>stop
'''
'''
0 => stop
1 => walk
'''
import numpy as np
weights = np.array([0.1,-0.5,0.5])
alpha = 0.01
trainingData = np.array([
[0,0,0],
[0,1,1],
[0,0,1],
[1,1,1],
[0,1,1],
[1,0,1],
... |
fa87ba48ce7daf3854eb1f614b40a6b96271c38e | gokayozcoban/binary_2 | /from int to binary and from binary to int.py | 219 | 3.9375 | 4 |
# from integer to binary and from binary to integer
veri = int(input("Sayı girin: "))
if veri == veri:
print(bin(veri)[2:])
veri2 = input("Kodu Girin: ")
if veri2 == veri2:
print(int(veri2,2))
|
3a17e1717321533b96759ff24345b879c3932625 | frdenzer/personummer-generator | /main.py | 5,708 | 3.75 | 4 | """
Generate a valid number for the German Personalausweis
"""
import argparse
import datetime
import string
from random import randint, choice
from pandas import Timestamp
parser = argparse.ArgumentParser(description='Generate a valid number for the German Personalausweise')
parser.add_argument('--verbose', '-v', n... |
190149cd217996504c8ed54bb261b17bbe25ad06 | yyjazsf/learn-python3 | /mydict_test.py | 186 | 4.09375 | 4 | def abs(n):
'''
Function to get absolute value of number.
Example:
>>> abs(1)
1
>>> abs(-1)
1
>>> abs(0)
0
'''
return n if n >= 0 else (-n)
|
59786a99b74c3ee1492b8b936d684ab026823aae | Stanshiki246/Introduction-to-Programming---Lab | /quiz 1 - array number 1.py | 246 | 3.953125 | 4 | # Group 5 - Pasha, Stanley,Naufal, Wely
#Upside down pythagorean triangle
x= int(input("Enter the number of row(s):\n"))
#Variable for asterisk symbol
aster="*"
#Start triangle looping
for i in range(0,x+1):
print( aster*(x-i)+" "*i)
|
62bfcfc3dbf8f2ff84840088a88364cc8c2b7c86 | sonisanskar/-MNITagainstExams | /tweets.py | 660 | 3.5625 | 4 | # Open/Create a file to append data
import csv
csvFile = open('blm_final1.csv', 'a')
#Use csv Writer
csvWriter = csv.writer(csvFile)
#Extracting tweets about #BlackLiveMatters and writing into a csv file.
# '-filter:retweets' used to filter out retweets.
for tweet in tweepy.Cursor(api.search,q='#MNITagainstExams -filt... |
910b2e2e62c5fdc50dc21b603585cafc8dee09a3 | swetabedmutha09/Assignment1 | /theautil.py | 1,091 | 3.546875 | 4 | #Copied this entire file from Professor Abram hindle theanets tutorial
import numpy as np
import collections
def joint_shuffle(arr1,arr2):
assert len(arr1) == len(arr2)
indices = np.arange(len(arr1))
np.random.shuffle(indices)
arr1[0:len(arr1)] = arr1[indices]
arr2[0:len(arr2)] = arr2[indices]
d... |
000037172abd7825e09c6087e772c7aae49c4816 | muzan1996/python | /salary.py | 125 | 3.734375 | 4 | hours = input ('please add number of hours')
rate = input ('please add rate')
pay = int (hours) * int (rate)
print (pay)
|
405f015135f8c372cd582934b03513be3d9af935 | OmarMuhammedAli/6.006 | /week1/peakFinding2D.py | 1,109 | 3.65625 | 4 | def max_in_col(arr, rows, col):
max_value, max_index = 0, 0
for i in range(rows):
if max_value < arr[i][col]:
max_value, max_index = arr[i][col], i
return max_value, max_index
def find_peak_logic(arr, left_col, right_col):
rows, cols = len(arr), len(arr[0])
mid_col = (left_col+r... |
714884c67c8d796619d74b690dfdfa3c7fe34503 | atulrana98/py_prog | /sch_admin_project.py | 1,073 | 3.921875 | 4 | import csv
def write_into_csv(info_list):
with open('student_info.csv', 'a', newline='') as csv_file:
writer = csv.writer(csv_file)
if csv_file.tell() == 0:
writer.writerow(["Name", "Age", "Contact Number", "Email ID"])
writer.writerow(info_list)
if __name__ == '__main... |
b353471d9e07a133745f94e4396c79ecff9377c8 | Hamza-Bik/pythonSwim | /script2.py | 537 | 3.84375 | 4 | print("Hello there ")
print("<-------------------------------------->")
#reverse:
str="ytreza"
s=""
for i in range(len(str)):
s += str[len(str)-i-1 : len(str)-i]
print(s)
print("<-------------------------------------->")
def stars():
x = input("how many stars you want ?")
s=''
output=''
for i ... |
7dbd1024a4dcc8e7bbeb01274c2804ca092e325a | OmkarKamat869/ShapeAI-Project | /ShapeAI_Project/Project1.py | 311 | 3.796875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sat Jul 3 23:01:22 2021
@author: Omkar Kamat
"""
# Project 1 = Program to generate md5 hash of the given data
import hashlib
word=input("Enter the word You want to encode = ")
enc=word.encode("utf-8")
digest=hashlib.md5(enc.strip()).hexdigest()
print(digest) |
2265d032ca4fc7148a6ff610e6fdd3d095484c5f | charukiewicz/Numerical-Methods | /convergence.py | 1,501 | 4.125 | 4 | # -*- coding: utf-8 -*-
"""
@author: Christian Charukiewicz (netid: charuki1)
This compares the rates of convergence between the Newton and Secant methods.
The program will print output values and display a plot in matplotlib.
More info:
- http://en.wikipedia.org/wiki/Newton's_method
- http://en.wi... |
99c1b9023abcf954ab2906c4ecbc4063e89b510e | CAECOMP/provas | /S08 - Padrões de projeto/abstract_factory/computador.py | 496 | 3.53125 | 4 | from abc import ABC, abstractmethod
from teclado import TecladoAbstrato
class ComputadorAbstrato(ABC):
@abstractmethod
def detalhes_do_hardware(self) -> str:
pass
class ComputadorModeloA(ComputadorAbstrato):
def detalhes_do_hardware(self) -> str:
return "Processador Core 2 + 8G Memória R... |
4d36c476662edd7d3562e58f2ac408661299efcc | CAECOMP/provas | /S08 - Padrões de projeto/grasp-creator/pedido.py | 532 | 3.5625 | 4 | from typing import List
from pedido_item import PedidoItem
from produto import Produto
class Pedido:
def __init__(self):
self.__items: List[PedidoItem] = []
def adicionar_item_na_compra(self, produto: Produto):
item: PedidoItem = PedidoItem(produto=produto)
self.__items.append(item)
... |
e20aaeab905634c5b0f26e61b48c6cfd7e2476b6 | LavanyaJayaprakash7232/python-code---string | /twowordstr.py | 350 | 3.765625 | 4 | '''
Get a two word string
Return True = When the first letter of two words is same
else return False
'''
#Function definition - animal_crackers
def animal_crackers(str1):
str2 = str1.split()
return str2[0][0] == str2[1][0]
#User input
a = input("Enter the string\n ")
output = animal_crackers(a)
... |
64036bd2592ca9ec1ba63056e02965902670f8f5 | Junctionzc/learncoding | /python/book/CorePythonProgramming/numstr.py | 1,602 | 3.875 | 4 | #!/user/bin/env python
class NumStr(object):
def __init__(self, num = 0, string = ''):
self.__num = num
self.__string =string
def __str__(self):
return '[%d :: %r]' % (self.__num, self.__string)
__repr__ = __str__
def __add__(self, other):
if ... |
d15f5b05cd08210600dcce2a1d29cc2a5d3e0c2e | Powana/AoC20 | /Day 7/main.py | 2,128 | 3.515625 | 4 | with open("input.txt") as f:
input_lines = f.readlines()
# Not the prettiest of solutions but it was easy to work with
gold = "shiny gold"
def contains_gold(bags_dict, bag):
if bag is gold:
return True
if not bag or bag not in bags_dict.keys():
return False
if gold in [x for x, _ in b... |
40bf90b5cc71dffbc46bfbccfc04d89862d16433 | UskovaKate/Coursework | /2-я часть/9.py | 961 | 3.703125 | 4 | #Создать прямоугольную матрицу A, имеющую N строк и M столбцов со случайными элементами.
#Определить, сколько нулевых элементов содержится в верхних L строках матрицы и в левых К столбцах матрицы.
import numpy as np
N = 6
M = 2
L = np.random.randint(0, 10)
K = np.random.randint(0, 10)
A = np.random.randint(low=-4, hi... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.