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 |
|---|---|---|---|---|---|---|
3cf5096bbe84a7fc9fca40f3b076252d06e0d9bb | Kimuksung/bigdata | /python/carclass.py | 727 | 4.15625 | 4 | '''
동적 멤버 변수 생성
- 필요한 경우 특정 함수에서 멤버 변수 생성
self : class의 멤버를 호출 하는 역할 self.member / self.method()
'''
class Car:
door = cc = 0
name = None # null
#생성자 : 객체 + 초기화
def __init__(self , door , cc , name):
self.door = door
self.cc= cc
self.name = name
def info(self):
... |
965a73abe7de3e6ef7d1ed179ba9d2afea690205 | ynoh01/DataStructure | /ScoreBoard.py | 16,868 | 3.90625 | 4 | # CS241 Project1
# Score class will be used to create objects that track several aspects (score,
# level, lives,multiplier) of a player’s performance during an arcade-style game.
# Scoreboard class will maintain (as long as the program is running) a
# leaderboard of high scores sorted in decreasing order.
class S... |
a01378929b5104660fd30d40070641b21b621712 | ionaic/the-only-one | /src/movement.py | 8,322 | 3.546875 | 4 | # functions for movement
# movement.py
# author Ian Ooi
import pygame, sys, math, operator, interactions
def dirToVec(direction):
if direction == 0:
# down (south)
return [0, 1]
elif direction == 1:
# down/left (southwest)
return [-1, 1]
elif direction == 2:
# left (... |
11595536059f66c82efa3f0dc1dc303c3151e113 | nathanslack/csc121 | /lab5.py | 4,973 | 4.34375 | 4 | import random
def main():
def print_intro():
print("""
Welcome to Camel!
In your desperation, you have stolen a camel to make your way across
the great Mobi desert.
The locals want their camel back and are chasing you down! Survive
""")
done = False
... |
4c2cb650e60fe92f2e3b0e8c23f9b81148f8351f | noelbk/battlesnake-heroku | /battlesnake/board.py | 2,132 | 3.75 | 4 | from collections import namedtuple
Move = namedtuple('Move', ['name', 'dx', 'dy'], verbose=True)
ManhattanMoves = (
Move("N", 0, -1),
Move("E", 1, 0),
Move("S", 0, 1),
Move("W", -1, 0),
)
CompassMoves = (
Move("N", 0, -1),
Move("NE", 1, -1),
Move("E", 1, 0),
Move("SE", 1, ... |
547c8c2021a76dca16234f0eced3ece7b3689437 | igor-fortaleza/myrepository | /Codes/python/data_science/grafico_x_y.py | 405 | 3.8125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sat Mar 23 16:39:37 2019
@author: igor2
"""
import matplotlib.pyplot as plt
# "as"= o apelido da forma que vc vai usar a função
x = [1, 2, 3, 4, 5]
y = [2, 4, 6, 3, 2]
titulo = "Grafico em Python"
eixo_x = "Eixo X"
eixo_y = "Eixo Y"
#legendas
plt.title(titulo)
plt.xlabel(eixo... |
8e2a5391fa20d1d3891ae03f38e0f7530848f818 | igor-fortaleza/myrepository | /Codes/python/data_science/grafico_comparacao.py | 533 | 3.6875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sat Mar 23 16:39:37 2019
@author: igor2
"""
import matplotlib.pyplot as plt
# "as"= o apelido da forma que vc vai usar a função
x1 = [1, 3, 5, 7, 9]
y1 = [2, 3, 7, 1, 6]
x2 = [2, 4, 6, 8, 10]
y2 = [5, 1, 3, 7, 4]
titulo = "Grafico Comparação em Python"
eixo_x = "Eixo X"
eixo_... |
7ee0cd4c39896e9c8ef5f19dc393733528d8d4f4 | leonardo111003/infosatc-lp-avaliativo-01 | /exercicio10.py | 89 | 3.890625 | 4 | km = float ( input ( "Insira a velocidade em km / h:" ))
ms = km / 3,6
print ( ms ) |
a49425c1d5962800f221b4f891c688423cce56c9 | AshishMaheshwari5959/Projects | /CH28_max_of_three.py | 233 | 4.03125 | 4 | a=int(input("ENTER THE FIRST NUMBER : "))
b=int(input("ENTER THE SECOND NUMBER : "))
c=int(input("ENTER THE THIRD NUMBER : "))
if a>=b and a>=c:
print(a)
elif b>=a and b>=c:
print(b)
elif c>=b and c>=a:
print(c)
|
3faaf1dac51e396b007f86e99f610d2a21ea722e | AshishMaheshwari5959/Projects | /CH16_password_generator.py | 933 | 3.8125 | 4 | import string
import random
capital=list(string.ascii_uppercase)
small=list(string.ascii_lowercase)
numbers=list(string.digits)
symbols=list(string.punctuation)
choice=str(input('''WHAT SHOULD IS THE STRENGTH OF YOUR PASSWORD :
STRONG : 12
MEDIUM : 10
... |
23fdff01628080bd0979d7a2dbc71c10a57e9309 | CGH233/Python | /2/2-6.py | 139 | 3.890625 | 4 | #coding: utf-8
num = input('输入数字:')
if num < 0:
print('负数')
elif num == 0:
print('0')
else:
print('正数')
|
3ef25417b881f983b8ca81e76d45c665bda52f0f | EishaMazhar/Semester6-Resources | /IR/Batch15_assignment2/__init__.py | 11,421 | 3.90625 | 4 | import re
# import stemmer
import csv
import os
data_dir = os.path.join(__path__[0], 'data')
def read_stopwords():
"""Return a set of stopwords stored in textmining.stopwords"""
stopwords = set()
f = open(os.path.join(data_dir, 'stopwords.txt'))
for line in f:
word = line.strip()
if no... |
b908d945c7b510fe17bef28ee5a2617847488205 | RobbeHeirman/SushiGo | /source/model/card.py | 2,006 | 4.09375 | 4 | """
@author: Robbe Heirman
@version: 0.01
@Description
The model Card Class for the sushiGo Game.
SushiGo! is a game containing the following cards.
This class will contain all the logic of holding and handling a card.
Basic Game:
Tempura
Sashimi
Dumpling
1 Maki rolls
2 Maki rolls
3 Maki rolls
S... |
bd7eb49070c4270fc52f6681b35c0c88b8ae2afd | tonykarthi/python-programming | /Beginner Level/leap year or not.py | 157 | 4.0625 | 4 | a=int(input("Enter the year :"))
if(a%4==0 and a%100!=0 or a%400==0):
print("it is a leap year")
else:
print("it isn't a leap year")
|
72455306f430b3c79ac3b97caa169fd4cb00e5a9 | usddddd/CompSci | /wordtools.py | 3,217 | 3.953125 | 4 | def myreplace(old, new, s):
"""Replace all occurences of old with new in the string s.
>>> myreplace(',', ';', 'this, that, and, some, other, thing')
'this; that; and; some; other; thing'
>>> myreplace(' ', '**', 'Words that will now be separated by stars.')
'Words**that**will**now**be**separated**b... |
26b44398c5ffb32c22b98bd8a145cca3e7540185 | usddddd/CompSci | /myfunc.py | 1,236 | 4.25 | 4 | def is_divisible_by_2_or_5(n):
"""
>>> is_divisible_by_2_or_5(8)
True
>>> is_divisible_by_2_or_5(7)
False
>>> is_divisible_by_2_or_5(5)
True
>>> is_divisible_by_2_or_5(9)
False
"""
return n % 2 == 0 or n % 5 == 0
def compare(a,b):
"""
>>> compare(5, 4)
1
>... |
3cb212414eb444e17899f469d89d8a2421f39517 | usddddd/CompSci | /numberlists.py | 2,385 | 4.125 | 4 | def only_evens(numbers):
"""
>>> only_evens([1, 3, 4, 5, 6, 7, 8])
[4, 6, 8]
>>> only_evens([2, 4, 6, 8, 10, 11, 0])
[2, 4, 6, 8, 10, 0]
>>> only_evens([1, 3, 5, 7, 9, 11])
[]
>>> only_evens([4, 0, -1, 2, 6, 7, -4])
[4, 0, 2, 6, -4]
>>> nums = [1, 2, 3, 4]
>>> only_evens(nums... |
d1b153bb8f9a28928868130e880b839669c7cb14 | muhammadbader/basicPython | /Regular_Exps.py | 1,388 | 3.9375 | 4 | import re
''' __________________________________________________'''
# import re
# def change(match):
# # print(match.group(0))
# try:
# if match.group(0)=='||':
# return "or"
# elif match.group(0) == '&&':
# return "and"
# except:
# print("Invalid")
# n = in... |
8c6bba85cede3cc76ca2b058be7776e62f791d54 | Sl3iN/mendelu-vui2 | /ukol_3/src/QueenHeuristic.py | 5,445 | 3.671875 | 4 | import copy
import random
class QueenHeuristic(object):
def choose_min_conflict_positions(self, original_state):
column_state = copy.deepcopy(original_state)
performed_steps = []
# For every column
for j in range(0, 8):
#print ('====col. %s====') % j
# Get ... |
c31da2020a4d839cfa44a42357aa51f5284804e0 | Sl3iN/mendelu-vui2 | /ukol_2/src/PuzzleWorld.py | 7,621 | 3.828125 | 4 | import random
from PuzzleHeuristics import PuzzleHeuristics
from PuzzleStatistics import PuzzleStatistics
class PuzzleWorld(object):
def __init__(self):
"""
Defines a goal state and initializes basic objects (heuristics, statistics).
"""
# State representation: tile value => (x,y... |
b762a823e1f4ef9bdb73d751c8016c25ed02a275 | kateenoel/rosalind | /string-algorithms/complementing-a-strand-of-dna.py | 460 | 3.84375 | 4 | # Given a DNA string s of length at most 1000 bp
# Return the reverse complement s^c of s
import sys
def main():
with open(sys.argv[1]) as fs:
dna = fs.read()
complements = {'A': 'T', 'C': 'G', 'T': 'A', 'G': 'C'}
reverse = dna[::-1]
reverse = reverse.lstrip()
reverseComplement = ''
... |
fa8153dc7081ddf3b5a3c8c11858e3d4466f3e91 | tosaddler/CAS_Validation | /cas_validation.py | 1,054 | 4.0625 | 4 | #!/usr/bin/python
import sys, re
def cas_validation(cas):
"""Validates if a provided CAS number could exist"""
try:
cas_match = re.search(ur'(\d+)-(\d\d)-(\d)',cas) # Takes into account the standard CAS formatting e.g. 7732-18-5
cas_string = cas_match.group(1) + cas_match.group(2) + cas_match.group(3)
increm... |
e3bf37dffb6bda9b27f88797a8f2fcf4a2cf9816 | ar9185/EATAWAY | /testy.py | 46 | 3.515625 | 4 | p={"u":4, "p":"po"}
for x in p:
print("hi") |
e443a8469abd8dd648d3919ba5122505f9ae0ee7 | ozturkaslii/GuessNumber | /Py_GuessNumber/Py_GuessNumber/Py_GuessNumber.py | 1,214 | 4.25 | 4 | low = 0;
high =100;
isGuessed = False
print('Please think of a number between 0 and 100!');
#loop till guess is true.
while not isGuessed:
#Checking your answer with Bisection Search Algorithm. It allows you to divide the search space in half at each step.
ans = (low + high)/2;
print('Is your secret number '... |
4c90f803b96ef4b19a391d38349b52295414459d | Glightman/Aula4-codelab-Python | /Aula04_CodeLab-IntroPython.py | 15,380 | 4.5625 | 5 | #!/usr/bin/env python
# coding: utf-8
# In[1]:
# **Comando Print, Variáveis e Input**
# In[2]:
#Print é uma função que imprimi na tela o que a gente quer:
print('Hello World') #Sempre acompanhado de parênteses
# In[3]:
#Variável é um espaço na memória que guarda algum dado.
#Em Python todas as váriáveis pr... |
03665caa0d575965dcfd793f66143f8036aa295a | benjamin-shen/web-test | /app/statModule.py | 1,546 | 3.765625 | 4 | # module for statistics
def mean(list):
if len(list) == 0:
return "none"
return sum(list) / float(len(list))
# print mean([1,2])
# print mean([1,2,3])
# print mean([])
def median(list):
if len(list) == 0:
return "none"
list.sort()
if len(list) % 2 == 0:
x = (... |
75d9b85cedfc07ca02e93afd69500bb9c68a1695 | A-Alexander-code/Math-adventures-with-python--Solutions | /sum_average.py | 236 | 3.765625 | 4 | def mySum(num):
running_sum = 0
addNumb = []
for i in range(1, num+1):
running_sum += i
addNumb.append(running_sum)
print(addNumb[-1])
average = sum(addNumb)/len(addNumb)
print(average)
mySum(10) |
633c2fe05e5b2fafed46fddc5674987d5c8e315b | A-Alexander-code/Math-adventures-with-python--Solutions | /polygonBeingShape/polygonBeingShape.pyde | 265 | 3.53125 | 4 | def setup():
size(600,600)
def draw():
translate(width/2,height/2)
polygon(360,100)
def polygon(sides,sz):
beginShape()
for i in range(sides):
step = radians(360/sides)
vertex(sz*cos(i*step),sz*sin(i*step))
endShape(CLOSE)
|
cc4570d2b923f179f8a591fad4e6b24ff864433a | Saauan/TP_S3_Codage | /TP2/TP2Codage.py | 4,400 | 3.59375 | 4 | import conversions, float_coding
#EXERCICE 1 - Q1
#On prend comme entiers de référence 35, 243 & 124
print("{:b}".format(35)); print("{:x}".format(35)); print("{:o}".format(35)); print("{:X}".format(35))
print("")#############
print("{:b}".format(243)); print("{:x}".format(243)); print("{:o}".format(243)); print("{:X}... |
528da2e43e9e01ec1f20638a5bf58d592937a9f5 | Jez2cool/PythonTheHardWay | /Exercise12/Exercise12.py | 203 | 3.609375 | 4 | age = raw_input("How old Are You?")
height = raw_input("How tall are you?")
weight = raw_input("How much do you weight?")
print "So you are %s years old \n%stall \nand %s heavy" % (age, height, weight)
|
9abe2e101efd221d4e94412abef9d2d46e7b36e0 | Abhishek19009/CSES | /coin_piles.py | 242 | 3.953125 | 4 | def calc_coin_pile(a,b):
if (a+b)%3 == 0 and 2*a >= b and 2*b >= a:
print("YES")
else:
print("NO")
if __name__ == "__main__":
n = int(input())
for _ in range(n):
a,b = input().strip().split()
calc_coin_pile(int(a), int(b))
|
9ac88bff95f14597c2cd9b2f28023909a50ea913 | foreverchaos/algo_python | /python_proj/code4interview/27.py | 438 | 3.84375 | 4 | def permutation(ss):
if len(ss) <= 0:
return []
res = []
perm(ss, res, '')
uniq = list(set(res))
return sorted(uniq)
def perm(ss, res, path):
if ss == '':
res.append(path)
else:
for i in range(len(ss)):
sub = ss[:i]+ss[i+1:]
add = path+ss[i]
... |
bda97d9f24a4ff4a3e2d35a1014f7e52ffbba4e7 | foreverchaos/algo_python | /python_proj/session 1/linklist_k.py | 1,447 | 3.671875 | 4 | class ListNode:
def __init__(self, x):
self.val = x
self.next = None
# def reverse_k_group(head: ListNode, k: int) -> ListNode:
# cur = head
# count = 0
# while cur and count != k:
# cur = cur.next
# count += 1
# if count == k:
# cur = reverse_k_group(cur, k... |
e6d1b5dd10c1ac5c416fcbd9aef10347513aa5d8 | foreverchaos/algo_python | /python_proj/code4interview/14.py | 718 | 3.875 | 4 |
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
# 快慢指针
def find_kth_to_tail(head, k):
if not head:
return None
pos_k = head
pos_start = head
for i in range(k-1):
if pos_k.next:
pos_k = pos_k.next
else:
return pos... |
c4a4c6bd68a6730a1af26fd8e7ee1ac39020c8c7 | ientropic/data | /list_sum.py | 373 | 4.03125 | 4 | def list_sum(numList):
theSum = 0
for i in numList:
theSum = theSum + i
return theSum
#print(listsum([1,3,5,7,9]))
#These test cases check that list_sum works correctly
test1 = list_sum([1, 2, 3])
print("expected result: 6, actual result: {}".format(test1))
test2 = list_sum([-1, 0, 1])
print("e... |
7e20b377cf069093ea362fef25774057a3bdd22b | bilbatez/impractical-python-projects | /finding-voldermort/voldermort_british.py | 3,992 | 3.78125 | 4 | #!/usr/bin/env python3
"""
Finding Voldermort.
Author: Albert Julian Tannady <me@albertjtan.com>
"""
import sys
from itertools import permutations
from collections import Counter
from load_dictionary import load
def main():
"""Load files, run filters, allow user to view anagrams by 1st letters."""
name = "t... |
3fad08544066c1661e49e1292eb581bdde8a5d3b | Shubham-Tripathi-DS/Binary-Search-Tree | /Btree.py | 4,832 | 3.9375 | 4 | #Date: 26-09-18
#Author: Suraj Kumar
#Roll No: 181046037
class BST:
class _TreeNode:
def __init__(self,ele):
self.data=ele
self.left=None
self.right=None
def __init__(self):
self.root=None #stores the reference of root
self.count=0
### Adding a Node to A tree ####
def add_node(self,ele)... |
1967736dd7d65b2be735539c9f625472f3cebdc8 | vuminhkhue/C4E8 | /S3_homework.py | 784 | 3.90625 | 4 | print("hello, my name is Khue and there are my ship sizes")
list_sheep =[5,7,300,90,24,50,75]
print(list_sheep)
months =3
for m in range(months):
max= 0
for i in range(7):
if list_sheep[max]< list_sheep[i]:
max = i
print("now my biggist sheep has",list_sheep[max],"let's... |
dda2d40bf80a81ddfdf8009dcbe60264c7af9337 | andreaslordos/Olympia | /code/startup.py | 9,725 | 3.703125 | 4 | def setMeUp(confirmedName,confirmedBirthday,confirmedGender,confirmedLocation):
'''
Input: confirmedName, boolean /// confirmedBirthday, boolean /// confirmedGender, boolean /// confirmedLocation, boolean
Output: name, string /// gender, string /// dateofbirth, string /// location, string
Explanation:
... |
5c68ca3b6ea7ded0b2aa5fb837f1c738ebef160f | andreaslordos/Olympia | /code/determiner.py | 5,160 | 4.1875 | 4 | def determine(userinput):
'''
Input: userinput, string
Output: moduleToRun, string
userinput = What the user said
moduleToRun = What module the user requested
Explanation:
Firstly, the module figures out which modules the user *possibly* requested using the whichModule function.... |
2cc393287f3d2a6a66d9303d9ae0fb80f471aee0 | msaroufim/UndergradPythonDS | /quicksort.py | 1,825 | 3.78125 | 4 | class QuickSort:
def filterQuickSort(self,alist):
"""
Functional style implementation using filters
Elegant but highly inneficient since filter needs
to scan the whole list and evaluate the filter predicate on each element
O(N!) is not gonna work in the real world no matter how elegant this is
"""
if a... |
6bb5fe7da5b77c12e4f6f37cd852a5b74478ab3d | wrenoud/aoc2020 | /lib/__init__.py | 628 | 4.125 | 4 | class Coord(object):
def __init__(self, x: int, y: int):
self.x = x
self.y = y
def __add__(self, other):
return Coord(self.x + other.x, self.y + other.y)
def __sub__(self, other):
return Coord(self.x - other.x, self.y - other.y)
def __len__(self) -> int:
"""ret... |
3cd97631c511eef7851089c05de4afac525e8f36 | anthonykawamoto/toys | /toys.py | 3,386 | 3.65625 | 4 | """
Must be run from run_toy_robots.py or run_toy_robots.sh
"""
TABLE_LENGTH = 5 # assume square table
DIRECTIONS = {
'NORTH': {
'coords': (0, 1),
'left': 'WEST',
'right': 'EAST'},
'SOUTH': {
'coords': (0, -1),
'left': 'EAST',
'right': 'WEST'},
'EAST': {
... |
8e84ba212d23c8a5a4f3000afbb04eef1d0b2912 | jkirlans5282/Seymour | /algorithm.py | 3,175 | 4.0625 | 4 | #Algorithm Test
#nested dictionary, {username:{resturant:rating}}
users = {
"tom":{"a":1,"b":1,"c":0,"d":-1,"h":1,"f":1},
"beth":{"a":1,"d":-1,"e":1},
"mike":{"b":1,"e":1,"h":1},
"emma":{"d":1,"g":0,"e":1}
}
def addUser(username):
users[username]={}
def addRestaurant(restaurant,username):
while True:
... |
4c7e8722816c66f75ab087b5ab10ddd46d661609 | jasim-tech/Pandas | /Pandas.py | 2,051 | 3.71875 | 4 | #!/usr/bin/env python
# coding: utf-8
#
# Data loading in to pandas
# In[141]:
import pandas as pd
#load as txt file
df=pd.read_csv('pokemon_data.csv')
#load as csv file
#df=pd.read_csv('pokemon_data.txt',delimiter='\t')
print(df)
#
# Reading Data in pandas
#
# In[142]:
import pandas as pd
#print columns na... |
aad7acc3b5af6b1640d15ee9c04ed7be740b4ed3 | FritzHeider/FritzHeider-CS-1.2-Intro-Data-Structures | /Code/histogram.py | 648 | 3.71875 | 4 | from sys import argv
import sys
import re
text_input = str(sys.argv[1:])
#print(text_input)
def dict_hist(text_input):
text_list = re.split('\W+', text_input)
histo = dict()
for word in text_list:
if word.upper() in histo:
histo[word.upper()] += 1
else:
histo[word.u... |
38f47bbe179c573bcbd0241decac5c5ee565a03e | TheCacophonyProject/audio-classifier | /python/code/auxilary_functions.py | 1,195 | 3.71875 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu May 30 17:20:38 2019
@author: tim
"""
import os
import librosa
import pickle
import parameters
def convert_wav_files_to_array_pickles():
# Created this to covert all the wav files that came with the tutorial
# to numpy arrays, so can test if th... |
041f1e546ed2090c06340402049b5570d5581bf3 | SS-christianReyes/python | /day2-1.py | 677 | 3.796875 | 4 | print('Hello World'[8])
print('thinker'[2:5])
s = 'hello'
print(s[1])
s = 'sammy'
print(s[2:])
word = 'Mississipi'
def distinct(word):
return ''.join(set(word))
print(distinct(word))
#palindrome
alphabet = 'abcdefghijklmnopqrstuvwxyz'
def justText(word):
text = ''
for i in word.lower():
if alphabet... |
14301f33066e2b50d76cb0513d512356724c40b5 | cvasqxz/hashwar | /__main__.py | 1,341 | 3.609375 | 4 | from extras import checkAddr, logo
from character import character
from random import randint
def main():
print("\n" + logo)
print(" v0.0.01 // 09.01.2019 // @cvasqxz\n")
addr1 = input("> Enter valid address #1: ")
addr2 = input("> Enter valid address #2: ")
addr1 = "cRomsSTmwGCn2aGSrxik26iqTf655juUBR"
addr2... |
3b72cf3f9878c6a37ba0274f31df18f4f3a5ad69 | khusheimeda/Big-Data | /Assignment1 - Map Reduce/reducer.py | 789 | 4.125 | 4 | #!/usr/bin/python3
import sys
# current_word will be used to keep track of either recognized or unrecognized tuples
current_word = None
# current_count will contain the number of tuples of word = current_word seen till now
current_count = 0
word = None
for line in sys.stdin:
line = line.strip()
word,... |
e24ce800e1728c1c8e19f194004d766e71fa0dc1 | jgoodricke/ie-digital-coding-challenge | /ie-digital-coding-challenge/commandInput.py | 1,604 | 3.953125 | 4 | from Pacman import Pacman
class CommandInput(object):
"""Interprets commands and sends them to Pacman class"""
def __init__(self):
self.pac = Pacman()
#Method for interpreting inputCommand
def _execute(self, inputCommand):
inputCommandSplit = inputCommand.split(" ")
#Move
... |
68fa73c70227ff2281d193b840c8dbff72634de2 | beth-gooding/bnta_cohort1_queens-puzzle | /Queen.py | 1,068 | 3.875 | 4 | from Piece import Piece #The Queen class inherits from the Piece class, so we need to import that class here
class Queen(Piece): #This notation is like class Queen extends Piece in JS
def __init__(self): #Constructor function for the Queen class,
... |
732dd95ae29a11fd3d8a407f93257f571ffd07fe | AlperKoc/LeetCode_Problems | /#9_PalindromeNumber.py | 424 | 3.515625 | 4 | class Solution:
def isPalindrome(self, x):
x = str(x)
first = 0
last = len(x)-1
palyndrome = True
for i in range(len(x)//2):
if x[first] != x[last]:
palyndrome = False
break
first+=1
last-=1
if palynd... |
e1459fc2c2d9f16fdc4a955f1c4024c4bc41a33c | igor-nov/algorithms | /3sum_15.py | 6,221 | 3.90625 | 4 | """
15. 3Sum
Solution 1
Runtime: 2336 ms, faster than 6.34% of Python3 online submissions for 3Sum.
Memory Usage: 17 MB, less than 25.00% of Python3 online submissions for 3Sum.
Solution 2 - optimized 1
Runtime: 1384 ms, faster than 28.46% of Python3 online submissions for 3Sum.
Memory Usage: 16.1 MB, less than 100.0... |
18b362fb2e1cb691852d52905d1cd538ceed13f4 | igor-nov/algorithms | /copy-list-with-random-pointer.py | 2,995 | 3.734375 | 4 | """
138. Copy List with Random Pointer
A linked list is given such that each node contains an additional random pointer which could point to any node in the list or null.
Return a deep copy of the list.
Solution:
+++ Clone A Linked List (With Random Pointers) - Linear Space Solution & Tricky Constant Space Solution ... |
e213c4b9272a307b55d03a92366b5406855be7bc | igor-nov/algorithms | /word-break.py | 5,820 | 3.859375 | 4 | """
139. Word Break
Given a non-empty string s and a dictionary wordDict containing a list of non-empty words, determine if s can be segmented into a space-separated sequence of one or more dictionary words.
Note:
The same word in the dictionary may be reused multiple times in the segmentation.
You may assume the dic... |
50da659f7e26592e314b80cad487d2859d6dff8d | igor-nov/algorithms | /trapping-rain-water_42.py | 7,179 | 3.75 | 4 | """
42. Trapping Rain Water
##Array ##Two Pointers ##Stack
Solution 1 - O(n) time - O(n) space (2n)
Runtime: 56 ms, faster than 39.27% of Python3 online submissions for Trapping Rain Water.
Memory Usage: 13.2 MB, less than 100.00% of Python3 online submissions for Trapping Rain Water.
Solution 2 - just one s... |
a28a115e3f8518490135442b55ce967be17c3c16 | igor-nov/algorithms | /insert-delete-getrandom-o1-duplicates-allowed_381.py | 7,113 | 3.6875 | 4 | """
381. Insert Delete GetRandom O(1) - Duplicates allowed
Solution 1
Runtime: 128 ms, faster than 13.46% of Python3 online submissions for Insert Delete GetRandom O(1) - Duplicates allowed.
Memory Usage: 18.1 MB, less than 100.00% of Python3 online submissions for Insert Delete GetRandom O(1)
Solution 2
Runtime: 168... |
20abe422a8c523d645826a7dc953f91e3449d2fd | igor-nov/algorithms | /increasing-decreasing-string_1370.py | 5,932 | 3.859375 | 4 | """
1370. Increasing Decreasing String
Solution 1
Runtime: 68 ms, faster than 58.45% of Python3 online submissions for Increasing Decreasing String.
Memory Usage: 12.7 MB, less than 100.00% of Python3 online submissions for Increasing Decreasing String.
Solution 2
Runtime: 208 ms, faster than 10.10% of Python3 online... |
661b3485ff919f0fd1c88c1545db1e429c694398 | igor-nov/algorithms | /find-the-longest-substring-containing-vowels-in-even-counts_1371.py | 9,907 | 3.640625 | 4 | """
1371. Find the Longest Substring Containing Vowels in Even Counts
#####################
Optimized brute force
Solutions
[Python] Easy Sliding Window - https://leetcode.com/problems/find-the-longest-substring-containing-vowels-in-even-counts/discuss/531870/Python-Easy-Sliding-Window
[Python] Solution Sliding Wind... |
2809db8d65eb802d55c2bb9714c38d4dac331596 | igor-nov/algorithms | /maximal-square_221.py | 8,744 | 4.03125 | 4 | """
221. Maximal Square
Solution 1 - uses (m+1)*(n+1) matrix
Runtime: 220 ms, faster than 43.64% of Python3 online submissions for Maximal Square.
Memory Usage: 13.8 MB, less than 95.45% of Python3 online submissions for Maximal Square.
Solution 2 - same but uses m*n dp matrix
Solution 3 - O(m) - dp matrix
Runtime: ... |
d6e91315eb784db2a03c3e150fa4dff7acbfdeb5 | igor-nov/algorithms | /majority-element.py | 2,988 | 3.859375 | 4 | """
169. Majority Element
Given an array of size n, find the majority element. The majority element is the element that appears more than ⌊ n/2 ⌋ times.
You may assume that the array is non-empty and the majority element always exist in the array.
Example 1:
Input: [3,2,3]
Output: 3
Example 2:
Input: [2,2,1,1,1,2,2]... |
6fa80b17f8d8565a6da66efcb174740a9ebfa880 | igor-nov/algorithms | /search-in-rotated-sorted-array_33.py | 7,734 | 3.671875 | 4 | """
33. Search in Rotated Sorted Array
Solution 1 - search pivot On and binary search - wrong solution!!!
Runtime: 32 ms, faster than 96.30% of Python3 online submissions for Search in Rotated Sorted Array.
Memory Usage: 12.7 MB, less than 100.00% of Python3 online submissions for Search in Rotated Sorted Array.
Solu... |
9e1ccd331a002d0ad461600b3ce489417c52e01e | igor-nov/algorithms | /count-largest-group_1399.py | 2,307 | 3.78125 | 4 | """
1399. Count Largest Group
Solution 1
Runtime: 132 ms, faster than 11.11% of Python3 online submissions for Count Largest Group.
Memory Usage: 13.8 MB, less than 100.00% of Python3 online submissions for Count Largest Group
Solution 2
Runtime: 132 ms, faster than 11.11% of Python3 online submissions for Count Larg... |
340c7fc0ccbdf6fff853cf3d183a410ffb394ba6 | igor-nov/algorithms | /daily-temperatures_739.py | 3,536 | 3.828125 | 4 | """
739. Daily Temperatures
Solution 1
Runtime: 480 ms, faster than 92.43% of Python3 online submissions for Daily Temperatures.
Memory Usage: 16.9 MB, less than 34.21% of Python3 online submissions for Daily Temperatures.
Solution 2 - reverse order
Runtime: 496 ms, faster than 69.99% of Python3 online submissions fo... |
56a02d97f07d8c5adee56c4ced06156e48e96b2d | igor-nov/algorithms | /wildcard-matching.py | 6,406 | 3.84375 | 4 | """
44. Wildcard Matching
Given an input string (s) and a pattern (p), implement wildcard pattern matching with support for '?' and '*'.
'?' Matches any single character.
'*' Matches any sequence of characters (including the empty sequence).
The matching should cover the entire input string (not partial).
Note:
s co... |
2996516af201e4bf6ba552dcad0c08b5ad308d57 | Stairwaytoknowledge/Neo | /m6-Sample_testing.py | 3,509 | 3.921875 | 4 |
#import mean
from statistics import mean
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import style
#import random data
import random
style.use('fivethirtyeight')
#xs = [1,2,3,4,5,6]
#ys = [5,4,6,5,6,7]
#converting python list to numpy array
#xs = np.array([1,2,3,4,5,6], dtype = np.float6... |
b07cac89303fca4afa8350fafdbb0cc7a4999112 | ericrpowers/py_ms | /Solver.py | 13,128 | 4.125 | 4 | """ This will house the strategy/logic needed to solve
Minesweeper automatically. The current thought process
is the following:
1) Identify all safe moves and mines based on immediate neighbors
2) Identify all safe moves based on known mines
3) Identify all safe moves by using neighbors' info
4)... |
9ce6d36ed817b6029a056e3dbd9e6581a00853e5 | KirthanaRamesh/MyPythonPrograms | /decimal_To_Binary.py | 1,577 | 4.53125 | 5 |
# Function for separating the integer and fraction part from the input decimal number.
def separation_of_integer_and_fraction():
global decimal_number, decimal_integer, decimal_fraction
decimal_integer = int(decimal_number)
decimal_fraction = decimal_integer - decimal_number
# Function to convert integer... |
f2043b8f69852bb2f4fc6c4331d135b8ca56f30c | Sigtamx/EDD-HOFJ | /ColaPop.py | 818 | 3.6875 | 4 | cola=[]
index=0
size=5
def create():
for I in range(size):
cola.append(0)
return cola
create()
def push(Val):
global index
if index < size:
cola[index] = Val;
print(cola[index])
#print(index)
index+=1
else:
print("**********... |
409e2fc12f0a27a26d2b84e830e79694509c5063 | Sigtamx/EDD-HOFJ | /Practica2u1.py | 671 | 4.25 | 4 | """
Desplegar y calcular factorial de un numero dado por el usuario con recursividad
"""
m=1
def factorialRecursivo(n):
global m
if(n>1):
m*=n
n-=1
factorialRecursivo(n)
else:
print(m)
print("Fin")
print("Ingrese el numero para usar factorial:... |
11ea6c1b7060e0410a530e6fd24e7eada6e826e7 | Sigtamx/EDD-HOFJ | /PilaPop.py | 475 | 3.953125 | 4 | pila = []
size = 5
def push(Valor):
if len(pila) < size:
pila.append(Valor)
print("Valor ingresado")
else:
print("Pila llena")
def pop():
if 0 < len(pila):
print("Valor del tope de la pila:")
print(pila[len(pila)-1])
del(pila[len(pila... |
93a58fcf1ddca9944009e8a001e2341003d61833 | wigasper/jennys-pdf-util | /pageinserter.py | 930 | 3.96875 | 4 | #!/usr/bin/env python3
#
# This script takes a PDF file and inserts a blank page between every
# page in the PDF. Output is written to the containing directory of
# the original PDF.
import os
import sys
from PyPDF2 import PdfFileReader, PdfFileWriter
import tkinter as tk
from tkinter import filedialog
# Use TkInter... |
d0ca1715391fdbd24aa05470fc67f04d623fe335 | entrekid/daily_algorithm | /2020/0420/2447.py | 226 | 3.65625 | 4 | N = int(input())
graph = [[0] * N for _ in range(N)]
def solve(x, y, N):
for iter in range(3):
for jter in range(3):
graph[x + iter * N][y + jter * N] = " "
else:
N = N // 3
solve(N) |
4c588db5d248ba9fcbb9b3480e3a418c8a817966 | entrekid/daily_algorithm | /2020/0411/2250.py | 1,125 | 3.546875 | 4 | """
같은 레벨의 노드는 같은 행에 위치한다.
한 열에는 한 노드만 존재한다.
임의의 노드의 왼쪽 부트리에 있는 노드들은 해당 노드보다 왼쪽의 열에 위치하고,
오른쪽 부트리에 있는 노드들은 해당 노드보다 오른쪽의 열에 위치한다.
노드가 배치된 가장 왼쪽 열과 오른쪽 열 사이엔 아무 노드도 없이 비어있는 열은 없다.
"""
# 행은 트리의 level을 뜻한다.
# 열의 의미는 인오더 방문순서
import sys
input = sys.stdin.readline
N = int(input())
tree = {}
check = [False] * (N + 1)
che... |
2c78a6cf261523c934e090528000b2ceba9a9913 | entrekid/daily_algorithm | /2020/0411/10992.py | 319 | 3.59375 | 4 | import sys
N = int(input())
start = 0
end = N - 1
if start == end:
print(" " * (N - 1) + "*")
sys.exit(0)
else:
# start
print(" " * (N - 1) + "*")
# middle
for iter in range(1, N - 1):
print(" " * (N - iter - 1) + "*" + " " * (2 * iter - 1) + "*")
# end
print("*" * (2 * N - 1))
|
9616a6d62872851666cfb3e5df3baf34b652d0d4 | KnightTuring/sample_test | /src.py | 2,112 | 4.09375 | 4 | import wikipedia as wiki
import os
CONTENT_FILE="tempContentFile.txt"
'''
I needed a display like the man page. less serves that purpose.
TODO:
Please move to a better alternative; less is just temporary
'''
TERM_COMMAND_TEXT_DISP="less"
'''
TODO for inputFromUser()
-> take input as command line arguments
-> add f... |
d67fd5464e7e1bd583adf00944bb88d7f1f15c96 | Alweezy/number_of_vehicles_between_two_plates | /plate_diff.py | 1,698 | 3.75 | 4 | # Dictionary to give the value of any alpha plate character
from string import ascii_uppercase
from collections import OrderedDict
plates_alpha_value = OrderedDict((character, index) for index, character in enumerate(ascii_uppercase, 1))
def vehicleCount(latest_plate, older_plate):
diff_alpha_second = plates... |
2fe6cdcb2c39cf8ca1f9b85ae51568d60566c1e9 | gustavoluissiqueira/desafios_python | /Exercicios/ex003.py | 309 | 4.03125 | 4 | #Desafio 003 -Crie um programa que leia dois números e mostre a soma entre eles
nome = str(input('Digite seu nome:'))
n1 = int(input(f'{nome}, digite um número inteiro:'))
n2 = int(input(f'{nome}, digite mais um número inteiro:'))
soma = n1 + n2
print(f'{nome}, a soma entre {n1}+{n2} é igual {soma}. ') |
ed4ffd16581ff19ffa4852ca71ad69deaa00b6b3 | mrtnzagustin/platzi-python-intermediate-course | /divisors_with_asserts.py | 637 | 4.03125 | 4 | def divisors(number):
divisors = []
# Test from 1 to number if the number is divisible and collect al divisors
for divisor in range(1, number+1):
if number % divisor == 0:
divisors.append(divisor)
return divisors
def run():
try:
# Ask for a number
number = input(... |
727adbc50c418602133389acfe46be796632e5d1 | Dettrax/digitclassifier | /Code/nnet/activation.py | 1,171 | 3.5 | 4 |
import torch
def sigmoid(z):
"""Calculates sigmoid values for tensors
"""
result = 1.0 / (1 + torch.exp(-z))
return result
""" The derivative of sigmoid can be written as exp(-z) * ( 1 / (1 + exp(-z)**2))
on further simplifying (subraction of inner bracket value by 1 and taking sigmoi... |
005fd75f1dfca14a917da61d93fc8cebe0adad6d | zdenkoo98/programacion-1-python- | /Ejercicios/Ciclos/ejercicio 8.py | 431 | 3.5625 | 4 | i=0
claveprimera=''
clavesegunda=''
print("Ingrese clavemaestra")
clavemaestra=input()
x=len(clavemaestra)
print(x)
while i < x +1:
if i % 2 == 0:
z=clavemaestra[i]
clavesegunda=clavesegunda + clavemaestra[i]
i=i+1
else:
z=clavemaestra[i]
claveprimera=claveprimera + clavemaestra[... |
56b17d8e9567aa240d88706371764fcff9c67ee0 | zdenkoo98/programacion-1-python- | /Ejercicios/Condiciones/ejercicio 3.py | 286 | 4 | 4 | print("Ingrese 3 numeros")
a=int(input())
b=int(input())
c=int(input())
if a > b and a > c:
a=str(a)
print(a + " es el mayor numero")
elif b > a and b > c:
b=str(b)
print(b + " es el mayor numero")
elif c > a and c > b:
c=str(c)
print(c + " es el mayor numero")
|
9dac3119e2a10ed832fe00f4025fe32e01cde6b2 | zdenkoo98/programacion-1-python- | /Ejercicios/Funciones/ejercicio 8.py | 508 | 4.03125 | 4 | def func(a):
if a%2==0 and a >2:
print("El numero no es primo")
elif a%3==0 and a>3:
print("El numero no es primo")
elif a%5==0 and a> 5:
print("EL numero no es primo")
elif a%7==0 and a>7:
print("EL numero no es primo")
elif a%11==0 and a>11:
print(... |
05b0a48e8b064f082f50e78a85611edbd78bd543 | zdenkoo98/programacion-1-python- | /Ejercicios/Variables/ejercicio 4.py | 111 | 3.546875 | 4 | import time
a= 10
b= 2
c= a + b
if c/2==1:
print("El numero es impar")
else:
print("El numero es impar")
|
b4a49d247eb98d1e96d7e0ae54087dc247d07f3a | sw-devendra/algo-practice | /python-tricks/lru-2.py | 2,206 | 3.546875 | 4 | # Well Tested (passed on leetcode)
from __future__ import annotations
import typing
class Node:
def __init__(self, key =None, next: Node = None, prev: Node = None) -> None:
pass
class DLQ:
def __init__(self) -> None:
self.head = Node()
self.tail = Node()
self.head.next = self.... |
8052067b750fd9a1870d0efbf6ffb305a9d78486 | mandeep0405/data_structures | /linkedlist/merging_2_list.py | 1,192 | 4.09375 | 4 | class Node:
def __init__( self, data ):
self.data = data
self.next = None
class LinkedList:
def __init__( self ):
self.head = None
self.tail = None
def AddNode( self, data ):
new_node = Node( data )
if self.head == None:
self.head = new_node
if self.tail != None:
self.tail.next = new_node
sel... |
2828cdbf3154ddb4fcf9c818e9de9f37cbc40746 | prahacheuski/math2application | /_methods/bisection_method.py | 889 | 3.59375 | 4 | # coding=utf-8
from typing import Tuple
from . import IMethod
class BisectionMethod(IMethod):
@staticmethod
def calculate(func, interval: Tuple[int or float, int or float], epsilon: float) -> Tuple[float, int]:
"""
TODO: Write a description.
:param func:
:param interval:
... |
80da9bcb95fb306b2a773c291e1d7b90a7f134e6 | MrCaiting/Neural-Network | /cnn.py | 10,265 | 3.515625 | 4 | import matplotlib
matplotlib.use('TkAgg')
import matplotlib.pyplot as plt
import tensorflow as tf
import numpy as np
import pandas as pd
# define all functions for use
# set up one-hot vectors
def one_hot(labels, numbers):
num_of_labels = len(labels) # how many labels in total
one_hot = np.zeros((num_of_labels... |
6b8bf1fd5506f086a1367c35f416315b8cc8b8bb | jeffder/legends | /main/utils/misc.py | 621 | 4.3125 | 4 | # Miscellaneous utilities
from itertools import zip_longest
def chunks(values, size=2, fill=None):
"""
Split a list of values into chunks of equal size.
For example chunks([1, 2, 3, 4]) returns [(1, 2), (3, 4)].
The default size is 2.
:param values: the iterable to be split into chunks
:param... |
38b09b7b4366320162808c297005c605fbb1b7e1 | ben-marshall/microcoder | /pyucode/UCInstructions.py | 8,545 | 3.875 | 4 |
"""
Classes and functions for representing instructions.
"""
import re
import sys
import logging as log
from .UCInstructionStatement import UCInstructionStatement
class UCInstructionArgument(object):
def __init__(self, src=None):
"""
Create a new instruction argument using a string source.
... |
6dbfaa2bdac2d44559734a8dca92f888dc703a46 | ulamaca/DRLND_P3_MultiAgent_RL | /utils.py | 350 | 3.640625 | 4 | import random
# Misc
def random_color(choice=False):
"select the color code from "
lib=['r', 'b', 'g', 'k', 'y', 'c', 'm']
if isinstance(choice, int):
if choice<=6:
return lib[choice]
else:
raise ValueError("choice value should be less than/equal to 6")
else:
... |
5bdda96ed8ed67cb9ae0718fdad501c1205767d3 | mihaivalentistoica/Algorithms_Data_Structures | /01-recursion/rezolvare_exercise2.py | 215 | 3.8125 | 4 | def fibonacci(n):
if n < 0:
return ''
if n == 0 or n == 1:
return n
return fibonacci(n - 1) + fibonacci(n - 2)
sir = ''
for i in range(20):
sir += str(fibonacci(i)) + ' '
print(sir) |
0649d4edfd70e8836a98437b1860c7f7709adaae | mihaivalentistoica/Algorithms_Data_Structures | /01-recursion/example-01.py | 319 | 4.34375 | 4 | def factorial(n):
"""Factorial of a number is the product of multiplication of
all integers from 1 to that number. Factorial of 0 equals 1.
e.g. 6! = 1 * 2 * 3 * 4 * 5 * 6
"""
print(f"Calculating {n}!")
if n == 0:
return 1
return n * factorial(n - 1)
print(f"6! = {factorial(6)}")
|
4aa138ffcd76a40fbf851181924c22d2dd9faa9c | smrrrazu/pythontut | /forloop.py | 311 | 3.875 | 4 | fruits =['apple','orange','banana']
#for loop from list
for f in fruits[:1]:
print (f)
print (len(f))
#for loop with range
for x in range(10):
print(x)
print("----------")
for x in range(10,40,2):
print(x)
# while loop
triger = True
while triger
# some comments
# some comments from sheikh ubuntu
|
d681c9ae54e7eeddce52d24655a59e97cb3efadb | MarcelKukurowski/Pogoda_Obiektowo | /teoria_operatory.py | 816 | 3.890625 | 4 | class Animal:
def __init__(self, name, age):
self.name = name
self.age = age
def __str__(selft):
return 'f{self.name} {self.age}'
# MATEMATYCZNE
def __add__(self, other):
self.age = self.age + int(other)
return self.age
def __sub__(self, other):
sel... |
195c775cb4f2e746c1b2e1b7cf9de493058f889e | editazhu/scripting | /wordcounter.py | 832 | 3.671875 | 4 | import re
import sys
from collections import Counter
class WC:
def __init__(self, filename):
self.filename = filename
#Reading file
def open_file(self, filename):
with open(filename, 'r') as f:
file_contents = f.read()
return file_contents
def counts(self):
wc_file = self.open_file(self.filename)
#... |
ae75bd495cc002d56b87ac85660c82532134b32e | sylmarien/Poly-works | /INF8225/TP3/rendu/learningModule.py | 4,072 | 3.546875 | 4 | import numpy as np
import dataManagement
# Function that compute the output of the neural network for the given x input
def networkFeedForward(x, hiddenLayers, outputLayer):
# feedForward
outputPreviousLayer = x
for layeri in hiddenLayers:
outputPreviousLayer = layeri.feedForward(outputPreviousLay... |
582856d3d4e3bc4a654f15b03bfa472cfac6f127 | code-11/GPRO | /Level2/ttt4.py | 8,537 | 3.921875 | 4 | #!/usr/bin/env python
#
#
# Game Programming, Level 2 Project
#
# TIC-TAC-TOE 4
#
# A simple input_strategy game, an extension of the standard 3x3 tic-tac-toe
#
import sys, cProfile
from graphics import *
size = 200
minDict = {}
maxDict = {}
WIN_SEQUENCES = [
[0,1,2,3],
[4,5,6,7],
[8,9,10,11],
[12,1... |
fd794814f92a54f570e73656b7139db0ac2c72b2 | code-11/GPRO | /Level5/block.py | 688 | 3.609375 | 4 | from drawing import *
class Block(object):
def __init__(self,x,y,width,height,sprite):
self._x=x
self._y=y
self._width=width
self._height=height
## print sprite
self._sprite=sprite
def on_draw(self):
draw_rectangle_alt(self._x,self._y,self._width,self._heig... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.