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 |
|---|---|---|---|---|---|---|
c05f369e874662f1f383cd25148e99c980f37d49 | Vohsty/password-locker | /user.py | 1,472 | 4.21875 | 4 | class User:
"""
Class to generate new instances of users
"""
user_list= [] # Empty user list
def __init__(self, f_name, l_name, username, password):
'''
To take user input to create a new user
'''
self.f_name = f_name
self.l_name = l_name
self.usernam... |
173a5caac24fd52fd3dc4bdd32339cf928d6e0ac | saji021198/incomplete | /rockpaper.py | 257 | 3.734375 | 4 | lo,mo=(map(str,input().split()))
if(lo=='R' and mo=='P') or (lo=='P' and mo=='R'):
print("P")
elif(lo=='R' and mo=='S' or lo=='S' and mo=='R'):
print("R")
elif(lo=='S' and mo=='P' or lo=='P' and mo=='S'):
print("S")
elif(lo==mo):
print("D")
|
26b2febe6b3967e58a4722ca12c4b2f4fd27cad2 | KatherineCG/Algorithm | /不用加减乘除做加法.py | 302 | 3.75 | 4 | class Solution:
def Add(self, num1, num2):
if num2 == 0:
return num1
while num2 != 0:
sum = num1 ^ num2
carry = (num1 & num2) << 1
num1 = sum
num2 = carry
return sum
test = Solution()
print test.Add(2,0) |
b5d377c5db1f765135f6458caf32bef32c104c3d | JanusDG/Homework_0_2nd_term | /project/build/lib/modules/comments_genre.py | 4,260 | 3.609375 | 4 | import matplotlib.pyplot as pyplot
from matplotlib import style
from modules.dict_atd import Dictionary
from modules.dict_usage import in_file, get_data_from_URL
url = 'https://api.deezer.com/genre'
def add_to_dict(d, text):
""" (Dictionary, str) -> NoneType
Add to the dictionary all words of this te... |
de2f0f1192f9937e4e4580bd76855a08e9237a8a | startup-systems/time-grading | /reader.py | 562 | 3.5 | 4 | import urllib2
import csv
def fetch(net_id):
"""Returns the URL, the response, and the corresponding score."""
website = 'https://' + net_id + '-time.herokuapp.com'
try:
response = urllib2.urlopen(website).read()
except urllib2.HTTPError:
response = None
return website, response
... |
06e7e424ff0f49afb45eabafca263d60df433274 | delucks/scripts | /occurances.py | 4,898 | 3.8125 | 4 | #!/usr/bin/env python3
'''<whatever> | ./occurances.py [options] [<method>] [<input>] [<output>]
perform basic statistics on input
like "sort | uniq -c | sort -nr" by default
doesn't do any column selection, this is for use in a pipe silly
Methods:
count: unique line count of the input (default)
percentage: uniqu... |
363822a43d42ad63432023d080d6855253c3bb43 | mwvuyk/Expressiebomen | /input.py | 4,084 | 3.953125 | 4 | from Expressiebomen import *
import traceback
trees = {}
helpstr = {"new" : "Create a new tree from an expression. Syntax: new <name> <expression>.",
"simplify" : "Simplify a tree to a new tree. Syntax: simplify <name> <new name>.",
"diff" : "Differentiate by a variable from a tree ... |
1ad951f3a7286ddad93b9864e58f5a6dda77412f | Niteshnupur/greyatom-python-for-data-science | /Nitesh-Bhosle-SPY-GAMES/code.py | 5,496 | 4.21875 | 4 | # --------------
##File path for the file
file_path
print(file_path)
def read_file(path):
# Opens the file associated with the 'path' in the read-only mode ('r') and store it in a variable file
file = open(path, "r")
# Reads the content(first line) of the file and stores it in a variable called 's... |
681e5c2683048d4c03b44f21c6453856caba6d7e | noabak/UnitConverter | /main.py | 425 | 3.875 | 4 | print(" *** Bienvenido al conversor de kms a millas ***")
kilometros=0
millas=0
repetir= True
while repetir== True:
kilometros= int(input("Por favor introducir la cantidad en Kilómetros:"))
print(kilometros,"km = ",kilometros*0.621371,"millas")
rep= input("Desea convertir otra cantidad?, escribir 'Y' o 'N'... |
19b7f3ec659486cc7d8a15057abd8edab2f9eada | DiegoDeJotaWeb/uninove | /5 - LÓGICA DE PROGRAMAÇÃO/aula_05-06-2020/exer2.py | 376 | 3.640625 | 4 | n1=float(input("Diegite a primeira nota"))
n2=float(input("Diegite a segunda nota"))
n3=float(input("Diegite a terceira nota"))
n4=float(input("Diegite a quarta nota"))
media=(n1+n2+n3+n4)/4
if(media >= 7):
print("Sua média é {:.2f}. Você esta aprovado!".format(media))
else:
print("Sua média é {:.2f}. Você es... |
f8ebe9757272796c0b59f3546009d39492af63ae | DiegoDeJotaWeb/uninove | /5 - LÓGICA DE PROGRAMAÇÃO/aula_12-06-2020/exer.py | 354 | 3.75 | 4 | qtdi = 0
qtdf=0
for cont in range (1,11):
nun = int(input("digite um numero inteiro"))
if(num > 15 and num < 35):
qtdi = qtdi+1
else:
qtdf=qtdf+1
input("fim")
print("O total de números que estão entre 15 e 35 é {}".format(qtdi))
print("O total de números que estão fora do intervalo entre ... |
20294cc862db3bf2318757d1027ab27ecd109ce9 | DiegoDeJotaWeb/uninove | /5 - LÓGICA DE PROGRAMAÇÃO/aula_29-05-2020/exer5.py | 289 | 3.859375 | 4 | n1=float(input("Digite um numero que sofrerá acréscimo de 30%:"))
n2=float(input("Digite um numero que sofrerá desconto de 25% :"))
acrescimo=n1*1.30
desconto=0.75*n2
print("O valor com acréscimo é {:.2f}".format(acrescimo))
print("O valor com desconto é {:.2f}".format(desconto))
|
72d89fa9093ed5d9629c86480309380b87d871a2 | DiegoDeJotaWeb/uninove | /5 - LÓGICA DE PROGRAMAÇÃO/aula_05-06-2020/exer8.py | 394 | 4.125 | 4 | '''Para doar sangue é necessário ter entre 18 e 67 anos.
Faça um programa que pergunte a idade de uma
pessoa e diga se ela pode doar sangue ou não.'''
idade=int(input("Digite sua idade"))
if(idade >= 18 and idade <=67):
print("Sua idade é {}. Você pode doar sangue!".format(idade))
else:
print("Sua idade é {}... |
dbdd593e243472d35ceb76ea694f20e96ffca9fc | chnbin/CodeSnippet | /Leetcode/others/permutation.py | 404 | 3.953125 | 4 | def permutationHelper(nums, start, end, ans):
if (start == end):
ans.append(list(nums))
else:
for i in range(start, end):
nums[i], nums[start] = nums[start], nums[i]
permutationHelper(nums, start + 1, end, ans)
nums[i], nums[start] = nums[start], nums[i]
def permutation(nums, ans):
perm... |
9af1fdec1e337ac23ec66f1a16b528e327c0ce7b | Hithul/Python-Internship-30-Days-30-Hour- | /Day4/Day4.py | 216 | 3.796875 | 4 | #TASK1
A = [10,20,30,40,50]
A.insert(5,60)
print(A)
A.remove(50)
print(A)
lar = max(A)
print(lar)
small = min(A)
print(small)
#TASK2
B=(1,2,3,4,5)
print(B[::-1])
#TASK3
B = list(B)
print(B) |
c71efbffecfc283b119d827dbc78611f375406c4 | AlmDiana/Matrices-Numpy | /Codigo/main.py | 1,119 | 3.8125 | 4 | import numpy as np
print ("<< MULTIPLICACION DE MATRICES >>\n")
print ("MATRIZ 1:")
f_mat_1 = int(input("Número de filas: "))
c_mat_1 = int(input("Número de columnas: "))
print ("\nMATRIZ 2:")
f_mat_2 = int(input("Número de filas: "))
c_mat_2 = int(input("Número de columnas: "))
while (c_mat_1 != f_mat_... |
3f6e66a5e45651ee7fe6dd0454f771b6343edc29 | davidjbrossard/python | /hello.py | 669 | 4.3125 | 4 | import math as m
"""
This method takes in a string and returns another string. It encrypts the content of the string by using the Caesar cipher.
"""
def encrypt(message, offset):
encryptedString = "";
for a in message:
encryptedString+=chr(ord(a)+offset);
return encryptedString;
"""
This method ta... |
2ffebae5d22d4a20af8c6c234199e8ef28f8f72d | nathancfox/toy-projects | /secure_comm_demo.py | 10,780 | 4.25 | 4 | import textwrap as tw
def print_intro():
title = ('\nSecure Communication on Unsecured Lines Between Strangers\n'
+ '-----------------------------------------------------------------\n')
intro_pt1 = ('Story Time! Alice and Bob are great friends! So much so that '
'Alice wants to sen... |
a1c58e704867d6bfee2fb546e6f4b861a7081f2a | Osaroigb/Breakout-Game | /blocks.py | 960 | 4 | 4 | from turtle import Turtle
class Blocks:
def __init__(self):
self.width = 1
self.block_list = []
self.build_blocks()
def create_block(self, axis_x, axis_y, color):
"""A function that creates a block with a specified color at a specified position"""
self.block_list.ap... |
d26e719b4d312b8ac40696c490c878bd0aa3a18d | AcEbt/STGCN_COVID19_prediction | /calc_distance.py | 1,033 | 3.828125 | 4 | from math import radians, cos, sin, asin, sqrt, atan2
import math
def distance(lat1, lat2, lon1, lon2):
# The math module contains a function named
# radians which converts from degrees to radians.
lon1 = radians(lon1)
lon2 = radians(lon2)
lat1 = radians(lat1)
lat2 = radians(lat2)... |
58249aa99ceb10d7d93f622c80c22e73e7fe0c5a | XIII834/mnemo_dev | /mnemo.py | 3,663 | 3.703125 | 4 | # coding: utf8
what_do_you_want = str(input("What kind of training do you want?\n"))
if(what_do_you_want == 'words'):
import random
file_nouns = open("nouns.md", "r")
file_result = open("./results/words.md", "w")
arr = []
rand_indexes = []
cx = 0
for line in file_nouns:
arr.append(line)
how_many = int(inpu... |
0ee2fbc2ead607dee3c29beb2b60ca824dc51d6d | LNS98/Taxi-Fare-Competition | /scripts/inference.py | 1,941 | 3.609375 | 4 | """
Functions used to predict on new data
"""
import pandas as pd
import numpy as np
def predict(clf, DataFrame, features):
"""
Predict on the given df with the clf and the features provided.
"""
# copy df in
df = DataFrame.copy()
# as X values get the features in the df
X = df[features]... |
ee333d5bf02a1233e2367c18f78c851ba95cfa49 | ziaridoy20/DeepMoon | /py/filter_grade.py | 652 | 3.5 | 4 | import argparse
import json
parser = argparse.ArgumentParser()
parser.add_argument('--input_json', type=str, default='../data/2016+2017.json', help='filename of input JSON data')
parser.add_argument('--output_json', type=str, default='output.json', help='filename of output JSON data')
parser.add_argument('--grade', ty... |
6f3ba998639a510e55bee600227ffa9c63560735 | poyea/Hacktoberfest-2018 | /PYTHON/kmp.py | 1,058 | 3.671875 | 4 | import time
class KMP:
def part(self, pattern):
ret = [0]
for i in range(1, len(pattern)):
j = ret[i - 1]
while j > 0 and pattern[j] != pattern[i]:
j = ret[j - 1]
if pattern[j] == pattern[i]:
ret.append(j+1)
else:
... |
c76a4fe422a447692ffefd29fc88e61eb257bc2d | poyea/Hacktoberfest-2018 | /PYTHON/Trapezoidal rule.py | 686 | 3.734375 | 4 | #trapeziodal rule
x0 = int(input("Enter first value of x:"))
xn = int(input("Enter last value of x:"))
n = int(input("Enter number of iterations:"))
h = ((xn-x0)/n)
x=[x0]
f=0
m=0
y=[]
while (m+h)!=xn:
x.append(m+h)
m=m+h
x.append(xn)
#print(x)
degree = int(input("Enter degree of f(x):"))
coeff=[]
for i in range(degr... |
25a99f0f005722c65e774a3518cf09d582b4ec04 | Hellencarla/lista1 | /7 exc.py | 366 | 4 | 4 | #Faça um Programa que pergunte quanto você ganha por hora e
#o número de horas trabalhadas no mês.
#Calcule e mostre o total do seu salário no referido mês.
din = float( input("Quanto você ganha por hora: ") )
horas = float( input("Quantas horas você trabalha por mês: ") )
salario = (din* horas)
print("A médi... |
f38782d724ee0a1b3d86644859bf89918d5d467e | ahmedzitouni586/holbertonschool-higher_level_programming | /0x0C-python-almost_a_circle/models/rectangle.py | 3,947 | 3.75 | 4 | #!/usr/bin/python3
"""module to define rectangle class"""
from models.base import Base
class Rectangle(Base):
""" define rectangle class"""
def __init__(self, width, height, x=0, y=0, id=None):
super().__init__(id)
self.__width = width
self.__height = height
self.__x = x
... |
5375443669689f11237d7d191e503f67be36437f | ahmedzitouni586/holbertonschool-higher_level_programming | /0x04-python-more_data_structures/0-square_matrix_simple.py | 220 | 3.75 | 4 | #!/usr/bin/python3
def square_matrix_simple(matrix=[]):
squares = []
for i in range(len(matrix)):
new = []
new = list(map(lambda x: x**2,matrix[i]))
squares.append(new)
return squares
|
f33b2bb8b260bbeee5ebcd81148578a14c6e33a8 | LiamDGray/LiFi-With-Arduino | /lib/my_states.py | 1,989 | 3.5 | 4 | """
my_states.py
This file contains the definitions and transitions for ever state in our state machine.
"""
import serial
from state import State
from Sender import Sender_Driver
# Start Of Our States
class Receiver(State):
"""
The state indicating that the driver/arduino is
going to receive data... |
cd96c19bd4726aacd28ccfd5bfc4af573ce8b30b | NgoclanTran/PNO | /AUTO_DRIVE/Robot.py.save | 17,109 | 3.59375 | 4 | #!/usr/bin/env python
# Initial Date: Oktober 13, 2014
# Last Updated: Oktober 22, 2014
# Team Ijzer
# A file containing the robot class and some additional helper classes.
#import BrickPi.py file to use BrickPi operations
from BrickPi import *
# Import time module to keep track of time
import time
# Import RPi.GP... |
748997342da16a59f1894640584b9b23aaf690f9 | haiyanzzz/Questionnaire | /测试.py | 1,200 | 3.828125 | 4 | #!usr/bin/env python
# -*- coding:utf-8 -*-
# 如果获取的数据不是直接可以展示的结构
# 方式一
user_list = [
{"id":222,"name":"haiyan","age":33},
{"id":2,"name":"zzzzz","age":13}
]
new_user_list = []
for item in user_list:
item["age"] = item["id"]+item["age"]
new_user_list.append(item["age"])
# print(new_user_list)
# print(use... |
0abcc3e4aab213b49a96856a7c7352a63d6d53fc | wildcatalum/intro-to-comp-sci | /asciiart.py | 773 | 3.90625 | 4 | # Efren Ibarra, CSC 110, Fall 2016, Section 1B
# programming assignment #2A, 09/03/16
def main():
antenna()
top()
gap()
eyes()
gap()
mouth()
gap()
top()
def top():
for i in range(1, 6):
print("__", end="")
print()
def eyes():
print("|... |
d45a366a0567dd296489b6a641a36f9104edabeb | AdamPohl/bink-technical-test | /phone_masts.py | 5,108 | 3.921875 | 4 | import csv
from datetime import datetime
from pprint import pprint
class PhoneMasts:
def __init__(self):
try:
self.csv_file = open('python_developer_test_dataset.csv', 'r')
except Exception as e:
print("Unable to read in csv file.")
raise e
def make_csv_rea... |
8abc502e0bce6dcd42123d7fbfe973d11c65cf30 | kushajha/graph-Plotter | /tangr.py | 159 | 3.609375 | 4 | import matplotlib.pyplot as plt
import numpy as np
import math
x=np.linspace(0,2*np.pi,200)
plt.title("tanx")
plt.plot(x,np.tan(x),color='black')
plt.show()
|
c89aabe05f30f05ac4125f4f02722356d00d52f3 | kushajha/graph-Plotter | /tur.py | 795 | 3.53125 | 4 | from turtle import *
import turtle
from random import randint
y=int(raw_input('Press 1 for 1st Pattern\nPress 2 for 2nd Pattern\n>> '))
bgcolor('black')
if y==1:
speed(0)
x = 0
up()
rt(45)
fd(90)
rt(135)
down()
while x<120:
r=randint(0,255)
g=randint(0,255)
b=randint(0,255)
col... |
520f357328f7aa468f17530cb464af06f41e839d | Wardl1/Math-Quiz | /09_Warning_GUI_v1.py | 1,617 | 3.734375 | 4 | """09 Warning GUI Version 1
sets up design for the Warning GUI
No buttons frame yet
"""
from tkinter import *
class WarningGUI:
def __init__(self):
# Formatting variables
background_color = "#FF9999" # light red
# Warning Frame
self.warning_frame = Frame(width=300, bg=background... |
cde23e59128138d6349d9cee50b0c383857650eb | Wardl1/Math-Quiz | /01_Main_Menu_v3.py | 3,464 | 3.8125 | 4 | """Component 1 Main Menu GUI version 3
this version continues on from the last with all
buttons now in the GUI and all buttons have been formatted."""
from tkinter import *
class MathQuiz:
def __init__(self):
# Formatting variables
background_color = "#66FFFF" # light blue
# Main menu G... |
dcb566add7321c6b79ca5b9361daac1ea74b159e | Kufooloo/pytuts | /howlongtillbirthday.py | 424 | 3.984375 | 4 | from datetime import date
from datetime import time
from datetime import datetime
from datetime import timedelta
today = date.today()
birthdate = date(2002, 10, 30)
birthday = date(today.year, 10, 30)
diffrence_birthdate = today-birthdate
print("your birthday was ",diffrence_birthdate , " ago")
if today > birthday:
... |
9aa6d3cfc8a6767991c37316d8b01f8b1c6726cc | DepthDeluxe/GeneticBrewRun | /serialPort.py | 19,009 | 3.59375 | 4 | import serial
def lookup(a, b):
num1 = 0
num2 = 0
if a < b:
num1 = a[0]
num2 = b[0]
else:
num1 = b[0]
num2 = a[0]
if num1 == 0 and num2 == 1:
return 9
if num1 == 0 and num2 == 2:
return 12
if num1 == 0 and num2 == 3:
return 23
if num1 == 0 and num2 == 4:
return 22
if num1 == 0 and num2 == ... |
6ca863f66219bfe6456dd1c97b884762367f9110 | raj9226/hackerrank | /venv/loops.py | 82 | 3.671875 | 4 | n = int(input())
if n in range(0,21):
for i in range(0,n):
print(i**2) |
e958ad4004ea6e3f9c138230c2a669d8bef5fd9a | kirankumarcs02/course-datacamp | /image-processing/chapter-4/exe_2.py | 1,341 | 3.828125 | 4 | # Import the corner detector related functions and module
from skimage.feature import corner_harris, corner_peaks
# Convert image from RGB-3 to grayscale
building_image_gray = color.rgb2gray(building_image)
# Apply the detector to measure the possible corners
measure_image = corner_harris(building_image_gray)
# Fin... |
25424f5b9b6180ee484159cb78ddde99e85db44e | kirankumarcs02/course-datacamp | /image-processing/chapter-1/exe_4.py | 664 | 3.609375 | 4 | # Import the otsu threshold function
from skimage.filters import threshold_otsu
from skimage.color import rgb2gray
from matplotlib import pyplot as plt
def show_image(image, title='Image', cmap_type='gray'):
plt.imshow(image, cmap=cmap_type)
plt.title(title)
plt.axis('off')
plt.show()
chess_pieces_i... |
efe5a5c620ed9663cd1ecb986210318927211091 | rpask00/codeforces_py | /Simpler Interactive Interpreter.py | 5,891 | 3.5625 | 4 | import functools
import itertools
def flat_list(arr):
send_back = []
for i in arr:
if type(i) == list:
send_back += flat_list(i)
else:
send_back.append(i)
return send_back
def insert_plus(seq, a):
operators = ['+', '-', '*', '/']
if type(seq) == str:
... |
daf00f81e60cd217d6fea835616c4cb509797437 | rpask00/codeforces_py | /Simple Interactive Interpreter.py | 9,717 | 3.515625 | 4 | import functools
def flat_list(arr):
send_back = []
for i in arr:
if type(i) == list:
send_back += flat_list(i)
else:
send_back.append(i)
return send_back
def insert_plus(seq, a):
operators = ['+', '-', '*', '/']
if type(seq) == str:
seq = [seq]
... |
4745b095863861b72e4a1ece16016048cce43f90 | andrewmartins/COMP202 | /Assignment2/RightTriangle.py | 280 | 3.65625 | 4 | import sys
rows = int(sys.argv[1])
if rows >= 0:
for i in range(1, rows+1):
for j in range(0, rows-i):
print(" ", end = "")
for k in range(0, i):
print("*", end = "")
print("")
else:
print("Error: input value must be >=0") |
9473f6456519749d1b687bc83cf290e9d31316cf | KoushikRaghav/commandLineArguments | /stringop.py | 1,399 | 4.125 | 4 | import argparse
def fileData(fileName,stringListReplace):
with open(fileName,'w') as f:
f.write(str(stringListReplace))
print stringListReplace
def replaceString(replace,stringList,fileName,word):
rep = replace.upper()
stringListReplace = ' '
for w in stringList:
stringListReplace = w.replace(word, re... |
4be5055a1b36fc3eefa65cd0b9a6ae1f06709d83 | keithmonreal/FTW | /TrueOrFalseQuiz.py | 2,007 | 4 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon Sep 21 00:15:37 2020
@author: Keith Monreal
"""
# Give the user some context and get his or her name
print("\nAre you ready to take a quiz about everything and anything under the sun today?")
choice = input("Yes or No\n")
if 'Yes' in str(choice):
print("\nOka... |
7018d821c64d220355ed9a2f0d54c259f2e93422 | mattsunner/file-zipper | /app.py | 875 | 4.03125 | 4 | from file_manager.file_manager import file_zipper, file_unzipper
def main():
function_selection = input(
str('What would you like to do? (Zip or Unzip): '))
if function_selection == 'Zip':
file_path = input(str('Enter the Original File Path: '))
zip_path_name = input(str('Enter the De... |
b8e67ac7d38a7936d6fe8ed71f6de2f303165694 | arpitchandak/python_1011 | /strabc.py | 127 | 3.5625 | 4 | a = input("Enter a string:")
b = input("Enter a char:")
i=0
m=0
x = len(a)
while (i<x):
if(b == a[i]):
m+=1
i+=1
print(m)
|
3c96888314636a92ad4b11ee30adaf33483d9cbc | arpitchandak/python_1011 | /fabonnic.py | 120 | 3.78125 | 4 | n = int(input("Enter a no. = "))
print("01")
x = 0
y = 1
i = 0
while (i<n-2):
m = x+y
print(m)
x = y
y = m
i+=1
|
eb42a00600d06efb20f8cd6fae09b1801a38106a | ananyae-24/ML-repo | /regression/mySimple_linear_regression.py | 657 | 3.71875 | 4 | import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
dataset=pd.read_csv("Salary_Data.csv")
X=dataset.iloc[:,:-1].values
y=dataset.iloc[:,-1].values
from sklearn.model_selection import train_test_split
X_train,X_test,y_train,y_test=train_test_split(X, y,test_size=.2,random_state=1)
from sklearn.linear... |
8a6762d7a1760af46c718497d875349b925c6606 | majdalkilany/madlib-cli.1 | /madlib_cli_1/madlib.py | 2,192 | 3.84375 | 4 | def welcom() :
"""
print welcom message
"""
print('''welcom in madlib game
please fill the blanks in the words
''')
def read_file() :
'''
read text from file
'''
fname = open('assets/mad_file.txt','r')
fname = fname.read()
fname =fname.strip()
return(fnam... |
c9c2c79ae4cb85d88aea14c1838b3037ead4e537 | mkmad/CtCI-6th-Edition | /mycode/dsap/textProcessing/kmp.py | 3,621 | 3.640625 | 4 | class KMP(object):
@staticmethod
def failure_function(pattern):
"""
The idea is to run two pointers i and j, i starting from 1
and j from 0
if values at the pattern i and j don't match then i simply
moves to the next element
if it matches however, value at i is... |
cc72e292fae35b8cc8155f07e470b8c6301275e9 | mkmad/CtCI-6th-Edition | /mycode/dsap/graphs/ug_cycle.py | 1,232 | 3.96875 | 4 | import sys
class UndirectedGraphCycle(object):
"""
The difference between this dfs and the other
dfs is, here we keep track of the prev vertex to
avoid going back in the same direction in which we
came from.
We say the graph has a cycle if it reaches a node that's
already in the visited d... |
ce2d4d6777df0fe2068b1c72bf503d847b91b223 | HwangDongJun/Study_Python-inflearn- | /반복문/odd & even number 구분.py | 425 | 3.828125 | 4 | for i in range(0, 10):
if i % 2 == 0:
print(str(i) + ' 짝수') #i가 정수인데 string형태가 아니라 str로 캐스팅한다.
print('{} 짝수'.format(i)) #str사용안하는 방법
else:
print(str(i) + ' 홀수')
print('{} 홀수'.format(i))
print("\n")
for one in range(1, 10):
for two in range(1, 10):
print('{} * {} = {}... |
cd8f7212b11ec07bd1e4f3868a014930f344ef73 | HwangDongJun/Study_Python-inflearn- | /클래스/mandoo_wage_program.py | 2,326 | 3.65625 | 4 | class EmployeeList: #클래스를 만들때는 첫번째 문자를 대문자로 시작
name = "-"
wage_per_hour = 7530
work_start = None
work_finish = None #아무것도 없다라는 의미 -> None
def __init__(self, name, work_start, work_finish): #생성자를 의미
self.name = name
self.work_start = work_start
self.work_finish = work_finish
... |
d051781a48707cc8a96d37b7474b1295c0efb466 | Paolavigni/lista5 | /ex5.py | 157 | 3.953125 | 4 | val = int(input('Digite um valor: '))
cont = 1
num = val
while cont < val:
num = cont * num
cont = cont + 1
print (f'{val}! é igual a {num}.') |
328cae0e0f01148c37db88604b94e382cd82c200 | RosezClassrooms/assignment2-team-krallar | /robot_with_keywords.py | 4,418 | 4.25 | 4 | from abc import ABC, abstractmethod
# In order to only give values for relevant attributes, you must
# use some form of keyword argument initialization
# However, all of the attributes must be given default values
# Keep in mind that in a real application, these would be endless ...
# Is there any danger in hav... |
2cc0a965156892484a2dd4465903b8ee78ca41ed | Miguelsantos101/algoritmos1-2021-1 | /1042_sort.py | 393 | 3.734375 | 4 | a, b, c = map(int, input().split())
if a < b:
if b < c:
#print(f"{a}\n{b}\n{c}")
A = a
B = b
C = c
else:
# b é o maior de todos
if a < c:
print(f"{a}\n{c}\n{b}")
else:
print(f"{c}\n{a}\n{b}")
else:
if a < c:
print(f"{b}\n{a}\n{c}")
else:
# a é o maior de todos
if b < c:
print(f"{b}\n{c... |
ef79f28c0f0abb5acc0701b074d07aee62472e20 | Miguelsantos101/algoritmos1-2021-1 | /1036_bhaskara.py | 407 | 3.53125 | 4 | # 1036 Bhaskara
# entrada:
a, b, c = input().split()
a = float(a)
b = float(b)
c = float(c)
# outro jeito de fazer a entrada:
#a, b, c = map(float, input().split())
delta = b ** 2 - 4.0 * a * c
if delta < 0.0 or a == 0.0:
print("Impossivel calcular")
else:
r1 = (-b + (delta ** 0.5)) / (2.0 * a)
r2 = (-b - (delta... |
04c6219f4352ee5823de25615373621facac5566 | Miguelsantos101/algoritmos1-2021-1 | /fibonacci_f.py | 336 | 3.765625 | 4 | # Calcula o n-ésimo número de Fibonacc
def fibo(n):
if n == 0 or n == 1:
fib = n
else:
# n >= 2
a = 0
b = 1
for i in range(1, n):
fib = a + b
a = b
b = fib
return fib
#-------------------------------------
def main():
n = int(input())
Fn = fibo(n)
print(Fn)
#-------------------------------... |
d13354f1bb95403357a5ad1adb3a189d564c45c6 | Miguelsantos101/algoritmos1-2021-1 | /adivinha2.py | 253 | 3.71875 | 4 | # sem usar o break
import random
n = random.randint(0, 10)
acertou = False
while not acertou:
i = int(input("Adivinhe o número: "))
if i == n:
acertou = True
else:
print("Você errou! Tente novamente.")
print("Você acertou!")
print("Bye.")
|
ce97e62547c83f9f85665872fad61e6d26510bc8 | Miguelsantos101/algoritmos1-2021-1 | /primo.py | 198 | 3.75 | 4 | n = int(input())
i = 2
primo = True
while i < n and primo:
# testar se é possível dividir n por i
if n % i == 0:
primo = False
i = i + 1
if primo:
print("Primo")
else:
print("Composto") |
9d522959bc643ce2cbfb8a5b59e6c73f10309a2a | Miguelsantos101/algoritmos1-2021-1 | /pot_euler.py | 231 | 3.78125 | 4 | x = float(input())
n = int(input())
valor = 0.0
for i in range(0, n+1):
# print(i)
# calcula i!
fat = 1
for j in range(1, i+1):
fat = fat * j
#print(f"{x}^{i} / {fat}")
valor = valor + x ** i / fat
print(f"{valor:.4f}") |
7e648b5e28912ba2be6dbf040fd9f0fc2f559854 | Miguelsantos101/algoritmos1-2021-1 | /adivinha.py | 266 | 3.921875 | 4 | # Como usar o comando break
import random
n = random.randint(0, 10)
while True:
i = int(input("Adivinhe o número: "))
if i == n:
print("Você acertou!")
break
else:
print("Você errou! Tente novamente.")
print("Bye.")
# Faça este jogo sem usar o break |
150a16338613c15e999558ea13b6bd1ebd6f7bf2 | angel-sm/Python | /HellowWorld.py | 963 | 3.890625 | 4 | nombre = 'Angel'
def seleccionDatos(nombre):
print(nombre[1:5])
def condicionalIf():
edad = int(input('Dame edad '))
if edad > 5:
print ('mayor')
else:
print ('menor')
def entradaDatos():
entrada = input ('Dame tu nombre ')
def cicloWhile():
x = 10
while x != 0:
... |
3de7f6d52983d7b9d4f5bbec03ad4853edc4a0e1 | Abulswalih/psychic-octo-spoon | /largest.py | 151 | 3.609375 | 4 | def largest(a,b,c):
if a > b:
if a>c:
return a
else:
return c
else:
if b>c:
return b
else:
return c
|
ae7088de86c97a8737e59c83d2c08ec6d1b6390a | micvianna/Python_Fundamentals | /working_with_variables.py | 211 | 3.765625 | 4 | a = 3
greeting = "Hello,"
name = "Zoey"
print(a + 3)
print(greeting + ", there!")
print(greeting + " " + name)
name = "Zoeski"
print(greeting + " " + name)
name = "Zoey"
print(greeting + " " + name)
|
290696e2238ad293dcbe4fc35b2a1438bfe10740 | Sweltering/regular_expression | /regular_expression2.py | 853 | 3.625 | 4 | # 正则表达式常用匹配规则
# 以下匹配都是匹配多个字符
import re
# 1、* 匹配0个或者任意多的字符,没有匹配空白
# text = '12ab'
# ret = re.match('\d*', text)
# print(ret.group())
# 2、+ 匹配1个或者任意多的字符,没有返回None,
# text = '12ab'
# # ret = re.match('\d+', text)
# # print(ret.group())
# 3、? 匹配1个或者0个
# text = '12ab'
# ret = re.match('\d?', text)
# print(ret.grou... |
5ce58dda0c9928a43e3463e7447ce63f404c5e51 | brickfaced/data-structures-and-algorithms | /challenges/multi-bracket-validation/multi_bracket_validation.py | 2,197 | 4.34375 | 4 | class Node:
"""
Create a Node to be inserted into our linked list
"""
def __init__(self, val, next=None):
"""
Initializes our node
"""
self.val = val
self.next = next
def __repr__(self, val):
"""
Displays the value of the node
"""
... |
e80d56ed863853dc27c5b52fb07fa89c87411b22 | brickfaced/data-structures-and-algorithms | /sorting_algos/quick_sort.py | 372 | 3.90625 | 4 | """Quick Sort Algorithm"""
def quick_sort(lst):
if len(lst) < 1:
return lst
pivot = lst[0]
left = []
middle = [pivot]
right = []
for i in range(1, len(lst)):
if lst[i] <= pivot:
left.append(lst[i])
if lst[i] > pivot:
right.append(lst[i])
r... |
d1f9324a011cbbe33a65a2005115e06ab86f74d1 | brickfaced/data-structures-and-algorithms | /data-structures/binary_search_tree/fizzbuzztree.py | 602 | 4.5625 | 5 | def fizzbuzztree(node):
"""
Goes through each node in a binary search tree and sets node values to
either Fizz, Buzz, FizzBuzz or skips through them depending if they're
divisible by 3, 5 or both. The best way to use this function is to
apply it to a traversal method. For example: BST.in_order(fizzb... |
0a748373a51802c7500f8b6bd72cbd44d3f467d9 | brickfaced/data-structures-and-algorithms | /data-structures/hash_table/repeated_word.py | 857 | 4.125 | 4 | """Whiteboard Challenge 31: Repeated Word"""
from hash_table import HashTable
def repeated_word(text):
"""
Function returns the first repeated word.
First thing it does is splits the inputted string
into a list and for each word in that list it checks
if that word is already in the hash table, if ... |
7c290e483421caf1f0987201a0af04dffc3cba20 | hyl404/HTML | /python练习/2月5日python练习/列表和字典.py | 1,888 | 4 | 4 | '''inventory = ["sword","armor","shield","healing potion"]
print("Your items:")
for item in inventory:
print(item)
print("You have",len(inventory),"in your ass")
#对列表进行检索
index = int((input("选择你想要的角色:")))
print("这是你选择的角色:",inventory[index])
#对列表进行切片
start = int(input("选择你的角色从:"))
finish = int(input("到这里结束:"))
pri... |
4da3c966f0231b974a307080a35cef3212d417d9 | SungjinJo/git-python | /Day03/food_manager.py | 4,312 | 3.828125 | 4 | '''
* 사전을 사용한 음식점 메뉴판 관리 프로그램.
- key: 음식명, value: 음식의 가격
'''
foods = {}
while True:
print("\n\n====== 음식점 메뉴 관리 프로그램 ======")
print("# 1. 신규 메뉴 등록하기")
print("# 2. 메뉴판 전체보기")
print("# 3. 프로그램 종료")
print("===========================================")
menu = int(input("# 메뉴 입력: "))
if menu =... |
1053f73b5b78009a5dba2a57dd9076ae70327a11 | SungjinJo/git-python | /Day01/hello.py | 645 | 3.53125 | 4 |
'''
- 여러 줄 주석입니다.
- 주석: 코드에 설명을 첨언하는 기능.
'''
# 한 줄만 주석 처리를 할 때는 # 기호를 사용.
# Ctrl + alt + n : 실행 단축키
print('안녕 파이썬!') # 샵 오른쪽만 주석으로 간주
# 파이썬에서는 문장의 끝에 세미콜론을 적지 않아도 됩니다.
# 단, 한 줄에 여러 문장을 작성할 때는 사용!
print(3 * 7); print(2 + 3)
# 파이썬에서는 불필요한 들여쓰기를 절대 허용하지 않습니다.
# print('야호') (x)
# 파이썬의 모든 명령은 대/소문자를 철저하게 구분합니다... |
8cd3f4b3924a37ff726245696991f8e40a8b8cbe | SungjinJo/git-python | /Day01/input_ex01.py | 701 | 3.65625 | 4 |
'''
* 표준 입력함수 input()
- 함수 괄호 안에 사용자에게 질문할 내용을 문자열 형태로
작성합니다.
- input()과 함께 항상 변수를 선언해서 입력값을 받아주셔야 하며
입력받은 데이터의 타입은 str로 저장됩니다.
'''
nick = input('너 별명이 뭐야?: ')
print('내 별명은 ' + nick + "입니다.")
# 입력값이 만약 정수, 실수라면
# input함수 자체를 int(), float() 함수로 감싸주시면 됩니다.
# input함수의 리턴값이 문자열이라 했으니까, 변환함수로 변환하면 끝.
price = int(in... |
b3e01eac63ae1ce3905feb3f4dc53739243e8e3f | chalasanim/Blogger | /app.py | 1,564 | 4.03125 | 4 | from blog import Blog
from post import Post
blogs=dict() # blogname:BlogObject
MENU_PROMPT = "Enter 'c' to create blog, 'l' to list the blogs,'r' to read the blog 'c' to create a post or 'q' to quit"
Post_Template='''---{} ---
---{}---
'''
def menu():
#show the user available blogs
#let user make choice
... |
4993224ddd0744510bcff623637c2b3e44bdaf7f | anandawira/HackerrankProjects | /DailyCodingProblem/Problem #2.py | 667 | 3.9375 | 4 | # Given an array of integers, return a new array such that each element at index i of the new array is the product of all the numbers in the original array except the one at i.
# For example, if our input was [1, 2, 3, 4, 5], the expected output would be [120, 60, 40, 30, 24]. If our input was [3, 2, 1], the expected ... |
d4ac34f66b4f1da30af3f8e32215f71c9345d0bf | anandawira/HackerrankProjects | /Euler/Project Euler #10: Summation of primes.py | 920 | 3.625 | 4 | #!/bin/python3
import sys
def SieveOfEratosthenes(n):
# Create a boolean array
# "prime[0..n]" and initialize
# all entries it as true.
# A value in prime[i] will
# finally be false if i is
# Not a prime, else true.
prime = [True for i in range(n+1)]
p = 2
while (p * p <= n):
... |
569d0a2258a0d8082eff6d925378f6197e78b012 | anandawira/HackerrankProjects | /Euler/Project Euler #1: Multiples of 3 and 5.py | 457 | 3.546875 | 4 | #!/bin/python3
import sys
import math
def sumOfMultiple(n, multiple):
n=n-1
if n<multiple:
return 0
max = n//multiple
return math.floor((((max*max) + max)//2)*multiple)
def solve(n):
sumOf3 = sumOfMultiple(n, 3)
sumOf5 = sumOfMultiple(n, 5)
sumOf15 = sumOfMultiple(n,15)
... |
e75fc2ddab06241b5f3262b09798a40151972fac | abhaysingh00/PYTHON | /sum of numbers using list.py | 272 | 3.984375 | 4 | l=[]
for i in range(3): #to run the loop 3times
l.append(int(input("enter a number")))
if l[0]==l[1]==l[2]: #to check if all the three values are same
print(3*sum(l)) #to print 3 times the sum of the numbers
else:
print(sum(l))
|
c7b1e0312b7b032e4f69e0e05b695b1604e82722 | abhaysingh00/PYTHON | /sumOfThree.py | 130 | 3.921875 | 4 | def sumOfThree():
sm=0
for i in range(3):
sm = sm +int(input("enter a number"))
return sm
print(sumOfThree())
|
b26893e0db5a57db2eed7de038eedc67337aecbf | abhaysingh00/PYTHON | /even odd sum of 3 digit num.py | 307 | 4.21875 | 4 | n= int(input("enter a three digit number: "))
i=n
sm=0
count=0
while(i>0):
count=count+1
sm=i%10+sm
i=i//10
if(count==3):
print(sm)
if(sm%2==0):
print("the sum is even")
else:
print("the sum is odd")
else:
print("the number entered is not of 3 digits")
|
cf0f32e7db6d2faae867d704b3f6c6d4b5954ece | abhaysingh00/PYTHON | /reversing string by words.py | 287 | 3.765625 | 4 | s=input("enter a sentence to reverse: ")
st=s+" "
l = len(st)
word =" "
sentence =""
for i in range(l):
if st[i].isspace():
print(word)
sentence=word + sentence
word =" "
else:
word=word + st[i]
print(sentence)
print(l)
print(len(sentence))
|
e7916d0b112ca2b8b28cd25dc80e53c4c8ed57bc | ankur02001/TextClassification-EmailSpamCorpora | /classifySPAM.py | 14,934 | 3.5 | 4 | # program to get started creating a spam detection classifier
# open python and nltk packages needed for processing
import os
import sys
import random
import nltk
from nltk.corpus import stopwords
import csv
import re
import math
import string
from nltk.tokenize import wordpunct_tokenize as tokenize
from nltk.stem.port... |
bcce9ed469f8ad71394ad9bf13e556631cf9557b | ddavisqa/ChallengeProblems | /find_number_in_list.py | 1,057 | 4.0625 | 4 | # Implement a binary search algorithm to
# find if a number is in a given sorted list of numbers.
# If true, return the index of the number.
def find_num(num_list, num):
if len(num_list) < 1:
return 'Number not in list.'
else:
current_index = (len(num_list)//2)
if num_list[current_index] == num:
return cu... |
1fbf336bdc18c86e1f4a449ac5e47a3071c99557 | clarkbulleit/unit-testing-clarkbulleit | /is_tachycardic.py | 283 | 3.625 | 4 |
def is_tachycardic(candidate):
clean_candidate = candidate.strip().lower()
clean_candidate = ''.join(letter for letter
in clean_candidate if letter.isalpha())
if clean_candidate == 'tachycardic':
return True
return False
|
aeeabf666ce139d0ce82fade7b60af4b65e88eaa | Kairs0/Symbolic-Execution-Tool | /ast_tree.py | 19,278 | 4.0625 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
#### AST Tree structure:
# Each node has a category (string), values can be :
sequence, if, variable, constant, operation, assign, compare, while, logic
# Each node has a list of nodes which are his children
# A node can have a data (for constant, operation, compare... |
08e914530e1949b38208a2fcf2d5988c38b11bb5 | o0brunolopes0o/Curso-em-video-exercicios | /ex114.py | 304 | 3.5 | 4 | """
Exercício Python 114: Crie um código em Python que teste se o site pudim está acessível pelo computador usado.
"""
import urllib
import urllib.request
try:
site = urllib.request.urlopen('http://www.pudim.com.br')
except:
print('Deu erro')
else:
print('Site funcionando')
|
ee3f8590f6a7be22bdf100b98b772aa9c09cc024 | o0brunolopes0o/Curso-em-video-exercicios | /ex044.py | 898 | 4.15625 | 4 | """
Exercício Python 44: Elabore um programa que calcule o valor a ser pago por um produto, considerando o seu preço normal
e condição de pagamento:
– à vista dinheiro/cheque: 10% de desconto
– à vista no cartão: 5% de desconto
– em até 2x no cartão: preço formal
– 3x ou mais no cartão: 20% de juros (no valor t... |
da2704b8f2d09525012a6b60336045fbed942339 | o0brunolopes0o/Curso-em-video-exercicios | /ex070.py | 1,043 | 4 | 4 | """
Exercício Python 70: Crie um programa que leia o nome e o preço de vários produtos.
O programa deverá perguntar se o usuário vai continuar ou não. No final, mostre:
A) qual é o total gasto na compra.
B) quantos produtos custam mais de R$1000.
C) qual é o nome do produto mais barato.
"""
total = totmil ... |
c299b481a9174bb71ae7f67d9875955d402b1eb5 | o0brunolopes0o/Curso-em-video-exercicios | /ex030.py | 212 | 4 | 4 | numero = int(input('Digite o número inteiro: '))
resultado = numero % 2
if resultado == 0:
print('O número {} é PAR' .format(numero))
else:
print('O número {} é IMPAR' .format(numero))
|
024e7330f042912361349ac26d8f3eb51f2497b2 | o0brunolopes0o/Curso-em-video-exercicios | /ex091.py | 794 | 3.96875 | 4 | """
Exercício Python 091: Crie um programa onde 4 jogadores joguem um dado e tenham resultados aleatórios.
Guarde esses resultados em um dicionário em Python.
No final, coloque esse dicionário em ordem, sabendo que o vencedor tirou o maior número no dado.
"""
from random import randint
from time import sleep
fro... |
1fc4adc1860c895218a1c154d96f202bbb3ef574 | o0brunolopes0o/Curso-em-video-exercicios | /ex055.py | 500 | 3.859375 | 4 | """
Exercício Python 55: Faça um programa que leia o peso de cinco pessoas. No final, mostre qual foi o maior e o menor
peso lidos.
"""
maior = 0
menor = 0
for peso in range(0, 5):
peso = float(input(f'qual pesso da {peso} pessoa: '))
if peso == 1:
maior = peso
menor = peso
else:
... |
3bc808621c79b6cf1730dae5c686887ecb9547f4 | o0brunolopes0o/Curso-em-video-exercicios | /ex113.py | 1,047 | 4.0625 | 4 | """
Exercício Python 113: Reescreva a função leiaInt() que fizemos no desafio 104,
incluindo agora a possibilidade da digitação de um número de tipo inválido.
Aproveite e crie também uma função leiaFloat() com a mesma funcionalidade.
"""
def leiaInt(f):
while True:
try:
valor = int(i... |
d4d6c3d64ca2d49cd01d734d42ee16ed17c858f4 | anooprh/leetcode-python | /algorithm/a409_Longest_Palindrome.py | 588 | 3.59375 | 4 | import os
import collections
class Solution(object):
def longestPalindrome(self, s):
"""
:type s: str
:rtype: int
"""
odd_seen = False
ans = 0
for v in collections.Counter(s).values():
if not odd_seen and v%2 == 1:
ans += v
... |
a43043c613a4424340752c333d9a5d43f5a29a9c | anooprh/leetcode-python | /algorithm/a237_Delete_Node_In_A_Linked_List.py | 637 | 3.75 | 4 | import os
# Definition for singly-linked list.
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
class Solution(object):
def deleteNode(self, node):
"""
:type node: ListNode
:rtype: void Do not return anything, modify node in-place instead.
... |
78aa35361438055115f831c3a36638694ab46667 | anooprh/leetcode-python | /algorithm/a001_Two_Sum.py | 414 | 3.578125 | 4 | import os
class Solution(object):
def twoSum(self, nums, target):
m = {}
for i, num in enumerate(nums):
if target - num in m:
return [m[target - num], i]
else:
m[num] = i
if __name__ == "__main__":
print("Running", os.path.basename(__file... |
411ab2ca0b84ec887f76348f5be3f24a5083dfe0 | anooprh/leetcode-python | /algorithm/a011_Containter_With_Most_Water.py | 560 | 3.65625 | 4 | import os
class Solution(object):
def maxArea(self, height):
"""
:type height: List[int]
:rtype: int
"""
i,j=0,len(height)-1
ans = 0
while i<j:
h = min(height[i], height[j])
ans = max(ans, h*(j-i))
while(height[j] <= h and... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.