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 |
|---|---|---|---|---|---|---|
3434b25d66c2edefe39cc30ecc20b8a886d45639 | kundaMwiza/dsAlgorithms | /source/palindrome.py | 869 | 4.1875 | 4 | def for_palindrome(string):
"""
input: string
output: True if palindrome, False o/w
implemented with a for loop
"""
for i, ch in enumerate(string):
if ch != string[-i-1]:
return False
return True
def rec_palindrome(string):
"""
input: string
output: True if p... |
a48e91e03bf600a76899e02ea3ac3a75ed43a55d | chiaminchuang/Leetcode | /Easy/349-Intersection of Two Arrays/349.py | 750 | 3.796875 | 4 | class Solution(object):
def intersection(self, nums1, nums2):
"""
:type nums1: List[int]
:type nums2: List[int]
:rtype: List[int]
"""
return list(set(nums1) & set(nums2))
def quicksort(self, arr):
if len(arr) <= 1:
... |
30464a88b5ae8ac2e53d6eda62742a64496b2025 | DaianaMicena/fiap-exercicios-python | /Exercicios_Python/exercicio79.py | 409 | 4.0625 | 4 | lista = []
while True:
n = int(input('Digite um numero: '))
if n not in lista:
lista.append(n)
print('Numero adicionado com sucesso!!!')
else:
print('Numero duplicado!!!',end= ' ')
n = int(input('Digite um numero: '))
r = str(input('Deseja continuar? [S/N]')).upper()
... |
f12d55f3c49e756325fc79d0676e754b3a1af0db | DaianaMicena/fiap-exercicios-python | /Exercicios_Python/exercicio7.3.py | 378 | 3.78125 | 4 | for each in range(10, 20):
print('esse é o valor de n: ', each)
print('esse é o valor de n: ', each)
print('esse é o valor de n: ', each)
print('esse é o valor de n: ', each)
print('esse é o valor de n: ', each)
print('esse é o valor de n: ', each)
print('esse é o valor de n: ', each)
pr... |
d20ba95cea567d6d6830ce9312fd30b328f364f6 | DaianaMicena/fiap-exercicios-python | /Exercicios_Python/exercicio10.py | 221 | 3.65625 | 4 | d = float(input('Quanto dinheiro voce tem? '))
conversao = (d / 3.27) * 1.00
conversao1 = (d/6.27) * 1.00
print(f'Com o valor de R$ {round(d,2)} vocë pode comprar USD {round(conversao,2)} ou EUR {round(conversao1,2)}.')
|
9843e8d8c3669c2a7376ec757e183229b7325bf5 | DaianaMicena/fiap-exercicios-python | /Exercicios_Python/exercicio4.6.py | 339 | 3.609375 | 4 | #entrada
altura = float(input("Informe sua altura"))
sexo = input("Informe seu sexo")
#processamento
if sexo.lower() == 'm':
peso_ideal = (72.7 * altura) - 58
elif sexo.lower() == 'f':
peso_ideal = (62.1 * altura) - 44.7
else:
peso_ideal = 0
print("Sexo nao reconhecido")
print (f"Seu peso ideal é {round... |
1ab26d5a0aeeb439b2302bae327ad916ae46f095 | DaianaMicena/fiap-exercicios-python | /Exercicios_Python/exercicio32.py | 206 | 3.71875 | 4 | ano = int(input('Digite um ano'))
if ano % 4 ==0 and ano % 100 != 0 or ano % 400 == 0:
print(f'O ano \033[33;m{ano}\033[m é bissexto.')
else:
print(f'O ano \033[33;m{ano}\033[m nao é bissexto.') |
4512b1f073b3fd7b3f7b1fd6d50c6736d3fed1d7 | DaianaMicena/fiap-exercicios-python | /Exercicios_Python/exercicio38.py | 347 | 4.0625 | 4 | num = int(input('Digite um numero. '))
num2 = int(input('Digite um numero. '))
if num > num2:
print(f'O PRIMEIRO numero \033[33m {num}\033[m é maior que o numero {num2}. ')
elif num2 > num:
print(f'O SEGUNDO numero \033[33m {num2}\033[m é maior que o numero {num}. ')
else:
print('Nao existe valor maior, os... |
fcda3012b054df34715aaaf2e4043f544f6c195b | DaianaMicena/fiap-exercicios-python | /Exercicios_Python/exercicio58.1.py | 383 | 3.875 | 4 | from random import randint
from time import sleep
tentativa = 1
print('Vou pensar em um numero, tente adivinhar...')
sorteio = (randint(0,10))
digite = int(input('Digite um numero '))
#print('PROCESSANDO...')
#sleep(5)
while digite != sorteio:
digite = int(input('Errado! Tente novamente: '))
tentativa += 1... |
8812c81766edf440898d82b180ee525a5c1132e7 | DaianaMicena/fiap-exercicios-python | /Exercicios_Python/exercicio13.py | 237 | 3.78125 | 4 | nome = input('informe o nome do funcionario ')
salario = float(input(f'informe o salario do {nome} R$ '))
reajuste = salario * 0.15
salarioatual = salario + reajuste
print(f'O salario atualizado do {nome} é R$ {round(salarioatual,2)}')
|
89857b64feb432153dde176e3d250bb78b26d499 | DaianaMicena/fiap-exercicios-python | /Exercicios_Python/exercicio12.py | 270 | 3.78125 | 4 | produto = input('Informe o nome do produto ')
valor = float(input('Informe o valor do produto R$ '))
desc = (valor * 0.05)
valdes = (valor - desc)
#per=float(desc)*(100/5)
print(f'O valor do {produto} é R$ {round(valor,2)} com desconto ficou em R$ {round(valdes,2)}.')
|
a128b92cef789af10a9db271d20c40aaab60fcbd | DaianaMicena/fiap-exercicios-python | /Exercicios_Python/exercicio31.py | 377 | 3.671875 | 4 | trecho = float(input('\033[34;mInforme a distancia da viagem:\033[m'))
valor = trecho * 0.50
valor2 = trecho * 0.45
#if trecho <=200:
# print(f'O valor a pagar é R$ {valor} ')
#else:
# print(f'O valor a pagar é R$ {valor2}')
#Forma mais rapida de fazer:
preço = trecho *0.50 if trecho <=200 else trecho * 0.45... |
8fab139a747fffd35f7b49ba2df5516433cf5bd4 | DaianaMicena/fiap-exercicios-python | /Exercicios_Python/exercicio6.10.py | 626 | 4 | 4 | #entrada
idade = int(input("Informe a idade"))
#processamento
if idade >= 5 and idade <= 7:
print(f"Criancas com idade de {idade} anos fara parte da categoria Infantil A")
elif idade >= 8 and idade <= 11:
print(f"Criancas com idade de {idade} anos fara parte da categoria Infantil B")
elif idade >=12 and idade <... |
e80746b792ff29ce2731dba4e50ef558a2c1fafe | DaianaMicena/fiap-exercicios-python | /Exercicios_Python/exercicio8.4.py | 154 | 3.859375 | 4 | vetor = []
for n in range (0,5):
num = int(input(f"Digite um numero {n+1} / 5: "))
vetor.append(num)
print(f"A soma do vetor é {(sum(vetor))}") |
04e73d38d19d3d1a7a60a9774fd735c09a791069 | DaianaMicena/fiap-exercicios-python | /Exercicios_Python/exercicio72.py | 426 | 4 | 4 | escolha = 0
num = ('zero', 'um', 'dois', 'tres', 'quatro', 'cinco', 'seis', 'sete', 'oito', 'nove', 'dez', 'onze', 'doze', 'treze',
'catorze', 'quinze', 'dezesseis', 'dezessete', 'dezoito', 'dezenove', 'vinte')
while True:
escolha = int(input(' Digite um numero de 0 a 20: '))
if 0 <= escolha <= 20:
... |
bcacc4ac98a353bda2edc1844466564175be70f5 | Samtec-ASH/pyrpiic | /pyrpiic/clock/utils.py | 993 | 3.765625 | 4 | import math
def float2frac(x, error=1e-9):
''' float to fraction (numerator / denominator). '''
n = int(math.floor(x))
x -= n
if x < error:
return (n, 1)
if 1 - error < x:
return (n+1, 1)
# The lower fraction is 0/1
lower_n = 0
lower_d = 1
# The upper fraction is 1... |
8fb4b29a2debbe8f92cc976a7c61eff4824beb9b | hagifoo/learn | /oop-exercise/after/client.py | 1,906 | 3.671875 | 4 | from vending_machine import VendingMachine
from currency import Yen100Coin
from currency import Yen500Coin
from drink import Coke
from drink import DietCoke
from payment import Payment
if __name__ == '__main__':
print('# 200円を入れて 0: COKE を購入')
payment = Payment([Yen100Coin(), Yen100Coin()])
drink_type = C... |
62376c620bb57c97c33e8adb55763d37e87a865d | joelbiffin/otb-test | /src/directed_graph.py | 4,110 | 3.59375 | 4 | from typing import *
class DirectedGraphHandler(object):
def __init__(self, user_input: str):
"""
Initialises empty directed graph, builds graph from user input string.
:param user_input: string representation of jobs and their dependencies
"""
self.graph = {}
inp... |
e4a30ba3187968dd889aea1d639641bb4fbe8fdf | my-workspace/AI-Programming-using-Python | /Search/npuzzle.py | 3,813 | 3.609375 | 4 | import math
import matplotlib.pyplot as plt
class NPuzzleState:
def __init__(self, N=8, tiles=None):
if tiles is None:
self.tiles = tuple(range(N + 1)) # [0, 1, 2, ..., N] and 0 is blank
else:
N = len(tiles) - 1
self.tiles = tuple(tiles[:])
... |
277b72a614fdb18062d129259c0fe07f64626922 | Hanaasagi/imouto | /imouto/utils.py | 4,560 | 3.5625 | 4 | import re
import urllib.parse
from string import ascii_letters, digits
from typing import Mapping
"""Some utility functions and classes"""
def url_encode(value, plus=True):
"""urlencode
if plus is True ' ' will convert to '+'
otherwise ' ' will convert to '%20'
>>> url_encode('www.google.com.hk/#saf... |
688ef5b09d0ff5ff5b86345d46754cfc73a79c8c | anubhab-code/HackerRank | /Problem Solving/Algorithms/Strings/HackerRank in a String!.py | 272 | 3.546875 | 4 | str = 'hackerrank'
t = int(input())
for i in range(t):
test = input()
count = 0
for j in test:
if(count < len(str)):
if j == str[count]:
count+=1
if count == len(str):
print('YES')
else:
print('NO') |
e32f295fdc40478a1df7eaec2b74fda86579f0b7 | anubhab-code/HackerRank | /Problem Solving/Algorithms/Sorting/Quicksort 1 - Partition.py | 174 | 3.609375 | 4 | num = input()
pivot, *ar = input().split()
left = [x for x in ar if int(x) <= int(pivot)]
right = [x for x in ar if int(x) > int(pivot)]
print(" ".join(left+[pivot]+right)) |
326f41a566e004af79ab741042d8f0d38832c890 | anubhab-code/HackerRank | /Problem Solving/Algorithms/Strings/Funny String.py | 421 | 3.765625 | 4 | def isFunnyString(string):
result = 'Funny'
l = len(string)-1
for i in range(int(len(string)/2+1)):
if abs((ord(string[i+1]) - ord(string[i]))) != abs((ord(string[l-i-1]) - ord(string[l-i]))):
result = 'Not Funny'
break
return result
num = int(input())
strings = []
for i... |
ada352a1aa90acd700c4fe66181ffebc5d8a3517 | gibinaghi/cursods | /Guía 1/ejercicio11.py | 497 | 4 | 4 | '''
Crear un programa que almacene la cadena de caracteres contraseña en una variable,
pregunte al usuario por la contraseña e imprima por pantalla si la contraseña
introducida por el usuario coincide con la guardada en la variable.
'''
contrasena = 12568996
contrasena_ingresada = int(input("Ingrese su contraseña: ")... |
f320603ef51d82d3e0f7ae8d6f2a6518b798a707 | RIT-Dubai/assignment-1-Erg3048 | /main.py | 3,131 | 4.03125 | 4 | import turtle as t
XMAX = 200 #Defined constants as global variables
XMIN = -XMAX
YMAX = 200
YMIN = -YMAX
PI = 3.1415926535
def grid(): #Defined grid using max and min constants
t.penup()
t.goto(XMIN, YMAX)
t.pendown()
for i in range(4):
t.forward(400)
t.... |
5c30a3093ad4fca9ef738d7901f659eff9698700 | ase1590/python-spaghetti | /divide.py | 254 | 4.1875 | 4 | import time
print('divide two numbers')
# get the user to enter in some integers
x=int(input('enter first number: '))
y=int(input('enter number to divide by: '))
print('the answer is: ',int(x/y)),
time.sleep(3) #delay of a few seconds before closing
|
a66f497cd03bbcf1f5ba39fb38179f769cfefb3c | cadtexas/fa17-intro-to-python | /In-class exercises/ExercisesWeek4.py | 2,382 | 4.0625 | 4 | # write a program that takes in letter grades
# and converts to find an average numerical grade
# counter-controlled
'''
# initialize variables (count, total)
count = 0
total = 0
numGrades = eval(input("How many grades would you like to enter? "))
print()
while count < numGrades:
# use this line in yo... |
179ed135585c5355014aec223179c2bb33c487e7 | Rose-Lin/Konane_Checkers | /util.py | 232 | 3.5 | 4 | class Queue:
def __init__(self):
self.list = []
def push(self, item):
self.list.insert(0, item)
def pop(self):
return self.list.pop()
def isEmpty(self):
return len(self.list) == 0
|
f387dde859fc77dcd2cb6584d1c512c8312c9d9e | purcellconsult/tlg_learning_python | /07_22_20/bright.py | 619 | 4 | 4 |
# nested if statement
answer = 'bright'
print('Finish this sentence. Always look on the __ side of life.')
uanswer = input('Complete the phrase ')
if uanswer == answer:
print('That is correct!')
else:
print('2 tries left. Guess again. ')
uanswer = input('Complete the phrase ')
if uanswer == answer:
... |
616a87c9b2a71fd85738fb2ba652a1666c532ea7 | Dimosphen1/PythonGTK | /10_text_styling.py | 4,140 | 3.609375 | 4 | import gi
gi.require_version("Gtk", "3.0")
from gi.repository import Gtk
# here we will create a program which has one horizontal box and three vertical boxes inside
# of the horizontal one
class MyWindow(Gtk.Window):
def __init__(self):
Gtk.Window.__init__(self, title="Text styles")
self.set_bor... |
d337aaf545f5407409682a4f7056383dbcc14b73 | Dimosphen1/PythonGTK | /11_user_input.py | 1,844 | 3.796875 | 4 | import gi
gi.require_version("Gtk", "3.0")
from gi.repository import Gtk
# here we will work with user input, get data from there and use it further
class MyWindow(Gtk.Window):
def __init__(self):
Gtk.Window.__init__(self, title="User Input")
self.set_border_width(10)
self.set_size_reques... |
18ae2d6986dcf78b504954483e648361cfbccca6 | mattsutton41/Agent-Based-Systems | /CS404 ABS/Code2020 - Student Version/bots/u1604990_2.py | 7,090 | 3.53125 | 4 | import numpy as np
import random
import math
class Bot(object):
def __init__(self):
self.name = "1604990_2"# Put your id number her. String or integer will both work
#akash = '1602498'
#if(akash in bots_in_room):
# alpha = 1
# Add your own variables here, if yo... |
cd607ae14d83626cb1994e489e96f4a9131732fc | uccser/cs-field-guide | /csfieldguide/tests/utils/errors/test_MissingRequiredFieldError.py | 2,081 | 3.59375 | 4 | """Test class for MissingRequiredFieldError error."""
from django.test import SimpleTestCase
from utils.errors.MissingRequiredFieldError import MissingRequiredFieldError
class MissingRequiredFieldErrorTest(SimpleTestCase):
"""Test class for MissingRequiredFieldError error.
Note: Tests to check if these were... |
17df52f4d8c098d9a98f2d833b9f8bca1474cff5 | hipiphock/Deep-Learning | /practice3/test.py | 2,909 | 3.5625 | 4 | # task3.py
import numpy as np
import random
import time
## INITIALIZATION
TRAIN_NUM = 1000
TEST_NUM = 100
alpha = 0.003 # learning rate
# initialize the variable
W1 = np.array([[0, 0], [0, 0], [0, 0]])
W2 = np.array([0, 0, 0])
B1 = np.array([0, 0, 0])
B2 = 0
# generate random data
def generate_data(size):
X = ... |
06a9eac91f8c7b3d7a127acd395aa96a97d723ef | syw2014/semi-supervised-algo | /algos/1.LP/1_label_propagation.py | 4,725 | 3.734375 | 4 | #!/usr/bin/env python
# -*- encoding: UTF-8 -*-
# Author: Jerry.Shi
# Date: 2017-10-16
# Description:
# Label propagation is a semi-supervised learning algorithms, we can be used to find data with labels,and expand labeled data.
# reference: http://pages.cs.wisc.edu/~jerryzhu/pub/thesis.pdf
import numpy as np
imp... |
a00dcd360a221db6aa1aed1df02ecf7baf8cb221 | gitmohitshinde/SVM-Classification-for-Heart-Disease-Prediction- | /svm.py | 1,470 | 3.546875 | 4 | #Import the Libraries
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
#Import the Dataset
Dataset = pd.read_csv("heart_disease_dataset.csv")
X = Dataset.iloc[:,:-1].values
y = Dataset.iloc[:, -1].values
#Feature scaling the independent variable
from sklearn.preprocessing import StandardScaler
... |
009de8faffad6fca4b074dd86cb5f04c81aa75cd | wsabin19/375_CS | /chapter 01/SquareRoot.py | 255 | 4.03125 | 4 | #This progrm does math
import math
def main():
print("Calculate how long it will take")
speed = eval(input("How Fast are you going?(m/s)"))
distance = eval(input("How far will you go?(m)"))
time = distance/speed
print(time)
main()
|
8371e594038975d396f276f91cd3cb285487bdd0 | nathanriojas/CrackingCodingInterview | /Chapter3Stacks/3_5StackSort.py | 2,003 | 3.8125 | 4 | # Cracking the coding interview problem 3.5 - Sort a stack, use of temporary
# stack (I am using two temporary stacks) allowed. Cannot store in any other data structure.
# Only push, pop, peek, and isEmpty are available
# Implementation of Stack Class
class Stack (object):
def __init__ (self):
self.stack = []
... |
a95c4e3ddaea9a017af669c3dc6fb59889ddcd02 | nathanriojas/CrackingCodingInterview | /Chapter3Stacks/3_4MyQueue.py | 3,311 | 4.1875 | 4 | # Cracking the coding interview problem 3.4
# Implement a queue, MyQueue class using two stacks
# Implementation of Stack Class
class Stack (object):
def __init__ (self):
self.stack = []
def push (self, item):
self.stack.insert (0, item )
def pop (self):
return self.stack.pop(0)
def peek (self)... |
2ea33fda5f2b25b012a720157228d7e2e092f120 | AllisonKuhl/hist4006-cluny-final-project | /code/monk-simulator/monkSimulator2.0/objects.py | 2,566 | 3.671875 | 4 | from random import randint
class Object():
def __init__(self, name, init, description, action):
self.name = name
self.init = init
self.description = description
self.action = action
def use(self,player, time):
self.action(player, time)
def eat(player, time):
print("You look around furtively to see... |
b6acffcf6f5961952452fb366ea71971b9ffdac8 | AllisonKuhl/hist4006-cluny-final-project | /code/monk-simulator/monkSimulator2.0/roomClass.py | 1,743 | 3.625 | 4 | from activityClass import Activity
class Room():
def __init__(self, name, description):
self.name = name
self.description = description
self.north = None
self.east = None
self.south = None
self.west = None
self.stairs = None
self.people = []
self.objects = []
self.activity = ""
self.certainTime... |
5cfd561fc32a028223208019bde4c60736e786a5 | ndvssankar/ClassOf2021 | /Operating Systems/WebServer/test_pipe.py | 1,316 | 4.3125 | 4 | # Python program to explain os.pipe() method
# importing os module
import os
import sys
# Create a pipe
pr, cw = os.pipe()
cr, pw = os.pipe()
stdin = sys.stdin.fileno() # usually 0
stdout = sys.stdout.fileno() # usually 1
# The returned file descriptor r and w
# can be used for reading and
# writing re... |
5a16872a0a29492826468f66deec99c4293513f8 | brendansailer/Advent-Of-Code-2020 | /day13/program1.py | 550 | 3.796875 | 4 | #!/usr/bin/env python3
import sys
import math
def calculate_time():
time = int(sys.stdin.readline())
busses = [int(bus) for bus in sys.stdin.readline().split(',') if bus != 'x']
closest_bus_id = 0
time_waiting = float('inf')
for bus in busses:
departure = math.ceil(time/bus)*bus
i... |
90c3f40abecc49bb4622dfb230fd1f67c7737a57 | brendansailer/Advent-Of-Code-2020 | /day12/program2.py | 1,111 | 3.90625 | 4 | #!/usr/bin/env python3
import re
DIRECTION_RE = r'([A-Z])(\d+)'
def read_input(file_name):
return [line.strip() for line in open(file_name, 'r')]
def move_ferry(action, distance, x, y, wx, wy):
if action == 'N':
wy += distance
elif action == 'S':
wy -= distance
elif action == 'E':
... |
b2172a7076a94fd50f1545c849332fc7b11988ae | brendansailer/Advent-Of-Code-2020 | /day16/program1.py | 1,103 | 3.703125 | 4 | #!/usr/bin/env python3
import sys
import re
TICKET_RE = r'.*: (\d+-\d+) or (\d+-\d+)'
def read_input():
fields, nearby_tickets = [], []
line = sys.stdin.readline().strip()
while line != '':
field1, field2 = re.findall(TICKET_RE, line)[0]
fields.append(field1)
fields.append(field2... |
72fb7bd14bdd82afc675a9bd80629c0e6cfaff3b | brendansailer/Advent-Of-Code-2020 | /day19/program1_old.py | 2,230 | 3.515625 | 4 | #!/usr/bin/env python3
import sys
def get_rules():
rules = {}
canidates = []
for line in sys.stdin:
if ':' in line:
rule_number, requirements = line.strip().split(':')
requirements = requirements.strip().split('|')
if len(requirements) == 2: # x y | a b
... |
1cbf22789a38066e9ce8690e652ba3fdf4cfc0fc | likes2addfunctions/CodeSamples | /MachineLearningAlgs/Grad Descent Multi Var.py | 2,537 | 3.921875 | 4 | ### This is a tool to perform gradient descent on multiple variables.
# Based on Andrew Ng's Machine Learning course at Stanford.
# It currently generates a pseudo random input, then runs the algorithm
# and provides a hypothesis as well as a visualization of convergence.
import random
import numpy
import matplotlib.p... |
6e2a320b1cf178caf81248050e0184467c000675 | Minaksh1012/If_else_python | /questions.py/loop/if else.py/maximum number.py | 287 | 4.15625 | 4 | num1=int(input("enter the number"))
num2=int(input("enter the number"))
num3=int(input("enter the numbers"))
if num1>num2>num3:
print("num1 is gratest number",num1)
elif num2>num1>num3:
print("num2 is greatest number",num2)
else:
print("num3 is greatest number",num3) |
bfafa045df5c449cac9b43b3ab66c0bda07ba5a2 | Minaksh1012/If_else_python | /alphabet digit special character.py | 234 | 4.25 | 4 | ch=input("enter the character")
if (ch>='a'and ch<='z') or (ch>='A'and ch<='Z'):
print("these character is alphabet")
elif ch>='0'and ch<='9':
print("these character is digit")
else:
print("these is special character") |
dd5e0364f9de2e31b4f066f9acc9371da1d32e7e | Minaksh1012/If_else_python | /hackthon-nested-if else.py/facebook front page.py | 691 | 3.609375 | 4 | print("FACEBOOK FRONT PAGE")
language=input("enter the language")
ch=input("enter the anyone name ")
email_id=(input("enter the email id"))
password=input("enter the password")
gender=input("enter the gender")
if language=="english"or"hindi"or"marathi":
if ch>="a" and ch<="z":
if email_id=="ch@gmail.com":
... |
aa67603758a933bf7f9a7800d4f287e288b22ae2 | dmgig/algorithms | /week2_algorithmic_warmup/1_fibonacci_fast.py | 382 | 3.90625 | 4 | # Uses python3
import sys
import random
def fibonacci_number_fast(n):
if n == 0:
return 0
if n == 1:
return 1
store = [0,1]
for j in range(2, n+1):
store.append(store[len(store)-2] + store[len(store)-1])
return store.pop()
if __name__ == '__main__':
input = sys.stdin.r... |
1701010b9e13eb512e4617da84c11f1424994311 | MarcusDMelv/chatbot_practice | /nltk/text and words/text_as_list_of_words.py | 3,874 | 4.0625 | 4 | # download and run the books (start here)
"""
import nltk
nltk.download()
from nltk.book import *
"""
from nltk.book import *
from text_and_words import lexical_diversity
# Creating a list
list1 = ["call", "me", "Marcus", "."]
len(list1)
list2 = ['I', "am", "tired", "of", "working"]
len(list2)
# imported function t... |
fb4312f6c3dd76744cc80097468080757316c283 | Muffinous/DAA | /Abraham/kSmallestElement.py | 450 | 3.796875 | 4 | #k es una posicion, da todos los que son mayores y menores que el
def kthSmallestElement(k, elements):
mid = len(elements) // 2
pivot = elements[mid]
def median(elements):
ordinal = (len(elements) + 1) // 2
return kthSmallestElement(ordinal -1, elements)
def test():
print("Testing... ", end="")
v... |
f9f7e8968a4b02fb6962d127e4be24411f9e4e85 | Muffinous/DAA | /BACKTRAKING/initbattle.py | 1,044 | 3.515625 | 4 | def isFeasible(b, r, c):
feasible = True
i = 1
while feasible and i <= r:
columnFUp = b[r - i] != c
diagonalFRUp = b[r - i] != c - i
diagonalFLUp = b[r - i] != c + i
feasible = columnFUp and diagonalFRUp and diagonalFLUp
i += 1
return feasible
def initbattle(b, ... |
9698bb583caa6dbcbea6269e2284cd318319a3cb | profiterol81/erol-kazancli | /Individual Projects/MedianSearchAlgorithms - Python/CalculateTimeAndMedian.py | 1,133 | 3.515625 | 4 | import QuickSort
import RMedian
import QuickSelect
import time
import math
def calculate(numbers):
numbers1 = list(numbers)
start = time.time()
median_quick_sort = QuickSort.quick_sort_median(numbers1)
end = time.time()
quick_sort_elapsed = end - start
numbers2 = list(numbers)
start = ti... |
ee40eb03fc927ed1f87b94022b08554629d70c05 | tiroring09/Study | /Python_DataStructure_and_Algorithm/1장_숫자/9_find_fibonacci_by_generetor.py | 348 | 3.921875 | 4 | """ using generator(sequence in java) to get fibonacci sequence """
# 신기한 사용법이네
def fibonacci_generator():
a, b = 0, 1
while True:
yield b
a, b = b, a + b
if __name__ == "__main__":
target_number = 10
fg = fibonacci_generator()
for i in range(target_number):
print(next(fg),... |
1c866f86df99b118d8fd11db891e4d583bd564c4 | chenyao11235/py-wheel | /py核心知识/面向对象/类变量/main.py | 577 | 3.84375 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2020/5/15 14:38
# @Author : chenyao
'''类变量和实例变量
类变量保存在类的命名空间中,
通过类修改类变量的值,会影响所有的实例
通过实例子修改类变量的值,只会影响该实例,不会影响其他的实例
'''
class A:
aa = 1
def __init__(self, x, y):
self.x = x
self.y = y
if __name__ == "__main__":
a... |
401ce4682507daad5f48d776f832f466fbbd910f | dkavaler/cracking_the_coding_interview | /chapter1/1.2.py | 850 | 3.515625 | 4 | from collections import defaultdict
TEST_STRINGS = [('kjjkll', 'kkjjll'), ('dkaj', 'jkad',),
('abcde', 'edcba'), ('eeaee', 'aaeaa'),
('defg', 'gfde'), ('akjd', 'buif')]
CORRECT_RESULTS = [True, True, True, False, True, False]
# O(len(string1) + len(string2)) using hash table
def is_permutation(st... |
301808ef3fcc7e9d584c34cfa969fe649264c57e | dkavaler/cracking_the_coding_interview | /chapter4/4.2.py | 653 | 3.59375 | 4 | from node import Node
# Recursive method (much faster)
def create_bst(arr):
return _create_bst(arr, 0, len(arr) - 1)
def _create_bst(arr, start, end):
if end < start:
return None
mid_point = (start + end) // 2
mid_node = Node(data=arr[mid_point])
left_node = _create_bst(arr, start, mid_po... |
be7826854b62a1c8a6fe2df985b12b48fe548572 | YairAmar/Coursera_ML_intro | /ex3/neuralnet/neural_net.py | 619 | 3.59375 | 4 | import sys
import numpy as np
from neuralnet.trainer_nn import forward
from neuralnet.nn_utils import load_nn_weights
class NeuralNet:
def __init__(self):
"""The constructor of the NN-model object"""
self.weights = load_nn_weights(sys.argv[2])
def predict(self, x: np.ndarray) -> np.ndarray:
... |
1127ca5fd62e566e9ae9f823ebb19dc9f8e8820f | YairAmar/Coursera_ML_intro | /ex3/logistic_regression/trainer.py | 2,946 | 4 | 4 | import numpy as np
from utils import sigmoid
def forward(theta: np.ndarray, x: np.ndarray) -> np.ndarray:
"""
computes the hypothesis function
Args:
theta: logistic regression's parameters
x: input data
Returns:
hypothesis: sigmoid function applied over z=x@theta
"""
... |
91c8016997d6b4c3dce7dd0ae0991fcf0a454a7e | Eldersev/LibExcel | /Forca.py | 3,472 | 3.8125 | 4 | import os
class forca:
def __init__(self, secret_word, tips):
self.secret_word = secret_word.upper()
self.secret_word_size = len (secret_word)
self.secret_word_found = ('_'*len(self.secret_word))
self.tips = tips
self.error_count = 0
self.try_quantity = len(self.sec... |
6762b6a9fd444ddba46472d78cfa025f27d06d56 | furball0/algorithms_yandex | /2B_contest_3/C. Уникальные элементы.py | 775 | 3.875 | 4 | # Дан список. Выведите те его элементы, которые встречаются в списке только один раз.
# Элементы нужно выводить в том порядке, в котором они встречаются в списке.
#
# Формат ввода
# Вводится список чисел. Все числа списка находятся на одной строке.
#
# Формат вывода
# Выведите ответ на задачу.
#
lst = list(map(int, in... |
9f942a9334d16e94e353d0e1f63e05fb1d43b47d | furball0/algorithms_yandex | /2B_contest_1/D Строительство Школы.py | 1,991 | 3.5625 | 4 | # В деревне Интернетовка все дома расположены вдоль одной улицы по одну сторону от нее.
# По другую сторону от этой улицы пока ничего нет, но скоро все будет – школы, магазины, кинотеатры и т.д.
#
# Для начала в этой деревне решили построить школу.
# Место для строительства школы решили выбрать так, чтобы суммарное рас... |
bbf302107f2f5875e0ce2a052759544cae9c0755 | youngtailors/pythong | /code/greatest_common_prime_divisor.py | 693 | 3.53125 | 4 | import math
def greatestCommonPrimeDivisor(a, b):
gcd = greatestCommonDivisor(a, b)
if (gcd == 1):
return -1
else:
return greatestCommondPrimeDiv(gcd)
def greatestCommonDivisor(a, b):
if a % b == 0:
return b
else:
return greatestCommonDivisor(b, a % b)
def great... |
564be3d797b4993009205db721f2fb1c1513c820 | koussay-dellai/holbertonschool-higher_level_programming | /0x06-python-classes/3-square.py | 415 | 4.125 | 4 | #!/usr/bin/python3
class Square:
'''defining a sqaure'''
def __init__(self, size=0):
'''initialize an instance'''
self.__size = size
if type(size) is not int:
raise TypeError("size must be an integer")
elif (size < 0):
raise ValueError("size must be >= 0")... |
d2879b65504a58247ba435fa142d475dae3bdd8a | koussay-dellai/holbertonschool-higher_level_programming | /0x04-python-more_data_structures/2-uniq_add.py | 122 | 3.6875 | 4 | #!/usr/bin/python3
def uniq_add(my_list=[]):
s1 = set(my_list)
j = 0
for i in s1:
j += i
return j
|
99f7f46430267a6ee17e0288b14511e3cbef57fc | koussay-dellai/holbertonschool-higher_level_programming | /0x0B-python-input_output/2-read_lines.py | 350 | 4.1875 | 4 | #!/usr/bin/python3
"""
module to print lines of a file
"""
def read_lines(filename="", nb_lines=0):
"""
function to print n lines of a file
"""
number = 0
with open(filename, encoding="UTF8") as f:
for i in f:
number += 1
print(i, end="")
if nb_lines == ... |
c7ecb0001678b96df592df082bbae65c438b5964 | Achinoam11/Reversi | /rules.py | 11,972 | 3.640625 | 4 | from disk import Disk
from board import Board
class Rules:
"""Class that defines all the possible moves, and execute moves"""
"""
def __init__(self, board, color):
self.board = board
self.color = color
self.moves = set()
#def find_2_different(self):
"""
d... |
8f841429c62306e20db1ac9a863cdea4430498a1 | Shreyas-Penkar/Crypto-Chinese | /ASCII_Printer.py | 278 | 3.921875 | 4 |
print("Start limit:")
n=int(input()) #to input start of the ASCII list
print("End Limit:")
e=input() #to input end of the ASCII list
print("\n")
print("NUM ASCII")
while n!=(int(e)+1): #ASCII printer module
print(n,' ',chr(n))
n=n+1
pass |
e50ba1781ffa510bfc0195cdb9b1f3df67fbf2ba | SilviHambardzumyan/EmailSender | /FollowUps.py | 494 | 3.875 | 4 | #python code
email_title = "HW submission"
email_sander = "smnatsakanyan@aua.am"
email_receiver = "anna_alaverdyan2@edu.aua.am"
unsubscribe = 0
email_reply= int (input("Please input the number of replies"))
if (email_reply>=1):
print("You have a reply")
else:
unsubscribe = input("unsubscribe? please type yes or n... |
90be53ee075538378a61b5675783eede8e996596 | surculus12/py-hyphen | /hyphen/trie.py | 705 | 3.90625 | 4 | """
Our trie implementation
"""
_SENTINEL = object()
class Trie(dict):
"A trie"
def __init__(self):
super(Trie, self).__init__()
def insert(self, key, value):
"Inserts a key-value pair into the trie"
trie = self
for char in key:
if char not in trie:
... |
fce2be88790287f25b5d6cf863720bbf172f772c | katealex97/python-programming | /UNIT2/homework/hw-1.py/hw-3.py | 394 | 4.21875 | 4 | odd_strings = ['abba', '111', 'canal', 'level', 'abc', 'racecar',
'123451' , '0.0', 'papa', '-pq-']
count = 0
for string in odd_strings:
#find strings greater than 3 and have same
#first and last character
first = string[0]
last = string[len(string) - 1] #python allows neg. indexes last = string[-1]
... |
770c1bceee9239904be03b4eb59e71ad4ff27339 | liyu10000/playboy | /python/project_02/move_test.py | 1,313 | 3.875 | 4 | def aprint(a):
print("print array:")
for row in a:
print(row)
def transpose(board):
return [list(row) for row in zip(*board)]
def flip(board):
return [row[::-1] for row in board]
def row_move_left(row):
nums = [num for num in row if num > 0]
nums_new = []
j = 0
while j+1 < len(nums):
if nums[j] == nums[j... |
371deac575bfb0172bfe276eb746adb3ab98ceed | zhaoziguangzhaoziguang/first | /神经网络代码/NeuralNetwork.py | 1,070 | 3.859375 | 4 | '''这个程序展现了通过神经元创建了一个神经网络,这里只有前向传播
,没有参数的更新'''
import numpy as np
# 定义一个激活函数
def sigmoid(x):
return 1 / (1 + np.exp(-x))
# 创建一个神经元的类
class Neuron:
def __init__(self, weights, bias):
self.weights = weights
self.bias = bias
# 进行前向传播
def feedforward(self, inputs):
total = np.dot... |
96d36331cb5465ed7ccde451bef776a4efe4c06d | weijie6966/python_final_20DDT19F1077 | /question2.py | 547 | 3.96875 | 4 | class Converter:
def __init__(self,weight,unit):
self.weight=weight
self.unit=unit
def kg_to_pound(self):
pound=self.weight*2.20462
result=str(pound)+" Pound"
return result
def pound_to_kg(self):
kg=self.weight*0.45
result=str(kg)+" KG"
retur... |
667d1f913994df277295d91b81bc9293145eab38 | Chaztikov/python_tutorials | /examples/read_little_endian.py | 1,674 | 3.59375 | 4 | '''
https://stackoverflow.com/questions/46234200/python-read-hex-little-endian-do-math-with-it-and-overwrite-the-result-to-the
you can use the struct library to handle little endian as shown in the doc at https://docs.python.org/3/library/struct.html#struct.pack_into
For your specific task, I don't know if I understo... |
a7c95c2f073cace70374a47fc4febf1b846d821d | gramb0t/Treehouse-Python-Course | /number_game.py | 1,615 | 4 | 4 | import random
def win(secret_num, tries) :
print("YEAH!!! you got it! the secret number was {}".format(secret_num))
print("only took you {} tries!".format(tries))
def too_high() :
print("too high fool")
tries+=1
def too_low() :
print("nope! suckah! too low!")
tries += 1
def game() :
... |
7bc08a22482c10850e1d76e55661e67454dd1e6c | thecipherrr/Assignments | /Modularization/Modul10.py | 359 | 4.03125 | 4 | def pangram_checker(sentence):
alphabets = 'abcdefghijklmnopqrstuvwxyz'
for i in alphabets:
if i not in sentence.lower():
return 'This is not a pangram'
else:
return 'This is a pangram'
print(pangram_checker('the quick brown fox'))
print(pangram_checker('the qui... |
d931b1cdd1bd372ac6c5615b36a6cde12f3d7c20 | thecipherrr/Assignments | /Modularization/Modul4.py | 204 | 3.6875 | 4 | def is_member(val):
a = [1,2,3,4,5]
for i in a:
if val == i:
return True
else:
continue
if val != i:
return False
print(is_member(6)) |
cde77dfa50a8a370bf1c589bc8d262488dc81e29 | thecipherrr/Assignments | /New Project/Number1.py | 488 | 4.25 | 4 | # Main Function
def convert_to_days():
hours = float(input("Enter number of hours:"))
minutes = float(input("Enter number of minutes:"))
seconds = float(input("Enter number of seconds:"))
print("The number of days is:", get_days(hours, minutes, seconds))
# Helper Function
def get_days(hours, mi... |
7ebbde635500dce7e5feb0b16d9a1e7987fdf8b7 | thecipherrr/Assignments | /New Project/Number3.py | 240 | 3.640625 | 4 | # Atoms calculator
def num_atoms(element_mass, atomic_weight = 196.97):
avogadro = 6.022 * 10**23
return (element_mass / atomic_weight) * avogadro
print(num_atoms(10))
print(num_atoms(10, 12.001))
print(num_atoms(10, 1.008)) |
2fa81f92c862a8bd0a156fb3c76bc32712ae6ce5 | thecipherrr/Assignments | /Modularization/Modul11.py | 290 | 4.09375 | 4 | def char_freq(string):
freq_counter = {}
for i in string:
if i in freq_counter:
freq_counter[i] += 1
else:
freq_counter[i] = 1
return freq_counter
print('Character frequency for this string is:')
print(char_freq('apple'))
|
b87ec377efc1b63cc4c1260afe0cd6a09fc1c5df | shivani-Surusani/Music-Recommender-System | /src/python/songVectors.py | 823 | 3.53125 | 4 | class svError(Exception): pass
class dictError(svError): pass
class listError(svError): pass
class lengthError(svError): pass
def featureVector(s):
if isinstance(s,dict):
raise dictError, "input must not be a dictionary"
v = [0,0,0,0] #Sex,Age,Country,Date Joined
if(s[1]=='m'):
v[0]=1
if(s[1]=='f'):
v[0]=-... |
a2c2615509d2987d6f0b21b02953183f553ee200 | Annbeh/RobotStack | /Robot/array_shortest_path.py | 3,645 | 3.765625 | 4 |
from world import *
from array_stack import *
from world import *
from pprint import pprint
world=create_world("world1.txt")
for i in range(0,len(world)):
for j in range(0,len(world[0])):
if(world[i][j]=='g'):
goal=[i,j]
break
goal1=goal[0]
goal2=goal... |
ca8267742c6204dbd69639ac0c0f6fdc8a679f3b | serpherino/Cs-practicals | /14.py | 743 | 3.625 | 4 | queue=[]
def enqueue(element):
queue.append(element)
def dequeue():
try:
return queue.pop(0)
except:
return None
def peep():
try:
return queue[0]
except:
return None
def inputmember():
return list(map(str,input("reg_no, Name,admission_to_class (N... |
5733fc92babf6614afbb445d86d369eb92bbabae | serpherino/Cs-practicals | /8.py | 936 | 3.703125 | 4 | def generatefactors(n):
l=[]
s=int(n**0.5)+1
for i in range(s,0,-1):
if n%i==0:
l.append(i)
n=n//i
return l
def prime(n):
if n==1:
return False
if len(generatefactors(n))==1:
return True
else:
return False
d... |
b03656a4ab0df3901e6300e1bbb0fe65bf937cf3 | mahn14/Kaggle-HousePrice | /preprocessing.py | 5,059 | 3.578125 | 4 | # Dependencies
# Data Processing and Exploration
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
# Statistical Exploration Library
import scipy.stats as stats
from minepy import MINE
# Feature Engineering
from sklearn import preprocessing
from sklearn import decomposition... |
6e113e817483c9ff4ca25c435a448952f87bf28d | shanebaxter101/adventure_game | /adventure_game/rooms/room15.py | 2,634 | 3.734375 | 4 | import adventure_game.my_utils as utils
#ROOM 15
room15_inventory = {
"sword": 1
}
room15_description = '''
. . .Room 15. . .
You descend further down and enter a room with a small layer of water
covering the floor. You see a skeleton lying in the corner of the room
with a *sword* s... |
c1e7e8d1a5b6ebc9ea50f5404a37b7fe344ff6fb | shanebaxter101/adventure_game | /adventure_game/rooms/room6.py | 2,818 | 3.71875 | 4 | import adventure_game.my_utils as utils
#ROOM 6
room6_inventory = {
"coin": 1
}
room6_status = {
"door_locked": 0
}
def run_room(player_inventory):
room6_description = '''
. . .Room 6. . .
You enter a room filled with wooden crates stacked three high,
they all have so... |
f41a12f66c29ab12b3f70cc85544147f31dd7af1 | LivingInSyn/AoC2018 | /5/day5p1.py | 880 | 3.53125 | 4 | def remove_pairs(inputstring):
stringindex = 1
while stringindex < len(inputstring):
letterone = inputstring[stringindex-1]
lettertwo = inputstring[stringindex]
if letterone.lower() == lettertwo.lower():
if letterone.isupper() and lettertwo.islower() or letterone.islower() an... |
2b16e7ee45b487bb09c065ceb882dd4212a8e1b0 | LivingInSyn/AoC2018 | /9/day9p2.py | 3,579 | 3.75 | 4 | class Marble:
def __init__(self, value):
self.value = value
self.left = None
self.right = None
def printline(root, num_marbles):
oline = str(root.value)
cmarble = root.right
for _ in range(0, num_marbles-1):
oline = oline + ' ' + str(cmarble.value)
cmarble = cmar... |
b73006ee1f0b3be4146c950697730bd0c1d5aab7 | eechava6/PythonAlgorithms | /Uncompressed.py | 1,500 | 3.5 | 4 | import re
def searchNum (text):
textList = list(text)
num = re.compile('[1-9][0-9]*')
for i in range(0, len(textList)):
if num.match(textList[i]):
if textList[i+1] and num.match(textList[i+1]):
twoDig = ''.join(textList[i:i+2])
textList.insert... |
1414aef6db7b039b2f065d68376d903c79e7ba3f | seangrogan-archive/datastructures_class | /TP2/BoxClass.py | 1,691 | 4.28125 | 4 | class BoxClass:
"""class for easy box handling"""
def __init__(self, name, width, height):
"""init method"""
self._name = name
self._width = width
self._height = height
self._rotate = False
def __lt__(self, other):
"""for sorting"""
return ... |
d4199bf8e4847e20309d7ee2cf173d1b7e38b785 | seangrogan-archive/datastructures_class | /TP1/Mot.py | 1,423 | 3.515625 | 4 |
import random
class Mot: #class Mot(object):
def __init__(self, cle = None):
# TODO
#random.seed(5)
cleBanque = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z']
if cle == None: #assigns a random key "cle" to the
#Will generate a random word betwe... |
ab8f1d1e8dd1e2c5d82878cf766c81cdd48145c0 | seangrogan-archive/datastructures_class | /weekly_classes/10-FILES AVEC PRIORITIES/SortedListPriorityQueue.py | 2,346 | 4.0625 | 4 | from PriorityQueue import PriorityQueue
#SortedListPriorityQueue
class SortedListPriorityQueue( PriorityQueue ):
#ADT and basic methods
def __init__( self ):
self._Q = []
def __len__( self ):
return len( self._Q )
def __getitem__( self, i ):
return self._Q[i]
def is_emp... |
4a9c364b4e05c1e969e658df12af07959467fe20 | seangrogan-archive/datastructures_class | /weekly_classes/03-OOP/intervalle.py | 2,113 | 3.921875 | 4 | """Classe pour le cours IFT2015
Écrit par Francois Major le 12 janvier 2014.
Cette classe définit un intervalle, soit
l'équivalent du "range" en python.
Comportement :
range( inf ) = 0, 1, ... stop-1
range( inf, sup ) = inf, inf+1, ... sup-1
range( inf, sup, inc ) = inf, inf+... |
31c4f9cfd348ce0f411785c3f38933964b76701e | seangrogan-archive/datastructures_class | /Demo 3/Sorts.py | 2,040 | 4.25 | 4 | def main():
liste = ['B','C','D','A','E','H','G','F']
print(liste)
insert = InsertSort(liste)
print(insert)
merge = MergeSort(liste)
print(merge)
quick = inplace(liste, 0, len(liste) - 1)
print(quick)
def InsertSort(element):
for i in range(len(element)):
j ... |
473c25c8e025b39613aaa37747b857fc6b29020d | seangrogan-archive/datastructures_class | /Listes/ArrayList.py | 1,513 | 3.859375 | 4 | from DynamicArray import DynamicArray
class ArrayList:
#implements the ADT List (List.py)
#uses the DynamicArray class (DynamicArray.py)
def __init__( self ):
self._A = DynamicArray()
def __len__( self ):
return len( self._A )
def __str__( self ):
return str( self._A )
... |
07049d9c8655a2d89200d515fd6f8060e5751f9c | seangrogan-archive/datastructures_class | /code/ArrayHeapPriorityQueue.py | 3,224 | 3.9375 | 4 | """Code Python pour le cours IFT2015
Mise à jour par François Major le 23 mars 2014.
"""
from PriorityQueue import PriorityQueue
#ArrayHeapPriorityQueue
class ArrayHeapPriorityQueue( PriorityQueue ):
def __init__( self ):
self._Q = []
def __len__( self ):
return len( self._Q )
def __... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.