blob_id stringlengths 40 40 | repo_name stringlengths 5 127 | path stringlengths 2 523 | length_bytes int64 22 545k | score float64 3.5 5.34 | int_score int64 4 5 | text stringlengths 22 545k |
|---|---|---|---|---|---|---|
175641a5e00fd0b16bd20307674c7a00ec70bb6d | baduy9x/AlgorithmPractice | /nearest_clone.py | 2,003 | 3.703125 | 4 | #!/bin/python3
import math
import os
import random
import re
import sys
from collections import defaultdict, Counter, deque
# Complete the findShortest function below.
#
# For the weighted graph, <name>:
#
# 1. The number of nodes is <name>_nodes.
# 2. The number of edges is <name>_edges.
# 3. An edge exists between... |
27bb510bb917e5b0aaff7cf9eab91ed821082bff | baduy9x/AlgorithmPractice | /recursion.py | 541 | 3.53125 | 4 | #!/bin/python3
import math
import os
import random
import re
import sys
# Complete the stepPerms function below.
result = [0] * 36
result[0] = 1
result[1] = 2
result[2] = 4
for i in range(3, 36):
result[i] = result[i - 3] + result[i - 2] + result[i - 1]
def stepPerms(n):
return result[n - 1]
if __name__ ... |
4ecaa46387006f4a2989d4ea11f6d2fccfaf46d7 | baduy9x/AlgorithmPractice | /valid_soduku.py | 1,442 | 3.59375 | 4 | from collections import defaultdict
def check_dup(arr):
hash_map = defaultdict(int)
for i in arr:
hash_map[i] += 1
for item in hash_map:
if hash_map[item] > 1 and item != ".":
return True
return False
class Solution:
def isValidSudoku(self, board):
for i in ra... |
1a36432332636bb9a5b54efe452e5b7467b49fb8 | baduy9x/AlgorithmPractice | /validate_bst.py | 503 | 3.765625 | 4 | """ Node is defined as
class node:
def __init__(self, data):
self.data = data
self.left = None
self.right = None
"""
def check(root, MIN, MAX):
if root is None:
return True
if root.left is None and root.right is None:
if MIN < root.data < MAX:
return True... |
4949865d501f409427859d008c03237ca0c15379 | baduy9x/AlgorithmPractice | /palindrome2.py | 1,077 | 3.734375 | 4 | class Solution:
# def validPalindrome(self, s: str) -> bool:
# if s == "".join(reversed(s)):
# return True
# for i in range(len(s)):
# new_s = s[:i] + s[(i + 1):]
# if new_s == "".join(reversed(new_s)):
# return True
# return False... |
693798e442fbdf31c6f2adebfcaea777a0942ecb | baduy9x/AlgorithmPractice | /unnest_list.py | 438 | 3.78125 | 4 | def flatten_list(arr):
result = []
for item in arr:
if isinstance(item, list):
result.extend(flatten_list(item))
else:
result.append(item)
return result
def flatten_list(mapping):
for key in mapping:
if isinstance(mapping[key], dict):
value = ... |
3b3a2e25444c9ebc16da3d7654f60c757f67e0af | Peel-Park233/-LeetCode- | /Leetcode_str_chain_tree/shortestPalindrome.py | 576 | 3.65625 | 4 | # 题目描述:214. 最短回文串
# 给定一个字符串 s,你可以通过在字符串前面添加字符将其转换为回文串。
# 找到并返回可以用这种方式转换的最短回文串。
class Solution:
def shortestPalindrome(self, s: str) -> str:
if len(s) == 0:
return ''
ss = s[::-1]
length = len(s)
for i in range(length):
if ss[i:] == s[:length ... |
2d4e6b2b3c5f877689b87c618f9a19105814a513 | Peel-Park233/-LeetCode- | /Leetcode_str_chain_tree/130. 被围绕的区域.py | 835 | 3.59375 | 4 | class Solution:
def solve(self, board):
m = len(board)
n = len(board[0])
if m == 0 or n == 0:
return board
def dfs(i, j):
if i == 0 or i == m-1 or j == 0 or j == n-1:
return # 不做改变
# if board[i-1][j] != 'O' and board[i]... |
deff465c6dcf2e15e00576efb40be0871ff37a0f | Peel-Park233/-LeetCode- | /Leetcode_math_double/threeSum_2.py | 1,145 | 3.515625 | 4 | # 题目描述:
# 给定一个n个整数的数组nums和一个目标值target,找出数组中三个数,使它们的和与target最相近
# 返回他们的和
class Solution:
def threeSum(self, nums, target):
nums.sort()
ans = 0
minnum = 2**32 - 1
for i in range(len(nums) - 2):
# 双指针模板
j = i + 1 # 指向头
k = len(nu... |
15844b4e3e8cd3bae5584e586d506bc057927118 | Peel-Park233/-LeetCode- | /Leetcode_str_chain_tree/113. 路径总和 II.py | 672 | 3.5 | 4 | class Solution:
def pathSum(self, root, sum_1: int):
ans = []
if not root:
return ans
def dfs(root, temp):
if not root:
return
# print(temp)
if sum(temp) == sum_1 and not root.left and not root.right:
a... |
298530c0c90f55387aa4e35911fb8beb5e86d0dd | Peel-Park233/-LeetCode- | /Leetcode_math_double/209. 长度最小的子数组2.py | 1,027 | 3.5 | 4 | # 题目描述:
# 给定字符串 s 和 t ,判断 s 是否为 t 的子序列。
# 找出该数组中满足其和 ≥ s 的长度最小的 连续 子数组,并返回其长度。
# 如果不存在符合条件的子数组,返回 0。
class Solution:
def minSubArrayLen(self, s, nums):
if not nums:
return 0
if nums[0] >= s:
return 1
i = 0 # 头
j = 0 # 尾
minans = 2**31... |
b27756a450e42c349dbb44ba59f0e7c74d391905 | Peel-Park233/-LeetCode- | /Leetcode_math_double/392.判断子序列_2.py | 676 | 3.609375 | 4 | # 题目描述: 给定字符串 s 和 t ,判断 s 是否为 t 的子序列。
class Solution:
def isSubsequence(self, s, t):
i = 0
j = 0
while i < len(s) and j < len(t):
if s[i] == t[j]:
i += 1
j += 1
else:
j += 1
# 这一段可以简化为:return i==len(... |
8d78f177ff1e2a57e9ddc38030d69110460f1076 | Peel-Park233/-LeetCode- | /Leetcode_str_chain_tree/demo1017.py | 120 | 3.546875 | 4 | def solution_1017(nums):
return True if nums == nums[::-1] else False
nums = 'abbad'
print(solution_1017(nums))
|
1771605f9cace38978c664b6f9eb980e38cc610b | Peel-Park233/-LeetCode- | /Leetcode_math_double/剑指 Offer 14- I. 剪绳子.py | 829 | 3.71875 | 4 | # 题目描述: 给你一根长度为 n 的绳子,请把绳子剪成整数长度的 m 段(m、n都是整数,n>1并且m>1)
# 每段绳子的长度记为 k[0],k[1]...k[m-1] 。请问 k[0]*k[1]*...*k[m-1] 可能的最大乘积是多少?
class Solution:
def cuttingRope(self, n):
if n == 2:
return 1
if n == 3:
return 2
times = n // 3
other = n % 3
if ... |
a8473e009243a9b9894765768c05134abd985cf4 | lijz36/2048 | /2048.py | 981 | 3.640625 | 4 |
"""2048主程序"""
import m_2048 as T
import sys
import os
def show_input():
while True:
action = input("Move:")
if action == 'A' or action == "a":
os.system('clear')
print("左移<<<")
T.F_LeftMove()
elif action == 'D' or action == "d":
os.system('... |
57fff789ebe7c107ad260275d117cd06c9538380 | AjengWidya/DQLab_Coding | /python-for-data-professional-beginner/python-basic1.py | 4,050 | 4.4375 | 4 | # These are statements
print("Learning Python is fun!")
print("Hello, world!")
# Variables & literals
number1 = 5
number2 = 10
sentence1 = "Learning Python programming language"
# Operator
print(number1 + number2)
'''
This is multi line comments
We will make a simple program to calculate a total price
'''
init_price... |
be9520c3cd336c0118118995e6407534e53c10e6 | tractorboy1/Project-Euler-Solutions | /p048.py | 273 | 3.78125 | 4 |
class NumberToTheNumber():
def __init__(self, number):
self.value = number ** number
total = 0
for n in range(1000):
if n % 10 == 0:
pass
else:
item = NumberToTheNumber(n)
total += item.value
print(total % 10 ** 10) |
d06b0cc78b4beaf7a6250402b86879c867311692 | DeepakumarDK1998/python_first | /zero.py | 155 | 4.09375 | 4 | a=int(input("Enter 1st Number:"));
if a>0:
print("The number is positive");
elif a<0:
print("Number is negative");
else:
print("zero");
|
44a684866ad146d3ef9cbc1181a7628ba4de2237 | DeepakumarDK1998/python_first | /sum_looping.py | 151 | 4.1875 | 4 | a=int(input("Enter Number upto which you want to sum:"))
b=1
sum=0
while (b<=a):
sum=sum+(a*a*a*a*a*a*a*a)
b=b+1
print("sum=",sum);
|
53490c2c6e9feba29d73cb1024895eda79298a2e | rollbackzero/projects | /ex30.py | 458 | 4.1875 | 4 | people = 40
cars = 30
trucks = 45
if cars > people:
print("We should take cars")
elif cars < people:
print("We should not take cars")
else:
print("We can't decide")
if trucks > cars:
print("Thats too many trucks")
elif trucks < cars:
print("Maybe we could take the trucks")
else:
print("We sti... |
18dc35789b8dfb352fb3af34c216e5edb9780fdc | rollbackzero/projects | /ex19b.py | 701 | 3.96875 | 4 | from sys import argv
cheese = input(f"How many cheese: ")
crackers = input(f"How many crackers: ")
def cheese_and_crackers(cheese_count, boxes_of_crackers):
print(f"You have {cheese_count} cheeses!")
print(f"You have {boxes_of_crackers} boxes of crackers!")
print("Man that's not enough for a party!")
... |
9d1c41a44f82d25ab5e0e05bbc9faa052d242b39 | VibhorSingh19/python | /filehanling.py | 1,111 | 3.5 | 4 | #first
'''
file = open('file.txt', 'w')
L = ["Name:Vibhor \n", "Age:20\n", "Class:12 \n", "Month:4 \n", "Year:2020 \n"]
file.writelines(L)
file.close()
print("Added successfully!")
'''
#secound
'''
file1 = open('file.txt', 'r')
print(file1.read())
file1.close()
'''
#third
'''
file2 = open('file1.txt', 'a')
s ... |
009d63fffab9020cf7c8ebc4b9deec98b0f656a9 | UVvirus/frequency-analysis | /frequency analysis.py | 1,099 | 4.4375 | 4 | from collections import Counter
non_letters=["1","2","3","4","5","6","7","8","9","0",":",";"," ","/n",".",","]
key_phrase_1=input("Enter the phrase:").lower()
#Removing non letters from phrase
for non_letters in non_letters:
key_phrase_1=key_phrase_1.replace(non_letters,'')
total_occurences=len(key_phrase_1)
#Co... |
fbc47f7cdab276ae90534052b871bfdaf4389b65 | SIVAPRASATH101/GUVI-CODING | /player/set1/swap even and odd char.py | 104 | 3.640625 | 4 | z=list(input())
for i in range(0,len(z)-1,2) :
z[i],z[i+1]=z[i+1],z[i]
for i in z :
print(i,end="")
|
3de2b9b22e696acc09247407702a7927d5076f4f | SIVAPRASATH101/GUVI-CODING | /test9/hcf.py | 145 | 3.546875 | 4 | y,z=input().split()
y=int(y)
z=int(z)
if y>z :
s=z
else :
s=y
hcf2=1
for i in range(1,s+1) :
if i%y==0 and i%z==0 :
hcf2=i
print(hcf2)
|
ff845c0d427f18b9c0cfb15e6c2b1edde551d650 | joaquincoitino/python_group2 | /DataInput.py | 3,072 | 4.03125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sun Oct 9 16:28:02 2016
@author: lukaswolff
"""
import csv
import numpy as np
import Stock as st
import Correlations as c
import Stock_List as stl
def readCSVIntoList(name):
"""
Reads in a csv file and returns the rows as a list. This method is used
for the func... |
2f5a995206f4e37c8374ef6b1f9e058c9a624afc | joaquincoitino/python_group2 | /Stock.py | 3,698 | 3.828125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sun Oct 9 14:29:45 2016
@author: lukaswolff
"""
import numpy as np
import math
class Stock():
def __init__(self, name, price_list, sector, symbol):
"""
Constructor function for our stock class to initialize name, list with
the price changes, ... |
eb276fbe4f75fe8d3ae576af3f2c93dcbfb70dbc | guilhermemaas/guanabara-pythonworlds | /exercicios/ex062vG.py | 620 | 4.03125 | 4 | """
Melhore o exercicio 61, perguntando ao usuario se ele quer mostrar mais alguns termos.
O programa encerra quando ele disser que quer mostrar 0 termos.
"""
###Guanabara
from time import sleep
print('Gerador de PA')
print('-='*10)
primeiro = int(input('Primeiro termo: '))
razao = int(input('Razao da PA: '))
termo = ... |
5845f21ac973ca16b7109f843771c0490633c8fc | guilhermemaas/guanabara-pythonworlds | /exercicios/ex022.py | 1,124 | 4.34375 | 4 | """
Crie um programa que leia o nome completo de uma pessoa e mostre:
O nome com todas as letras maiusculas
O nome com todas as letras minusculas
Quantas letras ao todo sem considerar espacos
Quantas letras tem o primeiro nome
"""
nome_completo = input('Digite seu nome completo: ').strip() #Pra pegar ja sem espacos no... |
cd9a02b5f30f7b1d317d93deb405930f7e7b465d | guilhermemaas/guanabara-pythonworlds | /exercicios/ex010.py | 399 | 4.0625 | 4 | """
Crie um programa que leia quanto dinheiro a pessoa tem na carteira, e mostre quantos dolares ela pode comprar.
"""
carteira = float(input('Digite o valor atual em sua carteira: R$'))
dolar = 3.77
print('Voce possui R${:.2f}. Com isso voce pode comprar ${:.2f}.'.format(carteira, carteira / dolar))
print('Voce poss... |
4d1618885dfc9fc489bbf6bd9df11221e81ea623 | guilhermemaas/guanabara-pythonworlds | /exercicios/ex015.py | 525 | 4.0625 | 4 | """
Escreva um programa que pergunte a quantidade de km percorridos por um carro alugado
e a quantidade de dias pelos quais foi alugado. Calcule o preco a pagar,
sabendo que o carro custa R$60 por dia e R$0,15 por km rodado.
"""
dias = int(input('Informe quantos dias rodou com o carro: '))
km = float(input('Informe qu... |
75b3369bed26bf4844899716671301c07efecf50 | guilhermemaas/guanabara-pythonworlds | /exercicios/ex043.py | 1,028 | 3.953125 | 4 | """
Desenvolva um programa que leia o peso e altura de uma pessoa, calcule seu IMC e
mostre o status, de acordo com a tabela abaixo:
- Abaixo de 18.5: Abaixo do peso.
- Entre 18.5 e 25: Peso Ideal.
- 25 ate 30: Sobrepeso.
- 30 ate 40: Obesidade.
- Acima de 40: Obesidade morbida.
"""
print('CALCULO DE IMC (Indice de ma... |
2425e191c6c3c113aaeeebb7b656c887068303a2 | guilhermemaas/guanabara-pythonworlds | /exercicios/ex061.py | 826 | 4.03125 | 4 | """
Refaca o exercicio 051, lendo o primeiro termo e a razao de uma PA. Mostrando os 10 primeiros
termos da progressao aritmetica usando while.
"""
print('='*20+'\n\033[36;mPROGRESSAO ARITMETICA\033[m\n'+'='*20)
pt = int(input('Informe o primeiro termo da sua PA: '))
r = int(input('Informe a razao da sua PA: '))
n = p... |
7f3f66be6b60d7f058fd0b288bb1d5e807d6c164 | guilhermemaas/guanabara-pythonworlds | /exercicios/ex046.py | 420 | 3.578125 | 4 | """
Faca um programa que mostre na tela uma contagem regressiva para estouro de fogos de artificio,
indo de 10 ate 0, com uma pasa de 1 segundo entre eles.
"""
from time import sleep
print('*.*'*20+'\n'+' '*20+'SHOW DA VIRADA'+'\n'+'*.*'*20)
print('\nCONTAGEM REGRESSIVA!!!\n')
for c in range(10, -1, -1):
print('{... |
ffff8f3b99def5e98b3bf54fb24a5e1b63a08b03 | guilhermemaas/guanabara-pythonworlds | /exercicios/ex018.py | 1,075 | 4.125 | 4 | """
Faca um programa que leia um angulo qualquer e mostre na tela o valor de seno, cosseno, e tangente desse angulo.
"""
import math
cateto_oposto = float(input('Informe o comprimento do cateto oposto: '))
cateto_adjacente = float(input('Informe o comprimento do cateto adjacente: '))
hipotenusa = math.hypot(cateto_op... |
33d00b14f560c96cd25d96d2e1fc8612eb186c87 | guilhermemaas/guanabara-pythonworlds | /exercicios/ex055.py | 335 | 4.03125 | 4 | """
Faca um programa que leia o peso de cinco pessoas. No final, mostre qual foi o maior e menor peso lido.
"""
lista_pesos = []
for c in range(0, 5):
peso = float(input('Informe o peso da pessoa: '))
lista_pesos.append(peso)
print('MAIOR PESO: {:.2f}.\nMENOR PESO: {:.2f}.'.format(max(lista_pesos), min(lista... |
2d9399f45e21e28dab7a8681b00a7394d35ac73b | guilhermemaas/guanabara-pythonworlds | /aulas/world3/funcoes1(Aula20).py | 1,037 | 3.875 | 4 | def mostraLinha():
print('-' * 30)
def tituloCustom(texto):
mostraLinha()
print(texto)
mostraLinha()
def soma(a, b):
mostraLinha()
print(f'A = {a} e B = {b}.')
s = a + b
print(f'A soma A + B = {s}.')
mostraLinha()
def contador(* num):
tam = len(num)
print(f'Recebi os valor... |
5c298e208a80e7326f1e753497c0f3d726d271aa | guilhermemaas/guanabara-pythonworlds | /aulas/world2/interrompendoWhiles(Aula15).py | 493 | 3.734375 | 4 | n = s = 0
while True:
n = int(input('Digite um numero: '))
if n == 999:
break
s += n
print('A soma vale: {}.'.format(s))
#fstring
print(f'A soma vale {s}.')
nome = 'Jose'
idade = 35
salario = 1605.25
print(f'A pessoa se chama {nome:^20} tem {idade} anos e ganha R${salario:.2f} por mes.')
print(... |
d8c30b2c7ebc4fb7f37e8936a4ae98f3e8e07051 | guilhermemaas/guanabara-pythonworlds | /exercicios/ex041.py | 848 | 4.09375 | 4 | """
A confederacao Nacional de Natacao precisa de um programa que leia o ano de nascimento de um atleta e mostre
sua categoria, de acordo com a idade:
- Ate 9 anos: MIRIM
- Ate 14 anos: INFANTIL
- Ate 19 anos: JUNIOR
- Ate 30 anos: SENIOR
- Acima de 30 anos: MASTER
"""
from datetime import date
nome = str(input('Infor... |
ab1fa667813e0529da459b7e559dd493c66cb06e | guilhermemaas/guanabara-pythonworlds | /exercicios/ex066.py | 511 | 3.96875 | 4 | """
Crie um programa que leia diversos numeros inteiros. O programa so vai parar quando
o usuario digitar 999, que e a condicao de parada. No final, mostra quantos numeros
foram digitados e qual foi a soma entre eles(desconsiderando o flag).
"""
print('=.='*20+'\n\033[4;31;mDIGITE NUMEROS ALEATORIOS\033[m\n'+'=.='*20)... |
5c76413ea4b94dab9cbbcd9fb904c10f37b7f368 | guilhermemaas/guanabara-pythonworlds | /exercicios/ex070.py | 1,111 | 4.0625 | 4 | """
Crie um programa que leia o nome e o preco de varios produtos.
O programa devera perguntar se o usuario vai continuar.
No final, mostre:
A) Qual e o total gasto na compra.
B) Quantos produtos custam mais de R$1.000.
C) Qual e o nome do produto mais barato.
"""
print('=.='*20)
print(' '*5+'Cadastro de produtos')
pr... |
c44172d241d35968253acb2fbe2fef16bc779331 | guilhermemaas/guanabara-pythonworlds | /exercicios/ex063.py | 603 | 4.3125 | 4 | """
Escreva um programa que leia um numero n inteiro qualquer e mostre na tela
os n primeiros elementos de uma sequencia de Fibonacci.
Ex.: 0 -> 1 -> 1 -> 2 -> 3 -> 5 -> 8
"""
print('-'*30)
print('Sequencia de Fibonacci')
print('-'*30)
"""
n = int(input('Informe um numero inteiro inicial: '))
"""
qt = int(input('Infor... |
5445d08db0f152cba9a08f2f6d176a071d61c080 | habbyt/python_collections | /challenge_1.py | 292 | 4.15625 | 4 | #Challenge #1
#function takes a single string parameter and
#return a list of all the indexes in the string that have capital letters.
def capital_indexes(word):
word="HeLlO"
x=[]
for i in range(len(word)):
if word[i].isupper()==True:
x.append(i)
return x
|
5ab63722f1d9fd01d5d0df1acf9feebbf6b2e635 | habbyt/python_collections | /challenge_24.py | 474 | 3.671875 | 4 | #challenge 24
#function takes one parameter(+number)
#return after converting the number to a string and add commas as a thousands separator.
def format_number(pos):
b=str(pos)
x=[]
y=[]
re=0
result=""
for i in range(len(b)):
x.append(b[len(b)-1-i])
if i==re+2 and i<len(b)-1:
... |
4099d9148d81bba74b55cc4f7b34b2884ac8743b | hamedsafikhani/python-detect-change-in-txt-file | /code.py | 474 | 3.734375 | 4 | import time
sfile = open("YOUR-TEXT-FILE","r")
sreadFile = sfile.readlines()
sfile.close()
currentlen = len(sreadFile)
print(currentlen)
while currentlen >= 0 :
file = open("YOUR-TEXT-FILE","r")
readFile = file.readlines()
# print(len(readFile))
time.sleep(1)
if len(readFile) > currentlen :
... |
a1ac5779b889d51e1a9966fe50154e4a769c9f40 | yangyuegly/teron | /helper_functions.py | 372 | 3.640625 | 4 | from constants import *
def check_boundary(row, col):
"""
returns neighbors of the given cell
"""
neighbors = []
if row < HEIGHT-1:
neighbors.append([row+1], [col])
if row > 0:
neighbors.append([row-1], [col])
if col < WIDTH-1:
neighbors.append([row], [col+1])
i... |
9bede297db231b87a43383efa5eb7dc622883075 | HSzymski/Traveling-Salesman-Problem | /simulated_annealing.py | 3,770 | 4.1875 | 4 | import numpy as np
import random
from scipy.spatial import distance
from typing import Tuple
def simulated_annealing(cities: np.array,
initial_temperature: float,
minimum_temperature: float,
alpha: float,
scheduling: str) ... |
90e995e0b3f4e9a8f4991ee31c13bbdc2b968b2e | xana-rahmani/AesEncryption | /decrypt_mnemonic.py | 763 | 3.546875 | 4 | from Cryptodome.Cipher import AES
def string_to_byte_array(string):
return bytearray(string.encode())
try:
encryptedFileName = input("Enter Encrypted File Name: ")
with open('./generated_key/{}.hex.key'.format(encryptedFileName), "r") as f:
data = f.read().split('\n')
# convert hex data to b... |
e4cfbc8347bc4752ca81a84fa36cc1d900c65595 | efecini/mooniversity_examples | /1_notes.py | 1,861 | 3.5625 | 4 |
# Prints the hexadecimal representation of the value.
print(int('b',16), int('62ba1cd8a',16))
#testnet : A small replica of bitcoin for developers to test their app without real money.
#We use bitcoin-cli command to communicate with a node. It is a command line utility.
#In this course we use >testnet rather than >bi... |
cd2ae708b13c6359cbbcefa0b957fa58d304f722 | okazkayasi/03_CodeWars | /14_write_in_expanded_form.py | 682 | 4.375 | 4 | # Write Number in Expanded Form
#
# You will be given a number and you will need to return it as a string in Expanded Form. For example:
#
# expanded_form(12) # Should return '10 + 2'
# expanded_form(42) # Should return '40 + 2'
# expanded_form(70304) # Should return '70000 + 300 + 4'
#
# NOTE: All numbers will be whol... |
4f7cbb96396df971f262b7faecee06a8be3a23a9 | okazkayasi/03_CodeWars | /24_car_park_escape_5kyu.py | 2,297 | 4.15625 | 4 | # Your task is to escape from the carpark using only the staircases provided to reach the exit. You may not jump over the edge of the levels (youre not Superman) and the exit is always on the far right of the ground floor.
# 1. You are passed the carpark data as an argument into the function.
# 2. Free carparking... |
8b79cb22ebf59ff6dd2b8f1efbe840c8d519beb3 | okazkayasi/03_CodeWars | /06_title_case.py | 1,651 | 4.375 | 4 | # A string is considered to be in title case if each word in the string is either (a) capitalised (that is, only the first letter of the word is in upper case) or (b) considered to be an exception and put entirely into lower case unless it is the first word, which is always capitalised.
#
# Write a function that will c... |
e427b50b9a7a45b3bc9111ffe0441b4b73c34007 | okazkayasi/03_CodeWars | /11_two_to_one.py | 1,172 | 3.984375 | 4 | # Take 2 strings s1 and s2 including only letters from a to z. Return a new sorted string, the longest possible, containing distinct letters,
#
# each taken only once - coming from s1 or s2. #Examples: ```
#a = "xyaabbbccccdefww" b = "xxxxyyyyabklmopq" longest(a, b) -> "abcdefklmopqwxy"
#
# a = "abcdefghijklmnopqrs... |
1e739ce758b68c9a119ad7245ecc8a1bc42aebfd | s001015/Baekjoon | /Baekjoon 15727.py | 74 | 3.5 | 4 | L = int(input())
if L % 5 == 0:
print(L//5)
else:
print((L//5)+1)
|
56c2bafa240f9f4d8271ea4bac29607f9b0c41e0 | harrycampaz/reviewing-python | /Basic/generator.py | 568 | 3.625 | 4 | #generadores
def pairGenerator(limit):
num = 1
while num < limit:
yield num * 2
num += 1
misPares = pairGenerator(30)
# for i in misPares:
# print(i)
print(next(misPares))
print(next(misPares))
print(next(misPares))
print(next(misPares))
# Yield from
def ciudadesGenerator(*ciud... |
7f9c3ecf24b3fcef3be581072aa0e96ed9e10c80 | harrycampaz/reviewing-python | /Basic/platzi/algoritmos/busqueda_binaria.py | 886 | 3.765625 | 4 | import random
def busqueda_binaria(lista,comienzo, final, objetivo):
print(f'Buscamos {objetivo} entre {lista[comienzo]} y {lista[final - 1]}')
if comienzo > final:
return False
medio = (comienzo + final) // 2
if lista[medio] == objetivo:
return True
elif lista[medio] < objet... |
be6c9c6e972fc55b7afcbd3183b9d5e8c978ff4a | sanderslab/sanderslab.github.io | /code/optimize_size.py | 1,773 | 4 | 4 | #!/usr/bin/env python
# Optimize sizes for images/videos displayed in table format
# Author: David Young, 2020
import os
import sys
import pandas as pd
def main(path, max_width, group_col="Age"):
"""Optimize sizes of images or videos displayed in a table format,
assuming that items in the same group will be... |
066dd77335bcc186d40664faf6441f5544903d56 | PattyDelaluz/CS1400 | /trianglememe.py | 156 | 3.78125 | 4 | sidea = int(input())
sideb = int(input())
sidec = sidea ** 2 + sideb ** 2
area = sidea + sideb + sidec / 2
def triArea(area):
print(area)
triArea(area)
|
5c179b70c4600a5ac9409aadde2f64ad50772f1e | PattyDelaluz/CS1400 | /innerlist.py | 186 | 3.5625 | 4 | X = [1, 2, 3, 4]
Y = [5, 6, 7, 8]
def innerProd(X, Y):
if len(X) != len(Y):
return X * Y
return sum(i[0] * i[1] for i in zip(X, Y))
result = innerProd(X, Y)
print(result)
|
90f668d2f220011d2548646efb459edadc4e7838 | PattyDelaluz/CS1400 | /shuffle.py | 276 | 3.703125 | 4 | import random
ary = [1, 2, 3, 4, 5, 6, 7, 8 , 9, 0]
def shuffle(ary):
a=len(ary)
b=a-1
for d in range(b,0,-1):
e=random.randint(0,d)
if e == d:
continue
ary[d],ary[e]=ary[e],ary[d]
return ary
result = shuffle(ary)
print(result)
|
ed8f9221d677bef5a2513ccfb2a710beba47f401 | CMackay7/DNA_Analyser | /Edditor.py | 1,572 | 3.640625 | 4 | # Gets called by delete_lanes in user input handler handles removing the centroids from
# the list so they will not be places on the image
# This method will find the lane they clicked on and remove it from the list, it takes the list of grouped
# centroids and the position of the users click it will search and delet... |
2aca530c82c4e4a199f21208eef9c45f3ccb6853 | jimmybdc/python-challenge | /PyBank/PyBank2.py | 1,889 | 3.8125 | 4 | import os
import csv
# Path to collect data from the PyBankfolder
PyBankCSV = os.path.join('..','PyBank','budget_data_2.csv')
# Define the function and have it accept the parameters
def getRevenue(months, revenue):
diff = []
# The total number of months included in the dataset
totalMonths = len(mont... |
d38d6574d67bfe66e8a529934926da2bc74230ed | dengyungao/python | /老男孩python全栈开发第14期/python基础知识(day1-day40)/序列化模块 json模块+pickle模块 .py | 2,998 | 3.84375 | 4 |
"""
字典、列表、数字、对象转化成一个字符串,即序列化,反过来则是反序列化
何时用序列化:
要把文件写入文件时
网络传输数据时
序列化模块
json 支持数据类型较少(只支持列表或字典),但能跨语言,
pickle 注意,pickle的用法与json完全相同,pickle几乎支持python所有数据类型,但只能在python中用
json模块的限制:
json格式的字典的key必须是字符串类型,如果不是也会自动转成字符串。
json格式中的字符串只能用双引号括起来。不能用单引号。
json不支持元组作为字典的value,会自动转换成列表,也不支持元组作为字典... |
53ac8d6dc572787bc7005bf07ec647b615e8da01 | dengyungao/python | /老男孩python全栈开发第14期/python基础知识(day1-day40)/python多线程/互斥锁/演示死锁的发生.py | 1,006 | 3.9375 | 4 | import time
from threading import Thread, Lock
'''
背景:男的只拿到厕所资源,女的只拿到纸资源
'''
def man(l_tot, l_pap):
l_tot.acquire() # 是男的获得厕所资源,把厕所锁上了
print('alex在厕所上厕所')
time.sleep(1)
l_pap.acquire() # 男的拿纸资源
print('alex拿到卫生纸了!')
time.sleep(0.5)
print('alex完事了!')
l_pap.release() # 男的先还纸
l_tot.release() # 男的再还厕所
def wo... |
5e4ae3b7009333a950087fd44875b4db5a3b656c | dengyungao/python | /老男孩python全栈开发第14期/python基础知识(day1-day40)/python协程+多路复用机制/yield关键字实现状态保存.py | 940 | 4.0625 | 4 | '''
结论:
程序每遇到带yield关键的行时就会返回yield后面的参数(返回值),并停留在该行代码处,
继续运行代码的话,程序就会从该行的下一行继续执行。所以说yield能实现状态保存和程序切换。
'''
def func():
sum = 0
print(1)
print(2)
yield sum
print(3)
yield sum+1
print(4)
print(5)
yield sum+2
def ffff():
g = func()#此时不会执行func函数
print('这是在ffff函数中')
print(next(g))#此时才开始执行func函数到第10行(第一个yield),... |
4b58e15efc72753ed91975d5acb1192dcfaa60fc | Tim-Haarman/pong-rl | /pong.py | 3,784 | 3.5 | 4 | import pygame
from ball import Ball
from paddle import Paddle
class Pong():
def __init__(self):
self._WINDOW_WIDTH = 800
self._WINDOW_HEIGHT = 600
self._SCOREBAR_HEIGHT = 100
self._FIELD_HEIGHT = self._WINDOW_HEIGHT - self._SCOREBAR_HEIGHT
self._PADDLE_OFFSET = 40
s... |
2ee85aa47ea5114a18fab73a54fe3b3311678877 | clarinet758/codeforces | /etc/educational/round0001-0025/round0014/a1.py | 170 | 3.6875 | 4 | #!/usr/bin/env python
# -*- coding: UTF-8 -*-
n=int(raw_input())
l=map(int,raw_input().split())
print 'YES' if (l.count(0)==1 and n!=1) or (n==1 and l[0]==1) else 'NO'
|
073eee0734470481aeadd3c0e3dfebd0239537d4 | clarinet758/codeforces | /etc/VKCup/2017/Qu2/a1.py | 145 | 3.609375 | 4 | #!/usr/bin/env python3
# -*- coding: UTF-8 -*-
n,k=map(int,input().split())
x=ord("a")
ans=""
for i in range(n):
ans+=chr(x+i%k)
print(ans)
|
5e40bf1df70471894def49d1da95b7730bf0ec5b | clarinet758/codeforces | /round/round0351-0375/round0373/a1.py | 245 | 3.71875 | 4 | #!/usr/bin/env python
# -*- coding: UTF-8 -*-
n=int(raw_input())
l=map(int,raw_input().split())
if l[-1]==15 or (n>1 and l[-1]!=0 and l[-2]-l[-1]>0):
print 'DOWN'
elif l[-1]==0 or (n>1 and l[-2]-l[-1]<0):
print 'UP'
else:
print -1
|
328d62b96e4efa6d671c03b5813fa1a509a12bb2 | clarinet758/codeforces | /round/round0376-0400/round0386/b1.py | 173 | 3.6875 | 4 | #!/usr/bin/env pypy3
# -*- coding: UTF-8 -*-
n=int(input())
s=input()
ans=''
for a,i in enumerate(s):
if (a+n)%2:
ans+=i
else:
ans=i+ans
print(ans)
|
5ee8a1b202aee4c11f7f29834f00410f71a29396 | clarinet758/codeforces | /round/round0051-0075/round0059/a1.py | 372 | 3.578125 | 4 | #!/usr/bin/env python
# -*- coding: UTF-8 -*-
import time
import sys, io
import re, math
#start = time.clock()
n=int(raw_input())
d={'captain':[],'man':[],'woman':[],'child':[],'rat':[]}
for i in range(n):
a,b=[x for x in raw_input().split()]
if b=='woman': b='child'
d[b].append(a)
for i in ['rat','child','... |
ca628671c4fee4fbc9ebc3888a66d2ae6ea23914 | mickahell/quantum_Nim-game | /src/main.py | 5,469 | 3.5625 | 4 | """Main functions."""
from typing import Tuple
from qiskit import Aer, QuantumCircuit, QuantumRegister, execute
from src.function import control_input, who_start
from src import draw, ia
def battle(player1: list, backend_sim: Aer) -> Tuple:
"""Battle game.
Args:
player1: player
backend_sim: b... |
165ab21f2a231f5dad4707f4ff54f3280f998ce4 | N1ntEnd0/PythonStudy | /homework4/Task2.py | 1,122 | 3.875 | 4 | """
Write a function that accepts an URL as input
and count how many letters `i` are present in the HTML by this URL.
Write a test that check that your function works.
Test should use Mock instead of real network interactions.
You can use urlopen* or any other network libraries.
In case of any network error raise Value... |
7eb3303ac6e678cee5942627036a4a3e0ed271b6 | likwong00/UnknownSignal | /cw1_ka18866.py | 5,220 | 3.5625 | 4 | import os
import sys
import pandas as pd
import numpy as np
from matplotlib import pyplot as plt
import matplotlib.lines as lines
def load_points_from_file(filename):
"""Loads 2d points from a csv called filename
Args:
filename : Path to .csv file
Returns:
(xs, ys) where xs and ys are a nu... |
e35a17f9b063162aef099bec5f12d1c725fa1325 | leepeel/PL-Resolution-and-cnf | /SATplan/utils.py | 3,572 | 3.5625 | 4 | from copy import deepcopy
def to_atom(line):
""" Creates an Atom from a string given the format 'operator(arg0, arg1, ... )' """
operator = line[0:line.find('(')]
args = line[line.find('(') + 1:line.find(')')]
consts = args.split(',')
expr = []
for c in consts:
expr.append(Atom(c))
... |
e508201f832bd11579a14b8b6dd8c9f816ebb246 | KodingKurriculum/level-0-python-coding-interview | /practice_problems/graph/longest_connected_values.py | 1,349 | 3.671875 | 4 | from plumbum import cli
import pprint
class LongestConnectedValues(cli.Application):
# Making the assumption that values are not repeated!
# 6 , 5 , 7
# 1 , 4 , 8
# 2 , 3 , 9
_graph = {
6: [1, 5],
1: [6, 4, 2],
2: [1, 3],
5: [6, 4, 7],
4: [5, 8, 3, 1],
... |
e07db3b73f5e6f47ddb85a7a4fde18df4316c354 | wilsonqin/problem-solving | /python/16.py | 217 | 3.703125 | 4 | #gives a list of digits in string form
digits = list(str(pow(2,1000)))
#convert all digits to strings
digits = map(int, digits)
def add(x,y):
return x+y
sum_of_digits = reduce(add, digits, 0)
print sum_of_digits |
1d7807d7f2552595019d79c98d8ff535195c7f1c | Matthew-Carlson/algorithm-practice | /sorting/insertion_sort.py | 290 | 3.71875 | 4 | def insertion_sort(input_list):
for i in range(2, len(input_list)):
key = input_list.pop()
index = 0
for j in range(i):
if key > input_list[j]:
index = j+1
else:
break
input_list.insert(index, key)
|
4c621ed50b77d078c63b7776ae17ef1cda9a513f | abby2407/Data_Structures-and-Algorithms | /PYTHON/Graph/Minimum_Edges_between_SRC_and_DEST.py | 3,057 | 4.1875 | 4 |
# ------------------ Python program to find minimum edges between SRC nad DEST in an Undirected Graph -------------------
class minEdgesGraph():
def __init__(self, number_of_nodes):
self.number_of_nodes = number_of_nodes
self.matrix = [[0 for x in range(self.number_of_nodes)] for y in rang... |
1df122ea8c6cbe2473ffa0be8626f86c38d65760 | abby2407/Data_Structures-and-Algorithms | /PYTHON/Graph/Graph_Finding_Mother_Vertex.py | 1,339 | 4.15625 | 4 |
''' A mother vertex in a graph G = (V,E) is a vertex v such that all
other vertices in G can be reached by a path from v.'''
from collections import defaultdict
class Graph:
def __init__(self, vertices):
self.vertices = vertices
self.graph = defaultdict(list)
def addEdge(... |
f64fe593a08c79de7cd60ab565b6249bb8464192 | abby2407/Data_Structures-and-Algorithms | /PYTHON/Linked List/SingleLinkedList.py | 5,580 | 4 | 4 | class Node:
def __init__(self,data):
self.data = data # Node Data
self.next = None # Pointer to Next Node
class singleLinkedList:
def __init__(self):
self.head = None #... |
a40d1f6c1b6e2ca8124cb5dd729cdb8ccb9b7088 | chuksmbaka/laptop-python | /classes.py | 357 | 3.625 | 4 | class Animal:
def __init__(self, group, name):
self.group = group
self.name = name
#dispaplay animal
def display(self):
print("Animal type: " + self.group)
print("Name: " + self.name)
#main
animal1 = Animal("dog", "fago")
animal1.group.title()
animal1.name.title()
anima... |
71137da0d43a6086112e40b795b238ba33440fc7 | naveenchopra9/python3 | /Naivepatternsearching.py | 327 | 3.875 | 4 | The worst case complexity of Naive algorithm is O(m(n-m+1))
def search(txt,pat):
M=len(txt)
N=len(pat)
for i in range(M-N+1):
for j in range(N):
if txt[j+i]!=pat[j]:
break;
if j==N-1:
print ("position pattren" +str(i))
txt=str(input("input txt string: "))
pat=str(input("input pat string: "))
search(tx... |
1fb22cb6fe5e9acb929889693bff679e899ff731 | Nishijama/CS50 | /pset6/Cash/cash.py | 609 | 3.625 | 4 | # cash.py
from cs50 import get_float
dollars = 0
while float(dollars) < 0.01 or dollars > 100:
dollars = get_float("Change owed: ")
cents = round(dollars * 100)
# print(f"it's {cents} cents")
# quarter = 25 cents, dime = 10 cents, nickle = 5 cents, penny = 1 cent
q = 0
d = 0
n = 0
p = 0
if cents >= 25:
q ... |
e1a1c8e3f336bdff4a4512ec44d7f377358b075c | clean-code-craft-tcq-1/current-ranges-python-preetikadyan | /identify_range_and_count_implementation.py | 1,173 | 3.5 | 4 |
def identify_range_and_count(list_of_nos):
#ar=[3,5,3,10,15]
list_of_nos.sort() #sort the element to ascending order
count=[]
strt=[]
end=[]
result = []
i=0
ct=-1
pre= list_of_nos[0]-5
length = len(list_of_nos)
#in this logic I am comparing the current element... |
b3a63dfadc365724ee0b073ef3350f813ab9e9c8 | lalwanigunjan/Parking_Data_Analysis | /amount_due_per_licence/reduce.py | 2,188 | 3.6875 | 4 | #!/usr/bin/env python
"""s
The algorithm simply considers each licence type
as key and add +1 to count and the amount value
to current amount for the current key.
It averages by divding amount/count and outputs it.
"""
from operator import itemgetter
import sys
current_licence_type = None
current_co... |
04245a627a81d206fd76d72a9808524609498db9 | S-Tim/Codewars | /python/sudoku_solver.py | 1,926 | 4.1875 | 4 | """
Write a function that will solve a 9x9 Sudoku puzzle. The function will take one argument
consisting of the 2D puzzle array, with the value 0 representing an unknown square.
The Sudokus tested against your function will be "easy" (i.e. determinable; there will be
no need to assume and test possibilities on unknowns... |
abb8357f750eca6924d85efa5edd8fa737a4337d | fcostin/system_pytest | /system_test_machinery/file_diff.py | 1,456 | 3.53125 | 4 | """briefly explain differences between files"""
import difflib
def is_probably_binary(file_name):
"""ref: http://stackoverflow.com/questions/898669/ """
block_size = 1024
with open(file_name, 'rb') as f:
block = f.read(block_size)
while block == block_size:
if '\0' in block:
... |
589a7855893f78b443f1c54c9ae1476885409772 | GalickayaAleksandra/hillel_hometask5 | /task5.py | 863 | 3.671875 | 4 | # Дан файл с текстом, удалить из файла все отрицательные числа, числа могут быть не целыми
from Read_Write_File import read_file as rf
from Read_Write_File import add_file as af
from Regular_pattern import pattern_negative_numbers as pngn
from Read_Write_File import error_file
name_file_read_negative = "./numb... |
70c0dd67b82a2e22d35bb9e68d2022c841a099d8 | laura-daugherty/Sorting | /src/recursive_sorting/recursive_sorting.py | 2,027 | 4.03125 | 4 | # TO-DO: complete the helper function below to merge 2 sorted arrays
import math
def merge( arrA, arrB ):
elements = len( arrA ) + len( arrB )
merged_arr = [0] * elements
# TO-DO
new_arr = []
index_a = 0
index_b = 0
while len(new_arr) < len(merged_arr):
if len(arrA) == index_a:
... |
4e2f0756383f20a076086fb655e6ed4b9c76f7ab | xeohyeonx/python-practice | /format and etc.py | 2,656 | 4.1875 | 4 | year = 2019
month = 10
day = 29
print("오늘은 " + str(year) + "년 " + str(month) + "월 " + str(day) + "일입니다.")
# 이렇게 하면 너무 번거로우니까 문자열 포맷팅을 통해서 하면 더 편함
print("오늘은 {}년 {}월 {}일입니다.".format(year, month, day)) # 이렇게 해주면 중괄호 안에 format 뒤의 파라미터들이 순서대로 들어감.
# 이렇게도 가능.
date_string = "오늘은 {}년 {}월 {}일입니다."
print(date_str... |
58ddbfe8f4eca1b019b54c2dcac4c73c94f145e9 | clarkmp/CSCI215_Assignment_1 | /portfolio/csci220/Assignment03/assignment03.py | 2,218 | 4.15625 | 4 | from math import *
def checkIfPrime():
userNumber = eval(input("Give me a number: "))
if userNumber > 1: #this makes sure the number is greater than 1 which is not a prime number
while userNumber > 1: #this only loops if the number is greater than 1
if userNumber % 2 == 0: #this will determ... |
8dcdc18d3a3e021f36a9df6128bbcab84879cb66 | phayo/exercism-algorithms | /python/bob/bob.py | 448 | 3.6875 | 4 | import re
def response(hey_bob):
isUpper=hey_bob.isupper()
no_space = len(re.sub(r"\s*", "", hey_bob)) > 0
question= no_space and hey_bob.strip()[-1] == '?'
if(isUpper and question):
return "Calm down, I know what I'm doing!"
elif (isUpper):
return 'Whoa, chill out!'
elif (ques... |
9a534eaf0d88354daa8a7fa76aea3bd453ce3740 | phayo/exercism-algorithms | /python/matrix/matrix.py | 491 | 3.515625 | 4 | class Matrix(object):
def __init__(self, matrix_string):
self.matrix = matrix_string.split("\n")
def row(self, index=-1):
if index == -1:
return [[int(a) for a in x.split()] for x in self.matrix]
return [[int(a) for a in x.split()] for x in self.matrix][index-1]
def col... |
07c2d7816ba29ed9ffe16ed748dccfcd83255ab0 | wardm5/Machine_Learning | /Wine Classifcation - Final Project/MachineLearningProject.py | 8,914 | 4.0625 | 4 | #!/usr/bin/python
# K Nearest Neighbor
from sklearn import neighbors
import matplotlib.pyplot as plt
# K-Nearest Neighbor Example Code, thanks to SKLearn Examples - https://bit.ly/2AWVSHO
def kthNearest(X, y, n):
n_neighbors = n
h = .02 # step size in the mesh
for weights in ['uniform', 'distance']:
... |
5f3ad9c7ceaca383b2ef7a2b1561a4046105f1fb | brianwoo/python-for-informatics | /exercise2/pay.py | 134 | 3.828125 | 4 |
hours = raw_input("Enter Hours: ")
rate = raw_input("Enter Rate: ")
pay = float(hours) * float(rate)
print "Pay is: " + str(pay);
|
1efa5b91aa53946db6bf26ee026fe16a36a12a02 | gkc23456/BIS-397-497-CHANDRATILLEKEGANA | /Mid Term/Midterm12.py | 880 | 3.71875 | 4 | # Score 15/25
# You did not create a fucntion that will calculate descriptive statistics.
# You created a script that calls existing functiions.
# Script was also supposed to work on any arbitrary list of numbers.
$ You have "hard-wired" it for 6 numbers.
import statistics
def descriptive():
number = ran... |
0678f44e86e93fdef14ff4f35e8b6e5b7fe3ad31 | gkc23456/BIS-397-497-CHANDRATILLEKEGANA | /Assignment 2/Assignment 2 - Excercise 3.16.py | 477 | 4.15625 | 4 | # Exercise 3.16
largest = int(input('Enter number: '))
number = int(input('Enter number: '))
if number > largest:
next_largest = largest
largest = number
else:
next_largest = number
for counter in range(2, 10):
number = int(input('Enter number: '))
if number > largest:
next_largest = lar... |
c7b368be9c464cdb5dae0f7cf16689491cecc442 | floogulinc/hydrus | /hydrus/core/HydrusArchiveHandling.py | 692 | 3.734375 | 4 | import zipfile
def ExtractSingleFileFromZip( path_to_zip, filename_to_extract, extract_into_file_path ):
with zipfile.ZipFile( path_to_zip ) as zip_handle:
with zip_handle.open( filename_to_extract ) as reader:
with open( extract_into_file_path, "wb" ) as writer:
... |
6b99441089eb7af1c9b3a537c90c2b6a743910a0 | JupiLogy/uninteresting-random-code | /less_than_list.py | 141 | 3.765625 | 4 | a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
limit = int(input('See numbers less than: '))
b = [item for item in a if item < limit]
print(b)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.