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 |
|---|---|---|---|---|---|---|
462b9b76fe3b31d937eb8ead58f87802ef33dd3e | mabergerx/codesignal | /arcade/smoothSaling/reverseInParentheses.py | 1,026 | 3.5625 | 4 | def reverseInParentheses(inputString):
if "(" not in inputString:
return inputString
else:
last_opening_index = 0
corresponding_closing_index = 0
startIndex = None
results = []
reversedString = ""
... |
ab1cc72aade05ec0df48420dcfca51ec1460e1cd | mabergerx/codesignal | /arcade/throughTheFog/depositProfit.py | 337 | 3.59375 | 4 | def solution(deposit, rate, threshold):
def calculate_yearly_increase(amount):
return amount * ((rate/100) + 1)
amount = deposit
years = 0
while True:
amount = calculate_yearly_increase(amount)
years += 1
print(amount)
if amount >= threshold:
... |
dda65cae00928850271f2534265e91f1499126d8 | mabergerx/codesignal | /arcade/theJourneyBegins/checkPalindrome.py | 693 | 3.84375 | 4 | def checkPalindrome(inputString):
middleIndex = int(len(inputString)/2)
if len(inputString) % 2:
return inputString[middleIndex+1:] == inputString[:middleIndex][::-1]
else:
return inputString[middleIndex:] == inputString[:middleIndex][::-1]
print(checkPalindrome("aabaa")) #true
p... |
b409c4cdc092a1d161cc84fc4081183a8ba0bcec | mabergerx/codesignal | /arcade/darkWilderness/digitDegree.py | 421 | 3.625 | 4 | def solution(n):
if n < 10:
return 0
count = 0
def recursively_solve(number, count=count):
count += 1
string_representation = str(number)
sum_digits = sum([int(digit) for digit in string_representation])
if sum_digits > 9:
return recursively... |
ac3a6fcb8237f80f54bd88856cc669d578ea08b5 | kieranmcgregor/Python | /PythonForEverybody/Ch2/Ex2_prime_calc.py | 2,439 | 4.125 | 4 | import sys
def prime_point_calc(numerator, denominator):
# Returns a number if it is a prime number
prime = True
while denominator < numerator:
if (numerator % denominator) == 0:
prime = False
break
else:
denominator += 1
if prime:
return num... |
417d8c435205d3fd812b0ad86163226983e8e4c4 | kieranmcgregor/Python | /PythonTinkering/Maze/maze.py | 4,251 | 3.71875 | 4 | import random
ALL_TILES = ['0', '1', '2', '3', '01', '02', '03', '12', '13', '23', '012', '013', '023', '123']
ONE_SIDED = {
'0' : [[1, 0], [0, -1], [-1, 0]],
'1' : [[0, 1], [0, -1], [-1, 0]],
'2' : [[0, 1], [1, 0], [-1, 0]],
'3' : [[0, 1], [1, 0], [0, -1]]
}
TWO_SIDED = {
'01' : [[0, -1], [-1... |
58bfbf28aa758d222f0375e61b4ed2dc95c2c8da | kieranmcgregor/Python | /PythonForEverybody/Ch9/Ex2_Day_Sort.py | 1,767 | 4.15625 | 4 | def quit():
quit = ""
no_answer = True
while no_answer:
answer = input("Would you like to quit? (y/n) ")
try:
quit = answer[0].lower()
no_answer = False
except:
print ("Invalid entry please enter 'y' for yes and 'n' for no.")
continue... |
0b24edf56290b00dbd374956e2204c4850f98f85 | kieranmcgregor/Python | /ML4HB/linear_regression/line_reg.py | 1,624 | 3.625 | 4 | import numpy as npy
import matplotlib.pyplot as plt
import csv
class LinearRegression(object):
# Implements Linear Regression
def __init__(self):
self.w = 0
self.b = 0
self.rho = 0
def fit(self, X, y):
mean_x = X.mean()
mean_y = y.mean()
errors_x = X - mean_x
errors_y = y - mean_y
errors_p... |
e00b1159d29bace8817dac03904b7b67a8530281 | ahamed2408/Mind-Map | /Mindmap.py | 2,684 | 3.75 | 4 | class Mindmap:
#initializing Variables
def __init__(self):
self.l=[]
self.x=0
#Function to insert the values to the cards
def insert(self):
for i in range(self.x):
m=[]
for j in range(self.x):
sm=[]
name=i... |
7b968f91ccc95bccac27bcc823b3d6fd4fa8e8f7 | tganderson0/class-info-master | /class-master.py | 10,498 | 3.890625 | 4 | import os
class ClassInfo:
def __init__(self, infoLine=""):
self.className = ""
self.instructor = ""
self.contactInfo = ""
self.whatToCallProf = ""
self.classMainURL = ""
self.applyInfo(infoLine)
def formatForSaving(self) -> str:
return f"{self.classNam... |
58fae696148c1558f5ccfce2c146b574b3d6368b | KennyReyesS/AirBnB_clone | /tests/test_models/test_city.py | 1,716 | 3.5625 | 4 | #!/usr/bin/python3
"""
This module contains test cases for City
"""
import unittest
from models.base_model import BaseModel
from models.city import City
import pep8
from datetime import datetime
class TestCity(unittest.TestCase):
"""" Test cases class of City """
def test_pep8_city(self):
"""pep8... |
3f66236ecc851b7aec3243da3de85cc537dd6864 | JDavid550/python_challenges | /calculator.py | 1,141 | 3.765625 | 4 | from math import sin,cos,tan,log
print("""
Operations available
[1]-sin
[2]-cos
[3]-tan
[4]-ln
""")
epsilon=0.01
def apply_funtion(f,n):
function={
1:sin,
2:cos,
3:tan,
4:log
}
result = {}
for i in range(1, n+1):
result[i]=function[f](i)
return result
de... |
6afe93b0bb66b817ba92c8d1eca2e40333552a39 | AshishBora/challenge1 | /thresholding.py | 1,109 | 4 | 4 | """Find optimal threshold"""
import numpy as np
def find_best_threshold(arr0, arr1):
"""Find the best threshold seprating arr0 from arr1.
We maximize the number of elements from arr0 that are less than or equal to
the threshold plus the number of elements from arr1 that are greater than
the threshol... |
a5f51f2eea4347a3c6cd4947429d3e9186b0f6f1 | Murdock135/TeachPython | /class4.py | 559 | 4.03125 | 4 | def two_sum(NumList):
# listOfNums = []
listOfNums = NumList
count = 0
# while count<5:
# string_nums = input('Enter a digit: ')
# nums = int(string_nums) #convert to int
target = int(input('What\'s the target'))
listLength = len(listOfNums)
for m in range(0, listLength)... |
81567c5895ebec2009ffac7000a0dcb7db71387e | mrupesh/US-INR | /USD&INR.py | 523 | 4.3125 | 4 | print("Currency Converter(Only Dollars And Indian Rupees)")
while True:
currency = input("($)Dollars or (R)Rupees:")
if currency == "$":
amount = int(input('Enter the amount:'))
Rupees = amount * 76.50
print(f"${amount} is equal to: ₹{Rupees}")
elif currency.upper() == "R":
a... |
46155b03dab8165762e9ecedebc7efb6a719af9c | zhouchuang/pytest | /test10.py | 355 | 4 | 4 | """
题目:暂停一秒输出,并格式化当前时间。
程序分析:无。
"""
import time
print(time.strftime("%y-%m-%d %H:%M:%S",time.localtime(time.time())))
time.sleep(1)
print(time.strftime("%y-%m-%d %H:%M:%S",time.localtime(time.time())))
myD = {1:'A',2:'B'}
for key ,value in dict.items(myD):
print(key,value)
time.sleep(1)
|
64585dcd3bd9861c4b2217e55115e56c443a96ea | zhouchuang/pytest | /yunsun.py | 1,034 | 3.625 | 4 | # coding=utf-8
def yunsuan(userA, userB, operate):
'运算函数'
try:
A = int(userA)
B = int(userB)
operate_list = {'+': (A + B), '-': (A - B), '*': (A * B), '/': (A / B)}
return operate_list[operate]
except KeyError:
return '%s 没有这个运算' % operate
except ValueError:
... |
d22e880532ea9e828118e8765c1bff7754330305 | zhouchuang/pytest | /test5.py | 723 | 3.734375 | 4 | #题目:输入某年某月某日,判断这一天是这一年的第几天?
#程序分析:以3月5日为例,应该先把前两个月的加起来,然后再加上5天即本年的第几天,特殊情况,闰年且输入月份大于2时需考虑多加一天:
def addleap(year,month):
if year % 4 ==0 and year%100!=0 and month > 2:
return 1
else:
return 0
def getdayth():
year = int(input('请输入年份'))
month = int(input("请输入月份"))
day = int(input("请输入... |
a5c883f15941ca3dbe09b1909762f29a9a8d430c | Thandhan/CSE7ML | /Program_9/prg9.py | 1,005 | 3.515625 | 4 | from sklearn.model_selection import train_test_split
from sklearn.neighbors import KNeighborsClassifier
from sklearn import datasets
iris = datasets.load_iris()
print("Iris Data set loaded...\n\n")
x_train,x_test,y_train,y_test = train_test_split(iris.data,iris.target,test_size =0.1)
print("Dataset is split into ... |
86f91d794953d183366e9290564313d1dcaa594e | gmanacce/STUDENT-REGISTERATION | /looping.py | 348 | 4.34375 | 4 | ###### 11 / 05 / 2019
###### Author Geofrey Manacce
###### LOOPING PROGRAM
####CREATE A LIST
months = ['january','february', 'match', 'april', 'may','june','july','august','september','october','november','december']
print(months)
#####using For loop
for month in months:
print(month.title() + "\n")
print("go for n... |
15b25ddb8ddd76c5e5923fa92c45760c5b92c0e1 | DavidToca/_learn_python_the_hard_way | /ex12.py | 655 | 3.8125 | 4 | #our hero remains in the temple and is been asking for his training so far
print "How are your skills with the math operators?"
math_operations_skills = raw_input("skills: ")
print "And what about your commenting ones?"
commenting_skills = raw_input("skills: ")
print "Why there isn't any more chapters between 6 and 11?... |
4407c72830681d2263c4882d39ab84070af61a77 | Compileworx/Python | /De Cipher Text.py | 348 | 4.34375 | 4 | code = input("Please enter the coded text")
distance = int(input("Please enter the distance value"))
plainText = ''
for ch in code:
ordValue = ord(ch)
cipherValue = ordValue - distance
if(cipherValue < ord('a')):
cipherValue = ord('z') - (distance - (ord('a') - ordValue + 1))
plainText += chr(ci... |
a61879f80699a457876f51b80db5a7a28227b733 | caethan/CSE232 | /problems/TOJ1297.py | 1,155 | 3.90625 | 4 | import sys
S = sys.stdin.readline().strip()
#Suffix tree implementation
tree = {}
END = 'END'
def add_word(tree, word, terminator, marker):
tree[marker] = True
if not word:
tree[END] = terminator
return
char = word[0]
if not char in tree:
tree[char] = {}
add_word(tree[char... |
adbd60fcb21c92970b7561225d0574300f958325 | quangnguyendang/Reinforcement_Learning | /Chapter06_Temporal_Difference/Cliff_Walking_Q_Learning.py | 8,666 | 3.75 | 4 | # Example 6.6 page 108 in Reinforcement Learning: An Introduction Book
# PhD Student: Nguyen Dang Quang, Computer Science Department, KyungHee University, Korea.
# Q learning, Double Q Learning and SARSA Implementation
import numpy as np
import matplotlib.pyplot as plt
# -------------- Set Constants ----------------
n... |
4e336ae145eaa3304a31d18f473b045fc19fc791 | quangnguyendang/Reinforcement_Learning | /Chapter07_N-Step_Bootstrapping/Off_Policy_N_Step_SARSA.py | 6,999 | 3.875 | 4 | # Example 7.1 page 118 in Reinforcement Learning: An Introduction Book
# PhD Student: Nguyen Dang Quang, Computer Science Department, KyungHee University, Korea.
# n-step SARSA for estimating Q with importance sampling factor on 100-State Random Walk
import numpy as np
import gym
import matplotlib.pyplot as plt
clas... |
5c8f903945c896c250cb23c7c9a29c355296b3c6 | LuisReal/IPC2-2021-_Proyecto1_201313965 | /Menu.py | 1,828 | 3.5 | 4 |
from Archivo import Carga
from MatrizOrtogonal import MatrizOrtogonal
class Menu:
def __init__(self):
self.archivo = ""
self.ruta = ""
self.nombre_terreno = ""
self.obj = ""
self.obj_Lista = ""
self.matriz = ""
def menu(self):
opcion = 0
... |
bd29943434b3033b2cb00d501b398a2426fef021 | LuisReal/IPC2-2021-_Proyecto1_201313965 | /ListaVertical.py | 1,509 | 3.625 | 4 | from NodoOrtogonal import Nodo
class Lista_V:
def __init__(self):
self.primero = None
self.ultimo = None
self.size = 0
def vacia(self):
return self.primero == None
def insertar(self, dato, x, y):
nodo_nuevo = Nodo(dato, x, y)
if self.vacia() == True:
... |
67a9bd1a092034f593be8f146ba6c417a526d6d1 | Aditya-kiran/AI-and-ML | /team_lecture/untitled.py | 140 | 3.734375 | 4 | while True:
prompt = "%s words: " % 3
sentence = input(prompt)
sentence = sentence.strip()
words = sentence.split(' ')
print(sentence) |
10b5e6f0afaaf53fd5139ef91ea65db5ac20545d | TheS1lentArr0w/Milestone-Project-2 | /blackjack.py | 7,819 | 3.78125 | 4 | '''
BlackJack Card Game
'''
# Imports
import random
# Global variables that will be useful throughout the code
suits = ('Hearts', 'Diamonds', 'Spades', 'Clubs')
ranks = ('Two', 'Three', 'Four', 'Five', 'Six', 'Seven', 'Eight', 'Nine', 'Ten', 'Jack', 'Queen', 'King', 'Ace')
values = {'Two':2, 'Three':3, 'Four':4, 'Fi... |
9efd80a345662fcd6e8b4631d99d8f9d903a8fae | isaigm/leetcode | /search-insert-position/Accepted/3-16-2020, 1_10_28 PM/Solution.py | 245 | 3.640625 | 4 | // https://leetcode.com/problems/search-insert-position
class Solution:
def searchInsert(self, nums: List[int], target: int) -> int:
for idx in range(len(nums)):
if nums[idx] >= target : return idx
return idx + 1 |
f240c65c8bd83da8bd36fe1c01a5ba0bb1ab4d19 | isaigm/leetcode | /word-pattern/Wrong Answer/9-8-2020, 1_56_05 AM/Solution.py | 411 | 3.578125 | 4 | // https://leetcode.com/problems/word-pattern
class Solution:
def wordPattern(self, pattern: str, strr: str) -> bool:
words = strr.split(' ')
l1 = len(pattern)
for i in range(l1 - 1):
if pattern[i] == pattern[i + 1]:
if words[i] != words[i + 1]: return False
... |
326c1d3a8e1ce7610bbf26b92d0ee957a03e291a | isaigm/leetcode | /remove-nth-node-from-end-of-list/Accepted/3-17-2020, 4_29_10 PM/Solution.py | 925 | 3.65625 | 4 | // https://leetcode.com/problems/remove-nth-node-from-end-of-list
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode:
size = 0
ptr = hea... |
38c3d2fe9e2e777e20a86dd6e19ece406bb05e50 | isaigm/leetcode | /word-break/Wrong Answer/5-30-2021, 10_09_10 AM/Solution.py | 244 | 3.671875 | 4 | // https://leetcode.com/problems/word-break
class Solution:
def wordBreak(self, s: str, wordDict: List[str]) -> bool:
large_string = ""
for word in wordDict:
large_string += word
return s in large_string |
d830adc3169ec263a5043079c99d8a8a65cda037 | orrettb/python_fundamental_course | /02_basic_datatypes/2_strings/02_11_slicing.py | 562 | 4.40625 | 4 | '''
Using string slicing, take in the user's name and print out their name translated to pig latin.
For the purpose of this program, we will say that any word or name can be
translated to pig latin by moving the first letter to the end, followed by "ay".
For example: ryan -> yanray, caden -> adencay
'''
#take the us... |
fc9692fb7de66bc5a8ae7102e7b19325fb8eb88b | yywxenia/MachineLearningProj | /ML_Algorithms/RandomOptimi/ml2_code/optim_alg.py | 4,017 | 3.9375 | 4 |
### Implement optimization algorithms: reference from Programming Collective Intelligence
### =============================================================================================
import random
import math
#-----------------------------------------------------------------------------------------
# Hill climb... |
ff3eab60580e342b83fa05e6bd111177cc5a53e5 | ghiyaath/Error-handling | /main.py | 1,453 | 3.71875 | 4 | from tkinter import *
from tkinter import messagebox
# The info for the window
window = Tk()
window.title("Verify Form")
window.geometry("540x340")
window.resizable(False, False)
window.config(bg="red")
user_pass = {'Ghiyaath': 'Zaeemgee', 'Jaydenmay': 'jaydenmay', 'Shuaib': 'Biggun',
'Zoe': 'Foodislife'... |
019115d2d0a51ab08b0a0ef0eb8e24dc31e98ecb | June-lizj/code-practice | /src/Offer-Python/Code006_Fibonacci.py | 954 | 3.578125 | 4 | # 大家都知道斐波那契数列,现在要求输入一个整数n,
# 请你输出斐波那契数列的第n项(从0开始,第0项为0)。
# n<=39
class Solution:
def Fibonacci(self, n):
result = [0,1]
if n < 2:
return result[n]
# for i in range(2,n+1):
# result.append(result[i-1]+result[i-2])
while len(result) < n+1:
result.app... |
610caef7eb530369d1d5467b6d5d5f1e10456eec | June-lizj/code-practice | /src/Offer-Python/Code013_ReverseList.py | 943 | 4.03125 | 4 | # 输入一个链表,反转链表后,输出新链表的表头。
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
# 返回ListNode
def ReverseList(self, pHead):
if pHead == None or pHead.next == None:
return pHead
pre = self.ReverseList(pHead.next)
pHead.next.next... |
851ac765a242ede13f482b0a971793ccfd2fc403 | luuuumen/algorithm013 | /Week_04/jump_games.py | 277 | 3.546875 | 4 | # coding:utf-8
class Solution(object):
def canJump(self, nums):
"""
:type nums: List[int]
:rtype: bool
"""
ep = len(nums) - 1
for i in range(len(nums)-1,-1,-1):
if nums[i] + i >= ep: ep = i
return ep == 0 |
a3e375e0ff88ff9487a9ed5035949bcc83bf268d | SalmanStarneo/OOP-201920 | /lab2_types_and_strings.py | 3,123 | 4.25 | 4 | #course: Object-oriented programming, year 2, semester 1
#academic year: 201920
#author: B. Schoen-Phelan
#date: 29-09-2019
#purpose: Lab 2
class Types_and_Strings:
def __init__(self):
pass
def play_with_strings(self):
# working with strings
message = input("Enter your name: ")
... |
425e5fa45d638c81352a74191a76c7057810c2c0 | Textualize/textual | /src/textual/_time.py | 1,435 | 3.59375 | 4 | import asyncio
import platform
from asyncio import sleep as asyncio_sleep
from time import monotonic, perf_counter
PLATFORM = platform.system()
WINDOWS = PLATFORM == "Windows"
if WINDOWS:
time = perf_counter
else:
time = monotonic
if WINDOWS:
# sleep on windows as a resolution of 15ms
# Python3.11 ... |
acea5b1f940289d35ff1c7a2df77627eac7543ce | Textualize/textual | /src/textual/geometry.py | 35,140 | 3.609375 | 4 | """
Functions and classes to manage terminal geometry (anything involving coordinates or dimensions).
"""
from __future__ import annotations
from functools import lru_cache
from operator import attrgetter, itemgetter
from typing import (
TYPE_CHECKING,
Any,
Collection,
NamedTuple,
Tuple,
Type... |
166d7a098db4017ca41e6de9058c1c3d5e78451f | clay1996/SimpleSweep | /SimpleSweepPro | 7,433 | 3.96875 | 4 | #!/usr/bin/env python3
'''Open to enter IP(s) as a command line argument.
An ARP scan is automatically performed on IP(s) entered and then prompted with the option to try to
ping the IP(s) found during the ARP scan.
If no IP is provided it will automatically perform an ARP scan on the network asking users
for ports... |
5c36317240cb693d50674cef15ee3737592a09c1 | Dimen61/leetcode | /python_solution/Array/56_MergeIntervals.py | 737 | 3.78125 | 4 | # Definition for an interval.
# class Interval(object):
# def __init__(self, s=0, e=0):
# self.start = s
# self.end = e
class Solution(object):
def merge(self, intervals):
"""
:type intervals: List[Interval]
:rtype: List[Interval]
"""
intervals.sort(key=l... |
64c3f597b0ca51f91b3216f93994989cac544fc6 | Dimen61/leetcode | /python_solution/Array/57_InsertInterval.py | 1,717 | 3.734375 | 4 | # Definition for an interval.
# class Interval(object):
# def __init__(self, s=0, e=0):
# self.start = s
# self.end = e
class Solution(object):
def insert(self, intervals, newInterval):
"""
:type intervals: List[Interval]
:type newInterval: Interval
:rtype: List[I... |
6881ca029f3a708884433e4b26010075f3979404 | Dimen61/leetcode | /python_solution/TwoPointers/209_MinimumSizeSubarraySum.py | 818 | 3.609375 | 4 | # The main idea is to main the proper window:
# Consider that every window which ends position is
# from 0 to len(nums)-1 and consider the start position
# of each window. We notice that start positions are ascending
# series.
class Solution(object):
def minSubArrayLen(self, s, nums):
"""
:type s: i... |
1ac11216ee3f43837c2fb2ea660a5c36c5d53b42 | Dimen61/leetcode | /python_solution/Tree/235_LowestCommonAncestorOfABinarySearchTree.py | 1,942 | 3.859375 | 4 | # Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def lowestCommonAncestor(self, root, p, q):
"""
:type root: TreeNode
:type p: TreeNode
:t... |
8923618cc605f650005e9f9fca42acbc1a6e9edf | Dimen61/leetcode | /python_solution/Tree/112_PathSum.py | 928 | 4 | 4 | # Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def hasPathSum(self, root, sum):
"""
:type root: TreeNode
:type sum: int
:rtype: bool
... |
99c46397bbcd013e3fe7c25dd1a0ee70b0055b35 | Dimen61/leetcode | /python_solution/Array/118_PascalTriangle.py | 747 | 3.671875 | 4 | class Solution(object):
def generate(self, numRows):
"""
:type numRows: int
:rtype: List[List[int]]
"""
triangle = []
current_line = []
for i in range(numRows):
if not current_line:
current_line.append(1)
triangle.ap... |
e0dca471d149615ebb6fce3f5011a80b609c5b73 | Dimen61/leetcode | /python_solution/Combination/140_WordBreakII.py | 1,943 | 3.625 | 4 | class Solution(object):
def wordBreak(self, s, wordDict):
"""
Basic dynamic programming
:type s: str
:type wordDict: Set[str]
:rtype: List[str]
"""
# word_lst = list(wordDict)
f = [[] for i in range(len(s)+1)]
for i in range(l... |
56bcab76434dc7b088e92960488fcabfb9b8d941 | Dimen61/leetcode | /python_solution/String/14.py | 671 | 3.734375 | 4 | class Solution(object):
def longestCommonPrefix(self, strs):
"""
:type strs: List[str]
:rtype: str
"""
res = ''
if not strs: return res # Empty list strs
for i in range(len(strs[0])):
char = strs[0][i]
flag = True
for j in ... |
70585f8c7aed6a0045485f05ca49586a203a0f7f | Dimen61/leetcode | /python_solution/Tree/124_BinaryTreeMaximumPathSum.py | 1,133 | 3.59375 | 4 | # Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def maxPathSum(self, root):
"""
Memorized search
:type root: TreeNode
:rtype: in... |
3d63b5d5b5844ef5d07dac492f2a50d63d7422e5 | Dimen61/leetcode | /python_solution/BinarySearch/230_KthSmallestElementInABST.py | 1,991 | 4.09375 | 4 | # Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def get_node_num(self, root):
"""
:type root: TreeNode
:rtype: int
"""
if not roo... |
77b73fc141684968c1e1294e8013ba05b15550f4 | Dimen61/leetcode | /python_solution/HashTable/274_H_Index.py | 949 | 3.6875 | 4 | # Use sorted array to implement a process intuitionly.
class Solution(object):
def hIndex(self, citations):
"""
:type citations: List[int]
:rtype: int
"""
array = sorted(citations, reverse=True)
index = citation = 0
for index, citation in enumerate(array):
... |
c94dfa49fb341906f3915db5ee07ed88e855d7e5 | kaifist/Rosalind_ex | /old_ex/k--mers_lexico_order.py | 872 | 3.75 | 4 | # Enumerating k-mers Lexicographically
##import itertools as it
##
##with open('rosalind_lexf.txt') as file:
## letras = file.readline().rstrip('\n').split()
## letras2 = ''.join(letras)
## print(letras2)
## n = int(file.readline())
##
## print(letras)
## print(letras2)
## lista_perm = it.product(letras2, repeat=n)
##... |
b25543c9cefc8df363d0a792e920c3880d8aa6a0 | BrandonMayU/Think-Like-A-Computer-Scientist-Homework | /6.13 Problems/6.13-4.py | 380 | 3.546875 | 4 | #Draw this pretty pattern.
import turtle
square = turtle.Turtle()
wn = turtle.Screen()
def drawSquare(turtle, size, totalSquares):
rotationAngle = 360/totalSquares
for i in range(totalSquares):
square.right(rotationAngle)
for i in range(4):
square.forward(size)
squar... |
dbd0ed785c9af1889311a980ad5911e9d0ae6c88 | BrandonMayU/Think-Like-A-Computer-Scientist-Homework | /6.13 Problems/6.13-14.py | 499 | 3.6875 | 4 | import math
def mySqrt(n):
initialGuess = n/2
for i in range(10):
newGuess = (1/2)*(initialGuess + (n/initialGuess))
initialGuess = newGuess
count = i + 1
print("Guess #", count,": ", newGuess)
trueSQRT = math.sqrt(n)
print("True Square root value = ", trueSQRT)
pr... |
482a4ab3e78e3f5e755ea3ff9b66fc48d3e5860f | BrandonMayU/Think-Like-A-Computer-Scientist-Homework | /7.10 Problems/5.6-17.py | 367 | 4.1875 | 4 | # Use a for statement to print 10 random numbers.
# Repeat the above exercise but this time print 10 random numbers between 25 and 35, inclusive.
import random
count = 1 # This keeps track of how many times the for-loop has looped
print("2")
for i in range(10):
number = random.randint(25,35)
print("Loop: ",c... |
b0c51fbea5fd4b4d4aa85f7137cea006f7de4acc | BrandonMayU/Think-Like-A-Computer-Scientist-Homework | /4.11 Problems/4.11-4.py | 516 | 4.03125 | 4 | import turtle
import math
print("Two Questions:")
print("A) Write a loop that prints each of the numbers on a new line. ")
print("Here is my solution.... ")
for i in [12, 10, 32, 3, 66, 17, 42, 99, 20]:
print("Value is ", i)
print("")
print("B) Write a loop that prints each number and its square on a new line. ... |
8478e33e1279a4135efdaf52e01e88ae3ca6d0b4 | roma-vinn/Combinatorics | /Matrix Chain/matrix_chain_dynamic.py | 2,195 | 4.03125 | 4 | """
Created by Roman Polishchenko at 12/9/18
2 course, comp math
Taras Shevchenko National University of Kyiv
email: roma.vinn@gmail.com
"""
import time
def matrix_chain_dynamic(dimensions, n):
""" Dynamic Programming Python implementation of Matrix
Chain Multiplication - build the worst sequence of brack... |
f3030a6ec17f2c79f004b68d360e2961d3e7b597 | suraj-pawar/python | /bitwiseoperator/swapbitsbetween2no.py | 459 | 4.0625 | 4 | #!usr/bin/python/python2.7
def swapbits(no1,no2,pos,bits):
x=no1
y=no2
mask=((2**bits)-1)<<(pos-bits) # pos=5,bits=4 ---> 0001 1110
xtemp= x & mask
ytemp= y & mask
x=x & (~ mask)
y=y & (~ mask)
x=x | ytemp
y=y | xtemp
return x,y
def main():
no1=input("Enter the no1")
no2=input("Enter the n... |
fb4a92c1a68d2645a3ba5f157c82dfde411f8b64 | suraj-pawar/python | /add10.py | 307 | 3.9375 | 4 | #!usr/bin/python/python2.7
#write a program to accept n no from user and add them
def my_generator():
count=input("HOW MANY ")
for x in range(count):
i=input()
yield i
def add(*args):
tot=0
for x in args:
tot=tot+x
print tot
if __name__ == "__main__":
it=my_generator()
add(*it)
|
5edf56c07a4fd7ad27529f0b009745889594b045 | TheProjecter/python-csv2pgsql | /csv2pgsql.py | 15,393 | 3.75 | 4 | """ Written by Cedric Boittin, 13/11/2013
A script for converting csv files to postgresql tables using python-psycopg2. It may be used to convert a single file, or every .csv file in a directory.
Automatically creates a table with the corresponding columns, assuming that the csv file has a one-row header. The d... |
869965fd4ec4fd740c4d05f09d2064e5d13fcbc7 | leeseulgi123/practice_python_coding | /Implementation_4.py | 1,908 | 3.59375 | 4 | # 구현 복습
print("지도의 크기를 입력하세요.(행,열) >")
n,m = map(int, input().split())
print("현재 캐릭터의 위치(행,렬)와 방향을 입력하세요. >")
x,y,d = map(int, input().split())
cnt = 1
turn_time = 0
# 경로
#(왼, 오, 상, 하)
steps = [(0,-1),(0,1),(-1,0),(1,0)]
# 방향
#(북, 동, 남, 서)
directions = [(-1,0),(0,1),(1,0),(0,-1)]
# 방문한 위치를 저장하는 2차원 리스트
my_path = [... |
6d5b34e5951b7ab00184f7ab79c8b6f95fdad582 | leeseulgi123/practice_python_coding | /23.py | 1,037 | 3.78125 | 4 | # 퀵 정렬(정통방식)
array = [5,7,9,0,3,1,6,2,4,8]
def quick_sort(array, start, end):
# 원소가 1개인 경우 종료
if start>=end:
return
# 첫번째 원소를 pivot으로.
pivot = start
left = start+1
right = end
while left<=right:
# pivot보다 큰 데이터를 찾을 때까지 반복.
while left<=end and array[left]<=array[pivo... |
a12ceb080ee0e74d55e9c692749d92e6abe150d4 | leeseulgi123/practice_python_coding | /70.py | 891 | 3.640625 | 4 | # 크루스칼 알고리즘
def find_parent(parent, x):
if parent[x]!=x:
parent[x] = find_parent(parent, parent[x])
return parent[x]
def union_parent(parent, a, b):
a = find_parent(parent, a)
b = find_parent(parent, b)
if a<b:
parent[b] = a
else:
parent[a] = b
print("노드의 개수와 간선의 개수를 입력... |
1f38fab51a8e374e89e2a501e07249ff03d6492f | leeseulgi123/practice_python_coding | /basic_adjacency_list.py | 330 | 3.515625 | 4 | graph = [[] for _ in range(3)]
# 노드 0에 1번 노드가 거리 7로 연결
graph[0].append((1,7))
# 노드 0에 2번 노드가 거리 5로 연결
graph[0].append((2,5))
# 노드 1에 0번 노드가 거리 7로 연결
graph[1].append((0,7))
# 노드 2에 0번 노드가 거리 5로 연결
graph[2].append((0,5))
print(graph)
|
96bcb662bf3270dcc8c8f76f0aceab9d0671d542 | Edmund-Lui98/SudokuCSP | /src/sudoku.py | 2,503 | 3.75 | 4 | """
-------------------------------------------------------
Sudoku class
-------------------------------------------------------
Section: CP468
-------------------------------------------------------
"""
import itertools
rows = characters = "ABCDEFGHI"
cols = numbers = "123456789"
class sudoku:
def __init__(... |
a311350bfa1104d209f64876457369db9c7caccd | vinitraj10/Python-Scrappers | /Image Downloader/image-downloader.py | 270 | 3.59375 | 4 | import random
import urllib.request
def download_image(url):
name = random.randrange(1,100)
file_name = str(name) + ".jpg"
urllib.request.urlretrieve(url,file_name)
print("Enter the URL:-")
x = input()
download_image(x)
print("Image Downloaded Please Check Folder") |
63d9e51100db4792259157df2e315f920b23f46f | Shashanksingh17/python-functional-program | /LeapYear.py | 227 | 4.125 | 4 | year = int(input("Enter Year"))
if year < 1000 and year > 9999:
print("Wrong Year")
else:
if year % 400 == 0 or (year % 4 == 0 and year % 100 != 0):
print("Leap year")
else:
print("Not a Leap Year")
|
68d2b16d105b9ec4642c467b96bec518f14b9646 | Shashanksingh17/python-functional-program | /PrimeFactor.py | 365 | 3.890625 | 4 | number = int(input("Enter Number"))
def prime(num):
count = 1
for i in range(1, num):
if num % i == 0:
count += 1
if count > 2:
break
if count == 2:
return True
return False
def factor(x):
for i in range(1, x+1):
if x % i == 0 and prime(i)... |
b5c3a44e099edcc1974e5854b17e4b2475dc6a76 | Appu13/RandomCodes | /DivideandConquer.py | 678 | 4.1875 | 4 |
'''
Given a mixed array of number and string representations of integers,
add up the string integers and subtract this from the total of the non-string integers.
Return as a number.
'''
def div_con(x):
# Variable to hold the string total
strtot = 0
# Variable to hold the digit total
digitot = 0... |
f71b9304377348916257e65a8fbcc29d3ed3652e | socrates77-sh/learn | /IntroAlgorithms/part1.py | 7,270 | 3.609375 | 4 | import numpy as np
from my_exception import *
def instersion_sort(a_list):
for j in range(1, len(a_list)):
key = a_list[j]
i = j-1
while i >= 0 and a_list[i] > key:
a_list[i+1] = a_list[i]
i = i-1
a_list[i+1] = key
return a_list
def sele... |
5a1793eadbe83d9a908e49dc320262c967cb2e13 | molchiro/AtCoder | /old/ABC131/D.py | 336 | 3.53125 | 4 | def main():
N = int(input())
tasks = []
for i in range(N):
tasks.append(list(map(int, input().split())))
tasks.sort(key=lambda x: x[1])
t = 0
for task in tasks:
t += task[0]
if t > task[1]:
print('No')
return
print('Yes')
if __name__ == "__main... |
f75b9ad9a002436828009a5589074e0d046cb09d | molchiro/AtCoder | /old/ABC196/B.py | 84 | 3.515625 | 4 | S = input()
if '.' in S:
ans, _ = S.split('.')
print(ans)
else:
print(S) |
e19bdfad1b2ec8290eeb59a1aaa33f5bab3b922a | molchiro/AtCoder | /ARC114/B.py | 806 | 3.875 | 4 | # UFして個数を数える
# ループを持っているものが有効
# 2^n-1が答え
class union_find:
def __init__(self, N):
self.par = [i for i in range(N)]
def root(self, i):
if self.par[i] == i:
return i
else:
# 経路圧縮
self.par[i] = self.root(self.par[i])
return self.par[i]
... |
7a049ad9b04e1243ad1f440447d89fe112979633 | Mvk122/misc | /CoinCounterInterviewQuestion.py | 948 | 4.15625 | 4 | """
Question: Find the amount of coins required to give the amount of cents given
The second function gets the types of coins whereas the first one only gives the total amount.
"""
def coin_number(cents):
coinlist = [25, 10, 5, 1]
coinlist.sort(reverse=True)
"""
list must be in descending order
... |
3214b2aee8eb0e99219132a7e53dd94fac966b6b | Mvk122/misc | /pisolver.py | 317 | 3.84375 | 4 | """
Solves for pi given random numbers between 0 and 1
"""
from random import random
def dist_from_origin(x,y):
return (x**2 + y**2)**0.5
in_circle = 0
step = 100000
for i in range(step):
x = random()
y = random()
if dist_from_origin(x,y) <= 1:
in_circle += 1
print(4 * in_circle/step) |
2af3d6bb8639cb85458007f533a0d416a9927718 | Yusra04/Assignment-1 | /yusra4.py | 229 | 3.96875 | 4 | newList = [12,35,9,56,34]
def swapList(newList):
size = len(newList)
temp = newList[0]
newList[0] = newList[size - 1]
newList[size - 1] = temp
return newList
print("list after swapping:",swapList(newList))
|
c0e648e64683095d35d3b2989bd0ad57f00dbe64 | yadhukrishnam/ProblemSolving | /Codeforces/1230A.py | 162 | 3.546875 | 4 | a,b,c,d = list(map(int, input().split()))
print ("YES" if a+b+c == d or a+b+d==c or b+d+c == a or c+a+d == b or a+b == c+d or a+c == b+d or d+a == b+c else "NO" ) |
6abf0887385dbb4e5a113a319aaa99960f7d803a | yadhukrishnam/ProblemSolving | /Codeforces/339A.py | 146 | 3.859375 | 4 | math = input().split('+')
math.sort()
for i in range(len(math)):
print (math[i], end='')
if i!=len(math)-1:
print ('+', end='')
|
08ee0fe594e47e38e12e85e95ea60c73f5bda6e3 | Rxy-J/BilibiliLiveRecorderV2 | /libs/parserSize.py | 558 | 3.546875 | 4 | def getSize(size):
counter = 0
while size > 1024:
counter += 1
size /= 1024
size = round(size, 2)
if counter == 0:
size = str(size)+"bytes"
elif counter == 1:
size = str(size)+"KB"
elif counter == 2:
size = str(size)+"MB"
elif counter == 3:
siz... |
0fbadc167cbe38b93d0a964cb260fad9e22c5eb1 | JackTJC/LeetCode | /Math/Divide.py | 1,533 | 3.609375 | 4 | # 29. 两数相除
# 给定两个整数,被除数 dividend 和除数 divisor。将两数相除,要求不使用乘法、除法和 mod 运算符。
#
# 返回被除数 dividend 除以除数 divisor 得到的商。
#
# 整数除法的结果应当截去(truncate)其小数部分,例如:truncate(8.345) = 8 以及 truncate(-2.7335) = -2
class Solution:
def divide(self, dividend: int, divisor: int) -> int:
def binary2decimal(binary):
i = 1
... |
c2369a92a6280ff7003dd8a8745fceed184b957e | zmh93/algorithm | /algorithm_py/main/quicksort.py | 1,882 | 3.5 | 4 | arr = [
2, 4, 5, 5, 6, 7, 11, 11, 11, 12, 12, 13, 13, 13, 13, 14, 16, 18, 19, 19, 19, 22, 22, 23, 27, 29, 29, 30, 31, 33,
37,
38, 38, 38, 39, 39, 40, 40, 41, 42, 42, 43, 43, 46, 46, 50, 50, 52, 55, 57, 57, 57, 58, 59, 59, 59, 59, 59, 60, 62,
65,
65, 65, 67, 68, 68, 68, 68, 71, 73, 73, 73, 73, 73, 73... |
3659873714b860773c3ad625e98cff815afa6d24 | ivvovk/homework1 | /Main.py | 2,089 | 3.8125 | 4 | def step1():
print('Привет, '+uname+'. Я хочу сыграть с тобой в игру! '
'Утка-маляр решила погулять.'
'Взять ей зонтик?')
option=''
options={'да': True, 'нет': False}
while option not in options:
print('Выберите: {}/{}'.format(*options))
option=... |
66ef5fe01c8646a41fd47263baf6fb45a636e563 | huqa/sudoku-solver | /solver.py | 5,077 | 3.671875 | 4 | # Simple brute force sudoku solver
#
# author: huqa (pikkuhukka@gmail.com)
S_NUMBERS = [1,2,3,4,5,6,7,8,9]
def change_zeroes_to_nones(grid):
'''Changes zeroes to None in grid'''
for i in range(0, len(grid)):
for j in range(0, len(grid[i])):
if grid[i][j] == 0:
grid[i][j] =... |
d25ac7c10ce42fed83f392ed9c5a02a3246eb146 | Svanfridurjulia/FORRITUN-SJS-HR | /Verkefni í tímum/assignment 3 while/assignment3.6.py | 222 | 4.125 | 4 | a0 = int(input("Input a positive int: ")) # Do not change this line
print(a0)
while a0 != 1:
if a0 % 2 == 0:
a0 = a0/2
print(int(a0))
elif a0 % 2 != 0:
a0 = 3*a0+1
print(int(a0))
|
594a8617abbfcd4175d45ff721b03d6f77425665 | Svanfridurjulia/FORRITUN-SJS-HR | /Hlutapróf 2/babynames.3.py | 3,394 | 4.28125 | 4 | def open_file(filename):
'''A function which tries to open the file and return it if the file is found. Otherwise it prints out error message'''
try:
opened_file = open(filename,"r")
return opened_file
except FileNotFoundError:
print("File {} not found".format(filename))
def m... |
583bfced1f6e8059c86a80fb64cf757db6cdde6d | Svanfridurjulia/FORRITUN-SJS-HR | /Verkefni í tímum/assignment 10 listar/assignment10.3.1.py | 489 | 4.03125 | 4 | def add_word():
word = ""
while word != "x":
word = input("Enter word to be added to list: ")
if word != "x":
first_list.append(word)
def word_list():
for word in first_list:
if len(word) > 1:
if word[0] == word[-1]:
second_list.append(word)
... |
8ce075118b7aca2dd2dc8f54eb59146e8c4edaf4 | Svanfridurjulia/FORRITUN-SJS-HR | /Hlutapróf 2/prófdæmi.py | 1,553 | 4.3125 | 4 | def sum_number(n):
'''A function which finds the sum of 1..n and returns it'''
sum_of_range = 0
for num in range (1,n+1):
sum_of_range += num
return sum_of_range
def product(n):
'''A function which finds the product of 1..n and returns it'''
multi = 1
for num in range(1,n+1):
... |
7c041a0333ad9a58383c495981485c535f6aa8bd | Svanfridurjulia/FORRITUN-SJS-HR | /æfingapróf/dæmi2.py | 878 | 4.21875 | 4 |
def open_file(filename):
opened_file = open(filename,"r")
return opened_file
def make_list(opened_file):
file_list = []
for lines in opened_file:
split_lines = lines.split()
file_list.append(split_lines)
return file_list
def count_words(file_list):
word_count = 0
punctua... |
a21a95fe8e825f0f09618cc3bcb6429dee540b70 | Svanfridurjulia/FORRITUN-SJS-HR | /Verkefni í tímum/assignment 3 while/Assignment3.1.py | 106 | 4.03125 | 4 | num = int(input("Input an int: ")) # Do not change this line
while num > 0:
print(num)
num -= 1
|
e96457e428d89fa70a8c586aeaf12921e84f2948 | Svanfridurjulia/FORRITUN-SJS-HR | /Verkefni í tímum/assignment 9 files and exception/assignment9.1.py | 274 | 3.890625 | 4 | def remove_whitespaces(opened_file):
for line in opened_file:
print(line.strip().replace(" ", ""), end = "")
return True
file_name = input("Enter filename: ")
opened_file = open("data.txt", "r")
readfile = remove_whitespaces(opened_file)
print(readfile)
|
9be417a8ba86044f1b8717d993f44660adfbf9cd | Svanfridurjulia/FORRITUN-SJS-HR | /æfing.py | 1,056 | 4.3125 | 4 |
def find_and_replace(string,find_string,replace_string):
if find_string in string:
final_string = string.replace(find_string,replace_string)
return final_string
else:
print("Invalid input!")
def remove(string,remove_string):
if remove_string in string:
final2_string = stri... |
ad54a59bba32e1563975822c184df6cd0881b223 | Svanfridurjulia/FORRITUN-SJS-HR | /Hlutapróf1/dog_age.py | 790 | 4.09375 | 4 | dog_age = int(input("Input dog's age: ")) # Do not change this line
human = 16
if 0 < dog_age < 17:
human_count = dog_age * human - (dog_age*dog_age*dog_age)
print("Human age:", int(human_count))
else:
print("Invalid age")
if 1 < dog_age < 17:
human_age = human + dog_age * 4 + 1
print("Human a... |
f0d663cbc1f64b3d08e61927d47f451272dfd746 | Hiradoras/Python-Exercies | /30-May/Valid Parentheses.py | 1,180 | 4.375 | 4 | '''
Write a function that takes a string of parentheses, and determines
if the order of the parentheses is valid. The function should return
true if the string is valid, and false if it's invalid.
Examples
"()" => true
")(()))" => false
"(" => false
"(())((()())())" => true
Con... |
cf9270abd93e8b59cdb717deeea731308bf5528d | Hiradoras/Python-Exercies | /29-May-2021/Reverse every other word in the string.py | 895 | 4.25 | 4 | '''
Reverse every other word in a given string, then return the string.
Throw away any leading or trailing whitespace, while ensuring there
is exactly one space between each word. Punctuation marks should be
treated as if they are a part of the word in this kata.
'''
def reverse_alternate(string):
words = string.s... |
babfec5fcd6237914c59f824bddafcf2e737d7a9 | wizardcalidad/Machine-Learning-Algorithms | /Logistic Regression/main.py | 3,703 | 3.71875 | 4 | import numpy as np
import util
import pdb
def main(train_path, valid_path, save_path, save_img):
"""Problem: Logistic regression with Newton's Method.
Args:
train_path: Path to CSV file containing dataset for training.
valid_path: Path to CSV file containing dataset for validation.
sav... |
1f38b049d4a9e7f0b91ab23ce54fd3ecfa65c47a | viorato/compute_rational_links_genus | /continued_fractions.py | 1,489 | 3.875 | 4 | """
Continued fractions.
"""
from decimal import Decimal
from fractions import Fraction
class CFraction(list):
"""
A continued fraction, represented as a list of integer terms.
"""
def __init__(self, value, maxterms=15, cutoff=1e-10):
if isinstance(value, (int, float, Decimal)):
... |
4768d84a53b7f0f91a47e43fd5764369cd1c8316 | RickLicona/Algorithms_and_Data_structures | /Sorting_and_searching/quick_sort.py | 1,770 | 3.984375 | 4 | def quick_sort(a_list):
quick_sort_helper(a_list, 0, len(a_list)-1)
def quick_sort_helper(a_list, first, last):
if first < last:
split_point = partition(a_list, first, last)
quick_sort_helper(a_list, first, split_point-1)
quick_sort_helper(a_list, split_point+1, last)
def partition(a... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.