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 |
|---|---|---|---|---|---|---|
bb08c38852491a5321ae1c11c198c5eaabd9b2e2 | kashishy/MLTraining | /mlpackage01/MLPractical23.py | 313 | 3.8125 | 4 | a = 10
print(type(a))
a = 12.5
print(type(a))
a = "IITK"
print(type(a))
import numpy as np
nparr = np.array([1, 2, 3])
print(type(nparr))
# datatype of elements of the array
print("nparr.dtype=", nparr.dtype)
# number of rows and column
print("nparr.shape = ", nparr.shape)
print("nparr.size = ", nparr.size)
|
aeaa4fef7cafc1481ba2c629028d3f6df945d18d | kashishy/MLTraining | /mlpackage01/MLPractical63.py | 634 | 3.90625 | 4 | from sklearn.cluster import KMeans
import pandas as pd
import numpy as np
# Importing the dataset
filename = 'KMeansData.csv'
data = pd.read_csv(filename)
print("Kmeans of sklearn")
# Number of clusters
kmeans = KMeans(n_clusters=3)
# getting the values and plotting
f1 = data["V1"].values
f2 = data["V2"].values
X = ... |
f4581254b7e170a7f6b016e3c2756bab25783faf | Vivekreddyd/Leet_code | /tinder.py | 1,090 | 3.921875 | 4 | # Prompt: Write a function that returns the longest,
# contiguous increasing sequence(s) in a given list of numbers.
#
# f([1, 3, 4, 7, 0, 1, 2, 3]) = [[1, 3, 4, 7], [0, 1, 2, 3]]
# f([1, 5, 8, 0, 9]) = [[1, 5, 8]]
def longest_continuous (list_input):
min_ind,max_ind=[],[] #store max indexes
min_val=0
max1... |
229539f8b2aa1948cbda43e3d055edf811cbbe98 | Vivekreddyd/Leet_code | /keyboard_row.py | 1,395 | 3.65625 | 4 | # class Solution(object):
# def findWords(self, words):
"""
:type words: List[str]
:rtype: List[str]
"""
words=["Hello","Alaska","Dad","Peace"]
final = []
r1 = ['q', 'w', 'e', 'r', 't', 'y', 'u', 'i', 'o', 'p']
r2 = ['a', 's', 'd', 'f', 'g', 'h', 'j', 'k', 'l']
r3 = ['z', 'x', 'c', 'v', 'b', 'n', 'm']
# p=re.compil... |
517cff5cb7ad0680de6d860b7dec80f7428c33ed | Varobinson/Projects | /python 102/even-numbers.py | 112 | 3.6875 | 4 | numbers = [2, 5, 9, 4, 1]
even_numbers =[]
for number in numbers:
if number % 2 == 0:
print(number) |
8a3f5679e60dc7af3d0f8cd5087a9ae89602e111 | faridaatei/python | /python/triangle1.py | 511 | 3.8125 | 4 | class Triangle:
base = 0
height = 0
hypotunous=0
def ____(self,base,height):
self.base = base
self.height=height
self.hypotunous=hypotunous
def area(self):
return 0.5*self.base*self.height
def perimeter(self):
return 2*(self.base +self.height+hypotunous)
small = Triangle(20,30)
l... |
d6f7ff769a665d86d49f920149ca12fdfce5fade | rlazarus/MUSS | /muss/channels.py | 1,690 | 3.59375 | 4 | class Channel(object):
def __init__(self, name):
if name in _channels:
raise ValueError("There's already a channel named {}.".format(name))
_channels[name] = self
self.name = name
self.players = set()
def __repr__(self):
return "Channel({})".format(self.name)... |
ae638c7d11b003b8e31e8f1b21de7753dbb67f60 | msafakdal1/Python- | /armstronSayısı.py | 355 | 3.828125 | 4 | toplam = 0
sayı = int(input("Bir sayı giriniz :"))
basamak = int(input("Basamak miktarını giriniz :"))
sayı1 = sayı
while sayı != 0:
sonuc = sayı % 10
toplam += sonuc**basamak
sayı = sayı // 10
print("Toplam : ",toplam)
if toplam == sayı1:
print("Armstrong Sayısıdır")
else:
print("Armstrong ... |
5a69399d9d23ab406a8fafb237b185b7b85a25b2 | msafakdal1/Python- | /Project.py | 968 | 3.734375 | 4 | sekil = input("Üçgen mi dörtgen mi?")
if sekil == 'Dikdörtgen':
kenar1 = int(input("Kenar giriniz :"))
kenar2 = int(input("Kenar giriniz :"))
kenar3 = int(input("Kenar giriniz :"))
kenar4 = int(input("Kenar giriniz :"))
if kenar1 == kenar2 == kenar3 == kenar4:
print("Dörtgendir")
else... |
f3b5fa7235e02c5c11116f05204508a5640b710d | Gac125/CS50 | /Python codes/mario1.py | 149 | 3.90625 | 4 | n = int(input("Height:"))
while n<=1 or n>8:
n = int(input("Height:"))
i = n-1
e = 1
while i>=0:
print(" "*i,"#"*e,"\n")
e+=1
i-=1 |
081803704bbec2f5a8cd06622fd7a22840158b3a | s-c-vaz/GoogleCodeJam | /GoogolString.py | 575 | 3.625 | 4 | '''
Created on 23-Dec-2015
@author: annervaz
'''
import math
def compute_kth_digit(k,l):
if k <= l/2:
return compute_kth_digit(k,l/2)
elif k == l/2+1:
return 0
else:
k = k-l/2-1
return 1 ^ compute_kth_digit(l/2-k+1,l/2)
if __name__ == '__main__':
testcases = ... |
0d182a20337af48572d36a8f4fa7ee624a4b2874 | s-c-vaz/GoogleCodeJam | /TextMessagingOutrage.py | 965 | 3.5625 | 4 |
def get_optimal_placement_keypadpress_count(P, K, L, frequencies):
keypadpress_count = 0
num_presses = 1
alloted_letters = 0
while alloted_letters < L:
press = 0
while (press < K) and (alloted_letters < L):
max_frequencies = max(frequencies)
frequencies[freq... |
293ce19aedd3fd32aceb427938f9b1bf74d0ea89 | UCLALibrary/iiif-experiments | /simple-converter/convert.py | 1,766 | 3.515625 | 4 | #!/usr/bin/python
#
# A very simple JP2 converter script that takes a file of file paths as input.
#
# The input file can be generated with something like:
# find `pwd` -type f -name "*.tif" > tiffs.txt
#
# The `pwd` can be replaced with a full system path to a directory containing
# images to convert into JP2. Usin... |
4338da4a8ba6c70f61dcde46df9f8de469286a05 | SamuelFolledo/SPD1.41-Communication-and-Interviewing | /classwork/first_and_last_occurence.py | 1,308 | 3.9375 | 4 | # 3) Given a sorted array, find the index of the first and last occurrence of a given element. If the given element is not found in the array, report that.
num_list1 = [1,2,2,3] #n = 2 -> [1,2]
num_list2 = [1,2,3,3,4,5,5] #n = 3 -> [2,3] #n=4 -> [4] #n=5 -> [5,6]
#Solution 1
def find_first_last_occurence(list1, n):
... |
70277b5371bcdb5190de68567903b4ed8aade82f | thomasdephuoc/bootcamp_python | /day_00/ex_03/count.py | 651 | 4.4375 | 4 | def text_analyzer(text=None):
"""This function counts the number of upper characters, lower characters, punctuation and spaces in a given text."""
if text is None:
text = input("What is the text to analyse?")
nb_char = sum(1 for c in text if c.isalpha())
nb_upper = sum(1 for c in text if c.isu... |
9e2ded3a088ec5083e845f70eb7925f519af6ae4 | thai-trung/python | /agree.py | 195 | 4.03125 | 4 | # Implement if, else in python
answer = input("Do you agree?");
if answer in ["y", "y"]:
print("Agreed!")
elif answer in ["N", "n"]:
print("Not agreed!")
else:
print("Not answer!")
|
c09d7a6b6bb047fd0d6a2516687eb58094a4182c | bigzhao/Algorithm | /LCS.py | 1,695 | 3.609375 | 4 | # coding:utf-8
"""
bigzhao, 2016/10/27
"""
def dynamic_programming_solve_lcs(x, y):
"""use dynamic programming to solve the LCS problem time: O(mn), space: O(mn)"""
c = [[0 for _ in xrange(len(x)+1)] for _ in xrange(len(y)+1)]
b = [['' for _ in xrange(len(x)+1)] for _ in xrange(len(y)+1)]
for i in xran... |
420025da4739e542419d0f5c26468dd4c096138a | hkujy/PT42185 | /PT2019/MSA_Python/GeneralShortestPath/GeneralMsa.py | 3,142 | 3.640625 | 4 | """
python code for the msa
course PT42185
"""
import networkx as nx ## network package
import math
demand = 500
theta = 0.1
walk_link_cap = 9999999999 # very large capacity for the walking link
def set_network():
# create a network
graph = nx.DiGraph()
# add nodes
graph.add_node('A')
... |
ccccf571b42180bccd88ae4d27067c78ce6dc46c | manashb21/PandasPractice | /numtomonth.py | 204 | 4.03125 | 4 | months = "JanFebMarAprMayJunJulAugSepOctNovDec"
print("Enter the month in numbers")
n = eval(input("Enter the Month Number? "))
value = (n-1)*3
print("The month is {}.".format(months[value:value+3]))
|
c696337cda0492a06385ab26fdff89cf8de0aa8f | irene-yi/Classwork | /Music.py | 2,108 | 4.28125 | 4 | class Music:
# if you pass in artists while calling your class
# you need to add it to init
def __init__(self, name, artists):
self.name = name
self.artists = artists
self.friends = {}
# Pushing information to the array
def display(self):
print()
print ("Your artists:")
for artists in self.artists:
... |
c4a1f0448e9ce013071569c6e3710bec01261f46 | paralaexperimentacion/experiment1 | /red_day16.py | 2,003 | 4.25 | 4 | import turtle
import random
#setting up variables
t = turtle #to make writing code easier
t.speed(10)
while True:
#assigning random numbers to variables for number and color
num = random.randint(10,40)
r = random.randint(1,255)
b = 0
g = 0
t.pd()
#assigns color of turtle
t.color(r, b, g)
#keeps... |
0ac6971f984d719c7d65752008b04c0b534eddb6 | pao10y/sales_inventory_system | /search product.py | 1,513 | 4.09375 | 4 | def findProd():
f=0
while f<1:
print("Would you like to search using product names(N) or by product ID(I)")
n=input()
if(n=='N' or n=='n'):
print("Please enter item name:")
i=input()
for x in products:
if (i==x[1]):
... |
7c78cdd9a7c791a82adfe6e19f2f9e1a63f3a953 | IronManCool001/Python | /Guess The Number/main.py | 590 | 4.125 | 4 | import random
chances = 5
print("Welcome To Guess The Number Game")
no = random.randint(0,256)
run = True
while run:
guess = int(input("Enter your guess"))
if guess == no:
print("You Got It")
run = False
break
elif guess > no:
... |
b8ecc471b73c1c9ff01b74835b490b29a803b8db | giovanna96/Python-Exercises | /Divisors.py | 279 | 4.125 | 4 | #Practice Python
#Create a program that asks the user for a number and then prints out a list of all the divisors of that number.
divisor = []
value = int(input("enter a number: \n"))
for i in range(value):
if value%(i+1)==0:
divisor.append(i+1)
print(divisor)
|
cc994308b4b752a55a5206cf23c2f566725939b8 | lubgade/Random_python | /middle_linklist.py | 471 | 4 | 4 | # Find the middle node of a linked list using 2 pointers
# Linear time O(n)
class Node:
def __init__(self, data, next):
self.data = data
self.next = next
n1 = Node("Hello", None)
n2 = Node("21", n1)
n3 = Node("Green", n2)
n4 = Node("Blue", n3)
n5 = Node("Daniel", n4)
head = n5
fastptr = head
s... |
6afe38015e2fd7b324ea08d470d7c125bc23cf3b | s1ma28/coding_test | /s18_Maximum Depth of Binary Tree.py | 1,367 | 4.03125 | 4 | #!/usr/bin/env python3
# *coding: utf-8
from typing import List
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
# Treeの最長の深さを調べて返す。Bottom-Upアプローチ
# p... |
103677dd5a62815180e69cbe257526cb91a78a12 | s1ma28/coding_test | /s7.py | 1,271 | 3.8125 | 4 | #!/usr/bin/env python3
# *coding: utf-8
from typing import List
class Solution:
# valの重複値をin-placeで削除し、削除後の要素数を返す
# pre: nums = [3,2,2,3], val = 3
# post: 2, nums = [2,2]
def removeElement(self, nums: List[int], val: int) -> int:
# corner case: 長さが1以下の場合、
runner_index = 0
targ... |
ebfae50ba92728ad939b23e0f675260ae63b414a | YaelGF/POO_1719110736 | /Semana_4/vacaciones.py | 1,050 | 4 | 4 | class Vacaciones:
def __init__(self,lugar,fecha,horario,precio,lugar_visitar):
self.lugar = lugar
self.fecha = fecha
self.horario = horario
self.precio = precio
self.lugar_visitar = lugar_visitar
def planear(self):
print("planeando")
def viajar(self):
print("viajando")
class Vacaciones... |
2fd498b038c04fc53dad089634da3e8be29d38ba | YaelGF/POO_1719110736 | /Semana_4/serie_TV.py | 1,074 | 3.5 | 4 | class SerieTV:
def __init__(self,genero,titulo,director,contenido,audiencia):
self.genero = genero
self.titulo = titulo
self.director = director
self.contenido = contenido
self.audiencia = audiencia
def informar(self):
print("informando")
def entretener(self):
print("entreteniendo")
cl... |
903b257704b0780bb5d9e8b242ce214549d2992e | YaelGF/POO_1719110736 | /Semana_10/alumnos.py | 981 | 3.96875 | 4 | class Alumnos():
#creacion de la clase y metodo
def get_data(self):
#declaracion de variables
students = []
answer = "s"
#inicio del ciclo
while answer == "s":
#declaracion y asignacion de las variables
name = input("Ingresa el nombre del alumno: ")
year_birth = int (input("Ing... |
9b1afe5f4af684a49d15456a8091100d8a374110 | YaelGF/POO_1719110736 | /Semana_3/estudiante.py | 952 | 3.765625 | 4 | class Estudiante:
def __init__(self,nombre,apellido_P,apellido_M,matricula,asignatura_Fav):
self.nombre = nombre
self.apellido_P = apellido_P
self.apellido_M = apellido_M
self.matricula = matricula
self.asignatura_Fav = asignatura_Fav
def hacer_Tarea(self):
print("haciendo tarea")
def es... |
b4b8658f9f4ad759f4111193d3763690ad9265b3 | wahome24/Udemy-Python-Bible-Course-Projects | /Project 10.py | 1,420 | 4.4375 | 4 | #This is a bank simulator project using classes and objects
class Bank:
#setting a default balance
def __init__(self,name,pin,balance=500):
self.name = name
self.pin = pin
self.balance = 500
#method to deposit money
def deposit(self,amount):
self.balance += amount
print(f'Your new balance ... |
e8ce8c415136c1819334c0d57c446f57acfbaa79 | AntonDos/lessons | /lesson04/classes01.py | 134 | 3.671875 | 4 | list = [5, 100, 1, 16, 8, 2, 23, 7, 7, 9, 56]
sum = 0
for element in list:
if element > 10:
sum = sum + element
print(sum) |
7d8f6fb22521f762c53da675fad75a725f030104 | AntonDos/lessons | /lesson03/solution-03.py | 86 | 3.609375 | 4 | list = ['w', 'r', '_', 'e', 'd', 'p']
symbols = "".join(reversed(list))
print(symbols) |
8c1656235c28e0807c0cc7383bea114d17465415 | JordySoftware/Proyecto-en-Grupo | /Main.py | 565 | 3.515625 | 4 | from WordCloud import generateImage
from UsersTags import getTags
flag = True
while flag:
print("\n Bienvenido al Request de stack OverFlow")
userid = input("\n Digite el ID del usuario de quien desea generar sus etiquetas o si desea salir digite y: ")
if userid == "y" or userid == "Y":
flag = False
... |
34016ae18d905b22fd334490f4b4c418f8788cc3 | uosmandy/CP3_Krit-Nawaritloha | /Exercise5_2.py | 166 | 3.578125 | 4 | print("**********")
print("Motion Distancing")
print("**********")
s = int(input("spatial :"))
t = int(input("times :"))
v = s/t
print("Velocity =", v,"km/h") |
a449f8f8ec9e2bb4ac480f2b73d6d58f0254be30 | TakanoriShima/Python | /Chap1/broadcast.py | 179 | 3.5625 | 4 | print("形状の異なる配列同士の演算:ブロードキャスト")
import numpy as np
A = np.array([[1, 2], [3, 4]])
print(A)
B = np.array([10, 20])
print(B)
print(A * B) |
04c2b516eae0959b8008eabb100059abfcf8c688 | donglai96/PIC_course | /mbeps1.source/OldVersions/dtimer.py | 385 | 3.5625 | 4 | import time
def dtimer(tim, itime, icntrl):
# input: icntrl, (float) itime
# icntrl = (-1,0,1) = (initialize,ignore,read) clock
# clock should be initialized before it is read!
# returns (float) tim[0] = elapsed time in seconds
if icntrl == 0:
return
if icntrl == 1:
usec = time.time() - itime[0... |
16ae9737144e170ab0dd090ae1172c0ac5321e5c | cortezmb/Python_Exercises | /ex8.py | 1,202 | 3.9375 | 4 | #Python exercise 8
total_bill = int(input("Total bill amount? "))
service_level = input("Level of service, which can be one of the following: good, fair or bad? ")
split_checks = int(input("Split how many ways? "))
good = .20
fair = .15
bad = .10
if service_level == "good":
total_tip = total_bill * good
total_... |
6b565782282551011dff64772b0f80a7da4bd3a1 | computer-programming-i-2020/HelloWorld | /Math.py | 552 | 4.09375 | 4 | '''
Created on Jun 19, 2019
@author: karl
'''
#Use the same print command as hello world except use numeric values
print(2)
#When using numeric values, you can use math functions
print(2 + 2) #addition
print(4 - 2) #subtraction
print(4 * 2) #multiplication
print(4 / 2) #Division
print(5 // 2) #Division... |
bcc825e83ae30373cd2a5756245ac2996b039adc | jfilliben/Lychrel | /lychrel.py | 553 | 3.84375 | 4 | #
# Calculates Lyrchrel number
#
# https://en.wikipedia.org/wiki/Lychrel_number
# https://www.youtube.com/watch?v=bN8PE3eljdA
#
original_num = 0
counter = 0
while original_num == 0:
user_input = raw_input("Enter number above 0: ")
if user_input.isdigit():
original_num = int(user_input)
num = original_n... |
a2d8404c7758d23e0f9e8fdbab799d8bfd67f501 | noooorfatima/exoplanet-analysis | /Analysis.py | 11,508 | 4.28125 | 4 |
# coding: utf-8
# # Exoplanets
# # The first submission had some errors regarding x and y axis.
# My final project is all about exoplanets. I will be analysing the relationship between the semi-major axis and period of orbit of exoplanets.
#
# I used the public data of exoplanets from NASA.
#
# What exactly are e... |
c6c45fd523f41b69ee0985afea23175681f63696 | PlysDecompiler/JustTetris | /src/vector.py | 1,755 | 3.703125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
import math
def get_vector(a, b):
if isinstance(a, Vector2D):
return a
elif isinstance(b, Vector2D):
return b
else:
raise ValueError("both not a vector")
def get_scalar(a, b):
if not isinstance(a, Vector2D): # TODO test for ... |
1183b9e6b37f77e9a1875fa5f21f119e658fbced | tosheeth/Edesign344_A3 | /student_heart.py | 820 | 3.640625 | 4 | import numpy as np
def calibrate(time, amplitude):
######################################
# Enter calibration code here: python assignment_3_heart.py 1.5 61.05 120
######################################
times_up = []
times_down = []
for i in range(2,len(amplitude)):
... |
cebc11a76eba589bec28dd26b3a4bab75e1e5ee8 | shashankmalik/Python_Learning | /Week_4/Modifying the Contents of a List.py | 787 | 4.34375 | 4 | # The skip_elements function returns a list containing every other element from an input list, starting with the first element. Complete this function to do that, using the for loop to iterate through the input list.
def skip_elements(elements):
# Initialize variables
new_list = []
i = 0
# Iterate through the lis... |
4155ab95685254e5d062e38a37a342d175e4b6fe | repodiscover/emailscrape | /emailphonescraping.py | 946 | 3.6875 | 4 | '''
a Python Script to scrape websites for
email addresses and US phone numbers
Author: Yannick Le Roux
http://github.com/YannickLeRoux
'''
from bs4 import BeautifulSoup
import re
from urllib2 import urlopen
f = urlopen('https://jekynewage.github.io/funds/')
s = BeautifulSoup(f, 'html.parser')
s = s.get_text()
ph... |
ecf78798c29ad29b8d2d24b5093db91b22b6e467 | chao-shi/lclc | /114_bst_to_flat_m/preorder.py | 904 | 4.0625 | 4 | # Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def flatten(self, root):
"""
:type root: TreeNode
:rtype: void Do not return anything, modify roo... |
b72c5ebc3be3ae660f3f756cf72c872e346e918a | chao-shi/lclc | /236_lca_bt_m/main_old.py | 1,007 | 3.921875 | 4 | # Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def lowestCommonAncestor(self, root, p, q):
"""
:type root: TreeNode
:type p: TreeNode
:t... |
06438c2316f71cc1716798aea72e6e491d2b5713 | chao-shi/lclc | /606_bt_bracket_str_e/main.py | 730 | 3.75 | 4 | # Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def tree2str(self, t):
"""
:type t: TreeNode
:rtype: str
"""
def recur(root):
... |
ea125c24fd9cec78a5b81ad6db471f91d1681cfe | chao-shi/lclc | /082_remove_dup_ll_2_m/main.py | 673 | 3.78125 | 4 | # Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def deleteDuplicates(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
dh = ListNode(None)
t... |
87c337efe80626c7c30dc55e55b9dc68d8eee2b9 | chao-shi/lclc | /530_min_abs_diff_bst_e/main.py | 778 | 3.703125 | 4 | # Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def getMinimumDifference(self, root):
"""
:type root: TreeNode
:rtype: int
"""
se... |
7fa78f9eaca71c853c6572d6c961920191f64153 | chao-shi/lclc | /587_erect_fence_vh/jarvis.py | 2,282 | 3.734375 | 4 | # Definition for a point.
# class Point(object):
# def __init__(self, a=0, b=0):
# self.x = a
# self.y = b
class Solution(object):
def outerTrees(self, points):
"""
:type points: List[Point]
:rtype: List[Point]
"""
# Use cross product
# to check i... |
d8d901dfdf4d5ace6a65cf1a87d1bfa109fbbbf5 | chao-shi/lclc | /114_bst_to_flat_m/head_end.py | 1,105 | 3.8125 | 4 | # Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def flatten(self, root):
"""
:type root: TreeNode
:rtype: void Do not return anything, modify roo... |
f44dc37b004f3610103fce769f79525712f803b2 | chao-shi/lclc | /369_plus_one_ll_m/two_pointers.py | 935 | 3.640625 | 4 | # Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def plusOne(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
hd = ListNode(0)
hd.next = hea... |
fa3bc9c81d4b37176016c1965c624b739522c510 | chao-shi/lclc | /572_subtree_of_another_m/substring.py | 884 | 3.6875 | 4 | # Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def isSubtree(self, s, t):
"""
:type s: TreeNode
:type t: TreeNode
:rtype: bool
"... |
3f61aea69f5d2eff08efc4d1166f8e51efd7a7f4 | chao-shi/lclc | /245_shortest_word_distance_3_m/main.py | 571 | 3.515625 | 4 | class Solution(object):
def shortestWordDistance(self, words, word1, word2):
"""
:type words: List[str]
:type word1: str
:type word2: str
:rtype: int
"""
last_idx = {}
mindis = len(words)
for i, word in enumerate(words):
if word == ... |
b182fa81b82cc95c88b7aa0ebe8e77bcac84da11 | chao-shi/lclc | /021_merge_two_sorted_ll_e/main.py | 620 | 3.9375 | 4 | # Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def mergeTwoLists(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
dh = ... |
27d2a44388880616129c433bc1a04b5858ee13fc | chao-shi/lclc | /160_link_list_intersection_e/main.py | 773 | 3.609375 | 4 | # Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def getIntersectionNode(self, headA, headB):
"""
:type head1, head1: ListNode
:rtype: ListNode
"""
def len(he... |
c601062b653a5e57295ed325fd0567e0f0cd8084 | chao-shi/lclc | /478_rand_point_on_circle_e/main.py | 857 | 3.75 | 4 | class Solution(object):
def __init__(self, radius, x_center, y_center):
"""
:type radius: float
:type x_center: float
:type y_center: float
"""
self.r = radius
self.x = x_center
self.y = y_center
def randPoint(self):
"""
... |
3bd4b2ab0b2cc56e3b9e2de58db05cd094a142c9 | chao-shi/lclc | /437_path_sum_3_m/main.py | 820 | 3.578125 | 4 | # Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def pathSum(self, root, sum):
"""
:type root: TreeNode
:type sum: int
:rtype: int
... |
235f719e7e887211c3ae2ed8f67b169e435b1a57 | chao-shi/lclc | /315_count_smaller_number_vh/merge_sort_asc.py | 1,523 | 3.53125 | 4 | class Solution(object):
def countSmaller(self, nums):
"""
:type nums: List[int]
:rtype: List[int]
"""
counts = [0] * len(nums)
tuples = list(enumerate(nums))
def sort_and_count(tuples, start, end):
if end - start < 2:
retur... |
c33e0da8031e438f6c57719e470e7b03d0eb54a2 | chao-shi/lclc | /640_solve_equation_m/main.py | 913 | 3.703125 | 4 | class Solution(object):
def solveEquation(self, equation):
"""
:type equation: str
:rtype: str
"""
def accu(term):
# Normalize
if term[0] != "-":
term = "+" + term
term = term.replace("+x", "+1x").replace("-x", "-1x")
... |
fa0bb842b3c08b1cb3c7167b82a01fdf1ca65c40 | chao-shi/lclc | /057_insert_range_h/main.py | 1,118 | 3.625 | 4 | # Definition for an interval.
# class Interval(object):
# def __init__(self, s=0, e=0):
# self.start = s
# self.end = e
class Solution(object):
def insert(self, intervals, newInterval):
"""
:type intervals: List[Interval]
:type newInterval: Interval
:rtype: List[... |
f632a70203c26e405d1d1ae05244a18319860c0e | chao-shi/lclc | /563_tree_tilt_e/main.py | 614 | 3.671875 | 4 | # Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def findTilt(self, root):
"""
:type root: TreeNode
:rtype: int
"""
self.total = 0... |
3727abfa41900ad276111b2f0bd3f66b66df9a19 | chao-shi/lclc | /547_find_circles_m/union_find.py | 1,257 | 3.6875 | 4 | class UnionFind(object):
def __init__(self, values):
self.parent = {v : v for v in values}
self.size = {v:1 for v in values}
self.set_cnt = len(values)
def root(self, u):
while u != self.parent[u]:
self.parent[u] = self.parent[self.parent[u]]
u = self... |
dfe51f97c1f2bf6c94c6a829d73fc4b8086e9f6b | chao-shi/lclc | /133_clone_graph_m/main.py | 712 | 3.734375 | 4 | # Definition for a undirected graph node
# class UndirectedGraphNode:
# def __init__(self, x):
# self.label = x
# self.neighbors = []
class Solution:
# @param node, a undirected graph node
# @return a undirected graph node
def cloneGraph(self, node):
hm = {}
def clone(no... |
7950b360a213395b3e62b283e67a1736b5948278 | chao-shi/lclc | /444_reconstruct_seq_h/pq.py | 2,868 | 3.578125 | 4 | import heapq
import itertools
# Min priority queue with upsert/delete supported (PirotityQueue)
#
# v will be unique that's why we can use q_map here
# Python website following
# https://docs.python.org/3/library/heapq.html
# Also uses a counter, because he needs to compare v
# In this question, we don't care about ... |
1a9bcee90c1b9875ceddf8720bec1cdc6ec01acb | chao-shi/lclc | /170_two_sum_data_structure_e/main.py | 1,276 | 3.96875 | 4 | class TwoSum(object):
def __init__(self):
"""
Initialize your data structure here.
"""
self.counter = {}
def add(self, number):
"""
Add the number to an internal data structure..
:type number: int
:rtype: void
"""
self.co... |
4d540640c41d61c2472b73dceac524eb6494797e | chao-shi/lclc | /489_robot_cleaner_h/main.py | 2,788 | 4.125 | 4 | # """
# This is the robot's control interface.
# You should not implement it, or speculate about its implementation
# """
#class Robot(object):
# def move(self):
# """
# Returns true if the cell in front is open and robot moves into the cell.
# Returns false if the cell in front is blocked and r... |
3bde8be698117975e9507ed5704c214640030cc3 | chao-shi/lclc | /258_add_digits_mod_9_e/main.py | 497 | 3.640625 | 4 | class Solution(object):
def addDigits(self, num):
"""
:type num: int
:rtype: int
"""
# number abcd and a+b+c+d
# The different is multiple of 9
# After each round, the new number has the same mod 9 with origin
# The final value will be in range of [0, ... |
65307f525ec7859af606277d566926ce862dac6b | chao-shi/lclc | /865_root_of_all_deepest_m.py/one_pass.py | 768 | 3.71875 | 4 | # Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def subtreeWithAllDeepest(self, root):
"""
:type root: TreeNode
:rtype: TreeNode
"""
... |
37ed35ed78bd3d12d9e47cfba7c62565ed122449 | chao-shi/lclc | /676_magic_dic_m/bf.py | 1,276 | 3.921875 | 4 | class MagicDictionary(object):
def __init__(self):
"""
Initialize your data structure here.
"""
def buildDict(self, dict):
"""
Build a dictionary through a list of words
:type dict: List[str]
:rtype: void
"""
self.dictionary = se... |
0306195b0d26211e24b7791c488605e3662a2781 | chao-shi/lclc | /958_check_complete_m/main.py | 846 | 3.796875 | 4 | # Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def isCompleteTree(self, root):
"""
:type root: TreeNode
:rtype: bool
"""
def rec... |
9d1db3091eabbdfdf66e5208a76530a480752331 | chao-shi/lclc | /431_deser_n_ary_bst_h/main.py | 1,445 | 3.96875 | 4 | """
# Definition for a Node.
class Node(object):
def __init__(self, val, children):
self.val = val
self.children = children
"""
"""
# Definition for a binary tree node.
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
"""
clas... |
6bc8ecb3c6b73694286abcec458cef1856df702d | chao-shi/lclc | /342_pow_4_e/main.py | 318 | 3.703125 | 4 | class Solution(object):
def isPowerOfFour(self, num):
"""
:type num: int
:rtype: bool
"""
return num > 0 and num&(num-1) == 0 and num&0x55555555 > 0
# num > 0 and num&(num-1) == 0 tells us only one 1 digit, check where is that digit
# Don't forget 1 is also power of 4 |
d3917864da7f0cd66f06d92510bd656546b70297 | chao-shi/lclc | /019_remove_last_n_ll_e/main_invalid_case.py | 870 | 3.671875 | 4 | # Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def removeNthFromEnd(self, head, n):
"""
:type head: ListNode
:type n: int
:rtype: ListNode
"""
dh = ... |
03ea3cd95e34016518816247c2f66602250df535 | chao-shi/lclc | /538_bst_to_greater_tree_e/recur_param.py | 767 | 3.8125 | 4 | # Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def convertBST(self, root):
"""
:type root: TreeNode
:rtype: TreeNode
"""
def rev... |
7a61e7d38c5099ae31342445ad46e038634b4240 | chao-shi/lclc | /023_merge_k_ll_m/main.py | 790 | 3.953125 | 4 | # Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
from Queue import PriorityQueue
class Solution(object):
def mergeKLists(self, lists):
"""
:type lists: List[ListNode]
:rtype: ListNode
"""
... |
f409f136fa3bcec0adc51ef36f12f1b6a1152ee0 | jayarrgp/upsitfDay1 | /fibonacci.py | 469 | 3.984375 | 4 | firstAddend = []
secondAddend = []
fibonacciNumber = []
firstAddend.append(0)
secondAddend.append(1)
fibonacciNumber.append(firstAddend [0]+ secondAddend[0])
x = int(input("Please input how many Fibonacci numbers: "))
for x in range(x-3):
fibonacciNumber.append(fibonacciNumber[x] + secondAddend [x])
seco... |
a8cec082a21480cd53b73bec20b738a0b3a96dff | NMoro811/Battleship-Online-AI | /cpu_class.py | 3,822 | 4.0625 | 4 | '''
Contains the CPU class
'''
from random import randint
from board_class import Ship, BoardState
class CPU():
'''This class is used to define the actions of the CPU in a game vs a player
Attributes:
ship_lengths Same as in the Player class
board The ... |
695eb8dd3d77dbeb9e5e0ec6cc8770fcd69333ae | SlicSide/NeuralNetworkTF | /neuralnet.py | 3,641 | 4.03125 | 4 | import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
from datetime import datetime
mnist = input_data.read_data_sets("/tmp/data", one_hot=True)
# What one_hot is:
'''
means that in this case for the number class 0-9 only one class is "hot". The others are not. Examples:
0 = [1,0,0,0,0,0,... |
004e9055dc73b791e14f5c7c9ffa6df862479499 | daniel-hocking/COMP9414-Assignment-3 | /Path.py | 6,617 | 3.953125 | 4 | '''
Path.py
Contains the Path class which is used to find the optimal path to a goal
Or at least a possible path
Written by: Daniel Hocking
zID: 5184128
Date created: 14/05/2018
'''
from Bfs import Bfs
from AStar import AStar
class Path:
def __init__(self, game_map):
# Keep a reference to the game_map ob... |
95aa5f8cd0b170de0df7abbc18a8016755282e7f | Daniel-Benson-Poe/Python_to_Cpp_Series | /Article_2/python/collecting_input.py | 428 | 3.84375 | 4 | print(input("What is your name? \n"))
a = input("Type in a phrase: \n")
b = input("Type in a whole number: \n")
c = input("Type in a decimal number: \n")
d = input("Type in 'True' or 'False': \n")
print(a, "\n", type(a))
print(b, "\n", type(b))
print(c, "\n", type(c))
print(d, "\n", type(d))
b = int(b)
c = float(c)
... |
474eae8941c6dbc4f3894d09e65c8e005cdf3871 | Zackster310/ATMClass | /ATM.py | 767 | 3.5625 | 4 | class ATM:
def __init__(self, cardNumber, PIN, balance):
self.balance = balance
self.PIN = PIN
self.cardNumber = cardNumber
def cashWithdrawal(self, PIN, amount):
if PIN == self.PIN:
self.balance = self.balance - amount
print(amount,"has been wit... |
a76b3097319f5455c007739893c867fb31cd12fa | nickklaskala/checkio | /O'Reilly/median_of_three.py | 1,054 | 3.796875 | 4 | #!/usr/bin/env checkio --domain=py run median-of-three
# 给你一个 整数列表 , 你需要创建并返回一个 列表 其中前两个元素要和输入列表一致, 从第三个元素开始,要取输入列表的该位置前三个数的中位数。
#
# 等等...你不知道什么是‘中位数’? 那先来看看这个Checkio任务"Median".
#
# 输入:整数列表。
#
# 输出:整数列表。
#
# The mission was taken from Python CCPS 109 Fall 2018. It’s being taught for Ryerson Chang School of Contin... |
aa101c35a2fd2b3969bab1022124c0f08bd3f539 | nickklaskala/checkio | /Scientific Expedition/time_converter_24h_to_12h.py | 1,404 | 3.9375 | 4 | #!/usr/bin/env checkio --domain=py run time-converter-24h-to-12h
# You prefer a good old 12-hour time format. But the modern world we live in would rather use the 24-hour format and you see it everywhere. Your task is to convert the time from the 24-h format into 12-h format by following the next rules:
# - the output... |
593cf5c68021aab87e6e482ef448d23e768ef992 | nickklaskala/checkio | /Mine/best_stock.py | 938 | 3.734375 | 4 | #!/usr/bin/env checkio --domain=py run best-stock
# You are given the current stock prices. You have to find out which stocks cost more.
#
# Input:The dictionary where the market identifier code is a key and the value is a stock price.
#
# Output:The market identifier code (ticker symbol) as a string.
#
# Precondit... |
433260de9b2ed0a9a85b50ebceb63bebf5e9ae82 | sandeepkmverma/python_calculator | /main.py | 674 | 3.828125 | 4 | import sum_sub
import practice.mul_div
import check_value
import check_operator
x = check_value.inputNumber("Enter first value : ")
y = check_value.inputNumber("Enter second Value : ")
z = check_operator.check_operator("Enter the operator as well (for eg. + - * /) : ")
if z=='+':
sum_value = sum_sub.sum(int(x), i... |
ed89a95565394f93acb0d530d693c83067ccd43e | GregGrigorop/Iterators-Generators | /infinite_generator.py | 526 | 4 | 4 | def current_digit(): # we want to be getting one result at a time
digit = (1,2,3,4)
count = 0
while count < 4: # OR: while True:
if count == 3:
yield digit[count]
count = 0
else:
yield digit[count]
count += 1
digit = current_digit()
print(next(digit))
print(next(digit))
print(next(digit))
print(next... |
fd755ddb0b7b5d3fa39cb0e1be1ef928bdba560d | p-perras/absp_projects | /pdf_password_breaker/passwordBreaker.py | 1,059 | 3.796875 | 4 | #! python3
# passwordBreaker.py
# ABSP - Chapter 15
import PyPDF2
def break_password(pdfFile, dictionnary):
"""
Summary:
breaks a single word password for a PDF
Args:
pdfFile (str): filename of the encrypted PDF
dictionnary (str): filename of dictionnary of words to use
Retu... |
93897a144a08baf27692f9dd52da610be41c0ad3 | p-perras/absp_projects | /table_printer/tablePrinter.py | 788 | 4.1875 | 4 | # !python3
# tablePrinter.py
# ABSP - Chapter 6
def print_table(table):
"""
Summary:
Prints a table of items right justified.
Args:
table (list): A 2d list of items to print.
"""
# Get the max length string of each row.
rowMaxLen = []
for row in range(len(table)):
... |
5b82eebb5b6b1fb4c44f0a4c2066e9a1d8a20094 | p-perras/absp_projects | /game_inventory/fantasyGameInventory.py | 1,209 | 3.828125 | 4 | #! python3
# fantasyGameInventory.py
# ABSP - Chapter 5
def display_inventory(inventory):
"""
Summary:
Displays what the play has in inventory.
Args:
inventory (dict): Inventory conainning items and their counts.
"""
print('Inventory: ')
for k, v in inventory.items():
... |
3b6efbbb26a842677c39795dda29e45c3990ae66 | p-perras/absp_projects | /custom_seating_cards/customCards.py | 1,469 | 3.9375 | 4 | # !python3
# customCards.py
# ABSP - Chapter 18
import os
from PIL import Image, ImageDraw, ImageFont
def make_cards(guestList):
"""
Summary:
Makes custom cards for each guest.
Args:
guestList (str): Path to a file containing a guest list.
"""
# Create folder to store images.
... |
9a32a1e090d595901e0817fa6c687f9ee5b0a83d | p-perras/absp_projects | /character_picture_grid/pictureGrid.py | 759 | 3.890625 | 4 | #! python3
# pictureGrid.py
# ABSP - Chapter 4
def rotate_90(grid):
"""
Summary:
Rotates a 2d grid 90 degrees and prints it.
Args:
grid (list): 2d representation of a grid
"""
for row in range(len(grid[0])):
print()
for col in range(len(grid)):
print(gr... |
b1c20adef2947f799e69ed947505eba2b8b28fab | YANG007SUN/data_structure | /heap/easy/jess_and_cookies.py | 485 | 3.515625 | 4 | # https://www.hackerrank.com/challenges/jesse-and-cookies/problem
from heapq import heapify, heappush, heappop
#
# Complete the cookies function below.
#
def cookies(k, A):
#
# Write your code here.
#
heapify(A)
i =0
counter= 0
while True:
x = heappop(A)
if x>=k:
... |
dda5ec5b80e79f8409eb72d34c8264bc5d00efa5 | max0man0/ICS104_Project | /Python_Lab_Project.py | 19,714 | 3.734375 | 4 | # This work done by group 10:
# Mohammed Alzayani, 201915730, (50%)
# Abdullah Alhifthi, 201963030, (50%)
from time import sleep
import datetime
# A global constant containing the threshold of the money one can have in their account
THRESHOLD = -1000
def main():
# Asks the user until receiving a valid input
... |
275a0f5335311db454a3c60ff6a8d730ce7223b4 | abeerIsaMoghrabi/companyRegex | /EmployeeRegex.py | 5,420 | 3.96875 | 4 | import re
from Employee import Employee
class EmployeeRegex(object):
""" parse string list using regex to:
1- search for specific value (parts : 1, 3, 4, 5)
2- create employee list
"""
def __init__(self, text):
"""
:param text: file content
:type text: string lis... |
505d55c4b03b3cbfc56fccf1e126ab28930e34c2 | patnev/GM1_G3 | /read_serial.py | 1,242 | 3.65625 | 4 | """
Class to read sensor data from serial port (via USB)
"""
import serial
from constants import *
class SerialReader:
"""
SerialReader: class to read sensor data
Methods: readline, readline_multi, isButtonPressed
"""
def __init__(self):
"""
Initialise serial reader from serial por... |
23a9027ad9ee1eb4fc4cd09bbd91b17b53cd48e8 | pleeplee-robot/location | /pleepleeloc/location.py | 5,075 | 3.90625 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
from .compute import compute2Data, compute3Data, sortData
class Odometry:
"""Class that represents an odometry.
Combination of last position, range and distance traveled.
Arguments:
lastPos: Last position of the robot when the position was computed... |
820529710dc98dda8db43f17cc782154602b32d1 | rubenhortas/python_examples | /variables/inline_variable_swapping.py | 192 | 4.03125 | 4 | #!/usr/bin/env python3
if __name__ == '__main__':
x = 1
y = 2
print(f"x={x} y={y}") # x=1 y=2
x, y = y, x # Inline variable swapping
print(f"x={x} y={y}") # x=2 y=1
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.