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 |
|---|---|---|---|---|---|---|
67edb12c7d86828e9db3927832fbce696a03b38a | ambika0203/NLP | /pblm4.py | 473 | 4.03125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Thu Apr 18 00:53:03 2019
@author: Ambika
"""
#Problem 6: Validate a phone number
# (phone number must be of 10 digits and starts with 8 or 9)
#list phone numbers in list “li” and here we will validate phone numbers
#using regular expression
import re
li=['9999999999'... |
86e7ce12e811d383f2d8d87b6a3abd8ade77caba | Shen-Meng/MITx-6.00.1x-Introduction-to-Computer-Science-and-Programming-Using-Python | /week2-problem-set2.py | 570 | 3.65625 | 4 | #problem 1
pay = 10
while True:
ub = balance
for x in range(12):
ub -= pay
ub += ub*(annualInterestRate/12.0)
if ub <= 0:
print('Lowest Payment: ' + str(pay))
break
else:
pay += 10
#problem 2
x = balance
low = balance/12.0
high = balance * (1+annualInterestRate/... |
d300339c5e1f5cf9fcea6caa9e6e501ca6023bb7 | SouravKr2001/winter-of-contributing | /Python/Parameters_and_Arguments/Variable_length_arguments.py | 147 | 3.6875 | 4 | def sum(*n):
total=0
for i in n:
total = total+i
print("the sum =",total)
sum()
sum(20)
sum(20,30)
sum(10,20,30,40)
|
e807ec7fcf5838a5570f7b559d06f62e6ed8debb | mcx2576/python_project | /Deep Learning/assignment_1/code/train_mlp_numpy.py | 6,334 | 3.921875 | 4 | """
This module implements training and evaluation of a multi-layer perceptron in NumPy.
You should fill in code into indicated sections.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import argparse
import numpy as np
import os
from mlp_numpy import M... |
e425ceefcdb0a75b3681bba2ea15fb84e4fcf97b | JorgeAntonioZunigaRojas/python | /practica_tupla.py | 1,638 | 3.78125 | 4 | #Creacion de una tupla################################################################################################
#Caractaristica de una tupla-> una tupla no es modificable............................................................
#mitupla=("Juan",13,1,1995)
#print(mitupla)
#Transformacion de tuplas a listas y ... |
bd3a39f97ab581ce0a090408c6d63039e0df80a6 | JorgeAntonioZunigaRojas/python | /practica_generadores_vs_funciones.py | 1,573 | 4.21875 | 4 | '''
def funcion_generar_numeros_pares(limite):
numero=1
numeros_pares=[]
while numero<limite:
numeros_pares.append(numero*2)
numero=numero+1
return numeros_pares
resultado=funcion_generar_numeros_pares(10)
print(resultado)
'''
# La diferencia entre un generador y una funcion es
# --> f... |
447e6bab964b2f691247b8110110ab176d7a912e | JorgeAntonioZunigaRojas/python | /practica_listas.py | 1,041 | 3.828125 | 4 | #miLista=["Guillermo", "Helen", "Andrea", "Jorge"]
#print(miLista)
#print(miLista[0:3])
#print(miLista[:3])
#print(miLista[1:3])
#print(miLista[2:])
#miLista.append("Toño")
#miLista.insert(2,"Antonio")
#miLista.extend(["Taty","Miguel","Antelin"])
#print(miLista.index("Andrea"))
#print("Helen" in miLista) #Busca el "... |
d0fd6ea4c8a31803d44619341152025be11f481c | JorgeAntonioZunigaRojas/python | /practica_interfas_grafica08_checkbutton.py | 1,033 | 3.5 | 4 | from tkinter import*
window=Tk()
window.title("Ejemplo")
playa=IntVar()
montana=IntVar()
turismoRural=IntVar()
def opcionesViaje():
opcionEscogida=""
if playa.get()==1:
opcionEscogida=opcionEscogida+" Playa"
if montana.get() == 1:
opcionEscogida = opcionEscogida + " Montaña"
if turismo... |
a4dca07fc47759371c5d63438413773695a7609d | JorgeAntonioZunigaRojas/python | /practica_expesiones_regulares_regex04.py | 531 | 4.09375 | 4 | import re
lista_nombres=[
'ana',
'pedro',
'maria',
'rosa',
'sandra',
'betob',
'celia'
]
print("->Imprime un rango de letras ejemplo: nombres que inicia con 'a' o 'b' o 'c'------------------------>")
for elemento in lista_nombres:
if re.findall('^[a-c]', elemento):
print(elemento... |
c3c0e124814a7b95374aa19705dd6a4251fc2fac | JorgeAntonioZunigaRojas/python | /practica_manejo_archivos01.py | 1,578 | 3.640625 | 4 | from io import open
'''
# Abrir archivo modo escritura #################################################################
name_file="archivo.txt"
modo_apertura="w" # (r=(lectura), w=(escritura), a=(modificar un archivo existente) )
archivo_texto=open(name_file, modo_apertura) #Si el archivo no existe esta linea d... |
4cd6b1d187c4f8115a9c6c0039a543c6b9c96645 | senaaac/coding-starter | /week_01_python/15_homeowork_05.py | 683 | 3.609375 | 4 | def gugudan():
try: #예외처리와 구분되는 정상적인 조건
dan = int(input("2에서 9사이의 숫자를 입력해주세요:"))
if 1 < dan < 10:
for num in range(1, 10):
print("{} * {} = {}".format(dan, num, dan*num))
else:
print("2에서 9사이의 숫자만 입력해주세요!")
gugudan()
except ValueError:... |
135a6246204c61c12c9afbbe0da7af742bec3066 | senaaac/coding-starter | /week_01_python/11_homework_02.py | 1,625 | 4 | 4 | # 1) 사람클래스
class Person:
# 이름, 나이, 성별
# name, age, gender
# 1-1) 새로 만들때 입력
def __init__(self, name, age, gender):
self.name = name
self.age = age
self.gender = gender
# 2) 직장 동료 클래스
class Colleague(Person):
#position = "대리"
# 상속
# 2-2) 새로 만들때 입력
def __init__(self, name,... |
ff55e8e1faf22bb0d782bf0e2b251cf960887c4f | yukkey-poker/atcoder | /beginners_selection/ABC081A_Placing_Marbles.py | 135 | 3.515625 | 4 | s = str(input())
answer = 0
for i in range(3):
if s[i] == '1':
answer += 1
else:
answer = answer
print(answer) |
a5727c2579126f93607cd59aedb9fc0f45662db2 | ratsirarar/prework-repo | /week2/length_last_word.py | 323 | 3.625 | 4 | class Solution:
# @param A : string
# @return an integer
def lengthOfLastWord(self, A):
A = A.strip()
last_word_count = 0
for char in A:
if char == ' ':
last_word_count = 0
else:
last_word_count += 1
return last_word_cou... |
62fd9f2b1adf30466d1db99346db090cda2bc29b | andreivisan/Coursera-Algorithms_Part1 | /Week4/topology_order.py | 709 | 3.890625 | 4 | #!/usr/bin/env python
graph = {"s" :["v", "w"] , "v":["t"], "w":["t"], "t" :[]}
current_label = len(graph)
visited = {}
mark = {}
def depth_first_search(graph, start):
global visited, mark, current_label
stack = []
visited[start] = 1
for edge in graph[start]:
if visited[edge]!=1:
depth_first_search(graph, e... |
5191bf3ef7658a74fb8ad5a4d8f42b3f7c4052d7 | rudresh-poojari/my-captain-assingments | /circle_area.py | 323 | 4.125 | 4 | r = float(input("enter the radius of the circle : "))
area = 3.14159265359*r**2
print("the area of thr circlr with radius ",r,"is : ",area)
# output :
# C:\Users\rudre\OneDrive\Desktop\pythonmc>circle_area.py
# enter the radius of the circle : 1.1
# the area of thr circlr with radius 1.1 is : 3.80132711084390... |
2928aac960286ff38dae1ca85e50c0d0ba653111 | cvhs-cs-2017/practice-exam-IMissHarambe | /Loops.py | 282 | 4.34375 | 4 | """Use a loop to make a turtle draw a shape that is has at least 100 sides and
that shows symmetry. The entire shape must fit inside the screen"""
import turtle
meme = turtle.Turtle()
for i in range (100):
meme.forward(1)
meme.right(3.3)
input()
|
fbcc409e7bdf235598c1db86b34f4a5ad4b146b5 | furtiveJack/Outils_logiciels | /projet/src/utils.py | 1,768 | 4.21875 | 4 | from enum import Enum
from typing import Optional
"""
Utility methods and variables for the game.
"""
# Height of the window (in px)
HEIGHT = 1000
# Width of the window (in px)
WIDTH = 1000
# Shift from the side of the window
ORIGIN = 20
NONE = 0
H_WALL = 1
V_WALL = 2
C_WALL = 3
MINO = 4
class CharacterType(Enum):
... |
fc8abd75812efc3ea99d5a8f460f33bd34c16e29 | thakreshardul/SecureMessenger | /chatapp/cli.py | 2,846 | 3.609375 | 4 | """This is the text interface at the client side"""
import getpass
import socket
import sys
import chatapp.client as client
import chatapp.config as config
import chatapp.exception as exception
class TextInterface:
def __init__(self, conf):
# configure the server address from config file
self.cli... |
d4fc145574619a6a79c7507f5a7f7ad54c60ec57 | prince-prakash/practice_session | /pp_triangle.py | 224 | 4.0625 | 4 | print('Area of the triangle....')
a = int(input('Enter the first side: '))
b = int(input('Enter the second side: '))
c = int(input('Enter the third side: '))
s = (a+b+c)/2
print(s)
s1 = (s*(s-a)*(s-b)*(s-c))-(1/2)
print(s1) |
37d80248eec332b86fc883eb1f13c64b7d162b74 | prince-prakash/practice_session | /pp_binarysearch.py | 331 | 3.8125 | 4 | def search(list, num): ## Caution: Should have a sorted array
u = 0
l = len(list)
mid = l//2
while list[mid] < num or list[mid] > num:
if list[mid] < num:
u = mid + 1
else:
l = mid - 1
mid = (u+l)//2
print(mid+1)
list = [4, 6, 19, 20, 21, 56]
search... |
c41097cb6c0b6c8319cff5a983171c36d1ed1a45 | prince-prakash/practice_session | /pp_multiplicationtable.py | 109 | 3.71875 | 4 | num = int(input('Enter the number for table evaluation: '))
for i in range(10):
w = i * num
print(w) |
47e5fcf40e07b6b5a2a6987892d485ee229b3897 | prince-prakash/practice_session | /pp_quadratic.py | 296 | 3.671875 | 4 | import math
import random
a = int(input('Enter the first number: '))
b = int(input('Enter the second number: '))
c = int(input('Enter the third number: '))
d = (b**2)-(4*a*c)
sol1 = (-b+math.sqrt(d))/(2*a)
sol2 = (-b-math.sqrt(d))/(2*a)
print(sol1, sol2)
r = random.randint(100, 500)
print(r) |
38e97acd4f53119a0469057819d39e1a1991a6b0 | prince-prakash/practice_session | /pp_Queue.py | 1,203 | 3.796875 | 4 | class simplequeue:
def __init__(self):
self.list = []
def push(self, data):
self.list.append(data)
def display(self):
l = len(self.list)
for i in range(l):
print(self.list[i], end=' ')
print()
def dele(self,data):
l = len(self.list)
... |
a7b811a623b606af7c0ad55eacc9bd024fbf4112 | Arif-Badhon/BongoBD | /q2.py | 727 | 3.953125 | 4 | class Person(object):
def __init__(self, first_name, last_name, father):
self.first_name = first_name
self.last_name = last_name
self.father = father
def print_depth(d, start=0):
for key, value in d.items():
print(key, start + 1)
if isinstance(value, dict):
print_depth(value, s... |
e6e4384208d13dff8f94d2001e6cabcf961bc323 | creativitRy/AOC2017 | /src/day2_2.py | 457 | 3.609375 | 4 | input = """5 9 2 8
9 4 7 3
3 8 6 5"""
def div(a, b):
if a < b:
a, b = b, a
if a % b == 0:
return a / b
return -1
sum = 0
for row in input.split("\n"):
list = []
for num in row.split():
n = int(num)
for i in list:
a = div(n, i)
if a > 0:
... |
7ebc17baa09212e28e53305591cbcc3516fbb42e | qinguan/infolist | /Karrigell-2.3.5/webapps/demo/wiki/wikiRemove.py | 605 | 3.546875 | 4 | """ Removes the pages whose names are the keys of QUERY """
# check authentication
Include("wikiAuthent.py")
if not QUERY.keys():
print 'No page to remove<p><a href="index.pih">Back</a>'
raise SCRIPT_END
# get records to remove using their recno
from wikiBase import db
recs_to_remove = []
f... |
56ee7e83d67b35377873dba2ba16680056daf267 | sunshyneDaCoder/for_loop_basic1.py | /funbasic1.py | 1,633 | 3.9375 | 4 | #1
def a():
return 5
print(a())
# output prediction 5
#2
def b():
return 5
print(b()+b())
# output prediction 10
#3
def c():
return 5
return 10
print(c())
# output prediction 5 , wont reach 10 because of the return statement
#4
def d():
return 5
print(10)
print(d())
# output prediction 5 , wo... |
b5a971c1954dc4f577e1f3040ceed194219bbedf | le0ra/eplusinterface_diagrams | /EPlusInputcode/EPlusCode/diffs.py | 3,317 | 3.828125 | 4 | """calculate the diffs for mathdiff.py and tablediff.py"""
import py
def dodiff(v1, v2, func=None, thelimit=0):
"""find the diff between v1 and v2. func is the function used to find the diff
1. text diff
a. if same, use v1
return (v1, False)
b. if diff, use v1 and mark as err
... |
a8d17074bfab81dc7b4d2d0acbb28ef4c776ca07 | spyamine/pycaishen3 | /pycaishen/user_programs/nice_print.py | 329 | 3.875 | 4 | def chunks(list, n):
"""Yield successive n-sized chunks from l."""
if n > 1:
for i in range(0, len(list), n):
yield list[i:i + n]
elif n == 1:
for i in range(0,len(list)):
yield list[i:i+1]
def print_n(l,chunk_size):
for l in chunks(l,chunk_size):
... |
e7a6924c67a3a4133fe14653d9aed931e4c75c3f | pyunits/pyunit-address | /pyunit_address/tool.py | 1,168 | 3.546875 | 4 | #!/usr/bin/python3.7
# -*- coding: utf-8 -*-
# @Time : 2020/4/6 12:29
# @Author: Jtyoui@qq.com
# @interpret: 常用工具
def remove_subset(ls) -> list:
"""去除列表中的子集
比如:['aa','a','ab'] --> ['aa','ab']
:param ls: 字符串列表
:return: 返回去重后的结果
"""
ls = sorted(ls, key=lambda x: len(x), reverse=True)
total ... |
2baac708d8221f95ededca3c8c1ab247322d31e5 | mpereira30/PiNets | /TensorFlowTutorials/tf_tutorial_1_MNISTclassifier.py | 2,283 | 3.8125 | 4 | #!/usr/bin/env python
import numpy as np
import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
# A one-hot vector is a vector which is 0 in most dimensions, and 1 in a single dimension
mnist = input_data.read_data_sets("MNIST_data/", one_hot=True)
# MNIST images are 28x28 pix... |
8ef752dbb28161057c05ce1c333e7e18842e1b2d | eugene-belkovich/algorithms | /find_disappeared_nums/variants_1.py | 146 | 3.703125 | 4 | def find(nums):
for i in range(0, len(nums)):
return 0
def main():
nums = [-1, -2, -3]
print('answer', find(nums))
main()
|
2b464b45443b697193d8ba8933529cb04e51618f | AdrianPratama/AdrianSuharto_ITP2017_Exercise3 | /Chapter 4-12.py | 207 | 3.671875 | 4 | foods = ['pizza', 'falafel', 'carrot cake', 'cannoli']
friend_foods = ['pizza', 'falafel', 'carrot cake', 'ice cream']
for i in range(4):
print(foods[i])
for j in range (4):
print(friend_foods[j])
|
bb2e377869de284ffc87879824e1ab8b120515d0 | AdrianPratama/AdrianSuharto_ITP2017_Exercise3 | /Chapter 4-1.py | 231 | 3.6875 | 4 | yummy = ["Meat Lovers","Cheese Burger","Fish n' Chips","American Supreme"]
for i in range (4):
print("I like "+yummy[i]+" pizza!")
print("\nI especially enjoy Cheese Burger pizza...\n" + "But in the end, it doesn't matter!")
|
62c91d908ffbb5208bde71f310cef50fae8671b8 | AdrianPratama/AdrianSuharto_ITP2017_Exercise3 | /Chapter 4-11.py | 347 | 4 | 4 | yummy = ["Meat Lovers","Cheese Burger","Fish n' Chips","American Supreme","Olive Mushroom"]
friend_pizzas = ["Meat Lovers","Cheese Burger","Fish n' Chips","American Supreme","Hawaiian Express"]
for i in range(5):
print("I like "+yummy[i]+" pizza!")
for i in range(5):
print("My friend's favorite pizza are: "+f... |
afbfeed74dc2deae4536271443e074a2899bf09c | AdrianPratama/AdrianSuharto_ITP2017_Exercise3 | /Chapter 3-6.py | 592 | 3.875 | 4 | name = ["Bill Gates","Stephen Hawking","William Shakespeare"]
print("It appears we have more space for our famous people!\n")
name.insert(len(name),"Jeanne D'Arc")
name.insert(len(name),"Oda Nobunaga")
name.append("Shimazu Toyohisa")
print("Would you like a small dinner "+name[0]+"?")
print("How about taking a smal... |
899a93d8e80eeadb95fe4fe55581ebcf94a44e56 | 25nehasinhaa/python-programs | /dice.py | 127 | 3.65625 | 4 | import random
While True:
r == "r":
print(random.randint(1,6))
if r == "q"
print("Bye!")
exit() |
5e2930e1215c7e606e822ade7d7141d6ba5c508f | vgerak/ProjectEuler | /52-Permuted_multiples.py | 167 | 3.515625 | 4 | i = 10
while True:
i += 1
if set(str(i)) == set(str(2 * i)) == set(str(3 * i)) == set(str(4 * i)) == set(str(5 * i)) == set(str(6 * i)):
break
print i
|
fd358de9e684fe33154fc54df837d3239c457663 | makrand12/handling-program-flow-in-python-code-along | /code.py | 2,615 | 3.5625 | 4 | # --------------
import json
from collections import Counter
with open(path) as f:
data = json.load(f)
#print(data)
# Code starts here
# Can you find how many deliveries were faced by batsman `SC Ganguly`.
def deliveries_count(data=data):
count = 0
innings_delivered = data["innings"][0]["1st innings"]... |
6e76bcf37e06e6c8493363e6606bcf9cc759cf25 | Gabrri/LOGICA2_CC | /Codificacion_y_escritura_formulas/main2.py | 942 | 3.578125 | 4 | import codificacion as C
import visualizacion as V
import tableaux as T
Nc = 9 # Numero de casillas
Nt = 10 # Numero de turnos
def crea_regla1():
# Creamos la regla de que debe haber por lo menos un caballo en cada turno
inicial_regla = True
for t in range(Nt):
inicial_clausula = True
fo... |
39e7e5bf7c4f3cec4cffdfa3512b24ebdf648fdc | PengInGitHub/Numpy-Tutorial-W3Resource | /Exercise-12.py | 132 | 3.953125 | 4 | import numpy as np
#Append values to the end of an array
x=[1,2,3] #list
print(type(x))
x=np.append(x,[[4,5,6],[7,8,9]])
print(x)
|
bf1facb50d323718beb766b2de34b085a4368592 | PengInGitHub/Numpy-Tutorial-W3Resource | /Exercise-14.py | 254 | 3.921875 | 4 | import numpy as np
#Write a Python program to convert the values of Centigrade degrees into Fahrenheit degrees. Centigrade values are stored into a NumPy array.
Fahrenheit=[0, 12, 45.21, 34, 99.91]
FArray=np.array(Fahrenheit)
print(5*FArray/9 - 5*32/9)
|
dc657b9020a4d2635cf85d2a00f8b4cb928c6a37 | arayariquelmes/curso_python_abierto | /18_ejemplo_while.py | 484 | 4.15625 | 4 | #import os
#Ejemplos de uso del ciclo while
#1. Ciclo que se repite una cantidad indeterminada de veces
res="si"
while res == "si":
print("Bienvenido al programa!")
res = input("Desea continuar?")
#Esto limpia la pantalla
#os.system('clear')
print("Gracias por utilizar el super programa más util del m... |
558cdfff62a1ca185bebfb0c6a95f7b6d506bbaa | arayariquelmes/curso_python_abierto | /31_ejercicio_20.py | 458 | 4.09375 | 4 | #Escribir un programa que solicite 3 números distintos por teclado,
#y calcule el número mayor ingresado..
#Forma cualquier lenguaje de programación
n1 = int(input("Ingrese número 1:"))
n2 = int(input("Ingrese número 2:"))
n3 = int(input("Ingrese número 3:"))
mayor = n1
if n2 > mayor:
mayor = n2
if n3 > mayor:
... |
9e3d37504f513721b2eab9e462ddf917544c723d | arayariquelmes/curso_python_abierto | /39_ejemplo_funciones.py | 228 | 3.625 | 4 | #Ejemplo de uso de funciones en python
def sumar(a,b):
return a + b
def calcularIva(valor):
return valor*0.19
lista = []
res = sumar(5,7)
iva = calcularIva(5000)
print("La suma es",res)
print("El iva de 5000 es",iva) |
5ccbf664b08ab7f2d4dbec376198b2afb0bc450a | arayariquelmes/curso_python_abierto | /8_ejercicio_4.py | 322 | 4.0625 | 4 | #Escriba un programa en Python que calcule el promedio de tres notas
#El programa de solicitar cada nota y entregar el resultado
n1 = float(input("Ingrese primera nota:"))
n2 = float(input("Ingrese segunda nota:"))
n3 = float(input("Ingrese tercera nota:"))
prom = (n1 + n2 + n3)/3
print("El promedio es:",round(prom,2... |
b3d2267df89cfd904bd4cf489c9bf0a627984bb2 | arayariquelmes/curso_python_abierto | /44_ejercicio_31.py | 834 | 3.9375 | 4 | #Escribir una función que reciba una
#muestra de números en una lista y devuelva otra
#lista con sus cuadrados. Solicitar 5 números,
#almacenarlos en una lista y mostrar el
#resultado de la llamada a la función
def cuadrados(lista):
lista_cuadrados = []
for n in lista:
lista_cuadrados.append(n**2)
... |
ebb2da632dee4d44cdc8183427665bebcefaf47b | arayariquelmes/curso_python_abierto | /33_ejercicio_21.py | 528 | 4.0625 | 4 | #Escribir un programa que almacena en una lista los números
#pares desde 1 hasta N donde N es entregado por el usuario.
#Posteriormente mostrarla por pantalla elemento a elemento
n = int(input("Ingrese número final"))
pares=[]
#Esto hace lo mismo que el for
#i = 1
#while i < n:
# if i % 2 == 0:
# pares.app... |
8b6a16a766fb665e4be63c74530356e23bdf9737 | patka12345/metody | /solutions/lab1.py | 1,819 | 3.78125 | 4 | from decimal import *
import math
import numpy as np
import matplotlib.pyplot as plt
#TASKS (4p)
#1 calculate & print the value of function y = 2x^2 + 2x + 2 for x=[56, 57, ... 100] (0.5p)
print('zbiór liczb:')
x = [i for i in range(56,101)]
print(x)
print('wartości funkcji:')
y = [2*i**2 + 2*i + 2 for i in x]
print(... |
69422e8bcf009b6bff2355220506721adc178cad | JasmineEllaine/fit1008-cpp-labs | /3-lab/task1_a.py | 1,180 | 4.25 | 4 | # Task 1a
# Read input from user (int greater than 1582)
# If leap year print - is a leap year
# Else print - is not a leap year
def main():
""" Asks for year input and prints response accordingly
Args:
None
Returns:
None
Raises:
No Exceptions
Preconditions:
... |
f69ab4eea85d720c141d48f6ebebb8bce2abcc91 | JasmineEllaine/fit1008-cpp-labs | /11-lab/task4.py | 7,252 | 3.84375 | 4 | """ Task 4
Implements hash table using separate chaining
"""
import linked_list as link
from referential_array import build_array
class kv_pair:
def __init__(self,key,value,collisions=0):
""" Key-value pair constructor
Args:
key (any): key
value (any): value
... |
c95b132ee2eeba0a316620ddc373ebb833316d36 | BONK1/Python | /tryExcept.py | 366 | 3.703125 | 4 | #First Case (Something is wrong)
greetings = "Hello Bob,"
try:
convert = int(greetings)
except:
print("I Knew this won't work")
#Second Case (Nothing is wrong)
noOranges = 25;
noGrapes = 50;
try:
fruitBasket = noOranges + noGrapes;
print(f'There are totallt {fruitBasket} no of fruits in basket');
except... |
e5478d7c6ac648e4e2c875ed4e0980d566c89145 | GRC-SummerSchool/learn-intermediate-python | /Classes/gamechar.py | 4,620 | 3.6875 | 4 | from random import randint
class ActionError(ValueError):
"""A custom-made error created by inheriting the ValueError class.
Although the class 'does nothing', it can still be distinguished from
a CharacterError or ValueError when using try-expect blocks
"""
pass
class CharacterError(ValueError):
... |
1139ac27cfe5fac9c3face5dfa6fba13e1331155 | SILIN-WANG/Sandbox | /Prac_02/randoms.py | 459 | 3.96875 | 4 | import random
print(random.randint(5, 20)) #I saw integers from 5 to 19, 2)the smallest number is 5 and the largest number is 19.
print(random.randrange(3, 10, 2))
# I saw 3 5 7 9 in this line, 2)the smallest number is 3 and the largest number is 9, 3)this line can not produce 4.
print(random.uniform(2.5, 5.5))
#I sa... |
e70310eb9a27345c7f3468a742d433725ccd1f4f | learnfunfc/algorithm | /selection sorting.py | 210 | 3.640625 | 4 |
"selection sorting"
num = [14,1,13,7,15]
i = 0
while i < len(num)-1:
j = i + 1
while j < len(num):
if num[i]> num[j]:
num[i],num[j] = num[j],num[i]
j+=1
i+=1
print(num) |
f6f8a2e6dd9a0920f57527bea4d02bcab7d0ad59 | aherschend/OOP | /Coin Toss.py | 1,064 | 3.984375 | 4 | import CoinClass as c
# c is just an alias, importing the file to use in the code
# The main function.
def main():
# Create an object from the Coin(came from other file) class.
my_coin = c.Coin() # this creates an instance called 'my_coin' of the class 'Coin()'
# Display the side of the... |
276af0551a851117387429d12e42cebe72803fba | msm17b019/Project | /DSA/Quick_Sort.py | 812 | 3.96875 | 4 | def swap(a,b,arr):
if a!=b:
temp=arr[a]
arr[a]=arr[b]
arr[b]=temp
def partition(elements,start,end):
pivot_index=start
pivot=elements[pivot_index]
while start<end:
while start < len(elements) and elements[start]<=pivot:
start+=1
while elements[e... |
bec90b0361b19f66e15bfef6d5abacd2bddc9970 | msm17b019/Project | /DSA/Bubble_Sort.py | 677 | 4.1875 | 4 | def bubble_sort(elements):
size=len(elements)
swapped=False # if no swapping take place in iteration,it means elements are sorted.
for i in range(size-1):
for j in range(size-1-i): # (size-i-1) as last element in every iteration is getting sorted.
if elements[j]>elements[j+1]:
... |
5ba1d1a31e3745bad7e88315d6a0270e9f6f369a | msm17b019/Project | /DSA/Tree.py | 1,419 | 3.671875 | 4 | class TreeNode:
def __init__(self,data):
self.data=data
self.children=[]
self.parent=None
def add_child(self,child):
child.parent=self
self.children.append(child)
def get_level(self):
level=0
p=self.parent
while p:
level+=1
... |
9d7380b38ef35efa89353f99d5c11aea2117b10b | StephenAshmore/league-bot | /bot/player.py | 1,775 | 3.5625 | 4 | import jsonpickle
import json
class Player(object):
def __init__(self, name):
self.name = name
self.elo = 1000
self.number_games = 0
self.number_wins = 0
self.number_leagues = 0
self.ratio = 0
self.leagues = []
self.games = []
def win(self):
... |
70851103de951eccdca7e720ddbb081d74dc5c9b | lauryndbrown/Challenges | /python programming part 1/merge2048.py | 2,142 | 4.03125 | 4 | """
Merge function for 2048 game.
http://www.codeskulptor.org/#user42_VXqZnQwTEI_17.py
"""
EMPTY_POS = 0
def merge(line):
"""
Function that merges a single row or column in 2048.
"""
merged_line = list(line)
shift_line(merged_line)
line_len = len(merged_line)
if line_len > 1:
for in... |
f2fe1b288d7adb06eb8004b340db62ab3feee5e3 | 549284345/Task | /2.Python/python.py | 13,465 | 4.09375 | 4 | import copy
# ͬʱ2汾pythonʹCMDòͬĽ
python -2 #python 2
python -3 #python 3
# ʹpipΪͬ汾pythonװ
python -2 -m pip install xxx
python -3 -m pip install xxx
# ͬʱ2б
for (i, j) in zip([1,2,3],['a','b','c']): # zipбԪб[(1, 'a'), (2, 'b'), (3, 'c')]
print(str(j) + str(i))
# »ǰ磺_fooຯmoduleʱʹfrom module import _foo
# ǰ˫ϹǮ:__... |
cc4917ac0e91caefd63e755139cd01a7e9b18ee2 | LavenderIris/pythonOOP | /underscore.py | 2,004 | 3.703125 | 4 |
class Underscore(object):
def map(self, numlist, callback):
# we take the value from each callback and reassign to my original numlist
for index, num in enumerate(numlist):
numlist[index] = callback(num)
return numlist
def reduce(self,numlist, callback):
... |
944953b400319e5d358cf8d856e5ef05fe4e069c | yasminara1990/TIC-TAC-TOE | /tic-tac-toe.py | 7,114 | 3.828125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon May 17 02:42:24 2021
@author: yasmin
"""
from tkinter import *
import tkinter.messagebox as msg
window= Tk()
window.title('TIC-TAC-TOE')
digits = [1,2,3,4,5,6,7,8,9]
mark = ''
count = 0
cells = ["cell"]*10
def win(cells,sign):
return ((cells[1... |
d80c6860c1560d77f5375136529dc5dfbfdfd709 | OusmaneCisse/tableMulti_anneeBiss | /tableMulti_anneeBiss/table_de_multiplication.py | 579 | 4.15625 | 4 | """
Cette fonction permet d'afficher la table de multiplication en fonction d'un nombre enter au clavier.
Auteur: Ousmane CISSE
Date: 05/12/2020
"""
__version__ = "0.0.1"
#Creation de la fonction
def table_de_multiplication():
#Recupération de la valeur
n = int(input("Veuillez entrer un nombre:... |
1db8fd77a66e6da3d2a12cfe266197fc23025d42 | Fanbo0428/Com_DPLL_zchaff | /DPLL-master/cnf.py | 6,531 | 3.71875 | 4 | # -*- coding = utf-8 -*-
import sys
import fileinput
def biconditionalElimination(s):
if type(s) is str:
return s
elif type(s) is list and s[0] == "iff":
return(["and",
["if",
biconditionalElimination(s[1]),
biconditionalElimination(s[2])],
... |
568959cd89ae1b475808eaaf597c69e80caf0834 | shashank5743/task | /task3.py | 288 | 3.921875 | 4 | def common(l1, l2):
l1_set = set(l1)
l2_set = set(l2)
if (l1_set & l2_set):
print(l1_set & l2_set)
else:
print("No common elements")
print((l1_set).difference(l2_set))# L1 not in L2.
l1 = ['a','b','c']
l2 = ['b','d']
common(l1, l2)
|
f4e7f516306ac9b5488c2d4e64253c356b0ea09e | sahilpundora/k-MEANS-clustering | /Q1.py | 5,143 | 3.75 | 4 | from matplotlib import pyplot as plt
import csv
import math
import numpy as np
#TO READ THE FILE AND CREATE DATASET-----------------------------------------
f= open('C:\\Users\\sahil\\Desktop\\A3_Q1_dataset.csv','rb') #mention the location where the dataset is located
readfile= csv.reader(f)
feat1=[]
feat2=... |
6ba0bb7c62c46dea9d6864d77de111d087654fd8 | gutus/MathAdvPython | /02_square_turtle.py | 189 | 3.890625 | 4 | # SQUARE TURTLE
from turtle import *
shape('turtle')
speed(2)
def square():
for i in range(60):
right(5) # geser 5 derajat
forward(200)
right(90)
square()
|
609db0a7003b5e1d154910d62211743d9a6d50f7 | omarsagoo/chess_challenge | /pawn_test.py | 1,420 | 3.6875 | 4 | from pawn import Pawn
import unittest
class PawnTest(unittest.TestCase):
def test_pawn_init(self):
loc = ("a", 1)
pawn = Pawn(loc, "white")
assert pawn.location == ("a", 1)
assert pawn.has_moved == False
assert pawn.board == None
assert pawn.value == 1
def test_... |
c5da82dced4f145ad6b9b1e567981d1ee448d539 | Depgit/Leetcode_problems | /daksh_assignment.py | 421 | 3.578125 | 4 | 2(a)
a, b = 'Mickey', 'Mouse'
print(a, b)
2(b)
lst = list(map(int, input("enter marks of 5 subject space seprated out of 100").split(" ")))
print('your percentage is', (sum(lst) / 500) * 100)
2(c)
for i in range(1, 11):
print(i * 5, end=" ")
2(d)
print((int(input("enter celsius value")) * 1.8) + 32)
2(e)
lst ... |
ecf31bb078b7e1b3304164982a436b168a8f667b | manoj8412/Python-Scripts | /Problem.py | 574 | 3.546875 | 4 | # https://math.stackexchange.com/questions/2438869/does-this-sequence-have-a-limit
import matplotlib.pyplot as plt
import string
def convert(x, b):
r = ''
while x > 0:
r = string.printable[x % b] + r
x //= b
return r
def digit_adder(num, base=10):
num = convert(num, base)
return sum([in... |
e680606e92b345260d5142e684e54ecac15e2b08 | CnrLwlss/ScientificPython | /Resources/turtleJohn.py | 861 | 3.8125 | 4 | import turtle
john = turtle.Turtle()
john.speed("fastest")
john.hideturtle()
john.pensize(2)
def polygon(side,ngon,colour="black",skip=1):
john.color(colour)
for i in range(ngon):
john.forward(side)
john.right((360.0/ngon)*skip)
def polycircle(side,num,ngon,colour="black"):
for i in range(num):
poly... |
0cb49bd7d4f56804062db55acfe826f31a41398b | CnrLwlss/ScientificPython | /Resources/mtDNA.py | 1,568 | 3.875 | 4 | # string package is for analysing text
# urllib is for downloading data from the web
import string, urllib
# Text file derived from http://www.mitomap.org/MITOMAP/HumanMitoSeq
URL="http://www.staff.ncl.ac.uk/conor.lawless/ScientificPython/Resources/mtDNA.txt"
textfile=urllib.urlopen(URL)
lines=textfile.readlines()
tex... |
285355621a72f1ff847571d0e96aa249a77844b4 | hampusrosvall/leetcode | /maximum_subarray.py | 449 | 3.53125 | 4 | def maximum_subarray(array):
N = len(array)
sums = [float('-inf')] * N
rolling_sum = 0
for idx, nbr in enumerate(array):
rolling_sum += nbr
sums[idx] = rolling_sum
if rolling_sum < 0:
rolling_sum = 0
return max(sums)
"""
[0 0 ... |
4367fc25f256846ac5099ab3674008072da0a93e | hampusrosvall/leetcode | /daily_temperatures.py | 1,798 | 3.921875 | 4 | """
The idea behind the solution is that we, for each temperature that is greater than the follwing days temperature,
we append its index to the a stack. As soon as we encounter a temperature that is greater than the previous days temperature,
we pop the last index from the stack and calculate the difference in posit... |
7fb7857110a21fe03e530fce4b99c8844595602f | hampusrosvall/leetcode | /shortest_path.py | 984 | 3.796875 | 4 | import collections
class Graph:
def __init__(self):
self.graph = collections.defaultdict(list)
def add_connections(self, vertexFrom, vertexTo):
self.graph[vertexFrom].append(vertexTo)
self.graph[vertexTo].append(vertexFrom)
def shortestPath(graph, startVertex, targetVertex):
... |
c93f8656c1237aae09a0fe0ecf58d422b4082c69 | hampusrosvall/leetcode | /linked_list_cycle.py | 992 | 3.75 | 4 | """
Time: O(N)
Space: O(N) as we are using a hashset to store the visited nodes
"""
def findLoopExtraMemory(head):
if not head: return False
cache = set()
currentNode = head
while currentNode:
if currentNode in cache: return True
cache.add(currentNode)
currentNode =... |
26f4e1fa78ef4bd2075143488bdc53f872779140 | hampusrosvall/leetcode | /find_duplicate_number.py | 200 | 3.796875 | 4 | def findDuplicate(nums):
nums.sort()
for i in range(len(nums) - 1):
if nums[i] == nums[i + 1]: return nums[i]
return None
nums = [1, 3, 4, 2, 2]
print(findDuplicate(nums)) |
0e6ff870f543bc2a0d56e5d2c3296563e9ff0b1e | hampusrosvall/leetcode | /buy_sell_stock.py | 296 | 3.671875 | 4 | def stock(prices):
profit = float('-inf')
buy = prices[0]
for i in range(1, len(prices)):
sell = prices[i]
profit = max(profit, sell - buy)
if prices[i] < buy:
buy = prices[i]
return profit
input = [7, 5, 6, 1, 4]
print(stock(input))
|
bb05a9044f8fdaca1ca78ec9d7f63f2840cc9866 | hampusrosvall/leetcode | /merge_linked_lists.py | 2,340 | 4.28125 | 4 | """
P C
l1: 1 -> 6 -> 7 -> 8
N
l2: 2 -> 3 -> 4 -> 5 -> 9 -> 10
The idea is to insert the nodes of the second linked list into the first one.
In order to perform this we keep track of three pointers:
1) prevNode (points to the previous node in the insertion list)
2) currentNode (points... |
3d7d1493ccd3d423eef9aab99be8ce49b583de4e | codedu-python/produce | /phonenumber-masking_ksw.py | 183 | 3.78125 | 4 | phonenumber = input("핸드폰번호 11자리를 입력하세요.")
def masking(phonenumber):
return phonenumber[0:7]+'*'*len(phonenumber[7:])
print(masking(phonenumber))
|
005f84288fd5ac6ce9aff4efa3c680b1d650b8a8 | codedu-python/produce | /요일 출력하기 - 라회택.py | 588 | 3.90625 | 4 | import datetime
print("2017년 A월 B일의 요일을 구하는 프로그램입니다.")
A = 1
B = 1
weekday = 0
days_of_week = ['MON', 'TUE', 'WED', 'THU', 'FRI', 'SAT', 'SUN']
def input_mon_day():
global A, B, weekday
try:
A = int(input("월을 입력하세요 "))
B = int(input("일을 입력하세요 "))
weekday = datetime.date(2017, A, B).w... |
ca39f812bd8271617cbd4ca3629ada41d2569c3d | blueclowd/leetCode | /python/0187-Repeated_dna_sequences.py | 623 | 3.640625 | 4 | '''
Description:
All DNA is composed of a series of nucleotides abbreviated as A, C, G, and T, for example: "ACGAATTCCG". When studying DNA, it is sometimes useful to identify repeated sequences within the DNA.
Write a function to find all the 10-letter-long sequences (substrings) that occur more than once in a DNA mo... |
b9a617f0880e2997d7319464c1c7c5aa7ff3395e | blueclowd/leetCode | /python/1042-Flower_planting_with_no_adjacent.py | 1,257 | 4.1875 | 4 | '''
Description:
You have N gardens, labelled 1 to N. In each garden, you want to plant one of 4 types of flowers.
paths[i] = [x, y] describes the existence of a bidirectional path from garden x to garden y.
Also, there is no garden that has more than 3 paths coming into or leaving it.
Your task is to choose a flower ... |
bd02d1209f41ab5ac17cb91be9b5a96ef24b16c4 | blueclowd/leetCode | /python/1160-Find_words_that_can_be_formed_by_characters.py | 1,127 | 3.78125 | 4 | '''
Description:
You are given an array of strings words and a string chars.
A string is good if it can be formed by characters from chars (each character can only be used once).
Return the sum of lengths of all good strings in words.
'''
class Solution:
def countCharacters(self, words: List[str], chars: str) -> ... |
ddc9be67fb37a2449061804876553c06198d6574 | blueclowd/leetCode | /python/0160-Intersection_of_two_linked_list.py | 979 | 3.796875 | 4 | '''
Description:
Write a program to find the node at which the intersection of two singly linked lists begins.
'''
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def getIntersectionNode(self, headA: ListNode, h... |
0b23ebf4c19a7d6dc6fbea5e184b61d1d6116854 | blueclowd/leetCode | /python/0101-Symmetric_tree.py | 1,458 | 4.15625 | 4 | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
# Iterative
class Solution:
def isSymmetric(self, root: TreeNode) -> bool:
if not root:
return True
... |
5c88a206e86f0e4cc55f36cb4b675d1967eafb24 | blueclowd/leetCode | /python/0147-Insertion_sort_list.py | 943 | 4.09375 | 4 | '''
Description:
Sort a linked list using insertion sort.
'''
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def insertionSortList(self, head: ListNode) -> ListNode:
if not head or not ... |
92ba455171f1907e6bb6c6461bb3a5519d469beb | aTan-aka-Xellos/algorithms-projector | /info/cube_root.py | 890 | 3.9375 | 4 | # to understand see how float point numbers stored
# 60 for 64 bit numbers, but for 32-bit numbers 23 is enough
def cube_root(n: int):
bad = 0
good = n
for i in range(60):
m = (bad+good)/2
if m*m*m >= n:
good = m
else:
bad = m
return good
# Окончание... |
4d6bdbda35e818e8ae854403b464450f592b3458 | SanyaAttri/LeetCode | /00938. Range Sum of BST.py | 1,789 | 3.6875 | 4 | # /usr/bin/env python2
# -*- encoding: utf8 -*-
"""
https://leetcode.com/problems/range-sum-of-bst/
Given the root node of a binary search tree, return the sum of values of all nodes with value between L and R (inclusive).
The binary search tree is guaranteed to have unique values.
Example 1:
Input: root = [1... |
794598df0f82485e6539fef4105015b972e917fd | rorochaudhary/just-get-me-by | /lib/algo.py | 5,325 | 3.78125 | 4 | import math
import copy
#returns an {'error'}: 'messagee'} on failure and the filled list on success
#Gets a target percent, a dictionary holding assignment name keys with data in a list,
# and a dictionary holding group id keys with the group weight and assignments in the group
def calculate_min_grades(target: float,... |
fb9c55ecafa064c5971a33e44fea53dfb163f828 | motiondepp/SmallReptileTraining | /ConcurrentSpider/demo_multiprocessing_lock.py | 1,560 | 3.9375 | 4 | '''
Python 3.X multiprocess 模块演示 Demo
multiprocess 锁同步机制及进程数据共享机制
当注释掉 self.lock.acquire() 和 self.lock.release() 后运行代码会发现最后的 count 为 467195 等,并发问题。
当保留 self.lock.acquire() 和 self.lock.release() 后运行代码会发现最后的 count 为 1000000,锁机制保证了并发。
'''
import multiprocessing
from multiprocessing import Process
class LockProcess(Proc... |
ce355367aa674cabd0169b7060c3f1c0169bbd96 | bxy8804/pyspectrograph | /PySpectrograph/WavelengthSolution/LineSolution.py | 1,214 | 3.5625 | 4 | """LineSolution is a task describing the functional form for transforming
pixel position to wavelength. The inputs for this task are the given pixel position
and the corresponding wavelength. The user selects an input functional form and
order for that form. The task then calculates the coefficients for that form.
P... |
4e34ccae8372a2195d5a0f17f8f5976a67b14803 | MarkCantuba/Python-ADTs | /LinkedList.py | 6,256 | 4.21875 | 4 | # @Author: Mark Cantuba
from LLNode import Node
class LinkedList(object):
"""
A Linked List ADT
"""
def __init__(self):
"""
Constructor method that initializes our Linked List. Creates an empty linked list!
"""
self._root = None
self._last = None
self._... |
1f78c540f60b806c42790f8ad770486c289a92e3 | croguerrero/pythonexercises | /ejerciciospracticafunciones.py | 1,642 | 4.1875 | 4 | def area_rectangulo(base,altura):
"""
Calcula el area del rectangulo
Arg:
base y altura (int or float)
Return:
area(Float)
"""
if base > 0 and altura > 0:
area = base * altura
else:
print("Los parametos ingresados de base y altura no son los correctos")
... |
c35efacbfe8705ab61608190d9aafdf06bcdddd2 | croguerrero/pythonexercises | /ejercicio8.py | 501 | 3.671875 | 4 | #combinando break y continue
s= "Pensamos demasiado y sentimos muy poco"
letter = input("Introduce una letra: ")
n = int(input("Indica el numero de veces que quieres que aparezca la letra anterior: "))
count= 0
s = s.lower()
letter= letter.lower()
for c in s:
if count >= n:
print("\nSe ha superado el limit... |
c98bb5bb0e732c435b577a70b9e9b7cc4d3b38e9 | croguerrero/pythonexercises | /filterfuncion.py | 723 | 4.125 | 4 | ###La funcion filter
## aplica la funcion a todos los elementos de un objeto iterable
##Devuelve un objeto generado de ahiq eu usemos las funcion list() para convertirlo a lista
### Duvuelve los elementos para los cuales aplicar la funcion devuelve un true
nums = [49, 57, 62, 147, 2101, 22]
print(list(filter(lambd... |
890ce9918a263281135dd400c1e099eee9f52558 | croguerrero/pythonexercises | /ejercicios24.py | 1,564 | 4.03125 | 4 | """El diccionario define una relación uno a uno entre claves y valores."""
datos_basicos = {
"nombres":"Marcelo ",
"apellidos":"Guerrero",
"cedula":"26938401",
"fecha_nacimiento":"03/12/1980",
"lugar_nacimiento":"Ibarra Ecuador",
"nacionalidad":"Ecuatoriana",
"estado_civil":"Soltero"
}
prin... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.