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 |
|---|---|---|---|---|---|---|
93b4f43cfc3b0067a31ae69b2159a8b3a0224593 | blhwong/chess | /src/chess.py | 34,572 | 3.5 | 4 | '''
Created on Aug 11, 2016
Modified on Aug 15, 2016
@author: Brandon Wong
Description: Lists out all available chess moves given state of the board,
and player's turn (black or white). There is no accommodation for king in check,
en passant, or castling at the moment. The board is already set for initial
st... |
853aed70158b6c4f63141fe2fe05293f000cc8a2 | watsonpy/watson-validators | /watson/validators/numeric.py | 970 | 3.90625 | 4 | # -*- coding: utf-8 -*-
from watson.validators import abc
class Range(abc.Validator):
"""Validates the length of a string.
Example:
.. code-block:: python
validator = Length(1, 10)
validator('Test') # True
validator('Testing maximum') # raises ValueError
"""
def __in... |
a499e78d9429cec4e7048d27c28dd2dd8eaca328 | RogerEC/CP-ICPC-Training | /Online-Judges/URI/Python/Iniciante/1064.py | 167 | 3.640625 | 4 | cont=0; soma=0.0
for i in range(6):
x=float(input())
if x>=0.0:
soma+=x
cont+=1
print("%d valores positivos" %cont)
print("%.1f" %(soma/cont))
|
0e9d463a1be1a09c63a62e1c4bbcfd01ffa21a02 | RogerEC/CP-ICPC-Training | /Online-Judges/URI/Python/Iniciante/1036.py | 246 | 3.6875 | 4 | a,b,c=input().split(' ')
a=float(a)
b=float(b)
c=float(c)
if a==0.0 or (b**2-4.0*a*c)<0:
print('Impossivel calcular')
else:
print("R1 = %.5f" %((-b+(b**2-4.0*a*c)**0.5)/(2.0*a)))
print("R2 = %.5f" %((-b-(b**2-4.0*a*c)**0.5)/(2.0*a)))
|
2e05f177f5f475c7f3ab4beb0357bb05546ad353 | RogerEC/CP-ICPC-Training | /Online-Judges/URI/Python/Iniciante/1011.py | 78 | 3.609375 | 4 | pi=3.14159
raio=float(input())
print("VOLUME = %.3f" %((4.0*pi*raio**3)/3.0))
|
fe8346b404dff136d32a77750c4564b7beef8397 | mohlinna/AoC2020 | /day8/aoc8.py | 613 | 3.703125 | 4 | def run_program(instructions):
acc = 0
line = 0
run_lines = set()
while line not in run_lines:
run_lines.add(line)
instruction = instructions[line].split()
op = instruction[0]
arg = int(instruction[1])
if op == 'jmp':
line += arg
elif op == 'ac... |
e9fad52f1d346aa6712257675c1ca97983269e3a | mohlinna/AoC2020 | /day5/aoc5_2.py | 607 | 3.5 | 4 |
def get_seat_id(boarding_pass):
binary_rep = boarding_pass.replace('B', '1').replace('F', '0').replace('R', '1').replace('L', '0')
return int(binary_rep, 2)
def find_my_seat(boarding_passes):
seat_ids = sorted(map(get_seat_id, boarding_passes))
print(seat_ids)
seat_candidate = seat_ids[0]
for... |
a75dc944ca31f4050f35556a5c749f0f34c6dc9a | kcpedrosa/Python-exercises | /ex020.py | 263 | 3.59375 | 4 | import random
a = str(input('Digite o nome do primeiro aluno: '))
b = str(input('Digite o nome do segundo aluno: '))
c = str(input('Digite o nome do terceiro aluno: '))
lista = [a, b, c]
print('A ordem de apresentação será {}'.format(random.shuffle(lista)))
|
83ab827c9060e7f55072bd6119ab777a25ce56da | kcpedrosa/Python-exercises | /ex066.py | 301 | 3.671875 | 4 | ##066 - Vários números com flag, interrupção de WHILE com BREAK
num = 0
cont = soma = 0
while True:
num = int(input('Digite um numero [e 999 para parar]: '))
if num == 999:
break
cont += 1
soma += num
print('Voce digitou {} numero[s] e sua soma foi {}'.format(cont, soma))
|
93a70e8646da7edf7963932154f9525854eed061 | kcpedrosa/Python-exercises | /ex008.py | 260 | 3.890625 | 4 | e = float(input('Digite um valor em metros: '))
km = e/1000
hm = e/100
dam = e/10
dm = e * 10
cm = e * 100
mm = e * 1000
print('O valor indicado vale {} km {} hm {} dam'.format(km, hm, dam))
print('O valor indicado vale {} dm {} cm {} mm'.format (dm, cm, mm))
|
abe613199f6440cada8ff01c173d44c96e7362de | kcpedrosa/Python-exercises | /ex071.py | 691 | 3.609375 | 4 | print('=-' * 25)
print('{:^40}'.format('BANCO DEUTSCHES BANK'))
print('=-' * 25)
valor = int(input('Digite o valor a ser sacado: R$ '))
total = valor
totalced = 0
ced = 50
while True:
if total >= ced:
total -= ced
totalced += 1
else:
#if totalced > 0 de um tab no print abaixo, o program... |
7662cf949856c7e6ec3dbc8c07c2a07e018dab91 | kcpedrosa/Python-exercises | /ex047segundomodo.py | 159 | 3.953125 | 4 | #contagem de numero par com a metade das iterações
for numero in range (2, 51, 2):
print('.', end=' ')
print(numero, end=' ')
print('Begin the game') |
17feb48a9bbf87a6799b4377b66f5db73aff3cd4 | kcpedrosa/Python-exercises | /ex055usandoLST.py | 335 | 3.890625 | 4 | # Maior e menor da sequência
lst=[]
for pessoa in range(1, 4):
peso = float(input('Digite o peso da {}ª pessoa em kgs: '.format(pessoa)))
lst+=[peso]
print('O valor do peso da {}ª pessoa é {} kgs'.format(pessoa, peso))
print('O maior peso foi {} kgs'.format(max(lst)))
print('O menor peso foi {} kgs'.format(... |
013ba65877e79e4b2b826c3b466ed443931570fe | kcpedrosa/Python-exercises | /ex056.py | 924 | 3.765625 | 4 | somaidade = 0
media = 0
maioridhom = 0
nomevelho = ''
totmulher20 = 0
for pess in range(1,3):
print('--- {} ª pessoa ---'.format(pess))
nome = str(input('Digite o nome da pessoa: ')).strip()
idade = int(input('Digite a idade da pessoa: '))
sexo = str(input('Digite o sexo [M/F]: ')).strip()
somaida... |
7d3247fe1ed6b9f4f7e4eef50209cca956deadcc | kcpedrosa/Python-exercises | /ex003.py | 186 | 3.828125 | 4 | numero1 = float (input ('Digite um valor: '))
numero2 = float (input ('Digite outro valor: '))
soma = numero1 + numero2
print ('Soma: {} mais {} dá {}'.format(numero1, numero2, soma)) |
a06e203bb0e30a1874d4448be811595b555bb59d | kcpedrosa/Python-exercises | /ex013.py | 305 | 3.65625 | 4 | salario = float(input('Digite o montante do salário: R$ '))
aumento = float(input('Digite o valor percentual do aumento: '))
salarionovo = salario * (1 + (aumento/100))
print ('Um funcionário que ganhava R$ {:.2f} , \ncom aumento de {} %, passa a receber R${:.2f}'.format(salario, aumento, salarionovo)) |
0d0af0c4388871a673dde68dd141543047cd7f19 | kcpedrosa/Python-exercises | /ex078.py | 500 | 4.0625 | 4 | #digite 5 numeros e o programa vai dizer quem é o maior E sua posição
lista=[]
for c in range(0, 5):
lista.append(int(input('Digite um número: ')))
print(f'Você digitou {lista}')
print(f'O maior valor foi {max(lista)} ...', end='')
for pos, c in enumerate(lista):
if c == max(lista):
print(f'na posição {... |
ab167169d58ee255733db3229d95bb5f5df4786f | kcpedrosa/Python-exercises | /ex079.py | 305 | 3.875 | 4 | lista = []
while True:
num = int(input('Digite um número: '))
if num not in lista:
lista.append(num)
else:
print('Valor duplicado. ACESS DENIED')
perg = str(input('Quer continuar? [S/N] ')).lower()
if perg in 'n':
break
print(f'Você digitou {sorted(lista)}') |
5225e5adf912762cc349331c4276b978190c8bf9 | kcpedrosa/Python-exercises | /ex005.py | 222 | 4.1875 | 4 | #faça um programa que fale de sucessor e antecessor
numero = int (input('Digite um numero: '))
ant = numero - 1
suc = numero + 1
print('Urubusevando {}, seu antecessor é {} e seu sucessor é {}'.format(numero, ant, suc)) |
05b81c7d0cfee21343ec43e07e90a80844ec1b1f | kcpedrosa/Python-exercises | /ex091.py | 774 | 3.796875 | 4 | from random import randint
from time import sleep
from operator import itemgetter
jogos = {'jogador1': randint(1, 6), 'jogador2': randint(1, 6),
'jogador3': randint(1, 6), 'jogador4': randint(1, 6)
}
ranking = []
print(' JOGO DE DADO ')
print(jogos)
for k, v in jogos.items():
print(f'O {k} tiro... |
034be106f76495593e2d2acaa5683960bd3be045 | kcpedrosa/Python-exercises | /ex075.py | 565 | 4.125 | 4 | #Análise de dados em uma Tupla
numeros = (int(input('Digite o 1º numero: ')), int(input('Digite o 2º numero: ')),
int(input('Digite o 3º numero: ')), int(input('Digite o 4º numero: ')))
print(f'Você digitou os valores {numeros}')
print(f'O valor 9 foi digitado {numeros.count(9)} vez(es)')
if 3 in numeros:
... |
6c01da59eaf3527be1aad68a889f7eabd24cbbf9 | kcpedrosa/Python-exercises | /ex029.py | 277 | 3.75 | 4 | velocidade = float(input('Qual a velocidade do carro? Digite aqui: '))
if velocidade > 80:
print('Atenção! Você foi multado')
print('Sua multa foi de R$ {}'.format((velocidade - 80) * 7))
else:
print('Parabéns, você está dirigindo dentro dos limites da lei.') |
5f46e672e9858af9f2e6b0372d87fa2df2022c82 | kcpedrosa/Python-exercises | /ex109reforc/mainprog.py | 870 | 3.828125 | 4 | from ex109reforc import moeda
#exerc refeito pra reforçar
preço = float(input('Digite o preço do produto: '))
taxa1 = int(input('Digite uma taxa de AUMENTO: '))
taxa2 = int(input('Digite uma taxa de DIMINUIÇÃO: '))
#o primeiro moeda é o nome do módulo e o segundo é o da função[abaixo]
#o preço abx está em dolar apenas ... |
adf4bb569e7585898d47ddf13f1aa3d862f2d430 | kcpedrosa/Python-exercises | /ex025optmzd.py | 590 | 3.84375 | 4 | cores = {'limpa': '\033[m',
'azul': '\033[34m',
'roxo': '\033[35m',
'fundociano': '\033[46m'}
n = str(input('Digite seu nome: ')).strip()
# O programa irá jogar tudo para minusculo.
n = n.lower()
n = str('silva' in n.split())
#Split will split a string into a list where each WORD is a list it... |
b6916ffc42aa78e03f2a0a8c9acdf4994c834509 | NightHydra/HonChemCalc | /Chapter_6_Menu.py | 11,446 | 3.625 | 4 | from Thermochemistry import *
from Number_Validation import *
def Thermo_Menu(): # Main menu for chapter 6
print ("\nChapter 6 Menu:\n")
print ("Rules:\n")
print ("Please input all mass in grams")
print ("Please input all temperature in Celcius")
print ("Please input all specific heat values in cal/... |
31029ba30520ba0f0f52246450554c8db3de6aac | nonlogic/BuildingTimeSeries | /linreg.py | 1,869 | 3.515625 | 4 | import numpy
from sklearn import linear_model
# Function to normalize data:
def normalize(X):
mean_r = []
std_r = []
X_norm = X
n_c = X.shape[1]
for i in range(n_c):
m = numpy.mean(X[:, i])
s = numpy.std(X[:, i])
mean_r.append(m)
std_r.append(s)
... |
b8749de2613cdc9ec48f3dd0ef26e07e8ef265c3 | fazejohk/Beginner-Projects | /Sentence-Gen/sentencegen.py | 453 | 3.53125 | 4 | import random
import time
first={
1:"What", 2:"Where", 3:"When", 4:"who"
}
second={
1:"did", 2:"you", 3:"were", 4:"do"
}
third={
1:"it", 2:"she", 3:"he", 4:"nibba"
}
fourth={
1:"do", 2:"eat", 3:"shit", 4:"steal"
}
random1=random.randint(1,4)
random2=random.randint(1,4)
print(first[random1])
time.sleep(... |
e8642c64ba0981f3719635db11e52a0823e89b68 | league-python/Level1-Module0 | /_02_strings/_a_intro_to_strings.py | 2,954 | 4.6875 | 5 | """
Below is a demo of how to use different string methods in Python
For a complete reference:
https://docs.python.org/3/library/string.html
"""
# No code needs to be written in this file. Use it as a reference for the
# following projects.
if __name__ == '__main__':
# Declaring and initializing a string variabl... |
163249718b991047cfb3c5245332ec871080a1e4 | kingwongf/basic_algos | /basic_algos3.py | 4,180 | 3.8125 | 4 |
def merge_sort(arr):
if len(arr)>1:
mid = len(arr)//2
L = arr[:mid]
R = arr[mid:]
merge_sort(L)
merge_sort(R)
i=j=k=0
while i < len(L) and j < len(R):
if L[i] < R[j]:
arr[k] = L[i]
i+=1
else:
... |
d84ca3a229d7603d0eeb4781c770e4ec1853dee7 | LeviMorningstar/Anotacoes-de-aulas | /PandasAula 3(DrataFrame Seleção Condicional, set_index).py | 581 | 3.53125 | 4 | import numpy as np
import pandas as pd
from numpy.random import randn
np.random.seed(101)
df = pd.DataFrame(randn(5, 4), index='A B C D E'.split(), columns='W X Y Z'.split())
bol = df > 0
print(df[bol])
print()
df = df[df['W'] >0]
print(df)
# o 'and' nao consegue tratar Series entao o '&' entra ... |
8d4d6b1f7fcacf7d519c6bddb7038039754ba871 | maxrosssp/project-euler | /problems/p19.py | 1,136 | 4.03125 | 4 | def isLeapYear(year):
if year % 4 != 0:
return False
if year % 400 == 0:
return True
if year % 100 == 0:
return False
return True
def thirty_day_month(year):
return 30
def thirty_one_day_month(year):
return 31
def february(year):
return 29 if isLeapYear(year) else 28
days_in_month = {
0: thirty_one... |
3d000553a48f8852f1ffb21bd4543b9fc217fc8b | maxrosssp/project-euler | /problems/p4.py | 728 | 3.640625 | 4 | def isPallindrome(n):
nStr = str(n)
nStrLen = len(nStr)
mid = nStrLen / 2
i = 0
while i < mid:
if nStr[i] != nStr[(nStrLen - 1) - i]:
return False
i += 1
return True
print('True: '),
print(isPallindrome(123321))
print('True: '),
print(isPallindrome(1235321))
print('False: '),
print(isPallindrome(12342... |
5e0dd91694bc5b7b0147492d6401183a51a45330 | mkrostm/Udacity-BikeShare-project | /bikeshare.py | 12,652 | 4.03125 | 4 | # -*- coding: utf-8 -*-
"""
@author: Mohamed Kamel
"""
import time
import datetime
import pandas as pd
CITY_DATA = { 'chicago': 'Data/chicago.csv',
'new york city': 'Data/new_york_city.csv',
'washington': 'Data/washington.csv' }
months =['january','february','march','april... |
cb304052a0a212b3e07ab2bf18b9b8b1b23f52e7 | tuxisma/python | /purepython/list_comprehension/list_comprehension.py | 93 | 3.8125 | 4 | words = "Hello I am Ismael Garcia".split()
r = [len(word) for word in words]
print(f'Result: {r}')
|
71ba32c406a48303f74e49a84f94f5acf01eaf8a | Pedro29152/binary-search-tree-python | /main.py | 1,046 | 3.734375 | 4 | import random, timeit, sys
from BinaryTree.BinarySearchTree import BinarySearchTree
if __name__ == '__main__':
size = 100
try:
size = int(sys.argv[1])
except:
pass
max_val = size*10
tree = BinarySearchTree()
arr = []
for i in range(size):
try:
val = ran... |
dd0e18c7d844270de3e94041634fb5eae9949c47 | prajjwalkumar17/DSA_Problems- | /dp/Knapsack_Unbounded.py | 1,874 | 4.0625 | 4 | """
Unbounded Knapsack problem using dp (Unbounded means all the given weights are available in infinite quantity)
Given weights and their corresponding values,
We fill knapsack of capacity W to obtain maximum possible value(or profit). We can pick same weight more than once.
N: Number of (items)weight elements
W: Capa... |
c18d5b47c2598b24703a2a7d3ba5c9b471ea78bb | prajjwalkumar17/DSA_Problems- | /dp/Maximum_Profit.py | 2,223 | 3.921875 | 4 | '''
Purpose :
In a trading system a product is bought in the morning and sold out on the same day.
If a person can make only 2 transactions a day with a condition that second transaction is followed only after first then find the maximum profit the person could get.
Input formate :
Line1 : Number of test cases
Line... |
17684e47bb9c34e7088b9336118d73b2eac9dd3a | prajjwalkumar17/DSA_Problems- | /dp/Unique_BST.py | 1,730 | 3.90625 | 4 | """
Purpose: Total number of Unique BST's that can be
made using n keys/nodes.
Method: Dynamic Programming
Intution: Total number of Unique BST's with N nodes
= Catalan(N)
Here function Unique_BST() return the total number of
diffrent Binary Search Trees that can be made with N distinct nodes
Arg... |
f17492efff4bbe8ce87a626abfece629c0297a83 | prajjwalkumar17/DSA_Problems- | /dp/length_common_decreasing_subsequence.py | 1,918 | 4.375 | 4 | """ Python program to find the Length of Longest Decreasing Subsequence
Given an array we have to find the length of the longest decreasing subsequence that array can make.
The problem can be solved using Dynamic Programming.
"""
def length_longest_decreasing_subsequence(arr, n):
max_len = 0
dp = []
# In... |
5851be9c774490d8643d8897c6aacb9a1340b569 | prajjwalkumar17/DSA_Problems- | /dp/Knapsack_01.py | 2,371 | 4 | 4 | """
Knapsack 0-1 problem using dp (0-1 means we either choose it or we don't, no fractions)
Given weights and their corresponding values,
We fill knapsack of capacity W to obtain maximum possible value in bottom-up manner.
N: Number of (items)weight elements
W: Capacity of knapsack
Time Complexity: O(N*W)(Looping thro... |
c437aca066dbd263bd28fba9b62953461eff4bb0 | Neix20/MiniProject | /Trash/Person_2.py | 2,413 | 3.59375 | 4 | import cv2
import numpy as np
def remove_background(img, threshold):
"""
This method removes background from your image
:param img: cv2 image
:type img: np.array
:param threshold: threshold value for cv2.threshold
:type threshold: float
:return: RGBA image
:rtype: np.ndarray
""... |
f728d25f7ee2afeac14a37cad376f7a422b6544b | Eron9528/python-learning | /grammar/senior/iterable.py | 1,492 | 3.9375 | 4 | #
# 直接作用于for循环的数据类型有以下几种:
# 一类是集合数据类型,如list、tuple、dict、set、str等;
# 一类是generator,包括生成器和带yield的generator function。
# 这些可以直接作用于for循环的对象统称为可迭代对象:Iterable。
# 可以使用isinstance()判断一个对象是否是Iterable对象:
from collections.abc import Iterable
isinstance([], Iterable)
# 而生成器不但可以作用于for循环,还可以被next()函数不断调用并返回下一个值,
# 直到最后抛出StopIteration错误... |
280bc39bc28284d12595dd473f0699c332bb0968 | Eron9528/python-learning | /grammar/basic/if.py | 132 | 3.875 | 4 | age = 23
if age > 13:
print('ninde',' ', age)
else:
print('sss');
name = ['1','2','3']
for n in name:
print(n) |
d660544616126da5b9217b419db55c0aedfc1fc7 | fionnmcguire1/College-Programming | /Advanced-Security/RSA_SecurityAssignment/security_assignment.py | 1,349 | 3.734375 | 4 |
#Fionn Mcguire
#C13316356
#DT211/3
#Security assignment (RSA encryption)
import random
import math
"""340282366920938463463374607431768211456"""
def getting_public_keys() :
prime1 = random.randint(2, 340282366920938463463374607431768211456)
prime2 = random.randint(2, 340282366920938463463374607431768211456)
... |
c9bc59915700903ee3cb4df87acedfa883f4e6cd | fionnmcguire1/College-Programming | /Advanced-Security/DES_Encryption2.py | 4,307 | 3.515625 | 4 | #-*- coding: utf-8 -*-
'''
C13316356
Fionn Mcguire
Advanced Security
Lab 3
DES with ECB mode encryption & Decryption
'''
#importing the encrytption algorithm
from pyDes import *
import base64
#Q1
'''
Key : '12345678'
Plaintext : AAAABBBBAAAABBBB
Encrypted: '\x19\xffF7\xbb/\xe7|\x19\xffF7\xbb/\xe7|'
Ciphe... |
9512f7d0d18954002f22943e603216f222527471 | fionnmcguire1/College-Programming | /Advanced-Security/Caesar_and_Railfence.py | 1,030 | 3.984375 | 4 | #Name: Fionn Mcguire
#Course: DT211/4
#Student Number: C13316356
#Advanced Security Lab 1
#Date: 13/09/2016
def caesar(s,k,decrypt=False):
if decrypt: k= 26 - k
r=""
for i in s:
if (ord(i) >= 65 and ord(i) <= 90):
r += chr((ord(i) - 65 + k) % 26 + 65)
elif (ord(i) >... |
df4cb5ed09c7922d28796c367e1d5e2775eb5217 | amirzhangirbayev/Final_Project_CSS253 | /DataCollection/split_csv.py | 1,207 | 3.703125 | 4 | # SPLIT THE CSV FILE
# import the necessary libraries
import csv
import pandas as pd
# a list for all the steam ids
steamids_list = []
# enter the name of the file with all the stema ids
steamids_csv = input('Enter the steamids file in the csv format: ')
# enter the per number
per_number = int(input('Enter the numb... |
701b81e63adb89610499967e2c1c39e16c56a921 | PatrickDoolittle/PyMJ | /Main/pyMahjonMain.py | 2,754 | 3.5625 | 4 | import random
# Trying to create a game of Mahjong to test python skills
# Data structure for the tiles
# 1-9 in 3 suits, man, sou, and pinzu. Plus 3 dragons and 4 winds. 4 of each tile
class tile:
def __init__(self, suit, value, numid):
self.suit = suit
self.value = value
self.string = self.value + ' ' + self... |
99c8288d94702e548e03d757403e1b022582bea1 | san123i/CUNY | /Semester2/620-WebAnalytics/Week4/Assignment.py | 1,613 | 3.59375 | 4 | import requests
import nltk
import collections
import nltk, re, pprint
from nltk import word_tokenize
from nltk.corpus import stopwords
import urllib2
import operator
import pandas as pd
import matplotlib.pyplot as plt
from collections import Counter
#from urllib2 import request
url = "https://raw.githubusercontent.... |
2c88ddfe992b4fcba6c1e2d4d06bdfa64c485b9b | ErikAckzell/cagd | /homework6/DeCasteljau.py | 2,997 | 3.890625 | 4 | import scipy
from matplotlib import pyplot
from matplotlib import cm
from mpl_toolkits.mplot3d import Axes3D
import numpy as np
def deCasteljau(n, controlnet, U):
"""
Uses the de Casteljau Algorithm for triangle patches to evaluate the point on the surface at U.
:param n: Degree
:param controlnet: List... |
5e61c8288b73e25a29564389c893c216a7d111f0 | arthur-wfb/python-lessons | /model/Human.py | 346 | 3.703125 | 4 | class Human:
def __init__(self, name = "No name"):
self.name = name
self.happiness = 0
self.hungry = 0
def say(self, word):
print(self.name + " said: " + word)
def eat(self, food):
self.happiness += 5
self.hungry += food
def work(self, hours):
... |
be625b2c25c8014a5f6dee8805680e5d6b2942c7 | danielanatolie/Data-Science-Concepts | /conditionalProbability.py | 1,151 | 3.890625 | 4 | # Condtional Probability
# Data: People's purchases based on age
# 100,000 random individuals are produced and are randomly
# sorted to be in their 20s, 30s, 40s and so forth
random.seed(0)
#Total number of people in each age group
totals = (20:0, 30:0, 40:0, 50:0, 60:0, 70:0)
#Total number of things purchased in e... |
3cb797e9ad6e9f9a3bcd231f8e6bf87d383f2f39 | kennc05/Computing-GCSE | /Cousework A453/Task 1 - Currency Converter/currency v2.py | 1,466 | 3.546875 | 4 | file = open ('currency.txt', 'rt')
lines = file.readlines()
num=0
for line in lines:
splitline=line.split(' ')
num+=1
print('Option '+str(num)+': '+splitline[0])
option= int(input('What option would you like to choose: '))
amount= input('Enter the amount you want: ')
chosenline = lines[option]
currenc... |
2acc09e82eec6baad0377d5045d1714affd0f23a | kennc05/Computing-GCSE | /Cousework A453/Task 2 - Address book/address book v3.py | 974 | 3.859375 | 4 | #Version 4 of the code - Goes with task requirements with only search for Surname + Date
# This code works when searching for surname but not year!!!
from csv import reader
file= reader(open('address.csv'))
results=[]
rowselect = input('Please select what row you want to search 1)Surname 2)Date Of birth')
search... |
dae30b825ba3cfc285fdb037882922dead1d84bc | huanhuan18/test04 | /learn_python/字符串案例.py | 437 | 3.71875 | 4 | # user_email = 'nakelulu@itcast.cn'
# split 拆分 特别多
my_str = 'aa#b123#cc#dd#'
ret = my_str.split('#')
print(ret)
print(ret[0])
print(ret[3])
user_email = 'nakelulu@itcast.cn'
# 获得@字符串在user_email中出现的次数
char_count = user_email.count('@')
if char_count > 1:
print('你的邮箱不合法')
else:
result = user_emai... |
8c2ae6eaa09ff199ed5dcf711ef7ad9edad03d2a | huanhuan18/test04 | /learn_python/列表练习.py | 1,081 | 4.25 | 4 | # 一个学校,有3个办公室,现在有8个老师等待工位的分配,请编写程序完成随机的分配
import random
# 定义学校和办公室
school = [[], [], []]
def create_teachers():
"""创建老师列表"""
# 定义列表保存老师
teacher_list = []
index = 1
while index <= 8:
# 创建老师的名字
teacher_name = '老师' + str(index)
# 把老师装进列表里
teacher_list.ap... |
ff2525a07e6b548ad8decc3c4cce62223188e724 | huanhuan18/test04 | /learn_python/字典.py | 1,064 | 3.90625 | 4 | # 1.字典定义
# 字典注意点:
# 1.1字典的键不能重复,值是可以重复
# 1.2字典是非序列式容器,不支持索引,也不支持切片
def test01():
my_dict = {'name': 'Obama', 'age': 18, 'gender': '男', 101: 100}
print(my_dict['name'])
print(my_dict[101]) # key 关键字 value 值
my_dict['gender'] = '女'
print(my_dict)
def test02():
my_dict = {'n... |
5571891f4b5b8ebae7e873de6669cc7b9d7b5fea | lakshyajit165/DS_Coursera | /programs/Balanced_Parentheses/python/balanced_brackets_using_stack.py | 554 | 3.65625 | 4 | #python3
s = input()
stack = ['LK']
flag = 0
marker = 0
if(len(s) == 1 and s[0] in "()[]{}"):
print("1")
else:
for i in range(len(s)):
if(s[i] not in "({[]})"):
continue
elif(s[i] == '(' or s[i] == '{' or s[i] == '['):
stack.append(s[i])
print(i)
elif(... |
9686cb889247f42481db72c01407a13fa8f03a49 | ElTioLevi/mi_primer_programa | /adivina_numero.py | 1,726 | 4.15625 | 4 | number_to_guess = int((((((((2*5)/3)*8)/2)*7)-(8*3))))
print("El objetivo del juego es adivinar un número entre 1 y 100, tienes 5 intentos")
number_user = int(input("Adivina el número: "))
if number_user == number_to_guess:
print ("Has acertado!!!")
else:
if number_to_guess < number_user:
print("Has f... |
4fc7f1196bf5e9df355d8ce2da9c269165bac519 | heysushil/python-practice-set-two-with-3.8 | /8.1.operatores.py | 2,381 | 4.0625 | 4 | # Operatores:
'''
Hame follwoing type ke Operatores milte hain:
1. Arithmatic Op (Math ke sare signs) + - /
2. Assigment Op (=)
3. Comparison Op (< > ! ==)
4. Logical Op (And Or Not)
5. Identity Op (is)
6. Membership Op (in)
7. Bitwise Op (True/False)
1. Arithmatic Op (Math ke sare signs):
+(add)
-(sub)
... |
8bc5a7f7a560110a4626405bddebbd1d3352b700 | heysushil/python-practice-set-two-with-3.8 | /9.list.py | 3,546 | 4.03125 | 4 | '''
Python Collections:
Ye 4 datatypes multiple values ko hold ya store karne ki capacity rakte hain. Is liye hi inhe collection bhi kha jata hai.
Example: Abhi tak humne int,float,comple aur set datatype use kiya but ye sabhi ek time pe ek value ko hi store kar sakte hain.
Isliye jab hame ek sath multiple values ko... |
a0d5767222865e698f097d2bf816c4751078275d | heysushil/python-practice-set-two-with-3.8 | /24.date_time.py | 712 | 3.890625 | 4 | # datetime
import datetime as d
mydate = d.date(2020, 11, 2)
print('\n mydate: ', mydate)
print('\nmydate.today(): ', mydate.today())
datedetail = '''
Todyas date: {}
Current Year: {}
Current Month: {}
'''.format(mydate.today(), mydate.today().year, mydate.today().month)
curetndatetime = d.datetime(2020, 11, 2)
pr... |
6d5b4c9c248fa3dc308e1f267e9033c855db95cf | Pogozhelskaya/pctm | /src/utils.py | 361 | 4.03125 | 4 | """ Useful utils module """
def is_prime(n: int) -> bool:
"""
Checks if a number n is prime
:param n: Integer number to test
:return: Boolean value - True if n is prime, else False
"""
if n < 2:
return False
i: int = 2
while i * i <= n:
if n % i == 0:
retu... |
f9a0d1cb85a5d77911206b7931094f97a8d2fe67 | JShanmukhRao/Blockchain | /Blockchain.py | 3,469 | 3.515625 | 4 | # Module 1 Create a Blockchain
import datetime
import json
import hashlib
from flask import Flask , jsonify
# Building Blockchain
class Blockchain:
def __init__(self):
self.chain=[]
self.create_block(proof=1,previous_hash='0')
def create_block(self,proof,previous_hash):... |
9de22a3e6b395267ffd011d8ebb1b74cfc4f8dca | TechNaturalist/MultiAgentEscape | /coalition.py | 4,067 | 3.625 | 4 | """A class to handle coalitions between the guards
Written by: Max Clark, Nathan Holst
"""
import random
from typing import Dict, List
from guard_agent import GuardAgent
colors = {
"WHITE": (255, 255, 255),
"BLACK": (0, 0, 0),
"GREEN": (0, 255, 0),
"DARKGREEN": (0, 155, 0),
"DARKGRAY": (40... |
75e5c159bcb924c21ede7c886c98f9e90986f654 | Hans-Bananendans/CubeSat-Mission-Planner | /opstate.py | 1,371 | 3.640625 | 4 | """
opstate.py
"Specification of the OpState class."
@author: Johan Monster (https://github.com/Hans-Bananendans/)
"""
class OpState:
"""This class represents a separate operational state, and can be used
to calculate used power values and separate these by channel."""
def __init__(self, device_powe... |
97174dfe60fdb0b7415ba87061573204d41490bc | rosa637033/OOAD_project_2 | /Animal.py | 597 | 4.15625 | 4 | from interface import move
class Animal:
#Constructor
def __init__(self, name, move:move):
self.name = name
self._move = move
# any move method that is in class move
def setMove(self, move) -> move:
self._move = move
# This is where strategy pattern is implemented.
def ... |
b2a54172fb136c2298ff451de82d8038872597ca | DouglasKosvoski/URI | /1141 - 1150/1142.py | 116 | 3.5 | 4 | n = int(input())
a, b, c = 1, 2, 3
for i in range(n):
print(a, b, c, 'PUM')
a += 4
b += 4
c += 4
|
ee807dfee965cbc246a5296115068d88d6abecfb | DouglasKosvoski/URI | /1001 - 1020/1009.py | 153 | 3.5625 | 4 | name = str(input())
salary = float(input())
sales = float(input())
total_salary = salary + ((15/100) * sales)
print('TOTAL = R$ %.2f'%(total_salary))
|
2b90255fb4af8f07a09e61d595fcdc0addb5a9a9 | DouglasKosvoski/URI | /1131 - 1140/1133.py | 135 | 3.75 | 4 | x = int(input())
y = int(input())
for i in range(min(x,y)+1, max(x,y)):
if i % 5 == 2 or i % 5 == 3 and x != y:
print(i)
|
363d2410efc59f9dc5536bbd714290d87a1ad1fe | DouglasKosvoski/URI | /1001 - 1020/1008.py | 162 | 3.75 | 4 | NUMBER = int(input())
HOURS = int(input())
VALUE = float(input())
SALARY = HOURS * VALUE
print('NUMBER = %d'%(NUMBER))
print('SALARY = U$ %.2f'%(SALARY))
|
37ae37043038181bda2bb66f83342301611cd9ac | DouglasKosvoski/URI | /1171 - 1180/1175.py | 165 | 3.65625 | 4 | lista = []
for i in range(20):
n = int(input())
lista.append(n)
lista.reverse()
for i in range(len(lista)):
print('N[{0}] = {1}'.format(i, lista[i]))
|
785deab7e175755c7cbe84b41eda2b0f6b8dfe39 | accuLucca/Curso-Introducao-a-Ciencia-da-Computacao-com-Python-Parte-1 | /Semana 2/imprimedezenas.py | 148 | 4.0625 | 4 | num=int(input("Insira um numero inteiro: "))
unidade=num%10
unidade=(num-unidade)/10
dezena=unidade%10
print("O dígito das dezenas é",int(dezena)) |
c6ee66d4918ff2e20402ec9aa17b589ee8da6453 | accuLucca/Curso-Introducao-a-Ciencia-da-Computacao-com-Python-Parte-1 | /Semana 2/Contasegundos.py | 300 | 3.5 | 4 | segundos= input("Por favor insira o total de segundos para converter: ")
totalSegundos=int(segundos)
horas= totalSegundos // 3600
segRestantes = totalSegundos % 3600
minutos = segRestantes // 60
segRestantes2= segRestantes % 60
print(horas,"horas, ",minutos,"minutos e ",segRestantes2, "segundos. ") |
8aa4034d804f96ae79caa7ebd375f383ca4fee1e | jebbica/lilTurtGame | /bonusTurt.py | 5,981 | 3.890625 | 4 | import turtle
import random
import time
print('--------------------------------------------')
races = int(input("How many races u wanna see bruv? "))
print('--------------------------------------------')
win1 = 0
win2 = 0
colors = ['blue','green','pink','purple','brown','yellow','gold','turquoise']
def data(num, ... |
55571b0cbb00e6586886d0f907486ebcc50533f6 | junes7/pythonprac | /class_inheritance.py | 3,696 | 3.609375 | 4 | # 사람 클래스로 학생 클래스 만들기
class Person:
def greeting(self):
print('안녕하세요.')
class Student(Person):
def study(self):
print('공부하기')
james = Student()
james.greeting() # 안녕하세요.: 기반 클래스 Person의 메서드 호출
james.study() # 공부하기: 파생 클래스 Student에 추가한 study 메서드
# 포함 관계
class Person:
def greeting... |
d5e73f709825cc160ac2688faafc2a57ce2875ca | junes7/pythonprac | /generator.py | 1,290 | 4.03125 | 4 | # 제너레이터 만들기
def number_generator(stop):
n = 0 # 숫자는 0부터 시작
while n < stop: # 현재 숫자가 반복을 끝낼 숫자보다 작을 때 반복
yield n # 현재 숫자를 바깥으로 전달
n += 1 # 현재 숫자를 증가시킴
for i in number_generator(3):
print(i)
# yield에서 함수 호출하기
def upper_generator(x):
for i in x:
yie... |
9f14f48a51cc8a7d8c9b6907e520abab02e39620 | junes7/pythonprac | /coroutine.py | 3,384 | 3.5625 | 4 | # 코루틴 사용하기
def add(a, b):
c = a + b # add 함수가 끝나면 변수와 계산식은 사라짐
print(c)
print('add 함수')
def calc():
add(1, 2) # add 함수가 끝나면 다시 calc 함수로 돌아옴
print('calc 함수')
calc()
# 코루틴에 값 보내기
def number_coroutine():
while True: # 코루틴을 계속 유지하기 위해 무한 루프 사용
x = (yield) # 코루틴 바깥에서 값을 받... |
1fbe4faa394a1d780010c2363e0395a7f5de2ea2 | ezekiel222/Matematica | /FuncCuadratica/func_cuadratica.py | 2,975 | 3.609375 | 4 | import os
from FuncCuadratica.calc_func_cuadratica import *
# Visual de la parte de Funcion Cuadratica.
def polinomio2():
while True:
try:
a = float(input("\nPrimer valor (a): "))
b = float(input("Segundo valor (b): "))
c = float(input("Tercer valor (c): "))
... |
fb05fad10a27e03c50ef987443726e2acd11d49a | adamchainz/workshop-concurrency-and-parallelism | /ex4_big_o.py | 777 | 4.125 | 4 | from __future__ import annotations
def add_numbers(a: int, b: int) -> int:
return a + b
# TODO: time complexity is: O(_)
def add_lists(a: list[int], b: list[int]) -> list[int]:
return a + b
# TODO: time complexity is O(_)
# where n = total length of lists a and b
def unique_items(items: list[i... |
5207495ad7699318b8650d2f61272995fceecbc4 | aruncancode/wshsprojects | /002_AddingMachine/adding_machine.py | 3,062 | 4.03125 | 4 | from tkinter import *
def add():
# retrieves the value from the input box and assigns it to a variable
number1 = float(inpNumber1.get())
number2 = float(inpNumber2.get())
result = number1 + number2
# assigns the result variable to the text variable
lblResult.config(text=result)
def subtracti... |
c1f32f2060251d7e5b4349eafb98023bcaece3a0 | suryaaathhi/python | /vowel.py | 245 | 3.96875 | 4 | #enter the variable
variable=(input())
l=variable.isalpha()
if(l==True):
if( variable=="a" or variable=="e" or variable=="i" or variable=="o" or variable=="u"):
print("Vowel")
else:
print("Consonant")
else:
print("invalid")
|
b848f777182c2bce5c0a87a38b14608b39cc45fb | satishjasthi/CodeWar-Kata-s | /FindTheOddInt.py | 606 | 4.09375 | 4 | #Details:Given an array, find the int that appears an odd number of times.
#There will always be only one integer that appears an odd number of times.
#my first attempt code :)
def find_it(l):
return([number for number in l if (l.count(number)%2 != 0)][0])
#a = find_it([1,1,5,3,3,6,5,3,6,6,6]);print(a)
#other amaz... |
eb667a28193f5c61ffc489d15285584d0a34ae13 | D10D3/Battleship | /battleship.py | 10,098 | 3.90625 | 4 | import os
import random
os.system('cls')
""" Single Player BattleShip Game Info:
Boards have 100 cells in 10 rows numbered A0 through J9
(chose to use 0-9 instead of traditional 1-10 to simplify code)
Cells will have 3 states:
"-" = empty or unknown
"O" = filled
"X" = bombed
"@" = known hit
players h... |
cc86f40a36fb6e74dae178fa6e1fd7324c17703e | Matt-Zimmer/week-3-lab-Matt-Zimmer | /week-03-lab-Matt-Zimmer.py | 2,807 | 3.875 | 4 | ######################################
# IT 2750 - Spring 2021 - Week 3 Lab #
# Password Cracking #
# Author: Matt Zimmer #
# Student: S00646766 #
######################################
############################################
#### SCROLL DOWN #####################... |
eafef01f598c0b42b79646000b0e6355d56ded43 | keelymeyers/SI206-Project1 | /206project1.py | 5,635 | 3.96875 | 4 | import os
import csv
import filecmp
## Referenced code from SI 106 textbook 'Programs, Information, and People' by Paul Resnick to complete this project
def getData(file):
#Input: file name
#Ouput: return a list of dictionary objects where
#the keys will come from the first row in the data.
#Note: The column heading... |
2d69346d0d83057fd18eb28f51e9135b16f1a87f | juelianzhiren/python_demo | /alice.py | 236 | 3.640625 | 4 | filename="alice.txt";
try:
with open(filename) as f_obj:
contents = f_obj.read();
except FileNotFoundError:
msg = "Sorry, the file " + filename + " doesn't exist";
print(msg);
title = "Alice in Wonderland";
print(title.split());
|
9d2496045c0476bf19d4b3ce8f65894093f5083d | ynadji/scrape | /scrape-basic | 638 | 3.65625 | 4 | #!/usr/bin/env python
#
# Basic webscraper. Given a URL and anchor text, find
# print all HREF links to the found anchor tags.
#
# Usage: scrape-basic http://www.usenix.org/events/sec10/tech/ "Full paper"
#
# returns:
#
# http://www.usenix.org/events/sec10/tech/full_papers/Sehr.pdf
# ...
# http://www.usenix.org/events/... |
e775866737d6da83a8311e5eaa45df7dcee199ea | vigneshrajmohan/CharterBot | /CharterBot.py | 3,356 | 3.765625 | 4 | # PyChat 2K17
import random
import time
def start():
pass
def end():
pass
def confirm(question):
while True:
answer = input(question + " (y/n)")
answer = answer.lower()
if answer in ["y" , "yes", "yup"]:
return True
elif answer in ["n", "no", "nope"]:
... |
4819a44f44262619c27320ce0fab50351f5039d6 | urmomlol980034/GCALC-V.2 | /square.py | 419 | 3.796875 | 4 | from os import system, name
from time import sleep
from math import sqrt
def clear():
if name == 'nt':
_ = system('cls')
else:
_ = system('clear')
def square():
sleep(1)
clear()
print('You have chosen: Square Root')
f = eval(input('What number do you want to be square rooted?\n> '))
equ... |
0d9f1324ec8c52ff6f2639439d705e11f65a35be | prah23/Stocker | /ML/scraping/losers/daily_top_losers.py | 943 | 3.515625 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Jul 29 23:52:33 2020
@author: pranjal27bhardwaj
"""
# This function will give the worst performing stocks of the day
import requests
from bs4 import BeautifulSoup
import pandas as pd
import matplotlib.pyplot as plt
def daily_losers():
dfs = pd.read... |
d6aa861af8b2d53326a1dc779682273bb09ac52c | rlgustavo/DarkWord | /Dark-world/Dark_World_S1.py | 26,383 | 3.546875 | 4 | """
Grupo 4
Indice:
1. Definição de cores
2. Abertura do display, considerando altura e largura
3. Iniciado a função Clock
4. Carregando para a memória as músicas presentes./
definido a função para o som das teclas
5. Carregando imagens para memória/redimensionando B1,
referente a imagens, de setas e B3, ... |
ef8e05fe07b951ec8d95b0c64491616b227eb0a2 | bmanandhar/python-playground | /b.py | 233 | 3.734375 | 4 | n = 100
for i in range(100):
i = i + 2
print(i)
arr = [1,2,3,4,5]
for i in range(len(arr)):
for j in range(5):
print('i is :-', i)
print('j is: ', j)
x = [7,2,4,1,5]
for i in range(len(x) - 1):
for |
e0241ab69dbb1a40c43e0db5fdcd2f0cc545100b | BOURGUITSamuel/NmapScanner_Project | /Scanner.py | 2,154 | 3.71875 | 4 | # coding: utf-8
import sys
import nmap
import re
import time
# Using the nmap port scanner.
scanner = nmap.PortScanner()
# Regular Expression Pattern to recognise IPv4 addresses.
ip_add_pattern = re.compile("^(?:[0-9]{1,3}\.){3}[0-9]{1,3}$")
# Display the program banner.
print("-------------------")
print("Nmap pyt... |
21791a22f0b353d69cf2f6ce03dff7a488cb2bbc | lazorfuzz/gameofde_rest | /ciphers/benchmark.py | 1,410 | 3.53125 | 4 | from Dictionaries import LanguageTrie, trie_search, dictionarylookup
import time
class Color:
PURPLE = '\033[95m'
CYAN = '\033[96m'
DARKCYAN = '\033[36m'
BLUE = '\033[94m'
GREEN = '\033[92m'
YELLOW = '\033[93m'
RED = '\033[91m'
BOLD = '\033[1m'
UNDERLINE = '\033[4m'
END = '\033[0m'
def t... |
159d935411dd314c544af263dc1edf7e5d9f8238 | ztoolson/Intro-to-Algorithms-and-Data-Structures | /LinkedList.py | 4,457 | 4.3125 | 4 | class List:
"""
Implementation of a Singely Linked List.
"""
def __init__(self):
""" (List) -> NoneType
Initialize the head and tail of the list
"""
self.head = None
self.tail = None
def __str__(self):
""" (List) -> str
"""
re... |
17911c3e3c9f130caeeddf9dc571068a25d7bf4b | ArnaudParan/stage_scientifique | /gestion_doonees/operations_vect.py | 1,890 | 3.5625 | 4 | #!/usr/bin/python3.4
#-*-coding:utf-8-*
from donnees import *
import math as Math
##
# @brief crée la moyenne d'un tableau
# @param tab le tableau qu'on moyenne
# @return la moyenne
def moy (tab) :
taille_tab = len (tab)
moyenne = 0.
for elem in tab :
moyenne += float(elem) / float(taille_tab)
return moyenne
d... |
177f4d54814f1f899d2ea119454b0d692dfff382 | AphelionGroup/Examples | /SampleBots/WeatherBot/getWeather.py | 2,199 | 3.578125 | 4 | import argparse
from flask import Flask
from flask_restful import Resource, Api, reqparse
import json
import urllib2
class getWeather(Resource):
def forecast(self, city):
answer = None
# calls the weather API and loads the response
res = urllib2.urlopen(weather_today + city)
data ... |
b13aa117b4f2bd0f0a04ce3b04ff9950c239a7f6 | wenjie711/Leetcode | /python/021_merge_2_sorted_lists.py | 909 | 3.953125 | 4 | #!/usr/bin/env python
#coding: utf-8
# Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
# @param {ListNode} l1
# @param {ListNode} l2
# @return {ListNode}
def mergeTwoLists(self, l1, l2):
l = ListNode(0)
... |
9cd76f9d4d60443cefc3cf495b67cade9ee06fba | wenjie711/Leetcode | /python/070_climbing_stairs.py | 538 | 3.9375 | 4 | #!/usr/bin/env python
#coding: utf-8
class Solution:
# @param {integer} n
# @return {integer}
def climbStairs(self, n):
c = n / 2
r = 0
for i in range(0, c + 1):
j = (n - i * 2) + i
r += self.C(i,j)
return r
def C(self, i, j):
return self.... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.