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 |
|---|---|---|---|---|---|---|
95d14c513d9dfbdd3523d00a8ac4d70c5b1a1213 | zjplter/leetCode | /Array/KthLargest.py | 2,786 | 3.921875 | 4 | """
设计一个找到数据流中第K大元素的类(class)。注意是排序后的第K大元素,不是第K个不同的元素。
你的 KthLargest 类需要一个同时接收整数 k 和整数数组nums 的构造器,它包含数据流中的初始元素。每次调用 KthLargest.add,返回当前数据流中第K大的元素。
示例:
int k = 3;
int[] arr = [4,5,8,2];
KthLargest kthLargest = new KthLargest(3, arr);
kthLargest.add(3); // returns 4
kthLargest.add(5); // returns 5
kthLargest.add(10... |
2dfb1f3a20fec445048e16899fb447ebe922df97 | piyush-98/Fruit_Predictor | /fruits.py | 1,819 | 3.875 | 4 | import numpy as np ##importing libraries
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.neighbors import KNeighborsClassifier
import sys
np.set_printoptions(precision=2)
fruits = pd.read_table('/home/piyush/Desktop/course3_downloads/fruit_data_with_colors.txt') ##path to the da... |
b9aee827c18757d33227f9a93a861bfe56eeff48 | jceipek/Robotics-AI | /foodSearch.py | 20,630 | 3.5625 | 4 | import random
import time
import cProfile
random.seed(234)
class Grid:
def __init__(self, size=10):
self.running = True
self.square_size = size
self._cell_grid = [0] * size
for y in range(size):
self._cell_grid[y] = [0] * size
def get(self,x,y):
if x > self.... |
dab5397c348ebcddc6549afd479cfd6828f8a8a3 | hamzarazzak/python_tutorials | /chapter02/test.py | 198 | 3.921875 | 4 | name = input('What is your name?')
print('You have entered your name as' + '', name.title())
quote = ('So I can confirm your name is')
print("\nIn uppercase:")
print(quote.upper(),name.upper())
|
5a4fb59a1d1257fcda00108ccbeb48f6a2665970 | hamzarazzak/python_tutorials | /chapter03/guess_123.py | 688 | 4.03125 | 4 | import random
print "\tWelcome to 'Guess My Number'!"
print "\nI'm thinking of a number between 1 and 100."
print "Try to guess it in as few attempts as possible.\n"
# set the initial values
the_number = random.randrange(100) + 1
guess = int(raw_input("Take a guess: "))
tries = 2
# guess/tries remaining loop
while (... |
dc7f656bb7c2487322607dd99a37ff8912f37957 | pavjelv/scripting-languages-course | /test.py | 5,952 | 3.6875 | 4 | import unittest
from polynomial import Polynomial
class Test(unittest.TestCase):
def test_emtpy_args_constructor(self):
self.assertRaises(TypeError, Polynomial)
def test_emtpy_list_constructor(self):
self.assertRaises(ValueError, Polynomial, [])
def test_emtpy_tuple_constructor(self):
... |
77fd477246132a19dff4007c8019405b86e329c4 | nerdrax/pwp-capstones | /TomeRater/TomeRater.py | 6,119 | 3.734375 | 4 |
# User
class User(object):
def __init__(self, name, email):
self.name = name
self.email = email
self.books = {}
def get_email(self):
return self.email
def change_email(self, address):
self.email = address
return "This user's email has been updated to: {emai... |
4d85263d6e9415e4868424d6510cf70459d2a47a | StevanCakic/ADIS-UDG | /Nedelja 12/zadatak1.py | 261 | 3.515625 | 4 | import csv
with open("rectangles.csv", newline='') as fajl:
reader=csv.reader(fajl)
header=next(reader)
data=[]
for row in reader:
a=int(row[0])
b=int(row[1])
if a==b:
data.append(a*b)
print(max(data)) |
7bef17a6c736ee1f350c7c690fd36f4831f33637 | StevanCakic/ADIS-UDG | /Nedelja 10/recursion.py | 375 | 3.546875 | 4 | # 1, 2, 3, 4, 5
def suma(array):
if len(array) == 0:
return 0
return array[len(array) - 1] + suma(array[0:len(array) - 1])
# return array[0] + suma(array[1:])
def factorial(n):
# return 1 if n == 0 else n * factorial(n - 1)
if n == 0:
return 1
return n * factorial(n - 1)
niz ... |
0f0510bfa31eef17c047ca1719513c4be88d6e0e | StevanCakic/ADIS-UDG | /Nedelja 9/zad3.py | 2,242 | 3.546875 | 4 | def valid(boja):
return boja >= 0 and boja <= 255
class Color:
def __init__(self, red, green, blue):
self.__red = red
self.__green = green
self.__blue = blue
def get_red(self):
return self.__red
def get_green(self):
return self.__green
def get_blue(self):... |
5ad448365a45b02f6815e980bb42fc1279a5b9e4 | gjmingsg/Code | /leetcode/Valid Parentheses.py | 871 | 3.953125 | 4 | class Solution:
# @return a boolean
def isValid(self, s):
stack = []
for item in s:
top = len(stack)-1
if item == '(' or item == '{' or item == '[':
stack.append(item)
elif top>=0:
if item==')' and stack[top] == '(':
... |
3537b9ae969a0029370aa2b00b2a2873a77fb099 | gjmingsg/Code | /leetcode/Fraction to Recurring Decimal.py | 1,430 | 3.609375 | 4 | class Solution:
# @return a string
def fractionToDecimal(self, numerator, denominator):
if numerator==0:
return '0'
dic={}
l = []
s = ''
k = 0
point=True
signed = (numerator * denominator)<0
numerator = abs(numerator)
de... |
be6d4b38435d949682e109d4dee5c6c7cc545995 | gjmingsg/Code | /leetcode/Flatten Binary Tree to Linked List.py | 1,743 | 3.84375 | 4 | # Definition for a binary tree node
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
# @param root, a tree node
# @return nothing, do it in place
def flatten(self, root):
stack=[root]
last = root
while... |
8c25e9cc0b21687aa89265a600e36713beaf568b | gjmingsg/Code | /leetcode/Reorder List.py | 1,522 | 3.8125 | 4 | # Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
def show(self):
cur = self
s = ''
while cur!=None:
s=s+ '%d->' % (cur.val)
cur = cur.next
print s
class Solution:
# @param head, ... |
96d9d7d615b65141c9b9e005b5e7a20c88cb229c | gjmingsg/Code | /leetcode/Length of Last Word.py | 449 | 3.625 | 4 | class Solution:
# @param s, a string
# @return an integer
def lengthOfLastWord(self, s):
s = s.strip(' ')
a = s.split(' ')
if len(a)>0:
return len(a[len(a)-1])
else:
return 0
s = Solution()
print s.lengthOfLastWord("Hello World") == 5
print s.lengthO... |
89320acdb75d15e2a9226623e849585563bce9b3 | gjmingsg/Code | /leetcode/Search Insert Position.py | 563 | 3.703125 | 4 | class Solution:
# @param A, a list of integers
# @param target, an integer to be inserted
# @return integer
def searchInsert(self, A, target):
bi = 0
ei = len(A)
while bi < ei:
mi = (bi+ei)/2
#print "%d %d %d" %(bi,ei,mi)
if A[mi]>=target:
... |
fce8594366c2c65af4f36a2537930197cc4b591a | ytnvj2/PythonPractice | /simple1.py | 177 | 3.8125 | 4 | ''' Simple 1'''
def add_square(num_a, num_b):
""" Adds and then Squares the numbers """
return (num_a + num_b)**2
if __name__ == '__main__':
print(add_square(2, 3))
|
e118f94fc829d69745831490b0a720b836f8d9f3 | TopZeraProductions/estrutura-de-dados | /AtividadesContinuas/AC-03/PilhaTests.py | 3,995 | 3.625 | 4 | import unittest
import Pilha
class TestPilha(unittest.TestCase):
'''
O método setUp roda uma vez antes de cada método de teste.
Nele você pode colocar comandos que se repetiriam em todos os teste, como criar a Pilha.
'''
def setUp(self):
self.__pilha = Pilha.Pilha()
'''
... |
3f3bbeed2f4f140dc114104ffcb656088379204d | samnalkande/python-mini-projects | /projects/Automated-Chrome-Dino_game.py | 1,059 | 3.515625 | 4 | import pyautogui # pip install pyautogui
from PIL import Image, ImageGrab # pip install pillow
import time
'''
For running this game:
1)Run code
2)open chrome type:chrome://dino
Note: After running code you should start dino game within 3 seconds
'''
def hit(key):
pyautogui.keyDown(key)
return
# This is go... |
1c25edca9caea19c7ed49e09d82a3b43dfafb280 | dajkatal/Codewars | /Python/Weight for weight.py | 293 | 3.5625 | 4 | def order_weight(strng):
weights = strng.split(" ")
new_w = []
for w in weights:
sm = 0
for c in w:
sm+=int(c)
new_w.append(sm)
one, two = zip(*sorted(zip(new_w, weights)))
return ' '.join(two)
print(order_weight("103 123 4444 99 2000")) |
a7c73a3744aec604e984c698798251dea16c4d4a | dajkatal/Codewars | /Python/Counting duplicates.py | 441 | 3.59375 | 4 | def duplicate_count(text):
duplicates = 0
dupes = []
text = list(text.lower())
testingText = text[:]
for char in text:
testingText = text[:]
del(testingText[testingText.index(char)])
for i in testingText:
if char == i:
duplicates += 1
if du... |
5ff10fac5f8d2e05de383bdf64973e56c01e8c97 | dajkatal/Codewars | /Python/Adjacent pairs in a string.py | 212 | 3.765625 | 4 | def count_adjacent_pairs(st):
st = st.lower()
s, f = '', ''
words = st.split(" ")
d = 0
for val in words:
if val ==f and val != s:
d += 1
s, f = f, val
return d |
2324e4e7349b588a031c183b446c234e87e7429b | dajkatal/Codewars | /Python/Convert string to camel case.py | 479 | 3.9375 | 4 | def to_camel_case(text):
if '-' in text:
text = text.replace('-', ' ')
if '_' in text and '-' not in text:
text = text.replace('_', ' ')
text = list(text)
for char in text:
if char == ' ':
index = text.index(char)
del (text[index])
text[index]... |
77e76d68abbf04e6346c223f63b05cb5421521d2 | changled/projectchill | /python/functions.py | 2,013 | 3.59375 | 4 | import sys
import datetime
def makeUser(info):
index = 0
user = User()
user.emplID = info[index]
user.firstName = info[++index]
user.lastName = info[++index]
user.email = info[++index] #also used as username
user.password = info[++index]
user.number = info[++index]
user.ssn = info[++index]
user.position ... |
130af87fa61680d02380d4a381842d9d7ecd5bc4 | wbradley93/python-sudoku | /sudoku.py | 3,165 | 4.0625 | 4 | """
Python Sudoku
Author: Wes Bradley
Last Modified: 5 December 2016
Terminal implementation of sudoku game.
Usage: sudoku()
TODO: curses: color 3x3 blocks in board, implement cursor, implement correctness check,
implement animated solver, implement game timer and leaderboard
maybe TODO: save logs of games, a... |
effe94d1b6bf723139b3afc02231b822d54f9d8c | Souro7/python_fundamentals | /conditionals.py | 450 | 4.28125 | 4 | x = 6
y = 5
# if x == y:
# print(f'{x} is equal to {y}')
if x > y:
print(f'{x} is greater than {y}')
elif x == y:
print(f'{x} is equal to {y}')
else:
print(f'{x} is less than {y}')
# membership operators - in, not in
numbers = [1, 2, 3, 4, 5]
if x in numbers:
print(x in numbers)
if x not in n... |
c1a9fa7dbaf6a6352dc03e68cddb946158a09e86 | oxanastarazhok/Hometask | /Task1/Task 1.py | 84 | 3.546875 | 4 | list = [0, 1, 2, 3, 4, 5]
l = list [1::2]
for number in l:
print sum(l)* list[5] |
864c7f910b3bb75224de2ec5078f326b3bb137c8 | goncalopereiramonteiro/lab-03-python | /exercicio_1/analisa_ficheiro/calculos.py | 789 | 3.640625 | 4 | def calcula_linhas(nome):
f = open(nome, "r")
return f.readlines().__len__()
def calcula_carateres(nome):
f = open(nome, "r")
return f.read().__len__()
def calcula_palavra_comprida(nome):
f = open(nome, "r")
data = f.readlines()
f.close()
bigword = ""
for line in data:
lo... |
df558d22d8f7b63eb29f71b821e9412377ae222c | mahersea/Assorted-functions | /next-duplicate.py | 1,070 | 3.703125 | 4 | # return the second element of first duplicate in a list
def nextDuplicates(a):
alreadyAdded = False
dupl_a = dict()
sorted_ind_a = sorted(range(len(a)), key=lambda x: a[x]) # sort incoming list but save the indexes of sorted items
index = len(a)
nomatch = True
for i in xrange(len(a) - 1): # lo... |
9d7a100ab210e793d4cd6f6c2ce57f7ea4ad30bc | mahersea/Assorted-functions | /2d-grid-area.py | 221 | 3.734375 | 4 | # area of elements in a 2d grid
def shapeArea(n):
total = 1
for i in range(1,n+1):
total = total + (4 * (i-1))
print total
return total
n = 1
n = 2
n = 3
n = 4
n = 5
n = 6
print shapeArea(n) |
0ea6d57a6bb60ffb37d296b30198750e2f837bf3 | rsg17/Python | /list_tuple.py | 425 | 4.125 | 4 | import sys
def merge_pair_list(list1,list2):
l1 = len(list1)
l2 = len(list2)
op = []
if l1 != l2:
print "Lists not of equal length"
sys.exit(1)
for i in range(0,l1):
y = (list1[i],list2[i])
op.append(y)
return op
if __name__ == "__main__":
input1 = ["apple", "banana", ""]
input2 = ["red", "yello... |
d33715450c9188456f613ff7b9696f87b139fe28 | rsg17/Python | /oop.py | 473 | 3.53125 | 4 | class MyClass(object):
__slots__ = ["a"]
def __init__(self, val):
self.a = val
def __str__(self):
return "This is MyClass"
def increment_a(self, val):
self.a += val
@staticmethod
def class_level_method(rachana):
return rachana
if __name__ == "__main__":
myobject = MyClass(5)
print myobject
myobje... |
9aa0a41ae6b7e4a29ed15aaa42f4620e238b6dbd | amygiles2610/management-system | /LoginPage.py | 4,199 | 3.8125 | 4 | from tkinter import *
from tkinter import messagebox
import sqlite3
class main:
def __init__(self,master):
self.master = master
frame = Frame(master, width=400, height=220, bg="white")
frame.pack(padx=0.5, pady=100, anchor=CENTER)
self.username_label=Label(frame, ... |
434e1e6ef1db0e5760d6fe56673d9a185abce19c | bearachute/babystepprogram | /babypython8.py | 223 | 3.640625 | 4 | supplies = ['pens', 'staples', 'flame-throwers', 'binders']
for i in range(len(supplies)):
print('Index ' + str(i) + ' in supplies is: ' + supplies[i])
name = 'Garnet'
for i in name:
print('* * * ' + i + '* * *')
|
4eb184088751134de5e0bb17dca5f6618d55a5b7 | barsazzar/bmicalculator | /app.py | 3,613 | 4.4375 | 4 |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import math
print ('''Welcome come to Easy BMI calculater
This program is programmed by Ding. Ver.0.1.2''')
#print ("This program is programmed by Ding. Ver.0.1" '\n','\n')
try:
name = input('Please enter your name: ') #get user name
print ('\n''Hello',name,', ... |
dc44658426c6cd5f2a53e75811e2db59f15d2c88 | yama1102/python520 | /Aula2/condicionais.py | 1,607 | 4.21875 | 4 | #!/usr/bin/python3
#input('Digite qual o caminho a ser seguido: ')
#a = 'engarrafado'
#b = 'livre'
#if a == 'engarrafado':
# print('Melhor ir pela b')
#else:
# print('Indo pelo Caminho a')
#########
### Estrutura de condicional
#########
# nome = input('Digite seu nome: ').strip().title()
# sobrenome = input ... |
aaa28e5bed9ea53b36c4ff2ee113e242ec7815de | yama1102/python520 | /Aula5/teste.py | 578 | 3.703125 | 4 | #!/usr/bin/env python3
import unittest
#print(__name__)
# print('Oi, estou sendo executado')
def soma(n1,n2):
return n1 + n2
def subtrai(n1,n2):
return n1 - n2
class Testes(unittest.TestCase):
def test_soma(self):
self.assertEqual(soma(2,2),4)
self.assertLess(soma(5,5),12)
def test... |
8e363b7afe93f0f181b0bac567e0a80dd238b1ec | yarduoc/L-Systems | /Environment-sensitive/Growth_Environment.py | 1,588 | 3.71875 | 4 | ## Environment Object
"""
Allows the turtle3D object to have environmental parameters impacting its evolution
"""
import os
os.chdir("C:\\GitHub\\L-Systems\\Environment-sensitive")
from Physical_object import Physical_Volume
from Growth_Modifier import *
from Geometry import *
class Environment :
"""
... |
e5a4647ff7747a051ccc17a8658f3ae99c665542 | yarduoc/L-Systems | /Environment-sensitive/Turtle_3D.py | 7,077 | 4.4375 | 4 | ## Turtle3D Object
"""
Allows the user to ave a turtle structure in a 3D space. Lines and position where
to draw can be exported into blender to have a 3D modelisation of the turtle output
"""
import os
os.chdir("C:\\GitHub\\L-Systems\\Environment-sensitive")
from Euclidian_Space_Vector import Euclidian_Space_Vector... |
0da02693688e3f8244c5cdfd9ed49466649ace45 | arturchesnokov/hillel_pyton_intro | /Lesson2_HW.py | 1,416 | 4.03125 | 4 | # Дележ яблок
n = int(input("Please input the number of students: "))
k = int(input("Please input the number of apples: "))
print(k // n)
print(k % n)
# Парты
def desks_need(child):
return child // 2 + child % 2
room1 = int(input("Please input the number of students in room 1: "))
room2 = int(input("Please inp... |
5661823ac28a7244f20a56382610947b8486807c | arturchesnokov/hillel_pyton_intro | /Lesson4_HW.py | 1,108 | 3.609375 | 4 | # https://prnt.sc/phn1lm
# Ряд - 1
a = int(input())
b = int(input())
for i in range(a, b + 1):
print(i)
# Ряд - 2
a = int(input())
b = int(input())
if a < b:
for i in range(a, b + 1):
print(i)
else:
for i in range(a, b - 1, -1):
print(i)
# Ряд - 3
a = int(input())
b = int(input())
for i... |
2930c8a3a05384e9ba31bf1b6ebaf0b75aa62b08 | Namratha53/GitDemo | /ReadWrite.py | 477 | 3.828125 | 4 | file = open('test.txt')
print(file.read(7))
print(file.readline())
#print(file.readline())
#print(file.readline())
#print(file.readline())
#file.close()
#print line by line using readline method
#file=open('test.txt')
#for i in range(1,4):
# print(file.readline())
#file.close()
#another way of printing
#line... |
5808d49f1e9d3aae106e415ab5a1de29e20b3409 | Namratha53/GitDemo | /OoopsDemo.py | 357 | 3.75 | 4 | class calculator:
num=100
def __init__(self,x,y):
self.i=x
self.j=y
print('Default constructor calling!')
def get_data(self):
print("Executing get_data function")
def mul(self):
return self.i*self.j
a= calculator(2,3)
a.get_data()
print(a.mul())
print('*******... |
1d2359d01003435608110710acbc36fb9eae5257 | nghiale0811/python-data-structure | /expression.py | 18,999 | 4.09375 | 4 | """Abstract Syntax Trees
=== CSC148 Winter 2021 ===
Department of Mathematical and Computational Sciences,
University of Toronto Mississauga
=== Module Description ===
This contains the code from lecture, in which we moved beyond expressions to
more general form of statements. We studied two main extensions:
- h... |
43c2127e9cbc428d9fa083686be5ab85471039b4 | Stephen-ODriscoll/2018_DataAnalytics | /Project A/main.py | 6,439 | 3.890625 | 4 |
# Name: Stephen O Driscoll
# Student Number: R00146853
import numpy as np
# My main runs a while loop displaying menu and getting input until user chooses exit (6)
def main():
choice = 0
while choice != 6:
print("Menu")
print("1. Basic Statistics for Total Rainfall(Millime... |
92556c1325fb8efa951489358d012379dabf1bf9 | ratin42/python_piscine | /j02/ex03/machine.py | 1,573 | 3.515625 | 4 | from beverages import HotBeverage, Tea
import random
class CoffeeMachine():
def __init__(self):
super().__init__()
self.broke = 0
class EmptyCup(HotBeverage):
name = "empty cup"
price = 0.90
def description(self):
return "An empty cup?! Gimme my money back!"
class BrokenMachineException(Exception):... |
1cf8743a0dfc74ed69f314fc86f9c73c86cb68b9 | ratin42/python_piscine | /j02/ex03/beverages.py | 799 | 4.03125 | 4 | class HotBeverage():
"""Just some hot water in a cup."""
price = 0.30
name = "hot beverage"
def description(self):
return "Just some hot water in a cup."
def __str__(self):
return(
"""
name : %s
price : %s
description : %s
""" % (self.name, self.price, self.description()))
class Coffee(HotBeverage):
... |
34daf256986c43f577b92ce154b8c4b3607b8e16 | nolistic/genetic-queens | /main.py | 3,764 | 4 | 4 | ## Heather Nolis
## 05/20/2018
import random
import copy
# given a board, this function returns the number of good queens
def goodQueens(board):
score = 0
#for every item in the board
for i in range(len(board)):
isSafe = True
# check all other items
for j in range(len(board)):
... |
2389401ee3200fba41c12b0c0a4352583424fa8d | Zeyu-Li/high_school_exercise_assignments | /hand-in/times_table.py | 688 | 3.90625 | 4 | """ Times Table
Course: CS 30
Period: 3
Date created: February 8, 2019
Date completed: February 11, 2019
By: Andrew Li
Prints times table from the 0*0 to 12*12
"""
def main():
# if i is 0, the print statement in loop will break because it is not
# possible to step by 0, thus there is a differed case to pri... |
373b876cc4d33473a44b483cdc56da538204a2e7 | ayns01/Algorithm-lesson | /day4.py | 1,015 | 4.09375 | 4 | # Insertion Sort
arr = [10, 5, 3, 6, 1, 4, 2, 8, 7, 9]
for i in range(1, len(arr)): # i: the index of the elements that will be inserted
x = arr[i]
k = i - 1
while k >= 0 and x < arr[k]:
arr[k + 1] = arr[k]
k -= 1
arr[k + 1] = x
print(arr)
# Factorial n
# 1. iterative Way
def... |
34af14952fb48f2cf00bbc1c800864138623b21d | dominapython/Figuras-geometricas-Basicas | /colmena.py | 424 | 3.671875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Aug 28 12:42:05 2019
@author: Usuario
"""
import turtle
turtle.Screen().bgcolor("black")
turtle.Turtle()
turtle.color("yellow")
turtle.hideturtle()
def hexagon():
for _ in range(6):
turtle.forward(100)
turtle.left(360/6)
for i in range (6)... |
a28381495e08d45a75e21c512d06f688b9ab5dff | iwantroca/PythonNotes | /zeta.py | 2,427 | 4.46875 | 4 | ########LISTS########
# assigning the list
courses = ['History', 'Math', 'Physics', 'CompSci']
# finding length of list
print(len(courses))
# using index in list
print(courses[0])
# adding item to list
courses.append('Art')
print(courses)
# using insert to add in specific location
courses.insert(2, 'Art')
print(... |
98c836d2762b5bbe2100d4418b9f1f2cde0e6c18 | dannyvankooten/advent-of-code | /2021/23-amphipod/main.py | 1,047 | 3.578125 | 4 | from pathlib import Path
def energy_cost(type: str, steps: int) -> int:
costs = {
'A': 1,
'B': 10,
'C': 100,
'D': 1000,
}
return costs[type] * steps
def done(rooms, hallway):
if len(hallway) > 0:
return False
for key in rooms:
if len(rooms[key]) !=... |
e962e2b0c98e9ac56bbe92272cfe9efe24efa7ca | jyotinlad/message-processor | /scripts/database.py | 2,955 | 3.859375 | 4 | from sqlite3 import connect
from os import path
DB_FILENAME = "fruits.db"
DB_FILE = path.join("..", "storage", DB_FILENAME)
class Database:
def __init__(self):
# flag setup tables if database does not exist
setup = False if path.isfile(DB_FILE) else True
# connect to database
s... |
f461e4886e514f6497cbe1f87d648efe3a7cf1cf | RaimbekNusi/Prime-number | /Project_prime.py | 1,146 | 4.25 | 4 | def is_prime(N):
"""
Determines whether a given positive integer is prime or not
input: N, any positive integer.
returns: True if N is prime, False otherwise.
"""
# special cases:
if N == 1:
return False
# the biggest divisor we're going to try
divisor = N // 2
... |
d979babb3f45df1ec6e1b29536492b5a85ee546c | bugounet/currency-converter | /src/change.py | 5,473 | 3.8125 | 4 | # -*- coding: utf-8 -*-
""" Program explanation:
Problem asks to get the lowest end-rate for a given change.
Let's say we want to change a price from currency AAA to currency CCC,
we can either change it directly using AAA to CCC change rate ; but
AAA->BBB->CCC must also be tried to make sur it can't be cheaper.
At ... |
d1eafdac6879944977df66b359aa26e3fd023586 | fossilet/checkio | /batteries_loading.py | 1,084 | 3.765625 | 4 | #! /usr/bin/env python3
'''http://www.checkio.org/mission/task/batteries-loading/
Since Mar 31 2013
'''
from itertools import combinations
def checkio(stones):
'''minimal possible weight difference between stone piles
'''
# XXX: This is O(2^n*n^3)*O(combinations(n, r))!!!
total = len(stones)
st... |
409f6004dc3fa2f27fee615b32d4ba845ed3ba8e | HarithaChilakala2106/PythonHandson | /Assignment7/encrypt_decorator.py | 731 | 3.53125 | 4 | from cryptography.fernet import Fernet
def encryptdecorator(**kwargs):
def wrapper(func):
def wrapped_function(*args):
print('Encrypts the string using decorator')
key = Fernet.generate_key()
message = kwargs['message'].encode()
f = Fernet(key)
e... |
1d35ee302383926efd0fe6be039ec819489ee3a1 | MwesigwaElijahK/week3 | /missing_number.py | 129 | 3.859375 | 4 | list1 = [4,2,8,1,9]
missing = []
for x in range(1,11):
if x not in list1:
missing.append(x)
print(missing)
|
0188c28e0485e2a0ff7efe15b89e7c5286723de9 | rajesh95cs/wordgame | /wordgameplayer.py | 2,158 | 4.15625 | 4 | class Player(object):
"""
General class describing a player.
Stores the player's ID number, hand, and score.
"""
def __init__(self, idNum, hand):
"""
Initialize a player instance.
idNum: integer: 1 for player 1, 2 for player 2. Used in informational
displays in the ... |
5f7b5e2e142cefbc6da09e1ca0d5a1dc7cf8d048 | jean1591/scammyScamScam | /creditCardGenerator.py | 1,298 | 4 | 4 | #!/usr/bin/env python
# author: garbu
from random import randint
card_types = ["visa16", "mastercard", "discover"]
def generate_card(type):
t = type.lower()
if t not in card_types:
print( "Unknown type: '%s'" % type)
print( "Please pick one of these supported types: %s" % card_types)
return
... |
1b0f6cb3ff00e3637bb02b2a85fa5937c7bca4aa | jso123450/softdev2 | /notes/apr5-2.py | 388 | 3.609375 | 4 | import random
def get_name():
names = ['tom','sue','harry','lisa','sarah','horatio']
return random.choice(names)
def dble(f):
name = f()
return name+name
print dble(get_name) # -> 2x same name
# not a closure, just assigning a fxn to a var name (no inner fxn here)
# similar to i = i + 1
get_name = d... |
fe225fa3a519aa2a974e9c9dcdb5c23b6c25f71d | jso123450/softdev2 | /notes/apr6.py | 1,165 | 3.96875 | 4 | # April 6
# 1) pt(n) -> returns a list of pythagorean triples, exclusive up until n
# 2) pt2(n) -> using list comprehensions
# 3)
print "Pythagorean Theorem Fxn 1"
def pt(n):
a = 1
b = a+1
c = b+1
triplets = []
for a in range(1,n):
for b in range (a+1,n):
for c in range(b+1,n):... |
dc1a4f87d3f59ea58ccf1bb4819cc7e6046ca684 | Samk208/Udacity-Data-Analyst-Python | /Lesson_2_functions/chunker.py | 755 | 4.03125 | 4 | # Quiz: Chunker If you have an iterable that is too large to fit in memory in full (e.g., when dealing with large
# files), being able to take and use chunks of it at a time can be very valuable.
#
# Implement a generator function, chunker, that takes in an iterable and yields a chunk of a specified size at a time.
# ... |
36d79b5867665cab83a2647cfabe2d14644ad32d | Samk208/Udacity-Data-Analyst-Python | /web_crawler_case_study/continue_crawl.py | 2,963 | 3.90625 | 4 | # The continue_crawl Function The first helper function we need to write is continue_crawl which will be used in our
# while loop like this:
#
# while continue_crawl(search_history, target_url):
# For example, we might call the function with these values:
#
# continue_crawl(['https://en.wikipedia.org/wiki/Floating_poin... |
1d76bf2cead6e296b7e7c37893a59a66cede9957 | Samk208/Udacity-Data-Analyst-Python | /Lesson_4_files_modules/flying_circus.py | 1,209 | 4.21875 | 4 | # You're going to create a list of the actors who appeared in the television programme Monty Python's Flying Circus.
# Write a function called create_cast_list that takes a filename as input and returns a list of actors' names. It
# will be run on the file flying_circus_cast.txt (this information was collected from im... |
87a54bf9f8875f2f578c0ed361b8adb924ff866c | Samk208/Udacity-Data-Analyst-Python | /Lesson_3_data_structures_loops/flying_circus_records.py | 1,018 | 4.1875 | 4 | # A regular flying circus happens twice or three times a month. For each month, information about the amount of money
# taken at each event is saved in a list, so that the amounts appear in the order in which they happened. The
# months' data is all collected in a dictionary called monthly_takings.
# For this quiz, wr... |
d33ef9a8a98070aa943403f12833f3831150a569 | PeterDoom/Coding-Adventures | /Python-code/Problem_3_Hex.py | 157 | 3.75 | 4 | import re
pattern= r"\b(?:0x)?[0-9A-F]+\b"
numbers= input()
matches = re.finditer(pattern,numbers)
for match in matches:
print(match.group(),end =" ") |
8156e5e0f42c50a1235adc93ab4a9d4bd0cac674 | PeterDoom/Coding-Adventures | /Python-code/Problem_9_Fishes.py | 1,359 | 3.515625 | 4 | import re
class Fish:
def __init__(self,lenght_of_tail,lenght_of_body,status_quo):
self.tail = len(lenght_of_tail)
self.body = len(lenght_of_body)
self.status = status_quo
list_of_fishes = []
data = input()
pattern = r"(?P<tail>>*)<(?P<body>\(+)(?P<eye>(x|'|-))>"
fish_matches = list(re.... |
b1743d0f1453f5ca6f361b163c1e3f220e864590 | PeterDoom/Coding-Adventures | /Python-code/butterfly.py | 444 | 4.09375 | 4 | n= int(input())
rows = (n-3)//2
dashes = n-2
print("*"*dashes + '\\'+ ' '+ '/'+ '*'*dashes)
for row in range(0,rows):
print("-"*dashes + '\\'+ ' '+ '/'+ '-'*dashes)
print("*"*dashes+ '\\'+ ' '+ '/'+ '*'*dashes)
print(' '*(n-1)+'@'+' '*(n-1))
for row in range(0,rows):
print("*" * dashes + '/' + ' ' + '\... |
f5e5fed471a5cf7c501659f75fd25d1cd08e523c | Venlos/Lv-518.PythonCore | /T2 Task3 | 222 | 3.6875 | 4 | a = int(input('Введіть перше число'))
b = int(input('Введіть друге число'))
print('a =', a)
print('b =', b)
print('Зміна значень:')
a, b = b, a
print('a =', a)
print('b =', b)
|
bda088191d7cfc156f6b9936ab5ec5421fb6c47d | knudsen80/DataVisHomework | /Class_examples/python1.py | 300 | 3.8125 | 4 |
name = "Scott"
country = "US"
age = 37
hourly_wage = 10
satisfied = True
daily_wage = hourly_wage*8
print("Name: " + name)
print("Country: " + country)
print("Age: " + str(age))
print("Hourly wage: " + str(hourly_wage))
print("Satisfied: " + str(satisfied))
print("Daily wage: " + str(daily_wage)) |
7dbe37e9da6d143c6baaf16c53f0b39e37fa338f | ipodlipnova/PMLDL_course | /HW1/Task2/visualization.py | 1,434 | 3.546875 | 4 | import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation, MovieWriter
from dataset_processing import coord, res_cities
def animate_problem(history, points):
"""
Used to animate problem solution
:param history: list of historical solutions
:param points: coordinates of cities
... |
afbb8aacc0d6936b6d3dbba28abea5815276e54e | suryaravikumar-pixer/webscraping | /udemy_faq.py | 1,301 | 3.5 | 4 | from bs4 import BeautifulSoup
import requests
import sqlite3
#create/create a database
conn=sqlite3.connect('udemy_faq.db')
print('database created for udemy_faq.db')
sql="""
CREATE TABLE IF NOT EXISTS faq_table(
question uniTEXT NOT NULL,
answer TEXT NOT NULL,
get_url TEXT NOT NULL
);... |
93e4fbd01ec15dae1dad99982d9f043d99878203 | malikowais/AmbientNoise | /ann_isb_plot_loss.py | 3,983 | 3.53125 | 4 | import pandas as pd
import numpy as np
from sklearn.neural_network import MLPClassifier
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.metrics import confusion_matrix
from sklearn import metrics
from sklearn.preprocessing import LabelEncoder
fr... |
319558317c1ad4f6667ebfc7b0b315e006abf084 | UstehKenny/Python | /Clases/clase2Cadenas.py | 1,339 | 4.375 | 4 | #Cadena:
#Arreglo de caracteres
cadena = "Este es el Curso de Python"
print(len(cadena))
print(cadena[11:16])
print(cadena[:20]) #Hasta el 20
print(cadena[20:]) #20 en adelante
print(cadena[::]) #Todo
#Formato de cadena
print(cadena.upper()) #Cambia a mayúsculas
print(cadena.lower()) #Cambia a minúsculas
print(cadena.s... |
0d81476e15fc3a88f97f85668a5385fb8c759963 | UstehKenny/Python | /Ejercicios en clase /ej3.py | 1,235 | 3.78125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Jun 21 11:44:04 2018
@author: carokennedy
"""
def Registro():
respuesta = 's'
while respuesta == 's':
username = input("Nombre de usuario: ")
password = input("Contraseña: ")
usuarios = {}
usuarios[username] = password
listaUsuario... |
1dbeb918cd749d811b4c078d1088d6164cbd6d93 | UstehKenny/Python | /Ejercicios en clase /registroLogin.py | 2,982 | 4 | 4 | usuarios = {} #Creamos un diccionario en donde, como llave, guardara el nombre del usuario y ,como valor, guardara la informacion del usuario que se pedira a continuacion
#Creamos la lista en donde se van a guardar los datos del usuario
unaLista = []
#Menu principal: Pide al usuario seleccionar una opcion y dependiend... |
31b9be64506e8d64c70f37ebaf2d483192ab9d88 | Shreyachidrawar1992/Python-basic | /dictionaries.py | 499 | 3.734375 | 4 |
student = {'name': 'shreya', 'age': '25', 'courses':['Maths','science']}
#print student['name'] # gives error for keys not present
#print student.get('courses') # gives None for keys not present
# for keys in student:
# print 'key is',keys
# for key,value in student.items():
# print '... |
0f36e601ba7005c8604f15af92258a29b34f508a | yeochinyi/codetest | /exercism/python/matrix/matrix.py | 738 | 3.71875 | 4 | class Matrix:
""" create a matrix starting from 1 as base """
def __init__(self, matrix_string):
# self.matrix = list(
# map(
# lambda x: list(map(
# lambda y: int(y),
# x.split(" ")
# )),
# matrix_stri... |
893d7cdc690e61e8f2bfb3bb88b32bcd972b65bf | yeochinyi/codetest | /exercism/python/perfect-numbers/perfect_numbers.py | 470 | 3.75 | 4 | import sys
def classify(number):
''' return perfect, abundant, or deficient if number is matching aliquot sum '''
num = int(number)
if num < 1:
raise ValueError(f"number {num} is invalid")
aliquot = sum([i for i in range(1,num) if num%i==0])
if aliquot == number:
return "perfect"
... |
786c8c336c317b0a768d11913c059738fd6af9ff | yeochinyi/codetest | /exercism/python/space-age/space_age.py | 2,594 | 3.78125 | 4 | import functools
class SpaceAge:
# def __init__(self, seconds):
# self.year = seconds / 31557600
# def on_earth(self):
# return round(self.year, 2)
# def on_venus(self):
# return round(self.year/0.61519726, 2)
# def on_mercury(self):
# return round(self.year/0.2408467 , ... |
fe1b9e86f81652d5bb607a9db243f04ee7564b0e | yeochinyi/codetest | /exercism/python/darts/darts.py | 309 | 3.59375 | 4 | import math
def score(x, y):
d = math.sqrt(x * x+ y*y)
# match d:
# case d if d <= 1:
# return 10
# case d if d <= 5:
# return 5
# case d if d <= 10:
# return 1
# case _:
# return 0
return (d<=1)*5+(d<=5)*4+(d<=10)*1
|
2eb8d0ab33b6ff1769ae6fb6984bbd14105a79c4 | GregoryValsaint/pythonProject | /main.py | 2,180 | 3.9375 | 4 | # # # This is a sample Python script.
# #
# # # Press Maj+F10 to execute it or replace it with your code.
# # # Press Double Shift to search everywhere for classes, files, tool windows, actions, and settings.
# #
# #
# # def print_hi(name):
# # # Use a breakpoint in the code line below to debug your script.
# # ... |
2de284de1dc00c1d3ffb7df19358720ff4b0a62b | GregoryValsaint/pythonProject | /exo2.py | 410 | 3.65625 | 4 | import numpy
from random import randint
#import random
# def is_moyenne():
# moyenne= sum(tableau)/len(tableau)
# return str(moyenne)
#
# liste = int(input("Note: "))
# tableau = []
# while 0 <= liste <= 20:
# tableau.append(liste)
# liste = input("Note: ")
# print("La moyenne est de:" + is_moyenne... |
87754d706f3bac7cde0be9821ca86fd684ccd79b | rechelletandog/hello.python | /hello.python/hello.py | 252 | 3.515625 | 4 |
print ("I am {}."
.format("Rechelle Tandog"))
print ("My spirit animal is {},because ."
.format("Cat","they are so sweet"))
print ("When not in school, I love to {}."
.format("watch horror films"))
print ("I dream being a {} in my future ."
.format("Nurse"))
|
7c1c8b715d88c337c25e1f90eb6d20bf0e5fbe53 | jkramerjj/OSU_Projects | /CS_325_Algorithms/proj4_Traveling_Salesman/proj4.py | 3,914 | 3.9375 | 4 | #!/usr/bin/python
import sys
import os
import math
import getopt
import time
TIMEOUT_SECS = 300
def usage(err=""):
if (err != ""):
print "Error:", err
print "Usage:"
print " python", os.path.basename(__file__), "[-t] input_file"
print " -t Find running time of algorithm (timeout at 5 mins)"
print " ... |
174b8d3f5e6f0ebb1fdaf6c09288fcf364fcbb9f | sjoshi5/Solution_Set | /Sierpinski Triangle.py | 627 | 3.640625 | 4 | #Chaos Game: Sierpinski Triangle
#Considering Equilateral Triangle
import numpy
import matplotlib.pyplot as plt
import math
import random
#Calculating midpoint
def mid(a,b):
return ((a[0]+b[0])/2, (a[1]+b[1])/2)
n = int(input('No. of iterations:'))
x=numpy.zeros(n) #array for coordinates
y=numpy.ze... |
e1a86620c6e280a98718145c03157f6e4de48b5c | jamesalexwhiteley/MIT-6.0001-Problem-Set-Solutions-Fall-2016 | /pset4/na/testc.py | 2,056 | 3.8125 | 4 | # import random as rs
# print(rs.random())
# def build_dictionary(alphabet):
# pos = 0
# dictionary = {}
# for i in list(alphabet):
# dictionary.update({key: i for key in list(alphabet)[pos]})
# pos += 1
# return dictionary
... |
b8d7600ec6218e1065badb3dc42dda716937aaf7 | KshitijSrivastava/python-cp-cheatsheet | /leet/trees/maxDepth.py | 727 | 3.828125 | 4 | # 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
"""
time: 2 min
errors: lots of syntax, need to practice recursion
Time: O(n)
Space: O(n) worst case, best case O(log(N)) becaus... |
6aa5c04ca0cfcef8fdbc059b827b69906442e8f0 | dsarok/CS384_1801ee19 | /Assignments/Assignment _5 /tutorial05.py | 8,010 | 3.5625 | 4 | import os
import re
def rename_FIR(folder_name):
e_padding = int(input("Enter the Episode Number Padding:"))
list = os.listdir("./Subtitles/" + folder_name)
for name in list:
try:
e_no = re.search(r'Episode\s(\d+)', name).group(1)
except:
e_no = re.search(r'Ep\s(\d+... |
b8875563792a24d119c35a6ee60685bc00bd9072 | llilsaber/data06 | /pack01/everyday.py | 783 | 3.8125 | 4 | class Day:
stu = None
time = None
place = None
def __init__(self, stu, time, place):
self.stu = stu
self.time = time
self.place = place
def study(self):
#print(self.stu, 'study is', self.time, 'hours')
return self.stu + ' study is ' + str(self.time) + ' hour... |
9a7b02ba65ac5991446d72dc6af792b762090f1f | uditsharma/python-programming | /04_journal/you_try/program.py | 1,124 | 3.828125 | 4 | import journal
def print_header():
print('------------------------')
print(' JOURNAL APP')
print('------------------------')
def list_entries(journal):
print("Your Journal Entries")
for idx, entry in enumerate(journal):
print("* [{}] {}".format(idx + 1, entry))
def add_entries(journ... |
38189b12c1e98ec72de69b989281349fa66ae814 | Vikram-Choudhary/Python-HackerRank | /30Days-of-Code/30-days-of-code.py | 8,439 | 4.125 | 4 | # Day 0: Hello, World.
input_string = input()
print('Hello, World. \n'+input_string)
# Day 1: Data Types
# Declare second integer, double, and String variables.
x = int(input())
y = float(input())
z = input()
# Read and save an integer, double, and String to your variables.
# Print the sum of both integer variable... |
16e342128e0f8197c00c952bf66c3f834a609238 | opticedscience/coffeeMachine | /coffee_machine.py | 4,728 | 4.34375 | 4 | # Write your code here
# print("Starting to make a coffee")
# print("Grinding coffee beans")
# print("Boiling water")
# print("Mixing boiled water with crushed coffee beans")
# print("Pouring coffee into the cup")
# print("Pouring some milk into the cup")
# print("Coffee is ready!")
# n=int(input("Write how many cups ... |
8266a30407edf4da055d8247e1b08cd2f84c7239 | rembold-cs151-master/HW10 | /Prob2.py | 2,699 | 3.828125 | 4 | ##################################################
# Name:
# Collaborators:
# Est Time Spent (hrs):
##################################################
import arcade
class Prob2():
'''
Class to display and move a circle about the screen using
mouse control.
All the needed inputs for any method can be... |
4f511921ae49d690cef882836c5d440278bba45f | jerrydavidlee/16PFAjerrydavidlee | /ex28/ex28.py | 706 | 3.703125 | 4 |
print(" 1. True and True = %s" % str(True and True))
print("2. False and True = %s" % str(False and True))
print("3. 1 == 1 and 2 == 1 = %s" %((1==1) and (2==1)))
print(" 4. 'test' == 'test' = %s" % str('test' == 'test'))
print(" 5. 1 ==1 and 2 == 1
True and 1 ==1
False and 0 != 0
True or 1 == 1
"test" == "testing"
... |
75b4423628456440c82a0fb361f01cb9a0461e1a | Berdugo1994/Tweeter-Search-Engine | /parsers/NumbersParser.py | 4,467 | 3.65625 | 4 | import math
notation_to_number = {
"k": 1000,
"m": 1000000,
"b": 1000000000,
"K": 1000,
"M": 1000000,
"B": 1000000000,
}
notation_signs_set = set(notation_to_number.keys())
number_notation_to_sign = {
"thousand": 'K',
"thousands": 'K',
"million": 'M',
"million... |
24a781e805598d9616da9d8c50d1ad5d50555db1 | ampopp04/logistic_regression | /logistic_regression/main.py | 2,697 | 3.640625 | 4 | from logistic_regression.utils.data_utils import load_dataset
from logistic_regression.utils.data_utils import unroll_images
from logistic_regression.utils.data_utils import normalize_dataset
from logistic_regression.utils.model_utils import run_trained_model_on_image
"""
The below code loads labeled training and te... |
e96d774006abaed83730cdcb522780dc1b5579ac | ZykaMyzyka/EGE | /6/2.py | 225 | 3.953125 | 4 | for x in range(2):
for y in range(2):
for w in range(2):
for z in range(2):
if ((x and not(y)) or (y == z) or w)==False:
print(x,y,w,z)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.