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 |
|---|---|---|---|---|---|---|
472abe0dbb38fbe93f7c86f09e6a9605d2276084 | hector81/Aprendiendo_Python | /CursoPython/Unidad9/Ejemplos/clase_persona.py | 592 | 3.90625 | 4 | # creamos la clase
class Persona:
# creamos las variables de la clase
nombre = "Juan"
Variable_local = 3
# declaramos el metodo __init__
def __init__(self):
self.nombre=input("Ingrese el nombre: ")
self.edad=int(input("Ingrese la edad: "))
# creamos la primera funcion
... |
ad24b511b70d2bb85230928b52d8c33117698ba8 | hector81/Aprendiendo_Python | /Prueba/encontrar.py | 192 | 3.859375 | 4 | cadena = "estamos en La Rioja por desgracia"
if cadena.find("La Rioja") >= 0:
print ("Se ha encontrado la rioja en el e-mail")
else:
print ("No se ha encontrado la rioja en el e-mail")
|
aa45f4f212d5892fa5f133b510d68416a5717fd4 | hector81/Aprendiendo_Python | /Listas/MaquinasExpendedoras_simple.py | 4,627 | 3.578125 | 4 | # solo devuelve monedas
# http://progra.usm.cl/apunte/ejercicios/1/maquina-alimentos.html
# funciones
def sumarCantidadDisponible(arrayCantidadMonedasBilletes):
cantidadTotal = 0.0
for i in range(len(arrayCantidadMonedasBilletes)):
cantidadTotal = cantidadTotal + arrayCantidadMonedasBilletes[i][0]... |
dd203682bf782143bc7db016931c8b016fe615b4 | hector81/Aprendiendo_Python | /CursoPython/Unidad6/Ejemplos/ejemplo1_Else.py | 1,039 | 3.984375 | 4 | n = int(input('Ingresa un número y te digo si es primo. '))
for x in range(2,n):
if n % x == 0:
print(n, 'es igual a', x, '*', n/x)
break
else:
print(n, 'es un número primo')
'''
Condicional con if para saber si un número no es primo.
En caso de que la condición sea verdadera (no pr... |
edd9c5c65bfbaac057661f230b380406d567ec93 | hector81/Aprendiendo_Python | /CursoPython/Unidad2/Ejemplos/operadores_comparacion.py | 618 | 3.734375 | 4 | resultado1 = 5 > 3
print("5 > 3 = " , resultado1)
resultado2 = 3 < 7
print("3 < 7 = " , resultado2)
resultado3 = 19 < 9
print("19 < 9 = " , resultado3)
resultado4 = 1 != 0
print("1 != 0 = " , resultado4)
resultado5 = 0 != 0
print("0 != 0 = " , resultado5)
resultado6 = False or (4 == 1 + 5) == False
print("Fa... |
4e3d2a56b9c1b632d79ae1147e6090c4f1fe8f06 | hector81/Aprendiendo_Python | /String_Cadenas/Palabra_Corta_Larga.py | 882 | 3.953125 | 4 | def introducirFrase():
while True:
try:
frase = input("Por favor ingrese una frase: ")
if frase != '':
print("La frase es " + frase)
return frase
break
except ValueError:
print("Oops! No era válido.... |
62c48ed596bb30a48b40b4b7a1f5a31d2a90d805 | hector81/Aprendiendo_Python | /CursoPython/Unidad9/Ejemplos/clase_metodo_str.py | 417 | 4.0625 | 4 | class punto():
"""Clase que va representar un punto en un plano
Por lo que tendrá una coordenada cartesiana(x,y)
"""
def __init__(self, x=0, y=0):
self.x = x
self.y = y
def __str__(self):
""" Muestra un par de variables como una tupla, el punto cartesiano"""
return ... |
6edc9a6cd63bbff4b6929879633cb39d5e4f8fe5 | hector81/Aprendiendo_Python | /CursoPython/Unidad3/Ejemplos/numero_int_float.py | 218 | 4.09375 | 4 | #Definimos dos variables llamadas numero1 y
# numero2, y asociaremos un número a cada una
numero1 = int(2)
numero2 =float(2.5)
print("numero1 = int(2) ==> " , numero1)
print("numero2 = float(2.5) ==> " , numero2) |
54fb0ee5160b4f686f630cebf3f331a99119071b | hector81/Aprendiendo_Python | /L14_Proyecto/Ejercicio1_1.py | 2,391 | 3.984375 | 4 | '''
EJERCICIO 1. Cargar los datos con la función pandas.read_json.
¿Qué tipo tiene cada columna?
¿Qué pasa con los datos numéricos?
Una pista: si necesitamos realizar manipulaciones elemento a elemento
(por ejemplo, eliminar un caracter extraño), podemos aplicar el método
apply junto con una función lambda. Si, e... |
59fd1f3fdf086d9bf627467a89a6d86bb9b14e12 | hector81/Aprendiendo_Python | /CursoPython/Unidad10/Ejemplos/ejemplo_archivos.py | 2,058 | 3.5 | 4 | # EJEMPLO: Distintas pruebas con los métodos de archivos
archivo = open("Unidad10\\Ejemplos\\archivo.txt","bw")
archivo.write(b'Hola Mundo')
# 10
# Si intentas leer el archivo, como lo has abierto en modo escritura te devolverá un error.
# archivo.read()
# Traceback (most recent call last):
# File "<stdin>",... |
d17d2dc1ae1c064a10642e436debd175944a013c | hector81/Aprendiendo_Python | /Listas/MaquinasExpendedoras_complicado.py | 15,186 | 4.0625 | 4 | '''
FUNCIONES
'''
def comprobarTabacoExisteNumero(arrayTabacosPrecios_Cantidad, numero):
numero = numero - 1
boolCom = False
for i in range(len(arrayTabacosPrecios_Cantidad)):
if i == numero:
boolCom = True
return boolCom
def comprobarTabacoCantidad(arrayTabacosPrecios_... |
60db772fe0b20473827de17fbcd6ceaf75cfccf3 | hector81/Aprendiendo_Python | /Modulos_pickle_json/Ejercicio2_leer_archivos_json_pickle.py | 1,853 | 3.9375 | 4 | '''
EJERCICIOS MÓDULOS pickle Y json
2. Recupere el contenido del fichero 'ejercicios.pic' o 'ejercicios.json'.
Determine el número de líneas que ha programado hasta ahora en el curso.
No cuentan las líneas en blanco ni las líneas que sean comentarios.
'''
import pickle
import json
#FUNCIONES
def recuperarD... |
6b89068c0bd117e7e4799e632cdce9e56c19122e | hector81/Aprendiendo_Python | /String_Cadenas/DevolverMayusculasMinusculas.py | 437 | 3.640625 | 4 | frase = 'Esto es una frase con Mayusculas y minusculas'
contadorMayusculas = 0
contadorMinusculas = 0
for i in range(len(frase)):
if frase[i].islower():
contadorMinusculas = contadorMinusculas + 1
elif frase[i].isupper():
contadorMayusculas = contadorMayusculas + 1
print('La frase : ... |
670a651707c59584b5d5a13f1650c2d1905b1472 | hector81/Aprendiendo_Python | /CursoPython/Unidad4/Ejercicios/actividad_I_u4.py | 522 | 3.8125 | 4 | '''
Selecciona las tres fechas más recientes de esta lista utilizando la notación de
slicing de lista que hemos ido viendo durante el tema.
'''
dias_eclipse = ['21 de junio de 2001', '4 de diciembre de 2002', '23 de noviembre de 2003',
'29 de marzo de 2006', '1 de agosto de 2008', '22 de julio de 2009', '11 de... |
109761a1fca526bb59dd1074bf15aacf649d5167 | hector81/Aprendiendo_Python | /CursoPython/Unidad10/Ejemplos/archivo_read.py | 331 | 3.578125 | 4 | # Si el archivo se encuentra en modo de lectura, lo lee y devuelve el contenido del archivo desde la posición en la que se encuentre hasta el final del archivo. Si se introduce un número como argumento,
# lee el número de posiciones indicadas en el argumento.
f = open("Unidad10\\Ejemplos\\archivo.txt", "r")
print(f... |
3cd870efac96ad2866c909ef969caf5acc2830d1 | hector81/Aprendiendo_Python | /CursoPython/Unidad9/Ejemplos/clase_metodo_operador_matematico.py | 557 | 4.375 | 4 | class Punto():
"""Clase que va representar un punto en un plano
Por lo que tendrá una coordenada cartesiana(x,y)
"""
def __init__(self, x=0, y=0):
self.x = x
self.y = y
def __add__(self, otro):
""" Devuelve la suma de ambos puntos. """
return Punto(self.... |
1ba04402ea117c9bc59eae2e91656535c84a8b57 | hector81/Aprendiendo_Python | /CursoPython/Unidad9/Ejemplos/clase_emtodo_property.py | 1,588 | 3.5625 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
class Perros(object): #La clase principal Perros
def __init__(self, nombre, peso): #Define los parámetros
self.__nombre = nombre #Declara los atributos (privados ocultos)
self.__peso = peso
@property
def nombre(self): #El método para ob... |
7a165c4d007d1ba99dc4024e658e26bcc7dbee5d | hector81/Aprendiendo_Python | /Listas/Ordenacion_listas.py | 729 | 4.40625 | 4 | '''
ORDENACIÓN DE LISTAS
'''
x = [8, 2, 3, 7, 5, 3, 7, 3, 1]
print(x)
print(f"1. El mayor número de la lista ")
print(f"{max(x)}")
print(f"2. El menor número de la lista ")
print(f"{min(x)}")
print(f"3. Los tres mayores números de la lista ")
lista = sorted(x, reverse=True)
print(lista[0:3])
print(f... |
c0c4a0af0ececd8f413b847aee15a3c4ed1fa24e | hector81/Aprendiendo_Python | /String_Cadenas/NumeroLetrasPalabra.py | 627 | 4.03125 | 4 | def introducirPalabra():
while True:
try:
palabra = input("Por favor ingrese una palabra: ")
if palabra != '':
print("La palabra es " + palabra)
return palabra
break
except ValueError:
print("Oops! ... |
87001d9e5d3f5215feeaad10012c67e76ef88824 | hector81/Aprendiendo_Python | /CursoPython/Unidad5/Ejercicios/ejercicio_III_u5.py | 848 | 4.03125 | 4 | '''
Escriba un programa que resuelva el siguiente problema:
El índice de masa corporal IMC de una persona se calcula con la fórmula IMC=P/T2 en donde P es
el peso en Kg. y T es la talla en metros.
Reciba un valor de P y de T, calcule el IMC y muestre su estado según la siguiente tabla:
IMC Esta... |
2a6dbf6e9c92a0d20b12ed8c7ec58f3959f0b702 | hector81/Aprendiendo_Python | /CursoPython/Unidad8/Ejemplos/principal_calculadora.py | 1,059 | 3.65625 | 4 | import calculadora
# Uso las funciones importadas
calculadora.suma(3,9)
calculadora.resta(3,9)
calculadora.multiplica(3,9)
calculadora.divide(3,9)
print('******************')
# igualo variables con las funciones importadas, y las uso como funciones directamente
suma = calculadora.suma
resta = calculadora.res... |
a43ddbb034d53912e38c51fc663c49e12520f22f | hector81/Aprendiendo_Python | /CursoPython/Unidad4/Ejemplos/listas_funciones.py | 996 | 4.40625 | 4 | ''' funciones_listas '''
x = [20, 30, 40, 50, 30]
y = [20, "abc", 56, 90, "ty"]
print(len(x)) # devuelve numero elemento lista x
print(len(y)) # devuelve numero elemento lista x
#max y min solo funcionan con listas numéricas
print(max(x)) # maximo de la lista x
# ERROR # print(max(y)) # maximo de la list... |
3230c051226bfb61c9388f98cb1a8f5b31b3ddbe | tk-learn-2020/tk-learn-2020 | /pa/lx/chapter08/metalcass_test.py | 1,740 | 3.734375 | 4 | # 类也是对象,type创建类的类
def create_class(name):
if name == "user":
class User:
def __str__(self):
return "user"
return User
elif name == "company":
class Company:
def __str__(self):
return "company"
return Company
# ------------... |
5a7bf9ca914cf05eeaa6f4e44edaef234758807e | tk-learn-2020/tk-learn-2020 | /pa/hl/collection/namedtuple_lern.py | 292 | 3.609375 | 4 | '''
@Author : hallen
@Contact : hallen200806@163.com
@Time : 2020-02-07
@Desc :
'''
from collections import namedtuple
# 相当于类的实例化,创建了一个Student类,一般用于数据库
Student = namedtuple("Student",['name','age','cla'])
user = Student("hallen",18,3)
print(user) |
f70ef591a26b376d9dcc79c30d9abcc5f55584be | 51042/fall-2017-hw7 | /problem2.py | 1,793 | 3.96875 | 4 | import pandas as pd
import numpy as np
def search_by_zip(dataframe):
"""
This function return a dataframe that contains restaurants that have failed an inspection within the last year within ZIP code 60661
Args: dataframe - DataFrame containing the original data.
Return: return a new dataframe which c... |
136ee1667d06e6cd8c6aeaca2ca6bf71d0c645cf | qtpeters/please-respond | /pleaserespond/main.py | 1,073 | 3.953125 | 4 |
from pleaserespond.prm import PleaseRespond
from sys import exit
DEFAULT_SEC = 60
def format_input( seconds ):
"""
Verifies that the value passed in is an integer
and if nothing is poassed in, the default is set.
"""
try:
if seconds == "":
seconds = DEFAULT_SEC
retu... |
722c65fc407a270f156204cc2c568cb5f2bf1381 | Nook-0/BD | /1/script/test_parser.py | 4,926 | 4.03125 | 4 | #!/usr/bin/env python3
# coding: utf8
import re
import sys
# Функция для очистки строки от двойных пробелов, пробела в начале строки и в конце
def deleteSpace(string):
if len(string) > 0:
while(string[0]==" "):
string = string[1:]
for i in range(len(string)-3):
if st... |
1861072d9b295defbd8c98e1a0d9a0914f3cfc54 | JDavid550/Python-Intermedio | /dics_Comprehenssions.py | 244 | 3.921875 | 4 | def run():
my_dic = {}
for i in range(1,101):
if i%3 != 0:
my_dic[i] = i**3
print(my_dic)
my_dic2 = {i: i**3 for i in range(0,101) if i%3 != 0}
print(my_dic2)
if __name__ == '__main__':
run() |
7915e90dd431cedcd1820486783a299df813b0b9 | SoumyaMalgonde/AlgoBook | /python/sorting/selection_sort.py | 654 | 4.21875 | 4 | #coding: utf-8
def minimum(array, index):
length = len(array)
minimum_index = index
for j in range(index, length):
if array[minimum_index] > array[j]:
minimum_index = j
return minimum_index
def selection_sort(array):
length = len(array)
for i in range(length - 1):
... |
15c813389a914213fee28c4cba5c86d3fdfbcd09 | SoumyaMalgonde/AlgoBook | /python/dynamic_programming/Edit_distance.py | 1,450 | 4 | 4 | # PROBLEM STATEMENT :
# Given two words str1 and str2, find the minimum number of operations required to convert str11 to str22.
# You have the following 3 operations permitted on a word:
# 1.Insert a character
# 2.Delete a character
# 3.Replace a character
# This is very Famous Dynamic Programming Problem cal... |
89994bd9a42798d11b46f6427eb811bfb0192fab | SoumyaMalgonde/AlgoBook | /python/string algorithms/Suffix_Array.py | 2,358 | 3.765625 | 4 |
class SuffixArray(object):
def __init__(self,array,n):
self.array = self.array #initial array
self.n = n #size of array
#dividing a word into its suffixes
def divideWordToSuffixes(self,word):
suffixes = []
n = len(word)
suffixes.append("$") #end termin... |
8ede8fe5b57dd3e897f6a08cc4ae9d0edfa80d98 | SoumyaMalgonde/AlgoBook | /python/Matrix/Spiral_Print.py | 875 | 3.984375 | 4 | def Spiralprint(matrix):
top = left = 0 # initializing with top
bottom = len(matrix) - 1
right = len(matrix[0]) - 1
while True:
if left > right:
break
# print top row
for i in range(left, right + 1):
print(matrix[top][i], end=' ')
top = top + 1
if top > bottom:
break
# print right column
... |
3b68f1f217fd64cc0428e93fbfe17745c664cb2e | SoumyaMalgonde/AlgoBook | /python/maths/jaccard.py | 374 | 4.1875 | 4 |
a = set()
b = set()
m = int(input("Enter number elements in set 1: "))
n = int(input("Enter number elements in set 2: "))
print("Enter elements of set 1: ")
for i in range(m):
a.add(input())
print("Enter elements of set 2: ")
for i in range(n):
b.add(input())
similarity = len(a.intersection(b))/len(a.union... |
df7feb3e68df6d0434ed16f02ce3fcf0fd1dbf99 | SoumyaMalgonde/AlgoBook | /python/maths/Volume of 3D shapes.py | 2,970 | 4.1875 | 4 | import math
print("*****Volume of the Cube*****\n")
side=float(input("Enter the edge of the cube "))
volume = side**3
print("Volume of the cube of side = ",side," is " ,volume,)
print("\n*****Volume of Cuboid*****\n")
length=float(input("Enter the length of the cuboid "))
breadth=float(input("Enter the breadth of the... |
79ba3736029a2bc29aa10adafc50ef24b92be115 | SoumyaMalgonde/AlgoBook | /python/string algorithms/kmp_string_matching.py | 2,451 | 4.09375 | 4 | '''
For details on the working of the algorithm, refer this video by Abdul Bari:
https://www.youtube.com/watch?v=V5-7GzOfADQ
'''
'''
Defining the KMP Search function
'''
def KMPSearchfn(pattern, input_text):
len_pattern = len(pattern)
len_input = len(input_text)
pi = [0]*len_pattern #pi is the piArra... |
bb114c561547aa3adbcf855e3e3985e08c748a01 | SoumyaMalgonde/AlgoBook | /python/sorting/Recursive_quick_sort.py | 834 | 4.1875 | 4 | def quick_sort(arr, l, r): # arr[l:r]
if r - l <= 1: # base case
return ()
# partition w.r.t pivot - arr[l]
# dividing array into three parts one pivot
# one yellow part which contains elements less than pivot
# and last green part which contains elements greater than pivot
yellow = l +... |
0be537def5f8cc9ba9218267bf774b28ee44d4c7 | SoumyaMalgonde/AlgoBook | /python/graph_algorithms/Dijkstra's_Shortest_Path_Implementation_using_Adjacency_List.py | 2,933 | 3.921875 | 4 | class Node_Distance :
def __init__(self, name, dist) :
self.name = name
self.dist = dist
class Graph :
def __init__(self, node_count) :
self.adjlist = {}
self.node_count = node_count
def Add_Into_Adjlist(self, src, node_dist) :
if src not in self.adjlist :
... |
67733ad845f63525ba2aa25faf37fb35b5456eb8 | SoumyaMalgonde/AlgoBook | /ml/Perceptrons/perceptronasand.py | 883 | 3.609375 | 4 | import numpy as np
## step-function
def step(vec):
""" returns 1 when true and 0 when false """
if vec >= 0 :
return 1
else:
return 0
## perceptron model
def perceptron(x, w, b):
""" defining the perceptron model
x = Inputs
w = weights
b = bias
"""
vec = n... |
c181d9bec769479718d31c01abb07f457f36a512 | SoumyaMalgonde/AlgoBook | /python/sorting/slow_sort.py | 394 | 3.859375 | 4 | def SlowSort(A, i, j):
if i >= j:
return
m = ((i + j) // 2)
SlowSort(A, i, m)
SlowSort(A, m + 1, j)
if A[m] > A[j]:
A[m], A[j] = A[j], A[m]
SlowSort(A, i, j - 1)
return A
# Example run of SlowSort
def main():
arr = [2, 7, 9, 3, 1, 6, 5, 4, 12]
print("Result: " + str... |
54bda362f5d8412257a1587629eeefa7e912e3fc | ajayram515/SearchString | /project.py | 1,566 | 4.09375 | 4 | #operating system dependent functionality
import os
# Ask the user to enter directory path
search_path = raw_input("Enter directory path to search : ")
# Ask the user to enter type of file
file_type = raw_input("File Type : ")
# Ask the user to enter string to be searched
search_str = raw_input("Enter the sear... |
b097d704c215d601a01a227bd6b045c46ba97e68 | maxmarzolf/random-objects | /Coffee.py | 972 | 3.8125 | 4 | class Coffee:
def __init__(self, roast, size, ice, temperature, price):
self.roast = roast
self.size = size
self.ice = ice
self.temperature = temperature
self.price = price
def is_hot(self, current_temperature, contains_ice):
"""your coffee is too cold unless ice... |
9656e8cf77882c4fbdabb5ebb11e3220ff0d4bc3 | scemama/basis_set_exchange | /basis_set_exchange/writers/common.py | 359 | 3.546875 | 4 | '''
Helper functions for writing out basis set in various formats
'''
def find_range(coeffs):
'''
Find the range in a list of coefficients where the coefficient is nonzero
'''
coeffs = [float(x) != 0 for x in coeffs]
first = coeffs.index(True)
coeffs.reverse()
last = len(coeffs) - coeffs.... |
fe5d8d2fd1d1c5561a83bab930d61f36f1311557 | Notgnoshi/research | /haikulib/eda/colors.py | 4,278 | 3.765625 | 4 | """Perform exploratory data analysis to parse colors from the haiku dataset.
find_colors() is used to initialize the haiku dataset, while get_color_counts is used to process
the prepared dataset after it's been initialized.
"""
import colorsys
import itertools
from collections import Counter
from typing import Iterabl... |
a8f650bbdeda5e903dc269d6bbf8ec56ce296aaf | BiYingP/a3 | /cal.py | 3,075 | 4.03125 | 4 | #!/usr/bin/python
# calc.py
# BiYing Pan
# 05.10.18
# This program is to create a calculator that parses an infix expression into postix, then evaluates it
import sys
class Stack:
# empty stack
def __init__(self):
self.s = []
# display the stack
def __str__(self):
return str(self.s... |
f9daa2cda430545c2e026f8decfdd09440b9cf1f | gregphillips03/Modeling-and-Simulation | /p0/wphilli2_ngram.py | 6,369 | 3.921875 | 4 | #!/usr/bin/env python
#-*- coding: utf-8 -*-
# p0 ngram
# William (Greg) Phillips
# Finalized
# ------------------------ #
# --- Section 0 - Meta --- #
# ------------------------ #
'''
NLTK was not allowed for use in this exercise
Written in Python 2.7, hence the magic statement on the 1st/2nd lines
Project Gutenber... |
95036998e279c645f6124122ae2373a96e18dbaf | AbhiniveshP/Design-4 | /TwitterDesign.py | 4,683 | 4.28125 | 4 | '''
Solution:
1. In order to design Twitter, we need a global timestamp, HashMap to map users to tweets, Hashmap to map users to
their followers.
2. Just to avoid null checks, we call isFirstTime() method to initialize user's info if not present already.
Time and Space Complexities are explained are in each func... |
e3a2bac0b37fe0c1e7349a55f2c77127f6c45b97 | apexfelix/strings | /strigs/modulous.py | 273 | 3.53125 | 4 | s="the croods"
s1="redemption"
print(len(s))
print(len(s1))
x=20
y=75
print("the sum of %d and %d is %d" %(x, y, x+y))
x=20.33
y=75.76
print("the sum of %0.2f and %0.2f is %0.2f" %(x, y, x+y))
x="The "
y="Croods"
print("the sum of %s and %s is %s" %(x, y, x+y)) |
b7c260023e072cbb7b8c71c62ffcb2cd8d748a76 | saisahanar/python-letsupgrade- | /DAY 7 ASSIGNMENT/q1.py | 376 | 3.78125 | 4 | # Use the dictionary,
# port1 = {21: "FTP", 22:"SSH", 23: "telnet", 80: "http"},
# and make a new dictionary in which keys become values and values become keys,
# as shown: Port2 = {“FTP":21, "SSH":22, “telnet":23,"http": 80}
port1 = {21: "FTP", 22:"SSH", 23: "telnet", 80: "http"}
port2={}
for key,values in por... |
b250b1be20c5989d7594f3bbaec28b3c0f6b9c71 | sbrick26/OOP-Design-Challenge | /run.py | 3,266 | 3.6875 | 4 | class Person():
def __init__(self, firstname, lastname):
self.__firstname = firstname
self.__lastname = lastname
def changeName(self, firstname, lastname):
self.__firstname = firstname
self.__lastname = lastname
def returnName(self):
return self.__firstname + " ... |
edb2d3e1a9f09ce94933b8b223af17dda52143a3 | SunshinePalahang/Assignment-5 | /prog2.py | 327 | 4.15625 | 4 | def min_of_3():
a = int(input("First number: "))
b = int(input("Second number: "))
c = int(input("Third number: "))
if a < b and a < c:
min = a
elif b < a and b < c:
min = b
else:
min = c
return min
minimum = min_of_3()
print(f"The lowest of the 3 numbers is {min... |
a451dc45989107a390e8ac7345d08d24e5566c79 | raghedisae/DEVUTC503_02 | /ex4/Fraction.py | 1,954 | 3.625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Fri Dec 20 21:12:48 2019
@author: raghed
"""
class Fraction:
'''num: numerateur
denom: denomominateur '''
def __init__(self, n, d):
self.num = int(n)
self.denom=int(d)
if self.denom <0:
self.denom = abs(self.... |
e735aec8a13110f611c3e7e1b5b79ebf8529dd64 | Harrison97/CTCI | /ch2/2.4.py | 1,448 | 3.546875 | 4 | import doctest
import LinkedList
LinkedList = LinkedList.SinglyLinkedList
# TC: O(n)
# SC: O(n)
# Bad implemintation
# Could be a little better if we kept trak of front oly nd appended to front of lists.
def partition(ll: LinkedList, x: int) -> LinkedList:
"""
Time: O(n)
Space: O(n)
>>> partition(Link... |
f063169ec81c0e989da04e0e108bb3d776d5cca2 | Harrison97/CTCI | /ch1/1.1.py | 657 | 3.53125 | 4 | import unittest
chars = 128
def has_unique_chars(s: str) -> bool:
memo = chars*[0]
for c in s:
memo[ord(c) % chars] += 1
if memo[ord(c) % chars] > 1:
return False
return True
class Test(unittest.TestCase):
def test_1(self):
self.assertEqual(has_unique_chars('aAsSdD... |
29089e890e62fe8459c2f79a42d715de180fa9c9 | Harrison97/CTCI | /ch2/2.7.py | 2,842 | 3.953125 | 4 | import doctest
import LinkedList
LinkedList = LinkedList.SinglyLinkedList
def intersects(ll1: LinkedList, ll2: LinkedList) -> bool:
"""
Time: O(n)
Space: O(1)
>>> n = LinkedList.Node(99)
>>> ll1 = LinkedList(1, 2, 3)
>>> ll1.append_node_to_tail(n)
>>> ll1.append_to_tail(6)
>>> ll2 = Li... |
270175c897da53c2d3a5f40cafb6adf099bcf017 | vijaysundar2701/python | /be44.py | 85 | 3.546875 | 4 | h=list(range(1,10))
k=int(input())
if k in h:
print("yes")
else:
print("no")
|
7324a5f182521b9a9a0def5c0dc152ce48f7b017 | vijaysundar2701/python | /begi54.py | 56 | 3.546875 | 4 | z=int(input())
if z%2==0:
print(z)
else:
print(z-1)
|
dc40d3454436f0ca1f099fe2ba723f3222a1a5ce | vijaysundar2701/python | /vowrcos.py | 156 | 3.8125 | 4 | v=input()
vow=['a','e','i','o','u','A','E','I','O','U']
if v in vow:
print("Vowel")
elif v.isalpha():
print("Consonant")
else:
print("invalid")
|
604839fd7f7448acd7a87baa5d3a64726280c6ff | vijaysundar2701/python | /beg60.py | 61 | 3.59375 | 4 | a=int(input())
s=1
for i in range(2,a+1):
s=s+i
print(s)
|
3e545854b563b3a1166c7a36dead61b5274ae521 | jlewis2112/CPTS-481 | /HW2/concord | 1,617 | 3.5625 | 4 | #! /usr/bin/env python3
"""
Joseph Lewis
concord script
"""
import sys
import concordance as C
fileNames = sys.argv[1:]
wordStructure = {}
#used to store word and locations
# {word: [(filename,[lines]),(filename,[lines])}
#scans the word structure and prints the results sorted
def printWords(words):
for word... |
47a0395d5d99612355328a92bf8f2bcf7bebc2c1 | freemanwang/AlgorithmJS | /Sort/QuickSort.py | 1,987 | 3.71875 | 4 | # coding=utf-8
import random
def quickSort(arr, left, right):
if len(arr) <= 1:
return arr
if left < right:
idx = getPivotIndex(arr, left, right)
quickSort(arr, left, idx-1)
quickSort(arr, idx+1, right)
def getPivotIndex(arr, left, right):
# temp 记录分隔元素
temp = arr[left]... |
f34219d1ee2ef0268506e136f341cd3f0485d77b | jideedu/DictAutomate | /dicts/cleanDicts.py | 741 | 3.84375 | 4 | ######
#this file takes disctionaries [american-english, british-english] and removes those entries
#that have stopwords, apostrophes or start with capital letters
######
#input dictionary files
inputDicts = ['american-english', 'british-english']
def checkCharacter(c, string):
return c in string
def checkCapitalLe... |
6ba14ff2c930aec459f6a12008d3a853817a1b51 | canw1993/CodeChallenges | /Fibonacci.py | 1,464 | 3.84375 | 4 | # Author: Can Wang, Bowen Deng
# Generate a random Fibonacci number smaller than equal to n (n>0) in O(log(n)) time
import math
import random
def matrix_power(mat, n):
# compute mat^n, mat is a square matrix
N = len(mat)
if n == 0:
zeros = [[0. for _ in range(N)] for _ in range(N)]
for i i... |
266b83e77c6042daade94de6edbd4e5d362943b2 | chasejwang/lpthw | /ex36.py | 545 | 3.59375 | 4 | from sys import exit
def start():
print "You are a fog prince with a golden key and a sword."
print "You ride into the dark forest"
print "Finding out two ways: a cave and a road to Glory riverside."
print "Which way you would to go, my prince?"
choice = raw_input(" >")
if "cave... |
aa99be7f1e3a51d2d5c0281516a3ef443c4fc0c0 | chasejwang/lpthw | /pr1.py | 375 | 3.515625 | 4 | x = "life can be difference, ppl can live in %d, %d, or %d ways" % (1, 2, 3)
creative= "creative"
will_not = "won't"
y = "so you should be %s, but you %s be pretend to be" % (creative, will_not)
print x
print y
w = "bitch, bitch, and bitches \n"
k = "cunt, cunt , and cunts"
print w + k
f = "you never know what happ... |
06b05625e0bdb938587a1ce2df230f3e2ee40277 | PaxMax1/School-Work | /a116_buggy_image_pg_version_5-21.py | 639 | 3.75 | 4 | # a116_buggy_image.py
import turtle as trtl
# instead of a descriptive name of the turtle such as painter,
# a less useful variable name x is used
spider = trtl.Turtle()
spider.pensize(40)
spider.circle(20)
spider_legs = 6
spider_leg_length = 70
leg_angle = 380 / spider_legs
print("Leg Angle =", leg_angle)
spider.pen... |
34a2bfbe98dfb42c1f3d2a8f444da8e49ca04639 | PaxMax1/School-Work | /fbi.py | 1,610 | 4.25 | 4 | # a322_electricity_trends.py
# This program uses the pandas module to load a 3-dimensional data sheet into a pandas DataFrame object
# Then it will use the matplotlib module to plot comparative line graphs
import matplotlib.pyplot as plt
import pandas as pd
# choose countries of interest
my_countries = ['United Stat... |
1ab03f22da176b7d8502d563c100f3f0eec65387 | 1aaronscott/cs-sprint-challenge-hash-tables | /hashtables/ex4/ex4.py | 602 | 3.90625 | 4 | def has_negatives(a):
"""
YOUR CODE HERE
"""
# Your code here
# create empty list and join with "a" to make a dict
b = [0]*len(a)
cache = dict(zip(a, b))
result = []
for k in cache:
if k > 0: # for every positive key
# print(k)
try: # chec... |
00e2d68e451511c443f96d1d27ac6e7820f4ab58 | GiovanaPalhares/python-introduction | /testes.py | 433 | 3.640625 | 4 | import re
texto = "joooooãooo, jooãooo e maria moravam na roça e então decidiram se mudar para cidade, pensaram em se mudar para São Paulo"
print(re.findall(r"[Jj]oão", texto))
print(re.findall(r"jOãO|MARIA", texto, flags=re.I))
# print(re.sub(r"jo+ão+", "felipe", texto, flags=re.I))
# print(re.sub(r"joão"))
print(re... |
524773cbc9374ee413f4e99d9ca0fff324ffe044 | GiovanaPalhares/python-introduction | /NIM.py | 350 | 3.96875 | 4 | print("Bem-vindo ao jogo do NIM! Escolha:")
print("1 - para jogar uma partida isolada ")
print("2 - para jogar um campeonato ")
escolha = int(input(" Escolha o tipo de jogo: "))
if "escolha" == 1:
print("você escolheu uma partida isolada")
if "escolha" == 2:
print("você escolheu um campeonato")
else:
... |
aa0e0d75269d67427d08f20fc9cdb8b376f850a0 | shohei-ojs/math- | /probability/otoku.py | 597 | 3.546875 | 4 | # coding: UTF-8
# 数字の書かれたカードを引いた時の期待値
# ①:カードの数字*100円
# ②:5が出た場合1000円
from numpy.random import *
CARDS = [1,2,2,3,3,3,4,4,4,4,5,5,5,5,5]
TOTAL = 100000
def draw():
return choice(CARDS)
def mean(l):
return sum(l) /TOTAL
def main():
a = mean([draw() * 100 for _ in range(TOTAL)])
b... |
4645c1449ee00c1b86c60d26f3e7abfd1cc6aef6 | rolundb/Labb1 | /Labb1.py | 4,263 | 3.703125 | 4 | import time
import os
from operator import attrgetter
# Reads from .txt-file and extracts relevant lines which becomes attributes for objects that are
#placed in an array.
#
#parameter1 a_filename Name of a txt-file.
# return: the_array_list List of objects created based on content of .txt file.
def readF... |
de2bfbd8bab8b02f529178d3919de0bd49b6e8d1 | happy-bean/python-Demo | /src/com/wgt/lesson4/Class1.py | 8,994 | 3.71875 | 4 | #!/usr/bin/python
# -*- coding: UTF-8 -*-
import os
# Python 文件I/O
# 本章只讲述所有基本的的I/O函数,更多函数请参考Python标准文档。
#
# 打印到屏幕
# 最简单的输出方法是用print语句,你可以给它传递零个或多个用逗号隔开的表达式。此函数把你传递的表达式转换成一个字符串表达式,并将结果写到标准输出如下
print "Python 是一个非常棒的语言,不是吗?"
# 读取键盘输入
# Python提供了两个内置函数从标准输入读入一行文本,默认的标准输入是键盘。如下:
# raw_input
# input
# raw_input函数
# ra... |
15a5b9e912cd614e9a6cec8c3140a4f254655616 | longlvt/CS50X | /pset6/mario.py | 435 | 3.859375 | 4 | from cs50 import get_int
height = ''
# print(type(height))
# while (height < 1 or height > 8):
# height = get_int("Height: ")
while (height.strip().isdigit() == False or (height.strip().isdigit() == True and (int(height) < 1 or int(height) > 8))):
height = input("Height: ")
for i in range(1, int(height) + 1):
... |
0eb00f4a770263ea840143cc72a99cd402475dda | ashishjain1988/PythonTest | /com/example/python/test.py | 522 | 3.578125 | 4 | import numpy as ny
import os as os
#s = "uxwrpxlwocnimr";
s="axabc";
count = True;
lstring = "";
length = len(s)
for i in range(0,length):
count = True;
for j in range(i+1,length):
if(s[j-1] > s[j]):
subStr = s[i:j];
if(len(subStr) > len(lstring)):
lstring = subSt... |
3e33624375f413e3d632999e29e71522d0bd2292 | wael-hub/untitled | /if + else+ else if statment.pyif + else+ else if statement.py | 694 | 3.828125 | 4 | username = input(" plase insert your name: ")
password = input(" plase insert your password: ")
if username == 'bohen' and password == 'ffff':
print("welcome to your emaile")
else:
print ('error')
z = 15
y = 10
if (z < y):
print (z)
w = z + y
print (w)
elif(z > y):
... |
b983c7c3384fcf521ea6ca79d262e73d3967678e | wael-hub/untitled | /Oop create class and object.py | 186 | 3.515625 | 4 | class car:
speed = 0
color = 'none'
def increment(self):
print('increment')
def decrement(self):
print ('decrement')
BMW = car()
camry = car()
|
d0daa9b74955010179caea96c694e8faab0b3c2d | wael-hub/untitled | /indexed.py | 439 | 3.703125 | 4 | word = 'bohen'
print (word)
print (word[0])
print (word[1])
print (word[2])
print (word[3])
print (word[4])
print (word[-1])
print (word[-2])
print (word[-3])
print (word[-4])
print (word[-5])
print (word[:])
print (word[3:])
print (word[3:])
print (word[0:3])
word = 'bohen', 'bird' , 10 , 20... |
586d76bd89db756c9add468c98d0b5b6e59091e5 | wael-hub/untitled | /Leen and Upper.py | 236 | 3.71875 | 4 | name = 'Wael Mohamad'
res = name.replace('Wael Mohamad', 'Ward')
print(res)
name = 'Wael Mohamad'
res = name.find('M')
print(res)
name = 'Wael Mohamad'
res = name.__len__()
print(res)
name = 'Wael Mohamad'
res = name.upper()
print(res)
|
c275468117aa43e59ac27afd391e463d0983a979 | gevishahari/mesmerised-world | /integersopr.py | 230 | 4.125 | 4 | x=int(input("enter the value of x"))
y=int(input("enter the value of y"))
if(x>y):
print("x is the largest number")
if(y>x):
print("y is the largest number")
if (x==y):
print("x is equal to y")
print("they are equal") |
c4314c1090df0a7dba6613ea8ddda0f3dd433235 | gcorbin/archive-computational-experiments | /experimentarchiver/__init__.py | 1,255 | 3.609375 | 4 | class Version:
def __init__(self, major=0, minor=0):
if not isinstance(major, int) or not isinstance(minor, int):
raise TypeError('Major and minor version numbers must be integers.')
self._version_tuple = (major, minor)
def major(self):
return self._version_tuple[0]
de... |
bb0ad1ce4f81a23b500ce5b86d92a0fc70241fc4 | loafer18/numBomb | /elifTest.py | 814 | 3.953125 | 4 | import random
numList = list(range(1,101))
#print (numList)
numBomb = random.choice(numList)
print(numBomb)
while True:
try:
#num= float(input("input a number pls."))
number1 = input("Please select a number between 1 and 100:")
number1 = int(number1)
print(number1) ... |
cf2193408564c9b3467abc19d590769c7f6f25c2 | jmptiamzon/study-python | /files.py | 2,950 | 3.625 | 4 | import os
os.path.join('folder1', 'folder2', 'folder3', 'file.png') #will join based on OS
os.sep #will show OS separator
os.getcwd() #current working directory, default is python folder
os.chdir('c:\\') #change directory
os.getcwd() #will show c:\\
os.path.abspath('spam.png') #will return current dir, which ... |
2fb6397026f25ef532c90ca5e1bf7b3539ee3495 | alinyara/course-ud303 | /newsdb.py | 1,852 | 3.5 | 4 | import psycopg2
from datetime import date
DBNAME = "news"
# Its necessary to create 2 different views in order to make the query results
# Question 1 and 2
def createview1():
db = psycopg2.connect(database=DBNAME)
c = db.cursor()
c.execute("create view question1_table as select name, title, path from (se... |
d76dfe561f9111effed1b82da602bf6df98f2405 | AdmireKhulumo/Caroline | /stack.py | 2,278 | 4.15625 | 4 | # a manual implementation of a stack using a list
# specifically used for strings
from typing import List
class Stack:
# initialise list to hold items
def __init__(self):
# initialise stack variable
self.stack: List[str] = []
# define a property for the stack -- works as a getter
@pro... |
25240f3e1f3cc702921cca1587df8e57d3adf570 | Muhammad-waqar-uit/HashTable-Own-Implementation- | /Chaining Collision( Hash Table).py | 2,091 | 3.875 | 4 | class HashTable:
def __init__(self,length):
self.length=length#Length of the hashtable
self.data=[[] for i in range(self.length)]#HashMap as an array for Hashing values
def Get_Array(self):#getting the whole hashmap array
return self.data
def __Get_Hash(self,key):... |
177bdc4ce61be25d10a3b6bda220fd7c93210777 | EcaterinaSchita/Siruri-de-caractere | /problema8.py | 567 | 3.765625 | 4 | s=str(input('Introdu sirul dorit:'))
a=s.count(('A'))
print('Numarul de aparitii a caracetrului A',a)
print('Sirul obtinut prin substiruirea caracterului A in *' )
s1=list(s)
s1.remove('B')
s1= ''.join(s1)
print('Sirul obţinut prin radierea din şirul S a tuturor apariţiilor caracterului ’B’:', s1)
print('Număru... |
8b7da9557874db581b38432a28b41f9058e9dadf | cpelaezp/IA | /1. Python/ejemplos/3.projects/1.contactos/contactoBook.py | 831 | 4.15625 | 4 | class Contacto:
def __init__(self, name, phone, email):
self._name = name
self._phone = name
self._email = email
class ContactoBook:
def __init__(self):
self._contactos = []
def add(self):
name = str(input("Ingrese el nombre: "))
phone = str(input("Ingrese e... |
63a30ff68c69f15b62bb59bfbb3b68cffc59c697 | paul-ivan/genetic_project | /vector.py | 702 | 3.8125 | 4 | #!/usr/bin/env python
import math
def dist(p1, p2):
return math.hypot(p2[1] - p1[1], p2[0] - p1[0])
class Vector:
def __init__(self, p1, p2):
self.x = p2[0] - p1[0]
self.y = p2[1] - p1[1]
def compare(self, v2):
return Vector(self.x, self.y, v2.x, v2.y)
def show(self):
... |
a650c4d0cb7bcc4a95037519046efce47d0e7dc8 | abhatt95/LeetCode | /Medium/350.py | 692 | 3.640625 | 4 | """
Given two arrays, write a function to compute their intersection.
"""
class Solution:
def intersect(self, nums1: List[int], nums2: List[int]) -> List[int]:
nums1.sort()
nums2.sort()
index1 = 0
index2 = 0
output = []
while index1 < len(nums1) a... |
d5b520af7a8ff1e7c7c5fbdd8c6d0169e7265731 | abhatt95/LeetCode | /Medium/743.py | 1,136 | 3.671875 | 4 | """
There are N network nodes, labelled 1 to N.
Given times, a list of travel times as directed edges times[i] = (u, v, w), where u is the source node, v is the target node, and w is the time it takes for a signal to travel from source to target.
Now, we send a signal from a certain node K. How long will it take for ... |
205837a1e1191374562287c9eff0b4ce9bf7a5b4 | abhatt95/LeetCode | /Medium/55.py | 843 | 3.640625 | 4 | """
Given an array of non-negative integers, you are initially positioned at the first index of the array.
Each element in the array represents your maximum jump length at that position.
Determine if you are able to reach the last index.
https://leetcode.com/problems/jump-game/
"""
class S... |
71021e7cf21f47c13df7be87afe4e169eb945ab5 | jessicazhuofanzh/Jessica-Zhuofan--Zhang | /assignment1.py | 1,535 | 4.21875 | 4 | #assignment 1
myComputer = {
"brand": "Apple",
"color": "Grey",
"size": 15.4,
"language": "English"
}
print(myComputer)
myBag = {
"color": "Black",
"brand": "MM6",
"bagWidth": 22,
"bagHeight": 42
}
print(myBag)
myApartment = {
"location": "New York City",
"type": "s... |
e724a913db3ddec93e12d1b422ec3b65b9015565 | gsy/leetcode | /design_hashset.py | 986 | 3.765625 | 4 | # -*- coding: utf-8 -*-
class MyHashSet:
def __init__(self):
"""
Initialize your data structure here.
"""
self.buckets = [None] * 10
def add(self, key):
while len(self.buckets) <= key:
self.buckets = self.buckets + [None] * len(self.buckets)
self.bu... |
85ed57e4097c51af6ad3e628bd274e4ec4509fa1 | gsy/leetcode | /path_sum.py | 3,056 | 3.53125 | 4 | __author__ = 'guang'
from bst import TreeNode
class Solution(object):
def is_leaf(self, node):
return node and node.left is None and node.right is None
def path_sum(self, node):
"""
>>> s = Solution()
>>> s.path_sum(None)
(0, -2147483648)
>>> s.path_sum(TreeNod... |
fab592507bc207929192d4fdc5902a7c5567f4cc | gsy/leetcode | /linklist/removeDuplicateNodes.py | 619 | 3.6875 | 4 | #!/usr/bin/env python3
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def removeDuplicateNodes(self, head: ListNode) -> ListNode:
seen = set()
sentinel = ListNode(0)
sentinel.next = head
prev = sentinel
node = pre... |
0cfafbcde85537dd0e3b5af7e74779e3cf975681 | gsy/leetcode | /binarytree/numUniqueEmails.py | 553 | 3.625 | 4 | class Solution:
def convert(self, email):
localname, domain = email.split("@")
name = ""
for char in localname:
if char == '.':
continue
elif char == '+':
break
else:
name = name + char
return name + ... |
33e32c81c4fea430a10d15206e4b4cfc17b13618 | gsy/leetcode | /preorder_traversal.py | 985 | 3.734375 | 4 | from bst import TreeNode
class Solution(object):
def preorderTraversal(self, root):
"""
:type root: TreeNode
:rtype: List[int]
>>> s = Solution()
>>> root = TreeNode(None).from_string("1,2,3")
>>> s.preorderTraversal(root)
[1, 2, 3]
>>> root = TreeNod... |
c30d7af1efe131fade73d0279f926064ec1aba23 | gsy/leetcode | /generate_parenthese2.py | 655 | 3.65625 | 4 | # -*- coding: utf-8 -*-
class Solution:
def generateParenthesis(self, n):
if n == 1:
return ["()"]
elif n == 2:
return ["()()", "(())"]
else:
result = set()
for parenthesis in self.generateParenthesis(n-1):
result.add("({})".f... |
2299604747cc781fa3025e710db75be29cadf1bb | gsy/leetcode | /valid_palindrome.py | 987 | 3.609375 | 4 | __author__ = 'guang'
class Solution(object):
def palindrome(self, s):
"""
:param s:
:return:
>>> s = Solution()
>>> s.palindrome("A")
True
>>> s.palindrome("")
True
"""
if len(s) == 0:
return True
i, j = 0, len(s)... |
9fdbeee26ef114f7dd7f7a0ee424c7949ad3e4de | gsy/leetcode | /linklist/copyRandomList.py | 1,369 | 3.6875 | 4 | #!/usr/bin/env python3
class Node:
def __init__(self, x: int, next: 'Node' = None, random: 'Node' = None):
self.val = int(x)
self.next = next
self.random = random
class Solution:
def indexof(self, head, node):
current = head
index = 0
while current:
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.