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 |
|---|---|---|---|---|---|---|
37c6b73514ef540e247e3997324adf4cda6f01f8 | MichaelEniolade/Tournament_Udacity | /tournament_test.py | 4,299 | 3.5 | 4 | #!/usr/bin/env python
#
# Test cases for tournament.py
from tournament import *
def testDeleteMatches():
deleteMatches()
print "1. Delete Old matches."
def testDelete():
deleteMatches()
deletegamers()
print "2. Delete gamer records."
def testCount():
deleteMatches()
deletegamers()
... |
34f8a256264e0da898d07b32d613371bc0fecde5 | SACHSTech/ics2o1-livehack-2-Kyle-Lue | /problem2.py | 1,066 | 4.5 | 4 | """
-------------------------------------------------------------------------------
Name: problem2.py
Purpose: Determine the sides of the traingle and determine if it is a triangle
Author: Lue.Kyle
Created: 23/02/2021
------------------------------------------------------------------------------
"""
#Input the le... |
1c17188e466cf9d7d5c032bab928c3b6ad867cb1 | rajasekharc/assignment2 | /assignment2/part1/abhi.py | 934 | 3.75 | 4 |
class A:
'This class is used to define a shapes.'
#variables
name='Bat'
@staticmethod
def change_name(updated_name):
A.name = updated_name
def __init__(self, len,color,diameter):
self.length = len
self.color = color
self.diameter = diam... |
76d874372d5c3188a3c2bd57283fbf4dc8a8aedf | KimKeonWoo/algorithm | /week_002/week_002_1864.py | 357 | 3.5625 | 4 | import math
base = "-\\(@?>&%"
## "/" : -1에 대응
while True:
n = input()
result = 0
count = 0
temp = 0
if n == "#":
break
n = n[::-1]
for i in n:
if i == "/":
temp = -1
else:
temp = base.find(i)
result += temp * pow(8, count)
... |
c79d6999b6917ab873187c06b29e0156c94e04be | KimKeonWoo/algorithm | /week_002/week_002_1264.py | 260 | 3.828125 | 4 | base = "aeiou"
while True:
count = 0
temp = input()
temp = temp.replace(" ", "")
temp = temp.lower()
if temp == "#":
break
for i in temp:
for j in base:
if i == j:
count += 1
print(count) |
13f8d46f29ebdb7014955d695a8df84ca5af81e8 | KimKeonWoo/algorithm | /CodeForces/take01_210604.py | 253 | 3.53125 | 4 | n = int(input())
for _ in range(n):
arr = list(map(int, input().split()))
flag = "YES"
if min(arr[0], arr[1]) > max(arr[2], arr[3]):
flag = "NO"
if max(arr[0], arr[1]) < min(arr[2], arr[3]):
flag = "NO"
print(flag)
|
5ba6cfe289b2cec8dd68df78d11253cbb7a5ec0c | ashutosh4336/python | /coreLanguage/ducktyping/lambda.py | 1,324 | 4.28125 | 4 | """
--> What is Lambda function ?
Lambda function are Namesless or Anonymous functions
'lambda' is not a function it is a keywork in python
--> Why they are Used.
One-Time-Use ==> Throw away function as they're only used Once
IO of other function ==> They're also passed as inputs or returned as outputs of other Hi... |
2d5f85e39b0aa1126981862fc5073bc5897f33f3 | gabrielablanco/PilasColas | /Libreria/librosMain.py | 538 | 3.84375 | 4 | pila = []
def apilar(libros):
pila.append(libros)
def desapilar():
print("El libro " + str(pila.pop()) + " se ha retirado de la pila")
def consultar():
print (pila)
while True:
print("1. Agregar libro")
print("2. Bucar ultimo libro ingresado")
print("3. Consultar libros")
... |
7c896f6a108356679ec145fdabe5189db6c36394 | vitroid/vitroid.github.io | /MD/smartfind.py | 979 | 3.75 | 4 | import types
def sfind(C, values, fromend=False):
"""
Given:
C: a sequence or a iterator
values: a collection of values to be found, or a function accepting single argument.
fromend=False: search from end.
Returns:
An iterator returning indexes.
"""
f = lambda x:x in values
... |
f7b2678e1e28c9f9d58cfb67579eda9643f72dc0 | swapnabandaru/chatbot | /bot.py | 459 | 3.515625 | 4 | from botfn import get_answer
ds= {'hi':['hello','hey','hi! good morning.'],
'hello':['hi','hey there','hello! how are you?'],
'how are you':['I am great','okay.what about you'],
'i am good':['oh thats great to hear','awesome!'],
'what is your name':['chatbot','chatterbot','bot-bot'],
'what is your fathers name':['ross... |
2c5a9eb55f19f64df92dff0433b5f43aa6c80ec2 | web3-qa/automateTheBoringStuff | /Chapter5Dictionary/fantasyGame/gameInventory.py | 725 | 3.703125 | 4 |
myStuff ={'rope' : 1, 'torch' : 6, 'gold coin' : 42, 'dagger' : 1, 'arrow' : 12}
def displayInventory(inventory):
print('Inventory:')
itemsTotal = 0
for k , v in inventory.items():
print(f'{v} {k}')
itemsTotal += v
print("Total items " + str(itemsTotal))
# displayInventory(myStuff... |
34e8655a26222e4c31f6a821ecada5c8b54d326f | shun2311/AADS-algorithms | /boyer-moore algorithm/good_suffix.py | 530 | 3.609375 | 4 | import z_algo
def reverse_z_array(pat):
reverse_pat = pat[::-1]
z_array = z_algo.z_algo(reverse_pat)
return z_array[::-1]
def good_suffix_array(pat):
reverse_z = reverse_z_array(pat)
good_suffix_array = [0] * (len(pat) + 1)
for i in range(0, len(pat) - 1):
j = len(pat) - reverse_z[i]
... |
1c252f47249967f0c06cfb9761a0bd3536d72c33 | afirez/alphazz-math | /math/py_math_calculus_001_limit.py | 477 | 3.515625 | 4 | import numpy as np
import matplotlib.pyplot as plt
import sympy as sp
x = sp.Symbol('x')
f = sp.sin(x) / x
limit = sp.limit(f, x, 'oo')
print(f'limit {f} : {limit} ')
x1 = np.arange(-100, 100, 0.01)
y1 = np.sin(x1) / x1
plt.figure(figsize = (12, 5))
plt.title('y = sin(x) / x')
plt.plot(x1, y1)
plt.show()
# def gr... |
345357e2e389c3886e3639c840c78f8fda01fd2a | Satishchandra24/CTCI-Edition-6-Python3 | /chapter2/removeDups.py | 1,859 | 4 | 4 | #Write code to remove duplicates from an unsorted linked list
class Node:
def __init__(self,data,next=None):
self.data=data
self.next=next
def getData(self):
return self.data
def getNext(self):
return self.next
def setNext(self,newNext):
self.next=newNext
class L... |
90b19ba814eb586ddae8d0b97068b71901a8627c | Satishchandra24/CTCI-Edition-6-Python3 | /chapter1/oneAway.py | 2,799 | 4.15625 | 4 | """There are three types of edits that can be performed on strings: insert a character,
remove a character, or replace a character. Given two strings, write a function to check if they are
one edit (or zero edits) away.
EXAMPLE
pale, ple-> true
pales, pale -> true
pale,bale-> true
pale,bake-> false"""
def oneAway(str1... |
9f23e5622d75c185d1dc267613745b85fa7f3c24 | Satishchandra24/CTCI-Edition-6-Python3 | /chapter2/sumList.py | 2,031 | 4.09375 | 4 | #You have two numbers represented by a linked list, where each node contains a single
#digit. The digits are stored in reverse order, such that the 1 's digit is at the head of the list. Write a
#function that adds the two numbers and returns the sum as a linked list.
import math
class Node:
def __init__(self,data,... |
46379b7d61a2c465139c7c9ed640c324375f1e35 | EricSchles/advanced_nyu_python_class | /class_three/singly_linked_list.py | 948 | 3.875 | 4 | class Node:
def __init__(self, data, next=None):
self.data = data
self.next = next
def __str__(self):
return repr(self.data)
class LinkedList:
def __init__(self):
self.head = None
self.size = 0
def append(self, data):
if self.head is None:
s... |
6135bd4e3d31721b0da958e6a05359242e812145 | Pravin2796/python_cls | /07_marks.py | 381 | 3.828125 | 4 | m1 =int ( input ("neter the marks of m1 : "))
m2 =int ( input ("neter the marks of m2 : "))
m3 =int( input ("neter the marks of m3 : "))
m4 = int (input ("neter the marks of m4 : "))
m5 = int (input ("neter the marks of m5 : "))
m6 =int ( input ("neter the marks of m6 : "))
m7 =int ( input ("neter the marks of m7 : "))... |
67596ad2023dce5d04fe4ba15de81ae4738108b2 | Pravin2796/python_cls | /pythoncourse.py | 219 | 4.03125 | 4 | print("GO CORONA GO")
i= 0
cases=list()
while(i < 5):
num = input("enter the total cases")
i = i + 1
cases.append(float(num))
#sum = sum + float(num)
avg = sum(cases) / len(cases)
print("avg", avg) |
eb449f33db9a5e2d47e3939dc980052d9852293b | IQRogelio/DeCeroaCienGen2021-03 | /Clase2/helloworld2.py | 152 | 3.578125 | 4 | # palabra = "Hola mundo"
#
# print(palabra)
#Este es un comentario solo de ejemplo
if True:
print("True")
else:
print("False")
print("False")
|
295b8804287db982a5f1f455c0298e27f27bc6d5 | IQRogelio/DeCeroaCienGen2021-03 | /Clase4/EjemploWhile.py | 349 | 3.84375 | 4 | #
# suma = 0
# numero = 1
# while numero != 10:
# suma = numero + suma
# numero = numero + 1
# print(suma)
# print ("La suma es " + str(suma))
print("¿Cuántos años tienes?")
edad = input()
print("La mitad de tu edad es "+ str(int(edad)/2))
def contar(tupla, entero):
#escribo mi codigo
return cua... |
bd897223c898fe68168a467fd41f7b1923bcf6ee | rwedema/master_ontwikkeling | /informatica_start/jupyter_notebooks/informatics01/WC_05/random_dna_template.py | 1,231 | 4.21875 | 4 | #!/usr/bin/env python3
#imports
import sys
import random
def calc_gc(seq):
#calculates the percentage of GC in the sequence
#finish this function yourself
pass
def generate_dna(len_dna):
#generates random DNA with GC percentage between 50 and 60%
#some comments removed. Write your own comments!... |
ea4d338b844b370f06bdfd9368fac0c1f154a8a7 | rwedema/master_ontwikkeling | /informatica_start/jupyter_notebooks/informatics01/WC_03/03_dna_convert_functions_solution.py | 1,748 | 4.15625 | 4 | #!/usr/bin/env python3
#solution for DNA convert
#imports
import sys
def is_valid_dna(seq):
#checks if all letters of seq are valid bases
valid_dna = "ATCG"
for base in seq:
if not base in valid_dna:
#the break statement is not needed anymore as return automatically breaks the loop.
... |
21e0628f603be17c0af1d91b7b624c27274af867 | TalalChaudhry/Elevator_System | /ElevatorSystem.py | 5,420 | 3.75 | 4 | import numpy as np
# simulates an elevator system
class ElevatorSystem:
# Initializing. This contains status of all elevators
def __init__ (self, number_of_elevators = None):
number = 16 if number_of_elevators is None else number_of_elevators
# This list contains the status of elevato... |
e3f55b3a606bb6897674f85edb5abb7fc3be94e2 | williamtw0131/interview_test | /solution1.py | 2,194 | 3.96875 | 4 | '''
1. 現有一字串 so = 'nahxatoamktbkoydvxoqbkkhvmadbu',
請找出在字串中出現最多次的字元並統計他的次數,
並以格式 "char:%s count:%d" 輸出
'''
so = 'nahxatoamktbkoydvxoqbkkhvmadbu'
# store the appearing letters without duplicate
# define a function takes in a string
def appearchar(str):
# storage list
chars = []
# iterate through the g... |
e7fe138254a4c6164e24e8aa9e72b081c16bfb92 | Lcicada/hello | /bullet.py | 1,608 | 3.765625 | 4 | # -*- coding: UTF-8 -*-
import pygame
from pygame.sprite import Sprite
class Bullet(Sprite):
def __init__(self, ai_settings, screen, ship):
super(Bullet,self).__init__()
self.screen = screen
#在坐标(0,0)处设置一个子弹的矩形
self.bullet_rect = pygame.Rect(0,0,ai_settings.bullet_width, ai_settin... |
da7e8e467ab2162b1c3ad437175a32ddb80fba71 | Registea2267/M3T2_Polygon | /M3T2_Register.py | 139 | 3.65625 | 4 | from turtle import *
def polygon(n, side_length):
for i in range(n):
left(360/n)
forward(side_length)
polygon(9,100)
|
1eba71594b4698c1bfa3a81bab6b64997661c274 | DataProphet/pdlog | /pdlog/string.py | 932 | 3.71875 | 4 | from datetime import date
from datetime import datetime
from typing import Any
from typing import Sequence
def plural(n: int, noun: str) -> str:
if n == 1:
return f"{n} {noun}"
return f"{n} {noun}s"
def percent(n: int, total: int) -> str:
if n == 0:
return "0%"
if n == total:
... |
8be6cedb8e2566652402f3e6814c1d3df9a4bae1 | mrdo19111911/datascience_supplychain_practice | /Jupyternotebook_source/Section_19_Consumer_behavior_and_pricing/linear+price+answers.py | 1,651 | 3.765625 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Sep 13 15:28:02 2020
@author: haythamomar
"""
import pandas as pd
from sklearn.linear_model import LinearRegression
import numpy as np
pineapple= pd.read_csv('pinapple_juice.csv')
X= pineapple[['Price']]
y= pineapple[['Pinapple juice']]
model= Line... |
7a43fd30e7272fc780e8516395a6a32c5c2cc2b0 | mohammedaheel98/Python_repo | /code kata absolute beginner/prb781.py | 109 | 3.546875 | 4 | N = int(input())
for i in range(1,N):
if N==0:
print("NULL")
else:
print(i*9,end=" ")
print(N*9)
|
b426eff13fd023ccef13256f1585ef1f9371da4b | abaldeg/EjerciciosPython | /PROGRAMACION I TP 3 EJ 4 SEGUNDO CUATRIMESTRE.py | 2,945 | 3.96875 | 4 | """
Una fábrica de bicicletas guarda en una matriz la cantidad de unidades producidas
en cada una de sus plantas durante una semana. De este modo, cada columna representa
el día de la semana (Lunes columna 0, Martes columna 1…) y cada fila
representa a una de sus fábricas.
Se solicita:
a. Crear una matriz con datos gen... |
b77b8bdbf1c7a2f30c411bef11c07a9a7fb0abe8 | abaldeg/EjerciciosPython | /PROGRAMACION I TP 1 EJ 1 HECHO OTRA VEZ.py | 884 | 4.09375 | 4 | """Desarrollar una función que reciba tres números positivos y devuelva el mayor de
los tres, sólo si éste es único (mayor estricto). En caso de no existir el mayor estricto
devolver -1. No utilizar operadores lógicos (and, or, not). Desarrollar también
un programa para ingresar los tres valores, invocar a la función y... |
112734e194746d6af106b76a3c274e695217a69c | abaldeg/EjerciciosPython | /PROGRAMACION I TP 2 EJ 3.py | 526 | 3.609375 | 4 | #Crear una lista con los cuadrados de los números entre 1 y N (ambos incluidos),
#donde N se ingresa desde el teclado. Luego se solicita imprimir los últimos 10 valores
#de la lista.
#Funciones
def crearListaCuadrados(l,n):
l=[0]*(n+1)
for i in range(1,n+1):
l[i]=i**2
return (l)
def imprimirLi... |
3be2607343cf924a32875437001c1375bfdfd7a1 | abaldeg/EjerciciosPython | /PROGRAMACION I TP 8 EJ 5 SEGUNDO CUATRIMESTRE.py | 672 | 3.84375 | 4 | """En geometría un vector es un segmento de recta orientado que va desde un punto
A hasta un punto B. Los vectores en el plano se representan mediante un par ordenado
de números reales (x, y) llamados componentes.
Dos vectores son ortogonales cuando son perpendiculares entre sí. Para determinarlo
basta calcular su prod... |
74d8061cc74328a6c65d08ff91ec679347bb76f3 | abaldeg/EjerciciosPython | /Simulacro Segundo Parcial Segundo Cuatrimestre Segundo ejercicio.py | 472 | 4.21875 | 4 | """2) Desarrollar una función recursiva que reciba un número binario y lo devuelva convertido
a base decimal. Creando una excepción o generando ValueError en caso de recibir un número que no es
binario o un número negativo con el mensaje aclaratorio correspondiente a cada error. Resolver utilizando
raise o assert."""
d... |
29dd164d30b9d496290b800587e26769be5172be | abaldeg/EjerciciosPython | /tp 4 ej 1.py | 89 | 4.03125 | 4 | n=0
while n !=-1:
n=int(input("Ingrese un Numero: "))
print ("Numero",n)
|
44eb5f2b9c15f5902356f84b980648b5d77ac6d7 | abaldeg/EjerciciosPython | /tp 4 ej 3.py | 248 | 4.03125 | 4 | n=0
impar=False
while n !=-1:
n=int(input("Ingrese Numero: "))
if impar==True:
impar=False
else:
impar=True
if impar == True:
print ("Numero de veces impar")
else:
print ("Numero de veces par")
|
1036c312d17f5951b235862a61e83917e69b5fe4 | abaldeg/EjerciciosPython | /PROGRAMACION I TP 7 EJ 6.py | 630 | 3.984375 | 4 | """La función de Ackermann A(m,n) se define de la siguiente forma:
n+1 si m = 0
A(m-1,1) si n = 0
A(m-1,A(m,n-1)) de otro modo
Imprimir un cuadro con los valores que adopta la ... |
af21c7e7b57405af6088a7ad509ddf3434c2b0b7 | abaldeg/EjerciciosPython | /Simulacro 2P Segundo Cuatrimestre Ejercicio Recursividad Extra.py | 765 | 3.796875 | 4 | """Utilizando una función recursiva determine cuál es la palabra de una lista
que repite más veces el último caracter."""
def mayorRepeticion(listapalabras, palabramayor="",cantmax=0):
if len(listapalabras)==0:
return palabramayor
else:
cantrepe=0
palabraactual=listapalabras[0].upper()
... |
6d2c5add24993e39fc519d16e959cbca7d263ebf | abaldeg/EjerciciosPython | /Segundo Parcial Gaston Abalde Ej2.py | 3,611 | 3.515625 | 4 | """
EJERCICIO 2
Hora de jugar!: Se requiere desarrollar un juego de preguntas, en que se puede
responder "si" o "no".
Las preguntas a formular se encuentran en un archivo de texto enumeradas desde el 1 hasta 8,
la pregunta a formular y la respuesta correcta (si o no) separada por punto y coma.
Ejemplo:
1;Los dicciona... |
697dfb7636f79d1e231e5a997a87c05d6370c7cd | abaldeg/EjerciciosPython | /tp 5 ej 4.py | 197 | 3.671875 | 4 | def fVerificaPar(n):
if n % 2 == 0 :
par = True
else:
par = False
return par
n=int(input("Ingrese número: "))
print (fVerificaPar(n))
|
58e775dcf05daddb351bed9255ef21716d8519c5 | abaldeg/EjerciciosPython | /2. Variables y operaciones.py | 311 | 3.859375 | 4 | a=3
b=a
c=a+b+1
print ("La variable a contiene",a,"b contiene",b,"y c contiene",c)
#Suma
print
print (2+2)
print
#Multiplicacion
print (2*2)
print
#Division
print (100/3)
print
#Division Entera
print (100//3)
print
#Potenciacion
print (2**4)
print
#Resta
print (2-2)
#Modulo
print (100%3) |
ad4bdf30529bc9c30ddacdca55772370c165d2b6 | abaldeg/EjerciciosPython | /PROGRAMACION I TP 4 EJ 6.py | 1,102 | 3.90625 | 4 | #Desarrollar una función que extraiga una subcadena de una cadena de caracteres,
#indicando la posición y la cantidad de caracteres deseada. Devolver la subcadena
#como valor de retorno. Escribir también un programa para verificar el comportamiento
#de la misma. Ejemplo, dada la cadena "El número de teléfono es 4356-
#... |
887791ca87dc6644398c91b3fe7ffee7653dca26 | abaldeg/EjerciciosPython | /EXTRAS_contar_cadenas_primer_y_ultimo_caracter_iguales.py | 634 | 3.90625 | 4 | #Write a Python program to count the number of
#strings where the string length is 2 or more
#and the first and last character are same from
#a given list of strings
#Sample List : ['abc', 'xyz', 'aba', '1221']
#Expected Result : 2
def contarCadenas(lista):
cont=0
for c in lista:
if len(c) > 1 and c[0]=... |
d2040f23880631d72fa1f90eca9374c012ac0db5 | abaldeg/EjerciciosPython | /PROGRAMACION I TP 2 EJ 7.py | 803 | 4.15625 | 4 | #Escribir una función que reciba una lista como parámetro y devuelva True si la lista
#está ordenada en forma ascendente o False en caso contrario. Por ejemplo,
#ordenada([1, 2, 3]) retorna True y ordenada(['b', 'a']) retorna False. Desarrollar
#además un programa para verificar el comportamiento de la función.
#Funci... |
bbab2b4abcbb9481d77313cd70a52fa30cf32b81 | abaldeg/EjerciciosPython | /EXTRAS_Listas_Por_Comprension.py | 862 | 4 | 4 | # Create `new_list`
numbers = range(10)
# Initialize `new_list`
new_list = []
# Add values to `new_list`
for n in numbers:
if n%2==0:
new_list.append(n**2)
#Ejemplo: ["1 Oros",#"2 Oros"... ]. Imprimir la lista por pantalla.
new_list = [ (n,p) for p in ["Oro", "Copas", "Espada", "Basto"] for n in range (1,... |
e590b6f55c9b0c21029f0e1dc6eb1b2287e46df6 | abaldeg/EjerciciosPython | /tp 5 ej 13.py | 446 | 3.6875 | 4 |
def fUltimosDigitos(d,e):
resultado = -1
div = 1
cont = 1
while cont <= e :
div = div * 10
cont = cont + 1
if (d//div) == 0:
return -1
else:
return d % div
a=int(input("Ingrese número E... |
137c094a217d90d71004a9027165ba572535648d | abaldeg/EjerciciosPython | /tp 5 ej 6.py | 554 | 3.71875 | 4 | #Devolver True si el número entero recibido como primer parámetro es múltiplo
#del segundo, o False en caso contrario.
#Ejemplo: esmultiplo(40,8) devuelve True
#y es multiplo(50,3) devuelve False.
def fVerificarMultiplo(a,b):
if a % b == 0:
Multiplo = True
else:
Multiplo = Fa... |
7e0fc8d5c2192656f58fa6eeae9de2d3361fde3d | abaldeg/EjerciciosPython | /EXTRAS busqueda de minimos.py | 135 | 3.984375 | 4 | #https://www.tutorialspoint.com/python/list_min.htm
list1 = [1,2,3,4,5,6,1,1,1,2,3,3,7,8,3]
print ("min value element : ", min(list1))
|
dce88da3313f31adc259d7c9ee17817578b9295a | abaldeg/EjerciciosPython | /tp 3 ej 10.py | 632 | 3.984375 | 4 | l1=float(input("Ingrese lado 1:"))
l2=float(input("Ingrese lado 2:"))
l3=float(input("Ingrese lado 3:"))
if l1 > l2 and l1 > l3:
a=l1
b=l2
c=l3
if l2 > l1 and l2 > l3:
a=l2
b=l1
c=l3
if l3 > l1 and l3 > l2:
a=l3
b=l1
c=l2
if a >= b + c:
resultado='No es un... |
4603414e65acc5b0ec1d2f9a717726291c6bf13e | BLPeng/LeetCode | /CIT590/cities.py | 4,382 | 4.21875 | 4 | #Student name: Bolu Peng
#Penn ID: 16847239
#I accomplish this assignment all by myself
import math
import random
def main():
road_map = read_cities('city-data.txt')
road_map_final = road_map[:]
print_cities(road_map)
count = 0
while count < 3:
# Randomly shuffle the list
random.sh... |
8e0ad249be1f9ec10611155cf30fc682f8f5f882 | senemaktas/Parallel-Programming | /rand1.py | 224 | 3.875 | 4 | # -*- coding: utf-8 -*-
import random
import matplotlib.pyplot as plt
print(random.randint(0,100))
x=[random.randint(0,9) for p in range(0,9)]
y=[random.randint(0,9) for p in range(0,9)]
plt.plot(x,y)
plt.show()
|
8475d3a3983443f1790e5d8347e74ea3ca5bfc49 | senemaktas/Parallel-Programming | /Trapezoidal_Integration.py | 315 | 3.90625 | 4 | '''Example of python code that finds numerically the zero pi / 2 range of x * sinx integral using
trapezoidal numerical integration method.'''
from math import sin,pi
f=lambda x: x*sin(x)
a=0
b=pi/2
n=5
h=(b-a)/n
s=0.5*(f(a)+f(b))
for i in range(1,n):
s+=f(a+i*h)
integral=h*s
print("integral= %f" %integral) |
e977567aa32b21b6b0a557963a5cd3a01982bca1 | boluwaji11/Py-HW | /HW4/HW4-5_Boluwaji.py | 674 | 4.5 | 4 | # This program calculates the factorial of nonnegative integer numbers
# Start
# Get the desired number from the user
# Use a repetition control to calculate the factorial
# End
# ==============================================================
print('Welcome!')
number = int(input('\nPlease enter the desired positiv... |
adf9d5898e666f01c6fb4e8c5a7976fe0242283f | boluwaji11/Py-HW | /HW3/HW3-4_Boluwaji.py | 1,191 | 4.4375 | 4 | # This program converts temperature in degrees Celsius to Fahrenheit.
# Start
# Get the temperature in celsius from the user
# Calculate the Fahrenheit equivalent of the inputted temperature
# Check the result
# If the result is more than 212F
# Display "Temperature is above boiling water temperature"
... |
0cd27f6603efb0bea65eb78aceff2e0ccb25a884 | boluwaji11/Py-HW | /HW5/HW5-3_Boluwaji.py | 1,712 | 4.1875 | 4 | # This program calculates dietary information
# Start
# Define main function
# In the main function,get fat and carbohydrate information from the user
# Pass fat to calories_fat and call it
# Pass carbohydrate to calories_carbs and call it
# Call calories_fat and calories_carbs in main
# Define the c... |
2eece337929e5f114a7a8a2e4dc0e33d4634906b | boluwaji11/Py-HW | /HW6/HW6-1-a_Boluwaji.py | 1,476 | 4.15625 | 4 | # This program saves different video running times for Kevin to the video_running_times.txt file.
# Start
# Define the main function
# Ask Kevin for the number of short videos he's working with
# Open a file to save the videos
# Enter the different times and write it to file
# Close the file
# Noti... |
f63a696b85997684283dd58cffeb2af6bf30dc9d | PrashantJalan/NLP | /Hindi/Word analysis/Functions/ignore.py | 189 | 3.640625 | 4 | # Deletes the strings having the mentioned frequency
def ignore_freq(db_word, freq):
i = len(db_word)-1
while i>=0:
if db_word[i][1]==freq:
db_word.pop(i)
i = i-1
return db_word
|
34620c179ed673c851895bb2fe4213b15604ff8d | BOT-Hunter/python-practice | /27)cumulativeSum.py | 156 | 3.71875 | 4 | list1 = [1, 2, 3, 4]
def cumulative_sum(list):
y = 0
a = 0
b = []
for x in list:
y += list[a]
b.append(y)
a += 1
print(b)
cumulative_sum(list1) |
f777a3a57bfabdc55e1236d1dd2f9173f8c78848 | BOT-Hunter/python-practice | /lensortList.py | 210 | 4.0625 | 4 | #sorting a list of strings based on the length of strings
list1 = ['apple', 'banana', 'cat', 'zebronic', 'cattle', 'hurdang']
def lensort(list):
list.sort(key = lambda x: len(x))
print(list)
lensort(list1) |
aba3856ac227e18ef323ee9510d75398a003a0a0 | ruediluethi/Ausbeutung_von_Tierpopulationen | /Code/cellular2/helpers.py | 228 | 3.8125 | 4 | def frange(start, stop, step=1, steps=None):
if steps:
step = (stop-start)/steps
n = start
while n < stop:
yield n
n += step
if __name__ == '__main__':
print(list(frange(2, 5, steps=10))) |
093968021a2516105bd98ea28be8da1edd765cd0 | AbsoluteVirtue/python-cheat-sheet | /general.py | 14,379 | 3.671875 | 4 | # list all keywords
def list_keywords():
import keyword
return keyword.kwlist
# show variable's unique identity
def show_var_id(var):
id(var)
# show object's type
def show_obj_type(var):
type(var)
# list all standard types
def list_standard_types():
import types
dir(types)
# calculate fa... |
acf7ba6c1b160e0036d65ef19a94c1204e729ec9 | Frankfurtjulian/python2020_Cent8 | /005_list_sort.py | 234 | 3.5625 | 4 | #!/usr/bin/python3.7
# -*- coding=utf-8 -*-
# 本脚本由黄猛编写,用于Python学习!
l1 = [4, 5, 7, 1, 3, 9, 0]
l2 = l1.copy()
l2.sort()
for i in range(len(l1)):
print(l1[i],l2[i])
if __name__ == '__main__':
pass
|
fafcd54d9ca7df23aa71d59fa7dde85b0b153aee | JasoSalgado/python-problems | /first-week/first-exercises/problem_16.py | 836 | 4.34375 | 4 | """
Pedir el día, mes y año de una fecha e indicar si la fecha es correcta. Con meses de 28, 30 y 31 días. Sin años bisiestos.
"""
instructions = "***** Enter a valid date. For instance: dd/mm/yyyy *****"
print(instructions.center(50, "*"))
day = int(input("Write a day: \n"))
month = int(input("Write a month: \n"))
y... |
a35aa8b96d8fa8820556790e4ebb69552e569d5b | JasoSalgado/python-problems | /second-week/first-exercise-poo/account.py | 1,595 | 4.1875 | 4 | class Account():
def __init__(self, account_holder, amount):
self.__account_holder = input("Enter an account holder: \n")
self.__amount = float(input("Enter an amount: \n"))
@property
def account_holder(self):
return self.__account_holder
@property
... |
6a1288f7eb4c1d9934ec25f3b6d1c71451f58819 | JasoSalgado/python-problems | /first-week/first-exercises/problem_18.py | 787 | 4.125 | 4 | """
Ídem que el ej. 17, suponiendo que cada mes tiene un número distinto de días (suponer que febrero tiene siempre 28 días).
"""
instructions = "***** Enter a valid date. For instance: dd/mm/yyyy *****"
print(instructions.center(50, "*"))
day = int(input("Write a day: \n"))
month = int(input("Write a month: \n"))
ye... |
f12636731501f945c801edefcc7236cddcf2c5c2 | sreshtha10/Python | /Chemical_Fuels/boys_calorimeter.py | 623 | 3.828125 | 4 | #Boys Caloriimeter
#Principle: principle involved in this method is to burn the gas at a known
#constant rate in a vessel under such conditions that the entire amount of heat
#produced is absorbed by water which is also flowing at a constant rate.
W = float(input("Weight of water passed in time t \n"))
V = float(input... |
07e7a71e70e2fed0f10c8c041b56b2dce24508bc | piyush546/Machine-Learning-Bootcamp | /Machine Learning programs/Supervised ML programs/ridge, lasso, elastic net/Prostate_cancer.py | 3,042 | 3.609375 | 4 | # -*- coding: utf-8 -*-
"""
Code Challenge 01: (Prostate Dataset)
Load the dataset from given link:
pd.read_csv("http://www.stat.cmu.edu/~ryantibs/statcomp/data/pros.dat", delimiter =' ')
This is the Prostate Cancer dataset. Perform the train test split before you apply the model.
(a) Can we predict lpsa from the ot... |
9f4e5d5c93d94f01f61e924974c34d869a5fa0b1 | piyush546/Machine-Learning-Bootcamp | /Basic Python programs/listreverse.py | 341 | 4.21875 | 4 | # -*- coding: utf-8 -*-
""" A program to demonstrate list content reversing and optimizing the reversing method of string """
# To take user name input in single command using split
name = input().split()
# to print the name string after reversing
name = name[::-1]
name = " ".join(name)
print(name)
# Input = piyu... |
bf2f55b748a1dc5ff8d4f72eab5d074e2a78ec39 | piyush546/Machine-Learning-Bootcamp | /Intermediate Python programs/copy_command2.py | 622 | 3.578125 | 4 | # -*- coding: utf-8 -*-
# To import time module for duration and time related activity
import time
start_time = time.time()
# To open a file for reading
with open("romeo.txt","r") as fileobj:
list1 = fileobj.read().splitlines()
words_list = []
for var in range(0, len(list1)):
words_list.extend(list1[var].sp... |
68742eb158b913e6e9f3f85f80d669eef018fa2d | piyush546/Machine-Learning-Bootcamp | /Basic Python programs/style.py | 290 | 4.15625 | 4 | # -*- coding: utf-8 -*-
""" A program to use some str methods """
# variables to store strings to be styled
First_string = input("Enter the string:")
# To print the strings after styling
print(str.upper(First_string))
print(str.lower(First_string))
print(str.capitalize(First_string))
|
8ee36e94471e1a22b1dcb58f11c5964a9c155782 | piyush546/Machine-Learning-Bootcamp | /Projects/Scrapper Project/scrapperproject.py | 6,011 | 3.546875 | 4 | # -*- coding: utf-8 -*-
""" A project which will provide all types of information of journals published
in the duration of a week from the present date in csv format"""
# Importing pandas to create dataframe and to save the data in csv format
from pandas import DataFrame as DF
import pandas as pd
# Importing regex t... |
c394fa007814461398ba7bef4a7120e406b334d7 | piyush546/Machine-Learning-Bootcamp | /Intermediate Python programs/fizzbuzz.py | 549 | 4.09375 | 4 | # -*- coding: utf-8 -*-
# program to print fizz for multiple of 3, buzz for multiple of 5 and fizzbuzz for both multiple of 4 and 5
for i in range(1, 51):
if(i % 3 == 0 and i % 5 == 0):
print("FizzBuzz")
elif(i % 5 == 0):
print("Buzz")
elif(i % 3 == 0):
print("Fizz")
else:
... |
a004c9daad285cdfaa44a82d2adcf6253427566a | piyush546/Machine-Learning-Bootcamp | /Data preprocessing and analytics/Numpy programs/Imagemaker.py | 811 | 3.875 | 4 | # -*- coding: utf-8 -*-
""" A program to make an graycsaleimage using numpy array """
# Importing the numpy and matplotlib module
import numpy as np
import matplotlib.pyplot as plt
# Importing Pillow libraray for saving the numpy array as image
from PIL import Image
# Defining the color codes for creating the image
... |
717405a3b7fd40f74b437bc3105f426ee4affc0b | piyush546/Machine-Learning-Bootcamp | /Intermediate Python programs/Intersection.py | 224 | 3.875 | 4 | # -*- coding: utf-8 -*-
# given list
list5 = [1, 3, 6, 78, 35, 55]
list6 = [12, 24, 35, 24, 88, 120, 155]
# Intersection list
Intersect_list = list(set(list5).intersection(set(list6)))
print(Intersect_list)
# output =[35]
|
c00fd33e280a8f4c56cfd7d4ed916a72b9e5872e | piyush546/Machine-Learning-Bootcamp | /Data preprocessing and analytics/pandas and matplotlib/csvGroupby.py | 2,584 | 3.765625 | 4 | # -*- coding: utf-8 -*-
""" Program to read a well structured csv file with headers and applying
various functions on it like groupby, reshape, isnull , dropna, fillna """
# Importing pandas module
import pandas as pd
try:
# Opening the csv file and storing it in the df
df = pd.read_csv("Salaries.csv")
exce... |
f995bb9a7a623456daa018dd70709534e4e87067 | piyush546/Machine-Learning-Bootcamp | /Json,Rest Api,Database programs/locally+remote database handling/sqlalchemy_test.py | 3,902 | 3.796875 | 4 | # -*- coding: utf-8 -*-
""" A program to implement database handling through sqlalchemy module """
# to create engine to through the database importing create_engine from sqlalchemy
# Impporting some methods required for creating a table
from sqlalchemy import create_engine, Column, Integer, String, ForeignKey
# Impo... |
384a01cfb8f8eaca02fcb0ff3698e56954a99964 | piyush546/Machine-Learning-Bootcamp | /Machine Learning programs/Unsupervised ML programs/Association/Association.py | 4,013 | 4.03125 | 4 | # -*- coding: utf-8 -*-
"""
Association rules analysis is a technique to uncover how items are associated
to each other.
There are three common ways to measure association.
Measure 1: Support. This says how popular an itemset is,
as measured by the proportion of transactions in which an itemset appears.
Itemsets ca... |
478190bc4022846cf840a91a300ee470459031d7 | piyush546/Machine-Learning-Bootcamp | /Fun programming/Hash of file.py | 1,479 | 4.0625 | 4 | # -*- coding: utf-8 -*-
# Hashing is the transformation of a string of characters into a usually shorter fixed-length value or key that represents the original string.
# hashlib - implements a common interface to many different secure hash and message digest algorithms.
# sha1 - Secured Hash Algorithm 1 - a cryptograph... |
3c35f304bfe1255efc5b6cc3a09aab1e69935869 | nlawrence22/advent-of-code | /day4/day4.py | 3,721 | 3.640625 | 4 | import re
validFields = {
"byr": 1,
"iyr": 1,
"eyr": 1,
"hgt": 1,
"hcl": 1,
"ecl": 1,
"pid": 1
}
valid = 0
lines = None
with open('day4input.txt', 'r') as input:
lines = input.readlines();
#print(lines)
def getPassports(input):
passports = []
passport = {}
for line in inp... |
2e1854e9ab538d801494beec7ea2fcd10adfc2d8 | xor26/cormen_algorithm_solutions | /2/2.1.py | 1,032 | 4 | 4 | def merge(left_part, right_part):
merged_array = [0] * (len(left_part) + len(right_part))
left_part.append(float("inf"))
right_part.append(float("inf"))
left_index = 0
right_index = 0
for i in range(len(merged_array)):
if left_part[left_index] <= right_part[right_index]:
me... |
51e9aab42bee596b8316cc11196d2a91fe701b95 | haimianying/Open-Sesame | /dtw_algorithm.py | 3,677 | 3.765625 | 4 | import math
class Vector:
def __init__(self, x, y, z):
self.x = x
self.y = y
self.z = z
def __sub__(self, other): # for if you were to subtract one vector object from another, uses Pythagorean theorem
x = self.x - other.x
y = self.y - other.y
z = self.z - othe... |
f94457243220f4d9493a3cf27b0d1c96b173df70 | syfanx/black-hat-python | /2-The Network: Basics/2.1-tcp-client.py | 2,338 | 3.921875 | 4 | # 0. import socket module
import socket
target_host = "www.google.com" # insert website "[]"
target_port = 80 # port 80 commonly used in Hypertext Transfer Protocol(http)
# 1. create a socket object # socket instance with 2 parameters(AF_INET & SOCK_STREAM)
client... |
86687ae0eb90fd4420d2e973566a32199272c900 | me0wingtons/python | /Triangle.py | 515 | 3.9375 | 4 | def triangle(n):
if n == 1:
return '*\n'
else:
star = ''
stacker = ''
for i in range(1,n+1):
if i == 1:
star += '*'
stacker += star +'\n'
elif i % 2 != 0: #odd
star = '*' + star
st... |
ddf8af3f71aa666b8e1e83c0a99d6ed495af98d5 | bartd990/mynameisdamien | /Homework.py | 407 | 3.796875 | 4 | import turtle
Window = turtle.Screen()
Window.bgcolor("black")
Window.title("Damien's super fun and boring game of code he did for homework")
TurtlePen = turtle.Pen()
turtle.speed(10)
Window.colormode(255)
TurtlePen.pencolor("white")
for counter in range(9000):
TurtlePen.forward(counter)
TurtlePen.left(20)
... |
a3feb02849cf4348ce42602c16cb98593b34cf14 | bartd990/mynameisdamien | /ColorSquareSpiral.py | 556 | 3.828125 | 4 | import turtle
Window = turtle.Screen()
Window.bgcolor("black")
Window.title("Damien's super fun and boring game of code called 'Color Square Spiral'")
Color = ["blue violet", "dark olive green", "dodger blue", "gold4"]
TurtlePen = turtle.Pen()
turtle.speed(10)
# TurtlePen.pencolor("red")
for counter in range(9000):
... |
ada8f29958079f39aad70a297dc1edd5e5ac389f | afdzioba/adv-rpn | /rpn.py | 1,250 | 3.5625 | 4 | #!/usr/bin/env python3
from colored import fore, back, style
def calculate(arg):
stack = []
tokens = arg.split()
for token in tokens:
try:
stack.append(int(token))
except ValueError:
val2 = stack.pop()
val1 = stack.pop()
print(val1, end='')... |
0a0a21e8a18b0fad9e48a4974e691de52df95ffe | sunnycake/Capstone_Lab5 | /jugglers.py | 3,750 | 3.625 | 4 | from peewee import *
db = SqliteDatabase('jugglers.sqlite')
class Juggler(Model): # Juggler model to make Juggler Object
name = CharField()
country = CharField()
catches = IntegerField()
class Meta: # Link model class to db.
database = db
def __str__(self):
return f'ID: {self.id}... |
77c4591d35aae0e6cd5b0d19e5de73fe8eb2cdf1 | realstraw/pylibstraw | /pylibstraw/maths/edit_distance.py | 1,115 | 4.03125 | 4 | # import sys
def __init_matrix(rows, cols):
"""Build a matrix required for dynamic computing edit distance given number
of rows and colums.
Returns matix (list of list)."""
matrix = [[0 for j in range(cols)] for i in range(rows)]
for i in range(rows):
matrix[i][0] = i
for i in range(co... |
655fc28a5baa9c942cf3914a5e94a405422d04a2 | carlosloureda/meme-generator | /src/quote_engine/TextIngestor.py | 1,362 | 3.734375 | 4 | """IngestorInterface strategy operator that implements an Ingestor strategy for text files."""
from typing import List
from .IngestorInterface import IngestorInterface
from .QuoteModel import QuoteModel
class TextIngestor(IngestorInterface):
"""Defines the two methods for implement the `txt` ingestion strategies... |
be154620213bfad54e0e3e357acff0412cace8a1 | 281950287581/linear_algebra | /积分函数/01.py | 1,549 | 3.734375 | 4 | import numpy as np
from scipy.integrate import quad
"""
在Scipy的integrate子包里提供了很多和积分相关的函数,
例如quad可以对一般一元函数进行积分
I=∫10(3x2+2x+1)dx=(x3+x2+x)|10=3+c
变量f是求积分的多项式 f(x)=3x2+2x+1 f(x)=3x2+2x+1,
quad函数则是求定积分函数,计算结果应该是3
"""
# f = np.poly1d([3, 2, 1])
# print(f)
# ret = quad(f, 0, 1)
# print(ret)
"""
在积分里±∞±∞用±np.inf±np.inf表示
"... |
32099e0fc99308def5b2a4c6967ec33423a41a34 | maylandertamas/Python_flask_taskmanager | /database_handler.py | 1,309 | 3.5625 | 4 | import sys
import os
import psycopg2
import urllib
"""
:Local connection to db
def connect_to_database():
try:
conn = psycopg2.connect("dbname='SI5_starwars' user=''")
except psycopg2.Error as error:
print("Couldn't connect to database")
print(error)
sys.exit(1)
else:
... |
8f53f56d46ffd2ff6a0b198762130da1cbb4633f | EricBanker12/Algorithms | /rock_paper_scissors/rps.py | 550 | 3.71875 | 4 | #!/usr/bin/python
import sys
def rock_paper_scissors(n):
outputs = ['rock', 'paper', 'scissors']
def next_perm(perm, n):
if n == 0:
return perm
permutations = []
for arr in perm:
for hand in outputs:
permutations.append([*arr, hand])
return next_perm(permutations, n - 1)
re... |
7fda982e8db8ee218bf2911ff731e182c0262240 | kaydee0502/bits | /Python 3/postfix.py | 897 | 3.640625 | 4 | class stack:
def __init__(self,data):
self.data = data
def stck(self):
obj = self.data
global s
s.append(obj)
def pf():
res = 0
op = list("* - / +".split())
global s
i = len(s)
a = 0
if (s[0] or s[1]) in op:
raise ... |
fca6d8aa9c4801ccd4f5c4a180896cf4904c7415 | tahirs95/pepys-import | /pepys_import/core/store/table_summary.py | 2,669 | 3.546875 | 4 | from tabulate import tabulate
class TableSummary(object):
"""
A summary of the contents of a table, which sends query to DB and finds
number of rows and creation date of last item added.
:param session: Bounded session for querying table
:type session: SQLAlchemy Session
:param table: SQLAlch... |
e66bfa75aada813fda00327d1bae1e76978bca1f | ralf1997/Assignment10 | /assignment10.py | 1,021 | 3.5 | 4 | import random
#Q1
f = open('test.txt', 'r') # file open operation for f1
lines = f.readlines()
n = int(input('enter the number of lines you want to print from the end'))
print(lines[:n])
#Q2
f = open('test2.txt')
line = f.read()
split = line.split()
print(split)
#Q3
f2 = open('test.txt', 'w')
for l... |
32bbd0139fd7545565e6a7777e8a6fc0a3f46bdb | Felopo/Progra-avanzada | /Syllabus/Actividades/AC00/base.py | 344 | 3.546875 | 4 | import math
class Cuadrado(object):
def __init__(self, lado):
self.lado = lado
def calcular_area(self, lado):
area = self.lado*lado
return area
class Triangulo(object):
def __init__(self, arg):
# Completar método y borrar pass
pass
# Agregar métodos
if __name__ == '__main__':
# C... |
0744cb85725d460f4eb4a5bd2cceac999ffc70be | marcellasiqueira/aplicacao_grafos | /atg2.py | 572 | 3.5625 | 4 | # coding: utf-8
# Marcella Medeiros Siqueira Coutinho de Almeida
# [ATG] Grau de um Vértice
# Matrícula: 117110492
N = int(input()) # número de vértices do grafo
grafo = {} # declara um Mapa vazio
# para cada vez (de 0 até o número total de vértices), lê-se um vértice, as arestas e associa-se essas arestas ao seu re... |
29ad9903d360d2a78a4fc36da9259ba56420ce40 | marcellasiqueira/aplicacao_grafos | /atg11.py | 1,496 | 3.515625 | 4 | # coding: utf-8
# Marcella Medeiros Siqueira Coutinho de Almeida
# [ATG] Fluxo Válido
# Matrícula: 117110492
N = int(input()) # número de arestas do grafo
digrafo = {} # declara um Mapa vazio
fluxo = {} # declara um Mapa vazio
# inicializa o vértice no dígrafo, percorre o tamanho da entrada e adiciona a aresta no ... |
7fc2a5961b57a7c08c5ebae3a0692cfba4778feb | dagorret/curso_python | /prueba_condicional_tres.py | 398 | 4 | 4 | print("Asignaturas optativas")
print("Optativas: Informática gráfica, Pruebas de software, Usabilidad y accesibilidad")
opcion = input("Escribe la asignatura escogida")
asignatura = opcion.lower()
if asignatura in ("informática gráfica", "pruebas de software", "usabilidad y accesibilidad"):
print("Asignatura eleg... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.