blob_id stringlengths 40 40 | repo_name stringlengths 5 127 | path stringlengths 2 523 | length_bytes int64 22 3.06M | score float64 3.5 5.34 | int_score int64 4 5 | text stringlengths 22 3.06M |
|---|---|---|---|---|---|---|
e03ee23d27385f92bde5067aa3158823807ac747 | ismael-lopezb/employee_class_project | /data_cleaning.py | 2,303 | 3.59375 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Feb 22 23:20:36 2021
@author: ismaellopezbahena
"""
#import usefull libraries
import pandas as pd
import numpy as np
#read csv file and get the info
df = pd.read_csv('aug_train.csv')
df.info()
#let's replace the gender missing data with the mode
gmode... |
34880def1217c10482dbbd3c637552fff0035ef3 | mishra-ankit-dev/tkinter-chat-automation | /chatApp/gui_chat.py | 1,659 | 3.625 | 4 | # -*- coding:utf-8 -*-
import sys
import time
import signal
import socket
import select
import tkinter
from tkinter import *
from threading import Thread
class client():
""" This class initializes client socket
"""
def __init__(self, server_ip = '0.0.0.0', server_port = 8081):
if len(sys... |
52b60e4bba09587fefd57678440a8afe275b955c | chiachunho/NTNU_OOAD_Homework | /Homework1/Homework1-2/main.py | 1,133 | 3.703125 | 4 | from Triangle import Triangle
from Square import Square
from Circle import Circle
from ShapeDatabse import ShapeDatabase
# construct shapes
shape1 = Triangle(0, 1, 6)
shape2 = Square(2, 2, 4, side_length=2)
shape3 = Circle(3, 3, 5, radius=3)
shape4 = Circle(2, 3, 3, radius=4)
shape5 = Square(1, 2, 1, side_length=5)
sh... |
f0d679d573068b5fc1f2d66b2f0d2c17824c22ed | mdzierzecki/algorithms | /binarytree/Node.py | 370 | 3.53125 | 4 | class Node:
def __init__(self, key=None):
self.key = key
self.left = None
self.right = None
def set_root(self, key):
self.key = key
def insert_left(self, new_node):
self.left = new_node
def insert_right(self, new_node):
self.right = new_node
def __... |
cc0c510075db7641bd5ae83e88c52b248473d999 | nik-panekin/pyramid_puzzle | /button.py | 1,238 | 4.09375 | 4 | """Module for implementation the Button class.
"""
import pygame
from blinking_rect import BlinkingRect
class Button(BlinkingRect):
"""The Button class implements visual rectangular element with a text
inside. It can be used for GUI.
Public attributes:
caption: str (read only) - stores button cap... |
1bb64c12a5738bc206746e547ed525089aaf0742 | lux563624348/Python_Learn | /basic/OI.py | 965 | 3.796875 | 4 | ########################################################################
#### Reading and Writing Files
###### Xiang Li Feb.18.2017
########################################################################
########################################################################
##Module
###############################... |
5ce316ef78144c1268521a913a494eead0b2baee | Yanhenning/python-exercises | /one/test_first_exercise.py | 1,213 | 3.65625 | 4 | from unittest import TestCase
from one.first_exercise import return_duplicated_items
class FirstExerciseTests(TestCase):
def test_return_empty_list_given_an_empty_list(self):
duplicated_items = return_duplicated_items([])
self.assertEqual([], duplicated_items)
def test_return_empty_list_giv... |
735e3a6325d2805d14e72615163138df6e79679f | Akawi85/Tiny-Python-Project | /03_picnic/picnic.py | 1,477 | 4.09375 | 4 | #!/usr/bin/env python3
"""
Author : Me <ifeanyi.akawi85@gmail.com>
Date : 31-10-2020
Purpose: A list of food for picnic!
"""
import argparse
# --------------------------------------------------
def get_args():
"""Get command-line arguments"""
parser = argparse.ArgumentParser(
descri... |
e650ddccebf0c6e1e97ee8c934e7c12948d299ab | BoHyeonPark/test1 | /028.py | 393 | 3.546875 | 4 | #!/usr/bin/python3
seq1 = "ATGTTATAG"
new_seq = ""
seq_dic = {"A":"T","T":"A","C":"G","G":"C"}
for i in seq1:
new_seq += seq_dic[i]
print(seq1)
print(new_seq)
new_seq1 = ""
for i in seq1:
if i == "A":
new_seq1 += "T"
elif i == "T":
new_seq1 += "A"
elif i == "C":
new_seq1 += "G"... |
c18490e52668ed9fc558ab7e4c1438dccd72427c | BoHyeonPark/test1 | /029.py | 207 | 3.53125 | 4 | #!/usr/bin/python3
seq1 = "ATGTTATAG"
print("C" in seq1)
for s in seq1:
b = (s == "C") #s == "C" -> False
print(s,b)
if b:
break
import re
p = re.compile("C")
m = p.match(seq1)
print(m)
|
cf7706deabaa3e1f59c8bb31bf34980cee4ea881 | BoHyeonPark/test1 | /014.py | 112 | 3.890625 | 4 | #!/usr/bin/python3
a = input("Enter anything: ")
if a.isalpha():
print("alphabet")
else:
print("digit")
|
cb8c1db76f1c7184635920f5811c56141929dbbf | BoHyeonPark/test1 | /034.py | 378 | 3.96875 | 4 | #!/usr/bin/python3
l = [3,1,1,2,0,0,2,3,3]
print(max(l))
print(min(l))
for i in range(0,len(l),1):
if i == 0: #set max_val, min_val
max_val = l[i]
min_val = l[i]
else:
if max_val < l[i]:
max_val = l[i] #max_val change
if min_val > l[i]:
min_val = l[i] #m... |
c891cd0f585b21859cfde5ffc0ef3aa77dbf2401 | BoHyeonPark/test1 | /assignment1_3.py | 111 | 3.515625 | 4 | #!/usr/bin/python3
try:
n = input("Enter number: ")
print(10/n)
except TypeError:
print("no zero")
|
3cada4756c6fd7259becea52725a3b85a0d7c25d | maxalbert/micromagnetic-standard-problem-ferromagnetic-resonance_v3_rewrite | /src/postprocessing/util.py | 1,478 | 3.96875 | 4 | def get_conversion_factor(from_unit, to_unit):
"""
Return the conversion factor which converts a value given in unit
`from_unit` to a value given in unit `to_unit`.
Allowed values for `from_unit`, `to_unit` are 's' (= second), 'ns'
(= nanosecond), 'Hz' (= Hertz) and 'GHz' (= GigaHertz). An error
... |
34c657d098bd5e80640c4da17189022219528c7e | zhangchuan92910/cmpt419 | /k_nearest_neighbor.py | 2,899 | 3.609375 | 4 | import numpy as np
from math import log10, floor
from collections import defaultdict
import os
from utils import *
def round_to_1(x):
return round(x, -int(floor(log10(abs(x)))))
def compute_distances(X1, X2, name="dists"):
"""Compute the L2 distance between each point in X1 and each point in X2.
It's pos... |
56df42f25fc0a3dddd57a8d70c63d7a3a4754900 | devmadhuu/Python | /assignment_01/check_substr_in_str.py | 308 | 4.34375 | 4 | ## Program to check if a Substring is Present in a Given String:
main_str = input ('Enter main string to check substring :')
sub_str = input ('Enter substring :')
if main_str.index(sub_str) > 0:
print('"{sub_str}" is present in main string - "{main_str}"'.format(sub_str = sub_str, main_str = main_str))
|
92d2b840f03db425aaaedf22ad57d0b291bb79e6 | devmadhuu/Python | /assignment_01/odd_in_a_range.py | 505 | 4.375 | 4 | ## Program to print Odd number within a given range.
start = input ('Enter start number of range:')
end = input ('Enter end number of range:')
if start.isdigit() and end.isdigit():
start = int(start)
end = int(end)
if end > start:
for num in range(start, end):
if num % 2 != 0:
... |
020278f3785bb409de5cd0afd67c4ccaf295e011 | devmadhuu/Python | /assignment_01/three_number_comparison.py | 1,464 | 4.21875 | 4 | ## Program to do number comparison
num1 = input('Enter first number :')
if num1.isdigit() or (num1.count('-') == 1 and num1.index('-') == 0) or num1.count('.') == 1:
num2 = input('Enter second number:')
if num2.isdigit() or (num2.count('-') == 1 and num2.index('-') == 0) or num2.count('.') == 1:
num3 =... |
bca391936ad2f918c4700dc581de7558dd081f41 | devmadhuu/Python | /assignment_01/ljust_rjust_q18.py | 409 | 3.6875 | 4 | my_str = 'Peter Piper Picked A Peck Of Pickled Peppers.'
sub_str = 'Peck'
index = 0
str_index = -1
replaced_str = ''
while my_str[index:]:
check_str = my_str[index:index + len(sub_str)]
if check_str == sub_str:
replaced_str = sub_str.rjust(index+1, '*')
replaced_str+=sub_str.ljust(len(my_str) - ... |
66c8afbcdd793b3817993abfb904b4ec0111f666 | devmadhuu/Python | /assignment_01/factorial.py | 410 | 4.4375 | 4 | ## Python program to find the factorial of a number.
userinput = input ('Enter number to find the factorial:')
if userinput.isdigit() or userinput.find('-') >= 0:
userinput = int(userinput)
factorial = 1
for num in range (1, userinput + 1):
factorial*=num
print('Factorial of {a} is {factorial}'.... |
83c5184a88d030bfd7d873e728653ac1f0248245 | alee86/Informatorio | /Practic/Estructuras de control/Condicionales/desafio04.py | 1,195 | 4.28125 | 4 | '''
Tenemos que decidir entre 2 recetas ecológicas.
Los ingredientes para cada tipo de receta aparecen a continuación.
Ingredientes comunes: Verduras y berenjena.
Ingredientes Receta 1: Lentejas y apio.
Ingredientes Receta 2: Morrón y Cebolla..
Escribir un programa que pregunte al usuario que tipo de receta desea,
... |
e4fe2f3a2fcb0f61de0a04aa746de174b64c9256 | alee86/Informatorio | /Practic/Estructuras de control/Complementarios/Complementarios4.py | 325 | 3.90625 | 4 | """
Realizar un programa que sea capaz de, habiéndose ingresado dos números m y n, determine si n es divisor de m.
"""
m = int(input("Ingrese el valor para el numerador "))
n = int(input("Ingrese el valor para el denominador "))
if m%n == 0:
print(f"{n} es DIVISOR de {m}")
else:
print(f"{n} es NO es DIVISOR de {m}"... |
213dab8cccc5a3d763c4afd329e6a461bb920b01 | alee86/Informatorio | /Practic/Estructuras de control/Repetitivas/desafio04.py | 973 | 4.03125 | 4 | '''
DESAFÍO 4
Escriba un programa que permita imprimir un tablero Ecológico (verde y blanco) de
acuerdo al tamaño indicado. Por ejemplo el gráfico a la izquierda es el resultado
de un tamaño: 8x6
import os
os.system('color')
columna = int(input("ingrese columnas: "))
fila = int(input("ingrese filas: "))
for fil... |
55efa3a71c684d8f68040ef917434b00a2bb589d | alee86/Informatorio | /Practic/Estructuras de control/Condicionales/desafio01.py | 793 | 4.09375 | 4 | '''
En nuestro rol de Devs (Programador o Programadora de Software), debemos elaborar un programa
en Python que permita emitir un mensaje de acuerdo a lo que una persona ingresa como
cantidad de años que viene usando insecticida en su plantación. Si hace 10 o más añoss,
debemos emitir el mensaje "Por favor solicite ... |
90965bb42e72a97fbea66ed53de0feff2eecc19c | alee86/Informatorio | /Practic/Listas/complementarios16.py | 1,164 | 4.03125 | 4 | '''
f. Se tiene una lista con los datos de los clientes de una compañía de telefonía celular,
los cuales pueden aparecer repetidos en la lista, si tienen registrado más de un número
telefónico. La compañía para su próximo aniversario desea enviar un regalo a sus clientes,
sin repetir regalos a un mismo cliente. En u... |
e23daf79dd41f1bce58bbaab7858941562be66ef | alee86/Informatorio | /Practic/Listas/complementarios12.py | 437 | 3.9375 | 4 | '''
b. Leer una frase y luego invierta el orden de las palabras en la frase. Por Ejemplo:
“una imagen vale por mil palabras” debe convertirse en “palabras mil por vale imagen una”.
'''
frase = str(input('Ingrese una frase para verla invrertida: '))
lista = frase.split()
#el metodo split toma un string y lo divide se... |
77329d1eb28a5d3565a346a30047871d2306abc6 | alee86/Informatorio | /Practic/Estructuras de control/Repetitivas/desafio01.py | 1,484 | 4.21875 | 4 | '''
DESAFÍO 1
Nos han pedido desarrollar una aplicación móvil para reducir comportamientos inadecuados para el ambiente.
a) Te toca escribir un programa que simule el proceso de Login. Para ello el programa debe preguntar
al usuario la contraseña, y no le permita continuar hasta que la haya ingresado correctamente.
... |
dd112a464e3c0ad07c28a31b94b693d533f758b3 | alee86/Informatorio | /Practic/06distribucionEstudiantes.py | 470 | 3.84375 | 4 | name = ""
while name != "quite":
name = input("Ingresa tu nombre completo: ").upper()
turn = input("ingresa si sos del TT (Turno Tarde) o del TN (Turno Noche): ").upper()
letters = "ABCDEFGHIJKLMNÑOPQRSTUVWYZ"
ft_letra = name[0]
if (letters[0:13].find(ft_letra) >= 0 and turn == "TT") or (letters[13:25].find(f... |
5112700bd8249864e978ed76dd52f85586fe848c | alee86/Informatorio | /Practic/Profe y compañeros/Desafio3.py | 1,400 | 4.09375 | 4 | '''Para el uso de fertilizantes es necesario medir cuánto abarca un determinado compuesto en el suelo el cual debe existir en una cantidad
de al menos 10% por hectárea, y no debe existir vegetación del tipo MATORRAL. Escribir un programa que determine si es factible la
utilización de fertilizantes.'''
print("Inicia... |
2649df22c828074a1eff5bcace5a2bf86dc5db98 | alee86/Informatorio | /Practic/numerosPrimos.py | 216 | 3.890625 | 4 | num = int(input("Numero para evaluar: "))
contador = 0
for x in range(num):
if num%(x+1) == 0:
contador += 1
if contador > 2:
print(f"El número {num} NO es primo")
else:
print(f"El número {num} SI es primo")
|
dd1eb3db497541007cb6abc22addb58838732c45 | bp345sa/Fizz | /Ex 5.py | 553 | 3.53125 | 4 | name = 'Zed A. Shaw'
age = 23 # not a lie
height = 74 # inches
h1 = height * 2.54
weight = 180 # lbs
w1 = weight * 0.456
eyes = 'Blue'
teeth = 'White'
hair = 'Brown'
print "Let's talk about %s." % name
print "He's %f centimetres tall." % h1
print "He's %f kilograms heavy." % w1
print "Actually that's not too heavy."
p... |
edff8364358f12b7248f2adb0d61cf18a97c349b | dds-utn/patrones-comunicacion | /corutinas/generator.py | 165 | 3.6875 | 4 | def productor():
n = 0
while True:
yield n
n += 1
def consumidor(productor):
while True:
println(productor.next())
consumidor(productor())
|
372fb0a40da5ea72d757f22ca8ed239abc52910d | CompAero/Genair | /geom/aircraft.py | 2,040 | 3.78125 | 4 | from part import Part
__all__ = ['Aircraft']
class Aircraft(Part, dict):
''' An Aircraft is a customized Python dict that acts as root for
all the Parts it is composed of.
Intended usage
--------------
>>> ac = Aircraft(fuselage=fus, wing=wi)
>>> ac.items()
{'wing': <geom.wing.Wing at ... |
1ee513ff7f5aac3fd043c7a907f7339a2348224a | vinvaid1989/training | /datecheck.py | 613 | 3.703125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Jan 17 14:20:10 2018
@author: RPS
"""
import datetime
print(datetime.datetime.now().hour)
def cutoff(amount):
currtime=datetime.datetime.now().hour;
if(currtime > 17):
print ("tomorrow")
else:
print ("ok")
cutoff(56) ... |
a877604bf5f4ed8a8ebb23c4a5e123113084a9cf | Tyshkevichvyacheslav/Lr3 | /22.4.py | 1,435 | 4.09375 | 4 | print("Уравнения степени не выше второй — часть 2")
def solve(*coefficients):
if len(coefficients) == 3:
d = coefficients[1] ** 2 - 4 * coefficients[0] * coefficients[2]
if coefficients[0] == 0 and coefficients[1] == 0 and coefficients[2] == 0:
x = ["all"]
elif coeffici... |
5cb27604af3a7a610dd5c6f0c072d10254141496 | Tyshkevichvyacheslav/Lr3 | /23.1.py | 282 | 3.625 | 4 | print("Мимикрия")
transformation = lambda x: x
values = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29]
transformed_values = list(map(transformation, values))
if values == transformed_values:
print('ok')
else:
print('fail')
input("Press any key to exit")
exit(0) |
e2a854d1e492f741a8eb5746d76e51532edf5e68 | Tyshkevichvyacheslav/Lr3 | /21.4.py | 332 | 4.09375 | 4 | print("Фрактальный список – 2")
def defractalize(fractal):
return [x for x in fractal if x is not fractal]
fractal = [2, 5]
fractal.append(3)
fractal.append(9)
print(fractal)
print("____________")
fractal = [2, 5]
fractal.append(3)
print(fractal)
input("Press any key to exit")
exit(0)
|
bb02d54d7e24832e5fac78aed4fc6ae2ab765dc6 | CognitiveNetworking/IOT-Malware | /ScoringAndPerformance/stats_calcutaion.py | 7,994 | 3.5 | 4 | '''
Program name : stats_calculation.py
Author : Manjunath R B
This program Calcutes the statistics and generate statistical features.
The program calculates statistics per class per feature basis.
The program accepts three command line arguments
1. input file name
2. output file name
3. Quartile step value
... |
96ee7f84b68f60c999e8450ade3f30ad667b89e8 | amark02/ICS4U-Classwork | /Classes/Encapsulation_1.py | 665 | 3.84375 | 4 |
class Person:
def __init__(self, name: str, age: int):
self.set_name(name)
self._age = age
def get_age(self):
#age = time_now - self.date_of_birth
return self._age
def set_age(self, value: int):
self._age = value
def get_name(self):
return self._fi... |
6d030f79eb3df2a3572eaadb0757401d3a330326 | amark02/ICS4U-Classwork | /Quiz2/evaluation.py | 2,636 | 4.25 | 4 | from typing import Dict, List
def average(a: float, b: float, c:float) -> float:
"""Returns the average of 3 numbers.
Args:
a: A decimal number
b: A decimal number
c: A decimal number
Returns:
The average of the 3 numbers as a float
"""
return (a + b + c)/3
def c... |
5b632636066e777092b375219a7a6cd571619157 | amark02/ICS4U-Classwork | /Classes/01_store_data.py | 271 | 4.1875 | 4 |
class Person:
pass
p = Person()
p.name = "Jeff"
p.eye_color = "Blue"
p2 = Person()
print(p)
print(p.name)
print(p.eye_color)
"""
print(p2.name)
gives an error since the object has no attribute of name
since you gave the other person an attribute on the fly
""" |
4a1e0cd10aa31c063f1b38f2197e6c640ab0e1d9 | robotBaby/linearAlgebrapython | /HW3.py | 608 | 3.671875 | 4 | from numpy import linalg as LA
import numpy as np
#Question 1
def get_determinant(m):
return LA.det(m)
##### Examples
#Eg: 1
#a = np.array([[4,3,2], [1,2,6], [5,8,1]])
#print get_determinant(a)
#b = np.array([[1, 2], [1, 2]])
#print get_determinant(b)\
#Question 2
def find_area(three_points):
m = np.array(three... |
012b65d8534f8d52d843fb52bed3e2827ff2d605 | doranbae/shinko | /images/playShinko_vanilla.py | 6,761 | 3.640625 | 4 | # +--------------------------+
# | SHINKO |
# | Play the mobile game |
# +--------------------------+
import numpy as np
# set random seed
np.random.seed(84)
# define variables
matrix_min = 1
matrix_max = 5
matrix_width = 5
level_num = 2
shinko_goal = 5
han... |
72f64a3b98ee883737a0ea668eda1151365d72b6 | MorHananovitz/CSCI-315-Artificial-Intelligence-through-Deep-Learning | /Assignment2/perceptron.py | 1,034 | 3.515625 | 4 | import numpy as np
#Part 1 - Build Your Perceptron (Batch Learning)
class Perceptron:
def __init__(self,n, m):
self.input = n
self.output = m
self.weight = np.random.random((n+1,m))-0.5
def __str__(self):
return str( "This is a Perceptron with %d inputs and %d outputs... |
e2fc0eb8047bbe73f5be60371a03ad388bc7f388 | ClaeysKobe/Kobeehhh | /Thuis 3.py | 520 | 3.609375 | 4 | print("*** Welkom bij het kassasysteem ***")
broeken = int(input("Hoeveel broeken werden er verkocht? "))
tshirts = int(input("Hoeveel T-shirts werden er verkocht? "))
vesten = int(input("Hoeveel vesten werden er verkocht? "))
prijs_broeken = broeken * 70.5
prijs_tshirts = tshirts * 20.89
prijs_vesten = vesten * 100.3
... |
23ee2c8360e32e0334a31da848043cf6187cd636 | cosinekitty/astronomy | /demo/python/gravity.py | 1,137 | 4.125 | 4 | #!/usr/bin/env python3
import sys
from astronomy import ObserverGravity
UsageText = r'''
USAGE:
gravity.py latitude height
Calculates the gravitational acceleration experienced
by an observer on the surface of the Earth at the specified
latitude (degrees north of the equator) and height
(met... |
6d0702099e71e5065cc3a1bdfeb152995fccdc81 | loki2236/Python-Practice | /src/Ej2.py | 439 | 3.71875 | 4 | #
# Dada una terna de números naturales que representan al día, al mes y al año de una determinada fecha
# Informarla como un solo número natural de 8 dígitoscon la forma(AAAAMMDD).
#
dd = int(input("Ingrese el dia (2 digitos): "))
mm = int(input("Ingrese el mes (2 digitos): "))
yyyy = int(input("Ingrese e... |
c5c9ed70accfeafc3d4ec07f8e9b9a556ec7143c | Dibyadarshidas/py4e | /open_files and big_count.py | 449 | 3.671875 | 4 | name = input("Enter file:")
handle = open(name)
counts = dict()
bigcount = None
bigword = None
smallcount = None
smallword = None
for line in handle:
words = line.split()
for word in words:
counts[word] = counts.get(word,0) + 1
#print(counts)
for p,q in counts.items():
print(p,q)
i... |
11575571fe85a08533ad8cfaffcdbd1c4936a8d8 | Dibyadarshidas/py4e | /19.09.2020.py | 640 | 3.640625 | 4 | # Sort by values instead of key
#c = {'a':10, 'b':1, 'c':22 }
#tmp = []
#for k, v in c.items() :
# tmp.append((v, k))
#print(tmp)
#tmp = sorted(tmp, reverse=True)
#print(tmp)
# Long Method
#fhand =open('words.txt')
#counts = {}
#for line in fhand:
# words = line.split()
# for word in words:
# ... |
a7f2d4a9a20c2eb58a04861708ac895baa6156ee | abeltomvarghese/Data-Analysis | /Learning/DataFrames.py | 724 | 3.765625 | 4 | import pandas as pd
import matplotlib.pyplot as plt
from matplotlib import style
style.use("fivethirtyeight")
web_stats = {"Day":[1,2,3,4,5,6],
"Visitors":[43,34,65,56,29,76],
"Bounce Rate": [65,67,78,65,45,52]}
#CONVERT TO DATAFRAME
df = pd.DataFrame(web_stats)
#PRINT THE FIRST FEW VALUES
pri... |
b8aa70ebee9c3db49bbc8905f88f0e604734894d | pureforwhite/ToyEncryptionAlgorithm | /main.py | 1,729 | 4.09375 | 4 | #PureForWhite create a string encryption program with Toy Encryption Algorithm
#The source code will be in the link description below
#Follow me on reddit, subscribe my youtube channel, like this video and share it thanks!
#creating decryption function
def decryption(s):
s = list(s)
for i in range(len(s)):
... |
de463c40b80011fd725e2675aa1ab0c4a16cf8c6 | joshinihal/dsa | /recursion/basic_problems.py | 1,146 | 3.828125 | 4 | # Write a recursive function which takes an integer
# and computes the cumulative sum of 0 to that integer
def rec_sum(n):
if n == 0:
return 0
return n + rec_sum(n-1)
rec_sum(10)
#-------------------------------------------------
# Given an integer, create a function which returns the sum of all... |
e27d035e4e5e2cb1a95204bcdbccae9237d70eda | joshinihal/dsa | /trees/binary_heap_implementation.py | 2,258 | 3.796875 | 4 | # min heap implementation
# https://en.wikipedia.org/wiki/Binary_heap
# list has a '0' element at first index(0) i.e. [0,.....]
class BinHeap():
def __init__(self):
self.heapList = [0]
self.currentSize = 0
def perUp(self, i):
while i // 2 > 0:
... |
e79076cd45b6280c2046283d9a349620af0f8d70 | joshinihal/dsa | /trees/tree_implementation_using_oop.py | 1,428 | 4.21875 | 4 | # Nodes and References Implementation of a Tree
# defining a class:
# python3 : class BinaryTree()
# older than python 3: class BinaryTree(object)
class BinaryTree():
def __init__(self,rootObj):
# root value is also called key
self.key = rootObj
self.leftChild = None
self.righ... |
4999709b618b6edca8a2e462c4575a56f81a580c | Amit998/python_software_design | /Intro/guess_game.py | 1,036 | 3.78125 | 4 | class GuessNumber:
def __init__(self,number,min=0,max=100):
self.number = number
self.guesses=0
self.min=min
self.max=max
def get_guess(self):
guess=input(f"Please guess a Number ({self.min} - {self.max}) : ")
if (self.valid_number(guess)):
retur... |
2e41ccaf34b9b6d8083df766a3a578418bbf6db0 | Khizanag/algorithms | /FooBar/Level 3/Bunny Prisoner Locating/Bunny Prisoner Locating.py | 186 | 3.796875 | 4 | def solution(x, y):
H = x + y - 1
n = 1 # value when x = 1
temp = 0 # n increases by temp
for i in range(H):
n += temp
temp += 1
print(n + x - 1)
print(solution(3, 2)) |
6d67c92e324e39b17788d860548bfd23059ca5af | domzhaomathematics/Competitive-Coding-8 | /minimum_window_substring.py | 2,246 | 3.53125 | 4 | #Time Complexity: O(s+t), traversal and building hashmaps
#Space complexity: O(s+t),length of S and T
'''
Evertime we encounter a letter that belongs to T, we append it to a queue and
increment the hashmap with that key. We keep a hashmap to check how many times
the letter appear in T. If we've found all the letter of... |
20ac70eaf04d544691436bbd5c6c0f5323ba40f8 | rizveeredwan/UID-Generation-Based-On-Polynomial-Hashing | /PhoneticMeasurePerformance/name_generator.py | 1,631 | 3.65625 | 4 | import csv
"""
### SEGMENT 1: Name collection
### Taking input of all the names ######
names=[]
with open('/home/student/Desktop/PhoneticAccuracyMeasure3/UID-Generation-Based-On-Polynomial-Hashing/TrainingData.csv') as csvFile:
csvReader = csv.DictReader(csvFile)
for row in csvReader:
v=row['name'].split(' ')
... |
74725fc2d2c7d06cec7bc468aa078f59e6aa21e7 | AGriggs1/Labwork-Fall-2017 | /hello.py | 858 | 4.125 | 4 | # Intro to Programming
# Author: Anthony Griggs
# Date: 9/1/17
##################################
# dprint
# enables or disables debug printing
# Simple function used by many, many programmers, I take no credit for it WHATSOEVER
# to enable, simply set bDebugStatements to true!
##NOTE TO SELF: in Python, first letter ... |
dbf03069fac82c54e3a158dae1d62b0589440176 | jphilippou27/kingmakers_capstone | /data/os2/load_cmte_advanced.py | 1,002 | 3.640625 | 4 | import csv, sqlite3, sys
if __name__ == "__main__":
conn = sqlite3.connect("os2.db")
cur = conn.cursor()
cur.execute("DROP TABLE IF EXISTS cmte_advanced;")
conn.commit()
cur.execute("""CREATE TABLE cmte_advanced (
id TEXT(9),
name TEXT(50),
parent TEXT(50),
cand_... |
4188c44dda65c2849f1ae89fd19eb46b7efffd14 | dancing-elf/add2anki | /add2anki/add2anki.py | 2,805 | 3.734375 | 4 | """Interactively translate and add words to csv file if needed"""
import argparse
import sys
import tempfile
import urllib
import colorama
import pygame
import add2anki.cambridge as cambridge
def add2anki():
"""Translate and add words to csv file if needed"""
parser = argparse.ArgumentParser()
parser.ad... |
29855d475c40a99d9c99896389b0129981d29131 | ochuerta/bolt | /docs/_includes/lesson1-10/Boltdir/site-modules/exercise8/tasks/great_metadata.py | 853 | 3.53125 | 4 | #!/usr/bin/env python
"""
This script prints the values and types passed to it via standard in. It will
return a JSON string with a parameters key containing objects that describe
the parameters passed by the user.
"""
import json
import sys
def make_serializable(object):
if sys.version_info[0] > 2:
return ob... |
243f97a94733bea6491fda338ab7831a6e773e4a | solonmoraes/CodigosPythonTurmaDSI | /Exercicio1/segunda atv.py | 186 | 3.9375 | 4 | print("===========Atividade=============")
salaTotal = float(input("Informe o quanto recebeu:\n"))
horasDia = int(input("Informe suas horas trabalhadas:\n"))
print(salaTotal / horasDia)
|
38445453493bcae3afdfafc93fd6568027dca64d | solonmoraes/CodigosPythonTurmaDSI | /Listas.py | 656 | 4.09375 | 4 | pessoas = ["Fabio","Carlos","Regina","Vanuza"]
print(type(pessoas))
print(pessoas)
pessoas[1] = "Sergio"
# adicionar elementoas
pessoas.append("Sarah")# adiciona no final
pessoas.insert(2,"Flavio")#adiciona em qualquer lugar
for chave, valor in enumerate(pessoas):
print(f"{chave:.<5}{valor}")
#removendo eleme... |
079e2d347895e1d1cf900b4772a3ad5902f793d7 | solonmoraes/CodigosPythonTurmaDSI | /banco de dados mongo/POO/aula3/conta.py | 1,220 | 3.8125 | 4 | class Conta:
def __init__(self, numero, titular, saldo, limite=1000):
self.__numero = numero
self.__titular = titular
self.__saldo = saldo
self.__limite = limite
def depositar(self, valor):
if valor < 0:
print("Voce nao pode depositar valor negativo")
... |
f2794e3c31b085db9b10afa837d6026848ef1318 | lucasferreira94/Python-projects | /jogo_da_velha.py | 1,175 | 4.25 | 4 | '''
JOGO DA VELHA
'''
# ABAIXO ESTAO AS POSIÇÕES DA CERQUILHA
theBoard = {'top-L':'', 'top-M':'', 'top-R':'',
'mid-L':'','mid-M':'', 'mid-R':'',
'low-L':'', 'low-M':'', 'low-R':''}
print ('Choose one Space per turn')
print()
print(' top-L'+' top-M'+ ' top-R')
print()
print(' mid-L'+' mid-... |
a9746ae70ae68aefacd3bb071fae46e949a7e29f | YangYishe/pythonStudy | /src/day8_15/day8_2.py | 683 | 4.40625 | 4 | """
定义一个类描述平面上的点并提供移动点和计算到另一个点距离的方法。
"""
class Point:
def __init__(self, x, y):
self._x = x
self._y = y
def move(self, x, y):
self._x += x
self._y += y
def distance_between(self, other_point):
return ((self._x - other_point._x) ** 2 + (self._y - other_point._y) *... |
f12289953bccf14110d3d75acca9b35797bf9b30 | YangYishe/pythonStudy | /src/day1_7/day4_3.py | 481 | 3.984375 | 4 | """
打印如下所示的三角形图案。
"""
for i1 in range(1, 6):
for i2 in range(1, i1 + 1):
print('*', end='')
print('')
for i1 in range(1, 6):
for i2 in range(1, 6):
if i2 + i1 <= 5:
print(' ', end='')
else:
print('*', end='')
print('')
for i1 in range(1, 6):
for i2 i... |
5c754378bc33111b88a28b80317c95ba075664a5 | YangYishe/pythonStudy | /src/day1_7/day7_6.py | 339 | 3.734375 | 4 | """
打印杨辉三角。
"""
def yhsj(n):
arr1=[1,1]
for i in range(n-1):
arr2=[1]
for j in range(i):
arr2.append(arr1[j]+arr1[j+1])
arr2.append(1)
arr1=arr2
yield arr1
pass
def main():
for i in yhsj(10):
print(i)
pass
if __name__ == '__main__':
m... |
bd49df8de11f36cfc6b881024001c01f6c88348e | benb2611/AmericanAirlines-scraper | /american_airlines.py | 16,446 | 3.828125 | 4 | """
Contains AmericanAirlines class, where help methods and logic for scraping data
from American Airlines web site are implemented. (all for educational purposes only!)
Check '__init__()' docstring for required parameters. To start scraping - just create instance of AmericanAirlines
and use 'run()' method. Example:
... |
aab450116da1a0597767e1062274c9088cf8a9ef | damilarey98/user_validation | /user_validation.py | 1,813 | 3.90625 | 4 | import random
value = "abcdefghijklmnopqrstuvwxyz1234567890"
client_info = {}
n = int(input("How many number of users?: "))
#since range begins from 1, when n=2, it request only one value
for i in range(1, n):
new_client = {}
print("Enter first name of user", i, ":")
fname = input()
print("Enter l... |
43d06f5cb81bd0e3c924b99164a4526758979052 | SanamKhatri/school | /student_update.py | 4,554 | 3.828125 | 4 | import student_database
from Student import Student
def update_student():
roll_no = int(input("Enter the roll no:"))
is_inserted = student_database.getStudentDetails(roll_no)
if is_inserted:
student_deatail = student_database.getStudentDetails(roll_no)
print(student_deatail)
print(... |
73a9544105ca7eae0d7997aa2e0a4b74bf8723b7 | SanamKhatri/school | /teacher_delete.py | 1,234 | 4.1875 | 4 | import teacher_database
from Teacher import Teacher
def delete_teacher():
delete_menu="""
1.By Name
2.By Addeess
3.By Subject
"""
print(delete_menu)
delete_choice=int(input("Enter the delete choice"))
if delete_choice==1:
delete_name=input("Enter the name of the... |
8103864502cd9649a73788870dabc9ac9cca1c6f | simhaonline/Database-Service-REST-API | /apps/app.py | 4,488 | 3.53125 | 4 | '''
SAMPLE DATABASE AS A SERVICE API
Register a user with username and password
Login a user with username and password
A user gets 10 coins by default when registration completed.
Every time a user logs in 1 coin is used up.
Once all coins are used up the registered user won't be able to l... |
551d2c2c5d240929b8289bd9e86c95bd1c599114 | DRogalsky/dataVisualizationPythonCC | /dice.py | 317 | 3.625 | 4 | from random import randint
class Die:
"a class to represent a single die"
def __init__(self, num_sides=6):
"""assume 6 sides"""
self.num_sides = num_sides
def roll(self):
"""spit out a random number between 1 and the number of sides"""
return randint(1, self.num_sides)
|
b86433902a7cf3e9dcba2d7f254c4318656ca7f7 | heba-ali2030/number_guessing_game | /guess_game.py | 2,509 | 4.1875 | 4 | import random
# check validity of user input
# 1- check numbers
def check_validity(user_guess):
while user_guess.isdigit() == False:
user_guess = input('please enter a valid number to continue: ')
return (int(user_guess))
# 2- check string
def check_name(name):
while name.isalpha() == False:
... |
f782209a4fb946cb6834f6c60cd33dd93d40b86e | josephevans24/SI106-Files | /ps6.py | 13,035 | 4.09375 | 4 | import test106 as test
# this imports the module 106test.py, but lets you refer
# to it by the nickname test
#### 1. Write three function calls to the function ``give_greeting``:
# * one that will return the string ``Hello, SI106!!!``
# * one that will return the string ``Hello, world!!!``
# * and one that ... |
020cea430b8939fef9b71ed4836c8bf85bf2211a | josephevans24/SI106-Files | /Final Project/finalproject.py | 18,208 | 3.6875 | 4 | import test106 as test
import csv
def collapse_whitespace(txt):
# turn newlines and tabs into spaces and collapse multiple spaces to just one space
res = ""
prev = ""
for c in txt:
# if not second space in a row, use it
if c == " " or prev == " ":
... |
a9a96b6bc344c5a44a45e61e4a947b1e37543e58 | ricew4ng/Slim-Typer-v1.0 | /code/class_thread_show_time_speed.py | 1,721 | 3.609375 | 4 | #coding:utf8
#显示用时以及计算打字速度的线程的类脚本
import threading
import time
# 创建此实例时,需要传入一个run_window(QtWidgets.QWidget对象)
# running是启动和关闭thread的标志。设置为false,则关闭线程。
class thread_show_time_speed(threading.Thread):
def __init__(self,run_window):
super(thread_show_time_speed,self).__init__()
self.run_window = run_window
self.... |
67df8cb2c8409510d9b0d1f0c859402db1993e93 | aswarth123/DevoWorm | /parse-beautiful-stone-soup.py | 298 | 3.515625 | 4 | import lxml.etree as ET // uses lxml for parsing
content = "data.xml"
doc = ET.fromstring(content)
data = doc.find('data of interest') //tag that defines source of data
print(data.text)
info = doc.find('information') //tag that defines metadata
print(info.tail)
outfile = "test.txt"
FILE.close |
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])
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.