blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
35ba71239600db9e75aad47d9e18a908f403dfee
marquesarthur/programming_problems
/interviewbit/interviewbit/codersbit/playlist.py
1,327
3.703125
4
def is_old_box(box): aux = box.replace("[", "") aux = aux.replace("]", "") aux = aux.split(" ", 1)[1] return not aux.replace(" ", "").isdigit() def compare_boxes(a, b): prefix_a = a.split(" ", 1)[0] prefix_b = b.split(" ", 1)[0] suffix_a = a.split(" ", 1)[1] suffix_b = b.split(" ", 1)...
e3d185002b739f2e8d184d8a0c4bf14bdaab913a
marquesarthur/programming_problems
/leetcode/amazon/2021/shopkeeper_items.py
811
3.765625
4
def find_discount_prices(val): stack = [] res = [0 for _ in range(len(val))] for i in range(len(val) - 1, -1, -1): current = val[i] while stack and stack[-1] > current: stack.pop() # means there is no value greater than current value res[i] = -1 if not stack else stack...
86f0fc075641a61d4df5108f5586b6b7cac07192
marquesarthur/programming_problems
/interviewbit/interviewbit/linked_lists/list_cycle_optimal.py
2,349
3.890625
4
# Definition for singly-linked list. # If you detect a cycle, the meeting point is definitely a point within the cycle. # # Can you determine the size of the cycle ? ( Easy ) Let the size be k. # Fix one pointer on the head, and another pointer to kth node from head. # Now move them simulataneously one step at a time. ...
7fe7714653dbd875cbd6668c021f6d09042ee0ae
marquesarthur/programming_problems
/interviewbit/interviewbit/arrays/n3_repeated_number.py
1,267
3.625
4
class Solution: # @param A : tuple of integers # @return an integer def repeatedNumber(self, A): # This is based on Majority Element algorithm first = max(A) + 2 # will guarantee that I have an element outside the array second = max(A) + 2 # will guarantee that I have an element ...
71aecdd5c1709a01a7b5bfd865bdeaa4b4132ac5
marquesarthur/programming_problems
/interviewbit/interviewbit/backtracking/permutations.py
772
3.671875
4
class Solution: # @param A : list of integers # @return a list of list of integers def permute(self, A): if not A: return [] if len(A) == 1: return [A] # remove index i from array # get all permutations for subarrays of i # re-insert i in all...
1ec14322eb2ce51023d31809b755c9b8cec4f106
liona24/snipppets
/tcp-proxy.py
2,916
3.796875
4
"""A simple TCP-Proxy. This is a snippet to create a simple TCP proxy server which can accept multiple connections and forward them to a single remote address. """ import socket import time import select import sys BUFF_SIZE = 4096 DELAY = 0.0001 BIND_PORT = 9999 def pp_peername(peername): """Prettily format ...
66cf5d99cd2e4a5edd36abf1273dfe3d91fa8a42
Jamaliela/Breaking-Bad-Ciphers
/Breaking Bad Ciphers _ small one.py
1,115
3.890625
4
###################################################################### # Author: Elaheh Jamali # Username: Jamalie # Assignment: A4: Breaking Bad Ciphers # # Purpose: Thia assignment explores the process for cracking different ciphers. # # Acknowledgement: Dr. Maiti and Emely Alfaro Zavala for giving me hints ...
6e7e3fa09b55a28e123a53b30d64409185cdbf85
akbugaekrem/pythonforeverbody
/9_4Assignment.py
513
3.546875
4
file =input("Enter file:") if len(file) < 1: name = "mbox-short.txt" fh = open(name) from_lines = [] emails = {} for line in fh: line = line.rstrip() if line.find('From ') == 0: line = line.split(' ') email = line[1] if email not in emails: emails[email] = 1 e...
59b20a5addf6be9207030c76d8c35b0d59460b29
alewis3/Computer-Security
/caesarShiftEncoderDecoderBreaker.py
14,866
4.3125
4
# Amanda Lewis # Computer Security and privacy # COSC 3325 - Dr. Shebaro # Assignment 1 # constant variables for the plain text file and cipher text file ENCRYPT_PATH = "plaintext.txt" DECRYPT_PATH = "ciphertext.txt" #main menu def main(): print("Welcome to the Caesar Cipher Encryptor/Decryptor!\n") # ch...
4059045ec53a9a61da8a3b1d05cde8db27f454ea
erenyt12/ejercicio-de-la-clase-4
/ejercicio_5.py
1,116
4.1875
4
""" Ejercicio 5: Realizar una función asociar() que reciba como parametro dos listas de la misma longitud de elementos y devuelva un diccionario de pares clave-valor asociando cada elemento de ambas listas segun su indice. Ej: empleado = ['Juli', 'Carlos', 'Roberto', 'Marta'] ...
e20063d0ba8377d5ec868f5906825ace288116ad
chuzhinoves/HW7_Python_DevOps
/2.py
1,487
4.125
4
""" 2. Реализовать проект расчета суммарного расхода ткани на производство одежды. Основная сущность (класс) этого проекта — одежда, которая может иметь определенное название. К типам одежды в этом проекте относятся пальто и костюм. У этих типов одежды существуют параметры: размер (для пальто) и рост (для костюма). Э...
d6bf156bd0e9728de14b3010d9c663b2fa38e245
gcharade00/programs-hacktoberfest
/append.py
192
4.15625
4
# animals list animals = ['cat', 'dog', 'rabbit'] # 'guinea pig' is appended to the animals list animals.append('guinea pig') # Updated animals list print('Updated animals list: ', animals)
75141dbd0657a7c07f5a4821190f19f60ab5efa0
AmuthaRavichandran/set-1
/evod.py
94
4.125
4
num=int(raw_input("enter a number: ")) if(num%2==0): print("even no") else: print("odd no")
119e2bdd963f638f2c371c7ee91842285b4a81ca
drussell1974/a-level
/line_profiler/graph_traversal.py
2,083
4.15625
4
""" DEPTH TRAVERSAL IN PYTHON """ def depth_traversal(graph, root_key): """ Pushes each vertex onto the stack, and after it has visited each vertex it pops it off the stack """ # track which edges of each vertex have been visited visited = [] # initialise the stack, pushing the root ve...
a7749f8946646464778aead7a7f017efab62d402
drussell1974/a-level
/stacks and queues/arrays.py
1,118
3.984375
4
""" A mock static array as python only has lists """ class StaticArray: def __init__(self, fixed_size): # create a static array self._lst = [] for i in range(fixed_size): self._lst.append(None) # the number of items with a non-Null value self._virtual_length = 0 ...
61881fca68d8ac2073597cf670c16db38d34fda8
kyooryoo/Data-Science-with-Python
/9_ConditionalP.py
1,814
3.828125
4
# fake data on how much stuff people purchase given their age range. # 100,000 random people randomly in 20's, 30's, 40's, 50's, 60's, and 70's. from numpy import random random.seed(0) # "totals" contains the total number of people in each age group. totals = {20:0, 30:0, 40:0, 50:0, 60:0, 70:0} # "purchases" is the ...
91db4ce7270ccccb12a4be9b6a169bdff6943286
hqt286/Jump
/jump/eventservice/dao/BaseDAO.py
597
3.53125
4
from abc import ABC, abstractmethod class BaseDAO(ABC): """ This interface class is set up a basic methods for each DAO class """ @abstractmethod def getById(self, id): pass @abstractmethod def removeById(self, id): pass @abstractmethod def create(self, item): ...
4e31c449d0b93a3c5a44effb441d9365039cba4b
ClimateImpactLab/downscaleCMIP6
/notebooks/qdm_validation/plotting.py
14,617
3.671875
4
import matplotlib.pyplot as plt import numpy as np def quantile_compare(xds, yds, kind, grouper='time', quantiles=[.01, .05, .25, .5, .75, .95, .99]): """ Takes the difference or the ratio of quantiles of the input datasets after grouping. `yds - xds` or `yds/xds`, Parameters ...
429d83e136bd3f1a8ff71e2f9745490d414adc1d
SobrancelhaDoDragao/Exercicio-De-Programacao
/Exercicios-Python/Basico/Exercicios/exercicio39.py
718
4.03125
4
# Faça um programa que leia o ano de nascimento de um jovem e informa, # de acordo com sua idade: # Se ele ainda vai se alistar ao serviço militar # Se é a hora de se alistar # Se já passou do tempo do alistamento # Seu programa também deverá mostrar o tempo que falta ou que passou do prazo from datetime import date...
47f1405a4a7f386f35abdd8950fc0d09ab8990b9
SobrancelhaDoDragao/Exercicio-De-Programacao
/Exercicios-Python/Basico/Exercicios/exercicio59.py
1,856
4.53125
5
# Crie um programa que leia dois valores e mostre um menu na tela: # [1]somar # [2]Multiplicar # [3]Maior # [4]Novos Números # [5]Sair do programa # Seu programa deverá realizar a operação solicitada em cada caso print("Digite dois numero: ") numero1 = int(input("1º: ")) numero2 = int(input("2º: ")) escolha = 0 pri...
7630ad26cd0235c60f40ebdb813464b004401651
SobrancelhaDoDragao/Exercicio-De-Programacao
/Exercicios-Python/Basico/Exercicios/exercicio23.py
255
3.890625
4
#Faça um programa que leia um número de 0 a 9999 e mostre na tela cada um dos dígitos separados. #Ex: #Digite um número:1834 # #unidade : 4 #dezena : 3 #centena: 8 #milhar: 1 numero = input("Digite um numero: ") numero = numero.split() print(numero)
3965c6a7187ac2191b3e38d000571d239d72c735
SobrancelhaDoDragao/Exercicio-De-Programacao
/Exercicios-Python/Basico/Exercicios/exercicio48.py
515
4.09375
4
# Faça um programa que calcule a soma entre todos os números # ímpares que são múltipla de três e que se encontram no intervalo de # 1 até 500 contador = 0 for numeros in range(1, 501): # Verificando se o numero é impar if numeros % 2 != 0: # Verificando se é multiplo de 3 if numeros % 3 == 0: ...
9de531a817e70ca79aa72afe540d08948ffb28b8
SobrancelhaDoDragao/Exercicio-De-Programacao
/Exercicios-Python/Basico/Exercicios/exercicio38.py
437
3.90625
4
# Escreva um programa que leia dois números inteiros e compare-os, mostrando na tela uma # mensagem: # O primeiro valor é maior # O segundo valor é maior # Não existe valor maior, os dois são iguais nu1 = int(input("Digite um numero: ")) nu2 = int(input("Digite um numero: ")) if nu1>nu2: print("O primeiro valo...
bb29a39a1def2b0143179f45a93f7d0d12b8d8de
SobrancelhaDoDragao/Exercicio-De-Programacao
/Exercicios-Python/Basico/Exercicios/exercicio24.py
451
4.1875
4
# Crie um programa que leia o nome de uma cidade e diga se ela começa ou não com o nome "SANTO". # O upper() no final, transforma todas as palavras em maisculo, assim evita erros cidade = input("Digite uma cidade: ").upper() cidade = cidade.strip() # Criando uma lista com o nome da cidade # Procurando no no indice o n...
435ab065f9313aca1d09952eee146019efe2db61
SobrancelhaDoDragao/Exercicio-De-Programacao
/Exercicios-Python/Basico/Exercicios/Bibliotecas.py
378
4.0625
4
# -*- coding: utf-8 -*- # Apredendo a importar e usar comandos de bibliotecas(ou Módulos) # Aqui estou importando todos as funções da biblioteca # Quando comandos são importados isoladamente, não é necessário botar math. from math import sqrt,floor #import math num = int(input("Digite um numero: ")) raiz = sqrt(num) pr...
4a48ea000df891c5f6ad37081d4256a5f78f8881
SobrancelhaDoDragao/Exercicio-De-Programacao
/Exercicios-Python/Basico/Exercicios/exercicio36.py
810
4.0625
4
# Escreva um programa para aprovar o empréstimo bancário para a compra de uma casa. # O programa vai perguntar o valor da casa. O salário do comprador e em quantos anos # ele vai pagar. # Calcule o valor da prestação mensal, sabendo que ela não pode exceder 30% do salário # ou então o empréstimo será negado. valor_ca...
e70fc1ab666bdf1980a76c17ca879d6c31ec5465
SobrancelhaDoDragao/Exercicio-De-Programacao
/Exercicios-Python/Basico/Exercicios/exercicio50.py
386
3.953125
4
# Desenvolva um programa que leia seis números inteiros e mostre a soma # apenas daqueles que forem pares. Se o valor digitado for ímpar, # desconsidere-o soma = 0 contador = 0 for c in range(1,7): num = int(input("Digite o {}º numero: ".format(c))) if num % 2 == 0: contador += 1 soma += num p...
08126ae6f834ba12f2a541bcb7bd1d4a5c468a41
SobrancelhaDoDragao/Exercicio-De-Programacao
/Exercicios-Python/Basico/Exercicios/exercicio88.py
778
4.09375
4
""" Faça um programa que ajude um jogador da Mega Sena a criar palpites. O programa vai perguntar quantos jogos serão gerados e vai sortear 6 números entre 1 e 60 para cada jogo, cadastrando tudo em uma lista composta. """ from random import randint from time import sleep sorteio = [] print() print('--'*30) print(...
6c4059c5794d8de0db2cac17aa398e1324433f20
ChestertonCC/Bronze-tasks-28.10.2019
/4/miniutils.py
1,291
4.15625
4
import ast version = "a1.0.0-minimod-1" def miniInput(inputType: type = str, *prompt: str, errorMessage: str = "You must enter a{n} {type}"): """ An input function that you always wished python had as default PARAMETERS: inputType: must be a type, determines the required type of the input. Use str to allow all inp...
8fad48e2d103751f0b5962fda9d7537075f3fd05
MANZARACI/Basit-Python
/Filmlik/filmlik.py
2,365
3.71875
4
import sqlite3 class Film(): def __init__(self,isim,tür,yıl,puan): self.isim=isim self.tür=tür self.yıl=yıl self.puan=puan def __str__(self): return (f"Filmin adı: {self.isim}\nTür: {self.tür}\nYıl: {self.yıl}\nPuan: {self.puan}\n") class Filmlik(): ...
91234afd11aa294cd5b8f62d8b78f333a92fbda3
chipsandtea/ProjectEuler
/longestCollatzSequence.py
503
3.546875
4
# Christopher Hsiao - 7/21/2016 # Problem 14: Which starting number, under one million, produces the longest chain? n = 999999 currMax = (0,0) # Returns size of chain of Collatz sequence def collatzSequence(n): count = 0 while n != 1: if n%2 == 0: count +=1 n /= 2 else: count += 1 n = (3*n)+1 retur...
e26389da0f1267362f43063d89d3797602b157d8
chipsandtea/ProjectEuler
/specialPythagoreanTriplet.py
232
3.6875
4
for a in range(1000): b = a+1 c = b+1 while c <= 1000: while c*c < (a*a + b*b): c+=1 if c*c == (a*a + b*b): #print('a:' + str(a) + ' b:' + str(b) + ' c:' + str(c)) if a+b+c == 1000: print(a*b*c) break b+=1
b4973e3008fe967d947980babfd7e47a5d2c054b
jra165/colorizer
/main2.py
14,378
3.5
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue May 4 10:49:09 2021 @author: Joshua Atienza, Janet Zhang @net-id: jra165, jrz42 @project: colorizer """ import imageio from typing import List import numpy as np import os import random import sys import math from PIL import Image from typing import ...
8d0555ba46879793802a318a8636f7efadc3655a
Asish-08/python
/eveodd.py
444
4.25
4
#Write a Python program to count the number of even and odd numbers from a series of numbers print('write the number of digits you want to analyze') i=int(input()) my_list = [] while i!=0: my_list.append(int(input())) i=i-1 odd = 0 even = 0 for x in my_list: x=int(x) if x % 2 ==0: ...
0b3b87f344609b8c12e3feb4f2bb51cab668bcc3
sammo11r/AutomataChecker
/DFA.py
3,030
3.953125
4
# Returns True if the submitted DFA accepts the set of words W, # and False otherwise. # # @param dfa - the Deterministic Finite Automaton, represented as a list # @param W - the set of words to be checked # # @pre dfa[0] == the transition function, dfa[1] == starting state, # dfa[2] == set of final sta...
1be1bbe82d2e1ff7f0a9a245aec9c42a414b6456
alexandershearer/CS_BankAccount
/BankAccount.py
1,952
4.03125
4
import random routing_number = 62738412 class BankAccount: #Set up the main function to get a name and balance def __init__(self, full_name): self.full_name = full_name self.account_number = str(random.randint(10000000, 99999999)) self.routing_number = 62738412 self.balance = 0...
1a406b41c1f4fc3e235d761446a48439b72bfe56
phaibin/papermaker
/src/core/compare.py
3,698
3.515625
4
#!/usr/bin/env python # -*- coding:utf-8 -*- def compareCities(innsCities, jjeCities): '''Compare cities in inns&jje return format. {'innswithcode':inns with code[(code,name),(...)], 'inns':inns cities, 'jje':jje cities, 'intersection':intersection cities, 'innsOnly': city only in inns, 'jjeOnly': city on...
55518c4f4cdbf8217340c931afc3b0e95dafb739
Temirlan2000/homework11
/функция3/main.py
1,414
4.1875
4
# 3. Написать программу, которая: # - выводит следующее меню на экран # 1. Ввести значения а и b # 2. Умножить значения а и b # 3. Делить а на b # 4. Выход # - реализует кажду опцию как фукцию # - реализует все ошибки и исключения. def user_input(): A = int(input('a: ')) B = int(input('b: ')) return A, B ...
7750fa0f713f88750ea3406e72bd5ba067d2f526
Kensawa94/differential-evolution-for-portfolio-optimisation
/src/objective_function/objective_function.py
715
3.59375
4
''' Created on Aug 12, 2013 @author: feaver ''' from abc import ABCMeta, abstractmethod class ObjectiveFunction(object): __metaclass__ = ABCMeta @abstractmethod def calc_fitness(self, vector): """ Calculate the fitness of a member of the population """ pass @abstractm...
5438b29450773cb642f4cf0585caf731bbb8a457
iRRiNiS/Pythagorean-theorem
/Python/distance_calc.py
525
3.921875
4
from math import sqrt def distance2d(_from, to): diffX = abs(_from[0] - to[0]) diffY = abs(_from[1] - to[1]) delta = sqrt((diffX ** 2) + (diffY ** 2)) return delta def distance3d(_from, to): from2d = (_from[0], _from[2]) to2d = (to[0], to[2]) diffX = distance2d(from2d, to2d) diffY = abs(_from[1] - to[1]) de...
30735d8d327d91db6f5ee851110b444cb99caaa1
standrewscollege2018/vehicle-rental-system-bmo9932
/vms.py
4,614
4.21875
4
class Vehicle: # Function to get the objects listed below and extract the variables within them add adding them to the list vehicles def __init__(self, name, seats, licence, avaiable, renter, cost): self._name = name self._seats = seats self._licence = licence self._available = a...
9f3ef6b9358568726e19ee65f055b7e02ba43bd9
abaah17/Programming1-examples
/w3s2_say.py
1,019
4.375
4
# Define a function that takes a single parameter: number_of_repetitions # The function will print as many lines as the number provided. # Each third line will be different from the other 2. def say(number_of_repetitions): # We set up a local variable for couting. count = 1 # As long as our count IS NOT B...
160f8d677e07adb6863d4911bec015d5ca5dc1a4
abaah17/Programming1-examples
/extra-sessions-examples/extra-session-1.py
3,448
4.5625
5
# Demo 1: # Function print_favorite_number with no parameter def print_favorite_number(): favorite_number = 17 print(favorite_number) print_favorite_number() # Function print_favorite_number with a parameter def print_favorite_number(favorite_number): print(favorite_number) print_fa...
2df428e3880d3097656211f0d5f8a446cc5f56d4
abaah17/Programming1-examples
/w8s2_oop_demo.py
1,098
4.375
4
from w8s2_ball import * # Ball() takes 5 parameters: # x and y of the ball # radius of the ball # vx and vy, changes to x and y respectively # We call the constructor here by using the Class name, followed by the parameters # of the __init__ method we defined in the class ball_1 = Ball(50, 50, 10, 2, 2) ball_2 = Ball...
6bfdb83faa76332e0b2a7d965c022413c8d47763
mikpim01/python_hindi
/verify-bst.py
526
4.03125
4
# Verify if the tree is binary search tree or not import math def verify_tree(n, min, max): if (n == None): return True if (n.val < min or n.val > max): return False # on the left side of a node n.val is the maximum element # on the right side of a node n.val is the minimum element ...
5c0792418b6159a5f8fdcfaa2898e80e5c504c42
GawBar/Python
/W3Schools/exercises1.py
4,520
4.75
5
############################################################################## ### https://www.w3resource.com/python-exercises/python-basic-exercises.php ### ############################################################################## ''' 1. Write a Python program to print the following string in a specific format...
f41f483310134bfecd83474b0759236524454ac7
hyuniebee/python-practice
/2p1_removeduplicates_hashLL.py
1,246
3.796875
4
class Node(object): def __init__(self): self.data = None self.next = None def get_data(self): return self.data def get_next_data(self): return self.data.next class LinkedList (object): def __init__(self): self.head = None def insert(self, data): new_node = Node() new_node.data = data new_node.nex...
056d011a44d448f7cc6b351cf2e711991db88eae
abhi1510/learnings
/TkinterPython/4.entry.py
332
4.09375
4
from tkinter import * root = Tk() def click_handler(): label = Label(root, text='Hello ' + entry.get()) label.pack() # Creating a entry widget entry = Entry(root, width=50, borderwidth=5) button = Button(root, text='Click Me', command=click_handler) # Showing it on the screen entry.pack() button.pack() roo...
6c1d4d3cb43efe616c8a9e273963e8381df0e1c7
abhi1510/learnings
/FluentPython/2. An array of Sequences/src/Eg2-10.py
355
3.8125
4
# Named tuple attributes and methods from collections import namedtuple City = namedtuple('City', 'name code population coordinates') tokyo = City('Tokyo', 'JP', 36.933, (35.689722, 139.691667)) print(tokyo._fields) # attribute _fields print(tokyo._asdict()) # as_dict method make_tokyo = City._make(tokyo) print...
22afdd56cbf31cd99529817693978ab72e2dd966
abhi1510/learnings
/TkinterPython/10.windows.py
274
3.859375
4
from tkinter import * root = Tk() def open_window(): top = Toplevel() top.title('My Second Window') label = Label(top, text='Hello from new window') label.pack() Button(root, text='open window', command=open_window).pack(padx=20, pady=20) root.mainloop()
b63a483bcffa6e3ab273d4d6c017fea2fd60d019
cauequeiroz/MITx-6.00.1x
/problem_set_2/problem_1.py
502
3.953125
4
# Variables balance = 42 annualInterestRate = 0.2 monthlyPaymentRate = 0.04 # Algorithm minimum_payment = balance * monthlyPaymentRate unpaid_balance = balance - minimum_payment interest = (annualInterestRate/12.0) * unpaid_balance for month in range(12): balance = unpaid_balance + interest minimum_payment = ...
034dbe81f5c560f7a84c38d6116c33ba8aa5f788
MethaneRain/Python
/atmos-sci/sounding/UWyo_Upper_Air_Text_Scrape.py
5,013
3.84375
4
#!/usr/bin/env python # coding: utf-8 import requests from bs4 import BeautifulSoup import urllib.request from datetime import datetime import os, sys ''' Handy little script for grabbing the text data from the University of Wyoming Upper Air data Url: http://weather.uwyo.edu/upperair/sounding.html Author - Justin ...
286a0667f80489f923f045db18fcb8fadc80b02b
drwebb98/Assignment_1
/agentsframework.py
1,753
3.78125
4
#agentsframework.py import random class Agent(): def __init__(self, environment, agents, y , x): if (x == None): self.x = random.randint(0,100) else: self.x = x if (y == None): self.y = random.randint(0,100) else:...
532e1abdcc128bea6ce2786bd517b6275253a756
dillu9878/Assignment1
/dice.py
749
3.734375
4
from random import randint def diceGame(amt=100): win = 0 count = 0 while amt > 0: count += 1 (a,b)=(randint(1,6),randint(1,6)) if (a+b) == 7: amt += 4 win += 1 else: amt -= 1 print('Not sufficient amount for next roll\n') print(c...
31744a34f06af0ea5b7843b5baeeae7e240444bf
munoz196/moonyosCSSIrep
/WeLearn/M3-Python/L2-Python_List_Dict/list.py
1,011
4.03125
4
# students = ["Alice","Javi","Damien","Javi"] # students.remove("Javi") # print(students) # # smith_siblings = ["Emily", "Monique","Giovanni","Jorge", "Jacob", "Emmanuel", "Hayden"] # for name in smith_siblings: # print(name + " Smith") # print(len(smith_siblings)) # # smith_siblings = ["Emily", "Monique","Giovanni...
334236b55a75d8680c2950583f099f3b691dfbce
ZeGmX/Stats-Project2
/NeuralNetwork.py
8,651
3.75
4
import numpy as np from Neuron import Neuron class NeuralNetwork: """ fields: format: array of integers of size C -> (n_c)_c neuron_layers: array of arrays ofNeurons array length C. The c th layer has length n_c -> a line represents a layer of neurons Z_layers: float array a...
8bbfc1b0233b649f33778d2251a73a3812324525
Keszua/project-2
/python/testy.py
2,094
3.8125
4
# produkty = ("mleko", "ser", "parówki") # tup = 1, 2, 3 # to tez jest tuple # produkty = produkty + tup # można robić konkatenacje, następuje stworzenie nowego tupla # set (zbiór) # s = {1, 2, 3, 1, 1, 2, 3} # s2 = set({3, 4, 5}) # print(s.intersection(s2)) # print(s.difference(s2)) #{1, 2} elementy ze zbioru...
c0195cf6a3313affba7f595019a7c1eb50dbea33
meke101/simple-numpy-pandas-matrix-creation
/dashboard.py
570
3.671875
4
# Difference between matrix and dataframe: # All columns in a matrix must have the same data type (numeric, character, etc.) and the same length. A data frame # is more general than a matrix, in that different columns can have different modes (numeric, character, factor, etc.) import numpy as np import pandas as pd ma...
18301e38ee75226c09b51086c6e7c16a461f2e56
guiqiqi/leaf
/leaf/selling/commodity/generator.py
3,899
3.53125
4
"""使用树算法根据产品生成商品信息""" from queue import Queue from typing import List from typing import NoReturn from .stock import Stock from .product import Product from .product import ProductParameter from ...core.algorithm import tree class StocksGenerator: """ 使用树算法根据传入的产品信息生成商品并设置 """ def __init__(self, ...
affc704cd4150bf759e4a12ffc2d53a38b3894a2
Yash-s-Code-Camp/Python-Day-2
/main.py
616
3.90625
4
# # def sum_mul_sub(a, b): # # return a+b, a*b, a-b # # s1, m1, sub1 = sum_mul_sub(5, 7) # # print(s1, m1, sub1) # # a=3 # # b=5 # # a, b= b,a # # print('a={} and b={}'.format(a, b)) # mydict = {"rutvik":11,"sahil":11,"nikunj":11,"kishan":7} # print(mydict["sahil"]) # for a in mydict: # print("{} prefers {...
d8df0c7207d5ba408113a62d91ac0036d95b7dc5
ThomasDre/TicTacToe-0.1-RL
/src/TicTacToe.py
5,926
3.578125
4
import numpy import random class GameEnvironment: """ empty slots of board are represented with '0' PC (playable character: simulated or real player) mark moves with '1' AI mark move with '4' if a row, column, or diagonal sums up to 3 then player 1 has won, if it sums up to 12 Agen...
bc861e4ec33f7bf75eab1c1e7d61f801166024c6
a55779147/Notes
/Python3/Fluent Python 章节总结/chapter8/1.py
911
4.03125
4
t1 = (1, 3, [30, 40]) t1[2].append(20) print(t1) l1 = [3, [55, 44], (1, 2, 3)] l2 = list(l1) print(l2 is l1, l2 == l1) # list() 创建副本 l2 = l1[:] print(l2 is l1, l2 == l1) # l1[:] 创建副本 print('-' * 20) # 但list() 和 l1[:] 是浅复制仅仅复制了最外围的容器 # 当元素的引用为可变序列时, 会发生意象不到的问题 l2 = l1[:] print(l1) print(l2) l1[1].append(20) print...
982e16c13351e9d88c9c99f9ffb3a47da404bcba
a55779147/Notes
/Python3/python3 built-in modles/code/tzinfo001.py
511
3.765625
4
from datetime import tzinfo, datetime, timedelta class UTC(tzinfo): def __init__(self, offset=0): self._offset = offset def utcoffset(self, dt): return timedelta(hours=self._offset) def tzname(self, dt): return "UTC +{}".format(self._offset) def dst(self, dt): retur...
dc1d04014790e24a173467fe0797e27ccecb7938
a55779147/Notes
/Python3/Fluent Python 章节总结/chapter7/what-is-decorate.py
403
3.84375
4
""" @decorate def target(): print("running target") == def target(): print(" running target") target = decorate(target) """ # example1 def deco(func): def inner(): print("running inner") return inner @deco def target(): print("running target") target() print(target) # --------- # ...
b98bf4f517e368826a2c52f7631ae4a7958785dd
kivy-garden/garden.roulettescroll
/__init__.py
8,367
3.71875
4
''' RouletteScrollEffect =================== This is a subclass of :class:`kivy.effects.ScrollEffect` that simulates the motion of a roulette, or a notched wheel (think Wheel of Fortune). It is primarily designed for emulating the effect of the iOS and android date pickers. Usage ----- Here's an example of using :c...
43e2d123792f55e91139cf6a22588dcd36b00e35
chetanmhwr1111/Py_datafrme
/b_dataSeries.py
1,654
4.03125
4
# -*- coding: utf-8 -*- ### PANDAS SERIES Data Structures- A single column of dataframe with indexes acts as DATA Series import pandas as pd sports = {'Archery': 'Bhutan', 'Golf': 'Scotland', 'Sumo': 'Japan', 'Taekwondo': 'South Korea'} s = pd.Series(sports) s = pd.Series(sports,...
bc6141de6bb4132cccabd6979700a3fae3e69ac9
dgranillo/Projects
/Classes/bank_account_manager.py
2,980
4.21875
4
#!/usr/bin/env python2.7 """ Bank Account Manager - Create a class called Account which will be an abstract class for three other classes called: CheckingAccount, SavingsAccount, and BusinessAccount. Manage credits and debits from these accounts throough an ATM style program Author: Dan Granillo <dan.granillo@gma...
653dfc89b716d3c6ccef826cd04d3f2be6cedd68
zxf19960728/zengxianfa
/demo05.py
1,201
4.21875
4
""" class 声明类的名字 然后类的名字开头必须大写 def __init__(): #这是固定的写法 类里面所有的方法,都必须要传一个参数 """ class Girlfriend(): def __init__(self,sex,high,weigt,hair,age): self.sex =sex self.high =high self.weigt =weigt self.hair =high self.age =age def caiyi(self,num): print("你的性别为"+...
eb993cbc15e00b2ccf7b81fbf82a23caefe18d82
rui-min/Self_Study
/Python_Codes/Bisection.py
1,758
4.1875
4
""" @completion: October 12, 2020 @author: Rui Min @topic: Bisection method to find an approximate solution """ from math import * # the math function is defined here and can be changed def f(x): return x**5-x**3+3*x-5 # Main function of the method def bisection(a, b, N): if f(a)*f(b) >= 0: print("B...
f666fb29970ef1bc353ea8eae95a46fca38cbb7d
deepak-acharya-97/python-3-practice
/index.py
588
3.5
4
## Local Scope place="Hebri" def changeMadu(): """ Checking Local/Global Scope """ global place ## Global Scope place="Hiriyadka" print(place) changeMadu() print(changeMadu.__doc__) ## NonLocal Scope (Ensclosing Scope) - scope which is not local/global def valueFriendShip(): valueFG=Tru...
71872900ff645fded3de5788f7805c2b47240234
NeoGalaxy/pi-thon
/modules/arg_parse/types.py
1,121
3.765625
4
""" Defines useful types for the pargument parser. """ class NonNegInt(int): """A none negative int""" def __new__(cls, *args, **kargs): number = int.__new__(cls, *args, **kargs) if number < 0 : raise ValueError('This should not be a negative number.') return number class P...
522fa32dba03ca9c5e5a55b1f8989f8057128749
nathanjwtx/udemy_flask_intro
/Flask_SQL_Intro/code/create_tables.py
575
3.953125
4
import sqlite3 connection = sqlite3.connect("data.db") cursor = connection.cursor() # must use integer for auto-increment number field instead of int create_table = ("create table if not exists users (id integer primary key," + "username text, password text)") cursor.execute(create_table) # create_ta...
e285398fb386fc07aae777521fe95cf3aeb898df
obrunet/Apprendre-a-programmer-Python3
/03.01.if.py
280
4.3125
4
# a simple example of the if, elif and else statements a = 0 # try with different values 10, -10 # selection depending on the sign and value of a if a>0: print("a is positive") elif a<0: print("a is negative") else: print("a is null")
63b1124e4248e7e228f1264d9f4bc76e8d5bd385
obrunet/Apprendre-a-programmer-Python3
/10.50.mini_db_with_switch___not_corrected__.py
4,130
4.125
4
# Complétez l’exercice 10.46 (mini-système de base de données) en lui ajoutant deux fonctions : # l’une pour recordistrer le dictionnaire résultant dans un fichier texte, # et l’autre pour reconstituer ce dictionnaire à partir du fichier correspondant. # Chaque ligne de votre fichier texte correspondra à un éléme...
5f14abe4aec049988c4f4841147076349e715611
obrunet/Apprendre-a-programmer-Python3
/12.06.circle_completed.py
1,610
4.3125
4
# Complétez l’exercice précédent en lui ajoutant encore une classe Cone(), qui devra dériver cette fois de la classe Cylindre(), # et dont le constructeur comportera lui aussi les deux paramètres rayon et hauteur. # Cette nouvelle classe possédera sa propre méthode volume(), laquelle devra renvoyer le volume du côn...
afa19c277becccd50757fb9b7bc96b6de940d2e6
obrunet/Apprendre-a-programmer-Python3
/09.01.create_read_again_a_file.py
1,619
4
4
# Écrivez un script qui permette de créer et de relire aisément un fichier texte. # Votre programme demandera d’abord à l’utilisateur d’entrer le nom du fichier. # Ensuite il lui proposera le choix, soit d’enregistrer de nouvelles lignes de texte, soit d’afficher le contenu du fichier. # L’utilisateur devra pouvo...
01d58c5cc3cb059e14207db88db43394b7325dfd
obrunet/Apprendre-a-programmer-Python3
/07.07.stars__not_corrected__.py
896
3.9375
4
# Ajoutez au module de l’exercice précédent une fonction etoile5() spécialisée dans le dessin d’étoiles à 5 branches. # Dans votre programme principal, insérez une boucle qui dessine une rangée horizontale de de 9 petites étoiles de tailles variées from turtle import * def stars5(side, col, angle): co...
eb7cac40b4bd61d16ad7e270168def7697ff4db3
obrunet/Apprendre-a-programmer-Python3
/10.10.uppercase.py
645
4.09375
4
# Écrivez une fonction estUneMaj() qui renvoie « vrai » si l’argument transmis est une majuscule. # Tâchez de tenir compte des majuscules accentuées ! def isUppercase(car): if car in "ABCDEFGHIJKLMNOPQRSTUVWXYZ": return True else: return False userSentence, noUpperCase = input("P...
51cf5db9ebc404bfcdf85dbfce2580601063f853
obrunet/Apprendre-a-programmer-Python3
/10.41.random_append__not_corrected__.py
663
4.125
4
# Réécrivez la fonction list_aleat() ci-dessous, en utilisant la méthode append() pour construire la liste petit à petit à partir # d’une liste vide (au lieu de remplacer les zéros d’une liste préexistante comme nous l’avons fait). from random import * def list_aleat(n): s = [0]*n for i in range(n): ...
bfe84d2d945a4ac6011fa62516280f34069481ce
obrunet/Apprendre-a-programmer-Python3
/06.06.other_output__not_corrected__.py
968
4.21875
4
# Que font ces programmes ? """-------------------------------------------------------------- a = 5 b = 2 if (a==5) & (b<2): print('"&" signifie "et"; on peut aussi utiliser\ le mot "and"') -------------------------------------------------------------...
766ae5dde88bd1f55d7058a66c0a366da0251bb1
obrunet/Apprendre-a-programmer-Python3
/05.13.greatest_elt.py
471
3.84375
4
# Écrivez un programme qui recherche le plus grand élément présent dans une liste donnée. # Par exemple, si on l’appliquait à la liste [32, 5, 12, 8, 3, 75, 2, 15], # ce programme devrait afficher : le plus grand élément de cette liste a la valeur 75 l = [32, 5, 12, 8, 3, 75, 2, 15] greatestElt = 0 i=0 whil...
c89e705dd8b79eae1b1a855efd79733b883b062b
obrunet/Apprendre-a-programmer-Python3
/06.09.leap_year.py
552
3.984375
4
# Déterminer si une année (dont le millésime est introduit par l’utilisateur) est bissextile ou non. # Une année A est bissextile si A est divisible par 4. # Elle ne l’est cependant pas si A est un multiple de 100, à moins que A ne soit multiple de 400. print("Enter a year:") enteredYear = int(input()) if en...
c74cf54f37ca5b6c23e2b560b7d5cda0f6faf822
obrunet/Apprendre-a-programmer-Python3
/04.07.other_multiplication_table.py
508
4.09375
4
# Affiche les 20 premiers termes de la table de multiplication par 7 en signalant au passage (à l'aide d'une astérisque) ceux qui sont des multiples de 3 # exemple : 7 14 21 * 28 35 42 49 ... for i in range (1,21): # i is incremented at the end of the loop -> 21 nb = i*7 print (nb, end=" ") # end...
c9aa123838902ac515c8a95d576231120e747d2a
obrunet/Apprendre-a-programmer-Python3
/bank_acount.py
1,761
3.90625
4
# Définissez une classe Compte_bancaire(), qui permette d’instancier des objets tels que # compte1, compte2, etc. Le constructeur de cette classe initialisera deux attributs # d’instance nom et solde, avec les valeurs par défaut ’Dupont’ et 1000. # Trois autres méthodes seront définies : # • depot(somme) permettra d’aj...
5536b6a567806ee2909c2a56ba6ccaf962e6fe96
obrunet/Apprendre-a-programmer-Python3
/05.08.str_with_stars.py
433
3.609375
4
# REcopie une chaine (dans une nouvelle variable), en insérant des astérisques entre les caractères # gaston -> g*a*s*t*o*n str1 = "efffffffeffffffffffeffffffffffe" str2 = str1[0] # assignement of str2 needed before using it i = 1 #, j = 0, 0 while i<len(str1): str2 = str2 + "...
12e8c774fba4a59ca51fb1950e188553889238a9
obrunet/Apprendre-a-programmer-Python3
/10.23.word_count.py
378
3.5
4
# Écrivez un script qui compte le nombre de mots contenus dans un fichier texte. import os inFileObj = open("testLatin1.txt", "r", encoding="Latin-1") n = 0 while 1: newLine = inFileObj.readline() if newLine == "": break n += len(newLine.split()) result = "The are {} words in this ...
898c65c1104d8e787b59dfcd11071c605142a78f
Gezzellig/DynamicTopologySelection
/TopologyGenerator/artillery_to_csv.py
960
3.546875
4
import csv import json def json_to_csv(csv_file_name, json_file): with open(csv_file_name, "w+") as csv_file: csv_writer = csv.writer(csv_file) for measurement in json_file["intermediate"]: print(measurement) timestamp = measurement["timestamp"] started = measur...
5eeac5a821f89a1d0dc0416d973bfdb382e465be
lanzath/python-excercises
/Sequenciais/ex13.py
431
3.890625
4
#Tendo como dado de entrada a altura (h) de uma pessoa, construa um algoritmo que calcule seu peso ideal, utilizando as seguintes fórmulas: #Para homens: (72.7*h) - 58 #Para mulheres: (62.1*h) - 44.7 h = float(input('Qual é a sua altura? ')) print('A massa ideal para sua altura se você é homem é de {:.1f}kg'.format((72...
ec21ebf3779d576ea308db7d2aebf9396ce85678
lanzath/python-excercises
/Condicionais/ex21.py
735
3.6875
4
#ex. 21 saque = int(input('Informe o valor de Saque: R$ ')) print('Saque autorizado: R$ ', saque) if saque in range (10, 600): nota_cem = saque // 100 saque = saque % 100 nota_cinq = saque // 50 saque = saque % 50 nota_dez = saque // 10 saque = saque % 10 nota_cinc = saque // 5 saque ...
7f70f026e0190b01314fa352be3579de6f956bd5
lanzath/python-excercises
/Condicionais/ex27.py
559
3.703125
4
#ex 27 morango = int(input('Qual a quantidade de morangos? ')) maçã = int(input('Qual a quantidade de maçãs? ')) if maçã <= 5 and morango <= 5: valor_morango = morango * 2.5 valor_maçã = maçã * 1.8 total = valor_maçã + valor_morango elif maçã > 5 and morango > 5: valor_morango = morango * 2.5 valor_...
ef5b281bba098dfd5f91edc546bfff41b3813d5b
lanzath/python-excercises
/Condicionais/ex23.py
257
4
4
#ex 23 num = float(input('Digite um número qualquer: ')) if num == round(num): print('Número inteiro') else: print('Número decimal') print("Arredondado pra baixo: ", round(num-0.5) ) print("Arredondado pra cima : ", round(num+0.5) )
cfd884e673c737afa82c4a6600cf2515a0a306a5
lanzath/python-excercises
/Sequenciais/ex15.py
881
3.828125
4
#Faça um Programa que pergunte quanto você ganha por hora e o número de horas trabalhadas no mês. #Calcule e mostre o total do seu salário no referido mês #sabendo-se que são descontados 11% para o Imposto de Renda, 8% para o INSS e 5% para o sindicato #faça um programa que nos dê: #salário bruto. #quanto pagou ao INSS...
bbf397f1e5626773e9cf101c7feeff0c9b4d9d73
andycui97/csua_hackathon
/open_read_file.py
317
4.03125
4
def read_file(text_file): """ Takes in a text file and opens and reads it. Returns a string with the contents of the text file.""" text_file = open(text_file, 'r') return text_file.read() def write_file(text_file,text): text_file = open(text_file, 'w') text_file.write(text) text_file.close()
cbbff8a2e010978b915f5adc8074c25515aa293e
fiestas/CS1100-Sem08
/f_ejem02.py
314
3.90625
4
# definir varias funciones def suma_cuadrados(N): suma = 0 for i in range(1, N + 1): suma += i * i # suma=suma+i*i return suma def main(): a=int(input("ingrese un valor: ")) print("la suma de cuadrados hasta %d es: %f"%(a,suma_cuadrados(a))) if (__name__== "__main__"): main()
101a162f5c20e17074071301571496aec971705b
snerligit/BME230A
/scripts/create_new_rms_categories.py
742
3.53125
4
import os import sys import argparse def get_args(): """ Parse command line arguments """ parser = argparse.ArgumentParser(description="Method to reclassify rmsds") parser.add_argument("-csv", help="rms_output.csv") args = parser.parse_args() return args def relabel(args): inputfil...
d8e536840e634a3c3d36b132e62abf1a44267ad4
mayassheeb/maya-sheeb
/game/hailstone.py
99
3.546875
4
n=13 print n while(n!=1): if n%2==0: n=n/2 print n elif n%2==1: n=(3*n)+1 print n
6c754dbd9d20e666e14bee395714ccaf66adcb31
mayassheeb/maya-sheeb
/turtle/turtleprogram.py
574
4.03125
4
import turtle turtle.shape("turtle") input=3 if input==4: turtle.forward(100) turtle.right (90) elif input==3: turtle.fillcolor("pink") turtle.begin_fill() turtle.circle(89) turtle.end_fill() turtle.fillcolor("blue") turtle.begin_fill() for x in range(4): turtle.forward(100) turtle.right(90) turtle.for...
6565186f69e1b7ebdee300ca4da78284e628d347
mayassheeb/maya-sheeb
/game/pygamestart.py
663
3.5625
4
import pygame import sys import time from pygame.locals import* pygame.init() pygame.display.set_caption("Basics") direction="forward" x=160 screen=pygame.display.set_mode((500,400)) BLACK = (0,0,0) WHITE= (255,255,255) GREEN=(0,255,0) RED=(255,0,0) pygame.draw.rect(screen,WHITE,(x,100,100,50)) while True: for even...
bc4bbab8869a90106a703d68ea83981a5620e9ff
mayassheeb/maya-sheeb
/winterbreak/agario.py
4,748
3.640625
4
import turtle import time import random from basicgame import Ball1 turtle.tracer(0) turtle.hideturtle() RUNNING = True SLEEP = 0.0001 SCREEN_WIDTH = turtle.getcanvas().winfo_width()/2 SCREEN_HEIGHT = turtle.getcanvas().winfo_height()/2 MYBALL = Ball1(300,300,10,10,50, "RED") NUMBER_OF_BALLS = 5 MINIMUM_BALL_RADIUS = ...
40d13b6c69948afe8ddc0be8a0725f14ef6cf825
ja-thomas/PythonKurs
/Tag1/stringsearch.py
244
3.625
4
import re def stringsearch(substr, string): matches = re.finditer(substr, string) k = 0 for i in matches: k += 1 print "Instance %i: Start: %i, End: %i" %(k, i.start(0) + 1, i.end(0) + 1) print "%i Instances of '%s' found" %(k, substr)