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 |
|---|---|---|---|---|---|---|
4bbc746b1d384eb3c84a90f6037295ec599277b4 | parwell/Project-Euler | /Solved/002.py | 619 | 3.734375 | 4 | # Even Fibonacci Numbers
# Runtime 0.000 seconds
import time
start = time.time()
def genFibs(limit):
first = 1
second = 2
numbers = [1,2]
current = 0
while True:
current = first + second
if current >= limit:
break
numbers.append(current)
first = second
... |
c306bf38b4d5341fa26d3f022ea4d04bccdfda88 | parwell/Project-Euler | /Solved/009.py | 1,182 | 3.859375 | 4 | # Special Pythagorean Triplet
# Runtime 0.016 seconds
import time
start = time.time()
def findTriple(upper):
triples =[]
for a in range(1,upper+1):
for b in range(a,upper+1):
for c in range(b,a+b):
if a**2 + b**2 == c**2:
if a + b + c <= 1000:
... |
446b993dd15f8dbe684b7132a25b465cf431d4d8 | aalmsaodi/Algorithms | /after-session-2.py | 4,014 | 3.828125 | 4 | #Linked Lists: Swap List Nodes in pairs ************************************
class Solution:
# @param A : head node of linked list
# @return the head node in the linked list
def swapPairs(self, A):
counter = 0
tempValue = A.val
currentNode = A
while currentNode.next ... |
967410b51d41f20d4312cb92bfda0a1411c934ce | Vincent-Chung/SqueakyClean | /SqueakyClean/squeakytime.py | 2,728 | 3.671875 | 4 | '''
Data wrangling functions to supplement pandas
Intention is to cleanly abstract procedures for piping within method chains
Example:
df_new = (df_original
.pipe(ColKeepie, ColList = ['vendorMasterCode','ElectronicsFlag','TransactionDate'])
.rename(columns={"vendorMasterCode" : "vendorCode"})
... |
aa6f78b195251ed89b4c81287ea5974f23ddcb18 | akleeman/slocum | /slocum/lib/angles.py | 2,609 | 3.640625 | 4 | import pyproj
import numpy as np
def angle_normalize(a, degrees=True):
if degrees:
a = np.mod(a + 180, 360) - 180
else:
a = np.mod(a + np.pi, 2 * np.pi) - np.pi
return a
def angle_diff(a, b=None, degrees=True):
"""
Computes the angular difference between angle a
and angle b. ... |
bad55fdf1388f97043b8b7687ce98e5a5294c54b | cristian-mercadante/PongDuelSimulation | /agents.py | 10,688 | 3.625 | 4 | from abc import ABC, abstractmethod
NOOP = 0
UP = 1
DOWN = 2
class Agent(ABC):
# Abstract class for creating agents
def get_ball_dir(self, ball_dir_list):
if ball_dir_list[0] == 1:
return "NW"
elif ball_dir_list[1] == 1:
return "W"
elif ball_dir_list[2] == 1:
... |
ef54a3e02a38255deb3f734c575e8e5364bc002c | Ling-Alma/my_python_notes | /03_03_other_types.py | 2,778 | 3.8125 | 4 | ## Other types
# Reminder, this assumes you have setup an envioronment with conda using:
# conda create --name py38 python=3.8
# and that you have then activated it:
# conda activate py38
list_1 = [4, 5, 6]
print('list_1', list_1)
dictionary_1 = {23: "Favorite number", 24: "Second favorite number"}
print('dictionary_... |
02b7729d433060192070a91a75679560b1c8377f | Ling-Alma/my_python_notes | /04_03_knn_iris.py | 4,099 | 3.65625 | 4 | # Author: Justin A Johnson. Adapted from sklearn documentation and original content. License: Modified BSD License.
import numpy as np
from scipy import sparse
import pandas as pd
import os
from sklearn.model_selection import train_test_split
# Here we will use the built-in dataset load_iris to make a K-Nearest-Neig... |
4974367c2ffb209342fba5332d47f46904bc6497 | Tyler-Henson/Python-Crash-Course-chapter-10 | /silent_cats_and_dogs.py | 794 | 3.84375 | 4 | <<<<<<< HEAD
"""
Problem 10-9 of Python Crash Course
"""
def print_file(filename):
try:
with open(filename) as file:
print(file.read())
except FileNotFoundError:
pass
file.close()
if __name__ == '__main__':
print_file('cats.txt')
print_file('dogs.txt')
print_file... |
e3e51eeeb615b5043a218b38a2fec484c9ad1c87 | Sukhrobjon/Codesignal-Challenges | /Arcade/Intr/SmoothSailing/sortByHeight.py | 278 | 3.90625 | 4 | def sortByHeight(a):
indices = sorted([i for i in a if i > 0])
for index, item in enumerate(a):
if item == -1:
indices.insert(index, item)
print("a " + str(a))
return indices
a = [-1, 200, 190, 170, -1, -1, 160, 180]
print(sortByHeight(a))
|
19eff193956da31d7bf747a97c0c0a7fe5da9f91 | Sukhrobjon/Codesignal-Challenges | /challenges/remove_duplicates.py | 433 | 4.1875 | 4 | from collections import Counter
def remove_all_duplicates(s):
"""Remove all the occurance of the duplicated values
Args:
s(str): input string
Returns:
unique values(str): all unique values
"""
unique_s = ""
s_counter = Counter(s)
for key, value in s_counter.items():
... |
265204383801b469331347cd232b9a50468c39d8 | Meiirzhan00/Documents | /all documents/python code/classs.py | 614 | 3.90625 | 4 | ##class Name:
## def __init__(self,name):
## self.name=name
##c=Name(['Tom','Bob','Alisa'])
##c1=c.name
##for i in c1:
## print(i)
##print(c1)
##
class Name1:
def __init__(self,name):
self.name=name
def __getitem__(self,item):
return self.name[item]
def __len__(self):
re... |
258568ceeaf215f9c1da6c0c965b4aa026f879e1 | busraugurx/fibonacci | /fibonacci.py | 101 | 3.71875 | 4 | a=1
b=1
fibonacci=[a,b]
for i in range(10):
a,b = b,a+b
fibonacci.append(b)
print(fibonacci)
|
3cc0e30c27f76723175bc9ca8f62bb451c74c703 | MelJan/PyDeep | /pydeep/misc/visualization.py | 26,745 | 4.03125 | 4 | """ This module provides functions for displaying and visualize data.
It extends the matplotlib.pyplot.
:Implemented:
- Tile a matrix rows
- Tile a matrix columns
- Show a matrix
- Show plot
- Show a histogram
- Plot data
- Plot 2D weights
- Plot... |
2e2f33b7cfb659051552fc74a6f23591d914ae22 | jbeltranleon/python-basics | /funciones.py | 693 | 3.546875 | 4 | # El cuerpo de una funcion se diferencia por la identacion que tiene
#(4 espacios respecto a la declaracion de la funcion)
def saludar():
return "Hola"
def despedir():
print ("Chao")
print (saludar())
despedir()
# Funcion con parametros de entrada
def areaTriangulo(base, altura):
resultado = (base*altura)/2
... |
d34356368f59aee8ea5e862f2598de59644e6ce3 | jbeltranleon/python-basics | /ahorcado.py | 2,241 | 3.78125 | 4 | import random
# constante
IMAGES = ['''
+---+
| |
|
|
|
|
=========''', '''
+---+
| |
O |
|
|
|
=========''', '''
+---+
| |
O |
| |
|
|
=========''', '''
+---+
| ... |
bbf4e623592882b9b48990042b14b37da82025bb | jbeltranleon/python-basics | /currencyConverter.py | 401 | 3.765625 | 4 | def run():
print('Currency Converter')
print('Convert from MXN to COP')
print('')
ammount = float(input('Ammount (MXN): '))
result = foreign_exchange_calculator(ammount)
print('${} Mexican Pesos are ${} Colombian Pesos'.format(ammount, result))
print('')
def foreign_exchange_calculator(ammount):
mxn_to_cop... |
59d9cc1d1d397db34802829e4e44c99c41ddf7df | ankitjain87/miscellaneous | /go-jek/parking_lot.py | 5,179 | 3.734375 | 4 | import sys
class Slot(object):
'''Parking slot with attributes id, level, registration no, level.'''
def __init__(self, slot_id, reg_no, color, level=1):
self.id = slot_id
self.level = level
self.reg_no = reg_no
self.color = color
class ParkingLot(object):
'''Parking lot ... |
2316faceb7d9bdc34b674abd4ea4ceab7a74f1e9 | fathi123456/db_crud | /Exercices.py/exp5.py | 1,169 | 3.5625 | 4 | from exp4 import *
from exp3 import *
def ajoutformation(titre,formateur,prix,durée):
while(titre==""):
titre=input("donner le titre de formation :")
while(formateur==""):
formateur=input("donner le nom de formateur :")
while(prix<30):
prix=int(input("donner le prix de formation :"... |
d0e9c0ecc8fdc37a85cddba15c44f8993ee75d58 | Wisdom-gif/PET328_2021_Class | /mat_bal.py, 3.py | 1,461 | 3.5625 | 4 | #...TRIUMPHANT
# input statements
nx = int(input('How many blocks there are in x-axis?'))
ny = int(input('How many blocks there are in y-axis?'))
boi = float(input('What is the value of initial oil formation volume factor'))
ce = float(input('What is the value of effective compressibility'))
p1 = float(input('What is ... |
56e13230aa108a529301e4d3e74883e9a47b949f | juliafox8/cm-codes | /Lab6/list_a_words.py | 207 | 3.609375 | 4 | def list_a_words(lst):
if lst == []:
return []
if isinstance(lst[0], str) == True:
if (lst[0] != "") and (lst[0][0] == 'a'):
return lst[0] + list_a_words(lst[1:])
|
e26cff4aa05e2a397de5ccd7daad05c84e4285f2 | juliafox8/cm-codes | /Programming_a3/vacation.py | 630 | 3.90625 | 4 | def vacation(places, temps, costs, temp_min):
indexs_with_high_enough_temps = []
for i in range (len(temps)):
temp = temps[i]
#looking up temp and setting it to the 1,2,3 i value (ith)
if temp >= temp_min:
indexs_with_high_enough_temps.append(i)
if len(ind... |
1e8f6ef68b15abb23ab0961bb402f06768bec3c4 | juliafox8/cm-codes | /Programming_a2/test_pa2_v2.py | 2,338 | 3.609375 | 4 | from cone import cone_volume, print_object_volume
from quadratic import quadratic
from list_cubic import list_cubic
# from digit import digit, reverse_num, pal_num
import math
def test_all():
test_cone_volume()
test_print_object_volume()
test_quadratic()
test_list_cubic()
test_digit(... |
039fd2c5573ae6414a85f63e17d06018565b931b | juliafox8/cm-codes | /Programming_a5/shuffle.py | 222 | 3.890625 | 4 | def shuffle(list1, list2):
if list1 == [] or list2 == []:
return []
return [list1[0], list2[0]] + shuffle(list1[1:], list2[1:])
list1 = [1, 3, 5]
list2 = [2, 4, 6]
print(shuffle(list1, list2)) |
47087c38ea9601c71519d6df9e5245ffc81f6d42 | oreogee/python | /python_basic/chapter02_01.py | 2,286 | 3.90625 | 4 | # print 문 (역시 시작은 다 이건가)
print('파이썬 Python Start!')
print("double")
print('''333''')
print("""wow""")
print()
# separator 옵션
print('P', 'Y', 'T', 'H', 'O', 'N')
print('P','Y','T','H','O','N', sep='||')
print('010', '8577', '7170', sep='-')
print('ugeegee', 'gmail,com', sep='@')
print()
# .end 옵션
# print문으로 한줄 이어... |
e18278d472ab449a3524864656540432b7efbfb9 | robinsuhel/conditionennels | /conditionals.py | 365 | 4.34375 | 4 | name = input("What's your name: ")
age = int(input("How old are you: "))
year = str(2017-age)
print(name + " you born in the year "+ year)
if age > 17:
print("You are an adult! You can see a rated R movie")
elif age < 17 and age > 12:
print("You are a teenager! You can see a rated PG-13 movie")
else:
print("You are... |
c05c97cf8dd87bb874ed79a94f1cffa7a4d5ed3b | Anfany/Project-Euler-by-Python3 | /Problem001-100/015 Lattice paths.py | 363 | 3.515625 | 4 | #!/usr/bin/python3.5
# -*- coding: UTF-8 -*-
#Author: AnFany
# Problem015 Lattice paths
hu=list(range(1,22))
hh=[]
i=0
while i<21:
hh.append(hu[:])
i+=1
for j in range(0,21):
hh[0][j]=1
for ii in range(0,20):
for ji in range(0,20):
hh[ii+1][ji+1]=hh[ii][ji+1]+hh[ii+1][ji]
... |
1087d7da76852410373c6bd9c793360c4268595e | Anfany/Project-Euler-by-Python3 | /Problem001-100/066 Diophantine equation.py | 1,265 | 3.59375 | 4 | #!/usr/bin/python3.5
# -*- coding: UTF-8 -*-
#Author: AnFany
# Problem066 Diophantine equation
#Pell方程解题思路
#由X^2-D*Y^2=1。可得根号D约等于X/Y。而根号D恰好可以变为连分数的形式
def GetPell(number):
sboot=number**0.5
#判断是否为完全平方数
if int(sboot)-sboot==0:
return [number]
else:
#开始计算根号D的连分数形式
... |
56a8242e1c87ecc5c94d2c7171589ae8faafcede | Anfany/Project-Euler-by-Python3 | /Problem001-100/010 Summation of primes.py | 750 | 3.828125 | 4 | #!/usr/bin/python3.5
# -*- coding: UTF-8 -*-
#Author: AnFany
# Problem010 Summation of primes
#一般方法:全部数字都遍历 用时:23.517s
def an_prime(number):
for i in range(2,int(number**0.5)+1):
if number%i==0 and number!=i:
return False
return True
anfan=0
for i in range(2,2000000):#全部遍历
... |
1588562753e99f5e3ff8c5f3e4127bfe2efeb3b4 | Anfany/Project-Euler-by-Python3 | /Problem001-100/063 Powerful digit counts.py | 543 | 3.671875 | 4 | #!/usr/bin/python3.5
# -*- coding: UTF-8 -*-
#Author: AnFany
# Problem063 Powerful digit counts
#个数
count=0
#位数从1开始
weishu=1
while 1:
low=10**(weishu-1)#几位数的下限
up=10**weishu-1#几位数的上限
sboot=low**(1/(weishu))#下限的方根
#获得sboot与9之间的整数个数
dd=9-int(sboot)
if dd==0:
print(coun... |
04e09a08aa8d3326267ee633e5561cbbb0196318 | igorgabrig/WebServiceSimples | /TCPServer.py | 2,230 | 3.734375 | 4 | #Importa modulo de soquete
from socket import *
#Cria um soquete do servidor TCP
#(AF_INET usado para protocolos IPv4)
#(SOCK_STREAM e usado para TCP)
serverSocket = socket(AF_INET, SOCK_STREAM)
# Atribui um numero de porta
serverPort = 9900
#Associa o numero de porta do servidor ao socket
serverSo... |
d33b15d30b37b920c428e9515212cdc32f65f43e | wscheib2000/CS1110 | /spellcheck.py | 628 | 3.671875 | 4 | # Will Scheib wms9gv
"""
Checks an inputted line of text for spelling errors.
"""
import urllib.request
link = "http://cs1110.cs.virginia.edu/files/words.txt"
file = urllib.request.urlopen(link)
words = []
for line in file:
words.append(line.decode("utf-8").lower().strip())
print("Type text; enter a blank line ... |
43264f35f210963e7b6aeda37a534bc52302fec5 | wscheib2000/CS1110 | /gpa.py | 966 | 4.21875 | 4 | # Will Scheib wms9gv
"""
Defines three functions to track GPA and credits taken by a student.
"""
current_gpa = 0
current_credit_total = 0
def add_course(grade, num_credit=3):
"""
This function adds a class to the gpa and credit_total variables, with credits defaulting to 3.
:param grade: Grade in the ... |
c90f4c21877404128933639f9de462cf594073f9 | FlorianMarcon/104intersection | /cone_intersection.py | 707 | 3.9375 | 4 | from math import tan, radians
from display import *
def cone_intersection(line, cone):
angle = radians(cone.angle)
angle = pow(tan(angle), 2)
second = pow(line.vector.x, 2) + pow(line.vector.y, 2)
second = second - (pow(line.vector.z, 2) * angle)
first = (line.point.x * line.vector.x) + (line.point.y * line.vecto... |
57413e87cef87c653fbf803609f13e18fc03d468 | GroundP/StudyPython | /OOP/class_instance.py | 808 | 3.640625 | 4 | class User:
def say_hello(some_user):
print("안녕하세요! 저는 {}입니다!".format(some_user.name))
user1 = User()
user2 = User()
user3 = User()
user1.name = "김대위"
user1.email = "captain@codeit.kr"
user1.password = "12345"
user2.name = "강영훈"
user2.email = "younghoon@codeit.kr"
user2.password = "78978"
user3.name = "... |
d97b0b964964feec3189a3cd9f7d64bf12ecb46c | shin-shin-01/algorithm | /sort/selection-sort/main.py | 802 | 3.5 | 4 | import numpy as np
import random
import unittest
def selection_sort(lst):
for i in range(0, len(lst)):
minimum = i
for j in range(i, len(lst)):
if lst[minimum] > lst[j]:
minimum = j
else:
pass
lst[i], lst[minimum] = lst[minimum], lst[... |
9e513c9b29a5acb3b9b62953453b19c2ef23d293 | shin-shin-01/algorithm | /abc/167/d-teleporter/main.py | 861 | 3.640625 | 4 | def main_TLE():
N, K = map(int, input().split())
a = list(map(int, input().split()))
now = 1
visited = []
visited_flg = False
for i in range(K):
bef = now
now = a[bef-1]
# どこからどこ?線で記憶
if {"bef":bef,"aft":now} in visited:
visited_flg = True
... |
81489ec1c08cb2e554b5a1064d602faf926145d3 | spencerbrett/project-euler | /problem24.py | 1,274 | 4.03125 | 4 | ''' Lexicographic permutations
A permutation is an ordered arrangement of objects. For example, 3124 is one possible permutation of the
digits 1, 2, 3 and 4. If all of the permutations are listed numerically or alphabetically, we call it
lexicographic order. The lexicographic permutations of 0, 1 and 2 are:
012 021 ... |
045bd0c8552e3893632231ceb1ab537a0b585160 | cudjoeab/python_fundamentals_1 | /tipping.py | 181 | 3.890625 | 4 |
#info from input is stored in the variable
tip = float(input())
if tip <= 0.10:
print("Thanks.")
elif tip <= 0.15:
print("somethinghappier")
else:
print('validation') |
7b9f10e11a302b9c0cd19821e5c99602894bf53c | caiespin/Connect4_Alpha-beta_Expectimax_Search_AI | /Player.py | 12,616 | 3.5 | 4 | import numpy as np
import random
import math
class AIPlayer:
def __init__(self, player_number):
self.player_number = player_number
self.type = 'ai'
self.player_string = 'Player {}:ai'.format(player_number)
def drop_piece(self, board, row, col, piece):
board[row][col] = piece
... |
e49e5eed2313886539ace816229eaa2d6d294eea | vitalis0itu/standings-simulator | /convert.py | 1,402 | 3.859375 | 4 | import argparse
def main():
parser = argparse.ArgumentParser(
description='Convert csv from tilastopalvelu.fi to a format that standings-simulator can understand. 1. Download schedule as Excel 2. Open in spreadsheet 3. export as csv. Tested with libreoffice 6.0.7.3')
parser.add_argument('-i', '--input... |
e170206db0985d64446d3c885963f50ade83d773 | SeanLuTW/codingwonderland | /lc/lc1233.py | 1,903 | 3.84375 | 4 | """
1233. Remove Sub-Folders from the Filesystem
Given a list of folders, remove all sub-folders in those folders and return in any order the folders after removing.
If a folder[i] is located within another folder[j], it is called a sub-folder of it.
The format of a path is one or more concatenated strings of the fo... |
66140fac83b5d31bbb0669991fc457c1c1949374 | SeanLuTW/codingwonderland | /lc/lc1237.py | 2,077 | 4.09375 | 4 | """
1237. Find Positive Integer Solution for a Given Equation
Given a function f(x, y) and a value z, return all positive integer pairs x and y where f(x,y) == z.
The function is constantly increasing, i.e.:
f(x, y) < f(x + 1, y)
f(x, y) < f(x, y + 1)
The function interface is defined like this:
interface CustomF... |
19a806b0a9afd6f0e00fa8936bca0fa474bea769 | SeanLuTW/codingwonderland | /lc/lc437.py | 3,394 | 3.71875 | 4 | """
437. Path Sum III
You are given a binary tree in which each node contains an integer value.
Find the number of paths that sum to a given value.
The path does not need to start or end at the root or a leaf, but it must go downwards (traveling only from parent nodes to child nodes).
The tree has no more than 1,00... |
4bc774e836a572a63e93c9021ab1f9cb9786f36c | SeanLuTW/codingwonderland | /lc/lc501.py | 1,335 | 3.953125 | 4 | """
501. Find Mode in Binary Search Tree
Given a binary search tree (BST) with duplicates, find all the mode(s) (the most frequently occurred element) in the given BST.
Assume a BST is defined as follows:
The left subtree of a node contains only nodes with keys less than or equal to the node's key.
The right subtree... |
5f9cdd0beac5d1e8110a3479a9edbfa5d4216d9a | SeanLuTW/codingwonderland | /lc/lc1268.py | 2,487 | 3.921875 | 4 | """
1268. Search Suggestions System
Given an array of strings products and a string searchWord. We want to design a system that suggests at most three product names from products after each character of searchWord is typed. Suggested products should have common prefix with the searchWord. If there are more than three ... |
9584c21b4de7189e1870adc1fca447c6a0c83fcf | SeanLuTW/codingwonderland | /lc/lc509.py | 2,070 | 3.984375 | 4 | """
509. Fibonacci Number
The Fibonacci numbers, commonly denoted F(n) form a sequence, called the Fibonacci sequence, such that each number is the sum of the two preceding ones, starting from 0 and 1. That is,
F(0) = 0, F(1) = 1
F(N) = F(N - 1) + F(N - 2), for N > 1.
Given N, calculate F(N).
Example 1:
Input: ... |
dda2be8ff29cb7d923f78814ec3e6a3910d02dd9 | SeanLuTW/codingwonderland | /lc/lc572.py | 1,183 | 3.734375 | 4 | """
572. Subtree of Another Tree
Given two non-empty binary trees s and t, check whether tree t has exactly the same structure and node values with a subtree of s. A subtree of s is a tree consists of a node in s and all of this node's descendants. The tree s could also be considered as a subtree of itself.
Example 1... |
9aaf0b4687dc206435cd628d9ab340201ebcdb33 | SeanLuTW/codingwonderland | /lc/lc1332.py | 1,278 | 3.921875 | 4 | """
1332. Remove Palindromic Subsequences
Given a string s consisting only of letters 'a' and 'b'. In a single step you can remove one palindromic subsequence from s.
Return the minimum number of steps to make the given string empty.
A string is a subsequence of a given string, if it is generated by deleting some ch... |
c8188387bca8ad2e93b50668890ab2f065483660 | SeanLuTW/codingwonderland | /algo_prac/merge sort for linkedlists.py | 3,975 | 4.40625 | 4 | """
Merge Sort for Linked Lists
Merge sort is often preferred for sorting a linked list. The slow random-access performance of a linked list makes some other algorithms (such as quicksort) perform poorly, and others (such as heapsort) completely impossible.
Let head be the first node of the linked list to be sorted an... |
aa5de34d76c0e49d5c443541a312e70b43edb36b | SeanLuTW/codingwonderland | /lc/lc1009.py | 1,558 | 3.65625 | 4 | """
1009. Complement of Base 10 Integer
Every non-negative integer N has a binary representation. For example, 5 can be represented as "101" in binary, 11 as "1011" in binary, and so on. Note that except for N = 0, there are no leading zeroes in any binary representation.
The complement of a binary representation i... |
958b661e6b41e47a301c50420b3133d9356ae167 | SeanLuTW/codingwonderland | /lc/lc922.py | 994 | 3.921875 | 4 | """
922. Sort Array By Parity II
Given an array A of non-negative integers, half of the integers in A are odd, and half of the integers are even.
Sort the array so that whenever A[i] is odd, i is odd; and whenever A[i] is even, i is even.
You may return any answer array that satisfies this condition.
Example 1:
... |
583480d2f366d7fcbf1a9f16c03c40c8e3f1248b | SeanLuTW/codingwonderland | /lc/lc174.py | 2,254 | 4.15625 | 4 | """
174. Dungeon Game
The demons had captured the princess (P) and imprisoned her in the bottom-top corner of a dungeon. The dungeon consists of M x N rooms laid out in a 2D grid. Our valiant knight (K) was initially positioned in the top-left room and must fight his way through the dungeon to rescue the princess.
The... |
961fa9892449ac9b23fcf53bd99ad3497e85d6e6 | SeanLuTW/codingwonderland | /lc/lc1089.py | 1,267 | 3.8125 | 4 | """
1089. Duplicate Zeros
Given a fixed length array arr of integers, duplicate each occurrence of zero, shifting the remaining elements to the right.
Note that elements beyond the length of the original array are not written.
Do the above modifications to the input array in place, do not return anything from your fu... |
3c7792243caf171970559f20e205481f45ce8ecc | SeanLuTW/codingwonderland | /lc/lc221.py | 1,052 | 3.71875 | 4 | """
221. Maximal Square
Given a 2D binary matrix filled with 0's and 1's, find the largest square containing only 1's and return its area.
Example:
Input:
1 0 1 0 0
1 0 1 1 1
1 1 1 1 1
1 0 0 1 0
Output: 4
"""
#PT:DP
"""
intuition:
clear dp question
TC:O(m*n)
SC:O(m*n)
ref:
https://leetcode.com/problems/maximal-... |
30a665a286f0dcd8bd5d60d78fae0d1669f2e0c1 | SeanLuTW/codingwonderland | /lc/lc1464.py | 761 | 4.25 | 4 | """
1464. Maximum Product of Two Elements in an Array
Given the array of integers nums, you will choose two different indices i and j of that array. Return the maximum value of (nums[i]-1)*(nums[j]-1).
Example 1:
Input: nums = [3,4,5,2]
Output: 12
Explanation: If you choose the indices i=1 and j=2 (indexed from ... |
11f39febc4bb55b3581cfd66e60468f57e545524 | SeanLuTW/codingwonderland | /lc/lc1302.py | 1,073 | 3.703125 | 4 | """
1302. Deepest Leaves Sum
Given a binary tree, return the sum of values of its deepest leaves.
Input: root = [1,2,3,4,5,null,6,7,null,null,null,null,8]
Output: 15
"""
# Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = ... |
75ee7211a0fa95f4bfad57d3d71c7cd86ab1f7b4 | dharmit/Projects | /Numbers/alarm.py | 1,568 | 3.828125 | 4 | #!/usr/bin/env python
import time
import pyglet
def alarm(hh, mm):
check = True
while check:
curr_hh = int(time.strftime("%H"))
curr_mm = int(time.strftime("%M"))
if curr_hh == hh and curr_mm == mm:
music = pyglet.media.load("1.mp3")
music.play()
p... |
a0f06e65c70862194f25bee20a4ad1eed82ae586 | dharmit/Projects | /Numbers/mortgage.py | 460 | 4.25 | 4 | #!/usr/bin/env python
def mortgage_calculator(months, amount, interest):
final_amount = amount + ((amount * interest)/100)
return int(final_amount / months)
if __name__ == "__main__":
amt = int(raw_input("Enter the amount: "))
interest = int(raw_input("Enter the interest rate: "))
months = int(ra... |
d13f6910e7ca4145b797e80d6385f24cd414b8bd | AdamSpannbauer/line_art | /rand_walk_draw.py | 6,211 | 3.96875 | 4 | import numpy as np
import cv2
def weight_step(canvas, canvas_color, location, lo_weight=0.3):
"""Weight random walk to step towards the most blank areas of the canvas
:param canvas: np.array that is the drawing canvas
:param canvas_color: starting color of canvas
:param location: (y, x) location wher... |
a0e8d50ca6904365c213a861df774aec2ef8ac34 | AdityaChirravuri/Coursera | /Python/Course_1_Basics/Exercise4.py | 291 | 3.859375 | 4 | score = input("ENTER SCORE: ")
s = float(score)
if s>1:
print("ENTER LESS THAN OR EQUAL 1 ")
elif s>=0.9:
print("A")
elif s>=0.8:
print("B")
elif s>=0.7:
print("C")
elif s>=0.6:
print("D")
elif s<0.6:
print("F")
elif s<0:
print("ENTER VALID SCORE") |
4367efd22665a01b600c7df0c1a9ebd5cdd99170 | alilkkanyil/congress-record-searcher | /scraper2.py | 1,195 | 3.65625 | 4 | # File: scraper2.py
# Function: Intended to go over the results from scraper.py
# It will be used to further refine search results.
# Currently it just prints the text from each output from scraper.py
# Last updated: 08.14.20, by Ali Yildirim
import os
from bs4 import BeautifulSoup
import requests
import csv
... |
baf234ed556488a5d5a8f1229b5bf69958b232e1 | krakibe27/python_objects | /Bike.py | 802 | 4.125 | 4 | class Bike:
def __init__(self,price,max_speed):
self.price = price
self.max_speed = max_speed
self.miles = 200
#self.miles = self.miles + self.miles
def displayInfo(self):
print "Price :", self.price
print "max_speed :" + self.max_speed
print "total ... |
a5db9738c3b991a05061a9e905f5515d88d868e0 | OnurcanKoken/Python-GUI-with-Tkinter | /11_Adding the Status Bar.py | 1,876 | 4.03125 | 4 | from tkinter import * #imports tkinter library
#we will not deal with the function here
def doNothing():
print("so what?")
root = Tk() #to create the main window
# ***** Main Menu *****
#menu is at the top by default settings
#we want to add an item that has drop-down functinality
#drop-down functinality is cal... |
832a79bbaf9f1961dc580f064efbf1903057d803 | OnurcanKoken/Python-GUI-with-Tkinter | /6_Binding Functions to Layouts.py | 1,154 | 4.3125 | 4 | from tkinter import * #imports tkinter library
root = Tk() #to create the main window
#binding a function to a widget
#define a function
def printName():
print("My name is Koken!")
#create a button that calls a function
#make sure there is no parantheses of the function
button_1 = Button(root, text="Print my na... |
1f9420da7437a496d83f97a0d6c6166460bac02e | anarayanan123/DS-ALGO-COURSEWORK | /Algorithmic Toolbox/week1_programming_challenges/max_pairwise_product1.py | 303 | 3.890625 | 4 | # python3
def max_pairwise_product(numbers):
a = max(numbers)
b = numbers
b.remove(max(numbers))
d = max(b)
return a*d
if __name__ == '__main__':
input_n = int(input())
input_numbers = [int(x) for x in input().split()]
print(max_pairwise_product(input_numbers))
|
79668fb62ca2da7dbe039a41c625bcb8a9a65200 | anarayanan123/DS-ALGO-COURSEWORK | /DS/W1/check_brackets.py | 1,687 | 3.796875 | 4 | # python3
import sys
class Bracket:
def __init__(self, bracket_type, position):
self.bracket_type = bracket_type
self.position = position
def Match(self, c):
if self.bracket_type == '[' and c == ']':
return True
if self.bracket_type == '{' and c == '}':... |
b1c3c146425a72805707ed1ac95f4c47312f1a4a | markellisdev/2020-PythonPractice | /arrays.py | 471 | 3.609375 | 4 | import random
my_randoms = list()
for i in range(10):
my_randoms.append(random.randrange(1, 6))
print(my_randoms)
numbers_1_to_10 = range(1, 11)
for number in numbers_1_to_10:
for random in my_randoms:
if number == random:
print(f'{number} is in the random list')
the_numbers_match = ... |
36c4a847bad96bae252543ca9c12fb6ac5dc1abc | Juan55Camarillo/pattern-designs | /strategy.py | 1,433 | 4.625 | 5 | '''
Strategy pattern designs example
it allows make an object can behave in different ways
(which will be define in the moment of its instantiation or make)
'''
from __future__ import annotations
from abc import ABC, abstractmethod
from typing import List
class Map():
def __init__(self, generateMap: Ge... |
73ccde5e6ec6fcf2bcb5b303bfb914b1a20adccd | patrickaroo/moan | /syllables.py | 560 | 3.765625 | 4 | '''
from nltk.corpus import cmudict
d = cmudict.dict()
import string
def nsyl(word):
return [len(list(y for y in x if y[-1].isdigit())) for x in d[word.lower()]]
def is_haiku(text):
poem = text.split()
#poem = [s.translate(string.maketrans("",""), string.punctuation) for s in poem]
syllables = [sum(nsyl(word)) fo... |
40c1e02e260475cbc0c2d0bd4c9ee9de6206a007 | dinnguyen1495/StockTradingNotifier | /notify.py | 5,147 | 3.828125 | 4 | """
Stock Trading Alerter
This script will automatically send stock information via SMS.
"""
import requests
import re
from datetime import datetime, timedelta
from pytz import timezone
from twilio.rest import Client
import config
# Stocks that are interested and their companies
STOCKS = ["TSLA", "FB", "SIEGY", "... |
d1abbafa19f53b7c55c4491d6861f24a699ba3ea | sujitkc/calendar | /py/teams.py | 684 | 3.828125 | 4 | #!/usr/bin/python
import random
import csv
import sys
def getNamesFromCSV(csvfilename):
with open(csvfilename, 'rb') as csvfile:
reader = csv.reader(csvfile)
names = [row[1] for row in reader]
return names
def makeTeam(l, n):
if(len(l) < n):
return (l, [])
else:
return(l[:n], l[n:])
def ma... |
7fe57589751197b15128bd4c19574753dfcd8cdf | CodecoolBP20172/pbwp-1st-si-game-inventory-bogiNagy | /gameInventory.py | 3,081 | 4.15625 | 4 | # This is the file where you must work. Write code in the functions, create new functions,
# so they work according to the specification
# Display7s the inventory.
import sys
import csv
import operator
inventory={'rope': 1, 'torch': 6, 'gold coin': 42, 'dagger': 1, 'arrow':12}
dragon_loot = ['gold coin', 'dagger', 'go... |
bb2bf5330a21ecf103b078f43b9b53ac8dd1a457 | duhan9836/Algorithm-learning | /GCD.py | 1,110 | 3.796875 | 4 | #define a function, that given two positive integers, m and n, the function will return their greatest common divisor,GCD
import random
def gcd(m,n):
if m==n:
return m
elif m<n:
m,n=n,m
if m%n==0:
return n
else:
i=n-1
while i>1:
if m%i==0 a... |
9576633a9fef9dfe4067fae5e77475872db26431 | duhan9836/Algorithm-learning | /removeDuplicates.py | 433 | 3.953125 | 4 | def removeDuplicates(nums):
"""
:type nums: List[int],in order
:rtype: int
"""
nums_new = []
count = 0
for i in nums:
if i not in nums_new:
nums_new.append(i)
count += 1
nums = nums_new[:]
return count,nums
nums1=[1,1,2,2,3,3,3,4]
nums2... |
93208dc2ad4e0a859e00901ba29d2b09b299f692 | duhan9836/Algorithm-learning | /addBinary.py | 1,035 | 3.578125 | 4 | def addBinary(a,b):
#suppose len(a)>=len(b)
#1. convert a,b into list, from end to beginning
#note the data type, the difference between string adding and int adding
aa=[int(a[len(a)-1-i]) for i in range(len(a))]
bb=[int(b[len(b)-1-i]) for i in range(len(b))]+[0]*(len(a)-len(b))
#2. define... |
a0cae2c2ce4a13dec2de73a36595c9830baff673 | kuzha/study-notebook-for-ml | /mnist_off.py | 2,668 | 4.0625 | 4 | from tensorflow.examples.tutorials.mnist import input_data
# mnist stands for modified NIST (national institue of standards and technology)
# NIST contains the raw database of handwritten digits. It has been modified by
# Yanne LeCun for easier preprocessing and formatting
# one_hot is a vector with only one 1 and wit... |
93caef40573734f3f8a6f2551eeaba52ede84291 | destae/Milestones | /milestone_1/src/adapter.py | 3,464 | 3.625 | 4 |
# What is a data adapter meant to be able to do?
# It is meant to be able to:
# open a file
# read a file
# determine the longest number of columns
# determine the schema
# generate a dataframe
import utils
from dataframe import Dataframe
class Adapter:
def __init__(self, name):
self.... |
deb3ebc5f4641d8d37a57a5337cbeee60f7df120 | destae/Milestones | /7DegreesOfLinus/src/schema.py | 1,049 | 3.53125 | 4 | import os
class Schema:
## Creates a schema object: main constructor
def __init__(self, sch: list, ncols: int=0,nrows: int=0):
self.schema_list = sch
self.ncols = ncols
self.nrows = nrows
def __eq__(self, other):
"""Overrides the default implementation"""
if isinsta... |
63dc875b60b20204ef8bc4a18b80183c066f31cf | freddy5566/AlloST | /egs/fisher_callhome_spanish/st1/local/phone_mapping.py | 1,516 | 3.578125 | 4 | from typing import Dict
import argparse
def read_phone_dictionary(dict_path: str) -> Dict[str, str]:
phone_mapping = {}
base = ord("\U00013000")
with open(dict_path, "r") as phone_dict:
lines = phone_dict.readlines()
for line in lines:
line = line.strip().split()
... |
a34063f6b6ba6e086b633508fad186b4e9622df7 | sachinsaini4278/Data-Structure-using-python | /insertionSort.py | 622 | 4.15625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sat Mar 2 07:18:31 2019
@author: sachin saini
"""
def insertion_sort(inputarray):
for i in range(size):
temp=inputarray[i]
j=i
while(inputarray[j-1]>temp and j >=1):
inputarray[j]=inputarray[j-1];
j=j-1
i... |
bf018fdef033f0115685f88771260db5d94ed6b3 | rodrigolousada/udacity_ML_for_trading | /lesson01_03.py | 6,616 | 3.703125 | 4 | import time
import timeit
import numpy as np
def create_numpy_arrays():
"""Creating NumPy arrays."""
#List to 1D array
print(np.array([2,3,4]))
#List to 2D array
print(np.array([(2,3,4),(5,6,7)]))
#Empty array
print(np.empty(5))
print(np.empty((5,4,3)))
# Array of 1s
print(np... |
9259a3b6575504831a6c9a4601035771b48e1ced | mattwright42/Decorators | /decorators.py | 1,560 | 4.15625 | 4 | # 1. Functions are objects
# def add_five(num):
#print(num + 5)
# add_five(2)
# 2. Functions within functions
# def add_five(num):
# def add_two(num):
# return num + 2
#num_plus_two = add_two(num)
#print(num_plus_two + 3)
# add_five(10)
# 3. Returning functions from functions
# def get_math_function(operati... |
d1d41df23975751678c157a5edc1743f00a17bbf | golharam/genomics | /NGS-general/split_fasta.py | 8,066 | 3.734375 | 4 | #!/usr/bin/env python
#
# split_fasta.py: extract individual chromosome sequences from fasta file
# Copyright (C) University of Manchester 2013-2019 Peter Briggs
#
########################################################################
#
# split_fasta.py
#
######################################################... |
383079a14d2761672e143e2bbb88061804d98a3a | divyansh13kietmca/LeeT-CodE | /Merge Sorted Array.py | 596 | 3.8125 | 4 | class Solution:
def merge(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None:
"""
Do not return anything, modify nums1 in-place instead.
"""
# i = 0
# for j,each in enumerate(nums1):
# if each == 0:
# nums1[j] = nums2[i]
# ... |
e731ec495bdde66f20a2b7c3d2e0d4c615f6a854 | divyansh13kietmca/LeeT-CodE | /Duplicate Zeroes.py | 432 | 3.65625 | 4 | class Solution:
def duplicateZeros(self, arr: List[int]) -> None:
"""
Do not return anything, modify arr in-place instead.
"""
extra = []
i = 0
size = len(arr)
for i in range(len(arr)):
if arr[i] == 0:
extra.append(0)
ex... |
2a47dda71d4eb91ab0df0808659713f0b6329bed | dxcv/quantest | /板块龙头股分析/sector_head_v1.py | 3,753 | 3.53125 | 4 | """
统计过去一个月内某板块股票的价格和成交量,并据此计算得分。
如果价格上升同时成交量上升,那么+2分;如果价格上升同时成交量下降,那么+1分;
如果价格下降同时成交量上升,那么-1分;如果价格下降同时成交量下降,那么-2分。
计算过去一个月内的总分,从大到小排名,选出最高的10个股票,每月调仓。
同时加入止损,没月初选股时,如果大盘之前一周内下跌8%则空仓。投资组合一个月内累计下跌5%则平仓。
https://www.ricequant.com/api/python/chn#other-methods-sector,主要是传入给sector的参数变化一下即可
"""
#TODO: WIP
# 可以自己import我们平台支... |
5fc023b0fa953460dd1cb45e6446ab629d47db77 | enthusiasticgeek/AI | /tutorialspoint/naive_bayes_classification.py | 1,627 | 3.828125 | 4 | #!/usr/bin/env python3
import sklearn
from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import train_test_split
from sklearn.naive_bayes import GaussianNB
from sklearn.metrics import accuracy_score
#Naïve Bayes is a classification technique used to build classifier using the Bayes theorem. T... |
db09cc8134b15bce20a0f6f74d73e67e2ec723ee | The-Coding-Hub/Comp-Class-Code-Notes | /Python/q1.py | 451 | 4.4375 | 4 | # Enter 3 number and print the greatest one.
n1 = int(input("Number 1: "))
n2 = int(input("Number 2: "))
n3 = int(input("Number 3: "))
if n1 > n2 and n1 > n3:
print(f"{n1} is largest")
if n2 > n1 and n2 > n3:
print(f"{n2} is largest")
if n3 > n2 and n3 > n1:
print(f"{n3} is largest")
# OR
if n1 > n2 and... |
da463aae470f86a5d4bc9a9175f6c4b32f71f323 | The-Coding-Hub/Comp-Class-Code-Notes | /Python/calculator.py | 438 | 4.4375 | 4 | # Simple Calculator
num_1 = float(input("Number 1: "))
num_2 = float(input("Number 2: "))
operator = input("Operator (+, -, *, /): ")
result = None
if (operator == "+"):
result = num_1 + num_2
elif (operator == "-"):
result = num_1 - num_2
elif (operator == "*"):
result = num_1 * num_2
elif (operator == "/"):
... |
68b7114bf770ed412ca8cff03a945b972fc4ae03 | UsmanMaan324/logistic-regression | /Logistic Regression/regularized-logistic-regression.py | 3,763 | 3.8125 | 4 |
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
reg_factor = 1
alpha = 0.001
def mapFeature(X1, X2, degree):
res = np.ones(X1.shape[0])
for i in range(1, degree + 1):
for j in range(0, i + 1):
res = np.column_stack((res, (X1 ** (i - j)) * (X2 ** j)))
... |
5d6517898797d0038eb4a5561b19dbab6cf230d1 | AadityaJ/Text_Analytics_Python | /ctlk_det.py | 1,328 | 3.5625 | 4 | import collections
import numpy as np
import matplotlib.pyplot as plt
graph=list()
fig = plt.figure()
ax = fig.add_subplot(111)
## Getting the file
count=dict()
count2=list()
total=0
i=0
dat=dict()
fname="text_mod_alp.txt"
fh=open(fname)
## File got
## Now conversion to string
for line in fh:
line=... |
f5edb7b29e99421eff0a071312619d011e833038 | lucipeterson/Rock-Paper-Scissors | /rockpaperscissors.py | 2,800 | 4.125 | 4 | #rockpaperscissors.py
import random
print("~~ Rock, Paper, Scissors ~~")
weapon_list = ["rock", "paper", "scissors"]
user = input("Rock, paper, or scissors? ")
while user.lower() not in weapon_list:
user = input("Rock, paper, or scissors? ")
computer = random.choice(weapon_list)
print("Computer chooses " + comput... |
05e109d5d83c0e438b89cdb3e6d4f650885eae16 | jdb158/problems | /problem108-try2.py | 1,246 | 4.15625 | 4 | import math
primes = [2,3]
largestprime = 3
def main():
test = 80
pflist = primeFactors(test)
print (pflist)
def primeFactors(number):
factors = []
global largestprime # grab our largest generated prime
# check already generated primes
while (number > 1):
for i in primes:
if (number % i == 0)... |
2c73001f1a9007ce9e09364ed88fbbe0bb8ebc48 | Rodann/CIAOD | /kurs_work/tasks.py | 3,717 | 3.71875 | 4 | import math
import numpy as np
import numpy.random as rand
#Треугольник с максимальным периметром
def triangle(nums):
if(len(nums)<3):
return 0
last = 2
middle = 1
first = 0
num_last = len(nums)-1
num_middle = num_last-1
num_first = num_middle-1
sum=0
while fi... |
ef949c39755d56c5dbf3ef5bd9212bfb36a2df92 | aseemchopra25/Integer-Sequences | /Juggler Sequence/juggler.py | 706 | 4.21875 | 4 | # Program to find Juggler Sequence in Python
# Juggler Sequence: https://en.wikipedia.org/wiki/Juggler_sequence
# The juggler_sequence function takes in a starting number and prints all juggler
# numbers starting from that number until it reaches 1
# Keep in mind that the juggler sequence has been conjectured to reach... |
78d244b7e468f23108702edd66321b9361161aab | aseemchopra25/Integer-Sequences | /Wedderburn–Etherington number/Wedderburn Etherington Numbers.py | 1,032 | 3.5625 | 4 | store = dict()
def Wedderburn(n):
# Base case
if (n <= 2):
return store[n]
# If n is even n = 2x
elif (n % 2 == 0):
# get x
x = n // 2
ans = 0
# a(2x) = a(1)a(2x-1) + a(2)a(2x-2) + ... +
# a(x-1)a(x+1)
for i in range(1, x):
... |
9ac424119cbb8df18eb336296a93ddf15aa62713 | aseemchopra25/Integer-Sequences | /Jacobsthal Numbers/Jacobsthal_Numbers.py | 575 | 3.8125 | 4 | ###############################
### Jacobsthal Numbers ###
###############################
# Forumula: J(n) = J(n-1)+2*J(n-2)
# Example: 0, 1, 1, 3, 5, 11, 21, 43, 85, 171, 341, 683, 1365, 2731, 5461, 10923, 21845, 43691, ……
def Jacobsthal(n):
n=n-1 #Edit: Considering first term is 0
dp = [0] *... |
9845ef4a3c1ba503e92f723126818b99f700079e | aseemchopra25/Integer-Sequences | /Sylvester Sequence/SylvesterSequence.py | 474 | 3.890625 | 4 | #########################
## Sylvester Sequence ##
#########################
#Example : 2 3 7 43 1807 3263443 ....
def seq(n):
pdt = 1
ans = 2
N = 1000000007
for i in range(1,n+1):
ans = ((pdt % N) * (ans % N)) % N
pdt = ans
ans = (ans ... |
f013a0c4604d3a39edf17405d34a5a1ff4722167 | aseemchopra25/Integer-Sequences | /Golomb Sequence/Golomb.py | 1,460 | 4.25 | 4 | # A program to find the nth number in the Golomb sequence.
# https://en.wikipedia.org/wiki/Golomb_sequence
def golomb(n):
n = int(n)
if n == 1:
return 1
# Set up a list of the first few Golomb numbers to "prime" the function so to speak.
temp = [1, 2, 2, 3, 3]
# We will be modifying the li... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.