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
e98d8dcea92717dc00bba19ef5d887b8d521e12e
akaliutau/cs-problems-python
/problems/dp/Solution115.py
1,170
3.515625
4
""" Given two strings s and t, return the number of distinct subsequences of s which equals t. A string's subsequence is a new string formed from the original string by deleting some (can be none) of the characters without disturbing the relative positions of the remaining characters. (i.e., "ACE" is a su...
1ac4822dd02e34f946f4183122d8a6b5ec804d02
akaliutau/cs-problems-python
/problems/greedy/Solution678.py
1,937
4.25
4
""" Given a string containing only three types of characters: '(', ')' and '*', write a function to check whether trightBoundarys string is valid. We define the validity of a string by these rules: Any left parenthesis '(' must have a corresponding right parenthesis ')'. Any right parenthesis ')' must...
d326550ff785ae5f01bdef0762886b2b5dc1dd0b
akaliutau/cs-problems-python
/problems/tree/Solution261.py
815
3.984375
4
""" Given n nodes labeled from 0 to n-1 and a list of undirected edges (each edge is a pair of nodes), write a function to check whether these edges make up a valid tree. Example 1: Input: n = 5, and edges = [[0,1], [0,2], [0,3], [1,4]] Output: true IDEA For the graph to be a...
acafe7d3e6f5799a0829489382272302d0263b68
akaliutau/cs-problems-python
/problems/math/Solution1073.py
838
4.0625
4
""" Given two numbers arr1 and arr2 in base -2, return the result of adding them together. Each number is given in array format: as an array of 0s and 1s, from most significant bit to least significant bit. For example, arr = [1,1,0,1] represents the number (-2)^3 + (-2)^2 + (-2)^0 = -3. A number arr in a...
06ef2b66f01a4e36d563f3be23a201bb18645f50
akaliutau/cs-problems-python
/problems/string/Solution556.py
1,102
3.671875
4
""" 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 IDEA: 1) find 2 n...
f4248de8ff831fbb0103ccce3c0effde23ea28ad
akaliutau/cs-problems-python
/problems/backtracking/Solution291.py
830
4.4375
4
""" Given a pattern and a string s, return true if s matches the pattern. A string s matches a pattern if there is some bijective mapping of single characters to strings such that if each character in pattern is replaced by the string it maps to, then the resulting string is s. A bijective mapping means t...
9369936045f15e39fe607e57906f4811c519fde6
akaliutau/cs-problems-python
/problems/bfs/Solution1293.py
1,001
4.28125
4
""" Given a m * n grid, where each cell is either 0 (empty) or 1 (obstacle). In one step, you can move up, down, left or right from and to an empty cell. Return the minimum number of steps to walk from the upper left corner (0, 0) to the lower right corner (m-1, n-1) given that you can eliminate at most k ...
2408dd036522239b8f1a45db6fa13d697d844324
akaliutau/cs-problems-python
/problems/array/Solution414.py
946
4.03125
4
""" Given a non-empty array of integers, return the third maximum number in this array. If it does not exist, return the maximum number. The time complexity must be in O(n). Example 1: Input: [3, 2, 1] Output: 1 Explanation: The third maximum is 1. IDEA: introduce a limit for max function ...
01b7648a4c71b2924847ff7a8424aff733b949ac
akaliutau/cs-problems-python
/problems/dp/Solution472.py
793
3.9375
4
""" Given a list of words (without duplicates), write a program that returns all concatenated words in the given list of words. A concatenated word is defined as a string that is comprised entirely of at least two shorter words in the given array. Examples: Input: ["cat","cats","catsdogcats","d...
a513105c93b08d12a8659f27946ab6881cf76eff
akaliutau/cs-problems-python
/problems/stack/Solution496.py
1,714
3.859375
4
""" You are given two arrays (without duplicates) nums1 and nums2 where nums1’s elements are subset of nums2. Find all the next greater numbers for nums1's elements in the corresponding places of nums2. The Next Greater Number of a number x in nums1 is the first greater number to its right in nums2. I...
893b5e6561de81e7be1cdd8190de6f5ee243c70e
akaliutau/cs-problems-python
/problems/greedy/Solution45.py
724
3.515625
4
""" Given an array of non-negative integers, you are initially positioned at the first index of the array. Each element in the array represents your maximum jump length at that position. Your goal is to reach the last index in the minimum number of jumps. Example: Input: [2,3,1,1...
60522a87c015f0755a3fee0c6b006f2267a8a0f5
akaliutau/cs-problems-python
/problems/greedy/Solution870.py
470
3.578125
4
""" Given two arrays A and B of equal size, the advantage of A with respect to B is the number of indices i for which A[i] > B[i]. Return any permutation of A that maximizes its advantage with respect to B. Example 1: Input: A = [2,7,11,15], B = [1,10,4,11] Output: [2,11,7,15] ID...
db6be99a0fb8e2a18b0470e53a21557ef47a026a
akaliutau/cs-problems-python
/problems/dp/Solution32.py
426
3.875
4
""" Given a string containing just the characters '(' and ')', find the length of the longest valid (well-formed) parentheses substring. Example 1: Input: s = "(()" Output: 2 Explanation: The longest valid parentheses substring is "()". Example 2: Input: s = ")()())" Output: 4 E...
6d1f674829d3339eea583dc887d2a8a8bfecfec6
akaliutau/cs-problems-python
/problems/dp/Solution140.py
643
3.984375
4
""" 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. Input: s = "catsanddog" wordDict = ["cat", "cats", "and", "sand", "dog"] Output: ...
95efa3b983dfeba0d20fdfe478e122e0dc22cf7f
akaliutau/cs-problems-python
/problems/math/Solution1742.py
942
3.53125
4
""" You are working in a ball factory where you have n balls numbered from lowLimit up to highLimit inclusive (i.e., n == highLimit - lowLimit + 1), and an infinite number of boxes numbered from 1 to infinity. Your job at this factory is to put each ball in the box with a number equal to the sum of di...
8bbe07b7eb1910b70196b0f5b7d075e9056df723
akaliutau/cs-problems-python
/problems/dp/Solution10.py
679
3.96875
4
""" Given an input string (s) and a pattern (p), implement regular expression matching with support for '.' and '*' where: '.' Matches any single character.​​​​ '*' Matches zero or more of the preceding element. The matching should cover the entire input string (not partial). Example...
387e672b3d766a710158021294bfb56b812c5ec8
akaliutau/cs-problems-python
/problems/dp/Solution354.py
534
3.734375
4
""" You have a number of envelopes with widths and heights given as a pair of integers (w, h). One envelope can fit into another if and only if both the width and height of one envelope is greater than the width and height of the other envelope. What is the maximum number of envelopes can you Russian doll? ...
15197217ce544404ac27b81468fca2a5b4092eb4
akaliutau/cs-problems-python
/problems/bfs/Solution1091.py
823
3.75
4
""" In 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 and share ...
b2801a9545ee714c27876f1ee0b791d9afaca79c
akaliutau/cs-problems-python
/problems/bfs/Solution1102.py
1,030
3.5
4
""" Given a matrix of integers grid with R rows and C columns, find the maximum score of a path starting at [0,0] and ending at [R-1,C-1]. The score of a path is the minimum value in that path. For example, the value of the path 8 → 4 → 5 → 9 is 4. grid path moves some number of times from one vis...
cb55dbd5cf3d58c37b850aa3476882c16332396a
akaliutau/cs-problems-python
/problems/slidingwindow/Solution993.py
2,134
4.0625
4
""" Given an array arr of positive integers, call a (contiguous, not necessarily distinct) subarray of arr good if the number of different integers in that subarray is exactly K. (For example, [1,2,3,1,2] has 3 diffCount integers: 1, 2, and 3.) Return the number of good subarrays of arr. ...
83b9c12a866593a96716cab74fdc2e9589dc2b0b
akaliutau/cs-problems-python
/problems/dfs/Solution690.py
752
3.53125
4
""" You are given a data structure of employee information, which includes the employee's unique id, their importance value and their direct subordinates' id. For example, employee 1 is the leader of employee 2, and employee 2 is the leader of employee 3. They have importance value 15, 10 and 5, respectiv...
c982ab5f53061a7d4d4bbfa979d05985bd4eca4c
akaliutau/cs-problems-python
/problems/binarysearch/Solution378.py
389
4.03125
4
""" Given a n x n matrix where each of the rows and columns are sorted in ascending order, find the kth smallest element in the matrix. Note that it is the kth smallest element in the sorted order, not the kth distinct element. Example: matrix = [ [ 1, 5, 9], [10, 11, 13], [12, 13, 15] ...
0d416d5ea0f0fff0d95abb9b0e79c5d1f5f79439
akaliutau/cs-problems-python
/problems/dfs/Solution695.py
724
3.84375
4
""" Given a non-empty 2D array grid of 0's and 1's, an island is a group of 1's (representing land) connected 4-directionally (horizontal or vertical.) You may assume all four edges of the grid are surrounded by water. Find the maximum area of an island in the given 2D array. (If there is no island, the m...
cdce34aaeeb4428c81f73de700e15cca8bbd0114
akaliutau/cs-problems-python
/problems/dfs/Solution109.py
1,119
3.859375
4
""" Given the head of a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST. For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never differ by more than 1. Input: head...
41acdd2f91669a03c8ab44e35ea7a7b786be3454
anettkeszler/ds-algorithms-python
/codewars/6kyu_break_camel_case.py
508
4.4375
4
# Complete the solution so that the function will break up camel casing, using a space between words. # Example # solution("camelCasing") == "camel Casing" import re def solution(s): result = "" for char in s: if char.isupper(): break result += char result += " " split...
7794d5612f6ae6bba43b17a94ff409a816bea887
leonardooo/Maratona
/URI/uri1040.py
524
3.6875
4
linha = input().split() n1 = float(linha[0]) n2 = float(linha[1]) n3 = float(linha[2]) n4 = float(linha[3]) media = n1*0.2 + n2*0.3 + n3*0.4 + n4*0.1 print("Media: %.1f" % media) if media < 5.0: print("Aluno reprovado.") elif media >= 7.0: print("Aluno aprovado.") else: print("Aluno em exame.") nf = flo...
519bd34400f3975d2e958d42458d3fdd704f3fc2
leonardooo/Maratona
/URI/uri1042.py
161
3.546875
4
linha = input().split() lista = [] for token in linha: lista.append(int(token)) lista.sort() for i in lista: print(i) print() for i in linha: print(i)
fcb959f4bf8c48d7165a5d85324e9d8b9a4f5a01
leonardooo/Maratona
/URI/tle/uri2878.py
1,060
3.515625
4
class Corte: def __init__(self, ini, fim): self.ini = ini self.fim = fim def intersect(self, outro_corte): if( self.ini < outro_corte.ini and self.fim > outro_corte.fim ) or ( self.ini > outro_corte.ini and self.fim < outro_corte.fim ): return True return False lin...
b5e7bcc36283ca414750bc272ee7a60d4113be08
leonardooo/Maratona
/URI/uri1168.py
507
3.625
4
n = int(input()) for i in range(n): linha = input() cont = 0 for j in range(len(linha)): if linha[j] == "0" or linha[j] == "6" or linha[j] == "9": cont += 6 if linha[j] == "1": cont += 2 if linha[j] == "2" or linha[j] == "3" or linha[j] == "5": co...
e2261f89903623e7822a6cf0473a2a87081b289f
Crissky/AED-TAEF
/Exercícios/Edson.Cristovam15(Com Dicionário).py
1,026
3.640625
4
#arq = open('1.in','r') #lista = arq.readline().split() lista = input().split() lista2, alunos, astr = {}, {}, '' for x in range(0,len(lista),2): #Criando um Dicionário com as salas como chaves e o alunos como valores. if(lista[x+1] in lista2.keys()): lista2[lista[x+1]].append(lista[x]) else: ...
e831141a6dc09d16d7b4d0cd17e3f58abf47f558
GregHilston/Code-Foo
/Challenges/challenge_26_shuffling_items/GregHilston/src/solution.py
961
3.90625
4
import math from random import shuffle num_iterations = 3 start_length = 5 end_length = 10 for length in range(start_length, end_length + 1): shuffle_history = [] print(f"length {length}, max shuffles = {length}! = {math.factorial(length)}") for iteration in range(num_iterations): print(f"\titera...
c72c76719cceb7f6ea364bf4875253f39ba96c3a
GregHilston/Code-Foo
/Challenges/challenge_37_bulb_switcher/GregHilston/src/solution.py
1,213
3.515625
4
class BulbSwitcher: def __init__(self): pass def solve(self, number_of_bulbs_and_rounds: int) -> int: # base case cause I'm lazy if number_of_bulbs_and_rounds == 1: return 1 # let -1 = OFF # let 1 = ON bulbs = [-1 for i in range(number_of_bulbs_and_r...
9639f40ec44dbafae3ae3a97f1cc30b527e094bd
GregHilston/Code-Foo
/Challenges/challenge_44_intermediate_sales/GregHilston/src/solution.py
1,603
3.671875
4
"""Greg Hilston's source code solution to Code Foo challenge 44.""" from math import ceil from typing import Dict from dataclasses import dataclass class IntermediateSales: """Calculates scheduling of car rentals to maximize number of cars rented.""" def solve(self, revenue: Dict[str, Dict[str, int]], exp...
52fe4c34d46fdab356a60c02e2dd70635d49f61f
xinnige/practice
/practice/python/utils.py
1,565
3.953125
4
class TreeNode(object): def __init__(self, x): self.val = x self.left = None self.right = None class ListNode(object): def __init__(self, x): self.val = x self.next = None def buildlist(arr): if len(arr) == 0: return None, [] nodelist = [] for number...
c990969f7add0f882fc6333e24630c9f832f808c
xinnige/practice
/practice/python/majorityEle.py
509
3.5
4
class Solution(object): def majorityElement(self, nums): """ :type nums: List[int] :rtype: int """ major = None count = 0 for num in nums: if count == 0: major = num if major == num: count += 1 ...
1e133cb6a5b835864b9e09013ae4574498569f98
xinnige/practice
/practice/python/odd_even_link.py
1,643
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 oddEvenList(self, head): """ :type head: ListNode :rtype: ListNode """ p2 = head pp1 = head if p2...
2a15e79234f8a1e62ba287ca89f0ef7e1803ef2a
ankitjain1998/Writing-Samples
/Early Coding Labs/Lab2/Lab2.py
7,345
4.15625
4
#Lab 2 print('Lab 2:') #Ankit Jain jaina2 96065117 #Problem 1 print('\nProblem 1:\n') year=int(input('Enter a year: ')) def leapYear(year:int)->int: '''Function checks if the year entered is a leap year by checking it's divisibility with 4 and 400 and non divisibility with 100''' if year%400...
49944eee2ffe2199a875aa2f153a03b7b7ea2980
Catochi/ISCRIP
/Tweede Poging/1_Germanisering.py
442
3.875
4
def Germanisering(): #input text van de gebruiker en splits elke woord in een list zin = input("Enter text: ").split(" ") # lees door hele list met een index nummer per woord for index,woord in enumerate(zin): # vervang elke woord in het list met een dat begint met hoofdletter zin[index...
5eda14097c9d4144e9181d17c1dabf223ee4b759
guilhermeG23/AulasPythonGuanabara
/Pratico/Desafios/desafio20.py
312
3.8125
4
#Meio guanabara from random import shuffle nome1 = str(input('Digite o nome1: ')) nome2 = str(input('Digite o nome2: ')) nome3 = str(input('Digite o nome3: ')) nome4 = str(input('Digite o nome4: ')) lista = [nome1, nome2, nome3, nome4] #Randomizar o eleito shuffle(lista) print('Ordem do sorteio foi...') print(lista)
585cf0eae32eab2156938b236d7f4da3dfd72620
guilhermeG23/AulasPythonGuanabara
/Pratico/Exemplos/ExemploEstruturaCondicinal.py
169
3.953125
4
nome = str(input('Qual é o seu nome: ')).strip().lower() if nome == 'teste': print('Bom Dia teste') else: print('Seu nome é {}'.format(nome)) print('--FIM--')
d177590ef53c9d2105dfcf7e2f46a9a913c34ab4
guilhermeG23/AulasPythonGuanabara
/Pratico/Desafios/desafio2.py
160
3.640625
4
dia = input("Dia do nascimento: ") mes = input("mes do nascimento: ") ano = input("ano do nascimento: ") print("Sua data de nascimento é",dia,"/",mes,"/",ano)
d627d1b6b9146f661cfc0448db91cf7910534cae
guilhermeG23/AulasPythonGuanabara
/PorFora/TimeAtual.py
621
3.96875
4
#Biblioteca from datetime import datetime #Variavel now = datetime.now() #Atual day Variavel print(now) #Imprimindo partes do dia print(now.year) print(now.day) print(now.month) #mais de uma forma de imprimir o date print('{}-{}-{}'.format(now.year, now.month, now.day)) print('{}/{}/{}'.format(now.year, now.month, no...
ea2ca3bce7b4b158415eddae8169b3832ff39908
guilhermeG23/AulasPythonGuanabara
/Pratico/Desafios/desafio17.py
812
4.15625
4
#Meu método #So o: from math import sqrt #Ou: from math import hypot import math a = float(input("Entre com o Cateto Adjacente A do triangulo retangulo: ")) b = float(input("Entre com o Cateto Oposto B do triangulo retangulo: ")) hipotenusa = (a**2) + (b**2) print("A Hipotenusa é {:.2f}".format(math.sqrt(hipotenusa))) ...
c367cfc8af16a442d3d792a5263863f79dab0985
guilhermeG23/AulasPythonGuanabara
/Pratico/Desafios/desafio31.py
517
3.859375
4
print('Voce vai viajar!') valor = float(input('Quantos Km você vai rodar: ')) if valor < 200: print('Você vai pagar de passagem {:.2f} por {:.2f} Km'.format(valor * 0.5, valor)) else: print('A viagem tem mais de 200Km, você vai pagar {:.2f} por {:.2f} Km'.format(valor * 0.45, valor)) #Operador resumido guanab...
036804724e164e08d4b350be66d97f80902c3506
guilhermeG23/AulasPythonGuanabara
/Pratico/Desafios/desafio10.py
197
3.71875
4
entrada = float(input("Quando reais você tem: ")) print("Em Dolar: {:.2f}".format(entrada / 3.17)) print("Em Iene: {:.2f}".format(entrada * 34.72)) print("Em Euro: {:.2f}".format(entrada / 3.87))
c867499f5522896a874306cbc22e8d83cabbaf1e
guilhermeG23/AulasPythonGuanabara
/Pratico/Desafios/desafio18.py
404
3.90625
4
#Este é so o guanabara #Não consegui #Importando tudo #import math #Impotando so algumas bibliotecas from math import radians, sin, cos, tan angulo = float(input("Entre com o angulo: ")) seno = sin(radians(angulo)) cosseno = cos(radians(angulo)) tangente = tan(radians(angulo)) print("Senho: {:.2f}".format(seno)) pr...
ae446b1c57aa05e46e013daf4fff61177e1c4e40
guilhermeG23/AulasPythonGuanabara
/Pratico/Exemplos/somaBasica.py
148
3.859375
4
n1 = float(input("Entre com o valor: ")) n2 = float(input("Entre com o valor: ")) s = n1 + n2 print("Soma entre {} mais {} é {}".format(n1, n2, s))
677f0f4d65d4e404d27b138d1715c0d2ebc41750
guilhermeG23/AulasPythonGuanabara
/Pratico/Exemplos/operadoresAritimeticos1.1.py
243
3.953125
4
n1 = float(input("Entrada 1: ")) n2 = float(input("Entrada 2: ")) #Imprimir na linha #Variaveos so são utilizadas quando a mais de uma chamada dela no codigo, um valor que se repetira mais de uma vez print("Valor somatorio: {}".format(n1+n2))
c406d32dfc1dbf1e07ea73fddf9c10d160d47dc1
guilhermeG23/AulasPythonGuanabara
/Pratico/Exemplos/AnalisandoVariaveis.py
657
4.28125
4
#trabalhando com métodos entrada = input("Entrada: ") print("Saida: {}".format(entrada)) #Tipo da entrada print("Tipo: {}".format(type(entrada))) #Entrada é Alpha-numero? print("AlphaNumerico: {}".format(entrada.isalnum())) #Entrada é alfabetica print("Alpha: {}".format(entrada.isalpha())) #Estrada é numerica print("Nu...
ff96063f1f75c29814effe2685f6702c8057c7f8
guilhermeG23/AulasPythonGuanabara
/Pratico/Exemplos/RaizQuadrada.py
603
4.09375
4
#Import tudo import math #Importando so o sqrt #from math import sqrt #por biblioteca entrada = float(input("Digite o valor: ")) print("O valor: {}\nRaiz Quadrada do valor é: {:.2f}".format(entrada, math.sqrt(entrada))) #Aredondando pra cima raiz = math.sqrt(entrada) print("O valor: {}\nRaiz Quadrada do valor é: {:.2...
04854c04f56ef38f72a13f6fd1dc3207627f36fa
guilhermeG23/AulasPythonGuanabara
/Pratico/Exemplos/bibliotecaDeUnicoComando.py
114
3.84375
4
from math import sqrt entrada = float(input("Entrada: ")) print("Saida ao Quadrado: {:.4f}".format(sqrt(entrada)))
f84b869c792faf4e49614a6098ca7b3e13c482e7
SamuelWeiss/termetris
/main.py
5,048
3.578125
4
from board import tetris_board from keyboard_actions import * from shape import shape, all_shapes import time import math import sys, select import random def calculate_next_frame(level): now = time.time() return now + (1.0 / (level * 0.5 + 0.5)) # avoid weird screen flickering def composite_display(board, score, ...
2c01b876ba15e8850dedf0e1bc588cfe636cdddf
waitalone/dnn-time-series
/dnntime/utils/ts.py
4,553
3.53125
4
import numpy as np class timesteps: def __init__(self, freq: str) -> None: """ Initializes timesteps class, which can output a number of timesteps with ease given the desired period duration in text. Contains mapping of num of timesteps to a stated period, relative to each other. ...
6f3f8098ef1f7bff76454e4dbb634d8578bae03e
anthorne/advent-of-code_2017
/d8.py
3,004
3.84375
4
# Advent of Code - 2017 - day 8 input_data = open('d8_input.txt') # input_data = open('d8_example.txt') registers = list() highest_value = int() class Register: def __init__(self, name): self.name = name self.value = 0 def check_register(register, registers): """check if register is found ...
f56a0284e8a68e37205f5d6e9fb197725c2ea5fd
anthorne/advent-of-code_2017
/d12.py
1,072
3.515625
4
# Advent of Code - 2017 - day 12 def add_childs(program, childs): for c in childs: found = False for p in programs[program][1]: if c == p: found = True if not found: programs[program][1].append(c) # Get input data f = open('d12_input.txt', 'r') pro...
b5b4ebc84d31f10c982dfc65275c44cf9d6a6703
saraatsai/py_practice
/number_guessing.py
928
4.1875
4
import random # Generate random number comp = random.randint(1,10) # print (comp) count = 0 while True: guess = input('Guess a number between 1 and 10: ') try: guess_int = int(guess) if guess_int > 10 or guess_int < 1: print('Number is not between 1 and 10. Please enter a valid n...
bb20892c11b9fedb0fe35696b45af31451bbe7e8
Devbata/icpu
/Chapter3/Fexercise3-3-1.py
594
4.25
4
# -*- coding: utf-8 -*- #Bisecting to find appproximate square root. x = float(input('Please pick a number you want to find the square root of: ')) epsilon = 1*10**(-3) NumGuesses = 0 low = 0.0 high = max(1.0, abs(x)) ans = (high + low)/2.0 while abs(ans**2 - abs(x)) >= epsilon: print('low =', low, 'high...
ea1c1e75081663990748cfe6f6376e95113f31eb
TripleC-Light/LintCode
/1505/LintCode.py
874
4.09375
4
""" Given an unsorted array of n elements, find if the element k is present in the array or not. Complete the findnNumber function in the editor below.It has 2 parameters: 1 An array of integers, arr, denoting the elements in the array. 2 An integer, k, denoting the element to be searched in the array. The function mus...
c8bb1adbedf3eea835224fc7d9a941f5b87b41be
TripleC-Light/LintCode
/1355/LintCode.py
917
4.09375
4
""" Given a non-negative integer numRows, generate the first numRows of Pascal's triangle. In Pascal's triangle, each number is the sum of the two numbers directly above it. Example 1: Input: 5 Output: [ [1], [1,1], [1,2,1], [1,3,3,1], [1,4,6,4,1] ] Example 2: Input: 3 Output: [ [1], [1,1], ...
e3b7b99ad809732f81da3da0b301cf77c24b587b
TripleC-Light/LintCode
/1535/LintCode.py
765
4
4
""" Implement function ToLowerCase() that has a string parameter str, and returns the same string in lowercase. Example 1: Input: "Hello" Output: "hello" Example 2: Input: "here" Output: "here" Example 3: Input: "LOVELY" Output: "lovely" """ class Solution: """ @param str: the input string @return: Th...
0ec2e450d1ed1adaa417cb3995e3096f2ed4e70b
Anvin3/python
/Basic/removeDup3.py
266
4.03125
4
''' This piece of code will remove duplicates in list ''' def removeduplicate(a): b=set(a) print('Removed duplicates---',b) a=[int(x) for x in input('Enter the numbers seperated by space \n').split()] print('Given list is ',a) removeduplicate(a)
6858af583e1ad4657650d185b87f289aec26a1a4
Anvin3/python
/Basic/divisor.py
261
4.15625
4
''' Create a program that asks the user for a number and then prints out a list of all the divisors of that number. ''' num=int(input("Please enter a number of your choice:")) subList=[i for i in range(2,num) if num%i==0 ] print("All the divisors are",subList)
ac2330f260c5bdf19a6f2ce4bca342bb3b58db33
shin623p/prime-numbers
/python/sieve.py
405
3.609375
4
import math def sieve(n): nums = list(range(n + 1)) for i in range( 3, math.ceil( n**0.5 ), 2): if nums[i] == 0: continue for j in range( i * i, n, i * 2 ): if nums[j] != 0: nums[j] = 0 return [2] + list( filter( lambda x: x % 2 != 0 and x > 2, nums ...
d0318e9d768d097d2d3e8cee8975051e67240293
Iboggio/All-other-py-files
/chapter7.py
949
4.03125
4
#x = [1,2] #print (x) #print(x[0]) #x[0] = 33 #print (x) #my_list = [101, 20, 10, 50, 60] #for item in my_list: # print(item) #my_list = ["Spoon", "Fork", "Knife"] #for item in my_list: # print(item) #my_list.append("ladle") #for item in my_list: # print(item) #my_list = [ [2,3], [4,3], [6,7] ] #...
293d4125f2931d036ba29a678cbdc7c656cdf82c
varun-sundar-rabindranath/detviz
/rotate_demo.py
1,745
3.890625
4
from detviz import * import math print (''' The determinant is the area of a unit square that you see in the plot ''') def draw_and_show(m, plt_name = "GRAPH"): plot_setup(plt_name) draw_matrix(m, "maroon", 0.5, "-", llgram = True) draw_axes_for_matrix(m, "red", 0.1, "-") plt.show() def rotate_v...
cb2b304e1d082ef01de0c3175b6957b903feb9d9
leeonweng/Python-Lab
/彭彭的課程學習/類別的定義與使用.py
956
3.625
4
# -*- coding: utf-8 -*- """ Created on Sun Dec 9 14:52:53 2018 @author: Home love #建立類別 class 類別名稱: 定義封裝的變數 定義封裝的函式 #使用類別 類別名稱.屬性名稱 """ #定義Test類別 class Test: x=3 #定義變數 def say(): #定義函式 print('Hello') #####################################################################...
4ae81d8dd7f99d4bbe6649617fd8000e79f505da
SPDhilrukshan/HDCBIS18.2F017
/caeserCipher.py.txt
302
4
4
# File: CaeserDecipher.py ctext = str(input("please enter the text you want to decipher")) text="" alphabet="abcdefghijklmnopqrstuvwxyz" key=3 for L in text: if L in alphabet: text += alphabet[(alphabet.index(L) - key)%26] else: text += L print("your deciphered text is :" + text)
65064e3c33410e3ec527b89d28872e6562491af1
anjana-analyst/Programming-Tutorials
/Competitive Programming/DAY-25/password.py
875
4.0625
4
def password(p): sym=['$','#','@','%'] val=True if len(p)<6: print("Length should be atleast 6") if len(p)>20: print("Length is more than 20") if not any(char.isdigit() for char in p): print("It should have atleast one number") val=False if not any(...
9ba20f0186ea9a8bf708fbd9133e99ea4845c765
anjana-analyst/Programming-Tutorials
/Competitive Programming/DAY-20/square.py
180
3.96875
4
def sq(n): s=n for i in range(1,n): s=s+n return s if __name__ == '__main__': n=int(input("Enter a number to square")) print("Square of",n,"is",sq(n))
382dbb2572586d26f9f335e004f6886f74abdc07
anjana-analyst/Programming-Tutorials
/Competitive Programming/DAY-29/metm.py
323
4.15625
4
def time(hh,mm,ss): return hh+(mm/60)+(ss/60)/60 def distance(): m=int(input("Enter the meters")) hh=int(input("Enter the hours")) mm=int(input("Enter the minutes")) ss=int(input("Enter the seconds")) miles=(m*0.000621372)/time(hh,mm,ss); print("Miles per hour is ",miles) distance...
781ac1b95d61aa7ddc55031358d7bd82e650f793
stuartjchapman/xltable
/xltable/__init__.py
3,762
3.609375
4
""" xltable ======= A package for writing excel worksheets with formulas and styles. Introduction ------------ :py:mod:`xltable` is an API for writing tabular data and charts to Excel. It is not a replacement for other Excel writing packages such as :py:mod:`xlsxwriter`, :py:mod:`xlwt` or :py:mod:`pywin32`. Instead ...
e79a41db606945edbaff6c6344e69d826bc805d7
woskoboy/itvdn
/1_intro/single.py
526
4.0625
4
class Singleton: """ Singleton гарантирует, что данный класс имеет только 1 экземпляр """ _instance = None # @classmethod - не требуется, python и так знает об этом спец.методе def __new__(cls): if cls._instance is None: cls._instance = object.__new__(cls) return cls._instan...
bd2dd9df88744f12a7d0d0e7d3edd3b60afccea7
ahastudio/CodingLife
/20200509/python/crain_test.py
1,393
3.671875
4
class Board(): def __init__(self, board): self.stacks = [ [row[x] for row in reversed(board) if row[x]] for x in range(len(board[0])) ] self.basket = [-1] # trick! :D self.score = 0 def pick(self, position): stack = self.stacks[position - 1] ...
ecc3c31f2aeb64482af1205f6b8e4f9f645fa9ce
allwak/algorithms
/Sprint14_Sorting/Theme1_Sorting/1c.py
981
3.765625
4
#%% def effective_quiqsort(array, left, right): if right - left < 1: return pivot = left position = right while pivot != position: if pivot < position: if array[pivot] >= array[position]: array[pivot], array[position] = array[position], array[pivot] ...
8b00536b2a3117586728cbe2bfd4f5fdf1221ce0
allwak/algorithms
/Sprint12/Final_tasks/3b.py
508
3.90625
4
#%% class Node: def __init__(self, value, next=None): self.value = value self.next = next def __repr__(self): return self.value def hasCycle(node): while (node.next is not None) and (node.next != node.value): tmp = node.next node.next = node.value node = tm...
332461a9b2ece6a7f133f54169cf7e5c0148c5c0
allwak/algorithms
/Sprint14_Sorting/Theme1_Sorting/1k.py
420
3.8125
4
#%% def partial_sorting(array): count = 0 for i in range(0, len(array)): border = array[array[i]] + 1 if set(array[:border]) == {i for i in range(border)}: count += 1 return count if __name__ == "__main__": with open("input.txt") as f: n = int(f.readline()) ...
abf7cdd0d1eff908da9a7991d24ba4ee232e09af
allwak/algorithms
/Sprint12/Theme2_basic_data_structures/linked_list.py
1,367
3.90625
4
#%% class Node: def __init__(self, value = None, next_item = None): self.value = value self.next_item = next_item def __str__(self): return self.value #%% def insert_node(node, index, value): head = node new_node = Node(value) if index == 0: new_node.next_ite...
3d8c142d088cc2def3300a318ae20d9ba40f7e84
allwak/algorithms
/Sprint14_Sorting/Final_tasks/b_radix_sort.py
1,075
3.59375
4
# ID успешной посылки 37090569 #%% def radix_sort(array, k): def sorting(item): item = "0" * (k - len(item)) + item return item[i] for i in range(k-1, -1, -1): array.sort(key=sorting) if __name__ == "__main__": with open("input.txt") as f: n = int(f.readline()) # читает 1-...
af28f44de4c426bfa494b5f01f55f7409f11f59f
allwak/algorithms
/Sprint15_Trees/e.py
957
3.84375
4
from collections import deque class Node: def __init__(self, value, left=None, right=None): self.value = value self.right = right self.left = left def __repr__(self): return str(self.value) def solution(root1: Node, root2: Node): q1, q2 = deque(), deque() q1.append(r...
1677eb9806c8e30c6565a6648109ca75c3e8b2ba
allwak/algorithms
/Sprint12/Theme2_basic_data_structures/2q.py
2,255
3.734375
4
#%% class Node: def __init__(self, value = None, next = None, prev = None): self.value = value self.next = next self.prev = prev def __str__(self): return self.value #%% class Deque(): def __init__(self, max_size): self.size = 0 self.max_size = max_size ...
d461fc5e1a7c55ea61350975ebc6801a92b5d923
allwak/algorithms
/Sprint12/Theme2_basic_data_structures/2l.py
1,032
3.875
4
#%% class Stack: def __init__(self): self.items = [] def is_empty(self): return self.items == [] def push(self, item): self.items.append(item) def pop(self): return self.items.pop() def peek(self): return (self.items[-1]) # def size(self): # r...
aca1d2871bf8a32646ff06c921d9f033ee769fe3
adityaprasann/PythonProj
/dsfunnexercise/missingnum.py
921
4
4
# Consider an array of non-negative integers. A second array is formed by shuffling the elements of the first array and deleting a random element. Given these two arrays, find which element is missing in the second array. # Here is an example input, the first array is shuffled and the number 5 is removed to construct t...
b1b03e4877a0719ac87cbb2093a157baec011abb
adityaprasann/PythonProj
/programforfun/SieveEratosthenes.py
1,687
4.09375
4
#The method works as follows (see [here](https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes) for more details) #1. Generate a list of all numbers between 2 and N #2. Starting with $p=2$ (the first prime) mark all numbers of the form $np$ where $n>1$ and $np <= N$ to be not prime (they can't be prime since they are mul...
4b85eb0e9e1462ab0bd1728f4ed1fba33ee99179
ngpark7/deeplink_public
/2.ReinforcementLearning/MCTS/mcts.py
9,222
3.5
4
# For more information about Monte Carlo Tree Search check out our web site at www.mcts.ai # http://mcts.ai/about/index.html from math import * import random def upper_confidence_bounds(node_value, num_parent_visits, num_node_visits): """ the UCB1 formula """ return node_value + sqrt(2 * log(num_parent_visit...
ced354d7034df14d43ff61cafe2d29026df9fd65
ngpark7/deeplink_public
/3.MachineLearning/06.numerai/numerai.py
5,631
3.8125
4
#!/usr/bin/env python import pandas as pd import numpy as np from sklearn import decomposition, ensemble, metrics, pipeline from xgboost import XGBClassifier def main(): # Set seed for reproducibility np.random.seed(0) print("# Loading data...") # The training data is used to train your model how to ...
8bed30fd6dde9ad07105409e2ff8aa3a18d66237
ngpark7/deeplink_public
/1.DeepLearning/01.Multiple_Neurons/or_gate_three_neurons_target.py
2,346
3.6875
4
from __future__ import print_function import numpy as np import random import math class Neuron1: def __init__(self): self.w1 = np.array([random.random(), random.random()]) # weight of one input self.b1 = random.random() # bias print("Neuron1 - Initial w1: {0}, b1: {1}".format(self.w1, ...
e436c6bd680f23f99b8599c496686bd959431d7e
MiguelBim/Python_40_c
/Challenge_35.py
2,384
4.0625
4
# CHALLENGE NUMBER 35 # TOPIC: Funct # Loan Calculator # https://www.udemy.com/course/the-art-of-doing/learn/lecture/17060904#overview import matplotlib.pyplot as plt def approve_loan(loan_amount, interest, monthly_payment): min_monthly_amount = loan_amount * (interest / 100) if monthly_payment <= min_monthl...
374aece2198b784cfcfa1ea60c00bd8ad205e0cc
MiguelBim/Python_40_c
/Challenge_1.py
1,068
4.0625
4
# CHALLENGE NUMBER 1 # Word count # https://www.udemy.com/course/the-art-of-doing/learn/lecture/17060710#overview def my_solution(message, letter): letter_dict = {} for character in message.lower(): letter_dict[character] = letter_dict.get(character, 0) + 1 return letter_dict[letter.lower()] d...
444b6f1afdc88970fc1e726e8cd317a932eea301
MiguelBim/Python_40_c
/Challenge_21.py
1,701
3.9375
4
# CHALLENGE NUMBER 21 # TOPIC: Dic Struct # Thesaurus App # https://www.udemy.com/course/the-art-of-doing/learn/lecture/17060816#overview import random def thesaurus_app(word, dictionary): rand_num = random.randint(0, 4) app_response = dictionary[word][rand_num] print("A synonym for {} is {}.".format(wo...
cc44c6d843b7b6533f2b9d944a45aedba9df1ffd
MiguelBim/Python_40_c
/Challenge_22.py
1,905
3.9375
4
# CHALLENGE NUMBER 22 # TOPIC: Dic Struct # Database Admin Program # https://www.udemy.com/course/the-art-of-doing/learn/lecture/17060820#overview def admin_database(username, user_password, database_users): print("\nHello {}! You are logged in!".format(username)) reset_pwd = input("Would you like to change ...
63d10fa7f02ba38539f03a49c09dccb6d36dbc70
MiguelBim/Python_40_c
/Challenge_31.py
1,250
4.1875
4
# CHALLENGE NUMBER 31 # TOPIC: Funct # Dice App # https://www.udemy.com/course/the-art-of-doing/learn/lecture/17060876#overview import random def dice_app(num_of_dice, roll_times): total_count = 0 print("\n-----Results are as followed-----") for rolling in range(roll_times): val_from_rolling = ra...
42779f1d41c6d33cd2ea16e66e1d805fc0b29894
marcodlk/perceptron
/datagen.py
816
3.53125
4
""" Created on Tue Aug 29 11:53:40 2017 @author: Kasey Hagi """ from random import randint def generate_random_linear_separable(size=10, slope=[0,5], inter=[0,10], bounds=[-50,50]): _dataset = [] _sl...
b54329efe31f6fbebff58b9fe6f343839944e8c4
sirokome19/library
/WarshallFloyd.py
2,515
3.90625
4
''' ワーシャルフロイド法 そんなに使用頻度は高くないが実装コストが低い。 本来は無向グラフを想定するが、有向グラフでも使える。 ''' class WarshallFloyd(): def __init__(self, N): """ Parameters ---------- N:int the number of node """ self.N = N self.d = [[float("inf") for i in range(N)] ...
b73efa38b6f3e925912c0fdfafd69098fa7cb5d9
adwitiya/intercom_test_solution
/solution.py
2,594
3.8125
4
#/**************************************************************/ # solution.py -- Distance between two locations * # Author: Adwitiya Chakraborty * # chakraad@tcd.ie * # github.com/adwitiya ...
069d66f7d28b5aaafb19270499140457577e1e55
heedfull/PythonTheHardWay
/ex8.py
538
3.703125
4
# create a string full of formatting characters formatter = "%r %r %r %r" # print numbers print formatter % (1, 2, 3, 4) # print strings print formatter % ("one", "two", "three", "four") # print booleans print formatter % (True, False, False, True) # print string of format characters print formatter % (formatter, form...
953cb72d2e4155438c6fe79d699c537c8afd2198
openstack/barbican
/barbican/tests/test_hacking.py
5,576
3.625
4
# Copyright 2016 GohighSec # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agree...
e11e70bd7fc36c3d4e3063579d4c5d917b91adaf
dimatolsti4/case2
/main.py
2,198
3.96875
4
import local tax = 0 year_income = 0 print(local.INCOME_INPUT) for month in range(12): # Ввод зарплаты за год помесячно month_income = int(input()) year_income += month_income print(year_income) category = int(input(local.CATEGORY_INPUT)) # Ввод вашей категеории if category == 1: # Подсчет для 1 категори...
2c04a22cfdaf701e0f108e8dec047556814a9d03
abin7-alpha/Solutions-think-python
/chapter10/exercise11.py
829
3.78125
4
def reverse_pair(word): a = word[::-1] return a def reverse_pair_list(word): reverse_list = [] for i in word: reverse_list.append(reverse_pair(i.strip())) return reverse_list def normal_list(word): lists = [] for i in word: lists.append(i.strip()) return lists def in_b...
dd51e48aa50427ecd9c8e9384150df24ffb2074e
abin7-alpha/Solutions-think-python
/chapter10/exercise7.py
215
3.671875
4
def has_duplicates(t): for i in range(len(t)): a = t[i+1 : len(t)] if t[i] in a: return True return False t = ["c","b","d","c"] print(has_duplicates(t))
094e42b4e584d5de116e650ebe0e6c3348339c6b
abin7-alpha/Solutions-think-python
/chapter5/recursion/interleavingstrings.py
285
4.09375
4
"""Find all interleavings of given strings""" def interleaving(str1,str2,length): string = str1+str2 length = len(string) print(string) print(length) a = string[i+1] string[i+1] = string[i] string[i] = a string interleaving("ab","da")