blob_id stringlengths 40 40 | repo_name stringlengths 5 127 | path stringlengths 2 523 | length_bytes int64 22 3.06M | score float64 3.5 5.34 | int_score int64 4 5 | text stringlengths 22 3.06M |
|---|---|---|---|---|---|---|
3d9fd4aebb9f1e3e4f40bd730feea960da85ddd0 | KaranPuro/present | /main.py | 460 | 3.65625 | 4 | import turtle
turtle.speed(0)
turtle.bgcolor("black")
for i in range(5):
for colors in ["red", "magenta", "blue", "cyan", "green", "yellow", "white"]:
turtle.color(colors)
turtle.pensize(3)
turtle.left(12)
turtle.forward(200)
turtle.left(90)
turtle.forwa... |
bc61fdd346da53b308c9289e32e2b69f49240262 | jasmingeorge/PythonProjects | /myPyFiles/ex16.py | 568 | 3.859375 | 4 | from sys import argv
script, filename = argv
print "Erase %r." % filename
print "hit CTRL^C to cancel"
print "hit ENTER to proceed"
raw_input("?")
print "Opening file"
target = open(filename, 'w')
print "Truncate file"
target.truncate()
print "Write 3 lines"
line1 = raw_input("Line 1 : ")
line2 = raw_input("Line 2... |
969c65b56454444a60a5364516fc17bd2027dd7d | Gikkman/retool | /modules/titleutils.py | 9,457 | 3.875 | 4 | import re
import sys
from modules.utils import Font
def check_date(string, title):
""" Basic date validation """
months = [
'january', 'february', 'march',
'april', 'may', 'june',
'july', 'august', 'september',
'october', 'november', 'december'
]
if r... |
4cc5e4aa3463e07ce239339aac99d5821ec786a1 | ashok148/TWoC-Day1 | /program3.py | 423 | 4.34375 | 4 | #Program to swap two variable without using 3rd variable....
num1 = int(input("Enter 1st number : "))
num2 = int(input("Enter 2nd number : "))
print("Before swaping")
print("num1 = ",num1)
print("num2 = ",num2)
print("After swapping")
#LOGIC 1:- of swapping
# num1 = num1 + num2
# num2 = num1 - num2
# num1 = n... |
8a88fc14eb9a78ea6a0aa1c52ed8dd40903b18ec | oswaldo-mor/Tarea_04 | /Descuentos.py | 923 | 3.8125 | 4 | #Encoding UTF-8
#Oswaldo Morales Rodriguez
#Conociendo la cantida comprada dar el total
def calcularDescuento(cantidadPaquetes):
if (cantidadPaquetes>=10) and (cantidadPaquetes<=19):
descuento=(cantidadPaquetes*1500)*0.20
elif (cantidadPaquetes>=20) and (cantidadPaquetes<=49):
descuento=(cantid... |
7f408dbc4d2894e0c9aa72b384e25951c7316e9a | snifhex/dsa | /data_structures/stacks/stack.py | 2,079 | 3.53125 | 4 | from abc import ABC, abstractmethod
from collections import deque
from queue import LifoQueue
from typing import NoReturn
class StackBase(ABC):
length = 0
bucket = None
def push(self, element) -> NoReturn:
self.bucket.append(element)
self.set_length()
def pop(self):
poped... |
0471b6470db0e38bd63529aa645c7a2af9da1301 | Gabopic/Exodo | /Operaciones.py | 326 | 4.03125 | 4 | x=6
y=8
print (f'La suma es primero, por ejemplo, y+x={y}+{x}={y+x}')
print (f'Luego va la resta, por ejemplo, y-x={y}-{x}={y-x}')
print (f'Ahora la multiplicación, por ejemplo, y*x={y}*{x}={y*x}')
print (f'Por último la división, por ejemplo, y/x={y}/{x}={y//x}')
print (f'Y el resto de esta división es {y%x}')
... |
97382d4b46211e0418e6f1db01d93b228338d90e | send2manoo/All-Repo | /myDocs/pgm/python/ml/01-LinearAlgebra/18-Reshape2Dto3DArray.py | 258 | 3.75 | 4 | # reshape 2D array
from numpy import array
# list of data
data = [[11, 22],
[33, 44],
[55, 66]]
# array of data
data = array(data)
print(data.shape)
print data
# reshape
data = data.reshape((data.shape[0], data.shape[1], 1))
print(data.shape)
print data
|
29db218d2c31b48cb39cc647ccbc02d329668d9f | send2manoo/All-Repo | /myDocs/pgm/python/ml/04-PythonMachineLearning/12-FeatureSelectionforMachineLearning/01-UnivariateSelection.py | 1,130 | 4.0625 | 4 | '''
The scikit-learn library provides the SelectKBest class that can be used
with a suite of different statistical tests to select a specific number of features.
The example below uses the chi squared (chi^2) statistical test for non-negative features to select 4 of the best features from
the Pima Indians onset of d... |
9878feed23238d5a152e08b2547b8db64d616a35 | send2manoo/All-Repo | /myDocs/pgm/python/ml/04-PythonMachineLearning/04-MatplotlibCrashCourse/01-LinePlot.py | 547 | 4.25 | 4 | '''
Matplotlib can be used for creating plots and charts.
The library is generally used as follows:
Call a plotting function with some data (e.g. plot()).
Call many functions to setup the properties of the plot (e.g. labels and colors).
Make the plot visible (e.g. show()).
'''
# The example below creat... |
1817e0b8a951e0d4e54a8b7f20ace542ab04cb54 | send2manoo/All-Repo | /myDocs/pgm/python/ml/01-LinearAlgebra/10-Two-DimensionalListofListstoArray.py | 172 | 3.5625 | 4 | # two dimensional example
from numpy import array
# list of data
data = [[11, 22],
[33, 44],
[55, 66]]
# array of data
data = array(data)
print(data)
print(type(data))
|
849647385e43448924aa7108a5f4986015c0c88a | send2manoo/All-Repo | /myDocs/pgm/python/ml/03-MachineLearningAlgorithms/1-Baseline machine learning algorithms/2-Zero Rule Algorithm Classification.py | 1,166 | 4.125 | 4 | from random import seed
from random import randrange
# zero rule algorithm for classification
def zero_rule_algorithm_classification(train, test):
output_values = [row[-1] for row in train]
print 'output=',output_values
print "set=",set(output_values)
prediction = max(set(output_values), key=output_values.count)
... |
18bc2446ec5cf1b44629fba4f7213d5eb8e26328 | send2manoo/All-Repo | /myDocs/pgm/c/Exercise/squareFunc.py | 140 | 3.90625 | 4 | print "Square of given No"
def Square(x):
return x*x
getvalue=input("Enter the value")
print "Square of",getvalue ,"is ",Square(getvalue)
|
73225a5b6e5bc8f5b5bdb5afce122d269e48ba71 | lathene/test-repository | /Calendar_tkinter.py | 1,012 | 3.828125 | 4 | from Tkinter import *
from tkcalendar import *
import tkMessageBox
root = Tk()
# makes a calendar with current date highlighted
def cal_func():
# makes a button that can be clicked to show current date
def calval():
tkMessageBox.showinfo("your date is", cal.get_date())
## top = Toplevel(root... |
91bbe60b759a0a369fc95fd80f2a2cb3aa195aee | laurendivney/laurendivney.github.io | /Website/textAdventure.py | 3,196 | 4.25 | 4 | start = '''
You wake up one morning and find that you aren’t in your bed; you aren’t even in your room.
You’re in the middle of a giant maze.
A sign is hanging from the ivy: “You have one hour. Don’t touch the walls.”
There is a hallway to your right and to your left.
'''
print(start)
print("Type 'left' to go left ... |
d526bf48950552494b1629abdab3cafb52169d4a | madiou/advent-of-code-2020 | /Day09/ex9_1.py | 475 | 3.5 | 4 | import sys
from itertools import combinations
numbers = []
for line in sys.stdin:
numbers.append(int(line.rstrip('\n')))
SIZE = 25
def is_valid(number, preamble):
try:
next(filter(lambda val: sum(val) == number, combinations(preamble, 2)))
return True
except StopIteration:
return... |
15c86dbea3792dcb8b3a33c8c4a8dd1a46fa06c0 | SnehaShree2501/HackerRankPythonPractice | /ListComprehensions.py | 360 | 3.921875 | 4 | x = int(input("Enter 1st co-ordinate"))
y = int(input("Enter 2nd co-ordinate"))
z = int(input("Enter 3rd ordinate"))
n = int(input("Enter the limit"))
ListOfNumbers =[]
ListOfNumbers = [[i,j,k] #list for the loop control variables
for i in range(0,x+1) #multiple loops running here
for j in range(0,y+1)
for k in range(0... |
266756785a481734b39f3d1db67439939b98cc75 | jradtkey/Python2 | /namess.py | 808 | 3.78125 | 4 |
def names(users):
print "Students"
for b in range(0, len(users["Students"])):
name = " ".join(users["Students"][b].values())
print b+1, "-", name.upper(), "-", len(name)-1
print "Instructors"
for j in range(0, len(users["Instructors"])):
name = " ".join(users["Instructors"][j].v... |
c4afdc0729ba126f76c47e42894834f7faf02264 | test12345-coder/Python | /OOP3-inheritance.py | 474 | 3.671875 | 4 | class Human:
name = ''
surname = ''
length = 0
def printVar(self):
print(f'{self.name} {self.surname} {self.length}')
class Student(Human):
grade = 0
def printVar(self):
print(f'{self.name} {self.surname} {self.length} {self.grade}')
if __name__ == '__main__... |
4bd55a701ea7ffb2f5fe9f609a79aa50a5931a55 | jfaccioli/python-challenge | /PyBank/main.py | 2,747 | 3.921875 | 4 | # Modules
import os
import csv
# Set path for file
dirname = os.path.dirname(__file__)
budget_csv = os.path.join(dirname, "Resources", "budget_data.csv")
# Define variables and lists
total_months = 0
net_total = 0
previous_value = 0
total_change = 0
months = []
total_net = []
change_list = []
# Open the CSV
with ope... |
c2dd38a003ecf858b16dd1abc14ba1f43951dfd4 | eskay101/projects | /fp.py | 1,053 | 4.09375 | 4 | ''' Program make a simple calculator that can add, subtract, multiply and divide using functions '''
# This function adds two numbers
def add(x, y):
return x + y
# This function subtracts two numbers
def subtract(x, y):
return x - y
# This function multiplies two numbers
def multiply(x, y):
retu... |
e4b919b306f2b99064c59edbc8f5d51e9b760fea | ZackarieP/Java-Projects | /Python/pos_neg.py | 524 | 4 | 4 | def pos_neg(a, b, negative):
if negative == True:
if a < 0 and b < 0:
return True
else:
return False
elif a < 0 or b < 0:
if a < 0 and b < 0:
return False
elif negative == False:
return True
else:
return False
... |
cabc2bddfde4a33c10ba9753716b17dfbe53b955 | tobynboudreaux/machine-learning-regression-practice | /mlinear_regression.py | 1,218 | 3.578125 | 4 | # Data Preprocessing Template
# Importing the libraries
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
# Importing the dataset
dataset = pd.read_csv('../Machine Learning A-Z (Codes and Datasets)/Part 2 - Regression/Section 5 - Multiple Linear Regression/Python/50_Startups.csv')
X = dataset.iloc[... |
57a99993916020b5c5780236c8efb052974c51b0 | wuxu1019/1point3acres | /Google/test_246_Strobogrammatic_Number.py | 908 | 4.15625 | 4 | """
A strobogrammatic number is a number that looks the same when rotated 180 degrees (looked at upside down).
Write a function to determine if a number is strobogrammatic. The number is represented as a string.
Example 1:
Input: "69"
Output: true
Example 2:
Input: "88"
Output: true
Example 3:
Input: "962"
Outp... |
d6221da320d561e86443cb55c14355a8bfe01c8d | wuxu1019/1point3acres | /Google/test_835_Image_Overlap.py | 1,361 | 3.890625 | 4 | """
Two images A and B are given, represented as binary, square matrices of the same size. (A binary matrix has only 0s and 1s as values.)
We translate one image however we choose (sliding it left, right, up, or down any number of units), and place it on top of the other image. After, the overlap of this translation... |
fe0c885f1a8f1d8fb1ca8306dbf5c7bd8e73b626 | wuxu1019/1point3acres | /Nvidia/trans_str_to_int.py | 307 | 3.71875 | 4 |
def changestring(s):
l = s.split(',')
rt = []
for a in l:
a = a.lstrip(' ')
a = a.rstrip(' ')
if a:
rt.append(int(a))
return rt
if __name__ == '__main__':
target = "1,,,, 3434, 22, , 345, 6, ,4,"
result = changestring(target)
print result |
0338a3890fdee169e9143a3b9eb17ae78c567616 | wuxu1019/1point3acres | /Google/test_280_Wiggle_Sort.py | 1,092 | 4.03125 | 4 | """
Given an unsorted array nums, reorder it in-place such that nums[0] <= nums[1] >= nums[2] <= nums[3]....
Example:
Input: nums = [3,5,2,1,6,4]
Output: One possible answer is [3,5,1,6,2,4]
"""
class Solution(object):
def wiggleSort_nlog(self, nums):
"""
:type nums: List[int]
:rtype: vo... |
37961ca6886c6abe98befdd1a2e96294d5721ce7 | wuxu1019/1point3acres | /Amazon/maxstack.py | 674 | 3.8125 | 4 |
class MaxStack(object):
def __init__(self):
self.stk = []
def push(self, val):
if not self.stk:
self.stk.append((val, val))
else:
self.stk.append((val, max(self.stk[-1][1], val)))
def pop(self):
if not self.stk:
return None
re... |
e7ab285e7ee756af1c8fdaa58e6a379c521d4040 | wuxu1019/1point3acres | /Nvidia/revert_32bit_int.py | 304 | 3.890625 | 4 | # revert 32 bit int by 8 bit
def revert32bit(num):
i = 2**9 - 1
rt = 0
for j in range(4):
p = 8 * j
rt |= (num ^ i) << p
num = num >> 8
return rt
if __name__ == '__main__':
num = 435
print bin(num)
rt = revert32bit(num)
print rt
print bin(rt) |
884cb9518cfa386a3bb587726af1602ba7a60254 | prashyboby/my-first-repo | /session7_exercises.py | 739 | 3.765625 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Feb 3 08:34:20 2020
@author: prasanthchakka
"""
#%%
def my_func():
i = 0
my_list=[]
while(i < 500):
my_list.append(i+1)
i+=1
return my_list
my_list = my_func()
#%%
def range_func(param):
for i in r... |
400c3dc44b73637ce66bed09e14a1fd9e5567bf7 | marqun/python_project_euler | /sol4.py | 643 | 4 | 4 | """A palindromic number reads the same both ways.
the largest palindrome made from the product of two 2-digit numbers is 9009 = 91 × 99.
Find the largest palindrome made from the product of two 3-digit numbers."""
import random
import time
start_time = time.time()
x= random.sample(range(1, 45), 5)
k=[]
for i in range(1... |
a7249a87f456f739cab212b416506e75c02053e4 | marqun/python_project_euler | /sol6.py | 534 | 4.0625 | 4 | """The sum of the squares of the first ten natural numbers is,
The square of the sum of the first ten natural numbers is,
Hence the difference between the sum of the squares of the first ten natural numbers and the square of the sum is .
Find the difference between the sum of the squares of the first one hundred natura... |
7280f3f12c8e9cf00f67f5dc04b38c0a9fe97249 | BrightnessMonitor/BrightnessMonitorClient | /src/brightnessmonitorclient/raspberry/timeConvert.py | 191 | 3.59375 | 4 | #!/usr/bin/env python
import datetime
# converts given seconds passed since 1 Jan 1970
# back into readable time
def convertback(seconds):
return datetime.datetime.fromtimestamp(seconds) |
b3927b707af3c7ab22563d88779f29811153e214 | opendere/ircbook | /util/dateutils.py | 778 | 4 | 4 | import re
from datetime import datetime, date
def today():
"""Obtain a naive date object from the current UTC time."""
now = datetime.utcnow()
return date(now.year, now.month, now.day)
def to_int(s):
try:
int(s[0:4])
except E as ex:
print(ex)
raise ValueError("Not an inte... |
74a626839f46dbb3da41c1f045e10902e1835c5d | krzysztofsmokowski/JsonToXml | /weather_comm.py | 2,656 | 3.75 | 4 | '''
Entire module is used for requesting different data from url passed in __init__
of this module.
Main purpose is to close data in json format for further actions.
'''
import json
import requests
from requests.compat import urljoin
class WeatherStations(object):
'''
This class is containing modules that are... |
b0e1e9ef12dcbf22b79838b953f8c5249fb3ddce | bluehorse07/python | /bincon.py | 567 | 3.53125 | 4 | n = int(input("Input and integer less than 256 : "))
d = 128
q = int (n / d)
r = int(n % d)
print (d,q,r)
n = r
d = int(d / 2)
q = int(n / d)
r = int(n % d)
print (d,q,r)
n = r
d = int(d / 2)
q = int(n / d)
r = int(n % d)
print (d,q,r)
n = r
d = int(d / 2)
q = int(n / d)
r = int(n % d)
print (d,q,r)
n = r
d = int(d / 2... |
624dc80e3388796c7a6fcc1f338b48b39947696b | AlexandreDejous/Misra | /misra.py | 13,135 | 3.625 | 4 | #ALL COMMUNICATION (between nodes) is going through gRPC
#each node has an internal state which is updated and used when receiving the marker for carrying out the misra algorithm
#each node can simulate computation and reading/sending messages
#each node has its own address, defined by the first argument send by the us... |
575f5def481566f9f5f677a37bd58884b6d69118 | tcamenzi/TetrisAI_old | /draw.py | 1,029 | 3.6875 | 4 | black = [0,0,0]
##Draw an individual black square, or don't draw if uncolored.
def drawSquare(board, screen, rowIndex, colIndex, pygame):
if board.board[rowIndex][colIndex] == 1:
x_coord = colIndex * board.colpixWidth
y_coord = rowIndex * board.rowpixWidth
pygame.draw.rect( screen, b... |
945fe684f9e429ea897d080871096fcf2c9206ce | varunnaganathan/DonkeyKong | /basicsprite.py | 1,104 | 3.953125 | 4 | import pygame
from helper import *
"""this is the basic sprite inheriting from pygame Sprite model.inherits the pygame Sprite adding the image and position of the image mapping to the 2-d matrix"""
class sprite(pygame.sprite.Sprite):
def __init__(self,centerPoint,image):
pygame.sprite.Sprite.__init__(self)
... |
859d548212a758d60f22027d168636fd7c48ec61 | neuromol/random_code | /pandas_sort.py | 1,315 | 3.65625 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Pandas Sort
■___■
(◕‿◕)
▐ __▐
.▆|▆.
"""
import pandas as pd
import argparse
import sys
def check_arg(args=None):
parser = argparse.ArgumentParser(description='Pandas sort using column names (compared to linux sort $columns)' ,formatter_class=argparse.RawTextHe... |
70db70d518376669d2dfd1c534122156f9ee1fc7 | jaronoff97/sample_code | /Control_Flow_Part_2.py | 363 | 3.796875 | 4 | students = ["Jacob", "Sam", "Corey", "Michael"]
num = 0
while num < len(students):
print(students[num])
num += 1
for student in students:
print(student)
for num in range(0, 10):
print(num)
list = ["string1", 10, "string2", 100]
if 10 in list:
list.remove(list.index(10))
list.insert(3, 300)
... |
c276832ed7e241ec1489b9b6c8ca67481f43f494 | UstunYildirim/CCLUB_AI_Challenge | /Bot/main.py | 5,431 | 3.671875 | 4 | """
METU CCLUB Sample AI
"""
from sys import stdout
from random import randint
from math import ceil
"""
You will mainly be changing myAI function below.
It is executed once every turn.
"""
def myAI(game):
"""
Every time this function is called, it finds your the most productive city for
that turn and finds yo... |
c5006c061a4df9eda3604aa847cbe8c22d0b7655 | SeitaBV/timely-beliefs | /timely_beliefs/utils.py | 8,162 | 3.515625 | 4 | import warnings
from datetime import datetime, timedelta
from typing import Optional, Sequence, Union
import pandas as pd
def parse_timedelta_like(
td: Union[timedelta, str, pd.Timedelta],
variable_name: Optional[str] = None,
) -> timedelta:
"""Parse timedelta like objects as a datetime.timedelta object.... |
c49ecc84bf531049eb2db3aa487b42e998a430be | tiedye93/Python--COT4930 | /lab07/tbourque2012_lab07.py | 3,799 | 3.875 | 4 | # COT 4930 Python Programming
# Name: Tyler Bourque
# ID : tbourque2012
# Lab : 07
#-----------------------------------------
class SLNode : # single link node
def __init__( self, data = None, next = None ) :
self.data = data
self.next = next
def get_data( self ) :
ret... |
3a70ff3fa0d765a90da81588aabae6c63d616504 | tiedye93/Python--COT4930 | /lab03/tbourque2012_lab03.py | 1,106 | 3.9375 | 4 | # COT 4930 Python Programming
# Name: Tyler Bourque
# ID : tbourque2012
# Lab : 03
#-----------------------------------------
def eratos( n ):
primeNumbers = [ ]
for i in range(2,n):
primeNumbers.append(i)
composite = 2
m = 1
loop = 0
while loop < m:
fo... |
c9fcb8765c36008cf1edade3b8e268ed28dfc931 | MooreRachel/Portfolio | /docs/Python/CreateFiles.py | 1,104 | 3.5625 | 4 | import os
####I wrote this script to creates a set of test text files.
##Since the volume of text files was what i was after and not content,
#I used range to create files and to fill the files content with a range of numbers.
def CreateFiles(noOfFiles, x): #(Number of Files, content)
a = range(x) #crea... |
34515f8656b395c4b843f192de78993544eb10d3 | JayaN790214/adv-163 | /fever_report.py | 1,875 | 3.9375 | 4 | from tkinter import *
root = Tk()
root.title("Fever_Report")
root.geometry("400x00")
question1_radioButton=StringVar(value="0")
Question1=Label(root, text ="Do you have headache and sore throat?")
Question1.pack()
question1_r1=Radiobutton(root, text = "yes", variable=question1_radioButton, value="yes")
ques... |
9f6d59a55c75acb5c7281cd6c35d1f5d08890d4e | COMU/cink | /playground/fatmagul.ergani/deneme5.py | 281 | 3.734375 | 4 | #!/usr/bin/python
# -*- coding: utf-8 -*-
from Tkinter import *
root = Tk ()
def key(event):
frame.focus_force()
print "pressed", repr(event.keysym)
frame = Frame (root, width=100, height=100)
frame.bind("<Key>", key)
frame.pack()
frame.focus_set()
root. mainloop()
|
0ec76417897f9de8c5ab4f293db3036915b5a1fa | brianjimenez/python-course | /material/examples/example_3.py | 581 | 3.953125 | 4 |
class Monster(object):
"""Represents a mythological creature"""
latin_name = 'monstrum'
def __init__(self, origin):
self.origin = origin
@classmethod
def get_latin(cls):
return cls.latin_name
@staticmethod
def battle(monster1, monster2):
print 'A monster from %s ... |
d6b0537a8ca9392772d74a88995c26683b12426c | brianjimenez/python-course | /material/challenges/challenge_2.py | 1,283 | 3.625 | 4 | import sys
class Atom(object):
def __init__(self, atom_type):
self.atom_type = atom_type
class Oxygen(Atom):
def __init__(self):
Atom.__init__(self, 'O')
class Hydrogen(Atom):
def __init__(self):
Atom.__init__(self, 'H')
class Water(object):
def __init__(self, oxygen, hyd... |
8991ba43a7d987b81d3c32cff7e3ab9a41b9edcf | robertompfm/pong | /pong.py | 12,594 | 4.0625 | 4 | """
CODE OF GAME PONG
The game Pong was one of the projects of the course Introduction to Interactive Programing with Python by Rice University through Coursera
This is an adapted version of the project I submitted, this time I did using pygame instead of simpleGUI
there are still a lot of things to improve but I a... |
f5575924d6740759b25852fe241b951deb4d0bb1 | fvvsantana/dynamicProgramming | /janKenPuzzle.py | 3,577 | 3.65625 | 4 |
#it will store all the solutions to all the possible boards
solutions = {}
#get the input and return the variables (int, int, list)
def readInput():
line = list(map(int, input().rstrip().split()))
rows = line[0]
cols = line[1]
board = []
for i in range(rows):
board.append(list(map(int, input().rstrip().spl... |
238dc292935318ba1dc292ade30b61865ad36316 | viviczhou/Data-Mining | /FPGrowth.py | 7,845 | 3.546875 | 4 | '''
Programming Project: Frequent Itemset Mining Algorithms
Author: Chunlei Zhou
2019/10/11 version 1.0
Due: 2019/10/17
Algorithms used:
(2) FP-growth [HPY00]
Use the UCI Adult Census Dataset
http://archive.ics.uci.edu/ml/datasets/Adult
The algorithm contains two parts.
First part: build the tree;
Second part:... |
c57e7cfb5c272def2c78350a1d481a00aa59997b | Laixsias/BigdataPython | /2.6.py | 656 | 4.03125 | 4 | dictionary = ["имя", "цена", "количество", "ед"]
goods = []
while input("Хотите добавить новый продукт ? Введите да/нет: ") == 'да':
new_goods = {}
for key in dictionary:
new_goods[key] = input("Введите параметр \"" + key + "\" для нового товара: ")
goods.append(new_goods)
print(goods)
analitics... |
a59fc3330c0cb851e43252c9f54c47f2ce2c175e | mennanov/problem-sets | /dynamic_programming/palindromic_subsequence.py | 2,379 | 4.125 | 4 | # -*- coding: utf-8 -*-
"""
A subsequence is palindromic if it is the same whether read left to right or right to left. For
instance, the sequence
A, C, G, T, G, T, C, A, A, A, A, T, C, G
has many palindromic subsequences, including A, C, G, C, A and A, A, A, A (on the other hand,
the subsequence A, C, T is not palin... |
efb2bfcf2e780a6de33bd4a2e9989b25cfcaef6f | mennanov/problem-sets | /math_problems/integer_multiplication.py | 2,411 | 4.0625 | 4 | # -*- coding: utf-8 -*-
import math
def multiple(a, b):
"""
Naive implementation of decimal integer multiplication.
It runs ~O(2N*M), where N = len(a) and M = len(b).
This algorithm seems to be slow (it may run quadratic if N==M)
"""
a, b = str(a), str(b)
# intermediary results
rows = ... |
df6cab7a299bf851115125e8c5e3bcedb209e246 | mennanov/problem-sets | /combinatorics/wildcard.py | 797 | 3.59375 | 4 | # -*- coding: utf-8 -*-
def wildcard(pattern):
"""
Given a string of 0s, 1s, and ?s (wildcards), generate all 0-1 strings that match the pattern
"""
wildcards = pattern.count('?')
alphabet = ['0', '1']
def xcombinations(items, length):
if length == 0:
yield []
else... |
bcb7788af7663d0e9c52057795c5f62acc349ba1 | mennanov/problem-sets | /other/strings/string_all_unique_chars.py | 1,371 | 4.125 | 4 | # -*- coding: utf-8 -*-
"""
Implement an algorithm to determine if a string has all unique characters.
"""
def all_unique_set(string):
"""
Running time and space is O(N).
"""
return len(string) == len(set(string))
def all_unique_list(string):
"""
Running time is O(N), space is O(R) where R ... |
907c19c0a141e093d7a2fa1670e515c6ac0a5248 | mennanov/problem-sets | /greedy_algorithms/big_clustering.py | 4,515 | 3.953125 | 4 | # -*- coding: utf-8 -*-
"""
It is a reversed problem of a clustering:
what is the largest value of k such that there is a k-clustering with spacing at least s?
Imagine that we have a big graph.
So big, in fact, that the distances (i.e., edge costs) are only defined implicitly,
rather than being provided as an explicit... |
1248d110f19b8e22098edd4f1d7c6c41f4d07048 | mennanov/problem-sets | /greedy_algorithms/graph_mst_prim.py | 2,740 | 3.59375 | 4 | # -*- coding: utf-8 -*-
from Queue import PriorityQueue
from other.graphs.graph import EdgeWeightedGraph
class MSTPrim(object):
"""
Lazy implementation of a minimum spanning tree Prim's algorithm which runs in O(MlogN)
where M is a number of edges and N is a number of vertices.
At each iteration it lo... |
412a9d6c8bacd15241be55c3ced1f7202cd74c0a | mennanov/problem-sets | /dynamic_programming/long_trip.py | 2,596 | 4.03125 | 4 | # -*- coding: utf-8 -*-
"""
You are going on a long trip. You start on the road at mile post 0. Along the way there are n
hotels, at mile posts a1 < a2 < · · · < an, where each ai is measured from the starting point. The
only places you are allowed to stop are at these hotels, but you can choose which of the hotels
yo... |
24a138a887902e511570cb744aae827d3b19409d | vatsaashwin/PreCourse_2 | /Exercise_4.py | 969 | 4.4375 | 4 | # Python program for implementation of MergeSort
def mergeSort(arr):
if len(arr) >1:
# find middle and divide the array into left and right
m = len(arr) //2
L = arr[:m]
R = arr[m:]
# print(L, R)
# recursively sort the left and right halves
mergeSort(L)
mergeSort(R)
i=j=k=0
... |
81cad42676b1bc47246872aaddb9fc34e0bfcd27 | suminb/coding-exercise | /leetcode/search_in_rotated_sorted_array.py | 1,765 | 3.953125 | 4 | #
# @lc app=leetcode id=33 lang=python3
#
# [33] Search in Rotated Sorted Array
# difficulty: medium
# https://leetcode.com/problems/search-in-rotated-sorted-array/
#
from typing import List
import pytest
class Solution:
def search(self, nums: List[int], target: int) -> int:
n = len(nums)
left, ... |
247cde1603a26c5788b2e46cd8e654679ce4d548 | suminb/coding-exercise | /leetcode/leetcode.py | 1,345 | 4.09375 | 4 | class ListNode:
def __init__(self, x):
self.val = x
self.next = None
def __repr__(self):
return f'ListNode<{self.val}>'
class TreeNode:
def __init__(self, x, left=None, right=None):
self.val = x
self.left = left
self.right = right
def build_linked_list(xs... |
367e5bcdd755649dbedac19066b4f77e3a1293d7 | suminb/coding-exercise | /daily-interview/binary_tree_level_with_minimum_sum.py | 1,516 | 4.125 | 4 | # [Daily Problem] Binary Tree Level with Minimum Sum
#
# You are given the root of a binary tree. Find the level for the binary tree
# with the minimum sum, and return that value.
#
# For instance, in the example below, the sums of the trees are 10, 2 + 8 = 10,
# and 4 + 1 + 2 = 7. So, the answer here should be 7.
#
# ... |
e4373e4ca38a1abbb97707bd65c676b5f99c147e | suminb/coding-exercise | /leetcode/merge_two_sorted_lists.py | 699 | 3.8125 | 4 | # 21. Merge Two Sorted Lists
# difficulty: easy
# https://leetcode.com/problems/merge-two-sorted-lists/
# submissions:
# https://leetcode.com/submissions/detail/203407798/
from leetcode import ListNode
class Solution:
def mergeTwoLists(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListN... |
c628ec65a8982ee325b1d4bdb2a844ff9d0ed380 | suminb/coding-exercise | /leetcode/maximal_rectangle.py | 1,693 | 3.625 | 4 | # 85. Maximal Rectangle
# difficulty: hard
# https://leetcode.com/problems/maximal-rectangle/
from typing import List
import pytest
class Solution:
def maximalRectangle(self, matrix: List[List[str]]) -> int:
return maximal_rectangle(matrix)
def maximal_rectangle(matrix):
if not matrix:
ret... |
72b94942ea0d29b122d0d0bd1d89d3ba0db1fd76 | suminb/coding-exercise | /leetcode/maximum_product_of_three_numbers.py | 1,387 | 4 | 4 | # 628. Maximum Product of Three Numbers
# difficulty: easy
# https://leetcode.com/problems/maximum-product-of-three-numbers/
from functools import reduce
from typing import List
import pytest
class Solution:
def maximumProduct(self, nums: List[int]) -> int:
return maximum_product_by_sorting(nums)
def... |
56d106d8f402776afda905895c5411b71ee7b144 | suminb/coding-exercise | /leetcode/permutations.py | 486 | 3.671875 | 4 | # 46. Permutations
from typing import List
class Solution:
def permute(self, xs: List[int]) -> List[List[int]]:
if not xs:
return [[]]
else:
r = []
for i, x in enumerate(xs):
for p in self.permute(xs[:i] + xs[i + 1:]):
r.appe... |
b68173eaf0c7724744815df7c4eac3094ccce89d | suminb/coding-exercise | /leetcode/valid-sudoku.py | 2,011 | 3.65625 | 4 | # 36. Valid Sudoku
# difficulty: medium
from typing import List
class Solution:
def isValidSudoku(self, board: List[List[str]]) -> bool:
return self.valid_rows(board) and self.valid_cols(board) and self.valid_subboxes(board)
def valid_rows(self, board):
for i in range(9):
if not ... |
0771ccc07fece05aadaab14d654be3fe2159c37b | suminb/coding-exercise | /leetcode/binary-tree-level-order-traversal-ii.py | 975 | 3.671875 | 4 | # 107. Binary Tree Level Order Traversal II
# difficulty: easy
# The solution is almost identical to that of 102. Binary Tree Level Order
# Traversal, except the result array is in a reverse-order.
from collections import deque
from typing import List
import pytest
from leetcode import TreeNode
class Solution:
... |
ea7e1bb20aa2b2e0456c349c6ef293ad8e1e75be | suminb/coding-exercise | /leetcode/best-time-to-buy-and-sell-stock.py | 861 | 3.8125 | 4 | # 121. Best Time to Buy and Sell Stock
# difficulty: easy
# https://leetcode.com/problems/best-time-to-buy-and-sell-stock/
from typing import List
import pytest
class Solution:
def maxProfit(self, prices: List[int]) -> int:
if len(prices) < 2:
return 0
min_price = prices[0]
... |
935bcac949139c79dc50375ac735b5a69cf77ab5 | anoof96/Python-Assignments | /july6th-anoof/swapping.py | 214 | 3.8125 | 4 | a = 10
b = 20
temp = a
a = b
b = temp
print(a)
print(b,"\n")
#or
a = 10
b = 20
a = a + b #10 + 20
b = a - b #30-20
a = a - b #30-10
print(a)
print(b,"\n")
#or
a, b = b, a
print(a)
print(b) |
f723a2c44555a585d24970c61d6997b6b0e69acc | stsewd/devsucodejam-2019 | /11.py | 651 | 3.5625 | 4 | # Pascal Triangle
def pascalTriangle(x, y):
if y > x:
return -1
middle = x // 2
if y > middle:
y = x - y
if y == 0:
return 1
row = [1]
for i in range(x):
extra = [] if i % 2 == 0 else [row[-1]]
row = [a + b for a, b in zip(row + extra, [0] + row)]
... |
ca6e1910148d63907839b7a3046c82b5b16716d4 | prasadhegde001/Turtle_Crossing_Python | /car_manager.py | 724 | 4.0625 | 4 | from turtle import Turtle
import random
car_color = ["red", "orange", "blue", "yellow", "green", "purple"]
DISTANCE = 5
class CarManager():
def __init__(self):
self.all_cars = []
def create_car(self):
random_number = random.randint(1, 6)
if random_number == 1:
... |
951f497bdc711f0884781b861bdb74183ea9cacf | isaac-portela/Estudos-Python | /exercicios/ex006.py | 154 | 4.15625 | 4 | num = int(input("Digite um numero: "))
dobro = num*2
triplo = num*3
raiz = num**(1/2)
print("Dobro : {}\nTriplo: {}\nRaiz: {}".format(dobro,triplo,raiz)) |
b1f17a40bd32f73e87cf5a4ae08dd2e85cf399a1 | isaac-portela/Estudos-Python | /exercicios/ex014.py | 156 | 3.8125 | 4 | temperatura = float(input("Digite a temperatura em graus Celsius: "))
print("A temperatura em graus Farennheit e : {:.2f}".format(temperatura * (9/5) + 32)) |
22a0100703ad8e08d97497a2423c191fe3ecd1cb | isaac-portela/Estudos-Python | /Lista2/tipo_de_combustivel(1134).py | 410 | 3.625 | 4 | # Isaac Portela da Silva
# matriculate: 20192004900
tipos = {1: "Alcool", 2: "Gasolina", 3:"Diesel"}
resultado = {'Alcool': 0, 'Gasolina': 0, 'Diesel': 0}
tipo = 0
while(tipo != 4):
tipo = int(input())
if tipo in tipos.keys():
resultado[tipos[tipo]] += 1
print("MUITO OBRIGADO")
print("Alcool... |
0aeeb0d1fbe15fe5cc936825c775d21b5ff6ba87 | huiqinwang/KesaiRecommend | /kesaiRecommend/srcs/sc/Singleton.py | 520 | 3.640625 | 4 | # -*- coding:UTF-8 -*-
class Singleton(object):
__instance = None
def __init__(self):
pass
def __new__(cls, *args, **kwargs):
if Singleton.__instance is None:
Singleton.__instance = object.__new__(cls,*args, **kwargs)
return Singleton.__instance
class A(Singleton):
_... |
7cd442736a1d68ef5e38bdb4927f7b02f2180c3f | zgaleday/UCSF-bootcamp | /Vector.py | 2,932 | 4.53125 | 5 | class Vector(object):
"""Naive implementation of vector operations using the python list interface"""
def __init__(self, v0):
"""
Takes as input the two vectors for which we will operate on.
:param v0: A 3D vector as either a python list of [x_0, y_0, z_0] or tuple of same format
... |
bf320a4a3eb4a61dbc1f485885196c0067208c94 | cs-fullstack-2019-fall/python-classobject-review-cw-LilPrice-Code-1 | /index.py | 1,852 | 4.28125 | 4 | def main():
pro1()
pro2()
# Problem 1:
#
# Create a Movie class with the following properties/attributes: movieName, rating, and yearReleased.
#
# Override the default str (to-String) method and implement the code that will print the value of all the properties/attributes of the Movie class
#
#
# Assign a value... |
45e0b6756098b8ec5a72b8d5f799485ae5a34f71 | margotduek/Mchine_Learning | /proyecto5/sigmo.py | 290 | 3.5625 | 4 | import numpy as np
def sigmoid(X):
A = []
a = []
for i in range(len(X)):
#for j in range(len(X[i])):
c = 1.0 / (1.0 + (np.exp(-X[i])))
A.append(c)
#A.append("||")
#A.append(a)
print(A)
return A
sigmoid([.31, .44, .37, .48])
|
c0f1afe1bc1218426abfdd484147239bd180afee | margotduek/Mchine_Learning | /examen1/proyecto-1.py | 2,154 | 3.609375 | 4 | import time
import matplotlib.pyplot as plt
import numpy as np
def main():
# We read the file
x, y = parse("ex1data1.txt")
# We calculate Theta and we save it in a varible
theta = gadienteDescendente(x, y, [0,0])
print "theta is ", theta
print "The cost is ", calculaCosto(x, y, theta)
grafi... |
72ea8e49d2fa17d5622cf9c2fa59af9109e62003 | shunyaorad/EE209AS-Project-Scratchpad | /Create2_controller/tag_follower.py | 6,472 | 3.578125 | 4 | '''
Rough draft of the robot motion algorithm.
Robot follows instruction from the last tag to find next tag.
If the robot has not seen a tag previously or can't find the
next tag within cerrtain time and distance, it will explore
untill it finds any tag. Each tag has information about the
current area the robot is in... |
f89ecca67b3a2fb5d64104d604c5dc72be2231a7 | Alexhuszagh/blockbot | /blockbot/whitelist.py | 2,013 | 4.03125 | 4 | '''
whitelist
=========
Optional utility to add a whitelist to certain accounts, which
will not block the account if a certain condition is met.
Whitelist will not suggest a block if:
1. The account is verified (override with the `whitelist_verified=False`).
2. You are following the accou... |
4dbd6ec6e9f919f8f6cfa23238af08b2958d45fe | Alexhuszagh/blockbot | /blockbot/collections.py | 14,220 | 4.25 | 4 | '''
collections
===========
High-level, file-backed collections to simplify memoizing data.
The collections are file-backed, so they are only transiently in
memory. These use SQLite, a file-based SQL database, for storage.
'''
import atexit
import csv
import collections.abc
import os
import sqlit... |
0354fa9e338622d73e61c26c0c82820fb35f2b52 | rajagoah/Data_structures | /String_compression_2.py | 1,407 | 3.8125 | 4 | """
a cleaner and efficient way to compress strings
1. Check for the following edge cases:
a. len == 0
b. len = 1
2. while loop
a. if the current element in the list is the same as the previous element, then increment counter
b. if not the same as the previous element, then reset counter and concatenate... |
ce28effb7a82860ea55f6d70b7c1fe08525bb3b8 | starwriter34/Advent-of-Code | /2020/03/code.py | 1,654 | 3.53125 | 4 |
def readFile() -> list:
with open(f"{__file__.rstrip('code.py')}input.txt", "r") as f:
return [line[:-1] for line in f.readlines()]
def count_trees(mylist, dx, dy):
x, y, cnt, length, mod = 0, 0, 0, len(mylist) - dy, len(mylist[0])
while y < length:
x = (x + dx) % mod
y += dy
... |
ae91dfd308b725346a0413edd441aa651658dba7 | pskd73/leetcode | /tree_mirror.py | 709 | 3.953125 | 4 | # Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def isSubtreeMirror(self, node1: TreeNode, node2: TreeNode) -> bool:
if node1 is None and node2 is None:
return True
if... |
e58c0fed989fe30ef688b4a7e27bace85077cbf8 | pskd73/leetcode | /april_challange/p7.py | 425 | 3.5 | 4 | from typing import List
class Solution:
def countElements(self, arr: List[int]) -> int:
s = set()
for n in arr:
s.add(n)
ans = 0
for n in arr:
if n+1 in s:
ans += 1
return ans
##
s = Solution()
print(s.countElements([1,2,3]))
print(s.... |
b91a6e79a3ef4b42740053e7e347bde78b21c68a | pskd73/leetcode | /april_challange/p8.py | 597 | 3.8125 | 4 | # Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def middleNode(self, head: ListNode) -> ListNode:
slow, fast = head, head
while fast != None and fast.next != None:
slow = slow.next
... |
4901a39b2b178c7c72e650322512a286dfed85f9 | stanley-c-yu/algorithms | /bubblesort/bubblesort.py | 666 | 4.0625 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Jun 16 17:24:08 2020
@author: stanley-yu
"""
import time
def bubbleSort(array):
start_time = time.time();
for i in range(len(array)):
n = len(array) - i - 1;
print(array);
for j in range(0,n):
#print(array... |
76baed2e05d66733e022a110fe2ce9188ed4cc5b | ReshmaRegijc/Leetcode | /tests/test_problem.py | 225 | 3.640625 | 4 | from src.Length_of_Last_Word import lengthOfLastWord
from src.Implement_strStr import strStr
def lengthOfLastWord():
assert lengthOfLastWord('Hi, Welcome to Leetcode')==8
def strStr():
assert strStr("hello", "ll")==2 |
ab01ceb3cc652a10760689052e898151de3295f0 | buzzf/CV_Projects_TF | /CNN_MNIST/MNIST_CNN.py | 4,030 | 3.5 | 4 | import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets('../learn/MNIST_DATA', one_hot=True)
batch_size = 100
n_batch = mnist.train.num_examples // batch_size
# 初始化权值
def weight_variable(shape):
initial = tf.truncated_normal(shape, stddev=0.1)
return tf... |
1591a5a8e525549a24ed11f49346c6b207b2ef7c | Anthncara/MEMO | /python/coding-challenges/cc-001-convert-to-roman-numerals/Int To Roman V2.py | 896 | 4.28125 | 4 | print("### This program converts decimal numbers to Roman Numerals ###",'\nTo exit the program, please type "exit")')
def InttoRoman(number):
int_roman_map = [(1000, 'M'), (900, 'CM'), (500, 'D'), (400, 'CD'), (100, 'C'), (90, 'XC'),\
(50, 'L'), (40, 'XL'), (10, 'X'), (9, 'IX'), (5, 'V'), (4, 'IV'), (1... |
6cd566d29ea73886e02f0a5805d629db59cf7289 | gulnaz1024/game-of-life-tkinter | /app.py | 2,145 | 3.703125 | 4 | from population import Population
from game_config import GameConfig
import tkinter as tk
class App(tk.Tk):
population: Population
config: GameConfig
canvas_objects: dict
def __init__(self, config: GameConfig) -> None:
tk.Tk.__init__(self)
self.config = config
... |
aed65393f01f2288293b53de8874d1fbf58e37ab | nitincic/git | /main.py | 244 | 3.6875 | 4 | print("Press\n1 for cube volume\n2 for cube surface area3for cuboid volume\n4 for cuboid surface area\n5 for exit");
a = int(raw_input("Give choice"));
print a;
def cube_volume():
i=float(raw_input("Enter side length "))
return i*i*i
|
2ce2767cf1f296899f2f6efa0a4e333df8cbd734 | PeterJCLaw/game-modeller | /src/vector_maths.py | 516 | 3.5 | 4 |
from cmath import phase, pi, polar, rect
from point import Vector
def angle_between(a, b):
a_phase = phase(a)
b_phase = phase(b)
angle = abs(a_phase - b_phase)
while angle > pi:
angle -= pi
return angle
def midpoint(a, b):
return (a + b) / 2
def length_towards(length, target):
"... |
d5f189f6b560fbc054bd53ada5f4a25c9f56b468 | conquistadorjd/python-03-matplotlib | /barplot-05.py | 1,114 | 3.53125 | 4 | ################################################################################################
# name: barplot-05.py
# desc: stacked bar plot
# date: 2018-07-02
# Author: conquistadorjd
################################################################################################
from matplotlib import pyplot as p... |
8d9a7c8a6ef777c34b9cb2953905d630a586ed83 | yizy/espresso | /leetcode/python/LRUCache.py | 1,874 | 3.859375 | 4 | # https://leetcode.com/problems/lru-cache
class ListNode(object):
def __init__(self, key, val):
self.key = key
self.val = val
self.prev = None
self.next = None
class LRUCache(object):
def __init__(self, capacity):
"""
:type capacity: int
"""
sel... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.