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 |
|---|---|---|---|---|---|---|
0bb48a546519602742cdf4cc615a31a95ba1348c | geekbert/pythoncharlesseverin | /pythoncharlesseverin/07_openfilename.py | 317 | 3.5625 | 4 |
fname = raw_input('Enter the file name: ')
try:
fhand = open( fname )
except :
print 'File cannot be opened:', fname
exit ()
count = 0
for line in fhand:
if line .startswith ('Subject:') :
count = count + 1
print 'There were', count, 'subject lines in', fname
|
42c17e76b020c3a03e2ef01d55f11df18733ab36 | vkolehmainen/ML_termproject | /neural_network.py | 6,022 | 3.59375 | 4 | import pandas as pd
import numpy as np
import sys
import matplotlib.pyplot as plt
# GLOBAL VARIABLES
epsilon = 0.01 # learning rate for gradient descent
reg_lambda = 0.01 # regularization term
def forward_propagation(params, x):
''' Predict probabilities for each class (0 or 1) for each row in x using forward pro... |
7938ffe39f62fda3f02d0771068557b9c2467d82 | softwarethreads/ca | /residential/Database.py | 2,288 | 3.8125 | 4 | # Created on September 6, 2020
# Copyright (c) 2020 - Software Threads, Inc.
import sqlite3
import time
from sqlite3 import Error
class Database:
def __init__(self):
try:
self.conn = sqlite3.connect('/Users/ravibhargava/sqlite')
except Error as e:
print(e)
def create... |
9702342e5382968011fe6eb42d5050c33579c889 | sourander/boardgamesetup | /modules/board.py | 1,371 | 3.546875 | 4 | from modules.location import Location
class Board():
def __init__(self, location_pool, bag):
self.location_pool = location_pool
self.locations = []
self.bag = bag
self.populate_locations()
def populate_locations(self):
for loc in self.location_pool:
name, s... |
6f4df65fd5faa1394b84059e2e81ca606e51054b | leapfrogtechnology/lf-training | /Python/susankoju/task0/shoppingList-class.py | 1,047 | 4.03125 | 4 | from datetime import date
price = {'biscuits': 12.50, 'noodles': 15}
class ShoppingItems:
def __init__(self, name, items):
self.items = items
self.name = name
self.date = date.today()
def showAll(self):
print(f"{(self.name)}\n")
items = ""
prices = ""
... |
3ed834b94e2a0c539b6800943d1d5b3a9f657924 | sneyd321/BankingApp-Python | /BankingApplicationPython/Bank.py | 1,938 | 3.890625 | 4 | from Account import *
from ChequingAccount import *
from SavingsAccount import *
class Bank():
"""Class that holds account information and creates accounts"""
#list that holds all bank information
_accountList = []
def __init__(self):
#Create 10 default accounts when initalized
for ... |
0ef89bf5ef5d946e7bc56e610f9c538f861d2dc2 | Tclack88/Lambda | /CS/CS-5-Graphs/projects/graph/graph.py | 6,537 | 4.09375 | 4 | """
Simple graph implementation
"""
from util import Stack, Queue # These may come in handy
class Graph:
"""Represent a graph as a dictionary of vertices mapping labels to edges."""
def __init__(self):
self.vertices = {}
def add_vertex(self, vertex_id):
"""
Add a vertex to the graph.
"""
self.vertices[... |
fcb8b95de64c317b74e91da2a011c51d4f88f332 | Tclack88/Lambda | /CS/CS-2-Algorithms/1-sorting/src/sorting_race.py | 1,560 | 3.703125 | 4 | #!/usr/bin/env python3
from recursive_sorting.recursive_sorting import merge, merge_sort, insertion_sort, timsort, just_merge
from recursive_sorting.extra_quicksort import quick_sort
from iterative_sorting.iterative_sorting import selection_sort, bubble_sort, count_sort
from random import sample, seed
from time impor... |
3cca8d02125009f8d3c1bfe0b0c456f569d37051 | Tclack88/Lambda | /CS/CS-5-Graphs/projects/ancestor/ancestor.py | 1,423 | 3.78125 | 4 | from graph import Graph
ancestors = [(1, 3), (2, 3), (3, 6), (5, 6), (5, 7), (4, 5), (4, 8), (8, 9), (11, 8), (10, 1)]
starting_node = 6
def earliest_ancestor(ancestors, starting_node):
# initialize and populate graph
g = Graph()
for a in ancestors:
g.add_vertex(a[1])
for a, c in ancestors:
... |
a0df45f9034903a3c0d41fe816353a6f5de4bee3 | loibucket/biopy | /archive-bioinformatics-3/bio3-wk5/bio3-wk5-3_colorededges.py | 1,799 | 3.625 | 4 | def chromosome_to_cycle(chromosome):
"""
convert genome to graph, where
node1 = chrom1_head, node2 = chrom1_tail
node3 = chrom2_head, node4 = chrom2_tail
"""
nodes = [0] * (len(chromosome) * 2 + 1)
chromo = [0] + chromosome.copy()
for j in range(1, len(chromo)):
i = chromo[j]
... |
3c09f6c23f6eff272a696072cd790c931504a029 | loibucket/biopy | /archive-bioinformatics-3/bio3-wk5/bio3-wk5-6_twobreakgenome.py | 4,225 | 3.625 | 4 | import copy
def chromosome_to_cycle(chromosome):
"""
convert genome to graph, where
node1 = chrom1_head, node2 = chrom1_tail
node3 = chrom2_head, node4 = chrom2_tail
"""
nodes = [0] * (len(chromosome) * 2 + 1)
chromo = [0] + chromosome.copy()
for j in range(1, len(chromo)):
i =... |
91fd1d8367dce0504023342949ae7e080dc055e3 | loibucket/biopy | /archive-bioinformatics-1/bio-wk3-3_medianstring.py | 3,066 | 3.96875 | 4 | import math
def ham_dist(p, q):
"""
hamming distance is the number of mismatches between equal length sequences p and q
returns integer
"""
count = 0
for i in range(len(p)):
if p[i] != q[i]:
count += 1
return count
def dee(pattern, seq):
"""
find the min possi... |
0b7a755a97ce7899f7f78896cbce81412125badd | loibucket/biopy | /archive-bioinformatics-3/bio3-wk2/bio3-wk2-2_local-score-matrix.py | 4,440 | 3.65625 | 4 | import numpy as np
from numpy import unravel_index
"""
Code Challenge: Solve the Local Alignment Problem.
Input: Two protein strings written in the single-letter amino acid alphabet.
Output: The maximum score of a local alignment of the strings, followed by a local alignment of these strings achieving the maximum sco... |
d23dab5a4eb6f8269e99ccd8d547072dec5a8d63 | loibucket/biopy | /bio4-wk3-3.py | 1,882 | 3.53125 | 4 | import networkx as nx
import matplotlib.pyplot as plt
import os
import pathlib
import copy
import pygraphviz
from datetime import datetime
def two_nearest_neighbors(G, e1, e2):
"""
make graphs of 2 of the nearest neighbors of graph G at edge e1-e2
"""
e1n = G.neighbors(e1)
e2n = G.neighbors(e2)
... |
fdc5e8a455a5d8239e671a30fb1ca5815c772e19 | JimmyJiang666/Similarity-Search-Using-LSH | /Ja.py | 6,328 | 3.546875 | 4 | def JaccardSimilarity(a,b):
intersection=len(set(a).intersection(set(b)))
union=len(a)+len(b)-intersection
output= float(intersection)/float(union)
return output
import random
import mmh3
import time
############################################################
##Problem 3.1
##just to test the function... |
f4512de1a852ddbf8beb1d94e05f545f7c11812e | ToraNoDora/learn-python | /moneyspent/moneyspent.py | 1,789 | 3.5625 | 4 | import os
import sys
# Объявляем функцию getMoneySpent
def getMoneySpent(keyboards, drives, b):
# Наибольший к клаве
max_of_keyboards = max(keyboards)
# наибольший к накопителям
max_of_drives = max(drives)
# Проверяет, одинаковы ли объекты
maximum_of_keyboards_and_drives = max(max_of_keyboard... |
00c1df55fdf57e7deacf2f866cbcc60909f47075 | midfield99/Calculator_UI | /Python_AccessorTests/bin/Debug/calc.py | 2,535 | 3.71875 | 4 | import numbers
def add(args):
return args[0].evaluate() + args[1].evaluate()
def sub(args):
return args[0].evaluate() - args[1].evaluate()
def multiply(args):
return args[0].evaluate() * args[1].evaluate()
def div(args):
return args[0].evaluate() / args[1].evaluate()
def test(exp):
if exp.args[0].valid():
i... |
b47ad62ef2697cd563b3a3f65b20c5e6bfafe453 | Energised/notes | /python/threads.py | 19,099 | 3.71875 | 4 | # threads.py
# dan woolsey
#
# threading module in Python 2.x
#
# - Higher level interface that allows for the creation of multiple 'threads of control'
#
# With thanks to https://pymotw.com/2/threading/ and docs.python.org
#
# NOTEABLE TERMS:
#
# daemon -> long running background process that answers requ... |
604477fd81a4b1139c755ef3500c350392a4dcf3 | jonathanelliott/mastermind | /main.py | 3,284 | 3.640625 | 4 | import random
from jonathan import *
colours = ["R","Y","B","G","W","K"]
num_pegs = 4
def valid_guess(guess, valid_length=4):
return len(guess) == valid_length and all(x in colours for x in guess)
def clue2(guess,code): #luke's way of assigning score pegs
guess_copy = [ g for g in guess ]
code_copy = [ c for c... |
4503729bbe248fb51892b06263c3572458104707 | OliviaFortuneUCD/pythonProject28 | /Python5.py | 553 | 3.578125 | 4 | import matplotlib.pyplot as plt
plt.style.use('classic')
import pandas as pd
import numpy as np
import seaborn as sns
import datatables
cereal = pd.read_csv("cereal.csv")
# get the hot cereals
hotcereals = cereal["sodium"][cereal["type"] == "H"]
# get the cold cereals
coldcereals = cereal["sodium"][cereal["type"] == "... |
b04396e2aed3fbe217458c8d0b9fbaa49b991842 | ujwaljoshi116/ecommerce-webpage | /loginpass.py | 528 | 3.78125 | 4 | def loginpass():
print("Sign in to contine ")
print("-"*80)
login=input("Enter username:")
password=input("Enter password:")
if login=="123@gmail.com":
if password == "1234":
print("Access given!!!!!!!")
else :
print("WRONG PASSWO... |
ffb5acfef7395967bfc3a8d62fb981768ef6bae4 | anish-lakkapragada/libmaths | /libmaths/trig.py | 2,884 | 4.28125 | 4 | #Developer : Vinay Venkatesh
#Date : 2/20/2021
import matplotlib.pyplot as plt
import numpy as np
def trigsin(z, b):
'''
In mathematics, the trigonometric functions are real functions which relate
an angle of a right-angled triangle to ratios of two side lengths.
Learn More: https://www.mathsisfun.com/sine... |
c66e3dd74ca1f8f58f62c9d42d5ebd0fd05db51b | daniarques11/duplicate_encoder | /duplicate_encoder_dictionary.py | 405 | 3.5625 | 4 | def duplicate_encoder(string):
dictionary = {}
string = string.lower()
for character in string:
if character in dictionary:
dictionary[character] = ')'
else:
dictionary[character] = '('
assert dictionary != {}
stringEncoded = ''
for character in string:
... |
9d59edf273a76e409ca5ba7a6898c50d130d43c7 | khanmaster/python_modules | /exception_handling.py | 1,246 | 4.1875 | 4 | # We will have a look at the practical use cases and implementation of try, except, raise and finally
we will create a variable to store a file data using open()
Iteration 1
try: # let's use try block for a 1 line of code where we know this will throw an error
file = open("orders.text")
except:
print(" Panic A... |
19d91775e6a60e8ff08183c9349497ff5c17fd2b | rntva/JumpToPython | /Test_Book/coding_test_4/greet_user1.py | 447 | 3.828125 | 4 | #함수 리턴값 받아서 프린트
import sys
def greet_users(str_list) :
result = ""
for x in usernames :
temp2 = ""
temp = list(x)
temp1 = str(temp[0]).upper()
for y in temp[1:] :
temp2 = temp2 + str(y)
result += temp1 + temp2 + ' '
result = result[:-1]
return resul... |
ad4ed9bfb5911f6a0a9f9630c307e35b9f277c65 | rntva/JumpToPython | /test.py | 2,047 | 3.6875 | 4 | # import math
#
# def suger_delivery() :
# total_suger = int(input("설탕 총 양 : "))
# return_value = int(total_suger / 5)
#
# if (total_suger % 5) / 3 == 0 :
# return_value += int(total_suger / 5 / 3)
#
# else : return_value = -1
#
# print(return_value)
#
# def terret() :
# test_case_num = ... |
d004c3c5696308dd48de01fcc1f8dceb5d825d48 | rntva/JumpToPython | /1.Chapters/chapter.7/xml_practice.py | 1,958 | 3.53125 | 4 | from xml.etree.ElementTree import Element, SubElement, ElementTree, dump, parse
blog = Element("blog", date = "20180108", editor = "Pycharm")
SubElement(blog, "subject").text = "Why Python"
SubElement(blog, "author").text = "Eric\n "
SubElement(blog[1], "age").text = "58"
SubElement(blog[1], "natin").text = "USA"
# a... |
bbd86abc41afd60f862871afd612b512062f2fa7 | rntva/JumpToPython | /DeepLearning/Chap.2_Perceptron/XOR.py | 146 | 3.703125 | 4 | def xor(x, y) :
if x == y :
return 0
else :
return 1
print(xor(0, 0))
print(xor(0, 1))
print(xor(1, 0))
print(xor(1, 1))
|
d932c487be341e930fd8bb0200bfab24766416b5 | rntva/JumpToPython | /DeepLearning/180611_numpy1.py | 513 | 3.5 | 4 | import numpy as np
import matplotlib.pyplot as plt
v1 = np.zeros(10, dtype=np.float32)
print(v1)
v2 = np.arange(10, dtype=np.uint64)
print(v2)
v2 *= 3
print(v2)
print(v2.mean())
num_points = 1000
vectors_set = []
for i in range(num_points) :
x1 = np.random.normal(0.0, 0.55)
y1 = x1 * 0.1 + 0.3 + np.random... |
0830ecf3b7be35f9c205fb8cb6df6199b98d28f8 | rntva/JumpToPython | /3.Data_Science/CVS_Handle/NeNe_Chicken/step_2.py | 2,497 | 3.765625 | 4 | import csv
def get_csv_row_Instance(row_name) :
try :
row_index = data[0].index(row_name)
row_instance = []
for row in data[1:]:
row_instance.append(row[row_index])
return row_instance
except ValueError :
print("찾으려는 Primary_key값이 없습니다.")
return 1
de... |
d47ffd3ca1c51afc2c07445730d4d89130714518 | rntva/JumpToPython | /Test_Book/coding_test_9/problem_1.py | 1,368 | 3.609375 | 4 | while 1 :
input_num = input("출력하고 싶은 단을 입력하십시오.(-1:종료, all:구구단 전체 출력) : ")
if input_num == "all" :
# Version_1
# result = []
# for y in range(2,10) :
# result = list(map(lambda x: x * y, range(1, 10)))
# for y in range(2, 10):
# for z in range(9) : print("... |
1712b11dca4b99fbb595ae269d8f37e9ac270e61 | AUSG/study-2019-first | /algorithm/sangyeol/week3/nested_for.py | 234 | 3.984375 | 4 | # n=7일 때 (0,1,2,3), (0,1,2,4) ~ (3,4,5,6)
# Nested For
def function(n):
for i in range(0, n):
for j in range(i+1, n):
for k in range(j+1, n):
for l in range(k+1, n):
print(i, j, k, l)
function(7)
|
ddf2b2c775e974434cbc5c028584e77d1de5a54c | AUSG/study-2019-first | /algorithm/sangyeol/week4/1427.py | 618 | 3.8125 | 4 | # 문제
# 배열을 정렬하는 것은 쉽다. 수가 주어지면, 그 수의 각 자리수를 내림차순으로 정렬해보자.
# 입력
# 첫째 줄에 정렬하고자하는 수 N이 주어진다. N은 1,000,000,000보다 작거나 같은 자연수이다.
# 출력
# 첫째 줄에 자리수를 내림차순으로 정렬한 수를 출력한다.
# 예제 입력 1
# 2143
# 예제 출력 1
# 4321
number = input()
def numbers_range(number):
number_list = list(number)
number_list.sort(reverse=True)
str ... |
f9b2b6d5c28e5a991343e1b802676ed3bcd60f5a | Expire0/Python_modules | /find_prime_position.py | 408 | 4.03125 | 4 | def isPrime(n):
# Corner case
if (n <= 1):
return False
# Check from 2 to n-1
for i in range(2, n):
if (n % i == 0):
return False
return True
# Driver Program
mas = input("number please:")
count = 0
for i in range(0,int(mas)+2):
if isPrime(i):
... |
7f207fc959b85502e244af382d97e8c7abd42dee | sibieler/CS182-Final-Project-4-Player-Chess | /pieces.py | 14,264 | 3.515625 | 4 | import random
import math
import os
import time
import numpy as np
import copy
from multiprocessing import Pool
'''
High level piece class containing the attributes that every piece will share.
Pieces must be given a start position, color, direction, board and x(row) and
y(column) locations.
'''
class PIECE():
def __... |
346e28967bb72cfd0bd60f07a14880b9823c409c | divyesh-mistry/Python_practice | /tic-toc-toe/hw2.py | 9,564 | 4.75 | 5 | # make tic-toc-toe
# this is game now and lets try to understand git
#Tic-tac-toe (or noughts and crosses) is a simple strategy game in which two players take turns placing a mark on a 3x3 board, attempting to make a row, column, or diagonal of three with their mark. In this homework, we will use the tools we've cove... |
5bcf8e9d4e3a4896d951780c7bb1244c98f9c457 | phibra/Codewars | /FoldTo.py | 289 | 3.671875 | 4 | # https://www.codewars.com/kata/folding-your-way-to-the-moon/
def fold_to(distance):
foldCounter = 0
thickness = 0.0001
if distance < 0:
return None
while distance >= thickness:
thickness *= 2
foldCounter += 1
return foldCounter
|
be47571e07d252dff24a341d7d46b449b7f5f479 | fulcircle/algorithm_practice | /General/string_ordered_subsets.py | 762 | 3.78125 | 4 | def ordered_subsets_bottom_up(available_characters, curr_string="", ordered_subsets=None):
if not ordered_subsets:
ordered_subsets = []
if not isinstance(available_characters, list):
available_characters = list(available_characters)
for i in range(0, len(available_characters)):
... |
995ad0c0a252046ef64bb200718884fe532a3f9f | fulcircle/algorithm_practice | /data_structures/vik_tree.py | 876 | 3.828125 | 4 | from random import randint
# For reference
# CHILD_NODES = 2
# NUM_NODES = 24
class Node:
def __init__(self, value, visited=0):
self.value = value
self.visited = visited
self.children = []
self.data = None
def add_child(self, child):
self.children.appen... |
83307d2eaa61f9a94080d702e3ee2ceb613026db | fulcircle/algorithm_practice | /Leetcode/n_queens.py | 4,101 | 3.8125 | 4 | # The n-queens puzzle is the problem of placing n queens on an n×n chessboard such that no two queens attack each other.
#
# https://assets.leetcode.com/uploads/2018/10/12/8-queens.png
#
# Given an integer n, return all distinct solutions to the n-queens puzzle.
#
# Each solution contains a distinct board configuration... |
dfaddab01ecaeca6c6023d46fb8b36ef2d091ce2 | fulcircle/algorithm_practice | /data_structures/mergesort.py | 1,018 | 3.890625 | 4 |
my_list = [52,8,45,43,6,56,76,36,54,12,34,98,41,30,-1]
def mergesort_recursive(arr):
if len(arr) <= 1:
return arr
# divide array in half and merge sort recursively
half = len(arr) // 2
left = mergesort_recursive(arr[:half])
right = mergesort_recursive(arr[half:])
return... |
a89ea893b8f11bf22fc437b1b43ef3cc1e7a19a2 | themoat/Codeforces-problems | /Advanced_Recursion.py | 902 | 4.125 | 4 | a=[[1,1,0],[1,2,1],[1,0,2]]
def floodfill(a,r,c,tofill,prevfill): # yahaan pe, r and c denote the row and column we are at, or in paint we will click at.
#Let's mention out how many rows and columns are there
rows = len(a)
col = len(a[0])
#Since we are applyng recursion over here, so let's start with ... |
2a4152eea928df7c381968df9799cf2360b0c84d | zzhyzzh/Leetcode | /leetcode-algorithms/384. Shuffle an Array/Solution.py | 958 | 3.84375 | 4 | import random
class Solution(object):
nums = []
origin = []
length = 0
def __init__(self, nums):
"""
:type nums: List[int]
"""
self.nums = nums
self.origin = list(nums)
self.length = len(nums)
def reset(self):
"""
Resets the array to ... |
00c6c0f04a7d8e2c70a9ee8cde56fc6c0a541b1b | zzhyzzh/Leetcode | /leetcode-algorithms/002. Add Two Numbers/addTwoNumbers2.py | 1,350 | 3.71875 | 4 | # Definition for singly-linked list.
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
class Solution(object):
def addTwoNumbers(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
def nodeVal(... |
51d270c2e7fcd62d53a1a86a3659a1cdf88cfa89 | zzhyzzh/Leetcode | /leetcode-algorithms/412. Fizz Buzz/fizzBuzz.py | 552 | 3.671875 | 4 | class Solution(object):
def fizzBuzz(self, n):
"""
:type n: int
:rtype: List[str]
"""
fb_list = []
for i in range(1, n + 1):
if i % 15 == 0:
fb_list.append("FizzBuzz")
elif i % 5 == 0:
fb_list.append("Buzz")
... |
b92b478a0afe75ad77084c4ebd551e3b099fe961 | zzhyzzh/Leetcode | /leetcode-algorithms/048. Rotate Image/rotate.py | 619 | 3.84375 | 4 | import math
class Solution(object):
def rotate(self, matrix):
"""
:type matrix: List[List[int]]
:rtype: void Do not return anything, modify matrix in-place instead.
"""
if matrix == []:
return
n = len(matrix)
for i in range(n/2):
for j ... |
15431e8f873ef33d046ae7d78fe766671c6bdfc1 | zzhyzzh/Leetcode | /leetcode-algorithms/046. Permutations/permute.py | 635 | 3.78125 | 4 | class Solution(object):
def permute(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
combi_list = []
if nums == []:
return []
if len(nums) == 1:
return [nums]
else:
permute_list = self.permute(nums... |
ae635403d93b7ba75976692f0289d5eea2fbb350 | zzhyzzh/Leetcode | /leetcode-algorithms/019. Remove Nth Node From End of List/removeNthFromEnd2.py | 897 | 3.90625 | 4 | # Definition for singly-linked list.
# Given linked list: 1->2->3->4->5, and n = 2.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def removeNthFromEnd(self, head, n):
"""
:type head: ListNode
:type n: int
:rtype: ListNode
... |
234033390510d81889a70ed7e894bea312ac66a6 | zzhyzzh/Leetcode | /leetcode-algorithms/014. Longest Common Prefix/longestCommonPrefix.py | 837 | 3.546875 | 4 | import re
class Solution:
def longestCommonPrefix(self, strs):
"""
:type strs: List[str]
:rtype: str
"""
LCP = ""
maxLen = 0
i, j = 0, 0
if strs == [] or strs[0] == "":
return LCP
else:
LCP_temp = strs[0][j]
whi... |
484d0519f4f394f83869d49826580fd93315f894 | zzhyzzh/Leetcode | /leetcode-algorithms/142. Linked List Cycle II/detectCycle2.py | 851 | 3.71875 | 4 | # Definition for singly-linked list.
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
class Solution(object):
def detectCycle(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
fast = head
slow = head
wh... |
217460f6027af8bbb5af4e3de270f3dc3a348051 | zzhyzzh/Leetcode | /leetcode-algorithms/287. Find the Duplicate Number/findDuplicate.py | 507 | 3.53125 | 4 | class Solution:
def findDuplicate(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
fastPtr = 0
slowPtr = 0
while True:
fastPtr = nums[fastPtr]
fastPtr = nums[fastPtr]
slowPtr = nums[slowPtr]
if fastPtr == s... |
1b986158695b8b0b01da18152ac2c4a142c0e6b2 | zzhyzzh/Leetcode | /leetcode-algorithms/202. Happy Number/isHappy2.py | 532 | 3.625 | 4 | class Solution(object):
def isHappy(self, n):
"""
:type n: int
:rtype: bool
"""
def digitSquareSum(n):
return sum([int(digit) ** 2 for digit in str(n)])
hastSet = set()
happy = n
while happy not in hastSet:
hastSet.add(happy)
... |
ef5bf257e9b98f693e509212fe579e6bcf789ed7 | zzhyzzh/Leetcode | /leetcode-algorithms/205. Isomorphic Strings/isIsomorphic.py | 593 | 3.765625 | 4 | class Solution(object):
def isIsomorphic(self, s, t):
"""
:type s: str
:type t: str
:rtype: bool
"""
def check(s,t):
hashMap = {}
for i in range(len(s)):
if s[i] not in hashMap:
hashMap[s[i]] = t[i]
... |
a1c9a574d52f8e5f690eb8b966ca3a55256be997 | jxhangithub/lintcode | /Medium/106. Convert Sorted List to Binary Search Tree/Solution.py | 1,043 | 3.8125 | 4 | """
Definition of ListNode
class ListNode(object):
def __init__(self, val, next=None):
self.val = val
self.next = next
Definition of TreeNode:
class TreeNode:
def __init__(self, val):
self.val = val
self.left, self.right = None, None
"""
class Solution:
"""
@param: he... |
6c7ff3bc7a7d84f7303529760673baad285088a1 | jxhangithub/lintcode | /DFS/153.Combination Sum II/Solution.py | 1,219 | 3.609375 | 4 | class Solution:
"""
@param num: Given the candidate numbers
@param target: Given the target number
@return: All the combinations that sum to target
"""
def combinationSum2(self, num, target):
# write your code here
self.results = []
if not num or len(num) == 0:
... |
89feed43be62bdb9416af70d063e4edfc7a0c23f | jxhangithub/lintcode | /Heap/401.Kth Smallest Number in Sorted Matrix/Solution.py | 1,059 | 3.515625 | 4 | from heapq import heappush, heappop
class Solution:
"""
@param matrix: a matrix of integers
@param k: An integer
@return: the kth smallest number in the matrix
"""
dx = [0, 1]
dy = [1, 0]
def kthSmallest(self, matrix, k):
# write your code here
if not matrix or len(mat... |
8ffcb523071924594cfa705119e913c006ccb58c | jxhangithub/lintcode | /Two_Pointers/406.Minimum Size Subarray Sum/Solution_2.py | 629 | 3.609375 | 4 | # 模版 2: 枚举右端点,左端点不回头
class Solution:
"""
@param nums: an array of integers
@param s: An integer
@return: an integer representing the minimum size of subarray
"""
def minimumSize(self, nums, s):
ans = sys.maxsize
left = 0
addup = 0
for ... |
6bbe3d1ba547642b182c412c19f0c0abd9eb8412 | jxhangithub/lintcode | /Easy/111. Climbing Stairs/Solution.py | 388 | 3.65625 | 4 | class Solution:
"""
@param n: An integer
@return: An integer
"""
def climbStairs(self, n):
# write your code here
if n == 1:
return 1
if n == 0:
return 0
dp = [sys.maxint] * (n + 1)
dp[1], dp[2] = 1, 2
for i in xrange(3, n + ... |
518a716768449feb3c7d3f19e8523613010117ac | jxhangithub/lintcode | /Stack/126.Max Tree/Solution_DFS.py | 867 | 3.8125 | 4 | """
Definition of TreeNode:
class TreeNode:
def __init__(self, val):
self.val = val
self.left, self.right = None, None
"""
class Solution:
"""
@param A: Given an integer array with no duplicates.
@return: The root of max tree.
"""
def maxTree(self, A):
# write your code ... |
d33d1aa46021b3a26787471c81c3ad3e7c15e056 | jxhangithub/lintcode | /Easy/595. Binary Tree Longest Consecutive Sequence/Solution.py | 1,055 | 4.03125 | 4 | """
Definition of TreeNode:
class TreeNode:
def __init__(self, val):
self.val = val
self.left, self.right = None, None
"""
class Solution:
"""
@param root: the root of binary tree
@return: the length of the longest consecutive sequence path
"""
def __init__(self):
self.l... |
ee4dcae87b0b1327078ffab3bd824a82cc1f2027 | jxhangithub/lintcode | /Easy/988. Arranging Coins/Solution.py | 797 | 3.59375 | 4 | class Solution:
"""
@param n: a non-negative integer
@return: the total number of full staircase rows that can be formed
"""
def arrangeCoins(self, n):
# Write your code here
start, end = 0, n
while start + 1 < end:
mid = (end - start) / 2 + start
if ... |
0cafa24f765067c72db7d92960ad480206f27298 | jxhangithub/lintcode | /Heap/543.Kth Largest in N Arrays/Solution_MaxHeap.py | 950 | 3.71875 | 4 | import heapq
class Solution:
"""
@param arrays: a list of array
@param k: An integer
@return: an integer, K-th largest element in N arrays
"""
def KthInArrays(self, arrays, k):
if not arrays:
return None
# in order to avoid directly changing the original arrays
... |
0a6c94fa6ef85e99e8e80c7b0d255e58c7cf1ed5 | jxhangithub/lintcode | /Heap/486.Merge K Sorted Arrays/Solution_DivideConquer.py | 1,094 | 3.84375 | 4 | class Solution:
"""
@param arrays: k sorted integer arrays
@return: a sorted array
"""
def mergekSortedArrays(self, arrays):
# write your code here
if not arrays or len(arrays) == 0:
return arrays
new_array = self._mergeKArrays(arrays, 0, len(arrays) - 1)
... |
2225e912e98d915bbc1892b782fbaa60aa8384ea | jxhangithub/lintcode | /DFS/33.N-Queens/Solution.py | 1,388 | 3.578125 | 4 | class Solution:
"""
@param: n: The number of queens
@return: All distinct solutions
"""
def solveNQueens(self, n):
# write your code here
self.solutions = []
if not n or n < 0:
return self.solutions.append([])
self._dfs(0, n, [])
results = self._d... |
a7d425fd4231c9475d2edb8d2ab8d0e11a024e41 | jxhangithub/lintcode | /Dynamic_Programming/1259.Integer Replacement/Solution_DFS.py | 529 | 3.5 | 4 | class Solution:
"""
@param n: a positive integer
@return: the minimum number of replacements
"""
def integerReplacement(self, n):
# Write your code here
ans = {}
return self.dfs(ans, n)
def dfs(self, ans, n):
if n == 1:
return 0
if n in ans... |
c4f88c9a4ace79913c701465b8b2017120959acb | jxhangithub/lintcode | /Linked_List/450.Reverse Nodes in k-Group/Solution.py | 985 | 3.890625 | 4 | """
Definition of ListNode
class ListNode(object):
def __init__(self, val, next=None):
self.val = val
self.next = next
"""
class Solution:
"""
@param head: a ListNode
@param k: An integer
@return: a ListNode
"""
def reverseKGroup(self, head, k):
# write your code her... |
fac81f6b24c9933df8064ad4b9516a960f05a752 | jxhangithub/lintcode | /Bit_Manipulation/83.Single Number II/Solution.py | 525 | 3.59375 | 4 | class Solution:
"""
@param A: An integer array
@return: An integer
"""
def singleNumberII(self, A):
# write your code here
if not A or len(A) % 3 != 1:
return -1
bits = [0 for _ in range(32)]
for a in A:
for j in range(32):
if ... |
06f45c5721853895d80e5d3f96e1cc952356f19c | jxhangithub/lintcode | /String/640.One Edit Distance/Solution_DP.py | 943 | 3.515625 | 4 | class Solution:
"""
@param s: a string
@param t: a string
@return: true if they are both one edit distance apart or false
"""
def isOneEditDistance(self, s, t):
# write your code here
if s == t:
return False
if abs(len(s) - len(t)) > 1:
return Fal... |
f2cb7759300d39d253848280cdbb37f4b1b457a0 | jxhangithub/lintcode | /Array/1287.Increasing Triplet Subsequence/Solution.py | 569 | 3.859375 | 4 | class Solution:
"""
@param nums: a list of integers
@return: return a boolean
"""
def increasingTriplet(self, nums):
# write your code
if not nums or len(nums) < 3:
return False
smallest, second_smallest = sys.maxsize, sys.maxsize
for num in nums:
... |
9b740b3ec1917602975180a890614c5654cb5918 | jxhangithub/lintcode | /Binary_Search/62.Search in Rotated Sorted Array/Solution_two_pass_binary_search.py | 1,126 | 3.75 | 4 | class Solution:
"""
@param A: an integer rotated sorted array
@param target: an integer to be searched
@return: an integer
"""
def search(self, A, target):
if not A:
return -1
index = self._find_min_index(A)
if A[index] <= target <= A[-1]:
... |
e26da75e5765c1ae63ef9769a558ae8e42ac432c | jxhangithub/lintcode | /Medium/47. Majority Element II/Solution.py | 844 | 3.953125 | 4 | """
47. Majority Element II
"""
# O(n logn) time
# O(1) extra space
class Solution:
"""
@param: nums: a list of integers
@return: The majority number that occurs more than 1/3
"""
def majorityNumber(self, nums):
# write your code here
nums.sort()
step = len(nums) / 3
... |
4d3777255ac3ddd8e53c95e2b68e24bb687954a6 | jxhangithub/lintcode | /Dynamic_Programming/115.Unique Paths II/Solution.py | 1,216 | 3.75 | 4 | class Solution:
"""
@param obstacleGrid: A list of lists of integers
@return: An integer
"""
OBSTACLE = 1
EMPTY = 0
def uniquePathsWithObstacles(self, obstacleGrid):
# write your code here
if not obstacleGrid or len(obstacleGrid) == 0 or len(obstacleGrid[0]) == 0:
... |
f06c94ffd35079e8e4e4abe00b74c1f94a5550fc | jxhangithub/lintcode | /BFS/7.Serialize and Deserialize Binary Tree/Solution_DFS.py | 1,007 | 3.625 | 4 | class Solution:
def serialize(self, root):
# write your code here
if not root:
return ['#']
ans = []
ans.append(str(root.val))
ans += self.serialize(root.left)
ans += self.serialize(root.right)
return ans
def deserialize(self, data):
... |
02ad572c74503763880319d431ac0834ca38461d | jxhangithub/lintcode | /Stack/510.Maximal Rectangle/Solution.py | 972 | 3.5 | 4 | class Solution:
"""
@param matrix: a boolean 2D matrix
@return: an integer
"""
def maximalRectangle(self, matrix):
# write your code here
area = 0
if not matrix or len(matrix) == 0 or len(matrix[0]) == 0:
return area
height = [0 for _ in range(len(matrix[... |
0ce96ac8992737ba503f6a6b401a8c6843fdfdf4 | jxhangithub/lintcode | /Array/1065.My Calendar I/Solution_Array.py | 671 | 3.5625 | 4 | class MyCalendar:
def __init__(self):
self.events = []
def book(self, start, end):
"""
:type start: int
:type end: int
:rtype: bool
"""
if len(self.events) == 0:
self.events.append([start, end])
return True
else:
... |
fd5183532e7a0862df6412eb8be79bbd47d672bd | jxhangithub/lintcode | /Tree/472.Binary Tree Path Sum III/Solution.py | 1,272 | 3.828125 | 4 | """
Definition of ParentTreeNode:
class ParentTreeNode:
def __init__(self, val):
self.val = val
self.parent, self.left, self.right = None, None, None
"""
class Solution:
"""
@param: root: the root of binary tree
@param: target: An integer
@return: all valid paths
"""
def b... |
3d76a03bdf7f0f11d8d28ec5103448721543dc76 | jxhangithub/lintcode | /Heap/4.Ugly Number II/Solution.py | 600 | 3.546875 | 4 | from heapq import heappush, heappop
class Solution:
"""
@param n: An integer
@return: return a integer as description.
"""
def nthUglyNumber(self, n):
# write your code here
pq = []
history = set()
history.add(1)
heappush(pq, 1)
count, res = 0, -1
... |
75d12563692a9fb6c03d3aabec681d6294ddd9f3 | jxhangithub/lintcode | /BFS/7.Serialize and Deserialize Binary Tree/Solution_BFS.py | 2,455 | 4.0625 | 4 | from collections import deque
"""
Definition of TreeNode:
class TreeNode:
def __init__(self, val):
self.val = val
self.left, self.right = None, None
"""
class Solution:
"""
@param root: An object of TreeNode, denote the root of the binary tree.
This method will be invoked first, you s... |
ce056c49695cd292d8146729f819d6529d80b6f4 | jxhangithub/lintcode | /Interviews/amazon/1797.optimalUtilization/Solution_BinarySearch.py | 1,097 | 3.5 | 4 | class Solution:
"""
@param A: a integer sorted array
@param B: a integer sorted array
@param K: a integer
@return: return a pair of index
"""
def optimalUtilization(self, A, B, K):
# write your code here
if not A or not B:
return []
if A[0] + B[0] > K:
... |
09a4dda2bded10ed30e037e17f5c896d612f5bdd | jxhangithub/lintcode | /Hash/124.Longest Consecutive Sequence/Solution.py | 569 | 3.640625 | 4 | class Solution:
"""
@param num: A list of integers
@return: An integer
"""
def longestConsecutive(self, num):
# write your code here
max_len = 0
if not num or len(num) == 0:
return max_len
mapping = {number:True for number in num}
for i in range(l... |
d1bde956b5126aa2258893510938a1bb77ad834a | jxhangithub/lintcode | /Medium/130. Heapify/Solution.py | 789 | 3.5 | 4 | class Solution:
"""
@param: A: Given an integer array
@return: nothing
"""
def heapify(self, A):
# write your code here
n = len(A)
for i in range(n, -1, -1):
self.helper(A, i)
def helper(self, A, i):
lowest = i # root is the smallest ele... |
e8a7cefc4da6a1d505339470cb11d50ca8dd996e | jxhangithub/lintcode | /BFS/375.Clone Binary Tree/Solution_BFS.py | 1,119 | 3.78125 | 4 | """
Definition of TreeNode:
class TreeNode:
def __init__(self, val):
self.val = val
self.left, self.right = None, None
"""
class Solution:
"""
@param root: The root of binary tree
@return: root of new tree
"""
def cloneTree(self, root):
# write your code here
if ... |
d9a4c9d582dacb3c5718100804a3bd9aa8c2732c | jxhangithub/lintcode | /Two_Pointers/373.Partition Array by Odd and Even/Solution.py | 698 | 3.65625 | 4 | class Solution:
"""
@param: nums: an array of integers
@return: nothing
"""
def partitionArray(self, nums):
# write your code here
if not nums or len(nums) == 0:
return nums
left, right = 0, len(nums) - 1
while left <= right:
while left <= rig... |
36ae3ffb781402d3c29f41e4701358789fb0c480 | jxhangithub/lintcode | /Stack/601.Flatten 2D Vector/Solution_Deque.py | 1,073 | 3.828125 | 4 | from collections import deque
class Vector2D(object):
# @param vec2d {List[List[int]]}
def __init__(self, vec2d):
# Initialize your data structure here
self.queue = deque(vec2d)
self.next_elem = None
# @return {int} a next element
def next(self):
# Write your code here... |
6c0f8eacedd25f9a08b4c63a05289c51f96868d0 | jxhangithub/lintcode | /Easy/96. Partition List/Solution.py | 887 | 3.953125 | 4 | """
Definition of ListNode
class ListNode(object):
def __init__(self, val, next=None):
self.val = val
self.next = next
"""
class Solution:
"""
@param head: The first node of linked list
@param x: An integer
@return: A ListNode
"""
def partition(self, head, x):
# writ... |
2ce6695b64cdb2a07c59bbc81ee5c2a66e8829a5 | jxhangithub/lintcode | /Union_Find/1257.Evaluate Division/Solution.py | 3,423 | 3.640625 | 4 | # 并查集里的变量:
# ra, rb 代表 a 的 root, b 的 root
# a_b 代表 a/b 的值
# self.root 存的是 某个node(比如a) 的 root, 以及 a/root的值 (node / node's root)
class UnionFind:
def __init__(self):
self.root = {}
# 这里 a 是分子,b是分母,这题我们总是把分母作为root
def union(self, a, b, a_b):
# 由于是在线问题,不能预先存好图,进来的节点不一定之前存在
# 因为一开始,每... |
1e96d6258e4c6e37334562182445ccaa4613af08 | jxhangithub/lintcode | /Heap/486.Merge K Sorted Arrays/Solution_heapq.py | 638 | 3.78125 | 4 | import heapq
class Solution:
"""
@param arrays: k sorted integer arrays
@return: a sorted array
"""
def mergekSortedArrays(self, arrays):
# write your code here
result = []
heap = []
for index, array in enumerate(arrays):
if len(array) == 0:
... |
f52a06cc424ceb0c91e5470d3e675030867f4ba5 | jxhangithub/lintcode | /BFS/242.Convert Binary Tree to Linked Lists by Depth/Solution_DFS.py | 912 | 3.90625 | 4 | """
Definition of TreeNode:
class TreeNode:
def __init__(self, val):
this.val = val
this.left, this.right = None, None
Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
"""
class Solution:
# @param {TreeNode} root the root... |
b4fd2625e2dcdfb8b717b6980207d592cd63d1f1 | jxhangithub/lintcode | /Easy/209. First Unique Character in a String/Solution.py | 489 | 3.59375 | 4 | class Solution:
"""
@param s: str: the given string
@return: char: the first unique character in a given string
"""
def firstUniqChar(self, s):
# Write your code here
mapping = {}
if not s or len(s) <= 0:
return '0'
for idx, char in enumerate(s):
... |
60e0fa3af1eca5fbd52590f7622545097db1a8be | jxhangithub/lintcode | /Tree/480.Binary Tree Paths/Solution.py | 1,853 | 4.15625 | 4 | """
Definition of TreeNode:
class TreeNode:
def __init__(self, val):
self.val = val
self.left, self.right = None, None
"""
class Solution:
"""
@param root: the root of the binary tree
@return: all root-to-leaf paths
"""
def binaryTreePaths(self, root):
# write your code ... |
b42679765d1fb505daf63dddb75a827e275fb7fb | jxhangithub/lintcode | /Union_Find/434.Number of Islands II/Solution.py | 1,877 | 3.90625 | 4 | """
Definition for a point.
class Point:
def __init__(self, a=0, b=0):
self.x = a
self.y = b
"""
class Solution:
"""
@param n: An integer
@param m: An integer
@param operators: an array of point
@return: an integer array
"""
dx = [0, 0, 1, -1]
dy = [1, -1, 0, 0]
... |
536ebef16ef34abc3ab20ec1ad2f1d4d7bcb4215 | jxhangithub/lintcode | /Linked_List/36.Reverse Linked List II/Solution.py | 1,097 | 3.890625 | 4 | """
Definition of ListNode
class ListNode(object):
def __init__(self, val, next=None):
self.val = val
self.next = next
"""
class Solution:
"""
@param head: ListNode head is the head of the linked list
@param m: An integer
@param n: An integer
@return: The head of the reversed Li... |
fbd664570d82402104788e7cfbdcebd7a34a4d5c | jxhangithub/lintcode | /Medium/11. Search Range in Binary Search Tree/Solution.py | 4,817 | 3.515625 | 4 | # 本参考程序来自九章算法,由 @This is Anfield 提供。版权所有,转发请注明出处。
# - 九章算法致力于帮助更多中国人找到好的工作,教师团队均来自硅谷和国内的一线大公司在职工程师。
# - 现有的面试培训课程包括:九章算法班,系统设计班,算法强化班,Java入门与基础算法班,Android 项目实战班,
# - Big Data 项目实战班,算法面试高频题班, 动态规划专题班
# - 更多详情请见官方网站:http://www.jiuzhang.com/?source=code
class Solution:
"""
@param: root: param root: The root of t... |
b9f52d9ed43515dcc913c8f1f33ce1362c51b412 | jxhangithub/lintcode | /Tree/1197.Find Bottom Left Tree Value/Solution.py | 678 | 3.765625 | 4 | """
Definition of TreeNode:
class TreeNode:
def __init__(self, val):
self.val = val
self.left, self.right = None, None
"""
class Solution:
"""
@param root: a root of tree
@return: return a integer
"""
def findBottomLeftValue(self, root):
# write your code here
... |
e2e08dc1bcd1c2fa5dbe7b996d9e6d74e8b818d1 | robertacristinaabreu01/Roberta_REDES | /Decisao1/decisaoSimples.py | 232 | 3.765625 | 4 | nome=input("Digite o nome: ")
idade = int(input("Digite a sua idade: "))
prioridade="NÃO"
if idade>=65:
prioridade="SIM"
print("O paciente " + nome + " possui atendimento prioritário? " + prioridade)
#decisão simples |
71ceb987e54e6349931156682ec12e926c2c0c2d | jaroslavhradsky/python-sandbox | /numpy/gradients.py | 575 | 3.515625 | 4 | # Incorporation of NumPy with OpenCV
import numpy as np
import cv2
# 256x256 pixel array with a horizontal gradient from 0 to 255 for the red color channel
r = np.reshape(np.arange(256*256)%256,(256,256))
# array of same size and type as r but filled with 0s for the green color channel
g = np.zeros_like(r)
# tr... |
58d4d2be32641e836326a11a452a955422c05849 | ayarimatsui/Google_Step_Program | /week_1/win_the_game_auto.py | 6,304 | 3.578125 | 4 | # Homework2の発展課題 自動化したもの
# i can haz wordz で高得点取れる文字列を返すプログラム
import chromedriver_binary
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.chrome.options import Options
from bs4 import BeautifulSoup
import pyperclip
import time
import collections
# ファイル'dictionary... |
f33bf95a96dec4a7b2ee43e16717412f680661ae | ayarimatsui/Google_Step_Program | /week_4/homework2/homework2.py | 4,170 | 3.828125 | 4 | from collections import deque
import heapq
class Page:
def __init__(self, name):
self.name = name
self.link_to = []
self.link_from = []
def add_link_to(self, page_id):
self.link_to.append(page_id)
def add_link_from(self, page_id):
self.link_from.append(page_id)
... |
efb3ce9bda83cb42bce90338e1b122351239acb5 | ayarimatsui/Google_Step_Program | /review/week_1/find_anagram1_bisect.py | 1,865 | 3.890625 | 4 | # Google STEP 2020 Week1 Homework1 Review
# 普通のアナグラムを辞書から探して返すプログラム
# 二分探索を利用
import bisect
import time
from key_list import KeyList
# 辞書のデータファイルを読み込む関数
def read_dic(file):
# 辞書データのファイルを読み込み、全て小文字に変換してリストdictionaryに格納
with open(file) as f:
dictionary = [s.strip().lower() for s in f]
return dicti... |
6723ecb0e1e7da15b63c822e8827e868ba53bd34 | Swift-2016/Python | /py001/Python3.5/control.py | 236 | 3.890625 | 4 | __author__ = 'xray'
# All the Flow You’d Expect
# For loop on a list
>>> numbers = [2, 4, 6, 8]
>>> product = 1
>>> for number in numbers:
... product = product * number
...
>>> print('The product is:', product)
The product is: 384 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.