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
3fa0e6d1bdde0a4086107ec9e84d37a3a1f78d73
ColgateLeoAscenzi/COMPUTERSCIENCE101
/HOMEWORK/hw2_volcano.py
1,104
4.03125
4
# ---------------------------------------------------------- # HW 2 PROGRAM 4 # ---------------------------------------------------------- # Name: Leo Ascenzi # Time Spent: 1 # ---------------------------------------------------------- # Write your program for the volcano pattern here import time #sets up loo...
01a31344d5f0af270c71baa134890070081a1d5c
ColgateLeoAscenzi/COMPUTERSCIENCE101
/LAB/Lab01_challenge.py
898
4.28125
4
import time import random #Sets up the human like AI, and asks a random question every time AI = random.randint(1,3) if AI == 1: print "Please type a number with a decimal!" elif AI == 2: print "Give me a decimal number please!" elif AI == 3: print "Please enter a decimal number!" #defines t...
bc9b0e89b907507970b187a44d0bfc3ecf2d4142
ColgateLeoAscenzi/COMPUTERSCIENCE101
/LAB/lab03_vowels.py
273
4.21875
4
#Leo Ascenzi #sets up empty string ohne_vowels = "" #gets response resp = str(raw_input("Enter a message: ")) #for loop to check if character is in a string for char in resp: if char not in "aeiouAEIOU": ohne_vowels += char print ohne_vowels
adb83bcac5c4340b2cf00a63bcb7fb2896981103
ColgateLeoAscenzi/COMPUTERSCIENCE101
/LAB/lab02_squares.py.py
701
3.75
4
#Leo Ascenzi import turtle import time times = int(raw_input("Please enter a number of squares you want for your spiral: ")) #ss stands for spiraly square ss = turtle.Turtle() L = 10 ss.pencolor("orchid") squares = times*4 count = 0 if 0<times<25: ss.speed("normal") for i in range(squares): ...
676f4845dc145feee1be508213721e26f2e55b2a
ColgateLeoAscenzi/COMPUTERSCIENCE101
/HOMEWORK/hw3_leap.py
2,055
4.15625
4
# ---------------------------------------------------------- # -------- PROGRAM 3 --------- # ---------------------------------------------------------- # ---------------------------------------------------------- # Please answer these questions after having completed this # program # ---...
7004bc9b49acc1a75ac18e448c2256cbec808cf4
CodyPerdew/TireDegredation
/tirescript.py
1,350
4.15625
4
#This is a simple depreciation calculator for use in racing simulations #Users will note their tire % after 1 lap of testing, this lets us anticipate #how much any given tire will degrade in one lap. #From there the depreciation is calculated. sst=100 #Set tire life to 100% st=100 mt=100 ht=100 p...
a3f4a8d56272248fe4acdda876922deb6de03491
San4stim/Python_6_Homeworks
/lesson_9/lesson_9_1.py
659
3.546875
4
import math number_of_flat = int(input('Введите номер квартиры \n')) etazh = int(input('Введи количество этажей \n')) kol_vo_kvartir = int(input('Введи количество квартир на этаже \n')) kvartir_v_padike = etazh * kol_vo_kvartir if number_of_flat % kvartir_v_padike ==0: nomer_padika = number_of_flat // kvartir_v_pad...
8204299aaf429a739a01539f53a94210c78006a9
AmitCharran/LearningPython
/first.py
7,651
4.125
4
print("This line will be printed") x = 1 if x == 1: print("x is 1") print("Goodbye, World") myInt = 7 print('int test', myInt) print('also use this ' + str(myInt)) myFloat = 7.0 print('float test ' + str(myFloat)) myString = 'string' myString2 = "string2" print("String test" + " " + myString + " " + myString2...
9919415bc66a1062c954f7cdde48df5901224a2a
Jason0409/cvxpy
/linear_programming.py
480
3.578125
4
import cvxpy as cvx # import numpy as np # Problem data. n = 4 A = [1, 2, 3, 4] m1 = [1, 1, 1, 1] m2 = [1, -1, 1, -1] # Construct the problem. x = cvx.Variable(n) objective = cvx.Minimize(A*x) constraints = [0 <= x, m1*x == 1, m2*x == 0] prob = cvx.Problem(objective, constraints) # The optimal objective value is ret...
d4345fbbeadafca2553d57b51b6b244bab0cdb31
devina-bhattacharyya/daily-coding-problem
/solutions/alternative_problem_077.py
1,055
3.84375
4
# Problem 77 # # This problem was asked by Snapchat. # # Given a list of possibly overlapping intervals, return a new list of intervals where all overlapping intervals have been merged. # # The input list is not necessarily ordered in any way. # # For example, given [(1, 3), (5, 8), (4, 10), (20, 25)], you should retur...
e954a1ea02dbb3c0efc43db26b973f9a069ec92f
cursoweb/python-archivos
/Gonzalo Grassi/wordcount.py
4,069
4.28125
4
#!/usr/bin/python -tt # -*- coding: utf-8 -*- # Copyright 2010 Google Inc. # Licensed under the Apache License, Version 2.0 # http://www.apache.org/licenses/LICENSE-2.0 # Google's Python Class # http://code.google.com/edu/languages/google-python-class/ """Wordcount exercise Google's Python class La función main() d...
7bd3cd9699ae98046019347c12138fc1486788d9
k3llymariee/oo-melons
/melons.py
2,415
3.875
4
from random import randint from time import localtime """Classes for melon orders.""" class AbstractMelonOrder(): """An abstract base class that other Melon Order inherit from""" def __init__ (self, species, qty, country_code, order_type, tax): self.species = species self.qty = qty s...
e93589ee1564591a3baa32f82f8995038ce98b36
asynched/RSA-Implementation
/src/rsa/encrypt.py
1,308
4
4
import traceback def encrypt(message: str, key: list) -> str: """Encrypts a message using the public keys Args: message (str): Message to be encrypted key (list): Public key to encrypt the message with Raises: Exception: Raises an exception if the encryption process fails Ret...
f7df9b20ba1dcc224cb31aa03d6d3c8cb144834c
HolyPi/LeetCode
/Smallernumbers.py
1,108
3.78125
4
#Given the array nums, for each nums[i] find out how many numbers in the array are smaller than it. That is, for each nums[i] you have to count the number of valid j's such that j != i and nums[j] < nums[i]. # 1. Restate the problem # Using an array of integers, remove the duplicates so they appear only once, and retur...
ca1f0e03618b285cebc24e19dd263f19f5def949
Elchin/PermaData
/replace_text.py
2,851
3.515625
4
""" String replace for column values. """ import csv import getopt import sys def replace_text(ggd361_csv, out_file, to_replace, with_replace): """ Replace text within field with new text. :param ggd361_csv: input CSV file :param out_file: output CSV file :param to_replace: substring within field t...
b38efc90e860c6f5366f603b6cbc85518a929ad2
Gujaratigirl/Python-Challenge
/PyBank/MainBank.py
3,285
3.84375
4
# module for PC/Mac file open import os # Module for reading cvs files import csv #start out empty list bank_date = [] bank_change = 0 bank_change_list1 = [] bank_change_list2 = [] bank_change_new=[] previous_bank_value=0 #loop thorough a list? HOw can I do this?? max_value=0 min_value=0 bankcsv = os.path.join('..'...
f0afa65944197e58bad3e76686cef9c2813ab16d
chrismlee26/chatbot
/sample.py
2,521
4.34375
4
# This will give you access to the random module or library. # choice() will randomly return an element in a list. # Read more: https://pynative.com/python-random-choice/ from random import choice #combine functions and conditionals to get a response from the bot def get_mood_bot_response(user_response): #add some...
30a7a05b2c37681fe0e1d187c98edf6a3c38da27
sseanik/Document-Reconstructor
/scanned/extractShreds.py
6,376
3.65625
4
import cv2 import numpy as np def viewImage(image): # Helper function to display an image in a small window cv2.namedWindow('Display', cv2.WINDOW_NORMAL) cv2.imshow('Display', image) cv2.waitKey(0) cv2.destroyAllWindows() # https://stackoverflow.com/questions/47899132/edge-detection-on-colored-b...
c96676ff67e902f19f39c486d1c09344b5991116
inewhart/E01a-Control-Structues
/main10.py
2,305
4.09375
4
#!/usr/bin/env python3 import sys, utils, random # import the modules we will need utils.check_version((3,7)) # make sure we are running at least Python 3.7 utils.clear() # clear the screen print('Greetings!') # prints Greetings colors = ['red','orange','yellow','green','blu...
e361bf7eb084aa538eec3312b4a62cb77011ce72
rsakib15/Python-Study
/loop.py
64
3.546875
4
li = [1, 2, 3, 4, 5, 3] for i in range(len(li)): print(li[i])
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...