blob_id
stringlengths
40
40
repo_name
stringlengths
5
127
path
stringlengths
2
523
length_bytes
int64
22
3.06M
score
float64
3.5
5.34
int_score
int64
4
5
text
stringlengths
22
3.06M
f805fcf8ca04dc8d23d6b0e2f27351b19d922c29
owendeng90/python_learn
/python学习/20191020_for星号输出1.py
865
3.765625
4
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2019/10/20 11:48 # @Author : owen # @Site : # @File : 20191020_for星号输出1.py # @Software: PyCharm Community Edition # @Code thought #类型3 numrows=1 while numrows <=6: print('') numcolumns=6 while numcolumns >0: if numcolumns<=numrows:...
554f27076bba32f42f26bc791bc362d88bb3e223
owendeng90/python_learn
/python学习/20191020_整数金字塔.py
665
3.796875
4
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2019/10/20 11:48 # @Author : owen # @Site : # @File : 20191020_for星号输出1.py # @Software: PyCharm Community Edition # @Code thought num = int(input("请输入任意整数(1-15)\n")) for numrows in range(1,num+1): print('') for numcolumns in range(1,2*num): ...
dd96f05dc6a33e705b1f88fad871384a55dbb5b5
tomassabol/ivo_turtleproject
/pong_game.py
2,801
3.734375
4
import turtle # screen config screen = turtle.Screen() screen.title("Pong game") screen.bgcolor("black") screen.setup(width=1000, height=600) # left pad left_pad = turtle.Turtle() left_pad.speed(0) left_pad.color("white") left_pad.shape("square") left_pad.shapesize(stretch_wid=6, stretch_len=2) left_pad.penup() lef...
76760bc59e273a7589abec7fdea5eca25c4961e9
lolpatrol/Advent-of-Code-2018
/Day5.py
589
3.53125
4
import string def part1(data): reduced = [] for letter in data: if reduced and abs(ord(letter) - ord(reduced[-1])) == 32: reduced.pop() else: reduced.append(letter) return len(reduced) def part2(data): smallest = len(data) for letter in string.ascii_lowerc...
876942c68f9f07c1f7cfca1580fce89d25b761d3
brendend/AutomateTheBoringStuff
/calc100.py
108
3.515625
4
total = 0 for I in range(101): total = total + I print('The calculated value is ' + (str(total)) + '.')
e21f0a7925825ae1496db0b0b2be3a90e89a03bc
arthurckl/ABC
/jogo_revisao.py
3,106
4.125
4
# -*- coding: utf-8 -*- """ Created on Mon Aug 3 14:29:27 2015 @author: Arthur Game Rock-Paper-Scissors-Spock-Lizard: With the old rules of Rock-Paper-Scissors, but now there are two more options, Spock and Lizard. """ import random A = ["rock","paper","scissors","spock","lizard"] B = {"rock":["paper","lizard","sp...
ec541b14059808cf538ba11ffa9645488d70f4f4
BuseMelekOLGAC/GlobalAIHubPythonHomework
/HANGMAN.py
1,602
4.1875
4
print("Please enter your name:") x=input() print("Hello,"+x) import random words = ["corona","lung","pain","hospital","medicine","doctor","ambulance","nurse","intubation"] word = random.choice(words) NumberOfPrediction = 10 harfler = [] x = len(word) z = list('_' * x) print(' '.join(z), end='\n') while Num...
7468cd814c2d83c6ccc40ce5fd700f5bde47ad41
Yury31/yury-siarhey
/lesson4.4_siarhey.py
337
3.75
4
try: x = int(input('Insert the number >> ')) except ValueError: print('Wrong value! Bye-bye!!') quit() while True: print('If you wanna kB press #1') print('Or press #2 for bytes!') break y = int(input('>> ')) if y == 1: print(x*1024, 'kB') elif y == 2: print(x/1024, 'b') else: print(...
6520609ec4b3bc30a6d61abc23a092b112bd1062
MindCC/ml_homework
/Lab02/Answer/TSPInstance.py
3,097
3.53125
4
import math from os import path import numpy as np import matplotlib.pyplot as plt class TSPInstance: ''' file format: city number best known tour length list of city position (index x y) best known tour (city index starts from 1) ''' def __init__(self, file_name): self.__fil...
cc0b8ef1943eb8b6b5b42870be3387bbde4f8001
MindCC/ml_homework
/Lab02/Question/lab2_Point.py
2,008
4.46875
4
# -*- coding: cp936 -*- ''' ID: Name: ''' import math class Point: ''' Define a class of objects called Point (in the two-dimensional plane). A Point is thus a pair of two coordinates (x and y). Every Point should be able to calculate its distance to any other Point once the second point is speci...
0b57a9545507ed95c6f205e680e6436645fffc68
jacareds/Unis
/2020.4_Atv2_Exer5.py
278
4.25
4
#Escreva uma função que: #a) Receba uma frase como parâmetro. #b) Retorne uma nova frase com cada palavra com as letras invertidas. def inverText(text): inversor = (text) print(inversor[::-1]) entradInput = str(input("Digite uma frase: ")) inverText(entradInput)
01b1090b01fa027571889fe82558817034faffc9
Hdwig/Math
/Lesson_3.2.1.py
368
3.609375
4
import numpy as np import matplotlib.pyplot as plt import math a = 10 a2 = a ** 2 b = 2 b2 = b ** 2 xm = [] xp = [] yp = [] ym = [] for i in np.linspace(-10, 10, 1000): x1 = i xp.append(x1) yp.append(math.sqrt(b2 - (x1 ** 2 * b2) / a2)) ym.append(-math.sqrt(b2 - (x1 ** 2 * b2) / a2)) plt.plot(xp, yp) p...
5b8b45455631739e209fb0e92c057826e523cc66
pesanteur/google_flight_api
/google_flight/querybuilder.py
434
3.8125
4
import json with open('airports.json') as data_file: data = json.load(data_file) def get_iata_num(location): "Get IATA number for a given city." # TODO: Make thi sbetter so it can find cities with similar names or find multiple airports in the same city for i in data: city = data[i]['city'] ...
838a748326aaac421224ae0ccb3e61363269c924
AnimatedRNG/splash-2016-conway
/snowflake.py
2,373
3.546875
4
#!/bin/env python3 from life_renderer import LifeWindow from random import randint ROWS, COLS = 100, 100 cells = [[]] def printall(): global cells for i in range(ROWS): for j in range(COLS): if cells[i][j] > 0: print((i, j, cells[i][j])) def setup(life_window): global cells cells = [[0 for r in range(...
edfbde378792e76035957665b102df3c7b59ad05
HyunaShin/AlgorithmStudy
/coding_interview_conquer/bfs.py
1,126
3.921875
4
vertex_list = ["A", "B", "C", "D", "E", "F", "G"] edge_list = [(0,1), (1,2), (1,3), (3,4), (4,5), (1,6)] graphs = (vertex_list, edge_list) def bfs(graph , start): ''' 너비 우선 탐색은 queue를 활용한 탐색법이다. 방법은 다음과 같다. 1. 시작 노드를 정한다. 2. 노드를 큐에 넣는다. 3. dequeue한다. --> dequeue한 노드의 인접 노드를 queue에 넣는다.이 때 이미 방문...
55337a14b3c2b6a3b77a54fcb77281f34f754566
geluso/learn-programming-programming-board-games
/03-grid-games/02-battleship/battleship-py/battleship_board_displayer.py
1,612
3.671875
4
from util import direction_to_dx_dy def display_board(board): print() print("Ships left:") print("X: 2[ ] 3[ ] 3[ ] 4[ ] 5[ ]") print("O: 2[ ] 3[ ] 3[ ] 4[ ] 5[ ]") print() print(" 1 2 3 4 5 6 7 8 9 ") rows = list("ABCDEFGH") for letter, row in zip(r...
3864ed6af4d0e73cb8d67a6441188e47d56518a9
geluso/learn-programming-programming-board-games
/02-card-games/03-poker/00-hand-detection/ranking.py
1,805
3.5625
4
class Rank: def __init__(self): pass def rank(self): """Stuff hand is an array of five Cards """ hands = [ self.is_royal_flush, self.is_straight_flush, self.is_four_of_a_kind, self.is_full_house, self.is_flush, self.is_straight, self....
85814d21f5ab1f57385cad9a4317f74c64e5ce70
geluso/learn-programming-programming-board-games
/02-card-games/03-poker/00-hand-detection/card.py
1,051
3.546875
4
SPADES = 'spades' CLUBS = 'clubs' DIAMONDS = 'diamonds' HEARTS = 'hearts' SUITS = [SPADES, CLUBS, DIAMONDS, HEARTS] FACES = [2, 3, 4, 5, 6, 7, 8, 9, 10, 'J', 'Q', 'K', 'A'] class Card: def __init__(self, face, suit): self.face = face self.suit = suit @classmethod def from_str(cls, str): ...
09157861238e085199b31fd12f1df22076e3a0ea
Mizoguchi-Yuhei/udemy-kame-python
/input.py
889
3.953125
4
# input(): ユーザーの入力した値(文字列)を取得する # age = input("何歳ですか?") # print("あなたは{}歳です。".format(age)) age = int(input("何歳ですか?")) # age = int(age) casino_age = 18 game_text = """プレイするゲームを選択してください。 1: ルーレット 2: ブラックジャック 3: ポーカー """ if age >= casino_age: print("どうぞカジノにお入りください。") game = input(game_text) if game == "1": ...
e2259e34e5a91d547e72dd1c516a745cf64faa1e
Mizoguchi-Yuhei/udemy-kame-python
/string_basic.py
269
3.53125
4
# 文字列(String) print("Hello World!!") print('1') print("I'm fine.") print('I"m fine.') print(""" Hello world!! How are you doing? """) print("Hello \nworld") print("Hello \tworld") print("back slash n: \\n") print('I\'m fine') print("hello" + "world" + "!!")
cc1fc1f9c827d29495d1d0b8849d2520467af3a6
Mizoguchi-Yuhei/udemy-kame-python
/range.py
360
3.984375
4
# range(start, stop, step) # for i in range(1, 7): # for i in range(1, 7, 1): # print(i) for i in range(7): print(i) # for i in range(4, 13, 2) # print(i) for _ in range(10): print("hello") for i in range(1, 51): if i % 15 == 0: print("FizzBuzz") elif i % 3 == 0: print("Fizz") elif i % 5 == 0...
dc7c432deb82bf1f07e3f6e2b0632fb515c5ed62
DiegoAyalaH/Mision-04
/Rectangulos.py
1,626
4.25
4
#Nombre Diego Armando Ayala Hernández #Matrícula A01376727 #resumen del programa: Obtiene los datos de dos rectangulos y te da el area y el perimetor de ambos #Calcula el área de un rectángulo def calcularArea(altura, ancho): area = altura * ancho return area #Calcula el perímetro de un rectángulo def calcu...
c0bb13e71c4175bd2d6f5b509e437caa2dbf41cd
adrian-popa/fundamentals-of-programming
/Assignment05-07/src/domain/grade.py
1,097
3.734375
4
class Grade: """ Grade domain class """ def __init__(self, assignment_id, student_id, grade=None): """ Constructor for grade domain class assignment_id - The assignment's ID (integer) student_id - The student's ID (integer) grade - The grade's value (integer) ...
3066c478740dd4d5974e7e0209a5c99f90f421ce
adrian-popa/fundamentals-of-programming
/tests/Hammurabi/src/validators/game_validator.py
1,444
3.53125
4
from controllers.controller_exception import ControllerError class GameValidator: @staticmethod def validate_turn(situation, acres_to_buy_sell, units_to_feed_population, acres_to_plant): land_price = situation.get_land_price() grain_stocks = situation.get_grain_stocks() if acres_to_bu...
33b31428f2451f5acd5e148e01ea18db564f540f
adrian-popa/fundamentals-of-programming
/Assignment05-07/out/production/Assignment05-07/controllers/student_controller.py
2,169
3.578125
4
from domain.student import Student class StudentController: """ Student controller class """ def __init__(self, student_validator, student_repository): """ Constructor for student controller class student_validator - The student validator for validating a student stude...
f6c77714d04c741fda5667435f26fc15d161a268
room77/py77
/pylib/util/math/errors.py
654
3.890625
4
""" Math function related errors """ __author__ = "Kar Epker, karepker@gmail.com" __copyright__ = "Room 77, Inc. 2013" class NotDefinedError(Exception): """Error to raise when the operation is not defined""" def __init__(self, operation, arg_dict): """Builds a not defined error Args: operation (st...
f98807412c2d9a098f5830c012e2b66cc561e844
leztien/utilities
/datasets/make_3D_S_shape_out_of_2D_data.py
1,001
3.5
4
def make_3D_S_shape_out_of_2D_data(data): import numpy as np assert isinstance(data, np.ndarray) and data.ndim == 2, "wrong input data" X = data t = (X[:,0] - X[:,0].mean()) * np.pi * 3 x = np.sin(t) y = (np.cos(t)-1) * np.sign(t) z = X[:,-1] X = np.vstack([x,y,z]).T # rot...
2bd760b8f685c2483606200f2d2161363f50e21e
leztien/utilities
/ml/utility_functions_from_project001.py
27,850
3.5625
4
class Coord: def __init__(self, hours, minutes=None): minutes = minutes or 0 assert -180 <= hours <= 180, "bar hours provided" assert 0 <= minutes < 60, "bad mintes provided" self.hours, self.minutes = hours, minutes def __str__(self): s = "{:>02}{}...
f5ba37f91a469a245113b30d1a37e8ad171ab278
chensxb97/Homework_2
/postingList.py
2,445
3.609375
4
import math class ListNode: # Initialisation def __init__(self, doc_id=None): self.doc_id = int(doc_id) # docId self.next = None # Points to next node self.skip_to = None # Points to skipped node class postingList: # Initialisation def __init__(self, postingStr=None): s...
97cc951bd585348f99f30d9b2cf56e6d42b2117e
ankitandel/list.py
/list10.py
318
3.796875
4
# # Q: How to find all pairs in an array of integers whose sum is equal to the given number? # number = 30 # n = [10, 11, 12, 13, 14, 17, 18, 19] # i=0 # a=[] # while i<len(n): # j=4 # while j<len(n): # if n[i]+n[j]==number: # a.append([n[i],n[j]]) # j=j+1 # i=i+1 # print(a)
2a91ea52ab877f3587a8f869648828006f61054c
GrayWizard12345/PythonGUI
/Starter.py
1,520
3.546875
4
from Customer import Customer from Order import Order from Product import Product from Staff import Staff from Store import Store if __name__ == "__main__": c1 = Customer("01223", "Peter Parker", "Qo'yliq", 2.2, "90-932-75-98", ["Silver", 'Gold']) c2 = Customer("01223", "Sherlock Holmes", "Backer street", 314...
7bbd3d5da5ee6272f1228623e0383e2cb7b3d755
RedKnite5/Junk
/file_ops.py
1,140
3.671875
4
#!C:\Users\RedKnite\AppData\Local\Programs\Python\Python38\python # file_ops.py class File(object): def __init__(self, filename=None): self.filename = filename if self.filename is not None: try: with open(self.filename, "r") as f: self.text = f.read() except FileNotFoundError: se...
e7cfc9650e8567b3e3b49c88b1d5ac82fb822f90
RedKnite5/Junk
/euler66.py
1,220
3.5
4
from itertools import count from math import isqrt, sqrt, isclose from fractions import Fraction def is_square(n): if isinstance(n, Fraction): num, denom = n.as_integer_ratio() if denom != 1: return False n = num if isqrt(n)**2 == n: return True return False def minimal_sol(D: int) -> in...
55ec148f1b65c4a82e959125decb4e5091756ed5
RedKnite5/Junk
/graph_calc_obj.py
2,351
3.546875
4
import math from math import e import tkinter as tk import list_functions as li # python graph_calc.py class graph(object): def __init__(self,func, scr_width=400,scr_height=400, xmin=-5,xmax=5,ymin=-5,ymax=5): def axis(x,y): return(0) def y1(x,y): return(eval(func)) xfunc = [axis,y1] ...
5a8ee88c65b580dcd9efcf73014edb50bffb8bad
RedKnite5/Junk
/euler34.py
672
3.8125
4
# euler34.py # Find the sum of all numbers which are equal to the sum of the factorial of their digits. # 1 and 2 dont count since theyre totals only contain 1 value and are not "sums" max = 362880 def fact(n: int) -> int: if n < 0: raise ValueError("negative value for factorial") result: int = 1 for i in ...
6b0abedebad8e88acf45541bd32b8f127ec5835f
RedKnite5/Junk
/calculus.py
1,964
3.8125
4
# calculus.py def make_int(i): if i.is_integer(): return int(i) else: return i class vector(object): def __init__(self, i=0, j=0, k=0): self.i = i self.j = j self.k = k def __repr__(self): return f"vector{self.i, self.j, self.k}" def __str__(self): return f"{self.i}i + {se...
3d4f7563471852e9ed616b8728ed2e07f1ce6fbe
aakriti04/Spirograph
/main.py
515
3.515625
4
from turtle import Turtle, Screen import random tiny = Turtle() screen = Screen() screen.colormode(255) tiny.speed("fastest") def get_color(): red = random.randint(0, 255) green = random.randint(0, 255) blue = random.randint(0, 255) return red, green, blue def draw_spirograph(size_of_gap): for...
7244d3d09c25bf82950579505c3b33985413a0fc
datalin/sql
/sqlud.py
397
3.84375
4
import sqlite3 with sqlite3.connect("new.db") as connection: cursor = connection.cursor() cursor.execute("UPDATE population SET population = 9000000 WHERE city = 'New York City' ") cursor.execute("DELETE FROM population WHERE city ='Boston' ") print "\n NEW DATA: \n" cursor.execute("SELECT * FROM population")...
86006d8fcf42dee17b4f7a9e0121cb30e547fe04
Havfar/Tsinghua-ML
/code/decision-tree/decision_tree_our.py
8,420
4.03125
4
# For Python 2 / 3 compatability from __future__ import print_function from csv import reader from math import sqrt import pandas as pd # Loading data def load_csv(filename): dataset = list() with open(filename, 'r') as file: csv_reader = reader(file) for row in csv_reader: if not row: continue datas...
9a01cd1953741d28f9420ade66e1bc98d5228679
invokerkael918/BinaryTree-Divide-ConquerTraverse
/Binary Tree Inorder Traversal.py
1,291
3.875
4
""" Definition of TreeNode: class TreeNode: def __init__(self, val): self.val = val self.left, self.right = None, None """ class Solution: """ @param root: A Tree @return: Inorder in ArrayList which contains node values. """ def inorderTraversal(self, root): # write yo...
a78e54197d5ebfea796d1d7bc9529c7bceb76c50
RockMiin/Deep_Learning
/chapter04/test.py
1,322
3.515625
4
import numpy as np from dataset.mnist import load_mnist from network import TwoLayerNet (x_train, y_train), (x_test, y_test)= load_mnist(normalize=True, one_hot_label=True) # 손실함수값을 담는 리스트 train_loss_list= [] train_acc_list= [] test_acc_list= [] # 하이퍼 파라미터 iters_num= 100 # 반복 횟수 train_size= x_train[0].size # 784 ba...
d29faa39dec07a25caa6383e0ecbe35edebbb4c5
AusCommsteam/Algorithm-and-Data-Structures-and-Coding-Challenges
/Challenges/minimumDominoRotationsForEqualRow.py
2,392
4.4375
4
""" Minimum Domino Rotations For Equal Row In a row of dominoes, A[i] and B[i] represent the top and bottom halves of the i-th domino. (A domino is a tile with two numbers from 1 to 6 - one on each half of the tile.) We may rotate the i-th domino, so that A[i] and B[i] swap values. Return the minimum number of rota...
e7fe8ffa16f0c95d77d5949aa4b352a1646dfb3b
AusCommsteam/Algorithm-and-Data-Structures-and-Coding-Challenges
/Challenges/trappingRainWater.py
1,647
4.03125
4
""" Trapping Rain Water Given n non-negative integers representing an elevation map where the width of each bar is 1, compute how much water it is able to trap after raining. The above elevation map is represented by array [0,1,0,2,1,0,1,3,2,1,2,1]. In this case, 6 units of rain water (blue section) are being trappe...
9d8447d6a6385f032da37a4722b0c7dc2c11bc11
AusCommsteam/Algorithm-and-Data-Structures-and-Coding-Challenges
/Challenges/repeatingCharacters.py
1,068
3.90625
4
""" Twitch Words You are given a word like hellloooo print all the repeating character index and the number of time it is has been repeated. Example 1: Input: "hellloooo" Output: [[2, 3], [5, 4]] Explanation: hellloooo has l and o as repeating characters so return index of l which is at 2 and the number of times it ...
136566eb89b6ed018b35c1bb28b513ce5950a76b
AusCommsteam/Algorithm-and-Data-Structures-and-Coding-Challenges
/Challenges/wordBreakII.py
2,812
4
4
""" Word Break II Given a non-empty string s and a dictionary wordDict containing a list of non-empty words, add spaces in s to construct a sentence where each word is a valid dictionary word. Return all such possible sentences. Note: The same word in the dictionary may be reused multiple times in the segmentation. Y...
f944d895524acc3acf080981610859f6e31c75c3
AusCommsteam/Algorithm-and-Data-Structures-and-Coding-Challenges
/Challenges/salaryAdjustment.py
1,616
4.09375
4
""" Give an array of salaries. The total salary has a budget. At the beginning, the total salary of employees is larger than the budget. It is required to find the number k, and reduce all the salaries larger than k to k, such that the total salary is exactly equal to the budget. Example 1: Input: salaries = [100, 30...
870b254cc9b82fa75a0df58708004055f2473bba
AusCommsteam/Algorithm-and-Data-Structures-and-Coding-Challenges
/Challenges/allPossibleFullBinaryTrees.py
2,125
3.859375
4
""" All Possible Full Binary Trees A full binary tree is a binary tree where each node has exactly 0 or 2 children. Return a list of all possible full binary trees with N nodes. Each element of the answer is the root node of one possible tree. Each node of each tree in the answer must have node.val = 0. You may re...
6ac38a5d92a978a72312502672b7af1d803df468
AusCommsteam/Algorithm-and-Data-Structures-and-Coding-Challenges
/Challenges/sequenceReconstruction.py
2,202
3.953125
4
""" Sequence Reconstruction Check whether the original sequence org can be uniquely reconstructed from the sequences in seqs. The org sequence is a permutation of the integers from 1 to n, with 1 ≤ n ≤ 104. Reconstruction means building a shortest common supersequence of the sequences in seqs (i.e., a shortest sequenc...
1b399e72edc812253cacad330840ed59cf0194c9
AusCommsteam/Algorithm-and-Data-Structures-and-Coding-Challenges
/Challenges/diameterOfBinaryTree.py
1,290
4.3125
4
""" Given a binary tree, you need to compute the length of the diameter of the tree. The diameter of a binary tree is the length of the longest path between any two nodes in a tree. This path may or may not pass through the root. Example: Given a binary tree 1 / \ 2 3 / \ ...
c46566508ff155387fd425d0150ec3b83306fbb6
AusCommsteam/Algorithm-and-Data-Structures-and-Coding-Challenges
/Challenges/largestValuesFromLabels.py
1,796
3.78125
4
""" Largest Values From Labels We have a set of items: the i-th item has value values[i] and label labels[i]. Then, we choose a subset S of these items, such that: |S| <= num_wanted For every label L, the number of items in S with label L is <= use_limit. Return the largest possible sum of the subset S. Example ...
19b5899f53bd94583c8b4208db2c5b3982020b55
AusCommsteam/Algorithm-and-Data-Structures-and-Coding-Challenges
/Challenges/greatestCommonDivisorOfStrings.py
1,331
3.984375
4
""" Greatest Common Divisor of Strings For strings S and T, we say "T divides S" if and only if S = T + ... + T (T concatenated with itself 1 or more times) Return the largest string X such that X divides str1 and X divides str2. Example 1: Input: str1 = "ABCABC", str2 = "ABC" Output: "ABC" Example 2: Input: s...
f490e6054c9d90343cab89c810ca2c649d8138fe
AusCommsteam/Algorithm-and-Data-Structures-and-Coding-Challenges
/Challenges/mergeIntervals.py
1,167
4.125
4
""" Merge Intervals Given a collection of intervals, merge all overlapping intervals. Example 1: Input: [[1,3],[2,6],[8,10],[15,18]] Output: [[1,6],[8,10],[15,18]] Explanation: Since intervals [1,3] and [2,6] overlaps, merge them into [1,6]. Example 2: Input: [[1,4],[4,5]] Output: [[1,5]] Explanation: Intervals [1,...
b7a8bfe774a497d709c6198f3b895d71793aa724
AusCommsteam/Algorithm-and-Data-Structures-and-Coding-Challenges
/Challenges/palindromeNumber.py
3,458
3.875
4
""" Palindrome Number Determine whether an integer is a palindrome. An integer is a palindrome when it reads the same backward as forward. Example 1: Input: 121 Output: true Example 2: Input: -121 Output: false Explanation: From left to right, it reads -121. From right to left, it becomes 121-. Therefore it is not ...
5d2924c98c659b1b8bfb2914f8927e7e5f0d504c
AusCommsteam/Algorithm-and-Data-Structures-and-Coding-Challenges
/Challenges/MaxSubarraySum.py
341
3.5
4
class Solution: def maxSubArray(self, nums): """ :type nums: List[int] :rtype: int """ if not nums: return 0 curr_sum = max_sum = nums[0] for n in nums[1:]: curr_sum = max(curr_sum + n, n) max_sum = max(max_sum, curr_sum) ...
5199c8a527f6cd7843f617dbe28c46ab0b6aa697
AusCommsteam/Algorithm-and-Data-Structures-and-Coding-Challenges
/Challenges/encodeAndDecodeTinyURL.py
3,302
4.125
4
""" TinyURL is a URL shortening service where you enter a URL such as https://leetcode.com/problems/design-tinyurl and it returns a short URL such as http://tinyurl.com/4e9iAk. Design the encode and decode methods for the TinyURL service. There is no restriction on how your encode/decode algorithm should work. You jus...
c408d4bc98627857f1b0a39810c517ff0b8259b9
AusCommsteam/Algorithm-and-Data-Structures-and-Coding-Challenges
/Challenges/nonOverlappingIntervals.py
5,138
4.125
4
""" Non-overlapping Intervals Given a collection of intervals, find the minimum number of intervals you need to remove to make the rest of the intervals non-overlapping. Example 1: Input: [[1,2],[2,3],[3,4],[1,3]] Output: 1 Explanation: [1,3] can be removed and the rest of intervals are non-overlapping. Example 2...
66edbdf3dde7da846d5ca7217b0fa65ded787ade
AusCommsteam/Algorithm-and-Data-Structures-and-Coding-Challenges
/Challenges/powXN.py
1,432
4.0625
4
""" Implement pow(x, n), which calculates x raised to the power n (x^n). """ """ Not allowed?? """ class Solution(object): def myPow(self, x, n): """ :type x: float :type n: int :rtype: float """ return x**n class Solution: def myPow(self, x: float, n: int) -> ...
eb9c67b2716252cfa33d63aa9a818fe25c332daa
AusCommsteam/Algorithm-and-Data-Structures-and-Coding-Challenges
/Challenges/minDepthBinaryTree.py
1,813
4.03125
4
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def minDepth(self, root): """ :type root: TreeNode :rtype: int """ if not root: retur...
d86c8afbca66bd1b0731b02fbb2c1bbf551c2615
AusCommsteam/Algorithm-and-Data-Structures-and-Coding-Challenges
/Challenges/reverseLinkedList.py
2,118
4.21875
4
# Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: def reverseList(self, head): """ :type head: ListNode :rtype: ListNode """ new_head = None while head: he...
111b0a0257a9e197a4d20f5c0576bfd6cf0d854a
AusCommsteam/Algorithm-and-Data-Structures-and-Coding-Challenges
/Dice Challenge/poker_dice.py
7,402
3.84375
4
''' A program that simulates the poker dice game. http://en.wikipedia.org/wiki/Poker_dice Functions: play(): randomly gives a hand and the dice can be kept by either inputting all or ALL or any current card. Nothing is kept otherwise. Simulate(): Shows the probability of each type of hand given the number of times pla...
2b6b64ed41e1ed99a4e8a12e1e6ab53e6a9596ef
AusCommsteam/Algorithm-and-Data-Structures-and-Coding-Challenges
/Challenges/shortestWayToFormString.py
7,619
3.78125
4
""" Shortest Way to Form String From any string, we can form a subsequence of that string by deleting some number of characters (possibly no deletions). Given two strings source and target, return the minimum number of subsequences of source such that their concatenation equals target. If the task is impossible, retu...
c6858af5e5805807fd78b699f4f819cf5cd97e04
AusCommsteam/Algorithm-and-Data-Structures-and-Coding-Challenges
/Challenges/nextPremutation.py
2,120
3.984375
4
""" Implement next permutation, which rearranges numbers into the lexicographically next greater permutation of numbers. If such arrangement is not possible, it must rearrange it as the lowest possible order (ie, sorted in ascending order). The replacement must be in-place and use only constant extra memory. """ """...
43bd43a6f6c2a296ed72646400a862eea2307131
AusCommsteam/Algorithm-and-Data-Structures-and-Coding-Challenges
/Challenges/stringCombinations.py
623
3.9375
4
""" Given a string s consisting of 0, 1 and ?. The question mark can be either 0 or 1. Find all possible combinations for the string. Example 1: Input: s = "001?" Output: ["0010", "0011"] """ def get_string_combinations(s): res = [] def get_strings(s, res, idx): if idx == len(s): res.append(s) return if...
99e25be34833e876da74bb6f53a62edf745be9a5
AusCommsteam/Algorithm-and-Data-Structures-and-Coding-Challenges
/Challenges/sortedSquares.py
2,053
4.25
4
""" Given an array of integers A sorted in non-decreasing order, return an array of the squares of each number, also in sorted non-decreasing order. Example 1: Input: [-4,-1,0,3,10] Output: [0,1,9,16,100] Example 2: Input: [-7,-3,2,3,11] Output: [4,9,9,49,121] Note: 1 <= A.length <= 10000 -10000 <= A[i] <= 10...
323ec56c71b0abfb505751145e4eb236d68b5881
AusCommsteam/Algorithm-and-Data-Structures-and-Coding-Challenges
/Challenges/zigzagLevelOrderTraversal.py
1,252
3.859375
4
""" Binary Tree Zigzag Level Order Traversal Given a binary tree, return the zigzag level order traversal of its nodes' values. (ie, from left to right, then right to left for the next level and alternate between). """ # Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.v...
29a9492d7b810fdf13731fe2679265b616095d7d
AusCommsteam/Algorithm-and-Data-Structures-and-Coding-Challenges
/Challenges/shortestPathInBinaryMatrix.py
1,670
4.0625
4
""" Shortest Path In Binary Matrix n an N by N square grid, each cell is either empty (0) or blocked (1). A clear path from top-left to bottom-right has length k if and only if it is composed of cells C_1, C_2, ..., C_k such that: Adjacent cells C_i and C_{i+1} are connected 8-directionally (ie., they are different ...
949196289694e00c9ca8e7381786a1cd91cdaf7c
AusCommsteam/Algorithm-and-Data-Structures-and-Coding-Challenges
/Challenges/nextGreaterElementII.py
2,687
3.84375
4
""" Next Greater Element II Given a circular array (the next element of the last element is the first element of the array), print the Next Greater Number for every element. The Next Greater Number of a number x is the first greater number to its traversing-order next in the array, which means you could search circula...
35f9c64ca063b6ba46c8145462fb67afc6a32076
AusCommsteam/Algorithm-and-Data-Structures-and-Coding-Challenges
/Challenges/numberOfSubsets.py
878
3.5
4
""" For a given list of integers and integer K, find the number of non-empty subsets S such that min(S) + max(S) <= K. Example 1: nums = [2, 4, 5, 7] k = 8 Output: 5 Explanation: [2], [4], [2, 4], [2, 4, 5], [2, 5] Example 2: nums = [1, 4, 3, 2] k = 8 Output: 15 Explanation: 16 (2^4) - 1 (empty set) = 15 Example 3: ...
e932cecd4084f2d7cef0faa06e792dab7ef590ad
AusCommsteam/Algorithm-and-Data-Structures-and-Coding-Challenges
/Challenges/binaryTreeLongestConsecutiveSequence.py
2,493
3.953125
4
""" Binary Tree Longest Consecutive Sequence Given a binary tree, find the length of the longest consecutive sequence path. The path refers to any sequence of nodes from some starting node to any node in the tree along the parent-child connections. The longest consecutive path need to be from parent to child (cannot ...
f325cecbb91df5d05bd766a8099a2ccd236759f8
AusCommsteam/Algorithm-and-Data-Structures-and-Coding-Challenges
/Challenges/twoSumSortedInput.py
608
3.640625
4
class Solution: def twoSum(self, numbers, target): """ :type numbers: List[int] :type target: int :rtype: List[int] """ left, right = 0, len(numbers)-1 while left < right: if numbers[left] + numbers[right] == target: return [left+1,...
33e938d5592965fa2c772c5c958ced297ee18955
AusCommsteam/Algorithm-and-Data-Structures-and-Coding-Challenges
/Challenges/flipEquivalentBinaryTree.py
1,531
4.1875
4
""" Flip Equivalent Binary Trees For a binary tree T, we can define a flip operation as follows: choose any node, and swap the left and right child subtrees. A binary tree X is flip equivalent to a binary tree Y if and only if we can make X equal to Y after some number of flip operations. Write a function that deter...
31c90567097d5ecabe0986d29a642950b5487b85
AusCommsteam/Algorithm-and-Data-Structures-and-Coding-Challenges
/Challenges/ArrayIndexAndElementEquality.py
469
3.875
4
def index_equals_value_search(arr): ''' for i in range(len(arr)): if i == arr[i]: return i return -1 ''' if len(arr) == 1: if arr[0] == 0: return 0 start, end = 0, len(arr) - 1 while start <= end: mid = (start + end) // 2 if mid == arr[mid]:...
8da53bbfcfdf16380d8b4c2620a6509ae8ff6ad6
AusCommsteam/Algorithm-and-Data-Structures-and-Coding-Challenges
/Challenges/maximumProductSubarray.py
1,399
4.0625
4
""" Maximum Product Subarray Given an integer array nums, find the contiguous subarray within an array (containing at least one number) which has the largest product. Example 1: Input: [2,3,-2,4] Output: 6 Explanation: [2,3] has the largest product 6. Example 2: Input: [-2,0,-1] Output: 0 Explanation: The result ca...
302f7ed1d4569abaf417efddff2c2b1721146207
AusCommsteam/Algorithm-and-Data-Structures-and-Coding-Challenges
/Challenges/maxStack.py
2,794
4.25
4
""" Max Stack Design a max stack that supports push, pop, top, peekMax and popMax. push(x) -- Push element x onto stack. pop() -- Remove the element on top of the stack and return it. top() -- Get the element on the top. peekMax() -- Retrieve the maximum element in the stack. popMax() -- Retrieve the maximum element i...
27b36d5fd37abd73621928e149440a7522da2afc
AusCommsteam/Algorithm-and-Data-Structures-and-Coding-Challenges
/Heap/preferred_heap.py
2,929
3.90625
4
# Randomly generates N distinct integers with N provided by the user, # inserts all these elements into a priority queue, and outputs a list # L consisting of all those N integers, determined in such a way that: # - inserting the members of L from those of smallest index of those of # largest index results in the sam...
98e45ace3d4486913d547c1f6234b4a2a202f512
AusCommsteam/Algorithm-and-Data-Structures-and-Coding-Challenges
/Challenges/maximumSumOfN-aryTree.py
1,472
3.890625
4
""" Given an N-ary tree and the weight of each edge represented in the value at the child node, now we are pouring water from root node and it gradually coming down through each node traversing one by one. Now time taken by the water to come from parent to child node was written by the value at child node and also root...
be4b1f82b684b71f01d76c32b573b96b6d07b658
AusCommsteam/Algorithm-and-Data-Structures-and-Coding-Challenges
/Challenges/nextGreaterElementIII.py
2,171
3.703125
4
""" Next Greater Element III Given a positive 32-bit integer n, you need to find the smallest 32-bit integer which has exactly the same digits existing in the integer n and is greater in value than n. If no such positive 32-bit integer exists, you need to return -1. Example 1: Input: 12 Output: 21 Example 2: Inp...
7a10218d23278cfce1aa3f24e1a12b473a257d4d
AusCommsteam/Algorithm-and-Data-Structures-and-Coding-Challenges
/Challenges/timeBasedKeyValueStore.py
4,155
3.6875
4
""" Time Based Key-Value Store Create a timebased key-value store class TimeMap, that supports two operations. 1. set(string key, string value, int timestamp) Stores the key and value, along with the given timestamp. 2. get(string key, int timestamp) Returns a value such that set(key, value, timestamp_prev) was cal...
39c5c28985e46e9266410896dc041f0948ea46d7
AusCommsteam/Algorithm-and-Data-Structures-and-Coding-Challenges
/Challenges/permutationSequence.py
2,125
4.0625
4
""" Permutation Sequence The set [1,2,3,...,n] contains a total of n! unique permutations. By listing and labeling all of the permutations in order, we get the following sequence for n = 3: "123" "132" "213" "231" "312" "321" Given n and k, return the kth permutation sequence. Note: Given n will be between 1 and 9...
f09ae78531c516afc4a4177bdf9f2bdbf537d043
AusCommsteam/Algorithm-and-Data-Structures-and-Coding-Challenges
/Challenges/verifyPreorderSequenceInBinarySearchTree.py
2,086
3.8125
4
""" Verify Perorder Sequence In Binary Search Tree Given an array of numbers, verify whether it is the correct preorder traversal sequence of a binary search tree. You may assume each number in the sequence is unique. Consider the following binary search tree: 5 / \ 2 6 / \ 1 3 Example 1: Input...
437e273c80d1f452066000556fde65871de49a3e
AusCommsteam/Algorithm-and-Data-Structures-and-Coding-Challenges
/Challenges/findCommonCharacters.py
1,908
4.03125
4
""" Find Common Characters Given an array A of strings made only from lowercase letters, return a list of all characters that show up in all strings within the list (including duplicates). For example, if a character occurs 3 times in all strings but not 4 times, you need to include that character three times in the ...
0e980363de2eb7407209395ab2b9ba73aaaa1f23
AusCommsteam/Algorithm-and-Data-Structures-and-Coding-Challenges
/Linked Lists/linked_list_adt.py
6,118
3.953125
4
# Written by Eric Martin and modified by Benny Hwang ''' A Linked List abstract data type ''' from copy import deepcopy class Node: def __init__(self, value = None): self.value = value self.next_node = None class LinkedList: def __init__(self, L = None, key = lambda x: x): self.k...
0e23639a8c4185493a53e157cc41df4f4543e086
AusCommsteam/Algorithm-and-Data-Structures-and-Coding-Challenges
/Linked Lists/extended_linked_list_adt.py
1,132
3.5625
4
''' Written by Benny Hwang 12/09/2017 Extends the module, linked_list_adt by adding a remove duplicate value feature ''' from linked_list_adt import * class ExtendedLinkedList(LinkedList): def __init__(self, L = None): # The super keyword allows it to inherit the class used in the argumet (LinkedList) i...
01b4259cf50c44ed8412415a550c3a67a150c065
AusCommsteam/Algorithm-and-Data-Structures-and-Coding-Challenges
/Challenges/treap.py
2,635
3.984375
4
""" A binary tree has the binary search tree property (BST property) if, for every node, the keys in its left subtree are smaller than its own key, and the keys in its right subtree are larger than its own key. It has the heap property if, for every node, the keys of its children are all smaller than its own key. You a...
5851ff675353f950e8a9a1c730774a35ab54b8db
AusCommsteam/Algorithm-and-Data-Structures-and-Coding-Challenges
/Challenges/stringConversion.py
2,321
4.25
4
""" Given 2 strings s and t, determine if you can convert s into t. The rules are: You can change 1 letter at a time. Once you changed a letter you have to change all occurrences of that letter. Example 1: Input: s = "abca", t = "dced" Output: true Explanation: abca ('a' to 'd') -> dbcd ('c' to 'e') -> dbed ('b' to '...
82189015651e918670a0685bed581e262098dd6d
AusCommsteam/Algorithm-and-Data-Structures-and-Coding-Challenges
/Challenges/compareStrings.py
1,763
4.09375
4
""" Compare String One string is strictly smaller than another when the frequency of occurrence of the smallest character in the string is less than the frequency of the occurrence of the smallest character in the comparison string. For example, string "abcd" is smaller than string "aaa" because the smallest charac...
ad7585865f7d924975f5f44cb9dd5bd857215f55
AusCommsteam/Algorithm-and-Data-Structures-and-Coding-Challenges
/Challenges/ReverseVowelsOfAString.py
1,513
4.09375
4
""" Write a function that takes a string as input and reverse only the vowels of a string. Example 1: Input: "hello" Output: "holle" Example 2: Input: "leetcode" Output: "leotcede" Note: The vowels does not include the letter "y". """ # Time O(n), Space: O(n) class Solution: def reverseVowels(self, s: str) -> s...
de1cdd7c24ce9e56af7baaf562ad915960eb246d
AusCommsteam/Algorithm-and-Data-Structures-and-Coding-Challenges
/Challenges/uniquePaths.py
1,433
4.15625
4
""" Unique Paths A robot is located at the top-left corner of a m x n grid (marked 'Start' in the diagram below). The robot can only move either down or right at any point in time. The robot is trying to reach the bottom-right corner of the grid (marked 'Finish' in the diagram below). How many possible unique paths ...
8cb2c5f1e33742337cdb1495c6d2f13e169d481a
AusCommsteam/Algorithm-and-Data-Structures-and-Coding-Challenges
/Challenges/binarySearchTreeIterator.py
5,505
4.15625
4
""" Implement an iterator over a binary search tree (BST). Your iterator will be initialized with the root node of a BST. Calling next() will return the next smallest number in the BST. Note: next() and hasNext() should run in average O(1) time and uses O(h) memory, where h is the height of the tree. You may assume ...
e81fb3440413a2ca42df459fec604df7d2aad8b8
AusCommsteam/Algorithm-and-Data-Structures-and-Coding-Challenges
/Challenges/largestSubarrayLengthK.py
1,764
4.1875
4
""" Largest Subarray Length K Array X is greater than array Y if the first non matching element in both arrays has a greater value in X than Y. For example: X = [1, 2, 4, 3, 5] Y = [1, 2, 3, 4, 5] X is greater than Y because the first element that does not match is larger in X. and if A = [1, 4, 3, 2, 5] and K = 4...
d8776c41083583c02c3fdc6ff3605cca4eea94af
AusCommsteam/Algorithm-and-Data-Structures-and-Coding-Challenges
/Dice Challenge/pivoting_die.py
4,498
4.125
4
''' Consider a board similar to the one below 7 8 9 10 6 1 2 11 5 4 3 However, imagine it as being infinite. A die is initially placed at 1 and can only move to the next consecutive number (e.g 1 to 2, 2 to 3...) Promp...
887127a0daa40d6f832475eb5ff8d5976e056510
AusCommsteam/Algorithm-and-Data-Structures-and-Coding-Challenges
/Challenges/addTwoNumbers.py
3,988
3.625
4
""" You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list. You may assume the two numbers do not contain any leading zero, except the number 0 itself. Ex...
368549e62f1c5994ae9030d43a1b518167425b74
AusCommsteam/Algorithm-and-Data-Structures-and-Coding-Challenges
/Challenges/2KeysKeyboard.py
2,034
3.796875
4
""" 2 Keys Keyboard Initially on a notepad only one character 'A' is present. You can perform two operations on this notepad for each step: Copy All: You can copy all the characters present on the notepad (partial copy is not allowed). Paste: You can paste the characters which are copied last time. Given a number ...
2b4e64d837993111fde673235c80dc26e3ded912
AusCommsteam/Algorithm-and-Data-Structures-and-Coding-Challenges
/Challenges/reconstructItinerary.py
2,112
4.375
4
""" Reconstruct Itinerary Given a list of airline tickets represented by pairs of departure and arrival airports [from, to], reconstruct the itinerary in order. All of the tickets belong to a man who departs from JFK. Thus, the itinerary must begin with JFK. Note: If there are multiple valid itineraries, you should ...
7192024a408d165666ad4f10f7b53b965ce4c769
AusCommsteam/Algorithm-and-Data-Structures-and-Coding-Challenges
/Challenges/minStack.py
2,110
3.96875
4
""" Design a stack that supports push, pop, top, and retrieving the minimum element in constant time. push(x) -- Push element x onto stack. pop() -- Removes the element on top of the stack. top() -- Get the top element. getMin() -- Retrieve the minimum element in the stack. """ class MinStack: def __init__(self)...
a5ecd1c97f54dbab3f1500677c6230da91ce45ad
AusCommsteam/Algorithm-and-Data-Structures-and-Coding-Challenges
/Challenges/minimumAbsoluteDifferenceBetweenServerLoads.py
1,446
3.671875
4
""" There are some processes that need to be executed. Amount of a load that process causes on a server that runs it, is being represented by a single integer. Total load caused on a server is the sum of the loads of all the processes that run on that server. You have at your disposal two servers, on which mentioned pr...
30672bb5dbe790fbbee64a49dcbff2727b344140
lokeshpopuri21/data-structures-and-algorithms-coursera
/great common divisor.py
168
3.546875
4
a, b = [int(i) for i in input().split()] def computeGCD(a, b): while(b): a, b = b, a % b return a print (computeGCD(a,b))
610bd5c83000ceb978178c651c3eafd8711aaf51
asteraceae/comp363TetrisProject
/tetrismain.py
26,267
3.546875
4
import pygame import sys from random import randrange as rand #Board configuration and block size (which can be changed to create different board dimensions: default is a square board 25x25) blocksize = 30 columnnum = 20 rownum = 25 maxfps = 60 #create a list of the colors (using the RBG color system) colors = [ (0, ...
670d62ffcdf05c898777d8876f11695b8df377b1
godumuyiwa/numericalcompute
/simpleiterationfor.py
378
3.734375
4
def simpleiterusingfor(a): x = a for loops in range (1,101): #using a for loop without any accuracy set x_new = (2*x**2 + 3)/5 print(loops, x_new) if abs(x_new - x) <0.00001: break else: x = x_new print(f"The number of iteration is {l...
7ccb8e1436ad8be419b257510e198e5054ced8d2
AliHaddad/Text-Analysis
/analyser.py
3,138
4.03125
4
import codecs def normalize(s): """ (str) -> str Given a string, return a copy of that string with all alphabetical characters turned lowercase and all special characters removed and replaced with a space. >>> normalize("Hey! How are you? I'm fine. ;D") 'hey how are you i m fine d' ...