blob_id stringlengths 40 40 | repo_name stringlengths 5 127 | path stringlengths 2 523 | length_bytes int64 22 545k | score float64 3.5 5.34 | int_score int64 4 5 | text stringlengths 22 545k |
|---|---|---|---|---|---|---|
672355d21d9e3e95ee91296ddb63a657649e68a9 | irshadmuaz/GPSProject | /PyVMU/vmu_velocity.py | 2,697 | 3.828125 | 4 | #!/usr/bin/env python3
''' vmu_velocity.py
Purpose: Basic code for reading velocity from VMU931
IMPORTANT: Must be run using Python 3 (python3)
Authors of Main Code: Christopher Brant, David Lynge, and Heath Gerrald.
Last Modified: 7/20/2018
'''
## Import Libraries ##
import numpy as np
import math
import serial
impor... |
a11fec12a30b334436e3d7ebf5ca44bdae44bb45 | fsciety/crack_hash.god | /crack.py | 888 | 3.84375 | 4 | import hashlib
print("""
_
| |_ ___ ___ ___ ___ ___ _ _ _
| | .'| _| . | -_| _| | | | |
|_|_|__,|_| | _|___|_| _____ _____|_____|
|_| |_____|_____| """)
hash_ = input("Enter ... |
8f87f2eaa1ae4b02e43ce70bbc56ab204085f947 | AshishHoodaIITD/competitive_coding | /Codeforces/cdf647/a.py | 450 | 3.546875 | 4 | import math
import sys
t = int(input())
def two_ana(num):
count = 0
while(num%2==0):
num = num >> 1
count+=1
return num, count
for i in range(t):
inp = input().split(" ")
a, b = int(inp[0]), int(inp[1])
a_rem, a_pow = two_ana(a)
b_rem, b_pow = two_ana(b)
if a_rem!=b_rem:... |
a121bc8590aeb852674381ac7cd71e2ea8a29d20 | qnewmk/testes_python | /pytrab2.1/main_confirmacao.py | 518 | 3.890625 | 4 | from datetime import datetime
hoje = datetime.today()
data_entrega= datetime.now()
dia = int(input('digite o dia de entrega'))
mes = int(input('digite o mes de entrega'))
ano = int(input('digite o ano de entrega'))
data_entrega.day = dia
data_entrega.month = mes
data_entrega.year - ano
data_entrega = datetime.... |
75512cdef0345981ba8556c649c58cc65cfdac65 | datastructurezerotoall/DataStructure | /sm/dijkstra/dijkstra.py | 2,834 | 3.859375 | 4 | class ShortestPath:
def __init__(self, s, distance, p):
self.source = s
self.distance = distance
self.p = p
class Graph:
# 모든 가중치보다 충분히 큰 수 int overflow 때문에 다익스트라에서는 import math.inf를 사용하면 안됨.
BIG_NUMBER = 2000
@staticmethod
def print_shortest_path(sp, dest):
if ... |
ef7cb3ec31fe915692c68d0d61da36bdb8004576 | jfonseca4/FonsecaCSC201-program03 | /program03-Part1.py | 1,129 | 4.375 | 4 | #Jordan Fonseca
#2.1
DNA = input(str("Enter the DNA sequence")) #asks user to input a string
DNA2 = []
for i in DNA:
if i == "A": #if DNA is A, replaces it with a T
DNA2.append("T")
if i == 'G': #if DNA is G, replaces it with a C
DNA2.append("C")
if i == "C": ... |
60c4871fa6f5cef63fd0924f4d0b6e4bcdbf7097 | Nazzekas/python | /внеземные_гости.py | 313 | 3.953125 | 4 | #597
r1 = int(input("Please enter the radius of field: "))
r2 = int(input("Please enter the radius of plate: "))
r3 = int(input("Please enter the radius of plate: "))
Sc1 = r1*r1*3.14
Sc2 = r2*r2*3.14
Sc3 = r3*r3*3.14
if Sc2+Sc3 < Sc1:
print("YES")
elif Sc2+Sc3 == Sc1:
print("YES")
else:
print("NO")
|
4585efdae5dffff316e6f37ff8ca74c176dadc0f | Nazzekas/python | /эния.py | 455 | 4.125 | 4 | #195
n = int(input("Введите количество панелей необходимых обработать: "))
a = int(input("Введите длину панели: "))
b = int(input("Введите ширину панели: "))
S = 2*a*b*n #общая площадь всех панелей, учитывая обработку с обеих сторон
print("На обработку необходимо " + str(S) + " сульфида!")
|
89fa4a392b54575f74edb2d6f98c6088fc980233 | Nazzekas/python | /арифметика.py | 314 | 3.953125 | 4 | #8
a = int(input("Введите первый множитель десятиричной системы: "))
b = int(input("Введите второе число десятиричной системы: "))
c = int(input("Введите ваш ответ: "))
if c == a*b:
print("YES")
else:
print("NO")
|
5630c72723d7cd7838aba1405fba32b63ffbc0e2 | Nazzekas/python | /время_года.py | 297 | 3.9375 | 4 | #892
n = int(input("Please enter the number of season: "))
if n == 1 or n == 2 or n == 12:
print("WINTER")
elif n == 3 or n == 4 or n == 5:
print("SPRING")
elif n == 6 or n == 7 or n == 8:
print("SUMMER")
elif n == 9 or n == 10 or n == 11:
print("AUTUMN")
else:
print("ERROR")
|
ebf9261d012e8f68667c26c5b883ea1e4370016f | Ravindra-14/python_assignment | /loop4.py | 99 | 3.515625 | 4 | s='Pentagon Space'
l=len(s)
s1=''
i=0
while(i<l):
s1=s[i]+s1
i=i+1
print(s1)
|
de2e031c415782fb45c1b2136f60d9bc6567932e | Winesss/2019T3-COMP9021 | /quiz_5/quiz_5.py | 2,217 | 3.875 | 4 | # COMP9021 19T3 - Rachid Hamadi
# Quiz 5 *** Due Thursday Week 7
#
# Implements a function that, based on the encoding of
# a single strictly positive integer that in base 2,
# reads as b_1 ... b_n, as b_1b_1 ... b_nb_n, encodes
# a sequence of strictly positive integers N_1 ... N_k
# with k >= 1 as N_1* 0 ... 0... |
dc673eec5f52fc5dc1b6743f31f1310a228af660 | afcarl/python_datastructure | /search_and_sort/functional_search.py | 1,388 | 3.96875 | 4 | def binary_search(elem,array,first,last):
midpoint = (first + last) // 2
print first,"first"
print last,"last"
if first > last:
return -1
if elem == array[midpoint]:
return midpoint
else:
if elem < array[midpoint]:
return binary_search(elem,array,first,midpoin... |
3f54deb3ba1c43715648857aee129551c20e1145 | afcarl/python_datastructure | /word_ladder_graph.py | 1,524 | 3.6875 | 4 | from graph import Graph
from queue import Queue
def build_graph(word_file):
d = {}
g = Graph()
with open(word_file,"r") as f:
words = f.read().split("\n")
for word in words:
for i in xrange(len(word)):
bucket = word[:i]+"_"+word[i+1:]
if bucket in d.keys():
... |
be26fb14a3e5d6ccbf064d04dff76ffd2dd2b487 | afcarl/python_datastructure | /search_and_sort/search.py | 3,460 | 3.84375 | 4 | def is_sorted(l):
return all(l[i] <= l[i+1] for i in xrange(len(l)-1))
def recursive_binary_search(elem,array,first,last):
midpoint = (first + last) // 2
if first > last:
return -1
if elem == array[midpoint]:
return midpoint
else:
if elem <= array[midpoint]:
retu... |
1f89a8b91e09390d3f0e956d446bee5b05b57a7a | shuangliu12/Euler-Problems | /Euler 009.py | 388 | 3.921875 | 4 | '''A Pythagorean triplet is a set of three natural numbers, a < b < c, for which,
a2 + b2 = c2
For example, 32 + 42 = 9 + 16 = 25 = 52.
There exists exactly one Pythagorean triplet for which a + b + c = 1000.
Find the product abc.'''
for a in range(0,1000):
b = (1000*500-1000*a)/(1000-a)
c = 1000-(a+b)
if a*... |
b994ebb535ee6b9b5e74b8f1c535863164f1000e | shuangliu12/Euler-Problems | /Euler 012.py | 896 | 3.734375 | 4 | '''The sequence of triangle numbers is generated by adding the natural numbers. So the 7th triangle number would be 1 + 2 + 3 + 4 + 5 + 6 + 7 = 28. The first ten terms would be:
1, 3, 6, 10, 15, 21, 28, 36, 45, 55, ...
Let us list the factors of the first seven triangle numbers:
1: 1
3: 1,3
6: 1,2,3,6
10: 1,2,5,1... |
516af0265bc40d205e5f3125f11ca025a94cde20 | bahleg/ft_compress | /ft_compress/interfaces/storage.py | 765 | 4.0625 | 4 | class Storage:
"""
A basic class for storages.
Storages are dict-like objects that
support access via two-level getters
(i.e. storage['a']['b']).
The top-level dict-like object for storage
is called `bucket`.
"""
def get_bucket(self, bucket):
raise NotImplementedError()... |
f819500378f06e6a0c20f3b3f198bb63974559ea | vikas0694/python_programs | /cube_finder.py | 153 | 3.96875 | 4 | def cube_finder(n):
cube = {}
for i in range(1,n+1):
cube[i] = i**3
return cube
a = int(input("enter a num :"))
print(cube_finder(a)) |
595fbef3f544cc65802d5188fd48a630bb18d08f | vikas0694/python_programs | /tic_toc_toe.py | 2,699 | 3.734375 | 4 | #Two Player TicTacToe
theBoard = {'top-L': ' ', 'top-M': ' ', 'top-R': ' ', 'mid-L': ' ', 'mid-M': ' ', 'mid-R': ' ', 'low-L': ' ', 'low-M': ' ', 'low-R': ' '}
def printBoard(board):
print(board['top-L'] + '|' + board['top-M'] + '|' + board['top-R'])
print('-+-+-')
print(board['mid-L'] + '|' + board['mid-... |
a4bfcb558c40c6ad4423533b6ccc7b94411b8d60 | drmrsmoke/GeekBrains | /HW6/HW2.py | 353 | 3.75 | 4 | class Road:
__length = 0
__width = 0
def __init__(self, length, width):
self.__length = length
self.__width = width
def calc(self):
print(f"Количество асфальта необходимого для дороги {self.__length * self.__width * 25 * 5 / 1000} тонн")
r = Road(5000, 20)
r.calc()
|
7d31361d93a30f1b6090c49dca852020abc8cde5 | drmrsmoke/GeekBrains | /HW6/HW1.py | 2,001 | 3.765625 | 4 | from turtle import *
import time
t = Turtle()
t.screen.setup(800, 800)
t.hideturtle()
def blink():
t.begin_fill()
t.circle(60, 360)
t.fillcolor("white")
t.end_fill()
def colors(color, x, y):
t.penup()
t.speed(0)
t.goto(x, y)
t.begin_fill()
t.circle(60, 360)
t.fillcolor(color... |
b2899f93b3394105c6751b758cd30b10a9e7ceac | drmrsmoke/GeekBrains | /hw1_2.py | 617 | 3.640625 | 4 | my_file = open("hw.txt", "r+", encoding="utf-8")
user_input = "s"
while user_input != "":
user_input = input("Введите текст")
my_file.write(user_input + "\n")
my_file.seek(0)
i = 0
while True:
read = my_file.readline()
if read == "\n":
break
else:
count = len(read) - 1
print(... |
d75b50c4a5b1efdc28d8b408f817bd189b3d1c17 | drmrsmoke/GeekBrains | /hw4/hw1.py | 537 | 3.59375 | 4 | from sys import argv
def budget():
file, stavka, time, bonus = argv
try:
int(stavka)
float(time)
int(bonus)
except ValueError:
return print("Введите корректныке данные")
print("File name", file)
print("Ставка : ", stavka)
print("Часов отработано: ", time)
pri... |
661ec2e7a6e0ae3083213ac54338876b3050b41d | mcsalgado/toys | /rot13_meta/rot13_python_codegen.py | 507 | 3.65625 | 4 | print('''#!/usr/bin/env python3
def rot13(c):''')
for i in range(ord('A'), ord('Z')+1):
j = ((i - ord('A') + 13) % (ord('Z') - ord('A') + 1)) + ord('A')
print(f" if c == '{chr(i)}':")
print(f" return '{chr(j)}'")
for i in range(ord('a'), ord('z')+1):
j = ((i - ord('a') + 13) % (ord('z') - ... |
e156a3690017bf795001d18ebfc5b28fdda72c5f | Luke-Beausoleil/ICS3U-Assignment-6-Python-quadratic_formula | /quadratic_formula.py | 1,485 | 4.09375 | 4 | #!/usr/bin/env python3
# Created by: Luke Beausoleil
# Created on: May 2021
# This program evaluates the quadratic formula with user inputs
import math
def discriminant(a, b, c):
# this function calculates discriminant
discriminant_value = (b ** 2) - (4 * a * c)
return discriminant_value
def value1(a... |
71df12be2a0dcbf6d31c3c5aebfcb43739cde7d1 | RyuHyoKyung/python-oop | /encapsulation/person.py | 445 | 3.6875 | 4 |
class Person:
def __init__(self,name,year,adr):
self.name = name
self.year = year
self.adr = adr
def
@staticmethod
def main():
p = Person (str(input('이름을 입력하세요.'), (int(input('주민번호 앞자리를 입력하세요.'))),(str(input('주소를 입력하세요.')
print('이름:'name)
print('만 나이:... |
22e13d4fee0e49a08fa197fd75d3fca41343b534 | rjmarzec/Google-CSSI---Coursera | /Algorithmic Toolbox/week5_dynamic_programming1/3_edit_distance/edit_distance.py | 793 | 3.546875 | 4 | # Uses python3
def edit_distance(t, s):
matrix = [[0 for x in range(len(s) + 1)] for y in range(len(t) + 1)]
for i in range(0, len(s) + 1):
matrix[0][i] = i
for i in range(0, len(t) + 1):
matrix[i][0] = i
for j in range(1, len(t) + 1):
for i in range(1, len(s) + 1):
... |
440bd8ba94e1320d5d44451e1abe2dca051cb25d | rjmarzec/Google-CSSI---Coursera | /Algorithmic Toolbox/week2_algorithmic_warmup/4_least_common_multiple/lcm.py | 523 | 4.125 | 4 | # Uses python3
def lcm(a, b):
current_a_mult = a
current_b_mult = b
a_times_b = a*b
while a_times_b > current_a_mult and a_times_b > current_b_mult:
if current_a_mult == current_b_mult:
return current_a_mult
elif current_a_mult < current_b_mult:
current_a_mult ... |
bc5e6d75a1aecbc92e50c86c9d5f9163ad647818 | rjmarzec/Google-CSSI---Coursera | /Algorithmic Toolbox/week3_greedy_algorithms/1_money_change/change.py | 458 | 3.765625 | 4 | # Uses python3
def get_change(m):
remaining_change = m
coins = [0, 0, 0]
# 10's
coins[0] = int(remaining_change/10)
remaining_change -= coins[0] * 10
# 5's
coins[1] = int(remaining_change/5)
remaining_change -= coins[1] * 5
# 1's
coins[2] = remaining_change
# return the ... |
34ad61069bad3e04387df5cd2e7eb1baf2685c13 | jsa4000/Training-Courses | /AI-edX-Training/Assignments/Assignment2/files/PlayerAI_3.v0.4.py | 6,158 | 3.703125 | 4 | import sys
import math
from random import randint
from BaseAI_3 import BaseAI
def get_heuristic_score(grid):
""" This function gets the current score for the current
grid. The score is independt of the minmax node, since the
algorithm itself need to choose between the worst or better
score given by thi... |
abeebeaaf3f1d5580cdad64cd4604acdea8193a5 | gihyunkim/baekjoon_study | /turret.py | 1,740 | 3.5625 | 4 | # 터렛
'''
조규현과 백승환은 터렛에 근무하는 직원이다.
하지만 워낙 존재감이 없어서 인구수는 차지하지 않는다.
이석원은 조규현과 백승환에게 상대편 마린(류재명)의 위치를
계산하라는 명령을 내렸다.
조규현과 백승환은 각각 자신의 터렛 위치에서
현재 적까지의 거리를 계산했다.
조규현의 좌표 (x1, y1)와 백승환의 좌표 (x2, y2)가 주어지고,
조규현이 계산한 류재명과의 거리 r1과 백승환이 계산한
류재명과의 거리 r2가 주어졌을 때, 류재명이 있을 수 있는
좌표의 수를 출력하는 프로그램을 작성하시오.
'''
import math
def dista... |
3f19b7455b02ebd21a1dd07bfa02d1a1e0df23f5 | gihyunkim/baekjoon_study | /hanoi.py | 948 | 3.578125 | 4 | # 하노이 탑
'''
세 개의 장대가 있고 첫 번째 장대에는
반경이 서로 다른 n개의 원판이 쌓여 있다.
각 원판은 반경이 큰 순서대로 쌓여있다.
이제 수도승들이 다음 규칙에 따라 첫 번째 장대에서
세 번째 장대로 옮기려 한다.
한 번에 한 개의 원판만을 다른 탑으로 옮길 수 있다.
쌓아 놓은 원판은 항상 위의 것이 아래의 것보다 작아야 한다.
이 작업을 수행하는데 필요한 이동 순서를 출력하는 프로그램을
작성하라. 단, 이동 횟수는 최소가 되어야 한다.
'''
n = int(input()) # 원판의 개수
list = []
cnt = 0
def move(n,... |
52eccd60f77a5b5b107330dd7d0e0894eefde720 | PrzemyslawSwiderski/PLCOpythonTool | /examples/nan_filling.py | 2,007 | 3.5 | 4 | import pandas as pd
csv_dataFrame = pd.read_csv('sample_data.csv')
print('Dane wejściowe:')
print(csv_dataFrame)
# Col1 Col2 Col3 Col4 Col5
# 0 1.0 4.7 2.0 1.5 1.0
# 1 NaN -9.0 0.0 5.2 NaN
# 2 -2.4 -1.0 1.4 8.7 NaN
# 3 -7.1 -3.0 NaN 2.4 NaN
# 4 4.0 8.0 1.4 1.2 6.6
# ... |
b61cca99b6eae96978b48499c43e91d88d7dc9bb | rodrigo-fernandes/python-exercise | /exercise8.py | 326 | 3.625 | 4 | # {} = Dicionário
# [] = Lista
cores = {'verde': 'green', 'vermelho':'red', 'preto':'black', 'branco':'whilte'}
# pega o que o usuário digitou e já transforma a letra em minúscula
cor = input('Escolha a cor que deseja traduzir: ').lower()
traducao = cores.get(cor, 'Esta cor não consta no dicionário')
print(traducao) |
26647d86971fbf4cfeaf8cf8753b5cecf618aba4 | Souzooka/HackerRank-Solutions | /Python/Basic Data Types/Find the Second Largest Number/Python 2/secondLargestNumber.py | 234 | 3.5 | 4 | if __name__ == '__main__':
n = int(raw_input())
arr = map(int, raw_input().split())
secondMax = None
firstMax = max(arr)
for x in arr:
if (secondMax < x < firstMax):
secondMax = x
print secondMax |
90fc9415691d96658f21a29380d86031672a96c9 | thepowerfuldeez/Tasks | /Contests/GoTo HSE Contest/G.py | 867 | 3.625 | 4 | class Solution:
# @param {string} s
# @return {string}
def longestPalindrome(self, s):
l = len(s)
if l <= 2:
if (s[0] != s[l - 1]):
return ''
else:
return s
result = ''
for i in range(0, l):
palindrome = sel... |
105afaafa1d8ba4baa7466826ebea8489759bc53 | adwinugroho/speech-to-text | /main.py | 692 | 3.625 | 4 | import speech_recognition as sr
from time import ctime
r = sr.Recognizer()
def record_audio():
with sr.Microphone() as source:
audio = r.listen(source)
voice_data = ''
try:
voice_data = r.recognize_google(audio)
except sr.UnknownValueError:
print("Sorry, I di... |
23625cceeacc7e9b9d1287a87f95eb6a24ff0a4a | mlm-distrib/py-practice-app | /00 - basics/05-operators.py | 2,466 | 4.46875 | 4 | # Operators
# Arithmetic operators
x = 10
y = 5
print('#### Arithmetic ####')
print('addition :', x+y)
print('subtraction:', x-y)
print('multiply :', x*y)
print('division :', x/y)
print('modulus :', x % y)
print('exponential:', x**y)
print('floor division:', x//y)
print('')
# Assignment operators
x = 15
print... |
b5eb87686608cd0fc8e4215db1479bfc2e9a379b | mlm-distrib/py-practice-app | /00 - basics/08-sets.py | 515 | 4.25 | 4 |
# Set is a collection which is unordered and unindexed. No duplicate members.
myset = {"apple", "banana", "mango"}
print(myset)
for x in myset:
print(x)
print('')
print('Is banana in myset?', "banana" in myset)
myset.add('orange')
print(myset)
myset.update(["pineapple", "orange", "grapes"])
print(myset)
print('l... |
716169701d33254dfb90cb3c020809aecfb0812e | andrew-g-nagy/Data-Frame | /data_frame.py | 12,844 | 4.21875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Thu Mar 25 2021
@author: Andrew G. Nagy
"""
#Create a data frame and perform data frame operations. Import from a csv, or past a list of lists, with each list representing a data row.
#Column names can also be specified, or will be created by default if none are passed. Sup... |
32b542e8f1c972324329621d5beab3fa67a23004 | cemrifki/answers-to-google-interview-qns | /Arrays-and-Strings/string_unique_chars.py | 266 | 3.75 | 4 | #!/bin/env/py
# -*- coding: utf-8 -*-
def has_all_unique(s):
if len(s) == 1 or not s:
return True
s = s.lower()
res = ''.join(sorted(s))
for i in range(len(res) - 1):
if res[i] == res[i + 1]:
return False
return True
|
9943e41da554d08368cc8e7d326dbd623643d192 | jakuberan/AoC-2020 | /src/day12_supp.py | 335 | 4.09375 | 4 | from math import sin, cos, radians
def rotate(px, py, degrees):
"""
Function for coordinate rotation
"""
# Transform degrees to radians
angle = radians(degrees)
# Perform rotation and return coordinates
qx = cos(angle) * px - sin(angle) * py
qy = sin(angle) * px + cos(angle) * py
... |
09f3d95bf68d3a5110375a3e1d56eab66c6708a4 | jakuberan/AoC-2020 | /src/day16_supp.py | 273 | 3.71875 | 4 | def is_valid(nums, options):
"""
Validates the options
"""
for n in nums:
check = 0
for opt in options:
if n in opt:
check = 1
break
if check == 0:
return False
return True
|
9f56b8aa263826b72b94be024ad45ee94eb6fe60 | kannanmavila/coding-interview-questions | /interview_cake/29_validate_braces.py | 920 | 3.796875 | 4 | class Stack(object):
def __init__(self):
self.container = []
def put(self, value):
self.container.append(value)
def pop(self):
return self.container.pop()
def peek(self):
n = len(self.container)
return self.container[n-1]
def is_empty(self):
return len(self.container) == 0
def v... |
66d034b7f5b97497fef317d377bfda59a5708f32 | kannanmavila/coding-interview-questions | /stack_sorting.py | 1,034 | 3.890625 | 4 | class EmptyStack(Exception):
pass
class Node:
def __init__(self, value, next=None):
self.value = value
self.next = next
class Stack:
def __init__(self, head=None):
self.head = Node(head) if head is not None else None
def push(self, *values):
for v in values:
new_head = Node(v, self.h... |
4447083372d3e94b2fa58c8756a18dca7918b94d | kannanmavila/coding-interview-questions | /threaded_queue.py | 1,176 | 3.828125 | 4 | from time import time, ctime, sleep
from threading import Thread, Lock
from Queue import Queue
class MyQueue(object):
def __init__(self):
self.store = []
def put(self, value):
self.store.append(value)
def get(self):
return self.store.pop(0)
def peek(self):
return self.store[0]
def emp... |
4cc99b2d1de0595bc2d0b6f335e7f8d1b80b906d | kannanmavila/coding-interview-questions | /quick_sort.py | 714 | 4.28125 | 4 | def r_quick_sort(array, start, end):
# Utility for swapping two elements of the array
def swap(pos1, pos2):
array[pos1], array[pos2] = array[pos2], array[pos1]
if start >= end:
return
pivot = array[start]
left = start+1
right = end
# Divide
while left - right < 1:
if array[left] > pivot:
... |
e50668342fff7d8f2433d7e122fc9dfe48821df4 | kannanmavila/coding-interview-questions | /queue_with_two_stacks.py | 1,189 | 3.765625 | 4 | class EmptyStack(Exception):
pass
class EmptyQueue(EmptyStack):
pass
class Node:
def __init__(self, value, next=None):
self.value = value
self.next = next
class Stack:
def __init__(self, head=None):
self.head = Node(head) if head is not None else None
def pop(self):
if self.head i... |
e177b1f2ba2fb3baaef810214a9325e1e9207342 | kannanmavila/coding-interview-questions | /reverse_string.py | 235 | 4.21875 | 4 | def reverse(string):
string = list(string)
length = len(string)
for i in xrange((length - 1) / 2 + 1):
string[i], string[length-i-1] = string[length-i-1],string[i]
return "".join(string)
print reverse("Madam, I'm Adam")
|
bafaf415a3601e67343fc78cf269eacc4199513b | kannanmavila/coding-interview-questions | /interview_cake/1_apple_stock.py | 481 | 3.671875 | 4 | class InvalidPrices(ValueError):
pass
def max_profit(prices):
"""Returns the maximum profit that can be made from yesterday’s stock."""
if len(prices) < 2:
raise InvalidPrices(prices)
min_price = prices[0]
max_profit = None
for i in xrange(1, len(prices)):
max_prof... |
94ae54321112bd9b8bf2b9898ab84025926b4e2e | kannanmavila/coding-interview-questions | /tree_largest_independent_subset.py | 1,099 | 3.859375 | 4 | class Node(object):
def __init__(self, value, left=None, right=None):
self.value = value
self.left = left
self.right = right
self.lis = None
def lis(node):
"""Return the size of the Largest Independent Subset (LIS)
of the tree rooted at `node`.
"""
# No node; empty subset
if node is None:... |
070d388659df628d00116c127f2b212c0e6033cf | kannanmavila/coding-interview-questions | /tree_from_inorder_postorder.py | 1,470 | 4.125 | 4 | class Node(object):
def __init__(self, value, left=None, right=None):
self.value = value
self.left = left
self.right = right
def binary_tree(inorder, postorder):
"""Return the root node to the BST represented by the
inorder and postorder traversals.
"""
# Utility for recursively creating BST f... |
668f846583dadfcd5270c9e674b3271ee7381235 | kannanmavila/coding-interview-questions | /interview_cake/16_cake_knapsack.py | 1,136 | 4.25 | 4 | def max_duffel_bag_value(cakes, capacity):
"""Return the maximum value of cakes that can be
fit into a bag. There are infinitely many number
of each type of cake.
Caveats:
1. Capacity can be zero (naturally handled)
2. Weights can be zero (checked at the start)
3. A zero-weight cake can give infinite... |
3198a18c45c445f3d2b36031ab0f651f782cd030 | kannanmavila/coding-interview-questions | /circle_inside_square.py | 214 | 3.671875 | 4 | def draw_circle(r):
for i in xrange(0, 2*r+2):
line =["X" if (i-r) ** 2 + (j-r) ** 2 <= r ** 2 else " " for j in xrange(0, 2*r+2)]
print " ".join(line)
if __name__ == "__main__":
draw_circle(20)
|
4a46b2a0a5c8455746758351e85cbf52eaee7e72 | engineeredcurlz/Sprint-Challenge--Intro-Python | /src/oop/oop2.py | 1,535 | 4.15625 | 4 | # To the GroundVehicle class, add method drive() that returns "vroooom".
#
# Also change it so the num_wheels defaults to 4 if not specified when the
# object is constructed.
class GroundVehicle():
def __init__(self, num_wheels = 4): # only works for immutable (cant change) variables otherwise use []
self.... |
240e3e604e155ed2371da5ce0a3c050a3c655429 | SamirBacha/hangman | /utils/game.py | 2,025 | 3.65625 | 4 | import re
import random
class Hangman:
def __init__(self):
self.possible_words = ['becode','learning','mathematics','sessions']
self.word_to_find = list(str(random.choice(self.possible_words)))
self.lives = 5
self.correctly_guessed_letters = ["_"]*len(self.word_to_find... |
5ac2c0302065ce8f55e3728d186a109eab658e96 | matusino221/AdventofCode_2020 | /day5.py | 3,999 | 3.921875 | 4 | import math
import re
import sys
def read_file(filename):
try:
with open(filename) as f:
content = f.readlines()
# I converted the file data to integers because I know
# that the input data is made up of numbers greater than 0
content = [info.strip() for info in conten... |
58b5d31b995dbc670f0c7f7cf52b865d9e1e014d | splicerex/Porfolio-Term-2 | /Hang Man/Hang Man.py | 2,345 | 3.8125 | 4 | #Kyle Baldwin
#Hang man game
#11/26/18
#import
import random
import time
#constants
HANGMAN=(
'''
------
| |
| |
|
|
|
|
|
|
-------
''',
'''
------
| |
| |
| 0
|
|
|
|
|
-------
''',
'''
------
| |
| |
| 0
| +
|
|
|
|
-------
''',
'''
------
| |
| ... |
ddb6175d13470ef34a1c316631d2961f87ebda23 | ThatGuyCalledGuy/NEA2020 | /MatrixTests.py | 1,545 | 3.8125 | 4 | #Matrix Operations test # Only for 2x2 & 3x3
#Multiplication - Strassen algorithm
#Determinant
#Inverse
def _round(A):
mat_result = [
[round(A[0][0]*1000)/1000, round(A[0][1]*1000)/1000],
[round(A[1][0]*1000)/1000, round(A[1][1]*1000)/1000]
]
return mat_result
mat_1... |
e367acfaa09e7b1879d1cf68a1d652e54afed957 | ashjazz/python_learning | /ThreadProduct.py | 2,212 | 3.53125 | 4 | # coding=UTF-8
import threading
import os, time
left_num = 500
con = threading.Condition()
class Producer(threading.Thread):
"""生产者"""
def __init__(self, target = None, name = None, args = (), kwargs = None):
threading.Thread.__init__(self, target = target, name = name, args = args, kwargs = kwargs)
... |
f29173d2bf9875c2748b4cb686b2d63522dda286 | AdiKaran/Project-Euler | /Problem9.py | 720 | 4.15625 | 4 |
# A Pythagorean triplet is a set of three natural numbers, a < b < c, for which,
# a**2 + b**2 = c**2
# For example, 3**2 + 4**2 = 9 + 16 = 25 = 5**2.
# There exists exactly one Pythagorean triplet for which a + b + c = 1000.
# Find the product abc.
sqr_roots = {}
ans = [] * 3
for x in range(500) :... |
c4b0a22510f9147bfc137e645b6eca36f63b975f | earlpanda/cs50x | /pset6/cash.py | 470 | 3.796875 | 4 | import math
from cs50 import get_float
while True:
n = get_float("Change: ")
if n > 0:
break
# to change the dollars into cents:
i = round(n * 100)
coin_amount = 0
# when over a quarter
while i >= 25:
i -= 25
coin_amount += 1
# when over a dime
while i >= 10:
i -= 10
coin_amount += 1
# ... |
6bd3571863e00199d3651b06d53beb19821fc6d6 | chenkangkang002/mySelenium | /get_name_email.py | 569 | 3.640625 | 4 | '''
自动生成用户名和email
'''
import connect_mysql as mysql
#调用数据库查询,得到用户名list
#用户名存在,更换用户名
def getUsername():
usernames,_ = mysql.getUsers()
username = max(usernames)
num = username[8:]
num = int(num)
num = num+1
username = username[0:8]+str(num)
return username
#email
def getEmail():
_, email... |
b8873226de4e7ffe1e3500c0ceb9aa35a3454897 | zhangquanliang/python | /学习/day1/强密码判断.py | 784 | 4 | 4 | # -*- coding: utf-8 -*-
def demo(L):
k = len(L)
if k >= 10:
if L.isalnum() and not L.isdigit() and not L.isalpha()and not L.isspace():
return print("是强密码")
else:
L = L.replace("!","")
L = L.replace("_","")
L = L.replace("#","")
L = L.... |
eef0e4e23e2c44502f1aec0a2d043b472dcc87c9 | medashiva/pybasics | /prime.py | 220 | 4.03125 | 4 | x=input("enter the number")
c=0
if x>1:
for i in range(2,x):
if x%i==0:
c+=1
else:
pass
if c==0:
print(x,"is prime number")
else:
print(x,"is not a prime number")
else:
print(x,"is not a prime")
|
5c95de33ab399b6fa20b8efcc9fccea7b13a2b72 | JaviCeRodriguez/Tkinter | /widgets/entries.py | 316 | 3.5 | 4 | from tkinter import *
root = Tk()
root.title("Soy un título")
root.geometry("400x500")
Label(root, text="Usuario: ").grid(row=0, column=0)
Label(root, text="Contraseña: ").grid(row=1, column=0)
entry1 = Entry(root)
entry2 = Entry(root)
entry1.grid(row=0, column=1)
entry2.grid(row=1, column=1)
root.mainloop() |
d5bfff305fcb9f3a10425f3e9f2fa8b08b18297c | JaviCeRodriguez/Tkinter | /geometry/grid.py | 262 | 3.671875 | 4 | from tkinter import *
root = Tk()
colours = ('red','green','blue','white','orange')
for c, x in enumerate(colours):
Label(text=x, relief=RIDGE, width=20).grid(row=c, column=0)
Entry(bg=x, relief=SUNKEN, width=10).grid(row=c, column=1)
root.mainloop() |
b747001979b68a34e19c88042f1631b7c1091503 | djmatt/adventofcode | /2017/day03/aoc2017d03p2.py | 1,497 | 4.0625 | 4 | from itertools import islice
def spiralgen():
'''
Infinite spiral generator
'''
loc = (0, 0)
yield loc
ring = 1
while True:
# move right for the next ring
loc = (loc[0]+1, loc[1])
yield loc
# move up right side
for _ in range((ring * 2)-1):
... |
ba78c609a6e351c3cf5cee3e1b9e24985f75ff7e | djmatt/adventofcode | /2018/day01/aoc2018d1p1.py | 600 | 3.5625 | 4 | def aoc2018d1p1(nums):
return sum(nums)
if __name__ == "__main__":
TESTCASES = [([+1, -2, +3, +1], 3),
([+1, +1, +1], 3),
([+1, +1, -2], 0),
([-1, -2, -3], -6)]
for case, expected in TESTCASES:
result = aoc2018d1p1(case)
print(f"Input: {c... |
949b6ae08c5586a6e2bc8869fd8774cf89da8096 | liorsze/Games-Menu | /MainSnake.py | 3,690 | 3.765625 | 4 | import os
from curses import textpad
from time import sleep
from Snake import *
from Food import *
def game(stdscr):
# set the cursor state
curses.curs_set(0)
# escape sequences generated by some keys will be interpreted by curses
stdscr.keypad(True)
stdscr.nodelay(0)
# makes getch() to block... |
9de76b0e53052bc74aaf18b35fad9dba521af772 | liorsze/Games-Menu | /Main2048.py | 1,314 | 3.90625 | 4 | import pygame
from config import *
from Game2048 import Game
from time import sleep
from MainHangman import blit_text
# Import and initialize the pygame library
pygame.init()
myfont = pygame.font.SysFont("Century Schoolbook", 24)
def startGame(screen):
# set title and icon
pygame.display.set_caption("2048")... |
63117486f2c73073c018850bd1defcdc3d6a6063 | chea-young/Financial-Statistics-Practice-Using-Python | /3주차/파이썬 기초 - 12. 인구구조를 다양한 형태로 시각화.py | 6,589 | 3.5 | 4 | #%% 참고 교재: 모두의 데이터 분석 with 파이썬 p.109 ~ p.123
#%% 지난 시간 인구 그래프를 좀더 꾸며 봅시다
import csv
f=open('age.csv')
data=csv.reader(f)
result=[]
name=input('인구 구조가 알고 싶은 지역의 이름(읍면동 단위)을 입력해주세요: ')
for row in data:
if name in row[0]:
for i in row[3:]:
result.append(int(i))
import matplotlib.pyplot ... |
65a1b5ebb40c08fe9d0b9be8632eac0c93da9649 | chea-young/Financial-Statistics-Practice-Using-Python | /9주차/31.py | 3,077 | 3.5625 | 4 | """"""""""""""""""""""""""" 파이썬 기초 """"""""""""""""""""""""""""""""""""""" #%% 참고 교재: 데이터 분석을 위한 판다스 입문 p.204 ~ p.210
#%% 1. 간단한 함수 만들기
# 사용자 정의 함수는 다음과 같은 기본 구조
# def my_function():
# 코드... # return x
def my_sq(x):
return x**2
print(my_sq(3))
def my_exp(x,n):
return x**n
print(my_exp(2,4))
#%% 2. apply메서드 사용 - 기초
... |
79351fd4aacae1e9354482322c7276bb6aa2a6b8 | chea-young/Financial-Statistics-Practice-Using-Python | /12주차/과제43-2.py | 387 | 3.578125 | 4 | #i) 사용자 정의 함수를 사용하여 계산하여 보세요.
import numpy as np
FV=1000
r=0.05
n=5
m = 2
def get_pv(Fv, r, n, m):
return FV/(1+r/m*n*m)
print(get_pv(FV, n, r, m))
#ii) numpy의 pv함수를 사용하여 계산하여 보세요.
import numpy as np
FV=1000
r=0.05
n=5
m = 2
def get_pv_np(Fv, r, n, m):
return np.pv(r/m,n*m,0,Fv)
print(get_pv_np(FV, n, r, m)) |
88e93cc8305f2e65c6b3a267fa371d6d674c4804 | tavilad/Ser2NetPython | /ClientUI.py | 480 | 3.8125 | 4 | from tkinter import *
from Client import *
#make an empty window
root = Tk()
#make the main window frame
frame = Frame(root)
frame.pack()
#pressing this button makes the connection of the client to the TCP/IP Server
connectBtn = Button(frame, text="Connect")
connectBtn.bind("<Button-1>", connect)
connectBtn.pack()
... |
432beb80d4f3a550145a37ff3ea1e650e24a15bc | dcaragea/TweetAnalysis | /src/addr_nlp/sync.py | 3,851 | 3.90625 | 4 | import threading
# Shamelessly stolen from
# <https://blog.majid.info/a-reader-writer-lock-for-python/>
class RWLock:
"""
A simple reader-writer lock Several readers can hold the lock
simultaneously, XOR one writer. Write locks have priority over reads to
prevent write starvation.
"""
def __init__(self):
... |
6a9a963535e63739d7982c17792b03f949a8fe53 | snir-levi/RedTeamTools | /External/DNS/subDomainCrawler.py | 2,087 | 3.90625 | 4 | ##Sub Domain Crawler by Snir Levi##
'''
Description: The script checks for any subdomains present in HTML file of given domain. For each subdomain the script crawls recursivly to find more subdomains.
Results output file: finaldomains.txt
Usage: python subDomainCrawler.py <domain>
Example: python subDomainCrawler.py ... |
d721800cd3a78144e58afb0f756e52889fe80f03 | a100kpm/daily_training | /problem 0270.py | 1,688 | 3.9375 | 4 | '''
Good morning! Here's your coding interview problem for today.
This problem was asked by Twitter.
A network consists of nodes labeled 0 to N. You are given a list of edges (a, b, t),
describing the time t it takes for a message to be sent from node a to node b.
Whenever a node receives a message, it immediately ... |
4238ba309d02c6f851defcfe9e602fcddae51215 | a100kpm/daily_training | /problem 0288.py | 1,197 | 3.828125 | 4 | '''
Good morning! Here's your coding interview problem for today.
This problem was asked by Salesforce.
The number 6174 is known as Kaprekar's contant, after the mathematician who
discovered an associated property: for all four-digit numbers with at least
two distinct digits, repeatedly applying a simple procedure... |
57170eafa6f1197f2032a809dbb0981f49b507ff | a100kpm/daily_training | /problem 0029.py | 983 | 4.1875 | 4 | '''
Good morning! Here's your coding interview problem for today.
This problem was asked by Amazon.
Run-length encoding is a fast and simple method of encoding strings.
The basic idea is to represent repeated successive characters as a single count and character.
For example, the string "AAAABBBCCDAA" would be encod... |
4846e0e5552d43668622d20802ecbad7b5f39741 | a100kpm/daily_training | /problem 0289.py | 1,637 | 3.734375 | 4 | '''
Good morning! Here's your coding interview problem for today.
This problem was asked by Google.
The game of Nim is played as follows. Starting with three heaps, each containing
a variable number of items, two players take turns removing one or more items from a single pile.
The player who eventually is forced ... |
08e8623d5f36faa4aace7ef318175fd4ff45bd81 | a100kpm/daily_training | /problem 0264.py | 1,788 | 3.890625 | 4 | '''
Good morning! Here's your coding interview problem for today.
This problem was asked by LinkedIn.
Given a set of characters C and an integer k, a De Bruijn sequence is a cyclic sequence
in which every possible k-length string of characters in C occurs exactly once.
For example, suppose C = {0, 1} and k = 3. The... |
003bc82579dfd89b4d1d001ee16d40d6a726da67 | a100kpm/daily_training | /problem 0207.py | 1,301 | 4.15625 | 4 | '''
Good morning! Here's your coding interview problem for today.
This problem was asked by Dropbox.
Given an undirected graph G, check whether it is bipartite.
Recall that a graph is bipartite if its vertices can be divided into two independent sets,
U and V, such that no edge connects vertices of the same set.
''... |
9307a36bb407f64ff7d37caea2ea5e191d18e5ff | a100kpm/daily_training | /problem 0130.py | 1,148 | 3.96875 | 4 | '''
Good morning! Here's your coding interview problem for today.
This problem was asked by Facebook.
Given an array of numbers representing the stock prices of a company in chronological
order and an integer k, return the maximum profit you can make from k buys and sells.
You must buy the stock before you can sell... |
0dc1cf2fcc01b34b4cf943a17ba24475df7e768a | a100kpm/daily_training | /problem 0034.py | 958 | 4.21875 | 4 | '''
Good morning! Here's your coding interview problem for today.
This problem was asked by Quora.
Given a string, find the palindrome that can be made by inserting the fewest
number of characters as possible anywhere in the word. If there is more than
one palindrome of minimum length that can be made, return the l... |
c42bddb990d70b0eb997fee79c9f9bd7ed7bd90e | a100kpm/daily_training | /problem 0081.py | 1,941 | 4.0625 | 4 | '''
Good morning! Here's your coding interview problem for today.
This problem was asked by Yelp.
Given a mapping of digits to letters (as in a phone number), and a digit string,
return all possible letters the number could represent. You can assume each valid number in the mapping is a single digit.
For example if... |
211d0303800ef36e5c658498aa5c8ed99b3a91e8 | a100kpm/daily_training | /problem 0202.py | 671 | 4.28125 | 4 | '''
Good morning! Here's your coding interview problem for today.
This problem was asked by Palantir.
Write a program that checks whether an integer is a palindrome.
For example, 121 is a palindrome, as well as 888. 678 is not a palindrome.
Do not convert the integer into a string.
'''
nbr1=121
nbr2=123454321
nbr3... |
4e38d4f0ec5a3b759c6344b0f3b6dbc270128645 | a100kpm/daily_training | /problem 0112.py | 1,099 | 3.890625 | 4 | '''
Good morning! Here's your coding interview problem for today.
This problem was asked by Twitter.
Given a binary tree, find the lowest common ancestor (LCA) of two given nodes in the tree.
Assume that each node in the tree also has a pointer to its parent.
'''
# 1
# / \
# 2 3
# / \
# 4 5
class Node... |
2d3369c67839346d1e81cc29eda6163e1bf27080 | a100kpm/daily_training | /problem 0063.py | 1,824 | 4.15625 | 4 | '''
Good morning! Here's your coding interview problem for today.
This problem was asked by Microsoft.
Given a 2D matrix of characters and a target word, write a function that returns
whether the word can be found in the matrix by going left-to-right, or up-to-down.
For example, given the following matrix:
[['F', ... |
d28009028b7d0577e768badefb0ed2cae3c3d513 | a100kpm/daily_training | /problem 0272.py | 700 | 4.0625 | 4 | '''
Good morning! Here's your coding interview problem for today.
This problem was asked by Spotify.
Write a function, throw_dice(N, faces, total), that determines how many ways it
is possible to throw N dice with some number of faces each to get a specific total.
For example, throw_dice(3, 6, 7) should equal 15.
'... |
fd52fa074a5eb39e814ed95a4d780ddda1c738f9 | a100kpm/daily_training | /problem 0165.py | 886 | 4 | 4 | '''
Good morning! Here's your coding interview problem for today.
This problem was asked by Google.
Given an array of integers, return a new array where each element in the new array
is the number of smaller elements to the right of that element in the original input array.
For example, given the array [3, 4, 9, 6,... |
539ae6e0ecf887e6d1d29a89a317d920bcd8899a | a100kpm/daily_training | /problem 0120.py | 672 | 4.09375 | 4 | '''
Good morning! Here's your coding interview problem for today.
This problem was asked by Microsoft.
Implement the singleton pattern with a twist.
First, instead of storing one instance, store two instances.
And in every even call of getInstance(), return the first instance and
in every odd call of getInstance()... |
86003bda5b8be72027c2c701712c981310379311 | a100kpm/daily_training | /problem 0108.py | 725 | 3.875 | 4 | '''
Good morning! Here's your coding interview problem for today.
This problem was asked by Google.
Given two strings A and B, return whether or not A can be shifted some number of times to get B.
For example, if A is abcde and B is cdeab, return true. If A is abc and B is acb, return false.
'''
def can_shift(A,B)... |
f34bef76194d77d6a5e5f5891c334c33c8d7ca10 | a100kpm/daily_training | /problem 0065.py | 1,407 | 4.15625 | 4 | '''
Good morning! Here's your coding interview problem for today.
This problem was asked by Amazon.
Given a N by M matrix of numbers, print out the matrix in a clockwise spiral.
For example, given the following matrix:
[[1, 2, 3, 4, 5],
[6, 7, 8, 9, 10],
[11, 12, 13, 14, 15],
[16, 17, 18, 19, 20]]
You s... |
359566a140a511e766aadf44c97edbdfdc06ad7c | a100kpm/daily_training | /problem 0151.py | 1,167 | 3.828125 | 4 | '''
Good morning! Here's your coding interview problem for today.
Given a 2-D matrix representing an image, a location of a pixel in the screen and a color C,
replace the color of the given pixel and all adjacent same colored pixels with C.
For example, given the following matrix, and location pixel of (2, 2), and '... |
ec51b4aed220b2c5bb4ac5e78fa9977f304a9427 | a100kpm/daily_training | /problem 0127.py | 1,881 | 3.875 | 4 | '''
Good morning! Here's your coding interview problem for today.
This problem was asked by Microsoft.
Let's represent an integer in a linked list format by having each node represent a digit in the number.
The nodes make up the number in reversed order.
For example, the following linked list:
1 -> 2 -> 3 -> 4 -> ... |
4be59ab979de011b3761d0744013c0ff1ff5d9d2 | a100kpm/daily_training | /problem 0241.py | 949 | 4.3125 | 4 | '''
Good morning! Here's your coding interview problem for today.
This problem was asked by Palantir.
In academia, the h-index is a metric used to calculate the impact of a researcher's papers. It is calculated as follows:
A researcher has index h if at least h of her N papers have h citations each.
If there are mu... |
391e822344d24481fca5cdb13ba9c20d9c823fd8 | a100kpm/daily_training | /problem 0203.py | 1,191 | 3.875 | 4 | '''
Good morning! Here's your coding interview problem for today.
This problem was asked by Uber.
Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand.
Find the minimum element in O(log N) time. You may assume the array does not contain duplicates.
For example, given [5, 7, ... |
73833189b95a57b5d148ef377f3fd2e353805b9d | a100kpm/daily_training | /problem 0072.py | 3,829 | 4.03125 | 4 | '''
Good morning! Here's your coding interview problem for today.
This problem was asked by Google.
In a directed graph, each node is assigned an uppercase letter. We define a path's
value as the number of most frequently-occurring letter along that path. For example,
if a path in the graph goes through "ABACA", th... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.