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 |
|---|---|---|---|---|---|---|
2a78dd3b9dc706c293872cf670f060d90a7a2c0e | sametdlsk/python_Basics | /basicFunc.py | 484 | 3.796875 | 4 | # -*- coding:utf-8 -*-
"""
Bu kodlar Python ile Pycharm editörü kullanılarak yazılmıştır.
Basitçe isminizi öğrenmek isteyen bir fonksiyondur.
These codes are written using the Pycharm editor in Python.
This code only simply func in Python.
"""
def whatsyourname():
x = input("Merhaba ben basit bir Python... |
e230018a3325271c99f237f48286c3210d9dd4f0 | jake-billings/edu-csci2421 | /misc/coins.py | 1,362 | 4.03125 | 4 | # US_COINS
US_COINS = [100, 25, 10, 5, 1]
# change()
#
# recursively generates all permutations for the change that can be made using coins
# with the values in coins for the given amount of money specified in cents by amountCents
#
# coins - See US_COINS = [100, 25, 10, 5, 1]
# amount_cents - the total we are makin... |
310f273de1a26854e584fe7da798dc0ef9c21322 | jsavon/final-project | /devel/diceroll.py | 2,408 | 4.125 | 4 | import random
print("")
print("Welcome to Josh's Dice rolling program!")
print("Press enter to roll the die")
input()
number=random.randint(1,6)
if number==1:
print("You rolled a one!")
print("[----------]")
print("[ ]")
print("[ O ]")
print("[ ]")
print("[----------]")
if ... |
3b6ce13820169e146abac7a6cbea4ae755628d3c | baton10/lesson_002 | /HW_002/010_datetime.py | 1,507 | 4.03125 | 4 | # модуль datetime
# # № 1
# # дата и врремя в данный момент
# from datetime import datetime
# dt_now = datetime.now() # берет с компьютера
# print(dt_now)
#
# dt2 = datetime(2015, 5, 16, 8, 3, 44) # можно задать дату и время самостоятельно
#
# # математические действия
# delta = dt_now - dt2
# print (delta)
#
# dt3 = d... |
6b83dc4312fe11dc32ce442cd755561f28cacdf2 | wwfirsov/dz3 | /3.py | 713 | 3.921875 | 4 | def my_func(var_1, var_2, var_3):
x = var_1
y = var_2
z = var_3
max_1 = z
max_2 = z
if x > y:
max_1 = x
if z > x:
max_2 = z
else:
max_2 = y
elif y > x:
max_1 = y
if x > z:
max_2 = x
else:
... |
069e3dd5dfd2b914d4eef9bbe0dffdf26365f3b0 | Edward123-lol/Things | /venv/crypto.py | 1,801 | 4 | 4 | # Transposition Cipher
# encryption function
def scramble2Encrypt(plainText):
evenChars = ''
oddchars = ''
charCount = 0
for ch in plainText:
if charCount % 2 == 0:
evenChars = evenChars + ch
else:
oddChars = evenChars + ch
charCount = charCount + 1
... |
f27015948ad6042d42f278c8cbd287d46b502e93 | GaryLocke91/52167_programming_and_scripting | /bmi.py | 392 | 4.46875 | 4 | #This program calculates a person's Body Mass Index (BMI)
#Asks the user to input the weight and height values
weight = float(input("Enter weight in kilograms: "))
height = float(input("Enter hegiht in centimetres: "))
#Divides the weight by the height in metres squared
bmi = weight/((height/100)**2)
#Outputs the ca... |
ad35271745809e54e49908b1a507e1c0c34fbfbf | shbhmbnsl1/DSCareerPath | /lesson6.py | 6,534 | 3.796875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Sep 26 13:01:18 2018
@author: shbhm
Data Science Career Path - Lesson 6
"""
"""
1. Importing files from the web
1.1. Importing flat files from web, downloading them locally and reading directly
1.2. Importing non flat files from the web
2. Making HTTP requests
2... |
a6279148ecb5f8db7cead1e6e657239984e52b70 | elenals/bay-area-housing | /raw-data/clean.py | 450 | 3.8125 | 4 | """
Splitting city name from zip code.
"""
import pandas as pd
import csv
df = pd.read_csv("test-data.csv", sep=",")
# Split city on "(", keep first split as zip code
# and last split as city.
split = df["zip-code"].str.split(" - ")
df["zip-code"] = split.str[0]
df["city"] = split.str[-1]
df = df[["zip-code", "cit... |
d6e511d76083d1e8c44634104beb753735b783ea | Sailor70/Ant_Colony_Optimization | /functions.py | 1,046 | 3.796875 | 4 | import math
def distance_on_unit_sphere(a, b):
lat1 = a[0]
long1 = a[1]
lat2 = b[0]
long2 = b[1]
# Convert latitude and longitude to
# spherical coordinates in radians.
degrees_to_radians = math.pi / 180.0
# phi = 90 - latitude
phi1 = (90.0 - lat1) * degrees_to_radians
... |
462383268b37fd4bdecac49a85c92588d8b179e1 | rishabh108/Python_programs | /FIle_palindrome.py | 610 | 3.96875 | 4 | with open('File_palindrome.txt') as f: #open a file
for str in f: #Run a loop and store each line in str
str1 = ''
for char in str: #Removing Non alphanumeric characters
if(ord(char)>= 97 and ord(char)<= 122 or ord(char)>= 65 and ord(char) <= 90 or
ord(char)>= 4... |
f3e3a5ee7bb2d4a77f71cc40a547a05d179f4ece | rishabh108/Python_programs | /BinaryTree_insert.py | 833 | 3.96875 | 4 | def getHeight(node):
if node is None:
return 0
else:
max_height = 1 + max(getHeight(node.left), getHeight(node.right))
return max_height
class Tree:
def __init__(self, data):
self.left = None
self.right = None
self.data = data
def insert(self, data):
... |
b1480f647f35aabc80578b8aff6e76a8c9d64bed | 2499603447/DeleteQqZone | /Deleteqq.py | 2,082 | 3.5 | 4 | from pynput.mouse import Button, Controller
from pynput import keyboard
import time
# 控制鼠标
mouse = Controller()
isDeleting = True
i = 1
# 监听键盘按下事件
# def on_press(key):
# try:
# print('alphanumeric key {0} pressed'.format(key.char))
# except AttributeError:
# print('special key {0} pressed'.for... |
55f732c19616f35accd3808f24a7c603f1ee647b | dobbinl/multiply2.py | /multiply.py | 200 | 4.0625 | 4 | def mult(base, num):
if num == 1:
"""set base case which will stop making recursive calls and finish function"""
return base
return base + mult(base, num-1)
print(mult(9, 5)) |
3a07dfc5f9ffd7cdc17ca1f21a01233a5d1a5350 | kiranajij/manim | /utils/space_ops.py | 4,118 | 3.96875 | 4 | import numpy as np
from constants import OUT
from constants import RIGHT
from functools import reduce
# Matrix operations
def thick_diagonal(dim, thickness=2):
"""
:param dim: The dimension of the array.
:param thickness: Thickness of the diagonal. Defaults to 2
:return: returns a array fo dimension... |
022a318753889a95471346c3596be560e43ef639 | boonwj/adventofcode2019 | /day09/intcode.py | 8,396 | 3.90625 | 4 | """
This creates program that executes `intcode` programs used in Santa's space shuttle.
Intcode program overview:
- A list of comma seperated integers
- Using the following opcodes to indicate operations
- 1, parameters 3, (num1, num2, sum_position)
- Sum num1 and num2 and store in sum_position
- 2, p... |
dbaefcf79545f054ba44f78a6190753addf35f60 | boonwj/adventofcode2019 | /day08/space_image_decoder.py | 2,559 | 4.0625 | 4 | """
Space Image Decoder
Images are sent as a series of digits that each represent the color of a single pixel.
The digits fill each row of the image left-to-right, then move downward to the next row,
filling rows top-to-bottom until every pixel of the image is filled.
Each image actually consists of a series of ident... |
f1786bf43dc19040524461b7b96c1b0bfb50e5de | zanzero/pyodbc | /test.py | 832 | 4.28125 | 4 | import datetime
from datetime import timedelta
now = datetime.datetime.now()
print("Current date and time using str method of datetime object:")
print(str(now))
d = str(now + timedelta(minutes=2))
print(d[:-3])
print(type(d))
"""
print("Current date and time using instance attributes:")
print("C... |
ae228f20431d3b234a191117fd15e029ea4d3d79 | Sawken/Anthill | /Semaine7/anthill-croissance-pop-tunnel.py | 23,188 | 3.625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sat Mar 25 01:45:53 2017
@author: Ariana
"""
import numpy as np
import random as rd
import copy
import matplotlib.pyplot as plt
import matplotlib.colors as mcolors
import math
# GLOBAL PARAMETERS FOR EXPERIMENTS
size_map = 200 # Size of square matrix map.
neig... |
a97487ff764108b2037053c5f8ae13c4a8328bb6 | WeedViks/epixx | /lesson_7/extra_number.py | 475 | 4.03125 | 4 | # extra_number.py
def total(initial=5, *numbers, extra_number):
count = initial
for number in numbers:
count += number
count += extra_number
return count
if __name__ == '__main__':
print(total(10, 1, 2, 3, extra_number=50))
# Вызовет ошибку, поскольку мы не указали значен... |
0147dfa892ec196da7e34f806f4482728af2f0a8 | bradleymackey/l2-image-proc | /dilation.py | 773 | 3.921875 | 4 | import cv2
import sys
# the function that can easily perform a morphological transformation
from erosion import morphologicalTransformation
def imageDilation(image):
"""performs dilation on an image and returns this"""
# produce the dilated image by using the 'max' selection function which will use the maximum... |
78fc05f0422dfdac6c9287b02df814976bea45dd | robotechstar/Planar-Disk-Packing | /Spring 2018/Rohit TwoRadiusRandomPlacement.py | 1,318 | 3.734375 | 4 | import csv
from random import randint
import math
current = []
xbound = int(input("upper x bound of frame: "))
ybound = int(input("upper y bound of frame: "))
radius_pri = int(input("radius of primary disks: "))
radius_sec = int(input("radius of seconday disks: "))
iterate = int(input("number of iterations: "))
def... |
f76af4b94936c927d5d95c19d1e25651f3f61944 | adit-negi/LeetcodePython | /strings/ispalindrome.py | 157 | 3.625 | 4 | s = "A man, a plan, a canal: Panama"
s = s.replace(" ", "")
a = ""
for i in range(len(s)):
if s[i].isalnum():
a = a+s[i]
a = a.lower()
print(a)
|
599ec7378710df3b399ce3eeb4885f975e4a20eb | votb92/python-library | /HelperScripts/DictHelper.py | 2,500 | 3.78125 | 4 | # -----------------------------------------------------------
# Demonstrates how to write helper library files using python
#
# (C) 2020 Kyle B. Vo, Virginia, USA
# Virginia Commonwealth University
# Society of bioinformatics
# Email thinhvo1101@gmail.com
# Github https://github.com/votb92/
# ------------------... |
34092996456eb579e246b6724855d9c90bbce17f | iasjkk/Machine-Learning-from-Scratch | /k_nearest_neighbors.py | 966 | 3.71875 | 4 | from __future__ import print_function
import numpy as np
import matplotlib.pyplot as plt
from sklearn import datasets
from data_helper import train_test_split, normalize
from data_helper import euclidean_distance, accuracy_score
from data_helper import Plot
from supervisedLearning import KNN
if __name__ == "__main__... |
d8359bd0cd9b35674eadc4002a2b8c83cb445578 | mhkmcp/In-Depth-OOP-in-Python | /tut04_inheritence_subclass_super_class.py | 1,904 | 3.84375 | 4 | # inheritance: subclass, superclass
class Employee:
raise_amount = 1.04
num_of_emp = 0
def __init__(self, first, last, pay):
self.first = first
self.last = last
self.pay = pay
self.email = self.first + '.' + self.last + '@company.com'
Employee.num_of_emp += 1
... |
228c7c6cf33d1c43fb7ad75223ab9079a192f23e | 33marvil/RubyPy | /expresiones_aritmeticas.py | 976 | 4.09375 | 4 |
#En la expresión1 no está permitido agregar otra operación aritmética,
#ni modificar el tipo de operación (p.e. una división por una resta, etc.)
expresion1 = (2 // (10 // (2 ** 2))) + (2 * 3)
expresion2 = (expresion1 + 1) * 10 / 80 == float("1.0")
#>>True
print(expresion2)
expresion3 = True#Aquí va una expresión a... |
11d25363d4234b68ad4b11fcafa02b999407a51e | celsofox/sistemas-distribuidos-exemplos | /client-server-udp/client-udp.py | 867 | 3.6875 | 4 | from socket import*
def main():
host = "localhost" # Endereco IP do Servidor
port = 5000 # Porta que o Servidor esta
#O servidor será um par endereço e porta
server = (host, port)
#Criando o socket
conexao = socket (AF_INET, SOCK_DGRAM)
conexao.bind((host, port))
#Vamo... |
dbb96f8f3641242580fb1713c2cc5981fae79230 | vetlelode/machinelearning | /Oblig1/Opg2.py | 2,073 | 3.515625 | 4 | import numpy as np
from sklearn.neighbors import KNeighborsClassifier
from sklearn import datasets
from sklearn.model_selection import train_test_split
from sklearn import model_selection
import matplotlib.pyplot as plt
# This is functionally the same as reading the data from the CSV file in the assignment
iris ... |
b7eccd866667ff762bd4c18d190cc41b6112148c | msalahm24/The-Python-Mega-Course | /core of python/string_formatting.py | 424 | 3.984375 | 4 | name=input('enter your first name : ')
surname=input('enter your surname : ')
#python 2 ---> 3.3
message='your name is %s and surname is %s ' % (name,surname)
#python 3.3 ----> later version
message2=f'yourname is {name} and surname is {surname}'
print('python 2 : ',message)
print('python 3.3 to leter version: ',messag... |
72fe0c43ecd19e304cc66751d3a3b58690c4088b | msalahm24/The-Python-Mega-Course | /core of python/loops.py | 691 | 4.03125 | 4 | import datetime
for letter in 'hello':
print(letter.title())
ages={
'mohamed':28,
'ahmed':26,
'mahmoud':22
}
#this will return tuple of item
for age in ages.items():
print(age)
#return value from dic
for age in ages.values():
print(age)
#return keys of dic
for key in ages... |
4b73187bcb1c0f6aca89486126addc6e721dd1e1 | yz-chen18/AndrewML | /linear regression.py | 977 | 3.59375 | 4 | import numpy as np
import matplotlib.pyplot as plt
def regression(inputMatrix):
shape = inputMatrix.shape
m = shape[0] #实例个数
n = shape[1] - 1 #特征数量,需要减去输入矩阵中的实际值
xMat = []
yMat = []
J = []
for i in range(m):
data = [1]
yMat.append([inputMatrix[i][-1]]) #将每一个data中的实际值录入
... |
e15edc0aa6a8fe717cefb459c6cfe2a0b7480a81 | rock-feller/Python_Challenge_DSI_Program | /Python_Challenge_DSI_Program/Solutions/challenge7.py | 622 | 3.640625 | 4 | """author = Rockefeller""""
#the word is "congratulations"
#Here is the code:
from string import ascii_lowercase
def ceasar_cipher(size_of_alphabet , correct_shift):
encrypted_word= 'htslwfyzqfyntsx'
James_BagOfWords = []
for shift in range(size_of_alphabet+1):
counter = 0
... |
4a24ab49ed17704767a80e5113f2bdb08f668116 | truedba/python_training | /entrance.py | 1,098 | 3.96875 | 4 | #!/usr/local/bin/python3
# script has 3 functions for 3 different options mentioned in task - so 3 outputs will be printed
def equal_entrance(nums, flat_num):
result = False
if (int(nums[0])-1) % flat_num:
print('NO that impossible for equal entrances')
else:
print('YES that may happen fo... |
c216eba9270aac25b2475e80237791e74e26797f | contact2sourabh/Collge-Assignmnt-Python- | /Arithmetic.py | 827 | 4.1875 | 4 | #%%
# Addition
num1=int(input('enter number: '))
num2=int(input('enter 2nd number: '))
sum=num1+num2
print('the sum of ',num1,'and',num2,'is :',sum)
#%%
#Subtraction
num1=int(input('enter number: '))
num2=int(input('enter 2nd number: '))
dif=num1-num2
print('the difference of ',num1,'and',num2,'is :',dif)
... |
51dace86451ce7ec286338c895698409c7cbc44c | bagmitamohanty/PythonDevlopment | /ValidHour.py | 231 | 3.953125 | 4 |
while True:
hr = input("Enter Hours:")
rt = input("Enter Rate:")
if hr == "Done":
break
try:
pay = float(hr) * float(rt)
except:
print("Not valid numbers")
continue
print (pay)
|
756874b94e705bdf1b0e33078a723a950a6644a9 | 50516043/program | /file_transfer2.py | 1,706 | 3.5625 | 4 | # -*- coding: utf-8 -*-
# client3.py
# python3 client3.py HostName PortNumber
#SEND FILE要求プログラム
from socket import *
import time
import sys
def receive_data(client_socket):#データ受信関数,aの長さが0のとき終了
response_server = bytearray()
while True:
a = client_socket.recv(1)#1バイトずつ
if len(a)<=0 :
... |
56f460c5299443481bcc62692d5db35377913aea | thangvu777/MarkovModel | /Markov.py | 3,276 | 3.578125 | 4 | from collections import defaultdict
import numpy as num
import random
class Markov:
# Constructor (k represents Markov Model order, assume text has at least length of k)
def __init__(self, sourceText: str, order: int) -> None:
self.order = order
self.tran = defaultdict(float) ... |
420340010544a71c19409a6928190b32b182525a | q36762000/280201102 | /lab2/example5.py | 168 | 3.9375 | 4 | x1 = eval(input("What is the first perpendicular edge?:"))
x2 = eval(input("What is the second perpendicular edge?:"))
x3 = (x1**2+x2**2)**0.5
print("Hypotenuse is",x3) |
3f885d827add7cabde9defd0705b68f3f3d8a13e | q36762000/280201102 | /lab7/example3.py | 317 | 3.6875 | 4 | employees = {}
for i in range(5):
name = input("name:")
salary = int(input("salary:"))
employees[name] = salary
salaries = sorted(employees.values())
itr = 0
for a in salaries:
if itr >= 2:
for b in employees.keys():
if employees[b] == a:
print(b)
print(employees[b])
itr = itr +1 |
114dfba988b859b0314aaf19615fd53292a24013 | q36762000/280201102 | /lab13/example2.py | 658 | 3.890625 | 4 | def selection_sort(list):
n = len(list)
for left in range(n):
min_index = left
for right in range(left+1, n):
if list[min_index] > list[right]:
min_index = right
list[left], list[min_index] = list[min_index], list[left]
return list
my_list = [22, 8, 12, -4, 27, 30, 36, 50, 7, 68, 91, 56... |
6f011c0c89a9686ac9a4b361c2a481a2514bd015 | q36762000/280201102 | /lab10/example1.py | 86 | 3.703125 | 4 | def mult(n):
if n == 1:
return 3
else:
return 3 + mult(n-1)
print(mult(5)) |
5e8a02b878c2895a0aed283ee53f3958a7266359 | q36762000/280201102 | /lab3/example6.py | 514 | 4.0625 | 4 | print("Write the parameters for represented quadratic equation : (ax**2 + b*x + c)")
a = float(input("Type a: "))
b = float(input("Type b: "))
c = float(input("Type c: "))
discriminant = b**2-(4*a*c)
x1 = (-b+discriminant**(1/2))/(2*a)
x2 = (-b-discriminant**(1/2))/(2*a)
if discriminant > 0:
print("Roots of quadra... |
297ba28d933862e34806208248b8e8d50e67e94a | maxipoemie/Wordmind | /Wordmind.py | 1,483 | 3.5 | 4 | import random
nog_een_keer_spelen = ""
def spel_input():
poging_teller = 0
gerade_woord = ""
woorden = ["bom", "kat", "kast", "raar", "schip", "stoel", "banaan", "piraat", "grassen", "boompje", "achterlijke", "paddenstoel", ]
geheim_woord = random.choice(woorden)
woordlen = len(geheim_woord)
dis... |
2e23b08a7b7da942a38720eddb24029277cbab0c | muberraylmz/BBY162 | /uygulama01.py | 1,692 | 3.6875 | 4 | puan = 0
print("Bilgeliği Temsil Eden Hayvanın Adı Nedir?")
n = input("Cevabınızı Giriniz : ").casefold()
if n == "Baykuş".casefold():
puan += 20
print("Cevabınız doğru, tebrikler!")
print(str (puan) + " " + "Puan")
else:
print("Cevabınız Yanlış")
print(str(puan) + " " + "Puan")
print("S... |
92bc95604d982256a602ef749f090b63b4f47555 | knightscode94/python-testing | /programs/cotdclass.py | 433 | 4.28125 | 4 |
"""
Define a class named Rectangle, which can be constructed by a length and width.
The Rectangle class needs to have a method that can compute area.
Finally, write a unit test to test this method.
"""
import random
class rectangle():
def __int__(self, width, length):
self.width=width
self.length... |
0f9cece79f1df74b23f2ee1b4d90341510185f8f | AmaralScientist/CourseworkCode | /Naive_Bayes_Algorithm.py | 13,278 | 3.859375 | 4 | ##
# This program uses the Naive Bayes algorithm to train and test a machine learning
# classifier. The input is a pre-processed data set organized in a pandas dataframe.
# The data set is randomly split into a training data set (2/3 of the number of
# instances) and a test data set (1/3 of the number of i... |
499cccb2e57239465a929e0a2dc0db0e9d4602b7 | ivankatliarchuk/pythondatasc | /python/academy/sqlite.py | 872 | 4.1875 | 4 | import sqlite3
# create if does not exists and connect to a database
conn = sqlite3.connect('demo.db')
# create the cursor
c = conn.cursor()
# run an sql
c.execute('''CREATE TABLE users (username text, email text)''')
c.execute("INSERT INTO users VALUES ('me', 'me@mydomain.com')")
# commit at the connection level and n... |
f512cf376248cfbe1ce963727148abff74f021bf | ivankatliarchuk/pythondatasc | /python/main/numpys/hrank/shapereshape.py | 451 | 3.90625 | 4 | '''
shape and reshape arrays
'''
import numpy as np
array = np.array([[1, 2],[3, 4],[6,5]])
sec_array = np.array([1, 2, 3, 4, 5, 6])
sec_array.shape = (3, 2)
print(sec_array)
'''
reshape
'''
array_v2 = np.array([1, 2, 3, 4, 5, 6])
print(np.reshape(array_v2, (3, 2)))
my_array = np.array([1,2,3,4,5,6])
print(np.resh... |
0aeaa34a11aef996450483d8026fe6bdc4da6535 | ivankatliarchuk/pythondatasc | /python/main/datastructures/set/symetricdifference.py | 820 | 4.4375 | 4 | """
TASK
Given 2 sets of integers, M and N, print their difference in ascending order. The term symmetric
difference indicates values that exist in eirhter M or N but do not exist in both.
INPUT
The first line of input contains integer M.
The second line containts M space separeted integers.
The third line contains an ... |
12f685cfa5415a63a8c4e2662b40e69e66e10379 | ivankatliarchuk/pythondatasc | /python/main/_30days/linkedlist.py | 1,998 | 3.8125 | 4 | class Node:
def __init__(self, data):
self.data = data
self.next = None
class Solution:
def insert(self, head, data):
p = Node(data)
if head == None:
head = p
elif head.next == None:
head.next = p
else:
start = head
... |
ff58d2ebc24c6b6293d16cf5411dbbc270d96ab5 | sdierauf/uw-cse | /143/PyHelloWorld/helloworld.py | 585 | 3.578125 | 4 | '''
Created on Feb 28, 2013
@author: Stefan
'''
print('hello world')
print(2**38)
print(4)
def repeat(s, exclaim):
result = s + s + s
if exclaim:
result = result + 'fuck!'
return result
def repeatO(s):
return repeat(s, True)
print(repeat('i', True))
s = 'hi'
print (s + re... |
07529a24b82110dbb833b3c5c89f12468f71f7b8 | zlwmzh/pythonLearn | /ai_sklearn/0704/02_SVR回归效果查看.py | 1,906 | 3.578125 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2019/7/4 13:35
# @Author : Micky
# @Site :
# @File : 02_SVR回归效果查看.py
# @Software: PyCharm
import numpy as np
import matplotlib.pyplot as plt
from sklearn.svm import SVR
from sklearn.linear_model import LinearRegression
np.random.seed(214)
if __name__... |
bd21de8a9cb706cd1b69c6cddaaa4659cc7f91d9 | mogi/project_euler | /problem6.py | 957 | 3.953125 | 4 | # -*- coding: utf-8 -*-
'''
The sum of the squares of the first ten natural numbers is,
1^2 + 2^2 + ... + 10^2 = 385
The square of the sum of the first ten natural numbers is,
(1 + 2 + ... + 10)^2 = 552 = 3025
Hence the difference between the sum of the squares of the first ten natural numbers and the square of the sum... |
63e30a11f13d095611dfa1250482d04bc1af7da7 | clouds16/intro-python | /week5/sales-invoice-finder.py | 1,399 | 3.8125 | 4 | import csv
def findInvoiceByID(findid):
csvfile = open('sales_data.csv')
readCSV = csv.reader(csvfile, delimiter=',')
idcol = []
for rows in readCSV:
if rows[0] == str(findid):
idcol.append(rows)
print(rows)
print(len(idcol), " records found \n")
csvfile.clo... |
e63e961ddac149f61dbdf07661c40672f786bea5 | clouds16/intro-python | /IntoProgramming/week1/phrase_repeater.py | 251 | 3.921875 | 4 | def logic():
input_phrase = input("\nInput your phrase: ")
count = int(input("\nHow many times should itbe repeated? "))
for i in range(count):
print(str(i+1) + " " + input_phrase)
if __name__ == "__main__":
logic()
pass |
3415154c7002758264b5680b732b61fff43523b7 | clouds16/intro-python | /week7/test_roll.py | 866 | 3.875 | 4 | import random as r
class Dice:
def __init__(self):
self.numdice = 2 # number of dice
self.numfaces = 6
def rollDice(self):
diceRolls = []
for i in range(self.numdice):
roll = r.randint[1, self.numfaces]
return diceRolls
def main():
count = 0
dic... |
792d75f77557a542363c782c4fa700fbe4ccffc7 | felipeschneider88/CockroachDBFullStackApp | /src/web/forms.py | 2,188 | 3.875 | 4 | """
Defines forms used by various web pages.
Each class is a form.
"""
from flask_wtf import FlaskForm
from wtforms import (DecimalField, IntegerField, SubmitField, SelectField)
from wtforms.validators import input_required, number_range
class StartRideForm(FlaskForm):
"""
"Start ride" button.
"""
s... |
b64c41f1627f672833c1998c0230d300d6790763 | OMR5221/MyPython | /Analysis/Anagram Detection Problem/anagramDetect_Sorting-LogLinear.py | 626 | 4.125 | 4 | # We can also sort each of the strings and then compare their values
# to test if the strings are anagrams
def anagramDetect_Sorting(stringA, stringB):
#Convert both immutable strings to lists
listA = list(stringA)
listB = list(stringB)
# Sort using Pythons function
listA.sort()
listB.sort()
... |
79a96ea2bf66f92ab3df995e2a330fd51cbae567 | OMR5221/MyPython | /Trees/BinarySearchTree.py | 2,308 | 4.125 | 4 | # BinarySearchTree: Way to map a key to a value
# Provides efficient searching by
# categorizing values as larger or smaller without
# knowing where the value is precisely placed
# Build Time: O(n)
# Search Time: O(log n)
# BST Methods:
'''
Map(): Create a new, empty map
put(key,val): Add a new key, value ... |
4143917f483f11fde2e83a52a829d73c62fc2fcd | OMR5221/MyPython | /Data Structures/Deque/palindrome_checker.py | 1,264 | 4.25 | 4 | # Palindrome: Word that is the same forward as it is backwards
# Examples: radar, madam, toot
# We can use a deque to get a string from the rear and from the front
# and compare to see if the strings ae the same
# If they are the same then the word is a palindrome
class Deque:
def __init__(self):
self.ite... |
e58b6dac395f11cff7ed110198168d54e1989f96 | OMR5221/MyPython | /Analysis/Anagram Detection Problem/anagramDetect_Linear.py | 1,642 | 4.03125 | 4 | # The Linear approach resolves around counting the number of occurrences of each letter
# and comparing these dictionaries for both words to one another
def anagramDetect_Linear(stringA, stringB):
# Create List of 26 elements where each index
# represents the letters alphabetical position
# a = 0, b = 1,... |
1ca1e025c249e5097e1f232175b9214a1d3e6eba | OMR5221/MyPython | /Data Structures/Unordered List/list_creation_analysis.py | 1,157 | 3.71875 | 4 | import timeit
# Python lists prioritize indexing
# These following operations are all valid ways to add elements to a list
# but some are much faster than others
def concat():
timelist = []
for i in range(1000):
timelist = timelist + [i]
def append():
timelist = []
for i in range(1000):
... |
04320147721c3a6e3c181a3b6b7592adab5796b0 | Frentree/pc_client | /lib/fileIO/trie.py | 2,322 | 3.625 | 4 | from collections import defaultdict
class TrieNode:
def __init__(self):
self.children = defaultdict()
self.terminated = False
self.parent = ""
self.data = ""
def deleteChildren(self, parent):
del parent.parent.children[parent.data]
class Trie:
def __init__(self):... |
71b32caf4be3b85b7a2280749f93f5cf9f369628 | quangnguyen17/Python | /python/fundamentals/bank_account.py | 1,279 | 3.90625 | 4 |
class BankAccount:
def __init__(self, name, initial_deposit=0, interest_rate=0.01):
self.name = name
self.current_balance = initial_deposit
self.interest_rate = interest_rate
def deposit(self, amount):
self.current_balance += amount
return self
def withdraw(self, a... |
2393fe0ce723619df680cd7318c3ba5733c4ffa3 | quangnguyen17/Python | /python/OOP/math_dojo_tdd.py | 1,392 | 3.8125 | 4 |
# Assignment: MathDojo + TDD
import unittest
class MathDojo:
def __init__(self):
self.result = 0
def add(self, num, *nums):
self.result += num
for arg in nums:
self.result += arg
return self
def subtract(self, num, *nums):
self.result -= num
... |
2fccb57d842ad2170ad4f4c1ed3c3b724ac7f815 | sheromon/aoc2020 | /day08/day08.py | 2,211 | 3.53125 | 4 |
class Console:
def __init__(self, input_path):
self.instructions = []
self._read_program(input_path)
self.accumulator = 0
self.loop = False # switches to True when revisiting an instruction
def _read_program(self, input_path):
lines = [line.strip() for line in open(i... |
891dfa6151fd12f681bffcba0f9caf674f6c741e | sheromon/aoc2020 | /day01/day01.py | 1,031 | 3.578125 | 4 | import numpy as np
def day01(input_path, n=2):
# n is the number of numbers in the list that must sum to 2020
int_array = np.array([int(line) for line in open(input_path)])
initial_inds = np.array(range(n))[::-1]
inds = np.copy(initial_inds)
return recursive_check(int_array, initial_inds, inds, n ... |
d1af831f48c2de1060b971019f337834705f0439 | Pfeffer-Hu/numpytest | /09цХ░ч╗ДчЪДхдНхИ╢.py | 622 | 3.640625 | 4 | #导入numpy模块
import numpy as np
#创建一个二维的数组
a=np.arange(1,13).reshape((3,4))
print(a)
#对a数组进行切片处理,获取第一、二行,第一二列
sub_a=a[:2,:2]
print(sub_a)
#对sub_a中第一行第一列的值进行修改
# sub_a[0][0]=100
# print(sub_a)
# print(a)
#通过切片可以获取到新数组,即使赋值给新的变量,但还是原来数组的视图。
# 如果对切片数组中元素的值,进行修改会影响原来的数组
#可以使用numpy中的copy方法实现
sub_aa=np.copy(a[... |
8cc43334ec7e70fc11ca3dbd609f66d524d9afa9 | VictorAether/pharmaSimulation | /sim/mc_trials.py | 6,861 | 3.890625 | 4 | from numpy import random
import matplotlib.pyplot as plt
# Trials are a Directed Acyclic Graph (DAG) -> for simplicity it's a singly linked list
# we can represent this by using a list [0, 0, 0, 0]
# This would be a drug that hasn't move though any trials
class NPV(object):
"""
A very simple NPV calculator
"""
... |
bb8c26d9f183f83582717e8fadc247b21f3c174d | freddieaviator/my_python_excercises | /ex043/my_throw.py | 982 | 4.28125 | 4 | import math
angle = float(input("Input angle in degrees: "))
velocity = float(input("Input velocity in km/h: "))
throw_height = float(input("Input throw height in meter: "))
angle_radian = math.radians(angle)
throw_velocity = velocity/3.6
horizontal_velocity = throw_velocity * math.cos(angle_radian)
vertical_velocity... |
c379d42b2b34a72e43b88db77af1ca7a69fa6385 | freddieaviator/my_python_excercises | /ex046/ex02.py | 319 | 3.703125 | 4 | #Tuple
captured = "Pikachu","Pidgey","Abra","Pidgey","Eevee","Pidgey"
#2b, Depends on if you want to store duplicates or not
# If we use tuples we're gonna see all pokemons caught, even duplicates
# With set we also see all types of pokemons caught but not how many of every type.
print(captured.count("Pidgey"))
|
2f12ddc1c86de47a02490b99281a45eca07c1f11 | gscutaru/CodeWars | /factorial.py | 583 | 3.9375 | 4 | """
In mathematics, the factorial of a non-negative integer n, denoted by n!,
is the product of all positive integers less than or equal to n. For example:
5! = 5 * 4 * 3 * 2 * 1 = 120. By convention the value of 0! is 1.
Write a function to calculate factorial for a given input. If input is below 0
or above 12 throw... |
e4e5b2624e70401390928beced59dfe8c81d5206 | dkipnis2/NaiveBayesFlightDelays | /Case2Final.py | 6,598 | 3.765625 | 4 | #Case Study 2
#Group Steven, Danny, Misha, Huayang
import csv
#this function generates a list of every attribute, its column number, and
#its respective number of nos and yeses from a given data set
def genArr(ex):
atr = []
ind = len(ex[0])-1
for i in range(0,ind):
for row in ex:
... |
2da2c383b613a8af29f21c5ec6d2213166c8d969 | cristian-trejo/pensamiento_computacional | /8_scope.py | 391 | 3.953125 | 4 | x = 'Esta es una variable global'
def funcion():
x = 'Esta es una variable local'
global y
y = 'Esta es una variable global creada desde una funcion'
print(x)
def funcion_interior():
print(f'Imprimiendo desde funcion interior: {x}')
funcion_interior()
#global x
x = 'Ca... |
807727200224530b96f1932885d0250d23746755 | guillerIs/Practica01 | /Suma/Basica.py | 115 | 3.609375 | 4 | n1=float(input("primer sumando es:"))
n2=float(input ("segundo sumando es:"))
suma=n1+n2
print("La suma es:", suma) |
bb80d5743f53aebceed9bde7593a130e0cd68e3e | jasphall/k_nearest_neighbours | /infrastructure/gui/color.py | 573 | 3.53125 | 4 | from enum import Enum
from PyQt5.QtGui import QColor
class Color(Enum):
""" Basic colors available in app """
RED = 0
GREEN = 1
BLUE = 2
YELLOW = 3
WHITE = 4
def to_qcolor(self):
if self.name == 'RED':
return QColor(255, 0, 0)
elif self.name == 'GREEN':
... |
53391103a09cb1616e474821fe55813ae059816a | ofir3009/Numpy | /Numpy MIN.py | 560 | 4.03125 | 4 | import numpy as np
def minnp(a,b):
#Function gets 2 matrixes a,b
#Returns Minimum of adding of Matrixes a + b
d1=a.shape
d2=b.shape
min1=(min(d1[0],d2[0])) # Min number of rows
min2=(min(d1[1],d2[1])) # Min number of columns
c1=np.zeros((min1,min2))
for x1 in range(min1):
... |
d14849d04bd0a7e9a7a53ab58f011beb89c2e7b0 | lutfia124/pemrograman-desktop | /no. 5.py | 376 | 3.671875 | 4 | username = "nama saya"
password = 123456
a = 1
while a <= 3:
b = str(input("masukkan username :"))
c = int(input("Masukkan password : "))
if b == username and c == password:
print ("anda berhasil masuk")
break
else:
print ("maaf username dan password anda salah")
... |
edd1dfac981962102bbe41a5f36c710d165a4641 | X-rayLaser/DeepNetLib | /structures.py | 3,067 | 3.84375 | 4 | import numpy as np
class LinkedList:
class Node:
def __init__(self, item, next):
self.next = next
self.item = item
class EndOfListError(Exception):
pass
def __init__(self, root=None):
self._root = root
def prepend(self, item):
self._root = sel... |
bd7f843193121016809314f413dfea2a56ccc373 | JaisonJames05/MyCaptain-Python | /circle.py | 128 | 4.34375 | 4 | r=float(input("Enter the radius of The Circle : "))
area= 3.14*r*r
print(f"{area} is the Area of the circle with Radius {r}") |
8732db57f5a0c422a9c35fec766c00052c8579b6 | solisruj/SBIO_Tools | /Archive/graphing/Barplot.py | 1,892 | 3.9375 | 4 | #!/usr/bin/env python3
# A quick program to create barplots with pythons seaborns module.
import seaborn as sns
import pandas as pd
import matplotlib.pyplot as plt
import argparse
# Creating TUI parser for users.
def create_parser():
parser = argparse.ArgumentParser(description="This outputs a barplot for... |
6b0b8eca4a2682729063d4aac7ed12b0d7e80002 | dyadi/dialogue-system | /miuds/nlg/nlg.py | 488 | 3.546875 | 4 | from abc import ABCMeta, abstractmethod
class NLG(metaclass=ABCMeta):
"""
NL Generation Interface
Usage:
>>> nlg = NLG(*args, **kwargs)
>>> nlg([{'intent': 'greeting'}])
'Hello!'
>>> nlg([{'intent': 'inform', 'slot': 'price', 'filler': '$10'}])
'It cost $10.'
... |
e6fbb307bb40ebfecddc6fda6e07a4a1e4291d77 | OlivierValette/python | /exercices.py | 3,731 | 3.609375 | 4 | # Exercice 1 :
# Un commerçant accorde une remise de 5 % pour tout achat d’un montant compris entre 100
# et 500 € et 8 % au-delà. Écrire un programme de calcul du montant de la remise sur un
# achat donné.
def remise(montant):
MT1 = 100
MT2 = 500
REM1 = 0.05
REM2 = 0.08
if montant > MT2:
... |
01fcc884fa78ad640194915e2ff9da874b129418 | jacobzamoraa/CIs106-JacobZamora | /Assignment 3/Activity 3 second question.py | 372 | 3.875 | 4 | print("How old are you in years")
yearsOld = int(input())
monthsOld = yearsOld * 12
daysOld = yearsOld * 365
hoursOld = yearsOld * 365 * 24
secondsOld = yearsOld * 365 * 24 * 3600
print("You are" + str(monthsOld) + "months old")
print("You are" + str(daysOld) + "days old")
print("You are" + str(hoursOld) + "Hours old")... |
7b6437a920c53b6d3c3ad5e2b86ce0ecefad19a7 | hedayet13/practiceCoding | /hackerRank26_catsAndMouse.py | 137 | 3.578125 | 4 | x=1
y=3
z=2
if abs(x-z)<abs(y-z):
print('Cat A')
if abs(x-z)>abs(y-z):
print('Cat B')
if abs(x-z)==abs(y-z):
print('Mouse C') |
2a7afde11e93c5cb82157182dd9f42a248143cc7 | hedayet13/practiceCoding | /hackerRank19_MigratoryBird.py | 713 | 3.546875 | 4 | '''
by using this code u may count how many real number in this
arr = [1,2,3,4,5,4,3,2,1,3,4]
n=len(arr)
arr= sorted(arr)
print(arr)
list=[]
count =0
for i in range(n):
for j in range(n):
if arr[i] == arr[j] and i<j:
list.append(arr[i])
n=n-1
print(n)
print(list)
'''
ar = [1,2,3,4,5,... |
04ec4e74841bcce4aa677677b53b44043251f6e9 | hedayet13/practiceCoding | /hackerRank70_superReducedString.py | 574 | 3.546875 | 4 | str = 'acdqglrfkqyuqfjkxyqvnrtysfrzrmzlygfveulqfpdbhlqdqrrqdqlhbdpfqluevfgylzmrzrfsytrnvqyxkjfquyqkfrlacdqj'
str=list(str)
str=sorted(str)
print(str)
x=0
y=1
for i in range(len(str)):
if str[x]==str[y]:
str.remove(str[y])
str.remove(str[x])
else:
x+=1
y+=1
if y>=len(str):
... |
dbb2f4474dd08924438d836ae28cbd3a7d07917a | hedayet13/practiceCoding | /hackerRank83_twoString.py | 212 | 3.8125 | 4 | n=int(input())
for iter in range(n):
a=input()
# a='hello'
a=set(list(a))
b=input()
# b='World'
b=set(list(b))
if a.intersection(b):
print('YES')
else:
print('NO') |
4209af8c49b784ac700f044754fda94994f378a5 | mike-rose/crawlbot | /red-andgreen.py | 4,285 | 3.5625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sat Mar 04 19:06:51 2017
@author: Corey Pullium
"""
import random
import time
import sys, pygame
pygame.init()
grid_w = 6 # width of grid
grid_h = 6 # height of grid
alpha = 0.9
gamma = 0.8
epsilon = 0.7
row = 0
col = 0
row_x = 0
col_x = 0
moveNum = 0
action = -1
class s... |
821b536246de7c6ed4802ab10457e90c0b0bf48d | matrackif/Python-Stock-Market-Prediction-Neural-Network | /src/csv_parser.py | 3,462 | 3.59375 | 4 | import argparse
import csv
import datetime
from pandas import read_csv
def from_timestamp_to_unix_time(timestamp: str) -> int:
# Convert date of form year-month-day to unix time
timestamp_as_list = timestamp.split('-')
year = int(timestamp_as_list[0])
month = int(timestamp_as_list[1])
day = int(ti... |
4505990363d9448684b7a2f4332758d670ce956b | gigatexal/alexandarnarayan | /projecteuler/prob14.py | 804 | 3.53125 | 4 | def isEven(num):
return num % 2 == 0
"""
pick a start number
one less than a million
run collatz sequence until at 1
append each item of the sequence to an array
run next sequence
append each item of this sequence to an array
if len of this sequence is not greater than the previous one, keep previous
repeat
"""
seque... |
14844f6ad13b0a31947b234837252b83e3aeb7f6 | gigatexal/alexandarnarayan | /projecteuler/prob25.py | 297 | 3.546875 | 4 | def fib():
a, b = 1, 1
while True:
yield a
a, b = b, a + b
fibs = fib()
f = 0
count = 0
while True:
someFib = str(next(fibs))
count = count + 1
if len(someFib) > 999:
f = int(someFib)
break
print count,f
|
42af61aa696405f939523cb9a0fa3fdb04933f50 | loretloret/Domaci-zadaci | /Lekcija - 4 Liste/main.py | 14,469 | 3.859375 | 4 | from random import randint
# NAPOMENA : Za zadatke koje sam smatrao prostim nisam ostavljao komentar tako da mogu naknadno da objasnim nacin
# na koji sam razmisljao tokom rada
#######################################################################################################################
#⦁ Napišite progra... |
f4b0da7e2b4b6c049acf535458f36754233b4fac | guotechfin/algo | /Queen.py | 2,151 | 4.09375 | 4 | #eight queen problem solution
#use recursion and backtracking
#why backtracking?
#we can decompose one instance of our problem into serveral possible subproblems
#That is, each time we make a recursive call, we will have to make a choice as
#to which decomposition to use. If we choose the wrong one, we will eventua... |
eea96527002704241bf77aabfece3d6ec89f93a8 | sunxyq/py-data-clean | /DataUtil.py | 1,466 | 3.71875 | 4 | #coding=utf-8
def is_target_shop(given):
if '鲜花' in given:
return True
if '蛋糕' in given:
return True
if '小龙虾' in given:
return True
return False
def get_shop_type(given):
shop_type = '其他'
if('蛋糕' in given):
shop_type = '蛋糕';
elif('鲜花' in given):
shop... |
b340563318988285ec22a196171de07f559dcc86 | s-ruby/pod5_repo | /robert_wilson_folder/temperature.py | 602 | 4.09375 | 4 | #1 convert a temperature of 100 degrees fahrenheit to celsius
celsius_100 = 100
print(100-32*5/9)
# the result is an integer b/c it does not have a decimal
#2 convert a temperature of 0 degrees fahrenheit to celsius
celsius_0 = 0
print(0-32*5/9)
#3 convert a temperature of 34.2 degrees fahrenheit to celsius
prin... |
b1ec2caa6676ba5dc9a4fde98aaa92c08ac3838c | s-ruby/pod5_repo | /lyndon_parilla_folder/nba_challenge.py | 4,785 | 4 | 4 | print("Challenge 2.1:")
jamal_murray_3pts_made = 46
Fred_VanVleet_3pts_made = 43
James_Harden_3pts_made = 37
# TODO: Create variable here for number of 3 pt shots made by Fred VanVleet
# TODO: Create variable here for number of 3 pt shots made by James Harden
print("Challenge 2.2:")
print(f"In the 2020 NBA playoffs, J... |
aad041babf64d755db4dad331ef0f7446a1f7527 | s-ruby/pod5_repo | /gary_brown_folder/temperture.py | 710 | 4.15625 | 4 | '''----Primitive Data Types Challenge 1: Converting temperatures----'''
# 1) coverting 100deg fahrenheit and celsius
# The resulting temperature us an integer not a float..how i know is because floats have decimal points
celsius_100 = (100-32)*5/9
print(celsius_100)
# 2)coverting 0deg fahrenheit and celsius
celsius... |
731307835a1ccda724281e6a068495435fd808dc | Soumitra-Mandal/ML-and-pyfiles | /nlp.py | 2,251 | 3.703125 | 4 |
import nltk
import textblob
from textblob import TextBlob
data=TextBlob("Hello Everyone!hope you are enjoying the day.")
data.translate(to="es")
data.translate(to="bn")
data=TextBlob("The orange is a bad fruit")
data.sentiment
data=TextBlob("Ii do have a car.")
data.correct()
#tokenize:divide the sent... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.