blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
1e9a3516a855996521f76299f9796691d448d958 | w40141/atcoder | /abc_164/a_tmp.py | 259 | 3.640625 | 4 | raw_input = input().split()
s = int(raw_input[0])
w = int(raw_input[1])
t = 0
if s - w > 0:
print('safe')
else:
print('unsafe')
def add(a, b):
return a + b
def f():
return add(None, 0)
def add(a, b):
c = a if a else 0
return a+ b
|
f82d948835ba52739977d1f3cfadd3cdcc7687c7 | w40141/atcoder | /bonzin/abc_146_c.py | 366 | 3.515625 | 4 | a, b, x = map(int, input().split())
def price(a, b, n):
return a * n + b * int(len(str(n)))
if x < price(a, b, 1):
print(0)
exit()
left = 1
right = 10**20
while right - left > 1:
center = (left + right) // 2
if price(a, b, center) <= x:
left = center
else:
right = center
i... |
eb15fa424d850d739dda38e84ebdcc923846fe02 | w40141/atcoder | /abc_164/b.py | 333 | 3.578125 | 4 | raw_input = input().split()
takahashi_hp = int(raw_input[0])
takahashi_ak = int(raw_input[1])
aoki_hp = int(raw_input[2])
aoki_ak = int(raw_input[3])
while 1:
aoki_hp -= takahashi_ak
if aoki_hp <= 0:
print('Yes')
break
takahashi_hp -= aoki_ak
if takahashi_hp <= 0:
print('No')
... |
7dd4ac9018e4b5c6e08548e41eb2339c5e9c9f1b | w40141/atcoder | /agc_056/a.py | 641 | 3.703125 | 4 | N = int(input())
num_list = list(range(n))
def make_str(n):
if N - n == 2:
s = "##" + "." * (N - 3) + "#"
elif N - n == 1:
s = "#" + "." * (N - 3) + "##"
else:
s = ""
for i in range(N - 3):
if i == n:
s += "###"
else:
... |
b8756c891b0688e4998ab481ad0215ea2d54c4a1 | AIDemyanov/Python_hw_3 | /3_task_3.py | 391 | 4.25 | 4 | # Реализовать функцию my_func(), которая принимает три позиционных аргумента, и возвращает сумму наибольших
# двух аргументов
def my_func(a, b, c):
if a >= b and b <= c:
print(a + c)
elif a <= b and a >= c:
print(a + b)
else:
print(b + c)
my_func(1, 2, 3) |
84b343d6f2c5ec96948e2b09abfca7fc867dde8c | GabrielCavalcanti13/Algorithms__Data-structures-IF969 | /Estruturas de Dados/doubly_linked_list.py | 1,516 | 3.65625 | 4 | class Node():
def __init__(self,item = None, previus_node = None, next_node = None):
self.item = item
self.previus_node = previus_node
self.next_node = next_node
def __str__(self):
return str(self.item)
def __repr__(self):
return self.__str__()
class List():
def __init__(self, item = None):
self.len ... |
296fc9a4f538c6acc66ca61514ae616a656af729 | Albert-91/url_shortener | /project/apps/url_shortener/utils.py | 757 | 3.625 | 4 | import os
from hashlib import blake2b
from typing import Text
def encode_string(s: Text, size: int = 10) -> Text:
"""
Function hashes provided string by BLAKE2 cryptographic algorithm
https://docs.python.org/3/library/hashlib.html#blake2
:param s: string to encode
:param size: integer with size of... |
64836a57f34832bb88399592f8aadb75ed07640d | YongTat/SudokuBackTrack | /sudoku.py | 2,770 | 3.765625 | 4 | GRID = [
[0,7,0,0,0,0,4,0,5],
[0,0,0,0,0,1,0,0,6],
[2,0,0,0,7,0,0,0,0],
[0,0,4,2,0,0,0,0,8],
[0,0,0,7,0,0,0,1,0],
[1,3,0,0,0,5,0,0,9],
[0,0,0,5,0,0,1,0,0],
[9,0,0,3,0,0,0,6,0],
[6,0,0,0,0,0,0,0,4]
]
def solver(grid):
"""[Sovle sudoku with given grid]
Args:
... |
4896fa848a0fac04640b05cb61ff79689b9705e1 | Mikko1o/Dynamic_programming | /lcs.py | 1,778 | 3.84375 | 4 | # Python 2.7.1
# Find the longest common subsequence of two strings
# Returns the longest of two strings
def maximum(x, y):
if x.__len__() >= y.__len__():
return x
else:
return y
# Returns the longest common subsequence
def lcs(x, y):
assert isinstance(x, str)
assert isinstance(y, st... |
44a2b6a83f95f6b754b133eecf38e163a3ee124f | Mikko1o/Dynamic_programming | /coin_game.py | 2,197 | 3.953125 | 4 | # Python 2.7.1
# Problem statement: Consider a row of n coins of values v1 . . . vn, where n is even.
# We play a game against an opponent by alternating turns.
# In each turn, a player selects either the first or last coin from the row, removes it from the row permanently,
# and receives the value of the coin.
# Deter... |
b6d856cde023e35ac184b51b4eaac1608fd12169 | glebsolyanik/homework_2 | /task_4.py | 1,017 | 4.125 | 4 | '''
Task №4
Программа принимает действительное
положительное число x и целое отрицательное
число y. Необходимо выполнить возведение
числа x в степень y. Задание необходимо
реализовать в виде функции my_func(x, y).
При решении задания необходимо обойтись
без встроенной функции возвед... |
8ab44b15861c23faa71a457d1ef5cec2834e3934 | dataloudlabs/dloud-ads | /dloud_ads/binary_tree.py | 1,909 | 4.125 | 4 | """Abstract base class representing a binary tree structure."""
from .tree import Tree
class BinaryTree(Tree):
"""Abstract base class representing a binary tree structure."""
def left(self, pos):
"""Return a Position representing p's left child.
Return None if p does not have a left child.
... |
9820df166ba055d05433098b8d408ae953668e57 | C-CCM-TC1028-111-2113/homework-4-Mike-GB | /assignments/17NCuadradoMayor/src/exercise.py | 201 | 3.984375 | 4 |
def main():
num = int(input("Escribe un numero : "))
#escribe tu código abajo de esta línea
v=1
while v**2<=num:
v=v+1
print(v)
if __name__=='__main__':
main()
|
1bb52289deadf0f73d0330ae9dec35c412172f9e | scott-rdl/m1ibiom-python-projetfinal | /Patient.py | 1,063 | 3.859375 | 4 | #! /usr/bin/env python3.6
# -*- coding: utf-8 -*-
from Occupant import *
class Patient(Occupant):
"""
CLASS PATIENT
Hérite d'Occupant pour les malades ayant des symptomes
@author: Scott RIDEL
"""
# === CONSTRUCTEUR ===
def __init__(self, _nom, _prenom, _age, _symptomes):
super()... |
bbdfd0cf34ed7e6842b4bf76d0dcb749cd742280 | intelshoe/simple_convert | /main.py | 1,683 | 4.3125 | 4 | '''
A simple converter tool.
Converts decimal, hex, binary, and ascii.
Author: mp
'''
# take first value to be converted
print("Convert what type of value?\n")
print("Type b for binary, d for decimal, h for hex, or a for ascii\n")
convertfrom = str(input())
print("Ok, please enter the value: ")
if convertfrom == "h" ... |
9382e60822efe8629077f3ed5923b882213f30d8 | SLB974/p3MacGiver | /labyrinth.py | 10,194 | 3.578125 | 4 | # coding:utf-8
import os
import pygame
from random import randint
import constants as ct
class Maze:
""" Class to define labyrinth's struture """
def __init__(self):
""" At init, get the maze's structure in structure file """
directory = os.path.dirname(__file__)
self.path_to_file ... |
2f4f1ed2e148a7eeb49a3e8f17c9498656251332 | yigitatesh/sudoku | /sudoku.py | 16,280 | 3.640625 | 4 | import numpy as np
import random
### SUDOKU ###
class Sudoku(object):
"""Creates a sudoku object that can handle sudoku events.
Initially creates a sudoku solution filled with digits."""
def __init__(self):
# keeps track to end sudoku creating process
# set to False to kill the... |
8337ac79cf209cdeb51c6c5ecab7f7b198cda3a3 | fawkesley/python-utcdatetime | /utcdatetime/parse_datetime_string.py | 2,112 | 3.5625 | 4 | import datetime
import re
from .utcdatetime import utcdatetime
DATETIME_REGEX = (
r'(?P<year>\d{4})'
'-'
'(?P<month>\d{2})'
'-'
'(?P<day>\d{2})'
'T'
'(?P<hour>\d{2})'
':'
'(?P<minute>\d{2})'
':'
'(?P<second>\d{2})'
)
FRACTIONAL_SECONDS_REGEX = r'(?P<fractional_second>\.\d+... |
591a94216cb2f295e9bc36ce31d8a3254058c852 | maxn-csi/python-training | /Tasks 02/task_2-2.py | 702 | 4.125 | 4 | #!/usr/bin/python3.8
#
# task_2-2
#
# Функция получает на вход целое число в диапазоне от 1 до 365. Это номер дня в 2020 году.
# Функция возвращает строку «workday» для рабочих дней (пн-пт), строку «day off» для выходных,
# и None, если входное значение было некорректным.
def weekday(day):
if 0 < day < 366:
... |
2f50390a8936d23c3b5d2074806728a5760cb14d | habibor144369/python-practice-2 | /list-revers.py | 236 | 4.0625 | 4 | # here list doing reverse----
saarc = ['Bangladesh', 'Afghanistan', 'Bhutan', 'India', 'Nepal', 'Pakistan', 'Sri Lanka']
saarc.reverse()
print(saarc)
# second program --
list = [2, 3, 5, 1, 7, 9, 4, 8, 6, 10]
list.reverse()
print(list) |
33da6c19f18110e2fd28e236fd376227542df48a | momandine/Hidden-Markov-Models | /adv_replace_rare.py | 2,169 | 3.59375 | 4 | """This program takes all of the words with counts < 5 and replaces
thier name with '_RARE_' to estimate the emmission probability of
words not seen before"""
from sys import argv
from sets import Set
import string
script, countsrcfile, trainsrcfile, destfile = argv
# The file from which count values will be extrac... |
a4a41f58db9be33efba02bb66768f7dcf782070d | harles/learning-python | /programmeerimise_alused_II/nadal_1/n11.py | 986 | 3.5 | 4 | # Esimese nädala ülesanne
# Allikas: https://moodle.ut.ee/mod/vpl/view.php?id=302356
# Näidis sisendfail: kalad.txt
import math
suurim_kala_kaal = 0
kaal = 0
def kala_kaal(kala_pikkus, tüsedusindeks):
kaal = round(math.pow(kala_pikkus, 3) * tüsedusindeks / 100)
return kaal
if __name__ == "__main__":
s... |
5c88cf1eb77b322dbd4b9244cd2c04ac690cc0a0 | prathameshanabhavane/python | /data_structure.py | 5,054 | 3.953125 | 4 | # letters = ["a", "b", "c", "d"]
# matrix = [[0, 1], [1, 2], [2, 3]]
# zeros = [0] * 5
# combined = zeros + letters
# numbers = list(range(0, 21))
# chars = list("Hello World")
# lengthChar = len(chars)
# lengthNumbers = len(numbers)
# print(letters)
# print(letters[0])
# print(matrix)
# print(zeros)
# print(combined... |
678ef9b3c470cb45955c96797e6962bbd36b66e6 | wilrop/Imperium | /explorer_plots.py | 5,421 | 3.5625 | 4 | import plotly.express as px
import plotly.graph_objects as go
from preprocessing import amount_years
import numpy as np
# The colours for the error bars and the lines connecting them.
marker_color = 'rgba(55, 153, 81, 1)'
line_color = 'rgba(55, 153, 81, 0.4)'
def calc_totals(df):
"""
Method to generate the m... |
938576e97fd8fcdcfc95bddefdaac051b8eab3da | Leonardo-S95/python-curso-em-video | /exercicios/desafio097-aula20.py | 491 | 4.0625 | 4 | '''
DESAFIO 097
Faça um programa que tenha um função chamada escreva(), que receba um texto qualquer como
parâmetro e mostre uma mensagem com tamanho adaptável.
Ex: escreva('Olá, Mundo!')
Saida: ~~~~~~~~~~~~
Olá, Mundo!
~~~~~~~~~~~~
'''
def escreva(txt):
print('~' * (len(txt... |
0e7a79513deeced24aaa575590daf8fcde24fa21 | Leonardo-S95/python-curso-em-video | /exercicios/desafio080-aula17.py | 712 | 4.3125 | 4 | '''
DESAFIO 080
Crie um programa onde o usuário possa digitar cinco valores númericos e cadastre-os em uma lista, já na posição correta
de inserção (sem usar o sort()). No final, mostre a lista ordenada na tela.
'''
lista = []
cont = 0
for i in range(0, 5):
num = int(input(f'Digite o {cont +... |
a5057841d82b8246673a56e98f835abc5dc40164 | Leonardo-S95/python-curso-em-video | /exercicios/desafio084-aula18.py | 1,832 | 3.9375 | 4 | '''
DESAFIO 084
Faça um programa que leia nome e peso de vários pessoas, guardando tudo em uma lista.
No final, mostre:
a) Quantas pessoas foram cadastradas
b) Uma listagem com as pessoas mais pesadas.
c) Uma listagem com as pessoas mais leves.
dados = []
maior = []
menor = []
count = 0
while... |
7d76d3cfd8d20ed6856a9f69b10beca88008ab47 | Leonardo-S95/python-curso-em-video | /exercicios/desafio086-aula18.py | 845 | 4.46875 | 4 | '''
DESAFIO 086
Crie um programa que crie uma matriz de dimensão 3x3 e preencha com valores lidos pelo
teclado. No final, mostre a matriz na tela, com a formatação correta.
'''
matriz = [[], [], []]
for i in range(0, 3):
for j in range(0, 3):
matriz[i].append(int(input(f'Digite um nú... |
99516a77ca5ff79ebd2c2e332c470e2d16ae593f | Leonardo-S95/python-curso-em-video | /exercicios/desafio005-aula07.py | 383 | 4.0625 | 4 | '''
DESAFIO 005
Faça um programa que leia um número inteiro e mostre na tela o seu sucessor e
seu antecessor.
'''
print('\t\t\t\tDESCUBRA O SUCESSOR E O ANTECESSOR DE UM NÚMERO!')
n1 = int(input('Digite um número: '))
su = n1 + 1
an = n1 - 1
print('O sucessor de', n1, 'é \033[1;32m{}\033[... |
2e53c8699f536734f532e4ca9d0f6c30cb9d80f8 | Leonardo-S95/python-curso-em-video | /exercicios/desafio087-aula18.py | 1,226 | 4.1875 | 4 | '''
DESAFIO 087
Aprimore o desafio anterior, mostrando no final:
a) A soma de todos os valores pares digitados.
b) A soma dos valores da terceira coluna.
c) O maior valor da segunda linha.
'''
matriz = [[], [], []]
spar = ster = maior = 0
for i in range(0, 3):
for j in range(0, 3):
... |
20dda70d340de5fce7abf4da3d2d47e0c7496bb1 | Leonardo-S95/python-curso-em-video | /exercicios/desafio050-aula13-revendo.py | 914 | 4 | 4 | '''
DESAFIO 050
Desenvolva um programa que leia seis números inteiros e mostre a soma apenas daqueles que forem pares.
Se o valor digitado for ímpar, desconsidere-o.
soma = 0
cont = 0
for i in range(1, 7):
n = int(input('Digite o {}º valor: '.format(i)))
if n % 2 == 0:
soma +=... |
8734acdd7396e6a36098f6dd496969727210ebd2 | Leonardo-S95/python-curso-em-video | /exercicios/desafio046-aula13-revendo.py | 714 | 3.5625 | 4 | '''
DESAFIO 046
Faça um programa que mostre na tela uma contagem regressiva para o estouro de fogos de artifício, indo de 10 até 0,
com uma pausa de 1 segundo entre eles.
from time import sleep
for i in range(10, -1, -1):
print(i)
sleep(1)
print('')
print('\t\033[30;41m~LE FOGOS DE AR... |
3fdc197473c6c56c1b60dd0109e4a8608d767937 | Leonardo-S95/python-curso-em-video | /aulas/aula7-operadores-aritmeticos.py | 1,923 | 4.53125 | 5 | '''
+ é adição * é multiplicação ** é potencia % é resto da divisão
- é subtração / é divisão // é divisão inteira
ORDEM DE PRECEDÊNCIA
1º ~> ()
2º ~> **
3º ~> *, /, //, %
4º ~> +, -
'''
n1 = int(input('Escreva um valor: '))
n2 = int(input('E... |
9b181dfb65a843fe5b12ee729a0fce9495c37eca | Leonardo-S95/python-curso-em-video | /exercicios/desafio034-aula10.py | 923 | 4.15625 | 4 | '''
DESAFIO 034
Escreva um programa que pergunte o salário de um funcionário e calcule o valor de seu aumento.
Para salários superiores a R$1.250,00, calcule um aumento de 10%.
Para os inferiores ou iguais, o aumento é de 15%.
'''
print('\t\tVENHA RECEBER UM AUMENTO DO NADA!!')
sal = float(input(... |
1f1b79e00a03d032004e7d4659cb06769c39327e | Leonardo-S95/python-curso-em-video | /aulas/aula11-cores-no-terminal.py | 1,456 | 3.78125 | 4 | #Primeiro código(style) é o estilo(negrito, itálico..),
#segundo código(text) é da cor do texto, terceiro código(back) é da cor do fundo.
#Códigos Style que funcionam melhor no Python -> 0(none), 1(Bold), 4(Underline, 7(Negative)
#Códigos Text -> 30(bra... |
da79cb697efb75a8f9a762e87919dfecef74136f | Leonardo-S95/python-curso-em-video | /exercicios/desafio006-aula07.py | 1,389 | 4.09375 | 4 | '''
DESAFIO 006
Crie um algoritmo que leia um número e mostre o seu dobre, tripo e raiz quadrada.
'''
n1 = int(input('Digite um número aqui: '))
d = n1 * 2
t = n1 * 3
r = n1 ** (1/2)
color = {'boldazul': '\033[1;34m',
'boldbranco': '\033[1;30m',
'limpa': '\033[m'}
print(... |
1dbe23e878c79a0f61648b1c0bbd6a54a29ee49d | Leonardo-S95/python-curso-em-video | /exercicios/desafio041-aula12.py | 1,325 | 4.15625 | 4 | '''
DESAFIO 041
A Confederação Nacional de Natação precisa de um programa que leia o ano de nascimento de um atleta e mostre sua
categoria, de acordo com a idade:
- Até 9 anos: MIRIM
- Até 14 anos: INFANTIL
- Até 19 anos: JUNIOR
- Até 25 anos: SÊNIOR
- Acima: MASTER
'''
from datetime import date... |
eaab347fcb0cf210726b3227471fd94086d0b5ee | Leonardo-S95/python-curso-em-video | /exercicios/desafio079-aula17.py | 701 | 4.34375 | 4 | '''
DESAFIO 079
Crie um programa onde o usuário possa digitar vários valores numéricos e cadastre-os em uma lista. Caso o número já exista
lá dentro, ele não será adicionado. No final, serão exibidos todos os valores únicos digitados, em ordem crescente.
'''
continuar = 'S'
cont = 1
lista = []
w... |
03620d1c5deb34e3b7f712b6039eedcb715194fa | Rubbic/Python | /Unidad05/Ejercicios.py | 704 | 3.875 | 4 | """def area(b, h):
global a
a = b*h
return a
b = int(input("Igresa la medida de la base de un rectangulo\t"))
h = int(input("Ingresa la medida de la altura del rectangulo\t"))
area(b,h)
print(a)"""
"""
def relacion(c,d):
if c < d:
print(-1)
elif c == d:
print(0)
... |
00f77eb6147b49a2298aa21cf300c4112dbb57f6 | Rubbic/Python | /Unidad04/Pilas.py | 199 | 3.625 | 4 | pila = [3,4,5]
pila.append(6)
pila.append(7)
print(pila)
print(pila.pop())
print(pila)
numero = pila.pop()
print(numero)
print(pila)
pila.pop()
pila.pop()
pila.pop()
print(pila) |
5305059749484f1561bd68efee415480782404b9 | Rubbic/Python | /Unidad06/Ejercicios.py | 1,176 | 3.78125 | 4 | def area(b, h):
global a
a = b*h
return a
b = int(input("Igresa la medida de la base de un rectangulo\t"))
h = int(input("Ingresa la medida de la altura del rectangulo\t"))
area(b,h)
print(a)
def relacion(c,d):
if c < d:
print(-1)
elif c == d:
print(0)
else:... |
36eddabf70b5f9938353f3c6da17dc5c4df430a6 | Rubbic/Python | /Unidad07/Manejo de excepciones.py | 800 | 3.984375 | 4 | try:
resultado = 10/0
except ZeroDivisionError:
print("La division entre 0 no esta definida, ingresa un numero distinto a 0")
lista=[1, 2, 3, 4, 5]
try:
lista[10]
except IndexError:
print("Estas buscando un elemento en fuera del rango de la lista\
solo tienes 5 elementos recuerda que... |
90b17e2825b16eb92c91b69343bc47fc4a50383a | OnurSevket/Learning-Python | /First_Time.py | 3,937 | 3.984375 | 4 | #print("Hello World.Its Run")
# region Exercise 1
# x = 1
# if x == 1:
# print("x is 1")
# endregion
# region Exercise 2
# myint=8
# print(myint)
# endregion
# region Exercise 3
# myfloat=0.7
# print(myfloat)
# myfloat=float(7)
# print(myfloat)
# endregion
# region Exercise 4
# mystring='hello'
# print(m... |
f10f790a0f886a620c3f35254f87b3c10a3d60eb | BreakINbaDs/Algorithm_project | /other.py | 233 | 3.5625 | 4 | import networkx as nx
def get_graph(file):
g = nx.Graph()
f = open(file,'r')
for line in f.readlines():
x,y = line.split()
g.add_edge(x,y)
return g
g = get_graph('graph.txt')
print(nx.clustering(g)) |
d53ce0e05c6e2b4920f33d4ffd8e13d8c8c9ddff | mkovar52/kata | /kata.py | 1,386 | 4.09375 | 4 | # #############
# ===== Kata exercises =====
# #############
# #############
# Take in a number and return that number
# as a list in reversed order
# #############
def digitize(n):
# num_str = str(n)
# num_split = num_str.split()
n = [int(x) for x in str(n)]
n.reverse()
# digitize(1234)
# #######... |
1f8fd2d5bdaa8920fd04ef9f1eff3d0ef6d2659c | andlgr/python-tutorial | /src/general/threads.py | 392 | 3.671875 | 4 | # Learning Python 101
import threading
from utils import *
def run(upto):
for i in range(0, upto):
printf("[" + str(threading.get_ident()) + "] " + str(i) + "\n")
def main():
t1 = threading.Thread(target=run, args=(35,))
t2 = threading.Thread(target=run, args=(20,))
t1.start()
t2.start... |
b85d836e901de56dc6740d52b4c71f7d9a86611d | renatismos/LP2_AC04 | /faltaapenasapartedeBruno.py | 7,976 | 3.71875 | 4 | class Pessoa:
def __init__(self, nome, cpf, dataNascimento):
self.nome = nome
self.cpf = cpf
self.dataNascimento = dataNascimento
class Aluno(Pessoa):
def __init__(self, nome, cpf, dataNascimento, endereco, telefone, cadastrado = True):
self.nome = nome
se... |
26273ab3360e7cfc856edf23e541ecc7212f194a | pranavanand24/Data-Structures-and-Algorithms-in-Python | /Recursion/factorial.py | 215 | 3.953125 | 4 | def factorial(n):
assert n>=0 and int(n) ==n, 'the number must be positive integer only!'
if n in [0,1]:
return 1
else:
return n * factorial(n-1)
print(factorial(6))
|
21322cf394a9b441f17de8a3958fcfe3939a6ba3 | pranavanand24/Data-Structures-and-Algorithms-in-Python | /Recursion/sum of digits.py | 228 | 3.6875 | 4 | def sumofdigits(n):
assert n >= 0 and int(n) == n, 'the number has to be positive integer only!'
if n == 0:
return 0
else:
return int(n%10) + sumofdigits(int(n/10))
print(sumofdigits(729)) |
6620b15fc8ab5a81e71c3a759321bdd1dba2a005 | pranavanand24/Data-Structures-and-Algorithms-in-Python | /Array/Traversal in Array.py | 201 | 3.890625 | 4 | from array import *
arr1 = array('i', [1,2,3,4,5,6])
def tarverseArray(array):
for i in array:
print(i)
tarverseArray(arr1)
# Time Complexity: O(n)
# Space Complexity: O(1) |
995b287b036668787a74a46da4c0fb4a43e9be99 | pranavanand24/Data-Structures-and-Algorithms-in-Python | /Array/Searching in 2D Array.py | 528 | 4.15625 | 4 | import numpy as np
twoDArray = np.array([[11,15,10,6],[10,14,11,5],[12,17,12,8],[15,18,14,9]])
def searchTDarray(array,value):
for i in range(len(array)):
for j in range(len(array)):
if array[i][j] == value:
return 'the value is located at index'+" "+str(i)+" "+str(j)
... |
1d3dc7627824de7f8a3eb1b031d06c75c6d675d1 | john820911/practice | /python/ch7/ch7.py | 1,407 | 4.0625 | 4 | #1. str v.s repr
s = "This is a string!!\n"
x = 1.0/7.0
print str(s) #This is a string!!
print repr(s) #"This is a string!!\n"
print str(x) #round
print repr(x) #detailed
#comment: str() for string, repr() for numeric
#2. str.ljust(), str.rjust(), str.center(), str.zfill(), str.format()
for x in range(1, 11, 1):
prin... |
d50002c92681edf546b0ae94cba5b5399071f0d0 | willhyper/blockchain | /blockchain.py | 789 | 3.546875 | 4 | import hashlib as hasher
from collections import deque
class Block:
def __init__(self, data: str, previous_hash: str):
self.data = data
self.previous_hash = previous_hash
@property
def hash(self) -> str:
hashable = self.data + self.previous_hash
sha = hasher.sha256()
... |
2f0f8d0f988d31cd82b06ae3ede2020b431aa70f | M-alio-n/AdventOfCode-2020 | /Day 4/Day4-2.py | 3,554 | 3.734375 | 4 | import numpy as np
import re
# import the xor operator
from operator import xor
# Define a function that will check if all passport entries in a string are correct
def check_validity(string):
# initialize an array of required substrings
substrings = ["byr", "iyr", "eyr", "hgt", "hcl", "ecl", "pid"]
e... |
e22aa28bf6fb3df7c99ade648faa0daef39c7eb9 | rg3915/api_crawler_challenge | /myproject/core/crawler.py | 706 | 3.671875 | 4 | import re
import requests
def contains_http(url):
''' Checks if url contains http or https. '''
STARTS_WITH_HTTP_OR_HTTPS = re.compile(r'(https?:\/\/[^\s]+)')
return 'http://' + url if not STARTS_WITH_HTTP_OR_HTTPS.match(url) else url
def get_text_content(url):
"""Retrieves the page text content given... |
65a6cb83d6f4bc4d176216be394b0261bee4a90e | Chirag-Mathur/hello-world | /Problem on sticks.py | 1,791 | 3.953125 | 4 | # On a sunny day, Akbar and Birbal were taking a leisurely walk in palace gardens. Suddenly, Akbar noticed a bunch of sticks on the ground and decided to test Birbal's wits.
# There are N stick holders with negligible size (numbered 1 through N) in a row on the ground. Akbar places all the sticks in them vertically; f... |
f5b15adaaec1468942c89c082f3594fd9c75af0f | JasonKarle/Learning_TKinter | /02_SimpleCalc_w_GUI.py | 3,325 | 4.25 | 4 | """
This is a very simple calculator with a simple GUI
that allows the user to add, subtract, multiple, and
divide. Based on the example from the YouTube course
"How to create Game: Python GUI 101 with TKiner Complete TUTORIAL"
https://www.youtube.com/watch?v=whErCLh0-QU
You can ONLY do one calculation at a... |
5991e1729f731ae75deb31fc76a42bb3183397a9 | anoopbhatn/Perceptrons | /xor1.py | 1,054 | 3.5 | 4 | # Backpropagation algorithm implementation for XOR
import numpy as np, matplotlib.pyplot as plt
import random
def sigmoid(z):
return 1.0 / (1.0 + np.exp(-z))
def compute_res(x, y, W1, W2, b1, b2):
z1 = np.dot(x, W1.T) + b1
x1 = sigmoid(z1)
z2 = np.dot(x1, W2.T) + b2
x2 = sigmoid(z2)
error = x2 - y
Ed = 0.5 * ... |
23efc1dc9a8d117b67e5aaee1de6cf23970a00f7 | afressancourt/iGraph-tutorial | /shortest_path.py | 989 | 3.625 | 4 | import time
from igraph import *
from random import randint
# We show how to find shortest paths ...
# Erdos Renyi undirected graph...
g_und = Graph.Erdos_Renyi(40000, 0.05, directed=False, loops=False)
print summary(g_und)
# Erdos Renyi directed graph...
g_dir = Graph.Erdos_Renyi(40000, 0.05, directed=True, loops=F... |
0222ca59469af703b2a00def3ad49403ed286669 | afressancourt/iGraph-tutorial | /node_addition.py | 596 | 3.671875 | 4 | from igraph import *
import time
# Let's look at graph creation tricks...
# We create a list with vertices
mylist = list(xrange(100000))
# Now, let's compare time to add vertices to graphs
g1 = Graph()
g2 = Graph()
# Adding vertices one by one...
start_time = time.time()
for i in mylist:
g1.add_vertex(id=i)
end... |
08c188328dbdb73449cb1fc073378eb834273cfe | dereklavigne18/adventofcode | /advent2019/questions/program_alarm.py | 2,682 | 3.5 | 4 | from typing import List, Optional, Tuple
ADD_OPCODE = 1
MULT_OPCODE = 2
EXIT_OPCODE = 99
OPERATION_LENGTH = 4
def execute_intcode(intcode: List[int]) -> List[int]:
resulting_intcode = intcode.copy()
current_position = 0
while current_position < len(resulting_intcode):
opcode = r... |
5578a5ec590fcce35f39735231bff3879498614a | dereklavigne18/adventofcode | /advent2020/questions/report_repair.py | 1,448 | 3.890625 | 4 | from argparse import ArgumentParser
from itertools import combinations
from math import prod
from typing import List, Optional, Tuple
INPUT_FILE_PATH = "/app/advent2020/inputs/report_repair.txt"
def find_vals_summing_to_target(vals: List[int], addend_count: int, target: int) -> Optional[List[int]]:
va... |
fc1aeb52b6418e3e6399d867a432856649e13efa | dereklavigne18/adventofcode | /advent2019/questions/tyranny_of_rocket_equation.py | 1,588 | 4.125 | 4 | from typing import List
def calculate_fuel_for_module_mass(module_mass: int) -> int:
fuel = (module_mass // 3) - 2
return max([fuel, 0])
def calculate_cumulative_fuel_needed_for_module_masses(module_masses: List[int]) -> int:
return sum([calculate_fuel_for_module_mass(module_mass) for module_ma... |
055c2db19a5ddb47a152e3e93a4ec3d595e32b24 | nagendrabl/uda_py_code | /inheritance.py | 416 | 3.84375 | 4 | class Parent():
def __init__(self,last_name,eye_color):
self.last_name = last_name
self.eye_color = eye_color
class Child(Parent):
def __init__(self,last_name,eye_color,number_of_toys):
Parent.__init__(self,last_name,eye_color)
self.number_of_toys = number_of_toys
mile... |
e731bd285f4a55bfa1a4653d50db8413e62b10ed | smoodydev/pythonKerry | /recurrsion.py | 273 | 3.953125 | 4 | y = ["a", "b", "c"]
def recurrsion_loop(y):
if len(y) > 0:
print(y[len(y)-1])
y = y[0:-1]
recurrsion_loop(y)
def f_e_loop():
for x in y:
print(x)
def not_recurssion():
print("hello")
not_recurssion()
recurrsion_loop(y) |
0206d3b11fbaa640614b10002970e173718ce7fa | matteocanegallo/Rosalind | /16-BINS.py | 587 | 3.765625 | 4 | def Binary_search(Array, item):
low = 0
high = len(Array)-1
while low <= high:
index = (low + high) // 2
if item == Array[index]:
return index + 1
elif item > Array[index]:
low = index + 1
else:
high = index - 1
return -1
with open('Ro... |
8c77bd49f9814da8be9c0a3da39050853a3b80de | matteocanegallo/Rosalind | /09-PERM.py | 237 | 3.671875 | 4 | from itertools import permutations
def permutation(n):
count = 0
number = list(permutations(range(1, n + 1)))
for i in number:
count += 1
print(count)
for i in number:
print(' '.join(map(str, i))) |
913734e2efb51cfa56bbd67036a55d8083e8492e | Jon-Burr/memoclass | /tests/test_mutates_with.py | 1,422 | 3.828125 | 4 | """ Tests for the 'mutates with' approach """
from memoclass.memoize import memomethod
from memoclass.memoclass import MemoClass
class Provider(MemoClass):
def __init__(self, value):
self.receiver = None
self.value = value
super(Provider, self).__init__()
def mutates_with_this(self):
... |
be3f5dd1a8682c4e7311e386cc49b87261be7a7e | SebasAren/smarter_grid | /src/visualizations/visualization.py | 2,702 | 3.53125 | 4 | # We do not use this file anymore, it was
# really helpful to use this plot in an earlier
# stage of the case.
#
# import right files
from data_structure import Battery, House
import data_generator
import numpy as np
import sys
import matplotlib.pyplot as plt
import csv
class Visualization(object):
def read... |
04e3cd7b2794eab29387abc1937286edf44a2701 | DZlearnscode/Graph-Search-Visualiser | /graph search Visualiser/search.py | 6,765 | 3.734375 | 4 | from math import sqrt
from min_heap import Heap
from random import randint
import sys
import datetime
import time
# increasing recursion limit
sys.setrecursionlimit(5000)
class Search():
def __init__(self, grid):
self.grid = grid
self.heap = Heap()
def heuristic(self, current, target):
... |
4af49d9c1cef3288f06bfb2f3b3ac3ad2715c6f5 | zaleskasylwia/RPG-hero | /hero.py | 979 | 3.703125 | 4 | from character import Character
from inventory import Inventory
class Hero:
def __init__(self, first_name, last_name, race):
if type(first_name) is str and type(last_name) is str and type(race) is str:
self.character = Character(first_name, last_name, race)
self.inventory = Invento... |
036287cd8712d6f8d32edc47aa871b252ea44f53 | Florence-TC/Numeric_Matrix_Processor | /Numeric Matrix Processor/task/processor/processor.py | 6,812 | 3.921875 | 4 | import copy
import math
class Matrix:
def __init__(self, row_number, column_number, rows):
self.row_number = row_number
self.column_number = column_number
self.rows = rows
self.columns = []
for i in range(self.column_number):
self.columns.append([self.rows[j][... |
d4378e77f645a3cef75ac335e55d718fd81d3a95 | Fearonyx/Lessons | /classes.py | 832 | 3.65625 | 4 | class Car:
pass
c = Car()
print(c, type(c))
class Room:
number = 'Room 34'
floor = 4
r = Room()
r1 = Room()
print(r.number, r1.number)
print(r.floor, r1.floor)
r.number = 12
r.floor = '5 floor'
print(r.number, r1.number)
print(r.floor, r1.floor)
class Door:
def open(self):
print('self is ', self)
prin... |
c4d6ecae0e00366447562816b72c1d418720f508 | JayDijkstra/signal-data-k-nearest-neighboor | /k-neighbors.py | 2,865 | 4.03125 | 4 | import csv
import random
import math
import operator
'''
In this Function there a similarity to K-Nearest Neighbour is created in Python only.
This function is to classify a signal of a potential Trend. This trend excists of similar values.
The objects seen in this example are different Integer. These integers stand ... |
e455ad08246edeedfb9e7efdbcf8abd71e84a664 | ayush-oberoi/My-DS-Problems | /Arrays/FindDuplicates.py | 566 | 3.875 | 4 | #Find duplicates of an array without set with hash table
#o(n)
def FindDuplicate(MyArray):
l = []
MyDictionary = dict()
for i in MyArray:
if i not in MyDictionary:
MyDictionary[i] = 0
l.append(str(i))
else:
MyDictionary[i] += 1
return ' '.join(l)
#Find duplicates of an array w... |
eb9dceb318eae7d233303018d5a550d76a51cfc4 | richnakasato/fc | /4.rearrange_linked_list_in_pairs.1.py | 804 | 3.734375 | 4 | from collections import deque
class SinglyLinkedList:
#constructor
def __init__(self):
self.head = None
#method for setting the head of the Linked List
def setHead(self,head):
self.head = head
def arrange_in_pairs(self):
if self.head:
queue = deque()
... |
73a52183d8899cef57bb77292423c5be25187437 | richnakasato/fc | /repeated_elements_in_array.py | 291 | 3.75 | 4 | def duplicate_items(list_numbers):
memo = dict()
for item in list_numbers:
if item not in memo:
memo[item] = 1
else:
memo[item] += 1
dupe = list()
for k, v in memo.items():
if v > 1:
dupe.append(k)
return dupe
|
96c517a73c631aafdce718507539a22d95b8559c | richnakasato/fc | /iterative_inorder_traversal.py | 915 | 3.703125 | 4 | class BinaryTree:
def __init__(self, root_data):
self.data = root_data
self.left_child = None
self.right_child = None
def inorder_iterative(self):
inorder_list = []
stack = list()
done = False
curr = self
while not done:
if curr:
... |
997ed6a3a4bae8044d1079a661338e9356ba7e1f | richnakasato/fc | /3.find_the_nth_from_the_end_node_in_a_list.0.py | 782 | 3.8125 | 4 | class SinglyLinkedList:
#constructor
def __init__(self):
self.head = None
#method for setting the head of the Linked List
def setHead(self,head):
self.head = head
def find_nth_node_from_end(self, n):
# potential better way is to iterate n times, then do double
# poi... |
a564b040edaa07aae0a8ee6191633a3904077349 | richnakasato/fc | /rotate_linear_array.py | 701 | 3.765625 | 4 | def rotate_left(list_numbers, k):
n = len(list_numbers)
shift = n-k
res = [None] * n
for idx, num in enumerate(list_numbers):
res[(idx+shift)%n] = list_numbers[idx]
return res
def rotate_left2(list_numbers, k):
n = len(list_numbers)
count = 0
dst = 0
src = (dst+k)%n
temp... |
5bd5250231343db6e1adf0916f52f9fc625d78b2 | richnakasato/fc | /4.triple_sum.0.py | 903 | 3.90625 | 4 | '''
First attempt, but this is wrong, looks like I should have used a sliding window
'''
def double_sum(arr, target, skip_idx):
memo = set()
for idx, val in enumerate(arr):
if idx != skip_idx:
sub_target = target-val
if sub_target not in memo:
memo.add(val)
... |
144ac7754b148f990231f47d55470e82432ee648 | richnakasato/fc | /find_the_kth_smallest_node_in_a_bst.py | 1,002 | 3.6875 | 4 | class BinaryTree:
def __init__(self, root_node = None):
# Check out Use Me section to find out Node Structure
self.root = root_node
# Helper Method
def size(self, root):
if root == None:
return 0
else:
return (self.size(root.left_child) + 1 + self.si... |
bf4e0a40e8ffadda363e352b004670ab52e376e7 | aclyde11/L5 | /goods.py | 930 | 4 | 4 | class Item:
'''
This class encapsulates a itemname in our store
'''
def __init__(self, name, price, quantity = 1):
self.name = name
self.quantity = quantity
self.price = price
'''
This function decrements the quantity in stock. If qty is greater than the quanity in stoc... |
c82184dfd32ff3c0f0d4a0f4e0b2310e6d51694d | chanshukwong/Sudoku-Mutator | /Mutator.py | 1,806 | 3.578125 | 4 | # Given a sudoku, create a new sudoku from it
import numpy as np
from numpy import genfromtxt
import random
def swap_row(pz:[], rows:tuple):
row1, row2 = rows
pz[[row1,row2],:] = pz[[row2,row1],:]
def swap_col(pz:[], cols:tuple):
col1, col2 = cols
pz[:,[col1,col2]] = pz[:,[col2,col1]]
def swap_blocks(pz:[], left... |
2cdc157a2ee39730add5a7a572640d802b8e37b5 | mdabdulbari/python | /ex43-again.py | 1,916 | 3.796875 | 4 | from random import randint
class Scene(object):
def enter(self):
print("Should not have been called.")
print("Subclass it and implement enter")
exit(0)
class CentralCorridor(Scene):
def enter(self):
print("Welcome to Gothons.")
joke = input("> ")
if joke != "tell... |
56045e9576fef7a80170b2eec46a919b79774bf2 | mdabdulbari/python | /projects/ex48/ex48/lexicon.py | 405 | 3.859375 | 4 |
direction = ["north", "south", "east", "west",
"down", "up", "left", "right", "back"]
verb = ["go", "stop", "kill", "eat"]
stop_words = ["the", "in", "of", "from", "at", "it"]
nouns = ["door", "bear", "princess", "cabinet"]
numbers = []
def scan(stuff):
word_list = []
words = stuff.split()
... |
0954ea8acd582c4f9cbad76f37ff803cb2bcb5b1 | mdabdulbari/python | /ex39real.py | 1,626 | 4.40625 | 4 | # create a mapping of state to abbreviation
states = {
'Telangana' : 'TG',
'Andhra Pradesh' : 'AP',
'Maharashtra' : 'MH',
'Uttar Pradesh' : 'UP',
'Jammu & Kashmir' : 'JK'
}
# create a basic set of states and some cities in them
cities = {
'TG' : 'Hyderabad',
'AP' : 'Amaravati',
'MH' : '... |
d43fddd4667b808abe68223bdfc0d46a87f9a846 | mdabdulbari/python | /ex39sample.py | 165 | 3.640625 | 4 | stuff = {'name': 'Bari', 'age': 21, 'height': 5 * 12 + 6}
print(stuff['name'])
print(stuff['age'])
print(stuff['height'])
stuff['city'] = "HYD"
print(stuff['city'])
|
17c5c8ddc6c0635b256734281f04999644ef1e20 | Hocnonsense/Python | /回溯法/生成所有子序列.py | 1,153 | 3.65625 | 4 | '''
在这里, 我们希望给出输入序列的所有子序列
使用回溯法
时间复杂度: O(2^n),
n还是输入序列的长度.
'''
def 生成所有子序列(序列):
结果 = list()
create_state_space_tree(序列, 0)
def create_state_space_tree(序列, 已用元素数, 当前序列 = list()):
'''
创建一个状态空间树,使用DFS遍历每个分支。
我们知道每个状态只有两个孩子(可能)。
index决定什么时候终止。
'''
if 已用元素数 == ... |
5ec7710e1a0e8863a93a941f5dc8907cad32abe4 | Hocnonsense/Python | /data_structures/binary_tree/lca.py | 2,688 | 3.84375 | 4 | import queue
def swap(a, b):
a ^= b
b ^= a
a ^= b
return a, b
def bfs(graph, max_node, root=1):
"""
从树的根节点运行宽度优先搜索。
parent: 设置每个节点的直接父节点。
根节点的父节点设置为0。
level: 计算每个节点从根节点开始的深度
"""
level = [-1 for _ in range(max_node + 1)] # initializing with -1 which means ev... |
f82917c220a48551d550c82d56227f603693d16c | Hocnonsense/Python | /算术代数分析/LU分解.py | 1,403 | 3.875 | 4 | """
在线性代数中, LU分解(LU Decomposition)是矩阵分解的一种,可以将一个矩阵分解为一个单位下三角矩阵和一个上三角矩阵的乘积(有时是它们和一个置换矩阵的乘积)。LU分解主要应用在数值分析中,用来解线性方程、求反矩阵或计算行列式。
菜鸡表示没读懂, 而且结果好像也不太对
"""
# lower–upper (LU) decomposition - https://en.wikipedia.org/wiki/LU_decomposition
import numpy
def LU分解(矩阵):
"""
矩阵: 必须是 n阶
"""
行, 列 = num... |
03c60fb1819661267f205b037be61adffd33ad29 | Hocnonsense/Python | /data_structures/binary_tree/red_black_tree.py | 27,677 | 3.703125 | 4 | """
python/black : true
flake8 : passed
规则:
1) 每个结点要么是红的, 要么是黑的
2) 根结点是黑的
3) 每个叶结点都是空结点 (NIL),且都是黑的
4) 如果一个结点是红的, 那么它的俩个儿子都是黑的
5) 对每个结点, 从该结点到其子孙结点的所有路径上包含相同数目的黑结点
"""
global check
check = False
class RedBlackTree:
"""
红黑树,是一种自平衡的BST(binary search tree, 二叉搜索树)。
此树具有与AVL树相似的性... |
113136e9bbc76fc938bbb7667376aecbdf86be0f | Hocnonsense/Python | /回溯法/生成定值子集.py | 1,485 | 4.0625 | 4 | '''
子集合和问题表示一组非负整数,和一个给定值,
确定给定集合的所有可能子集,它们的和等于给定值。
所选数字的和必须等于给定的数字M,并且一个数字只能使用一次。
'''
def 生成定值子集(集合: list, 给定值: int):
结果, 子集 = list(), list()
当前元素 = 0
__生成定值子集(集合, 给定值, 当前元素, 子集, 结果)
return 结果
def __生成定值子集(集合, 给定值, 当前元素, 子集, 结果 = list()):
'''
创建一个状态空间树,使用DFS遍历每个分支。
当下... |
d8cd2d792752180809f7f664e9b1a3d3c4ed54ff | emmatysinger/Cryptography | /cryptography.py | 2,018 | 3.90625 | 4 | """
cryptography.py
Author: Emma Tysinger
Credit: None
Assignment:
Write and submit a program that encrypts and decrypts user data.
See the detailed requirements at https://github.com/HHS-IntroProgramming/Cryptography/blob/master/README.md
"""
associations = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ01234... |
e0cbc44bef71f1d4a330ecb1f1cc7e02ce2f3f5b | lggruspe/ibex | /python/tests/tools/lexeme.py | 2,368 | 3.671875 | 4 | import random
import examples
DIGITS = "0123456789"
@examples.instances
def empty():
return ''
@examples.instances
def number():
def integer():
n = random.randint(1, 9)
if n == 1:
return random.choice(DIGITS)
rv = random.choice(DIGITS[1:])
for i in range(1, n):
... |
15c862bacaaa6453a66489b64ab7988e7f0f0f0f | TecProg-20181/02--BRZangado | /hang.py | 3,243 | 3.890625 | 4 | import random
import string
WORDLIST_FILENAME = "palavras.txt"
def loadWord():
wordlist = createWordList()
randomWord = random.choice(wordlist).lower()
testedWord = checkNumberOfLetters(randomWord)
return testedWord
def createWordList():
"""
Depending on the size of the word list, this f... |
22be6ee92b718d56bc5dd933e22f12f7af63393d | sulavpanthi/TestingRepo | /complete-assignment2.py | 14,455 | 4.1875 | 4 | 1. Create a variable, paragraph, that has the following content:
"Python is a great language!", said Fred. "I don't ever remember
having this much fun before."
paragraph = f'"Python is a great language!", said Fred. "I don\'t ever remember having this much fun before."'
print(paragraph)
2. Write an if statement to... |
5b23efc598fd71ac41710761c6d2be997c7971a9 | maltindal/algorithms | /basics/eratos.py | 918 | 4.09375 | 4 | import matplotlib.pyplot as plt
class Primes:
# compute primes up to the number n where n > 2
def sieve(self, n):
if n < 2:
return []
else:
ns = range(2,n+1)
r = list(ns) # copy list ns
for n in ns:
for x in range(n+n, ns[-1]+... |
08f52740f5e2ed61833753f9bdf278f99beeb051 | varun-v2021/Python-ML | /indexing.py | 3,647 | 3.75 | 4 | import pandas as pd
import numpy as np
df = pd.DataFrame(np.random.randn(8, 4),
index=['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'], columns=['A', 'B', 'C', 'D'])
print('>>>>>><<<<<<<<<<<<<<')
training = np.array(df)
print('training data contents')
print(training)
print('-----------all rows of ... |
9b0ba5a462522684c2c2bf10f56507f8181a9518 | forrestjan/Labos-MCT-19-20 | /2019-prog-labooefeningen-forrestjan/week1/oefening6test.py | 665 | 3.59375 | 4 | #zelfoefening ik germaak oefening 6 zonder _ bij woorden voor te weten of het een verschil maakt buiten orde en netheid van de code
totaalseconde = int(input("Geef het aantal seconden op "))
aantalsec1dag = 24 * 60 * 60
aantaldagen = totaalseconde // aantalsec1dag
print(aantaldagen)
restseconde = totaalseconde % aa... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.