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 |
|---|---|---|---|---|---|---|
8b231a40ccc5c66b1b28492a34049b12820d0629 | rtg0795/python_snippets | /union_of_lists.py | 415 | 3.5625 | 4 | # Source
# https://medium.com/better-programming/25-useful-python-snippets-to-help-in-your-day-to-day-work-d59c636ec1b
# Union of lists
import itertools
# logic
def union_of_lists(*args):
union = []
for item in itertools.chain([arg for arg in args]):
[union.append(item[i]) for i in range(len(item))]
... |
6a00e0241c7f5c4381347f24a799019cda955e6e | tres-xxx/UniSchedule | /mainSchedule.py | 9,020 | 3.5 | 4 | import xlrd
import os.path
import sys
''' How the sheet is organizated
0 - NRC
1 - Sesion
2 - Alfa numerico
3 - Nombre de la asignatura
4 - Opciones disponibles para las electivas y seminarios
5 - Creditos
6 - Dia
7 - Hora inicio
8 - Hora fin
9 - Programa
10 - Jornada
11 - Nivel/Semestre
12 - Modalidad
'''
# Function... |
4c52634b82528cdf0613e30d1a44211a64d46530 | ClayTaylor/HeadFirstPython-odd.py | /odd.py | 1,572 | 3.734375 | 4 | from datetime import datetime # Importing the Library and then the SubModule in that Library
odds = [1, 3, 5, 7, 9, 11, 13, 15, 17, 19, # odds is a list [], but also a variable
21, 23, 25, 27, 29, 31, 33, 35, 37, 39,
41, 43, 45, 47, 49, 51, 53, 55, 57, 59]
for i in range (5):
right_this_minute =... |
684f913040ab777d1ff4ed0aeb078725292aa959 | Daniel-Fan/CSCA48 | /Week11/ex9.py | 2,939 | 4 | 4 | class BTNode(object):
"""A node in a binary tree."""
def __init__(self, value, left=None, right=None):
"""(BTNode, int, BTNode, BTNode) -> NoneType
Initialize this node to store value and have children left and right,
as well as depth 0.
"""
self.value = value
... |
ff1890084e247ac48a3bbba1c9f3073006ea6315 | harshal-choudhari/books-python-wrappers | /books/model/Project.py | 7,969 | 3.71875 | 4 | #$Id$
class Project:
"""This class is used to create object for Projects."""
def __init__(self):
"""Initialize the parameters for projects object."""
self.project_id = ''
self.project_name = ''
self.customer_id = ''
self.customer_name = ''
self.currency_code = ... |
bacdb8ca06186587d35f45c88c0dafef40e59ac5 | IADT-y3-CMT-SWD/python_examples | /Week02/sales_bonus.py | 157 | 4.0625 | 4 | #weathercheck example
temperature= input('What\'s the temperature:')
if int(temperature) < 40:
print('Nice weather')
else:
print ('a little cold')
|
cd18eeaf65688721c9fae8f9f4af020222d262b1 | vitcmaestro/hunter_3 | /ascending_lower.py | 155 | 3.640625 | 4 | x = int(input(""))
alpha = list(map(str,input().split()))
for i in range(x):
alpha[i] = alpha[i].lower()
alpha.sort()
print("\n".join(map(str,alpha)))
|
0c770d76532eb0298729bc5ec37f68192346de68 | rathoresrikant/Analyzing-IPL-dataset-using-Scikit-learn | /Code/ipl2018.py | 4,199 | 3.5 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Mar 31 17:08:37 2018
@author: srikant
"""
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
deliveries = pd.read_csv('deliveries.csv')
matches = pd.read_csv('matches.csv')
print(deliveries.head(2))
print(matc... |
0a37ef969b8528afb3222034e4718eada8c0749e | GiovaneNardari/Exercises | /soma.py | 134 | 3.796875 | 4 | def somaP(n: int):
if n == 1:
return 2
else:
return n * 2 + somaP((n-1))
n = int(input('N: '))
print(somaP(n)) |
14528ef89398f0c6b0cd2a6d916ea7efc8aa8758 | GiovaneNardari/Exercises | /Nota-Final.py | 2,658 | 3.96875 | 4 | while True:
try:
N = int(input('Indique a quantidade de avaliações realizadas: '))
break
except ValueError:
print('Erro no input... Tente novamente!')
continue
notas = []
for i in range(N):
while True:
try:
nota = float(input('Digite suas notas: '))
... |
38880e1d299999c710ebf931a88ab805dc35f416 | totino1120/PythonTopics | /MatPlotLib/plot1.py | 770 | 3.65625 | 4 | import matplotlib.pyplot as plt
import numpy as np
# uses seed to generate random numbers
np.random.seed(444)
rng = np.arange(50)
rnd = np.random.randint(0, 10, (3, rng.size)) # 3 arrays of rng.size (49) # y axis
yrs = 1950 + rng # x axis
# print(rng)
# print(rnd)
print(rng+rnd)
#
fig, ax = plt.subplots(figsize=(... |
c33ab69ed86929f014f21ca1e827dec25f40b885 | Ananthan4451/ust_project | /student.py | 6,798 | 3.828125 | 4 | from tkinter import *
import sqlite3
from tkinter import messagebox
class DB:
def __init__(self):
try:
self.conn = sqlite3.connect("student.db")
self.cur = self.conn.cursor()
self.cur.execute(
"CREATE TABLE IF NOT EXISTS student (id INTEGER PRIMARY KEY, ... |
3edf6c7d3cf7bb9ed9efd0410c95289955206e15 | Egorova-Viktory/python-training | /12.7.3.py | 390 | 3.875 | 4 | per_cent = {'ТКБ': 5.6, 'СКБ': 5.9, 'ВТБ': 4.28, 'СБЕР': 4.0}
money=int(input("Введите сумму под проценты:"))
per_cent_list=list(per_cent.values())
deposit=[i*money/100 for i in per_cent_list]
print(deposit)
max_deposit=max(deposit)
print("Максимальная сумма, которую вы можете заработать:", max_deposit) |
d35fcdef487598200f2b7df01ef00a695d0e6e51 | fentonjamie/Udemy_Python_Challange1 | /main.py | 829 | 3.875 | 4 | true = 0
love = 0
name1 = input("Type the first name here: ")
name2 = input("Type the second name here: ")
name1Cap = name1.upper()
name2Cap = name2.upper()
TotalName = name1Cap + name2Cap
for element in TotalName:
if element == "T":
true += 1
elif element == "R":
true += 1
elif element ... |
5f76a63a73977b633e0456fcb9a53f76884fe303 | jsavage6/Fin-6320 | /Fin-6320/Assignment 2/coin flip.py | 504 | 3.875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon Feb 20 21:27:12 2017
@author: Joshua
"""
import random
total_heads = 0
total_tails = 0
count = 0
while count < 10000:
coin = random.randint(1, 2)
if coin == 1:
#print("Heads!")
total_heads += 1
count += 1
... |
54fa038de5119ab9c63fa101e2cd702ec2b33c8d | pkgauta/Incubyte-test-task | /process.py | 3,256 | 4 | 4 | import csv
import sqlite3
filename = 'input.csv'
dbname = 'test.db'
def initialize_db():
conn = sqlite3.connect(dbname) # creates db connection
return conn
def close_db( conn):
conn.close() # close connection from db
return True
def create_table( conn, table_name):
query = f'''CREATE TABL... |
336c41c08508a1162dd9c605ea32a4d2ec4ca06c | Tulip4attoo/coding-dojo | /project_euler/problem02.py | 368 | 3.859375 | 4 | #class fib(object):
#def fibonacci():
n = int(raw_input("Moi ban nhap so n: "))
fib = [1, 2, 3]
k = 2
l = 0
while l < n:
l = fib[k - 1] + fib[k]
fib.append(l)
k = k + 1
print "So Fibonacci lon nhat nho hon %d la: %d" % (n, fib[k - 1])
#fib.fibonacci
sum = 0
for x in xrange(k):
if x % 3 == 1:
s... |
bccd4a96b06d10c455cc8906d04c79ea40f33e81 | Tulip4attoo/coding-dojo | /project_euler/problem06.py | 250 | 3.671875 | 4 |
def sum_square(floor):
return (floor - 1) * floor * (floor + 1) / 3 + floor * (floor + 1) / 2
def square_sum(floor):
return (floor + 1) ** 2 * floor ** 2 / 4
k = int(raw_input("nhap k: "))
print "%d" % (square_sum(k) - sum_square(k)) |
ca8cb180e30914f5983562b375d09c0ed5bdfc5c | Tulip4attoo/coding-dojo | /project_euler/problem-56.py | 320 | 3.828125 | 4 |
def digit_sum(number):
dumb_list = list(str(number))
dumb = 0
for i in dumb_list:
dumb = dumb + int(i)
return dumb
max_digit_sum = 0
for a in xrange(10, 100):
for b in xrange(10, 100):
a_power_b = a ** b
if max_digit_sum < digit_sum(a_power_b):
max_digit_sum = digit_sum(a_power_b)
print max_digit_sum
|
23bf854e06aa0ca210112520ec738b359768c6c8 | Tulip4attoo/coding-dojo | /project_euler/problem-15.py | 197 | 3.640625 | 4 | number = 0
def factorial(ceiling):
temp_value = 1
for order in xrange(1, ceiling + 1):
temp_value = temp_value * order
return temp_value
print factorial(40) / (factorial(20) * factorial(20)) |
dd2379aaf2ceec1c8ce2874c5a57903861ca243e | Tulip4attoo/coding-dojo | /project_euler/problem-120.py | 338 | 3.734375 | 4 | import time
start_time = time.time()
sum_value = 0
# just explore the (a + 1) ** n + (a - 1) ** n
# we find the remain is 2 * n * a or 2
# so we calculate the a from n - so much easy
for n in xrange(3, 1001):
sum_value = sum_value + ((n - 1) / 2) * n * 2
print sum_value
print("--- %s seconds ---" % (time.time()... |
d986a7ff9ab4571f3cf0b404f6b524f9049c1e2b | Tulip4attoo/coding-dojo | /codefights/dojo.py | 32,464 | 3.765625 | 4 |
def find_short(s):
# your code here
word = s.split(" ")
lenList = map(len, word)
return min(lenList)
def longest_consec(strarr, k):
n = len(strarr)
longestString = ""
maxLen = 0
if (n == 0) or (k > n) or (k <= 0):
return longestString
for ind in xrange(0, n - k + 1):
... |
96d0c6a2974a42504755c76aa4a74c06795399c7 | Le6790/StockTracker | /getTime.py | 2,945 | 3.921875 | 4 | import time
#string returns the current time in 2018-06-29 11:37:00 format
def getCurrentTime():
localtime = time.localtime(time.time())
year = str(localtime[0])
month = '%02d' % localtime[1]
day = str(localtime[2])
hourEST = str(format(localtime[3] + 2,'02d')) #MST to EST
#TODO not sure why I... |
e7d9bf1216194e6a97fcf1a45a6c7fdc90cb8b9b | KayTate/BOMB_Bank_Simulation | /complaint.py | 22,208 | 3.71875 | 4 | def complaint_to_man():
print('''
Finding the service at the Bank of Mashed Beats less than desireable, you decide to speak with the manager of B.O.M.B.
You glare at the employee who has given you such rudimentary service and demand that you speak to the manager.
The employee stares back at yo... |
38eb21c057b90105afde6dc9c9a2c7bfe33127c4 | bryanhoulton/PyNet | /stocks.py | 2,054 | 3.5 | 4 | import pynet
import os, numpy
import yfinance as yf
import matplotlib.pyplot as plt
#get initial data
ticker = yf.Ticker('MSFt')
raw = [i[1] for i in ticker.history(period='max').to_numpy()]
# split raw into sets of 5 days to train the network with
c = 0
split_raw = []
temp = []
for i in raw:
if c < 5:
... |
cde841b9e4320dcb67c2f27b667274ede1aa4c80 | Eslee30/BasicPython | /TugasAkhir.py | 7,532 | 4.125 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[64]:
#KALKULATOR
def select_operation():
print()
print("---Select operation---")
print("1. Add")
print("2. Subtract")
print("3. Multiply")
print("4. Divide")
print("5. Exit")
def calculator():
while True:
select_operation()
... |
950dfeb1bc776d88e734cb3d08d3dc28ad3358f0 | Gaurav-Adlakha/MACHINE-LEARNING | /linear regression with numpy.py | 4,314 | 3.8125 | 4 |
# coding: utf-8
# In[1]:
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
from plotly import __version__
from plotly.offline import download_plotlyjs,init_notebook_mode,plot,iplot
import cufflinks as cf
get_ipython().run_line_magic('matplotlib', 'inline')
init_notebook_mo... |
deaa2ff835295843f80f39706b00a64fb4a3c316 | PrajwalChigod/find_restaurant | /find_restaurant.py | 3,531 | 3.859375 | 4 | '''
Name : find_restaurant.csv
Description : Find restaurant that are open
Input : CSV file & time
output : list of restaurant that are open duirng the time
usage : python - <filename.py> <datetime>
example - execute the script - enter input as prompted
restaurant.csv
01-12-2018 9:45 am
author : Prajwal Ch... |
185e71e61ec59c74410b502abd6f284ee1a0005a | armadanasar/ctci | /bab2/kthlast.py | 1,346 | 3.703125 | 4 | class Node():
def __init__(self, data):
self.data = data
self.next = None
def create_ll(arr):
result = None
head = None
print(arr)
for i in range(len(arr)):
n = arr[i]
if head:
head.next = Node(n)
head = head.next
if not result:
... |
f6721271db9e801c4f0008e7ab474159da5a78d3 | armadanasar/ctci | /bab1/nulllifyArray.py | 678 | 3.5 | 4 | input = [[1, 2, 3], [4, 0, 6], [7, 8, 9]]
def nullify(input, i, j):
for x in range(len(input)):
input[x][j] = 0
for y in range(len(input[0])):
input[i][y] = 0
def nullify_array(input):
arr_res_flag = [[False for i in range(len(input[0]))] for j in range(len(input))]
for i in range(len... |
2ef39eba8791671bf6fadb79f8f1ace7dcf2fc0e | yassinhc/Building_digital | /building_map/library/convex_hull.py | 3,770 | 4.09375 | 4 | import numpy as np
from math import atan2
def lowest_coordinate(points):
""" Returns the anchor point (pt with the lowest coordinates) in a list of points
Parameters
----------
points : numpy array of 2D
array of points
Returns
-------
numpy array of 1D
anchor point of th... |
cd874afd70e53cf0ec275c4f6fb10a407b3a46b0 | echushe/COMP9318 | /lab1/lab1/submission.py | 2,880 | 3.671875 | 4 | ## import modules here
################# Question 0 #################
def add(a, b): # do not change the heading of the function
return a + b
################# Question 1 #################
def nsqrt(x): # do not change the heading of the function
if (x < 2):
return x;
else:
small = nsq... |
acaccd3a887e409a5c03f8c16a58356b638605f7 | misagh1999/MyPythonExamples | /HelloWorld.py | 116 | 3.578125 | 4 | #--- Hello World Program
n=raw_input("please enter your name: ")
print "hello how are you"
print "I am a develoer"
|
4865bd40f50f7cf4fd81a0975b09f8c7bfc92ce9 | amitkji/asssignmentsubmission | /day1.py | 451 | 3.984375 | 4 | #AUTHOR AMIT hash used for single line comment
''' triple quotes used for multiline comment'''
print("HI I AM AMIT")
print('''u need to put triple quotes for
multiline string''')
a="amit"
b=123
c=1.2
d=10
e=5
print("the value of 10+5 is",10+5)
print("the value of 10-5 is",10-5)
print("the value of 10*5 is"... |
ec094d809089a6cff9ded0f6cd4a10e98a698e60 | rstrozyk/codewars_projects1 | /#8 alternate_capitalization.py | 673 | 4.28125 | 4 | # Given a string, capitalize the letters that occupy even indexes and odd indexes separately, and return as shown below. Index 0 will be considered even.
# For example, capitalize("abcdef") = ['AbCdEf', 'aBcDeF']. See test cases for more examples.
# The input will be a lowercase string with no spaces.
# Good luck!
d... |
94860038523d7e506eade97148024d69f942b4ae | Filipe-V/python-fil | /w24a2.py | 1,298 | 3.890625 | 4 | #------------------------------------------------------------------------------------------
# week 2, assignment 2: count organizations using file mbox.txt as input
#------------------------------------------------------------------------------------------
import sqlite3
import urllib
conn = sqlite3.connect('bd1.sqli... |
5414afab0d07c13b67d07aa26c67f3e15e9bf313 | Jean-Marcos-Amaro-Barbosa/LP-Atividade-2 | /Atividade 2 LP/Code4.py | 342 | 3.625 | 4 | def primo(n):
if n > 1:
for v in range(2,n):
if n % v == 0:
return False
return True
def exibir():
n=100
for v in range(1,n+1):
if(primo(v)):
print("O número",v,"é Primo!")
else:
print("O número",v,"Não é Primo... |
ae62950d230db005e0e6ed583f908d647f9858f3 | ZachBarbre/week_1_python | /prompt_for_number.py | 181 | 4.28125 | 4 | # run a program that prompts the user for a number
# and multiples that number by itself
user_input = int(input("Please enter a number: "))
result = user_input**2
print(result) |
5c3a75d5b06dd882db056991b0e23e4854c4ee06 | ZachBarbre/week_1_python | /tip_calc.py | 567 | 4.03125 | 4 | bill_amount = float(input("Total bill amount? "))
service_level = input("Level of service? ")
if service_level == 'bad':
tip = bill_amount * 0.1
total = bill_amount + tip
print("Tip amount: $%.2f" % tip)
print("Total amount: $%.2f" % total)
elif service_level == 'fair':
tip = bill_amount * 0.15
... |
ed5ca5468a116d179954138048409b367256ac57 | JaykeMeijer/UvA | /Beeldbewerken/Exercise 3/find_waldo.py | 2,377 | 3.609375 | 4 | # This is the final part of exercise 3 of 'Beeldbewerken'.
#
# This program highlights the spots where Waldo is most likely to be in an
# image. To do this, it uses the so called "Backprojection" algorithm, as
# described in "Indexing Via Color Histograms" by Michael J. Swain and Dana
# H. Ballard.
#
# Authors: Jayke M... |
17c3f27b503eb741523b0d1b54721a8e1b0e9392 | xJINC/HBL | /Practical1G.py | 1,429 | 3.734375 | 4 | import random
def score_list_generator(minvalue, givenvalue, maxvalue):
lower_score_list = list(range(minvalue, givenvalue))
score_list = []
for i in range(0, 5):
score = random.choice(lower_score_list)
lower_score_list.pop(lower_score_list.index(score))
score_list.append(score)
higher_sc... |
b7e3e0afd4da5ae3f89c518571cdd304acb8354c | OAbouHajar/What_Is_Programming | /day_4/while.py | 565 | 4.03125 | 4 | from datetime import datetime
# while loop to print while the i is less than 10
# i = 0
# # infinity loop - very bad code written:
# while i < 10:
# print(i)
# i = 1
# while i <= 10:
# print(i)
# i += 1
# takes the users names and exit when we enter x as an input
name = input("please enter the name: "... |
3b200bfc3b399b557578ba9d242899ecb5660de4 | OAbouHajar/What_Is_Programming | /extra_4/list.py | 731 | 3.984375 | 4 | # thisislist = ['osama','sa','jack']
# # we can have list of list
# # like shopping list (Lidl) (Aldi) (Tesco).... etc
# # print(thisislist[0])
# thisislist.append('doo')
# # students
# # results
# #
# shopping_lists = [
# ['toast', 'tea','coffe'], #pos 0
# ['tomatos'... |
6b6f4fce74fc49282d2de29e8dfe348e129b62a3 | OAbouHajar/What_Is_Programming | /day_2/exe1_var.py | 318 | 3.921875 | 4 | name = "Osama"
age = 28
email = "oabouhajar@hotmail.com"
is_student = True
blood_group = 'A+'
# user input for today var
today = input("What is Today? ")
print("Hello:" , name)
print("Happy", today)
age = input("Enter your age please! ")
# Print user input
print("Enjoy your",age)
print("Your age input result is: "... |
26e5725ef1c6eccd3a03d8ede119ed27195a26ba | some-coder/machine-learning-c16 | /learners/learner.py | 1,154 | 3.796875 | 4 | import numpy as np
from preprocess import RecordSet
class Learner:
"""
Establishes a base class from which learning algorithms can extend.
"""
def __init__(self, **params: any) -> None:
"""
Constructs a base learning algorithm.
:param params: Parameter values to supply.
"""
self.name: str = 'Base Lear... |
9f24e87f6c2f223fd243b96ae47a7a7224a75c7f | some-coder/machine-learning-c16 | /learners/svm.py | 1,595 | 3.890625 | 4 | import numpy as np
from learners.learner import Learner
from preprocess import RecordSet
from sklearn import svm
class SVM(Learner):
"""
The Support Vector Machine (SVM) algorithm. Given data, this class
projects data in a relatively high-dimensional space, allowing new
points to be classified linearly via a larg... |
819facef479402c2acba63fcfe7fe20031a3e904 | falenl/password-locker | /main.py | 2,531 | 3.546875 | 4 | #!python
import sys, getpass, shelve, pyperclip
from keytool import *
from user import *
userName = getpass.getuser()
shelfFile = shelve.open('data/data')
passed = False
while not passed:
pwd = getpass.getpass("User Name : %s\nPassword:" % userName)
keytool = Keytool(pwd)
keytool.loadKeyFrom... |
596c36a9448843d475a36298c307c9c90339f6bb | danineamati/Fun-Projects | /Machine Learning/ML_Digits.py | 1,371 | 3.875 | 4 | # First Machine Learning Practice File
# Daniel Neamati
# 10 September 2018
import numpy as np
from sklearn import datasets
from sklearn.cluster import KMeans
import matplotlib.pyplot as plt
class digitsML_model():
""" This serves a wrapper for the sklearn KMeans model for
unsupervised learning."""
def __init__(... |
e7202d2cf6e3080e556cec87c859d2a4f44c2ed5 | MingfeyZui/Smpro_Private | /hw9/mingfei/noun_similarity.py | 1,187 | 3.6875 | 4 | import nltk
from itertools import combinations
from collections import Counter
from nltk.corpus import wordnet as wn
def leave_odd_man_out(words):
#TODO find the odd man in the list of words: use get_similarity_scores() method
pass
def get_similarity_scores(pairs):
results = []
f... |
e2ec12cfa864dec4c9235df057ce63ec8bece4de | MingfeyZui/Smpro_Private | /hw9/Leo/noun_similarity.py | 1,157 | 3.703125 | 4 | import nltk
from itertools import combinations
from nltk.corpus import wordnet as wn
from collections import Counter
def leave_odd_man_out(words):
#TODO find the odd man in the list of words: use get_similarity_scores() method
pass
def get_similarity_scores(pairs): # path_similarity
results = []
fo... |
d453bd58cbe984e71f400ce2cc86655a000671cc | Kunal-Kumar-Sahoo/mail-bot | /mailBot/database.py | 1,001 | 3.546875 | 4 | import mysql.connector #pip install mysql-connector-python
client = mysql.connector.connect(host="localhost", user="root")
mycursor = client.cursor()
def create_database_and_table(database_name, table_name, schema):
try:
mycursor.execute(f"CREATE DATABASE IF NOT EXISTS {database_name}")
mycursor.e... |
d1b10f27c5c44b2f4dba6a30e7f7d39e13b2ec2a | XiaoR128/MachineLearning | /逻辑回归/代码含readme/logistic_mydata.py | 7,629 | 3.609375 | 4 | # 利用自己生成的数据进行测试
from numpy import *
import numpy as np
import matplotlib.pyplot as pt
# 从文档中读取数据
def readdata():
filename = 'mydata.txt'
X = [] # 属性的数组
Y = [] # 类别(用0或者1表示)
read = open(filename)
for line in read.readlines():
readin = line.strip().split()
size = len(readin)
... |
1a84de296000421f725a38ef905ab5f590d085ac | SanghamitraDutta/dsp | /python/markov.py | 2,440 | 4.5625 | 5 | #!/usr/bin/env python
# Write a Markov text generator, [markov.py](python/markov.py). Your program should be called from the command line with two arguments: the name of a file containing *text to read*, and the *number of words to generate*. For example, if `chains.txt` contains the short story by Frigyes Karinthy, w... |
9683b384ba5d508feadb81df61c90444f96cb402 | ashleybm/Cplusplus_CodeSmell_Visualization | /src/DataStructure.py | 10,619 | 3.765625 | 4 | import CodeParse
# Expressions are a list of segments that do not have relevance
# to the structure of the actual code. Generally, these also
# do not affect our code smell identification.
class Expression:
segments = list()
def __init__(self, segments):
self.segments = segments.copy()
def __eq__(... |
78c665c799597840fa864ced72367c87a426ecea | bhargavssbt38/Python_CyberSecurity | /file_search.py | 342 | 3.78125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Aug 8 21:52:49 2018
@author: bharg
"""
import re
import os
filename = raw_input("Enter the file name that you want to search for")
root,dirs,files= os.walk(os.getcwd())
pattern=re.compile(str(filename))
for i in files:
if(re.search(pattern,i)):
print " The file e... |
88ed1aed4ad37195d876538e0583880272a1371e | johnnyriverz/Neural-Network-Class | /neural_network.py | 1,344 | 3.75 | 4 | import numpy as np
class NeuralNetwork():
def __init__ (self):
np.random.seed()
self.synaptic_weights = 2 * np.random.random((3,1)) - 1
def sigmoid (self, x):
return 1 / (1 + np.exp(-x))
def sigmoid_derivative (self, x):
return np.exp(-x) / (pow((1 + np.exp(-x)),2))
def train (self,traini... |
0cfe1baf36f13b7646768c4e524e041152f21c79 | minhthe/algo-and-ds-practice | /Codility/02_array/02_missingNumber.py | 315 | 3.5 | 4 | # you can write to stdout for debugging purposes, e.g.
# print("this is a debug message")
#https://app.codility.com/demo/results/training6FDFVU-76B/
def solution(A):
# write your code in Python 3.6
missing_number = A[0]
for i in range(1, len(A)):
missing_number ^= A[i]
return missing_number |
f7827a6ecbcdd2cba6dfcb336bf0720b170c9fe7 | minhthe/algo-and-ds-practice | /BST/01_isSymmetric_Iteration.py | 868 | 4.09375 | 4 | '''https://leetcode.com/problems/symmetric-tree'''
import collections
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def isSymmetric(self, root: TreeNode) ... |
a440a047f8c10c8f531e9521d1e19c867ecdcfd1 | minhthe/algo-and-ds-practice | /sort/04_sort_2.py | 371 | 3.609375 | 4 | import collections
class Solution:
def frequencySort(self, s: str) -> str:
mp = {}
for c in s:
if c not in mp:
mp[c] = [-1, c]
else:
mp[c][0] -= 1
rst = ""
for k, v in sorted(mp.items(), key = lambda x: x[1]):
... |
34baa9067ee20a309bfb16ef2a0f970910170677 | jaxmandev/Python_Exercises | /YOB_task.py | 597 | 4.09375 | 4 | # Part 1
age = 34
name="Zizou"
year= 2020 - 34
print("OMG {}, you are {} years old so you were born in {}".format(name,age,year))
# Part 2
from datetime import datetime
name=input("Please enter your name: ")
age=int(input("Please enter your age: "))
DOB=input("Please enter your DOB in the format dd-mm-yyyy")
if int(... |
474d390da86fde4adee48437818a764632085498 | galengineer/Weekly-Life-Hack-with-Python | /1_simple_calculator.py | 333 | 3.796875 | 4 | # Weekly Life Hack using Python
# 1 - Simple Calculator
# galengineer.com
# April 2019
def addition(nX, nY):
sum = nX + nY
print("Sum of {0} and {1} is {2}".format(nX, nY, sum))
def main():
while True:
print("Enter nX value: ")
nX = int(input( ))
print("Enter nY value: ")
nY = int(input( ))
addition(nX... |
f4f725b16bfd002f1fdd51d16fc49d2f91c3fd7f | elise-lee/dns-centralization | /scripts/cdn_analysis.py | 4,073 | 3.59375 | 4 | import json
import csv
import os.path
from os import path
import matplotlib.pyplot as plt
def read_json(filename):
with open(filename) as json_file:
data = json.load(json_file)
return data
countries=[]
def get_countries_from_csv(filename):
with open(filename) as csv_file:
csv_reader = csv.reader(... |
5e4d70f4220865b55220cabb7e0afedad80a8241 | luicitoDC/Machine-Learning-From-The-Ground-Up | /mlgroundup/supervised/polynomial_features.py | 4,882 | 3.796875 | 4 | # Created by Tristan Bester
import numpy as np
class PolynomialFeaturesForDegree():
'''
Calculates the polynomial features of a dataset for a given degree.
Args:
degree (int): The degree of the polynomial features to be calculated.
Attributes:
degree (int): The degree of the ... |
18709988ddb953d0a379a447c2ac35dae91cd0d1 | luicitoDC/Machine-Learning-From-The-Ground-Up | /mlgroundup/examples/k_means_example.py | 563 | 3.703125 | 4 | # Created by Tristan Bester.
from mlgroundup.clustering import KMeans
from sklearn.datasets import make_blobs
import matplotlib.pyplot as plt
# Create data set.
X,_ = make_blobs(500, 2, 2, 5, random_state=42)
# Calculate clusters.
km = KMeans(n_clusters=5, n_iters=10)
km.fit(X)
# Calculate the cluster to which eac... |
43765f46f63810f0005828b5d59aac7b2fc5e90a | DJ-Yang/algorithm | /backjoon2581.py | 682 | 3.578125 | 4 | import math
import sys
num1 = int(input())
num2 = int(input())
z = num2 - num1 + 1
max_int = num2 + 1
sqrt_int = int(math.sqrt(max_int))
prime_bool = [1] * (max_int)
prime_list = []
# 에라토스테네스의 체
def check_prime():
prime_bool[0] = 0
prime_bool[1] = 0
a = 2
while a <= sqrt_int:
if prime_bool[a] == 1:
... |
311d28c949feae88713b119de5f29face6b551a1 | DJ-Yang/algorithm | /backjoon2446.py | 310 | 4.0625 | 4 | n = int(input())
for i in range(1, 2*n):
if i <= n:
for a in range(1, i):
print(' ', end='')
for a in range(i, 2 * n - i + 1):
print('*', end='')
else:
for a in range(1, 2 * n - i):
print(' ', end='')
for a in range(2 * n - i, i + 1):
print('*', end='')
print('') |
ee97c1ddba9b522429be0090efdd34e4713e4de1 | mthompson-CU/Thompson_CSCI3202_Assignment3 | /Thompson_CSCI3202_Assignment3.py | 1,317 | 3.859375 | 4 | # Author: Matthew Thompson
# IdentiKey: math1906
# Date: September 15, 2015
# Assignment 3
import sys
import AStarNode
def discoverNeighbors(node, world):
return
# inspired by http://theory.stanford.edu/~amitp/GameProgramming/Heuristics.html
def calculateManhattan(node, goalNode):
distance = 0
currentNode = node
... |
14f4b6abd789bffaf54ab8587be22f13dd87e572 | j721/cs-module-project-recursive-sorting | /src/searching/searching.py | 1,128 | 4.4375 | 4 | # TO-DO: Implement a recursive implementation of binary search
def binary_search(arr, target, start, end):
# Your code here
middle = (start +end)//2
if len(arr) == 0:
return -1 #empty array
#if target is equal to the middle index in the array then return it
if arr[middle] == target:
... |
a563eb397a7de92dc9cc4fc18e5b7a1a333d4f69 | Codemonkey2020/pythonprojects | /Tutorials/tuples.py | 197 | 3.75 | 4 |
coordinates = (4, 5)
print(coordinates[1])
#tupples are immutable(cant be changed) .
#but one could make multiple tupples inside a list.
bing = [(6, 7), (0, 6), (-9,2)]
bing[1] = 9
print(bing)
|
c30e0295c9c6c057032936a22b8f6668d9c18fc4 | eyecode4you/Membership-GUI-App | /Init/init_member_db.py | 856 | 3.828125 | 4 | """ init_member_db.py - Use schema.sql to create initial member db
Create a simple database to use with Membership app """
import sqlite3
connection = sqlite3.connect('members.db')
with open('schema.sql') as f:
"""Open our created sql schema & execute for initial db structure"""
connection.executescript(f.read())
cu... |
570b85577fcc8343c1d9fa11d8e0bd95eb3a4e3f | kulsuri/playground | /daily_coding_problem/solutions/problem_9.py | 611 | 4.1875 | 4 | # Given a list of integers, write a function that returns the largest sum of non-adjacent numbers. Numbers can be 0 or negative.
# For example, [2, 4, 6, 2, 5] should return 13, since we pick 2, 6, and 5. [5, 1, 1, 5] should return 10, since we pick 5 and 5.
def largest_sum(l):
inclusive = 0
exclusive = 0
... |
4ecf79677118a95f24d80fe0ead4272e8f61eeec | kulsuri/playground | /udemy-11-essential-coding-interview-questions/1.1_arrays_most_freq_no.py | 911 | 4.21875 | 4 | # return the most frequent element in an array in O(n) runtime
def most_frequent(given_array):
# insert all elements and corresponding count in a hash table
Hash = dict()
for c,v in enumerate(given_array):
if given_array[c] in Hash.keys():
Hash[given_array[c]] += 1
else:
... |
e5414f722cf45d8d5781bd52c84e2c4222a5a0c8 | kulsuri/playground | /leetcode/e_missing_number.py | 414 | 3.921875 | 4 | # Given an array containing n distinct numbers taken from 0, 1, 2, ..., n, find the one that is missing from the array.
# e.g. [3, 0, 1] -> 2
def missingNumber(nums):
Hash = dict()
for c,v in enumerate(nums):
Hash[v] = c
for i in range(len(nums)+1):
if i not in Hash:
retu... |
b709fcaa9f417b10525165e357cbf8dce725854b | kulsuri/playground | /daily_coding_problem/solutions/problem_11.py | 1,044 | 3.5 | 4 | # Implement an autocomplete system. That is, given a query string s and a set of all possible query strings, return all strings in the set that have s as a prefix.
# For example, given the query string 'de' and the set of strings [dog, deer, deal], return [deer, deal].
# Hint: Try preprocessing the dictionary into a ... |
fb6688a3de0312f72db5a9cd0d969b87cacae253 | kulsuri/playground | /daily_coding_problem/solutions/problem_13.py | 953 | 4 | 4 | # Given an integer k and a string s, find the length of the longest substring that contains at most k distinct characters.
# For example, given s = "abcba" and k = 2, the longest substring with k distinct characters is "bcb".
def longest_substring(k, s):
Hash2 = dict()
for y,v in enumerate(s):
dis... |
925d6ce637e9517d99cd0bd8b3d1729ac7dd1b65 | JieMing02/DPL5211Tri2110 | /lab2.3.py | 217 | 4 | 4 | #Student ID : 1201200787
#Student Name : Too Jie Ming
celsius=int(input("Please Enter the value of kilogram: "))
fahrenheit= (celsius*9/5)+32
print("For ",celsius," celsius is equivalent to ",fahrenheit, "fahrenheit") |
8506f36332e611840732428538c28619a8047631 | fariya-banu234-au7/computer-science | /graphs/python/weighted_graph.py | 2,387 | 3.71875 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
from typing import List, Dict, TypeVar, NamedTuple, Set
# types
VertexType = TypeVar('VertexType', # Any hashable object
str, int, float, complex, str, tuple, frozenset, bytes)
Stack = List
class Edge(NamedTuple):
"""The weighted edge structure.... |
49d825af8df6ad98dfc3b842a63a2777b29e3761 | soareslucas/DistProgPython | /BasicoSocket/ClientEcho.py | 801 | 3.53125 | 4 | '''
Created on 22 de abr de 2019
@author: lsrodrigues
'''
import socket
HOST = '127.0.0.1' # The server's hostname or IP address
PORT = 65432 # The port used by the server
# text = input("Insira sua mensagem:");
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
nome =... |
aaf71f45a4fae1def255e9bf6f42d85cea688838 | gloomyline/my-note | /python/22_week_1_July/input_and_output.py | 3,450 | 4.125 | 4 | # -*- coding: utf-8 -*-
import math
from datetime import datetime
## Fancier Output Formatting
# 1. Formatted String Literals
year = datetime.now().strftime('%Y')
event = 'Freedom'
print(f'Results of {year} {event}')
print('-' * 40)
# 2. The str.format() method of strings requires more manual effort
yes_votes = 42_5... |
56e7789689fd58910e875a2cb157b9d6b851282c | FayeLee303/ComputerVision | /OpenCv Test/cv_03.py | 2,091 | 3.59375 | 4 | """
通道的分离与合并
"""
import cv2 as cv
import numpy as np
import matplotlib.pyplot as plt
image = plt.imread('../images/lena256.jpg')
# 三通道分离形成单通道图片
b, g, r = cv.split(image)
# 注意分离出来时单通道,图片是灰色的!!!
plt.subplot(2, 3, 1), plt.imshow(b), plt.title('b')
plt.subplot(2, 3, 2), plt.imshow(b), plt.title('g')
plt.subplot(2, 3, 3)... |
a51df4021f09d7bd8d082feab10d89a8f742f2e4 | friggstad/cmput304_code | /dynamic_programming/tree_matching/tree_matching.py | 2,146 | 3.59375 | 4 | # Maximum-weight matching in a tree in O(n) time.
# Input assumes nodes are numbered 0 through n-1, 0 is the root,
# and node i has parent < i
#
# So the input consists of n
# and then n-1 pairs (p, w) where for the i'th pair (1 <= i <= n-1)
# we have p is the parent of node i and the edge has weight w
import sys
# -... |
3e29051bde4fcf232d20bd0cec1bc2ae33f1358b | friggstad/cmput304_code | /divide_and_conquer/closest_points/closest_points.py | 2,498 | 3.875 | 4 | # Closest pair of points in O(n log^2 n) time
# points are represented as a tuple of coordinates: (x, y)
#
# The textbook discusses how to get it down to O(n log n) time but it takes
# extra work coding. I won't bother unless someone really wants to see it,
# but I am happy doing it if someone is actually interested (s... |
07d0eb183fcc1f3fd342e785a743043658114649 | kylebush1986/CS3080_Python_Programming | /Homework/Homework_3/hw3_kyle_bush_ex_3.py | 1,708 | 4.4375 | 4 | '''
Homework 3, Exercise 3
Kyle Bush
9/21/2020
This program stores a store inventory in a dictionary.
The user can add items, delete items, and print the inventory.
'''
def printInventory(inventory):
print()
print('Item'.ljust(20), 'Quantity'.ljust(8))
for item, number in inventory.items():
print(i... |
d93755a6403cbf43542200e86fbf03f51463b7eb | kylebush1986/CS3080_Python_Programming | /Homework/Homework_7/lucky.py | 1,867 | 3.859375 | 4 | '''
Homework 7, Exercise 3
Kyle Bush
11/23/2020
Here’s what the program should do:
1. Read the command line arguments as the search term that you’ll use in Google.
2. Fetch the search results page with the requests module, then open the results to
inspect.
3. Find the links to each search result. Then call webbrowser.o... |
1270188cab6e1d289056abee5013a4f729bfb40d | justinDeu/path-viz | /algo.py | 1,273 | 4.40625 | 4 | from board import Board
class Algo():
"""Defines an algorithm to find a path from a start to an end point.
The algorithm will be run against a 2D array where different values
signify some state in the path. The values are as follows:
0 - a free cell
1 - a blocked cell (cannot ... |
18997481d5174803a1be1aa3c7ab006822073039 | sgzwiz/brython | /tests/test_import.py | 289 | 3.6875 | 4 | import simple
class Simple2:
def __init__(self):
self.info = "SimpleClass2"
class Simple3(simple.Simple):
def __init__(self):
simple.Simple.__init__(self)
text = "text in simple"
print(simple.text == text)
_s=simple.Simple()
_s3=Simple3()
print(_s.info==_s3.info)
|
87263f290bc504cd792eac58324809055e89beb4 | KarlKo1/prog_alused | /2/yl2.4.py | 568 | 3.890625 | 4 | from random import randint
seat = ""
choice = input("Kas soovite istekohta ise valida (\"ise\") või loosida (\"loos\")?")
if choice == "ise":
win_or_else = input("Kas soovite istud akna ääres (\"aken\") või mitte (\"muu\")? ")
if win_or_else == "aken":
print ("Valisite ise. Aknakoht")
else:
... |
d79bc6cf1c72cad97a529bbdb70b83e87771292b | marcelomanchester/pythonTraning | /python/louça.py | 4,095 | 3.578125 | 4 | class node():
def __init__(self, dado):
self.__dado = dado
self.__anterior = None
self.__proximo = None
def getDado(self):
return self.__dado
def setDado(self, novoDado):
self.__dado = novoDado
def getAnterior(self):
return self.__anterior
def setA... |
4e0c7f671559877b86b7bf41f2722f72aeffe7bd | marcelomanchester/pythonTraning | /python/TasksDone/apenas1for.py | 167 | 3.59375 | 4 | string = 'marcelo'
def substring (s):
p = ''
for x in range (len(s)):
p += s[x]
print (p)
if (len(s)) > 1:
substring(s[1:])
substring(string)
|
8831f5b685e33f5a07b957814509305f7c9cec3e | OtacilioN/cesar-school-fp-lista-de-exercicios-02-OtacilioN | /questoes/questao_2.py | 1,087 | 4.0625 | 4 | ## QUESTÃO 2 ##
# Uma forma de avaliar se uma pessoa está acima do peso é através do calculo do índice IMC.
# Se o valor do IMC estiver acima de 25, significa que a pessoa está acima do peso.
# A fórmula é: IMC = Peso(Kg) / (Altura(m)*Altura(m)). Com base na altura e peso fornecido no
# console exiba uma mensage... |
5d3f9ba65e4c68e743ea21a0db8dbbb54c92bd6f | prahate/python-learn | /python_classes.py | 926 | 4.21875 | 4 | # self is defined as an instance of a class(similar to this in c++),and variables e.g. first, last and pay are called instance variables.
# instance variables are the ones that are unique for each instance e.g. first, last and pay. They are unique to each instance.
# __init__ is called as constructor(in languages like ... |
e9d4a5afa1859ec6b3ad87a3000bee910afef669 | prahate/python-learn | /python_sqlite.py | 698 | 4.5 | 4 | import sqlite3
# Creating a connection sqlite database, it will create .db file in file system
# other way to create is using memory, so database will be in memory (RAM)
# conn = sqlite3.connect(':memory:')
conn = sqlite3.connect('employees.db')
# To get cursor to the database
c = conn.cursor()
# Create table using... |
107f687dfd91928b5d20a1627f513fb843bfd830 | minimusent/HelloWorld | /skill_app/test.py | 265 | 3.875 | 4 | while True:
answer = input()
if answer in ('y', 'n', 'N', 'Y'):
break
else:
print ('Invalid input.')
if answer == 'y':
break
elif answer == 'Y':
break
else:
print('Goodbye')
break |
5ddf61c978faeff648e9d73a846ae1bc93df8588 | wangineer/lpthw | /Readfilecisco/read-file.py | 907 | 3.625 | 4 | #This file reads line by line and applies attribute to it.
#To run
#python read-file.py
file = open('dev-01-info', 'r')
name = file.readline().strip()
ip_address = file.readline().strip()
os_type = file.readline().strip()
username = file.readline().strip()
password = file.readline().strip()
print('device name: ',n... |
eb7faa54abb92fcfd8eb0d5e2a4c00406dda6c0f | wangineer/lpthw | /ex13-Parameters_Unpacking_Variables.py | 877 | 3.71875 | 4 | # argv stands for argument varialble or vector
#allows you to use commandline arguments like "ls ex1*.py note the use of the astrisk after the ex1
# from Sys "system" module import the argv feature.
#python -m pydoc sys
#argv -- command line arguments; argv[0] is the script pathname if known
from sys import argv
# re... |
1b1f2a489667a63f905a47da921ad9674bd71d94 | Old-Shatterhand/MSADRL | /utils/hash_q_table.py | 1,550 | 3.609375 | 4 | import numpy as np
from utils.utils import hash_state
class HashQTable:
def __init__(self, num_seqs):
"""
Initialize the Q-Table as a wrapper around a dictionary. The reason is that the state-space is (n^(n+1)-1)/(n-1)
But these many states are never visited in the small amount of games p... |
aaca7d1a2ae7cb07b50d8f179f306d5375c9703a | mertmtn/PythonNotes | /MainTopics/variables.py | 286 | 3.734375 | 4 | x=0
print(x)
#Re define to variable
x="abc"
print(x)
#strongly typed language
#print("This is a string "+123)
#Global variable & Local variable
def func():
x="def"
print(x)
#Get different value of x
func()
print(x)
del x #deleted of the definition of the variable
print(x) |
32869af56049f486ee7edf5fb385073a711fe243 | kiasf159/Python | /Sort Algorithm/shellsort.py | 417 | 3.53125 | 4 | def shellSort(x):
length = len(x)
gap = length / 2
while gap >= 1:
for i in range(length - gap):
if x[i] > x[i + gap]:
x[i], x[i + gap] = x[i + gap], x[i]
gap = gap - 1 # it's important to set the gap
array = [13, 48, 23, 38, 9, 87, 55, 94, 72, 21, 46... |
8a0dd332fabcd4d0cdeea22512e76f8205b30481 | kiasf159/Python | /Sort Algorithm/bubblesort.py | 376 | 4.09375 | 4 | def bubbleSort(x):
length = len(x)
for i in range(length - 1):
for j in range(length - i - 1): # it's the same as the out-range
if x[j] > x[j+1]:
x[j], x[j+1] = x[j+1], x[j]
array = [13, 48, 23, 38, 9, 87, 55, 94, 72, 21, 46, 90, 31, 50, 77, 36, 64, 7, 81, 17, 29, 6... |
c97daefab6ab0222a60385067ecf02b06db30ca9 | freedomskying/python_study | /spider/BIT_spider/re/re_1.py | 271 | 3.5 | 4 | import re
match = re.search(r'[1-9]\d{5}', 'BIT 100081')
if match:
print(match.group(0))
match = re.match(r'[1-9]\d{5}', '100081 BIT')
if match:
print(match.group(0))
match = re.findall(r'[1-9]\d{5}', '100081 BIT TSU100084')
if match:
print(match.group(0)) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.