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 |
|---|---|---|---|---|---|---|
975fec797a263f6752b4f4d9cfabf16e910c7279 | DeepakSunwal/Daily-Interview-Pro | /solutions/towers_of_hanoi.py | 1,409 | 3.90625 | 4 | """
Proof: http://mathforum.org/library/drmath/view/55956.html
This problem is clearly a recursive problem:
- To move n disks from one pole to another, we must first move n-1 disks to the
helper pole and then move the n'th disk to the target pole. Finally, move the
n-1 disks from the helper pole to the tar... |
f86543f779c92ba95efd9c5a4ddcab3303bbc82c | DeepakSunwal/Daily-Interview-Pro | /solutions/pascals_triangle.py | 303 | 3.640625 | 4 | def pascals(n):
triangle = [[1] * i for i in range(1, n + 1)]
for i in range(n):
for j in range(1, i):
triangle[i][j] = triangle[i-1][j]+triangle[i-1][j-1]
return triangle[-1]
def main():
assert pascals(6) == [1,5,10,10,5,1]
if __name__ == '__main__':
main()
|
0269f0236dfa291272c1925b4cf8d50578685e39 | DeepakSunwal/Daily-Interview-Pro | /solutions/symmetrical_tree.py | 1,083 | 3.96875 | 4 | class Node(object):
def __init__(self, value):
self.value = value
self.children = []
def is_symmetrical(root):
return find_symmetry(root, root)
def find_symmetry(root1, root2):
if not (root1 or root2):
return True
if not (root1 and root2):
return False
if root1.va... |
5c67866d3212c69d8fb4e40e2fb5ce4e86f953b7 | DeepakSunwal/Daily-Interview-Pro | /solutions/generate_all_ip_addresses.py | 870 | 3.578125 | 4 | def is_valid(string):
for sub in string.split("."):
if len(sub) > 3 or int(sub) < 0 or int(sub) > 255:
return False
if len(sub) > 1 and int(sub) == 0:
return False
if len(sub) > 1 and int(sub) != 0 and int(sub[0]) == 0:
return False
return True
def g... |
92bd751ab4cfffe1d6b9861dc7e087ce9ce830be | DeepakSunwal/Daily-Interview-Pro | /solutions/calculate_angle.py | 484 | 4.03125 | 4 | def calculate_angle(hour, minute):
minute_angle = 6 * minute
hour_angle = (30 * hour + (30 * (minute/60))) % 360
print(minute_angle, hour_angle)
return hour_angle - minute_angle if hour_angle >= minute_angle else minute_angle - hour_angle
# each minute = 0.5 degrees
# hour = 30 degrees
# each rotation ... |
091d83f7649e680f0c9481bdc6deb6dbb3d21172 | DeepakSunwal/Daily-Interview-Pro | /solutions/rearrange_nonadjacent_string.py | 766 | 3.890625 | 4 | import heapq
def rearrange(string):
character_count = [(-string.count(char), char) for char in set(string)]
if any([-count for count, char in character_count]) > (len(string) + 1) / 2:
return ""
heapq.heapify(character_count)
result = ""
while len(character_count) >= 2:
count1, cha... |
4436362c69115bdc716fce8713961fc2ebc0c78a | DeepakSunwal/Daily-Interview-Pro | /solutions/all_permutations.py | 489 | 3.703125 | 4 | from copy import copy
def find_permutations(numbers, low, high):
if low == high:
return [numbers]
result = []
for i in range(low, high+1):
temp = copy(numbers)
temp[low], temp[i] = temp[i], temp[low]
result.extend(find_permutations(temp, low + 1, high))
return result
... |
6487331730c120c1a15329778306bddc9a9169ae | DeepakSunwal/Daily-Interview-Pro | /solutions/string_compression.py | 684 | 3.796875 | 4 | def string_compression(string):
count = 1
current_char = string[1]
result = []
for char in string[1:]:
if char == current_char:
count += 1
else:
if count > 1:
result.extend([current_char, str(count)])
else:
result.append... |
f703df8c624a0364c15d2ba43e44b43ea666edc4 | DeepakSunwal/Daily-Interview-Pro | /solutions/count_invalid_parenthesis.py | 560 | 4 | 4 | def count(parentheses):
p_stack = []
changes = 0
for p in parentheses:
if p == ")":
if not p_stack:
changes += 1
else:
p_stack.pop()
else:
p_stack.append(p)
if p_stack:
if len(p_stack) % 2:
changes +=... |
c503ba12389dc9f0f2fcdb6ea717308d8f5b4e9e | DeepakSunwal/Daily-Interview-Pro | /solutions/longestKDistinctCharSubstring.py | 910 | 3.703125 | 4 | from collections import deque
def longest_substring_with_k_distinct_characters(string, k):
char_dict = dict()
current_sub_string = deque()
largest_substring = ""
for char in string:
current_sub_string.append(char)
try:
char_dict[char] += 1
except:
char_d... |
ac4a6030fba4e128077f293875698049ba6af4e3 | DeepakSunwal/Daily-Interview-Pro | /solutions/palindromic_linked_list.py | 957 | 4 | 4 | class Node(object):
def __init__(self, val):
self.val = val
self.next = None
self.prev = None
def is_palindrome(node):
if not (node and node.next):
return True
head = node
current = None
while node.next:
if not node.next.next:
current = node.next... |
faf6b76ffa2320cc9d7d8d712fa7f828f7bd77f4 | DeepakSunwal/Daily-Interview-Pro | /solutions/number_to_column_title.py | 587 | 3.890625 | 4 | from string import ascii_uppercase
def convert(number):
alphabet_dict = {number: ascii_uppercase[number - 1] for number in range(0, 26)}
result = ''
while number >= 1:
res = (number % 26)
result = alphabet_dict[res] + result
if res == 0:
number -= 1
number //= 2... |
c86b4781187375143c5771f486da0501c2fa7a0e | DeepakSunwal/Daily-Interview-Pro | /solutions/sum_binary.py | 590 | 3.609375 | 4 | def sum_binary(bin1, bin2):
carry = 0
result = ""
index = 0
bin1, bin2 = bin1[::-1], bin2[::-1]
while index < len(bin1) or index < len(bin2):
if index < len(bin1):
carry += ord(bin1[index]) - ord('0')
if index < len(bin2):
carry += ord(bin2[index]) - ord('0')
... |
0eb285820cf4dd56b7b48ca16b3c4b34fe362610 | DeepakSunwal/Daily-Interview-Pro | /solutions/simpleCalculator.py | 1,472 | 3.5625 | 4 | from collections import deque
def eval(expression):
res = 0
remainingExp = deque()
currentExp = deque()
expression = expression.replace(" ", "")
for exp in expression:
if exp == ")":
for _ in range(len(currentExp)):
remainingExp.pop()
while currentEx... |
2834f29adbc341bf822e5418c96212f08954ad07 | DeepakSunwal/Daily-Interview-Pro | /solutions/product_all_other_values.py | 1,568 | 3.8125 | 4 | from collections import deque
def get_values(numbers):
temp = 1
result_array = [1 for _ in numbers]
# Each index has the accumulative product shifted one place to the right
for index, number in enumerate(numbers):
result_array[index] = temp
temp *= number
temp = 1
# From right ... |
553d54eea3d072a1ba4fbe432cf4a1471db2e0c4 | hariniavd/MethodProject | /test_nested_list.py | 1,008 | 3.8125 | 4 | """ Test cases for nested lists file.
"""
import unittest
import nested_lists
class TestNestedLists(unittest.TestCase):
""" Test cases for nested list function.
"""
def test_remove_nested_loop_dict(self):
""" Test case for nested lists passing a dictionary.
"""
expected = {}
... |
79db37e0b129c45892fb24b79f626477b3777b87 | Bongkot-Kladklaen/Programming_tutorial_code | /Python/Python_GUI/radio_button2.py | 474 | 3.71875 | 4 | from tkinter import *
d = {'thai':'th','japanese':'jp','korean':'kr','chinese':'cn'}
def on_select(e):
print(e.widget['text'], e.widget['value'])
root = Tk()
root.option_add('*Font','consolas 20')
tv_code = StringVar()
tv_code.set('thai')
n_col = 3
i=0
for k,v in d.items():
r = Radiobutton(root,text=k, value=... |
11917d14801009c9fdcf3146dfeaa925a3eee19c | Bongkot-Kladklaen/Programming_tutorial_code | /Lab_programming/Matrix Addition.py | 343 | 3.59375 | 4 | row, col = input().split()
numberSum, matrix = [], []
for _ in range(int(row)):
matrix.append([int(j) for j in input().split()])
for _ in range(int(row)):
numberSum.append([int(j) for j in input().split()])
for i in range(len(matrix)):
for j in range(int(col)):
print(matrix[i][j] + numberSum[i][j... |
92464b02d80f9faca7a3bbca6136bb7445cc1d56 | Bongkot-Kladklaen/Programming_tutorial_code | /Python/Python_Beginners/Sorting/list.py | 331 | 3.828125 | 4 | num = [10,2,3.4,56,1,1,11]
num2 = [10,2,3.4,56,1,1,11]
num.sort()
print(num)
num2.sort(reverse=True)
print(num2)
list1 = ['aa','b','eeee','ccccc','ddd']
list1.sort(key=len)
print(list1)
list2 = [[2,9],[1,10],[3,7]]
list2.sort()
print(list2)
def SortBySec(element):
return element[1]
list2.sort(key=SortBySec)
p... |
6c0777a8bd9129fcdf46041efa362c4abfc96652 | Bongkot-Kladklaen/Programming_tutorial_code | /Python/Python_Assignment/EP34.Assignment10.py | 803 | 3.59375 | 4 | # number = []
# while True:
# x = int(input("Enter number: "))
# if x < 0:
# break
# number.append(x)
# number.sort()
# number.reverse()
# print(number)
# print(min(number))
# print(max(number))
# print(sum(number))
fish_kg = []
number = []
while True:
x = int(input())
if x == 0:
m... |
8ba9f444797916c33a00ce7d7864b1fa60ae6f24 | Bongkot-Kladklaen/Programming_tutorial_code | /Python/Python_basic/Ex24_UserInput.py | 271 | 4.1875 | 4 |
#* User Input
"""
Python 3.6 uses the input() method.
Python 2.7 uses the raw_input() method.
"""
#* Python 3.6
username = input("Enter username:")
print("Username is: " + username)
#* Python 2.7
username = raw_input("Enter username:")
print("Username is: " + username) |
f83dc10a41d95cd7af2c032927dd40f88f084967 | Bongkot-Kladklaen/Programming_tutorial_code | /Python/NumPy/numpy6_Split.py | 236 | 3.78125 | 4 | import numpy as np
#? การแยกอาร์เอย์ออกแบบส่วน ๆ array_split()
arr = np.array([1, 2, 3, 4, 5, 6])
newarr = np.array_split(arr, 3)
print(newarr)
newarr = np.hsplit(arr, 3)
print(newarr) |
c62f52ea5e6260fbe15943d27c07d902671e9d01 | Bongkot-Kladklaen/Programming_tutorial_code | /Python/Python_DataStructure/Recursion/SumListNumber2.py | 257 | 3.8125 | 4 | def list_sum(data_list):
total = 0
for element in data_list:
if type(element) == type([]):
total = total + list_sum(element)
else:
total = total + element
return total
print(list_sum([2,4,[6,8],[10,12]])) |
929a317434e72aa599c84969e3bbdcc0f755653c | Bongkot-Kladklaen/Programming_tutorial_code | /Python/Python A.prasert/pass_fn_fn_arg.py | 817 | 4.03125 | 4 | import random
def add(a,b):
return a + b
def f(func,a,b):
return func(a,b)
def fx(func):
for _ in range(10):
a = random.randrange(1,13)
b = random.randrange(1,13)
print(f"{a} op {b} = {func(a,b)}")
def mental_math():
funcs = {
'+':lambda a,b: a+b,
'-':lambda a,... |
6abf3d5d18caaab027fced167a444774be8412b6 | Bongkot-Kladklaen/Programming_tutorial_code | /Python/Python_Beginners/Control_Sturcures/for.py | 176 | 4.03125 | 4 | for var in "python":
print(var)
for letter in [10,20,30,40,50]:
if letter >= 25:
print(letter,'greater than 25')
else:
print(letter,'lass than 25') |
1aa01887c22938e7c9de4f2672fb54e2f2596ac1 | Bongkot-Kladklaen/Programming_tutorial_code | /Python/Python A.prasert/basic_zip.py | 704 | 3.53125 | 4 |
def demo1():
weight = [70,60,48]
height = [170,175,161]
bmi = []
for i in range(len(weight)):
bmi.append(weight[i] / (height[i]/100) ** 2)
return bmi
def demo2():
weight = [70,60,48]
height = [170,175,161]
bmi = []
for w,h in zip(weight,height):
bmi.append(w / (h ... |
1c177c418dc1036b00da6a98ce409b7c233176ba | Bongkot-Kladklaen/Programming_tutorial_code | /Python/Python_basic/Ex5_Strings.py | 5,224 | 4.03125 | 4 | """
Escape Character:
\' Single Quote
\\ Backslash
\n New Line
\r Carriage Return
\t Tab
\b Backspace
\f Form Feed
\ooo Octal value
\xhh Hex value
"""
#* String Literals
print("Hello")
print('Hello')
#* Assign String to a Variable
a = "Hello"
print(a)
#* Multiline Strings
a... |
4d2dbcff8ab46180b0154e1503b1485739c6dde7 | HannesOS/Systems-Modeling-Spring-2015-Notebooks | /Thursday Feb 12 2015.py | 1,106 | 3.984375 | 4 | # -*- coding: utf-8 -*-
# <nbformat>3.0</nbformat>
# <codecell>
%gui tk
from turtle import *
# <codecell>
reset()
#speed("fastest")
current_color="red"
other_color="black"
for i in range(160):
pencolor(current_color)
forward(150)
backward(150)
left(3)
# comment - swap the colors
if i%3==0... |
e6b156740ad6ad521cd27ad86cc6d728529ad3a2 | HannesOS/Systems-Modeling-Spring-2015-Notebooks | /Correct Answer to HW from Thursday Feb 19 2015 - sim with two variables.py | 1,589 | 3.890625 | 4 | # -*- coding: utf-8 -*-
# <nbformat>3.0</nbformat>
# <markdowncell>
# ## Question to Hand In - Excel Simulation
#
# 1. For the following system, write out the discrete simulation equations
# 2. Make an Excel simulation using these equations
# 3. Discuss the result
#
# \begin{eqnarray}
# x'&=&v\\
# v'&=&k - c\cdot v... |
fb599eaa6e2a8bb4293223c38b3f98179734b92f | jkpubsrc/python-module-jk-console | /examples/simpletable.py | 892 | 3.875 | 4 | #!/usr/bin/env python3
#
# This example demonstrates the use of SimpleTable with alignments, text transformations and colors.
#
import os
import sys
from jk_console import *
t = SimpleTable()
with t.addRow("Key", "Value") as r:
r.color = Console.ForeGround.STD_LIGHTGREEN
#r.halign = SimpleTable.HALIGN_LEFT
... |
88da38a450a71d384bb3c777b4dd2c80a82ed7e7 | jkpubsrc/python-module-jk-console | /src/jk_console/viewport/Rectangle.py | 7,465 | 3.578125 | 4 |
from typing import Union
class Rectangle(object):
def __init__(self, *args):
if len(args) == 0:
self.__x1 = 0
self.__y1 = 0
self.__x2 = 0
self.__y2 = 0
elif len(args) == 1:
arg = args[0]
if isinstance(arg, (tuple, list)):
assert len(arg) == 4
assert isinstance(arg[0], int)
ass... |
532ccfeeeb90f0253f797033fe95b1fd3f1634c4 | jkpubsrc/python-module-jk-console | /examples/colorizedoutput.py | 282 | 3.5 | 4 | #!/usr/bin/env python3
#
# This example demonstrates how to write colored text to STDOUT.
#
from jk_console import Console
print(Console.ForeGround.CYAN + "Hello World!" + Console.RESET)
print(Console.BackGround.rgb256(128, 0, 0) + "Hello World!" + Console.RESET)
|
b19a0fca96e565ed56ccb2a82cb892b79dacafbc | NasreddinHodja/cg_t1 | /rasterization.py | 5,838 | 3.90625 | 4 | #!/usr/bin/env python3
""" Rasterization
Takes in a scene description with primitives, that can
have an xform associated with, and rasterizes it to an
image that is then shown using PIL Image.show().
Usage:
./rasterization.py [shape]
Args:
shape: json file containing grafics description
"""
import sys
imp... |
92e0fbe7905515ac40954a813dd2a37ffde79520 | raviitsoft/Python_Fundamental_DataScience | /0 Python Fundamental/25.b.map.py | 661 | 3.765625 | 4 | # map python
def y(a):
return len(a)
a = ['Andilala', 'Budiman', 'Caca']
x = map(y, a)
# print(x)
# print(list(x))
########################################
a = ['Cokelat', 'Melon', 'Nangka']
b = ['Apel', 'Jeruk', 'Nanas']
def combi(a, b):
return a+' '+b
x = map(combi, a, b)
# print(x)
# print(list(x))
######... |
cccab191e43db383bb37c1a9a05e60ce4df8777e | mayankDhiman/cp | /codechef/AUG19B/DSTAPLS.py | 188 | 3.546875 | 4 | import math
tt = int(input())
for _ in range(tt):
n, k = input().split(' ')
n = int(n)
k = int(k)
if (n % (k**2) == 0):
print("NO")
else:
print("YES")
|
a2245d6d3d4eef959623298322eb5a2bb3af0485 | SeungjuU/test1 | /task_9.py | 105 | 3.921875 | 4 | x=int(input('enter the x: '))
y=int(input('enter the y: '))
def mySum(x,y):
print (x+y)
mySum(x,y)
|
dc6515bb3acd810a8e1d86aa59033b660a368594 | Yibangyu/oldKeyboard1 | /1023.py | 381 | 4.1875 | 4 | #!/usr/bin/python
import re
preg = input()
string = input()
result_string = ''
preg = preg.upper() + preg.lower()
if '+' in preg:
preg = preg+'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
if preg:
for char in string:
if char in preg:
continue
else:
result_string = result_string + ... |
14fd87a29e472ebb0c074765b26425597dfcb2cc | mijapa/FuzzyLogic | /add.py | 994 | 3.703125 | 4 | from norm import minimum
f_number_1 = {(0.3, 1), (1, 2)}
f_number_2 = {(1, 1), (0.5, 2)}
def addition(number_1, number_2, norm):
a_set = set() # creating empty set
for x in number_1:
for y in number_2:
fuzzy_sum = (norm(x, y)[0], x[1] + y[1])
print("x: {}, y: {}, fuzzy sum: {... |
349cc587f4263f0eb99888dd43dc841b4c6c11e3 | captainpainway/advent-of-code-2019 | /day1.py | 648 | 3.5625 | 4 | import math
from functools import reduce
input = open('day1input.txt').read().splitlines()
def calcFuel(amt):
return math.floor(int(amt) / 3) - 2
def addFuel(f1, f2):
return f1 + f2;
def fuelRequired(modules):
return reduce(addFuel, map(calcFuel, modules))
def additionalFuelNeeded(fuel):
total = 0
... |
8076fc2f60d0526ac5a1feed7941882ebdd72704 | luizfranca/project-euler | /python/p09.py | 302 | 4.09375 | 4 | # Special Pythagorean triplet
import math
def pythagorean_Triplet(n):
number = 0
for a in range(1, n):
for b in range(1, n):
c = math.sqrt(a ** 2 + b ** 2)
if c % 1 == 0:
number = a + b + int(c)
c = int(c)
if number == n:
return a * b * c
print pythagorean_Triplet(1000) |
d978a0a27c0987acdd1dca405e71d7195cf70907 | alanbriolat/SFWG | /src/service.py | 1,864 | 3.515625 | 4 | #!/usr/bin/python
class Service:
ports = None
protocols = None
description = None
def __init__(self, params, desc):
# Split up parameters - these are the result of split('|') on a config
# line usually
port, proto = params
self.description = desc
# Check the v... |
21fe03d6144a70deccb408b6c4d1a2e5e065d255 | aces/Loris-MRI | /python/lib/database_lib/session_db.py | 3,784 | 3.578125 | 4 | """This class performs session table related database queries and common checks"""
__license__ = "GPLv3"
class SessionDB:
"""
This class performs database queries for session table.
:Example:
from lib.database_lib.session_db import SessionDB
from lib.database import Database
#... |
9e1133291434351af948b3f10621b3548bc4b7ed | aces/Loris-MRI | /python/lib/database_lib/physiologicalannotationfile.py | 2,229 | 3.515625 | 4 | """This class performs database queries for the physiological_annotation_file table"""
__license__ = "GPLv3"
class PhysiologicalAnnotationFile:
def __init__(self, db, verbose):
"""
Constructor method for the PhysiologicalAnnotationFile class.
:param db : Database class ... |
f1a2ceeea899520d3a3a5b3f11c5599ff1ee4903 | apmcdaniels/CAAP-CS | /Lab2/Lab2/game/game.py | 1,873 | 3.828125 | 4 | # imports multiple clases from the python library and some of our
# own modules.
from sys import exit
from random import randint
from map import Map
from leaderboard import Leaderboard
from scores import Score
from game_engine import Engine
# global variables to keep track of score, player, and leaderboard
m... |
2ae0b6dc06c2185db777ac1f2713d01556a409f0 | apmcdaniels/CAAP-CS | /hw1/Part_i/unitconversion.py | 149 | 3.875 | 4 | def main():
centimeters = eval(input("How many centimeters?"))
inches = centimeters/2.54
print("you have", inches, "inches.")
main() |
8884da37c1e7b0076c6acd2a0daa077762d7aadd | kerzol81/Bash-and-Python-scripts | /multipleSiteSearch | 314 | 3.5 | 4 | #!/usr/bin/env python3
import webbrowser
sites = [ 'site1', 'site2', 'site3', 'etc.' ]
print('Multiple google search on sites:')
for site in sites:
print(site)
keyword = input('\nKeyword: ')
for site in sites:
webbrowser.open_new_tab('http://www.google.com/search?btnG=1&q=%s' % keyword + ' ' + site)
|
0b4f540f089378f5adf6e5a5ad81283a0f2af7b2 | suphaWiz/Sanntid | /Exercise1.py | 442 | 3.609375 | 4 | from threading import Thread
global i
i = 0
def someThreadFunction1():
global i
for s in range(0,1000000):
i = i+1
def someThreadFunction2():
global i
for s in range(0,1000000):
i = i-1
def main():
someThread1 = Thread(target = someThreadFunction1, args = (),)
someThread2 = Thread(target = someThreadFuncti... |
466eafb6a18fbb60b2403a55ca0938d9f5121bab | riaz34/simple_port_scanner_using_sock | /simple.py | 684 | 3.734375 | 4 | #!//usr/bin/python
import socket
target=input("enter the ipaddress: ")
port_rg=input("enter the port range: ")
low=int(port_rg.split('-')[0])
high=int(port_rg.split('-')[1])
print('########################################################################')
print('target ip:',target,'scanning start from:',lo... |
c5df19647964583e9476722ba1128219e56acf78 | vanessadyce/Movie-Trailer-Website | /media.py | 450 | 3.890625 | 4 | class Movie():
"""This class defines a movie.
Attributes:
movie_title (str): The title of the movie
poster_url (str): The url to the movie poster
youtube_link (str): The link to the movie trailer
"""
# Movie constructor
def __init__(self, movie_title, poster_url, youtube_l... |
abddade25f89b83a28dd56a92f742a6ef0e3e04f | zacharyzhu2023/CS61C | /lectures/Lec31-IO Devices.py | 6,193 | 4.03125 | 4 | Lecture 31: I/O Devices
I/O Devices
- I/O interface provides mechanism for program on CPU to interact w/ outside world
- Examples of I/O devices: keyboards, network, mouse, display
- Functionality: connect many devices--control, respond, & transfer data b/w devices
- User programs should be able to build on their f... |
9b02c4bcb2ca1024a04cf0b354483d65e6a5d616 | CoderQingli/MyLeetCode | /669. Trim a Binary Search Tree.py | 456 | 3.53125 | 4 | def trimBST(self, root, L, R):
"""
:type root: TreeNode
:type L: int
:type R: int
:rtype: TreeNode
"""
def trim(root):
if not root:
return None
if root.val > R:
return trim(root.left)
if root.val < L:
return trim(root.right)
... |
4fe4f4939210b2fe975124c51b4ce4808360e4d3 | CoderQingli/MyLeetCode | /2. Add Two Numbers.py | 604 | 3.578125 | 4 | def addTwoNumbers(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
res = ListNode(0)
cur = res
flag = 0
while l1 or l2:
if l1 and l2:
flag, tmp = divmod(l1.val + l2.val + flag, 10)
elif l1:
flag, tmp = divmod(l1.val... |
9fb30377b4a0ec0c426923c8b6b3271bb8b6fb9b | CoderQingli/MyLeetCode | /415. Add Strings.py | 466 | 3.65625 | 4 | def addStrings(num1, num2):
"""
:type num1: str
:type num2: str
:rtype: str
"""
res = ""
tmp = 0
while num1 or num2 or tmp != 0:
if num1:
tmp += (ord(num1[-1]) - ord("0"))
if num2:
tmp += (ord(num2[-1]) - ord("0"))
res += str(tmp % 10)
... |
1c354c45edc44129c5cdc634a7a086c3826515a1 | CoderQingli/MyLeetCode | /70. Climbing Stairs.py | 175 | 3.671875 | 4 | def climbStairs(self, n):
"""
:type n: int
:rtype: int
"""
res = [1, 2]
while len(res) < n:
res.append(res[-1] + res[-2])
return res[n - 1] |
24112db6f4e4624b1bffb3aa672b3a3bd0417227 | CoderQingli/MyLeetCode | /860. Lemonade Change.py | 610 | 3.59375 | 4 | def lemonadeChange(bills):
"""
:type bills: List[int]
:rtype: bool
"""
res = {5: 0, 10: 0}
for b in bills:
if b == 5:
res[5] += 1
elif b == 10:
if res[5] == 0:
return False
else:
res[10] += 1
res[... |
e40709aef47d3b8c2477a9bf63e2a59e2dcceff7 | CoderQingli/MyLeetCode | /283. Move Zeroes.py | 306 | 3.5 | 4 | def moveZeroes(self, nums):
"""
:type nums: List[int]
:rtype: None Do not return anything, modify nums in-place instead.
"""
n = len(nums)
t = 1
i = 0
while t <= n:
if nums[i] == 0:
nums.append(nums.pop(i))
else:
i += 1
t += 1 |
fe462e3d26b866c500619db330b4e7c027189f85 | Grigorii60/geekbrains_DZ | /task_1.py | 730 | 4.15625 | 4 | name = input('Как твое имя? : ')
print(f'Привет {name}, а мое Григорий.')
age = int(input('А сколько тебе лет? : '))
my_age = 36
if age == my_age:
print('Мы ровестники!')
elif age > my_age:
print(f'{name} ты старше меня на {age - my_age} лет.')
else:
print(f'{name} ты младше меня на {my_age - a... |
0b68b3a9ec8de57671257df11cce33dc7d11da13 | gcvalderrama/python_foundations | /udemy/mine_sweeper_click.py | 2,204 | 3.609375 | 4 | import queue
def click_internal(field, num_rows, num_cols, given_i, given_j):
field[given_i][given_j] = -2
for i in range(given_i - 1, given_i + 2):
for j in range(given_j - 1, given_j + 2):
if 0 <= i < num_rows and 0 <= j < num_cols and field[i][j] == 0:
click_internal(f... |
a110f4bcca38f5d3e437f1fc7aca21b20c62ab7b | gcvalderrama/python_foundations | /dynamicprogramming/dynamic_programming.py | 744 | 3.984375 | 4 | from collections import defaultdict
def fibonacci_recursive(n):
if n <= 0:
return 0
if n == 1:
return 1
else:
return fibonacci_recursive(n-1) + fibonacci_recursive(n-2)
def dyna_fibonacci(n, state):
if n <= 0:
state[0] = 0
if n == 1:
state[n] = 1
if s... |
9297f1a0d8710008990cf37b47690773f3102d75 | gcvalderrama/python_foundations | /DailyCodingProblem/univaltrees.py | 763 | 3.609375 | 4 | # https://www.dailycodingproblem.com/blog/unival-trees/
import unittest
class Node:
def __init__(self):
self.left = None
self.right = None
self.value = None
def is_unival(root):
return unival_helper(root, root.value)
def unival_helper(root, value):
if root is None:
return... |
8881aa774131d27aef05870593658afd182d21e8 | gcvalderrama/python_foundations | /atest/CombinationSum.py | 513 | 3.65625 | 4 | import heapq
if __name__ == '__main__':
candidates =[2,3,6,7]
target = 7
res = []
resList = []
heapq.heappop()
def backtracking(start, rest):
if rest == 0:
temp = resList[:]
res.append(temp)
for i in range(start, len(candidates)):
if (candi... |
81cc75787fdd73aaa09436287c7c02cc6cec4012 | gcvalderrama/python_foundations | /udemy/last_common_ancestor.py | 1,395 | 3.75 | 4 | import unittest
from collections import deque
class Node:
def __init__(self, value):
self.left = None
self.right = None
self.value = value
def path_to_x(node: Node, x):
if not node:
return None
if node.value == x:
stack = deque()
stack.append(x)
re... |
30e43fa2101a7b39c98b50fffbd513139615296e | gcvalderrama/python_foundations | /udemy/nth_element.py | 1,663 | 3.890625 | 4 |
class Node:
def __init__(self, value, child=None):
self.value = value
self.child = child
def __str__(self):
return str(self.value)
def nth_from_last(head, n):
left = head
right = head
for i in range(n):
if right is None:
return None
right = righ... |
bfc1370319731fb0bd10bf2aa4749210d97801be | gcvalderrama/python_foundations | /left_rotate_matrix.py | 3,317 | 4.28125 | 4 | # Python program to rotate a matrix
def rotate_recursive(matrix):
if not len(matrix):
return matrix
rows = len(matrix)
if rows < 2:
return matrix
if len(matrix[0]) < 2:
return matrix
rotate_recursive(matrix)
rows = len(sample)
columns = len(sample[0])
#sample_... |
8d025a060a5eeb1ffe544c51e6fac20acad11e17 | gcvalderrama/python_foundations | /book/NewYearChaos.py | 1,760 | 3.671875 | 4 | import unittest
from collections import defaultdict, deque
import sys
def minimumBribes(q):
moves = 0
for pos, val in enumerate(q):
d = (val - 1) - pos
if d > 2:
return "Too chaotic"
start = max(0, val - 2)
end = pos + 1
for j in range(start, end):
... |
445b7001f0d91f771d18a23cad1a80f7c1075e8a | gcvalderrama/python_foundations | /book/substringanagram.py | 528 | 3.953125 | 4 | # We have two words. We need to determine if the second word contains
# a substring with an anagram of the first word
import unittest
def anagram_substring(target, base):
if not base or not target:
return False
state = dict()
for c in base:
state[c] = 1
for c in target:
i... |
db9cbff3f932f0e76a7595e2508e2413cd7d5d7c | gcvalderrama/python_foundations | /atest/BestTimetoBuyandSellStock.py | 545 | 3.5 | 4 | if __name__ == '__main__':
nums = [7, 1, 5, 3, 6, 4]
max_profit = 0
for i in range(len(nums) - 1):
for j in range(1, len(nums)):
if nums[i] < nums[j]:
profit = nums[j] - nums[i]
if max_profit < profit:
max_profit = profit
print(max... |
6ff2b981135a212c37555433fd617b8d9ca429f6 | gcvalderrama/python_foundations | /cracking/arraysStrings.py | 1,039 | 4.09375 | 4 | import unittest
def is_unique(target):
temp = ""
for c in target:
if c in temp:
return False
else:
temp += c
return True
def check_permutation(str_a, str_b):
longest = None
shortest = None
if len(str_a) >= len(str_b):
longest = str_a
... |
529bf7d2d2c40413f3cae61b307652d0760e779e | gcvalderrama/python_foundations | /DailyCodingProblem/MoveZeros.py | 1,348 | 4.03125 | 4 | # Given an array nums, write a function to move all 0's to the end of it while maintaining the relative order
# of the non-zero elements.#
# Example:
# Input: [0,1,0,3,12]
# Output: [1,3,12,0,0]
# You must do this in-place without making a copy of the array.
# Minimize the total number of operations.
import unittest
... |
7daab64b964cc36b579c1352f227421c4faabe1f | gcvalderrama/python_foundations | /udemy/setnumberssum16.py | 737 | 3.78125 | 4 | import unittest
def count_sets(arr, target):
state = dict()
return recursive(arr, target, len(arr)-1, state)
def recursive(arr, total, i, state):
key = '{}-{}'.format(total, i)
if key in state:
return state[key]
if total == 0:
result = 1
elif total < 0:
result = 0
... |
d982dbcd9d34ecfd77824b309e688f9e077093d5 | gcvalderrama/python_foundations | /DailyCodingProblem/phi_montecarlo.py | 1,292 | 4.28125 | 4 | import unittest
# The area of a circle is defined as πr ^ 2.
# Estimate π to 3 decimal places using a Monte Carlo method.
# Hint: The basic equation of a circle is x2 + y2 = r2.
# we will use a basic case with r = 1 , means area = π ^ 2 and x2 + y2 <=1
# pi = The ratio of a circle's circumference ... |
bea44d1998cb0d4d88e61b513364cca9f525f8bb | wing-py/matplotlib | /lorenz.py | 733 | 3.5 | 4 | import numpy as np
from matplotlib import pyplot as plt
x=np.linspace(0,15,150)
y1=np.linspace(0,10,100)
y2=np.linspace(10,0,50)
y=np.append(y1,y2)
f=(2*x+y)/(3**0.5)
h=(2*y+x)/(3**0.5)
#plt.subplot(30,30,1)
#plt.plot(x,y)
#plt.subplot(30,30,2)
plt.plot(f,h)
plt.show()
'''
图形横坐标为一维空间,纵坐标为时间,反斜... |
edcc3362e3e1932cae7d4bec660bc7b71e19aae5 | GFSCompSci/cs2 | /9-sorting/euclid.py | 254 | 3.8125 | 4 | val1 = input("Enter first number: ")
val2 = input("Enter second number: ")
if (val2 > val1): val1, val2 = val2, val1
print "a = %i b = %i" %(val1, val2)
print "Divide and conquer!"
a = val1
b = val2
while (b !=0): a, b = b, a%b
print "GCD is %i" %a
|
74ddb102f698ad2cc6ada0db7b51d991091bf4de | GFSCompSci/cs2 | /4-oop/employee/employee3.py | 1,295 | 3.9375 | 4 | #!/usr/bin/python
class Employee:
'Common base class for all employees'
empCount = 0
manCount = 0
clerkCount = 0
def __init__(self, name, salary, title):
self.name = name
self.salary = salary
self.title = title
Employee.empCount += 1
if self.title == "manage... |
062a7ceaec7acbef86dd1f36154627f5cfa9f10d | aldenkyle/DAT8_Homework | /Working/14_Yelp_hw_KSA.py | 6,345 | 3.5625 | 4 | # -*- coding: utf-8 -*-
"""
Spyder Editor
This is a temporary script file.
"""
import pandas as pd
import matplotlib.pyplot as plt
plt.style.use('fivethirtyeight')
plt.rcParams['figure.figsize'] = (6, 4)
plt.rcParams['font.size'] = 9
# 1. Read yelp.csv into a DataFrame.
#Read yelp.csv into a DataFrame.
yelp = pd.... |
a449dc6d6cacc3a96c795f73972c14bf16408086 | jros14/personal-work | /Game of Life/GameOfLife.py | 4,744 | 3.703125 | 4 | import numpy
import random
import pygame
class Grid:
def __init__(self):
self.grid = []
self.next_grid = []
self.display = Display()
self.create_random_grid()
self.display.main_display_loop(self)
def create_random_grid(self, grid_dimension=None):
if grid_dimens... |
d53a5033fd448c4c98e1817b0c6795103e77beaf | biyam/This_is_Coding_Test | /정렬/part2/위에서아래로.py | 439 | 3.828125 | 4 | n = int(input())
array = []
for i in range(n):
num = int(input())
array.append(num)
def quick_sort(array):
if len(array) <= 1:
return array
pivot = array[0]
tail = array[1:]
# pivot의 왼쪽과 오른쪽
left = [x for x in tail if x < pivot]
right = [x for x in tail if x > pivot... |
2815ab701aae131cf81a11a77c1b69e49776cf56 | ermolalex/tdd_money | /currency.py | 924 | 3.953125 | 4 | # -*- coding: utf-8 -*-
class Money():
def __init__(self, amount=0, currency="RUR"):
self._amount = amount
self._currency = currency
def __eq__(self, money):
return self._amount == money._amount and self._currency == money._currency
def __ne__(self, money):
... |
864e69f180897532924395a94a8bc09c27bba161 | dsc-sookmyung/2021-MAFIA-algorithm-study | /02-Stack_Queue/고성연/프린터.py | 592 | 3.640625 | 4 | from collections import deque
def solution(priorities, location):
answer = 0
index_queue = deque(range(len(priorities)))
priorities_queue = deque(priorities)
while True:
max_priorities = max(priorities_queue)
priorities_head = priorities_queue.popleft()
index_head = index_queue... |
d2c4315cdc60837c1212eb380c4ca80058699191 | dsc-sookmyung/2021-MAFIA-algorithm-study | /04-Sort/권은지/K번째수.py | 296 | 3.578125 | 4 | def solution(array, commands):
answer = []
for i in range(len(commands)):
start = commands[i][0]
end = commands[i][1]
cut = array[start-1:end]
cut.sort()
place = commands[i][2]
num = cut[place-1]
answer.append(num)
return answer |
d8bc18bc0cbba334d9f38a6883f6309ed4a09425 | dsc-sookmyung/2021-MAFIA-algorithm-study | /06-DFS_BFS/유지연/타겟 넘버.py | 1,510 | 3.59375 | 4 | # 데이터가 그래프 형태로 이루어져 있고, 그래프 끝에 노드까지 가서 그 값을 더하거나 뺀 값 얻어야함 -> DFS
# Solution1 : DFS - 반복
def iterative_solution(numbers, target):
result_list = [0]
for i in range(len(numbers)):
temp_list = []
for j in range(len(result_list)):
temp_list.append(result_list[j] - numbers[i])
... |
e0ea907ac144d00560feb2520d48be1402e5a598 | douzujun/LeetCode | /py56_1003_numOfBurgers.py | 1,062 | 3.6875 | 4 | # -*- coding: utf-8 -*-
class Solution:
def numOfBurgers(self, tomatoSlices: int, cheeseSlices: int):
low, high = 0, tomatoSlices // 4
# 巨无霸汉堡:4 片番茄和 1 片奶酪
# 小皇堡:2 片番茄和 1 片奶酪
print(low, high)
while low <= high:
mid = (low + high... |
d6a2c672d165b23065a4b69fe334e9e7c03aa44d | douzujun/LeetCode | /py03_1078_findOcurrences.py | 649 | 3.703125 | 4 | # -*- coding: utf-8 -*-
class Solution:
def findOcurrences(self, text: str, first: str, second: str): #-> List[str]:
words = text.split(' ')
res = []
wlen = len(words)
for i in range(0, wlen - 2):
if words[i] == first and words[i + 1] == second:
... |
a4c125d1d4d713de23543bcee55e06f457a8c6b6 | douzujun/LeetCode | /py5_longestPalindrome.py | 655 | 3.6875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Thu Mar 26 18:03:04 2020
@author: douzi
"""
class Solution:
def longestPalindrome(self, s: str) -> str:
length = len(s)
result = ""
for i in range(length):
sum1 = ""
sum2 = ""
for str1 in s[i:]:
... |
95b07563e8c1d081abbed9706a1e648d44c9b549 | douzujun/LeetCode | /py18_922_sortArrayByParity.py | 533 | 3.609375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Thu Apr 16 01:34:53 2020
@author: douzi
"""
class Solution:
def sortArrayByParityII(self, A):
Alen = len(A)
res = [0] * Alen
even, odd = 0, 1
for e in A:
if e % 2 == 0:
res[even] = e
e... |
e0b5213c06c03a2be402116a01d1771a70ed7b73 | douzujun/LeetCode | /py08_575_distributeCandies.py | 569 | 3.65625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Apr 14 19:47:00 2020
@author: douzi
"""
class Solution:
def distributeCandies(self, candies) -> int:
clen = len(candies)
ave = clen // 2
cset = set()
for e in candies:
cset.add(e)
if len(cse... |
23150de0cc769f44723ece360aa4582474ee70f6 | douzujun/LeetCode | /py78_20_isValid.py | 997 | 3.828125 | 4 | # -*- coding: utf-8 -*-
class Solution:
def isValid(self, s: str) -> bool:
ans = []
for e in s:
if e in ['(', '[', '{']:
ans.append(e)
elif e == ')':
if ans:
t = ans.pop()
if t != '(':
... |
3f554bfd6d303677bf51bd44a09b32ac329b2a74 | douzujun/LeetCode | /142.环形链表-ii.py | 773 | 3.578125 | 4 | #
# @lc app=leetcode.cn id=142 lang=python3
#
# [142] 环形链表 II
#
# @lc code=start
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def detectCycle(self, head: ListNode) -> ListNode:
if head =... |
99d73368dd42d92f4115eab4424bdf8fb19267e5 | douzujun/LeetCode | /py75_367_isPerfect.py | 334 | 3.609375 | 4 | # -*- coding: utf-8 -*-
class Solution:
def isPerfectSquare(self, num: int) -> bool:
for i in range(1, num+1):
if i**2 == num:
return True
elif i**2 > num:
return False
s = Solution()
print(s.isPerfectSquare(16))
print(s.isPer... |
1d2942e3b8b6adf93071e31050039c310c4b9bfd | douzujun/LeetCode | /py72_1184_distanceBetweenBusStops.py | 891 | 3.859375 | 4 | # -*- coding: utf-8 -*-
class Solution:
def distanceBetweenBusStops(self, distance, start: int, destination: int) -> int:
forward = 0
backward = 0
dlen = len(distance)
for i in range(0, dlen):
forward += distance[(start + i) % dlen]
if (st... |
574ae2836da910748210d3f2babd54565619545a | scroberts/Library | /MyUtil.py | 1,883 | 3.53125 | 4 | #!/usr/bin/env python3
# external modules
import re
# my modules
def strip_xml(mystring):
return(re.sub('<[^>]*>', '', mystring))
def get_all_none_indiv(question):
# Expects one of the following:
# 'A' = 'All'
# 'N' = 'None'
# 'I' = 'Individual Y/N'
# Returns 'All', 'None' or 'Indivi... |
24cf6864b5eb14d762735a27d79f96227438392f | ramalldf/data_science | /deep_learning/datacamp_cnn/image_classifier.py | 1,545 | 4.28125 | 4 | # Image classifier with Keras
from keras.models import Sequential
from keras.layers import Dense
# Shape of our training data is (50, 28, 28, 1)
# which is 50 images (at 28x28) with only one channel/color, black/white
print(train_data.shape)
model = Sequential()
# First layer is connected to all pixels in original im... |
9aeeabeb134a76adde0d1a417de6b43a3321b55f | cshintov/Learning-C | /c_projects/python_vm/testcases/recursive/reclcm_hcf.py | 332 | 3.671875 | 4 | def hcf(a, b):
if a < b:
return hcf(a, b - a)
elif a > b:
return hcf(a - b, b)
else:
return a
def lcm(a, b):
return a * b / hcf(a, b)
print 16
print 40
print hcf(16, 40)
print lcm(16, 40)
print 16
print 24
print hcf(16, 24)
print lcm(16, 24)
print 5
print 3
print hcf(5, 3)
print... |
f26d127894dbe54916f773def305f2431e459db3 | kingcunha23/python-learning | /n_impares.py | 193 | 3.890625 | 4 | # -*- coding: utf-8 -*-
n = int(input('Digite um número inteiro: '))
i = 0
y = (n // 10 ** i ) % 10
j = 0
while y != 0:
y = (n // 10 ** i ) % 10
i = i + 1
j = j + y
print(j) |
943abd4fe4bbfe18d2fe476be17cccf4545a2581 | kingcunha23/python-learning | /fizz.py | 150 | 4.15625 | 4 | # -*- coding: utf-8 -*-
x = int(input('Digite um inteiro: '))
if x % 3 == 0 and x % 5 == 0 :
print('FizzBuzz')
else:
print(x) |
6f1fdf99f378119e89bae468fce57382da125f4b | hmjyn/fishmen | /fishman.py | 955 | 3.6875 | 4 | from random import randint
class fishman:
def __init__(self):
self.name="fishman"
self.live=100
self.livestatus=1
self.fishnb=0
self.fishchick=0
self.fishislandnb=0
def fishhamter(self):
#rrrdd=1
if randint(1,5) == 3:
self.fishnb+=1
... |
a4e0edd928e4f212d58cfc29277cf69417702622 | DiegoPacheco2/gitpython | /ex003video10.py | 152 | 3.953125 | 4 | val1=int(input('Digite um valor: '))
val2=int(input('Digite outro valor: '))
print('A soma entre {} e {} é igual a {}!'.format(val1, val2, val1+val2))
|
89aa4c5a42c98986270f76c8c5b983e7ccdf207c | DiegoPacheco2/gitpython | /ex010video18.py | 176 | 3.703125 | 4 | dinheiro=float(input('Quanto dinheiro você tem na carteira? R$'))
print('Com R${} você pode comprar US${:.2f} e €${:.2f}'.format(dinheiro,dinheiro / 3.76,dinheiro / 4.27))
|
60b60160f8677cd49552fedcf862238f9128f326 | Prash74/ProjectNY | /LeetCode/1.Arrays/Python/reshapematrix.py | 1,391 | 4.65625 | 5 | """
You're given a matrix represented by a two-dimensional array, and two positive
integers r and c representing the row number and column number of the wanted
reshaped matrix, respectively.
The reshaped matrix need to be filled with all the elements of the original
matrix in the same row-traversing order as they were... |
b08bda08ed82d71f6421e3f56407be10107b87d6 | SarthakJShetty/Donkey | /donkey/mixers.py | 2,473 | 3.5 | 4 | '''
mixers.py
Classes to wrap motor controllers into a functional drive unit.
'''
import time
import sys
from donkey import actuators
class BaseMixer():
def update_angle(self, angle):
pass
def update_throttle(self, throttle):
pass
def update(self, throttle=0, angle=0):
'''Conv... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.