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 |
|---|---|---|---|---|---|---|
bb42400cf0c516d55cf8f02d213f5c842de131ee | Chris-Perkins/CodeForces-Solutions | /Programs/520A - Pangram/520a_pangram.py | 162 | 3.671875 | 4 | # Description of the problem can be found at http://codeforces.com/problemset/problem/520/A
_ = input()
print("YES" if len(set(input().lower())) == 26 else "NO") |
907fcc5d0ad6e561189faabbd0bb83f1c2e458d6 | Chris-Perkins/CodeForces-Solutions | /Programs/141A - Amusing Joke/141a_amusing_joke.py | 255 | 3.75 | 4 | # Description of the problem can be found at http://codeforces.com/problemset/problem/141/A
names = input() + input()
scrambled = input()
names = "".join(sorted(names))
scrambled = "".join(sorted(scrambled))
print("YES" if names == scrambled else "NO") |
9991f363c5239365113f120e85b1fb4734648b32 | Chris-Perkins/CodeForces-Solutions | /Programs/144A - Arrival of the General/144a_arrival_of_the_general.py | 1,489 | 3.75 | 4 | # Description of the problem can be found at http://codeforces.com/problemset/problem/144/A
_ = input()
soldiers = list(map(int, input().split()))
# holds height of our soldiers
min_height = None
min_index = None
# holds max height of our soldiers
max_height = None
max_index = None
for index in range(len(soldiers))... |
dde432eabeaa14ac346b9124e1938fa3f5ca6dc7 | kayiyo/python3_framework_automation | /testsuite1/mobile_random.py | 1,115 | 3.625 | 4 | import string
import random
for i in range(8):
minlength = 6
maxlength = 16
mobile_begin_seed = ['134','135','136','137','138','139','150','151','152','157','158','159','182','183','187','188','130','131','132','155','156','175','185','186','133','153','177','180','181','189']
mobile_seed = string.di... |
7bcf3b3899accd1d7e98656aac4dcf87b6520140 | ThiagoIvens/web2 | /intro-python-web2-thiago/web2-thiago/desafio-105.py | 874 | 3.609375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon Feb 17 19:18:48 2020
@author: Informatica
"""
'''
DESAFIO!!!
1) Crie uma lista com os 1000 primeiros numeros pares. Não use loop!
OBS.: Use sua linguagem de programacao favorita. Nao use funcoes/metodos prontos.
'''
lista = []
x = 0
def recursive(x):
if x % 2 ... |
8aa404fdf02c406f8cd30dbd1cd3230236a19c46 | RohitGodara77/Guess_the_number_Game | /game2.py | 432 | 3.875 | 4 | import random
n = random.randint(1,100)
g = int(input("you thing you are smart, guess the number?? "))
t = 0
f = True
while(f):
if g == n:
f = False
print(f'Good! correct guess,you made {t} guesses to make the correct one')
elif g > n:
t+=1
print('guess a smaller number : ')
... |
4edb779ab0cd96905cbfcc5a40b4b3124111b487 | flkt-crnpio/algorithms-exercises | /recursive-bubble-sort.py | 267 | 3.875 | 4 | def recursiveBubbleSort(arr, n):
for x in range(0, n-1):
if arr[x] > arr[x+1]:
arr[x], arr[x+1] = arr[x+1], arr[x]
recursiveBubbleSort(arr, n-1)
return arr;
arr = [2,5,8,1,4,9,3]
n = len(arr)
print(recursiveBubbleSort(arr,n))
|
1db98ff0f81b3f6d08cc59fe5da1a388cf0cba88 | flkt-crnpio/algorithms-exercises | /string-subsecuence.py | 861 | 3.890625 | 4 | # HackerRank in a String!
# Given an array of strings 's' print 'YES' if the string contains the letters to write 'hackerrank', otherwise, print 'NO'
# AND need to be in the same order
def hackerrankInString(s):
a = ['h','a','c','k','e','r','r','a','n','k']
for x in range(0,len(s)):
if((len(a) > 0) an... |
65ca0fdb4cd2d230112ce0e001c9404800132ace | flkt-crnpio/algorithms-exercises | /first.py | 198 | 3.75 | 4 | # Solve Me First
# Complete the function solveMeFirst to compute the sum of two integers.
def solveMeFirst(a,b):
return a+b
num1 = int(1)
num2 = int(5)
res = solveMeFirst(num1,num2)
print(res)
|
ef94ccd7d72d63fa091637ce2a48762b8546dced | peterkisfaludi/Leetcode | /240_search-a-2d-matrix-ii.py | 696 | 3.53125 | 4 | class Solution:
def src(self, mx, t):
n=len(matrix)
if n==0: return False
m=len(matrix[0])
if m==0: return False
mv = matrix[n//2][m//2]
if mv==t: return True
if mv<t:
A=mx[0:n//2][0:m//2]
return self.src(A) or self.src(B) or s... |
1777fa701636ce166e884ae77d52f4e5a7b50411 | peterkisfaludi/Leetcode | /332_reconstruct-itinerary.py | 1,146 | 3.53125 | 4 | class Node:
def __init__(self, name):
self.name=name
self.neigh=[]
self.vis=[]
def __lt__(self, other):
return self.name < other.name
class Solution:
def visit(self,node,togo,ret):
if togo==0: return True
for i in range(len(node.neigh)):
i... |
eb78301b1d1c528ae4efb4bfe6ae644f0872e688 | peterkisfaludi/Leetcode | /380_insert-delete-getrandom-o1.py | 1,858 | 3.75 | 4 | import random
class RandomizedSet:
def hashfun(self,val: int):
return 7*pow(val,5) % self.cap
def rehash(self):
self.cap*=2
dbl_arr=[]
self.nm=[0]*self.cap
for i in range(0,self.cap):
dbl_arr.append([])
for lst in self.ar... |
38f05b25d91c6db3be1e4c38370eea5edbe6eb36 | peterkisfaludi/Leetcode | /237_delete-node-in-a-linked-list.py | 336 | 3.546875 | 4 | class Solution:
def deleteNode(self, node):
arr=[]
head=node
n=head
while n is not None:
arr.append(n.val)
n=n.next
#print(arr)
n=head
prv=None
for x in arr[1:]:
n.val=x
prv=n
n=n.next
... |
ac937e2d1d61950723beddbbd3ed6f4f2d5466db | rohegde7/competitive_programming_codes | /Interview-TestPress-Reverse_of_number.py | 839 | 4.1875 | 4 | '''
Given a number N, print reverse of number N.
Note: Do not print leading zeros in output.
For example N = 100 Reverse of N will be 1 not 001.
Input: Input contains a single integer N. Output: Print reverse of integer N.
Constraints: 1<=N<=10000
'''
number = input() #storing the numeber in string fo... |
0058f5c2fa1980ccb39709af8d0129f23b80904e | rohegde7/competitive_programming_codes | /Interview-deepcompute-swap_list_values.py | 273 | 4 | 4 | list_numbers = list(map(int, input("Enter the numbers for the list\n").split()))
list_size = len(list_numbers)
#swaping:
list_numbers[0], list_numbers[list_size-1] = list_numbers[list_size-1], list_numbers[0]
print("The new list after swapping is:\n", list_numbers) |
c20d52bbef994a25219fb353b9723c0b63ac6414 | rohegde7/competitive_programming_codes | /cchef-JAN_LC'18-Maximum_Score.py | 1,472 | 3.96875 | 4 | # Author: https://www.github.com/rohegde7 (Rohit Hegde - hegde.rohit7@gmail.com)
# https://www.codechef.com/JAN18/problems/MAXSC
# Problem Code: MAXSC
# status: sub-task1: 1/2 passed, sub-task2: 1/4 passed
"""method:
Sort all the rows of the matrix in decending order.
Assign the max, i.e. 1st el... |
a9645eb7b1a4d68828434bf688ca462df8b5561c | herllyc/Leetcode_Daily | /二叉树中第k小的值/index.py | 454 | 3.59375 | 4 | # Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def kthSmallest1(self, root):
if not root:
return []
s = self.kthSmallest1(root.left)+[root.val]+self.kthSmallest1(root... |
347f7ff9df2d36f8a806625a6e814468e83e2d10 | herllyc/Leetcode_Daily | /两个数组的交集/index.py | 347 | 3.640625 | 4 | class Solution:
def intersect(self, nums1, nums2):
mod_list = nums1
fin_list = []
for i in nums2:
try:
mod_list.remove(i)
except ValueError:
continue
fin_list.append(i)
return fin_list
s = Solution()
print(s.inte... |
b4883b8d6bc3b3c76e8b7d2659a1f1ad265a1bf2 | herllyc/Leetcode_Daily | /鸡蛋掉落/index.py | 210 | 3.765625 | 4 | def index(K,N):
i = 1
while (deal(i,K)<N):
i+=1
return i
def deal(i,K):
if i==1 or K==1:
return i
else:
return (deal(i-1,K)+deal(i-1,K-1)+1)
print(index(2,3)) |
4dbff807381d236aa362c81383b97c127dcf89ff | AP-MI-2021/lab-3-AverageLinuxEnjoyer | /get_longest_all_not_prime.py | 1,286 | 3.734375 | 4 | from get_longest_subsequence import get_longest_subsequence
from is_prime import is_prime
def are_not_prime(lst: list[int]) -> bool:
"""Verifica daca o lista e formata doar din numere care nu sunt prime
Args:
lst (list[int]): Lista verificata
Returns:
bool: True daca lista e formata doar ... |
b5e6ad825bdb9ec6f8a3250c6e86c988a6736ce5 | AP-MI-2021/lab-3-AverageLinuxEnjoyer | /get_longest_all_palindromes.py | 1,824 | 3.75 | 4 | from get_longest_subsequence import get_longest_subsequence
def is_palindrome(x: int) -> bool:
"""Verifica daca un numar e palindrom
Args:
x (int): Numarul verificat
Returns:
bool: True daca e palindrom, False in caz contrar
"""
return str(x) == str(x)[::-1]
def test_is_palindrom... |
4e7d627e3678dd708272e1a74fe522c8fa8b168f | UN-FISICA/taller-2-2018-2-mstorresh | /Ejercicio1.py | 546 | 3.609375 | 4 | # -*- coding: utf-8 -*-
from turtle import *
T1=Turtle()
T2=Turtle()
T2.pensize(5)
T1.hideturtle()
T2.hideturtle()
D1=100 #dimension del cuadrado grande
d2=20 #dimension de las figuras en los bordes
d3=d2/2
def cuadro(x):
for i in range(4):
T2.fd(x)
T2.rt(-90)
def cuadrado(z):
for i in range... |
cae56f6c637c990f18e6390208e50a904cab78ce | monroy8888/universidad_python_udemy | /postgres_python/7_Herencia/herencia_simple.py | 1,393 | 3.78125 | 4 | class Mi_Lista:
def __init__(self, elementos):
self._elementos = list(elementos)
def agregar_elementos(self, elemento):
self._elementos.append(elemento)
def obtener_elemntos(self, indice):
return self._elementos[indice]
def ordenar_elemntros(self):
return... |
a256a06825f452c86b12983c70d28a8b7147fcca | monroy8888/universidad_python_udemy | /postgres_python/4_operador_unpacking/preguntas_set.py | 550 | 3.5 | 4 |
pelo_negro = {"sergio", "juan" , "pedro", "maria"}
pelo_rubio = {"laura", "lorenzo", "marco"}
ojos_cafes = {"juan","laura"}
ojos_verdes = {"sergio","maria"}
menos_30 = {'juan','pedro',"maria"}
#SubSet
#Si un set esta contenido en otro subset
print(f'Si menores de 30 es sub set de pelo negro :{menos_30.issubset(pelo_... |
0da362b8cbe1dcba83729e8b133dd6f9ee51794a | abdelrahmanhosny/bioinformatics | /rosalind_ba1c/main.py | 545 | 3.96875 | 4 | # Find the reverse complement of a DNA string
__author__ = 'Abdelrahman Hosny <abdelrahman.hosny@ieee.org>'
def reversecomplement(dna):
reverse = ''
for char in dna:
if char == 'A':
reverse += 'T'
elif char == 'T':
reverse += 'A'
elif char == 'G':
r... |
9eb3c5ccddb0bf412230650a349410bc4a37b3fb | Apolexian/Code-Olympics-2020 | /disgitsum_and_divis.py | 363 | 3.5 | 4 | # kinda works
import math
def smallestNumber(N):
if N % 9 == 0:
mod = 0
else:
mod = 1
min_dig = N // 9 + mod
i = max(N, (min_dig - 1) * 10)
while(True):
sum_dig_i = sum(int(digit) for digit in str(i))
if sum_dig_i == N:
return i
i += N... |
e8e5be803f188e44b30c0584b2544ef4e6d877e2 | Dong-Kim/python-practice | /day2/Simple_shopping_cart.py | 2,673 | 3.828125 | 4 | #!/usr/bin/env python
#-*- coding:utf-8 -*-
import os
userfile = 'user_info'
menu = [(1,'apple',5000),(2,'mac',7000),(3,'food',10)]
shop = []
money = 0
login_count = 0
if not os.path.isfile(userfile):
open(userfile,'w').close()
#定义个退出函数,不管在哪里退出时均调用。
def quit():
print('Shopping included %s , overage %s' %(sho... |
f11953278a7f3395e726f5421985d51358a75dff | xavialex/Deep-Learning-Templates | /Volume 1 - Supervised Deep Learning/Part 2 - Convolutional Neural Networks (CNN)/Section 8 - Building a CNN/cnn.py | 3,427 | 3.609375 | 4 | # Convolutional Neural Network
# Installing Theano
# pip install --upgrade --no-deps git+git://github.com/Theano/Theano.git
# Installing Tensorflow
# pip install tensorflow
# Installing Keras
# pip install --upgrade keras
# Part 1 - Building the CNN
# Importing the Keras libraries and packages
from keras.models im... |
8e8669c1fbe924a6d822a91bb101f1641c7a7f28 | KristaJaanus/Python | /hello.py | 607 | 3.890625 | 4 | number1 = int(input("Sisesta esimene number: "))
number2 = int(input("Sisesta teine number: "))
print ("Esimene number on " + str(number1)+ " ja teine number on " +str(number2)+ ". ", end="")
print ("Numbrite 1 ja 2 summa on :" + str(number1+number2))
print ("Numbrite 1 ja 2 korrutis on :" + str(number1 * number2) )
pr... |
b2b57871b921a662b2ffa2cd502a910345f6b92d | sd2017/dbaez_concurency | /src/countdown2.py | 385 | 3.5 | 4 | # countdown2.py
#
# An example of launching a function into a separate thread
import time
import threading
def countdown(count):
while count > 0:
print "Counting down", count
count -= 1
time.sleep(5)
return
# Sample execution
t1 = threading.Thread(target=countdown,args=(10,))
t1.start(... |
e61d0f61d373dfa2ee8540d2dde201bc8cceff38 | jphacks/NG_1702 | /Python/url_open.py | 1,149 | 3.953125 | 4 | """
Access to the page of the url and get its title or entire sentences
to generate tags, and another program generates the url's features from them.
"""
from urllib import urlopen
import BeautifulSoup
def __get_sample_url():
sample_url = "https://ja.wikipedia.org/wiki/クレープ"
return sample_url
def... |
9182da85b5210bea3c3ef024a110e9dd101a14cf | RandyWu/IAWD-w18-l2 | /NetworkOperatingSystems/Lab3/cst8254/lab3.py | 989 | 3.890625 | 4 | import os
def check_directory(directory_name):
directory_list = os.listdir()
if directory_name in directory_list:
return true
else:
return false
def create_hierachy(path):
os.chdir(os.getcwd() + "/" + path)
os.system("mkdir labs")
os.chdir(os.getcwd() + "/" + "labs")
os.sy... |
9d830836ef589fe2f12e96273e5d238ffbeea9b2 | justicesithole/functions | /recursion.py | 613 | 3.96875 | 4 | #Recursion
def binary_search(a_list, item, count):
print("\n", a_list, "plus count", count)
count += 1
if len(a_list) == 0:
return False
else:
midpoint = len(a_list)//2
if a_list[midpoint] == item:
return True
else:
if item < a_list[midpoint]:
... |
de81ad862090ad70173dd365cb55a89f8718c259 | PatrikBillgren/AdventOfCode2019 | /4/1/program.py | 476 | 3.5625 | 4 |
def checkDigit(number):
numberAsString = str(number)
lastDigit = int(numberAsString[0])
hasSeenTwo = False
for char in numberAsString[1:]:
currDigit = int(char)
if currDigit == lastDigit:
hasSeenTwo = True
elif currDigit < lastDigit:
return False
... |
af459ed06c21f4a73ea257d3713add9a3effd878 | andiwijayaid/BelajarPhyton | /dataSet.py | 570 | 3.6875 | 4 | print("Data set adalah himpunan yang sering kita kenal dalam matematika")
set = {1,2,3,4,5,6,7}
print(set)
print("")
print("Tambah", 5)
print(set)
set.add(5)
print("Data di atas tidak berubah karena set akan menganggap data 5 adalah sama")
set.add(10)
print(set)
print("")
print(100*'_')
ganjil = {1,3,5,7,9}
genap =... |
3536dd50e8da4bc3d5606a912515876dee9af173 | Bhawana3/codechef | /subarrays.py | 378 | 3.921875 | 4 | #find the count of increasing sub arrays
def increasing(array) :
List = []
if len(array) > 1 :
for i in array :
for j in array[1:] :
if i < j :
List.append([i,j])
else :
return 1
return len(List)
n = input()
i = 0
while (i < n) :
N = input() # size of array
elements = raw_input()
array = map(... |
9637e1b714e1e778e3ebd6897520fd1fd1185a24 | Bhawana3/codechef | /chef_and_fruit.py | 336 | 3.5 | 4 |
def difference(List) :
n = List[0]
m = List[1]
k = List[2]
while (k > 0):
if n > m :
m = m + 1
else :
n = n + 1
k = k - 1
return abs(n-m)
n = input()
i = 0
f = []
while (i < n) :
fruits = raw_input()
fruit_list = map(int,fruits.split())
f.append(fruit_list)
i += 1
for diff in f :
print differen... |
1935efa71ef8b3aaad632a0e6ebcbb99274e653c | Bhawana3/codechef | /life_universe.py | 98 | 3.8125 | 4 |
# input a two digit number
n = int(raw_input())
while n!=42:
print n
n = int(raw_input())
|
36ac3458da625fed183927995f0f9f39f1ded4ff | Bhawana3/codechef | /minimum_max.py | 474 | 3.578125 | 4 | T = int(raw_input())
for i in range(T):
N = int(raw_input())
x = map(int, raw_input().split())
# Because we can always find the minimum of all numbers and then
# group it left or right to eliminate the other elements
# and cost would always equal that minimum number
# Total number of oper... |
f14dd6a2de747dff12c735bb51a6d40227509ccc | Bhawana3/codechef | /first_last.py | 138 | 3.796875 | 4 | # add first and last digit of a number
n = input()
i = 0
while ( i < n ) :
r = raw_input()
print (int(r[0]) + int(r[-1]))
i = i + 1
|
32a8ba59a5a88c29075e5a62a70c6ce2e9e9215b | Pierina0410/t10_palacios.salazar | /salazar/app6.py | 631 | 3.75 | 4 | import libreria
def ingrese_laptop():
libreria.pedir_nombre("ingrese nombre de laptop:")
print("se ingreso nombre de laptop")
def ingrese_computadora():
libreria.pedir_nombre("ingrese nombre de computadora:")
print("se ingreso nombre de computadora")
opc=0
max=3
while(opc!=max):
print("###### MENU ... |
502c2640f0076b76b93e64519dbd74de7a0b838d | Pierina0410/t10_palacios.salazar | /palacios/app9.py | 561 | 3.90625 | 4 | import libreria
def agregar_mes():
input("Agregar mes: ")
print("Se ingreso mes")
def agregar_dia():
input("Agregar dia: ")
print("Se ingreso dia")
opc=0
max=3
while(opc!=max):
print("######### MENU ##########")
print("# 1. agregar mes #")
print("# 2. agregar dia #")
print... |
9c6220056f32224f5c32fefc511ff1bc70f7eb62 | Pierina0410/t10_palacios.salazar | /palacios/app7.py | 616 | 3.90625 | 4 | import libreria
def agregar_planetas():
input("Agregar planetas: ")
print("Se ingreso planetas")
def agregar_satelite():
input("Agregar satelites: ")
print("Se ingreso satelites")
opc=0
max=3
while(opc!=max):
print("######### MENU ##########")
print("# 1. agregar planetas #")
print("#... |
24d35fa3ae70fd5599798b8ef7ccac76b7e91802 | Pierina0410/t10_palacios.salazar | /palacios/app18.py | 1,577 | 3.734375 | 4 | import libreria
def pedir_silla1():
print("Se agrego silla de plastico")
def pedir_silla2():
print("Se agrego silla de madera")
def pedir_mesa1():
print("Se agrego mesa de mader")
def pedir_mesa2():
print("Se agrego mesa de fierro")
#fin_def
def agregar_silla():
opc=0
max=3
while(opc!=max)... |
098087e08d363b4e78606570b45dac1ffa09a910 | Pierina0410/t10_palacios.salazar | /palacios/app17.py | 1,599 | 3.75 | 4 | import libreria
def pedir_botella1():
print("Se agrego botella de plastico")
def pedir_botella2():
print("Se agrego botella de madera")
def pedir_caja1():
print("Se agrego caja de mader")
def pedir_caja2():
print("Se agrego caja de fierro")
#fin_def
def agregar_botella():
opc=0
max=3
while... |
26a71a42ba62092d64f62fc5087d7496ae45c216 | raywiis/advent-of-code-2020 | /src/day-25.py | 889 | 3.53125 | 4 |
def transform(sm, divisor, loops, initial_value=1):
value = initial_value
for _ in range(loops):
value *= sm
value %= divisor
return value
def find_loop_count(sm, divisor, key):
value = 1
loop = 0
while value != key:
loop += 1
value *= sm
... |
912ab70cdc8418e4eee0e79e5013cfd24136af1c | tfolkman/pytorch-deepq-doom | /memory/base_memory.py | 1,075 | 3.59375 | 4 | from abc import ABC, abstractmethod
from collections import deque, namedtuple
from utils.helper_functions import get_device
class AbstractMemory(ABC):
def __init__(self, memory_size):
super().__init__()
self.memory_size = memory_size
self.memory = deque(maxlen=memory_size)
self.Me... |
1ebda7f186dd73384741c229b47635c86a80dc22 | shenoyrahul444/CS-Fundamentals | /Linked Lists/Merge K sorted lists.py | 1,257 | 3.890625 | 4 | # Definition for singly-linked list.
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
class Solution(object):
def mergeKLists(self, lists):
"""
:type lists: List[ListNode]
:rtype: ListNode
"""
if lists == None or lists == []:
... |
1a8573f692940f3df4cca2eec7eaab4af0488bf9 | shenoyrahul444/CS-Fundamentals | /Arrays/WordSearch 1.py | 1,305 | 3.515625 | 4 | class Solution(object):
def exist(self, board, word):
"""
:type board: List[List[str]]
:type word: str
:rtype: bool
"""
if board == None or word == None or board == [] or word == "":
return False
def dfs(i, j, ind):
if ind == len(word)... |
a123e746145c59e3171e2d6bcd72e25568646be8 | shenoyrahul444/CS-Fundamentals | /Point Next Pointers in Binary Tree.py | 1,064 | 3.9375 | 4 | # Definition for binary tree with next pointer.
class TreeLinkNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
self.next = None
def preorder(root):
if root:
print(root.left.val if root.left else None,root.val,root.next.val if root.next else Non... |
453c29201b7cff3dcfd7ef4000fce410bc842738 | shenoyrahul444/CS-Fundamentals | /Linked Lists/Reorder List.py | 1,312 | 3.75 | 4 | # Definition for singly-linked list.
class Node(object):
def __init__(self, x):
self.val = x
self.next = None
class Solution(object):
def reorderList(self, head):
"""
:type head: ListNode
:rtype: void Do not return anything, modify head in-place instead.
"""
... |
7b1776df4a8f147bb9a5511e34b1ceeb1b5976f1 | shenoyrahul444/CS-Fundamentals | /Arrays/Implement Queue using Stacks.py | 922 | 4.0625 | 4 | """
Problem : Implement a queue using 2 stacks
Thought: Think of a queue in terms of stacks. It is a sliding window, with the top of the queue adding elements and the rear of the queue removing elements
So, a stack for adding elements, and a stack for popping elements
"""
class Queue:
def __init__(self):
... |
79cba5c7d8c031964a6648c34191448a774f373a | shenoyrahul444/CS-Fundamentals | /Trees/Flatten Binary Trees.py | 1,033 | 4.25 | 4 | """
Given a binary tree, flatten it to a linked list in-place.
For example, given the following tree:
1
/ \
2 5
/ \ \
3 4 6
The flattened tree should look like:
1
\
2
\
3
\
4
\
5
\
6
"""
# Definition for a binary tree node.
# class TreeNode:
# ... |
2177462718a65aee89e452d57c0e0bf949c64947 | shenoyrahul444/CS-Fundamentals | /Miscellaneous Problems/Roman to Decimal Conversion.py | 1,184 | 4.03125 | 4 | """
Converting Roman Numerals to Decimal lying between 1 to 3999
Given a Romal numeral, find its corresponding decimal value.
Example:
Input : IX
Output : 9
Input : XL
Output : 40
Input : MCMIV
Output : 1904
M is a thousand, CM is nine hundred
and IV is four
"""
def romanToDecimal(roman):
roman = roman.strip... |
6be2aa66f9480b15448b256b80d2297871ba156c | shenoyrahul444/CS-Fundamentals | /Trie - Implementation.py | 2,669 | 4.0625 | 4 | # """ Implementing Basic Trie - For efficient word lookups"""
# TRIE - BEST SOLUTION 300ms Leetcode
class Trie(object):
def __init__(self):
"""
Initialize your data structure here.
"""
self.trie = {}
self.end = "**"
def insert(self, word):
"""
Inserts ... |
8e6eb37b70daca7afed14093b98c28f1526fedee | minccia/python | /python3/cursoguanabara/while.py | 5,678 | 4.0625 | 4 | #sexo = str(input(
# 'Qual é o seu sexo? [M/F] '
# )).strip().capitalize()
#
#while sexo not in 'MFfm':
# sexo = (str(input(
# 'Sexo inválido, por favor insira um válido. [M/F] '))).strip().upper()
#
#print('Seu sexo foi registrado com sucesso.')
#
#from random import ra... |
610230d7b556acd13d7f6b1c1703d0dc29305b7c | minccia/python | /python3/cursoguanabara/breakrepeticao.py | 3,580 | 3.984375 | 4 | #numero = contador = soma = 0
#while True:
# numero = int(input('Digite um número: [999 para parar]'))
# if numero == 999:
# break
# contador += 1
# soma += numero
#print(f'O número de números digitados foi {contador} e a soma de todos eles é {soma}')
#numero = 0
#while True:
# numero = int(inp... |
8dc39a0d85883fc6747093eff452c47b851f3ea5 | minccia/python | /python3/cursoguanabara/pitagoras.py | 329 | 3.8125 | 4 | cateto_adjacente = int(input('Qual é o valor do cateto adjacente? '))
cateto_oposto = int(input('Qual é o valor do cateto oposto? '))
def Pitagoras(cateto_adjacente, cateto_oposto):
hipotenusa = ((cateto_adjacente**2) + (cateto_oposto**2))**(1/2)
return hipotenusa
print(Pitagoras(cateto_adjacente, cateto_opos... |
4b1edd2857d6f5fbc4122114fce0461cf63ca3ce | onrolll/Algorithms | /WordJustification/wj2.py | 1,987 | 3.703125 | 4 | class TextJustificator(object):
"""docstring for TextJustificator."""
def __init__(self, words, line_width):
super(TextJustificator, self).__init__()
self.words = words
self.width = line_width
self.memo = {}
self.parent = {}
def dp(self):
n = len(words)
... |
7d0b3cc9862ab44f0c7bb015e14d25a9cf972c86 | fanyujiaoy/ProgrammingTasks | /Task3/SortClass.py | 8,547 | 4 | 4 | # -*- coding: utf-8 -*-
import math
class SortClass:
"""
1. 插入排序
插入排序的基本操作就是将一个数据插入到已经排好序的有序数据中,
从而得到一个新的、个数加一的有序数据,算法适用于少量数据的排序,时间复杂度为O(n^2)。
插入算法把要排序的数组分成两部分:
第一部分包含了这个数组的所有元素,但将最后一个元素除外(让数组多一个空间才有插入的位置),
而第二部分就只包含这一个元素(即待插入元素)。
在第一部分排序完成后,再将这个最后元素插入到已排好序的第一部分中。
"... |
26ed8f32be0ca2e7ea223880cbc45969be6d01e7 | datcn1212/Hackerrank_Excersises | /Merge_the_tool.py | 501 | 3.703125 | 4 | # https://www.hackerrank.com/challenges/merge-the-tools/problem
def merge_the_tools(string, k):
# your code goes here
lst = []
result = []
for i in range(int(len(string)/k)):
lst.append(string[k*i:k*i+k])
for s in lst:
temp = []
for i in s:
if i not in temp: temp... |
f893bc6884fe162f2367828dbf566a6a13bf85c2 | AlejandroIV/MetNum2 | /Mets5_SolNumEcNoLin/Met3_BroyMain.py | 725 | 3.9375 | 4 | """Modulo que coordina: pide los datos al usuario para poder correr el programa que contiene el Metodo de Broyden"""
from Met_Broyden.Preparar_Programa import Identificar_Variables, Escribir_Programa
def Broyden():
fNombre = input("Escribe el nombre del archivo sin escribir la extension '.txt': ")
listaVars =... |
d03967c7f20ce1f930d234cc8f7eda298358e3e5 | ashwin-5g/LPTHW | /ex12.py | 357 | 4.03125 | 4 | age = raw_input("How old are you? ")
height = raw_input("How tall are you? ")
weight = raw_input("How much do you weigh? ")
print "So, you're %r old, %r tall and %r heavy." % (age, height, weight)
x = raw_input("Enter value for x: ")
y = raw_input("Enter value for y: ")
sum = int(x) + int(y)
print "The sum of the tw... |
13a9a16ed598e6b2f79f666ad34ae0012064e9dd | ashwin-5g/LPTHW | /ex3.py | 704 | 4.375 | 4 | #prompt for chicken count
print "I will now count my chickens:"
#display hens' count
print "Hens", 25 + 30 / 6
#display roosters' count
print "Roosters", 100 - 25 * 3
% 4
#display eggs' count
print "Now I will count the eggs:"
print 3 + 2 + 1 - 5 + 4 % 2 - 1 / 4 + 6
#comparison operation in use
print "Is it true tha... |
a9942ec8f60157a0d6d82cf3ff5da2f9b46f860c | ashwin-5g/LPTHW | /list_append.py | 266 | 3.84375 | 4 | num_list = [1, 2, 3, 4, 5, 6]
more_list = [23, 45, 767, 44, 334, 'cat', 'bat', 'sat', 'fat', 'lat']
for i in more_list:
num_list.append(i)
print more_list
print more_list.pop(), more_list.pop(), more_list.pop(2)
print more_list
print more_list[1], more_list[-1]
|
e536923026ccf8fe616497e5f88a895a59a9ec25 | Ezhilprabu/Ezhil | /odd_even.py | 154 | 3.765625 | 4 | number=int(input())
if(number>=1 and number<=100000):
if(number%2==0):
print("Even")
elif(number%2==1):
print("Odd")
else:
print("invalid")
|
d5ee557b7190ab90b7eef55c87a636ea13d70307 | oy6033/MobileApps-for-Android | /Human Activities/Code/logistic regression.py | 1,506 | 3.796875 | 4 | import numpy as np
import matplotlib.pyplot as plt
from include.data import get_data_set
#get_data_set is manually written function helps select train or test data from Data folder
from sklearn.linear_model import LogisticRegression
import seaborn as sns
from sklearn import metrics
train_x, new_train_y = get_data_set(... |
f7177712e607d8321b895e23b15849efd95ae61f | oy6033/MobileApps-for-Android | /Human Activities/Code/LinearSVC.py | 1,102 | 3.796875 | 4 | from include.data import get_data_set
#get_data_set is manually written function helps select train or test data from Data folder
import numpy as np
from sklearn.svm import LinearSVC
#Xt is collection of Vectors of size 64
#Yt is Y labels in one hot representation i.e for 4 classes: [1,0,0,0] <- representation for 1s... |
6c67ea84ee8763f35854ad8b1a420a01934ccc00 | Vartikag24/GamifyIt | /game.py | 2,315 | 3.71875 | 4 | import turtle
wn = turtle.Screen()
wn.title("Pong")
wn.bgcolor("black")
wn.setup(width=800, height=600)
wn.tracer(0)
#paddleA
paddle_a=turtle.Turtle()
paddle_a.color("white")
paddle_a.speed(0)
paddle_a.shape("square")
paddle_a.shapesize(stretch_wid=5,stretch_len=1)
paddle_a.penup()
paddle_a.goto(-350,0)
#paddleB
pad... |
95b920b9dfeb302a127f478203745c0b4c7ad5c4 | AtheeshRathnaweera/Basic_scraping_script_using_BeautifulSoup_library_in_python | /scraper.py | 2,053 | 3.90625 | 4 | #Python programme to retrieve data from a blog post
# import libraries
from urllib.request import urlopen
from bs4 import BeautifulSoup
# url of the site
quote_page = "https://se15053.blogspot.com/2018/12/how-to-write-cv.html"
# query the website and return the html to the variable ‘page’
page = urlopen(quote_page... |
e5f554a4ed8abecc6aa1801f68adfdfcf3738593 | xiaoyangren6514/python_imooc | /oop/test_object.py | 950 | 4.25 | 4 | class User(object):
"""
成员变量,可以通过类名饮用,所有对象共有
如果对象修改了成员变量的值,不会影响其他对象的值
如果通过类名调用直接修改了成员变量的值,那么所有对象对应的值都发生变化,除非对象之前修改过此值
"""
address = 'bj'
def __init__(self, name, age, weight):
self.name = name
self._age = age
self.__weight = weight
def get_weight(self):
... |
a8194aa920ae73661b4b66189077e9d22c90210b | xiaoyangren6514/python_imooc | /oop/test_class_extends.py | 601 | 3.703125 | 4 |
class Animal(object):
hobby = 'eat huo tui'
def __init__(self,name,weight):
self.name = name
self.weight = weight
@classmethod
def get_hobby(cls):
return cls.hobby
@property
def get_weight(self):
return self.weight
class Dog(Animal):
def __init_... |
77f929f5bf7e623852870e6575f6f90ccea33506 | Garvit-32/Opencv_code | /18_smoothning_image.py | 920 | 3.78125 | 4 | # homogeneous filter is the most simple filter each output pixel is the mean of its kernel neighbour
# In image processing a kernerl or mask is a small matrix It is used for blurring,sharpening,embossing,edge detection and more.
import cv2
import numpy as np
from matplotlib import pyplot as plt
img = cv2.imread('Noi... |
90012c431612c0221318d69ee94b8bed263a9736 | Garvit-32/Opencv_code | /15_adaptive_thresholding.py | 775 | 4.125 | 4 | import cv2 as cv
import numpy as np
# Adaptive Thresholding algorithm provide the image in which Threshold values vary over the image as a function of local image characteristics. So Adaptive Thresholding involves two following steps
# (i) Divide image into strips
# (ii) Apply global threshold method to each strip... |
8eeb61c5ebef629676104ab969a625f1a01418ca | Koweiyi/WebSpiderLearning | /05-数据存储/02-读取json格式字符串.py | 567 | 3.578125 | 4 | # -*- coding:utf-8 _*-
"""
@version: 1.0.0
author: 孔维一
@time: 2020/09/04
@file: 02-读取json格式字符串.py
@function:
@modify:
"""
import json
string = '''
[
{
"name": "bob",
"age": 21,
"gender": "male"
},
{
"name": "Lily",
"age": 18,
"gender": "female"
}
]
'''
da... |
2f3830c307caa93d0a824191b903dc6d1c3b0f88 | crisgrim/python-oop | /Kata2-Student.py | 842 | 3.6875 | 4 | class Student():
# Properties
name = ''
last_name = ''
dni = ''
age = 0
subjects = []
# Constructor
def __init__(self, name, last_name, dni, age):
self.name = name
self.last_name = last_name
self.dni = dni
self.age = age
# Methods
def greet(self)... |
eec4d9cf74338ba09526ecadfc42e9f2cecd81b2 | crisgrim/python-oop | /Composition.py | 603 | 3.875 | 4 | class Player():
# Properties
name = ''
age = 0
role = ''
# Constructor
def __init__(self, name, age, role):
self.name = name
self.age = age
self.role = role
class Team():
players = []
def show_team(self):
for player in self.players:
print(p... |
d7738620802b5f4751c496671df4f6fac1b2a514 | ounula/terana_python_code | /02_2048_core_algorithm.py | 984 | 3.828125 | 4 | """
2048游戏 核心算法
"""
list_map = [
[2, 0, 2, 0],
[2, 0, 0, 2],
[4, 4, 4, 4],
[2, 0, 4, 2]
]
list_merge = [2, 0, 2, 0]
def zero_to_end():
"""
零元素向后移动
"""
for i in range(len(list_merge) - 1, -1, -1):
if list_merge[i] == 0:
del list_merge[i]
list_merge.... |
a8dbc4ead47024aaae3146f4860fd8930a4f21b4 | cromptonhouse/examplesPi | /hiworld.py | 750 | 4.53125 | 5 | # This is a comment! If we type a # we can type what we want and the computer ignores it!
print "hello world" # prints words, know in code as a string - "Hello World"
# We are going to learn about variables"
# A variable is somewhere (memory) where we can store information"
x = 6 # we have assigned the ... |
8dc1b48a41cc4592566ffa8635de2fb602c9bc0e | wallacesilva/liasis | /liasis/core/datastructures.py | 961 | 3.890625 | 4 | from dataclasses import dataclass
@dataclass
class DataStructure:
"""
Base dataclass to be used as representation of Entities or any data
crossing the domain boundary.
"""
pass
@dataclass
class Request(DataStructure):
"""
Request attributes are specific for each UseCase, so te base datac... |
55a6c7ebfd05d205754f24e4eaead542c9f3000a | lukewrites/RealPython | /sql/hw7.py | 799 | 3.6875 | 4 | """
Output car's make & model on one line, quantity on the next, and then the order
count on the next line.
"""
import sqlite3
with sqlite3.connect("cars.db") as connect:
c = connect.cursor()
# get make, model, and quantity
c.execute("""SELECT * from inventory""")
rows = c.fetchall()
# print make... |
1612914dd68261bc547e77e5797d384916a67394 | mnowotka/Vending_Machine | /vending_machine.py | 757 | 3.515625 | 4 | class VendingMachine:
def __init__(self, floors, slots, products):
pass
# self.floors = floors
# self.slots = slots
# self.products = products
# self.machine = [[[Slot(floors) for _ in self.floors] for _ in self.slots] for _ in self.products]
def free_space(self):
... |
85c77babab8a2905dd1bb290fdf6a27dde4e71e3 | bobhall/bobhall_euler | /euler/35/bob.py | 1,216 | 3.578125 | 4 | from operator import add
from collections import deque
#
# Return a list of primes under num using the seive of eratosthenes
#
def getPrimesSeive(num):
nums = range(0,num+1)
nums[0] = 0
nums[1] = 0
i = 2
while i < len(nums) / 2:
j = i
val = nums[i]
if val == 0:
... |
9a0051d15191440d2a16769fc04880974b28083c | bobhall/bobhall_euler | /euler/12/bob.py | 1,295 | 3.65625 | 4 | from math import sqrt
def getNthTriangleNum(num):
return sum(range(1,num+1))
def getFactorsDumb(num):
vals = []
for x in xrange(1,num+1):
if num % x == 0:
vals.append(x)
return vals
def isFactor(num, candidate):
if num % candidate == 0:
return True
else:
... |
793807af7fa9e613a8eda6b85a336911d85c64eb | bobhall/bobhall_euler | /euler/22/22.py | 623 | 3.5625 | 4 | import string
def getAlphabetizedNamesFromFile():
fd = open('names.txt')
names = fd.readlines()
names = names[0]
names = names.split(',')
names = [x.strip('"') for x in names]
names.sort()
names = [string.lower(x) for x in names]
return names
def getScore(name, num):
score = 0
... |
cd609a8d4ba4f285ef8098648547441ed8fc37cb | Alejandrozic/CS3502-Virtual-OS-Barebone | /os_/alu.py | 909 | 3.75 | 4 | """
The Arithmetic Logic Unit (ALU) module is responsible
for all computations.
Takes int() and returns int().
"""
def add(r1, r2):
return r1 + r2
def sub(r1, r2):
return r1 - r2
def multi(r1, r2):
return r1 * r2
def div(r1, r2):
return r1 // r2
def and_ope... |
d98da73d8be2b72853b0d8d08062e04e63897829 | jenhantao/StateMachineDesigner | /stateMachineDesigner.py | 12,222 | 3.5 | 4 | ### Imports ###
import sys
### Classes ###
class Node:
def __init__(self, aLetter = None, aLevel = 0, aParent = None, aState = 0):
self.letter = aLetter
self.level = aLevel
self.children = []
self.parent = aParent
self.neighbors = [] # nodes with the same level as this ndoe
self.state = aState
def printN... |
07ca8044bc4230206a1667aad6cbe766a40bc2aa | a-muskin/my | /practice.py | 497 | 3.859375 | 4 | tickets = int(input('Привет, сколько Вам билетов? \n'))
for i in range(tickets):
age = int(input('Введите возраст гостя: \n'))
if age < 18:
print('В возрасте', age, 'вход бесплатный')
print('---')
elif 18 <= age <= 25:
print('В возрасте', age, 'вход 990 руб.')
print('---')
... |
52a3b73d92aca51b59ef65568bfef13335b8a607 | MichaelBarney/ProjetosEC | /4-logica/Resolucao.py | 2,646 | 3.75 | 4 | inputFile = open("Expressoes.in", "r")
width = 0
satisfativel = 0
refutavel = 0
myText = ""
def operatorValid(operator):
if operator != '.' and operator != '+' and operator != '-' and operator != '>':
return False
else: return True
def getExpressions(expr):
i = 0
opens = 0
closes = 0
... |
3ed0bfa5267c2dd4533deb9f85b879cb59b84d81 | xaliq2299/UFAZ-BSc | /L3/S1/CSfPh/hands-on/prime_numbers.py | 368 | 3.890625 | 4 |
# Main loop
for i in range(2,101):
primeNumber=True
# If the rest Euclidian division of i by at least one number between 2 and
# i-1 is 0, i has a divider which is nor 1 nor itself, thus, i is not prime
for k in range(2,i):
if(i%k==0):
primeNumber=False
# If after this loop primeNumber is stil... |
bc0016ed14878c0f5508903779de51611f48b02e | xaliq2299/UFAZ-BSc | /L3/S1/CSfPh/hands-on/fibonacci.py | 372 | 4 | 4 |
#Initialization
u0=1
u1=1
count=0
# Print the two first terms of the sequence (u0 and u1)
print(u0)
print(u1)
while(count<=18):
# Calculate the new term (result), then prepare the next iteration by
# shifting u1 into u0 and the result into u1.
result=u1+u0
u0=u1
u1=result
count+=1
# P... |
53d6443c954e116282e4048a560cc1e0650a9df7 | dannydiaz92/MIT_IntroToCS | /Pset2/ps2_hangman.py | 2,974 | 4.375 | 4 | # 6.00 Problem Set 3
#
# Hangman
#
# -----------------------------------
# Helper code
# (you don't need to understand this helper code)
import random
import string
WORDLIST_FILENAME = "words.txt"
def load_words():
"""
Returns a list of valid words. Words are strings of lowercase letters.
Depending... |
7a078242421c3d7ad36ad2a284053c6756cd734c | NaleRaphael/cartpole-control | /cpc/agent.py | 8,806 | 3.578125 | 4 | """
An agent plays a role like a brain of a solver.
It can `act` and `react` according to the observation of environment.
`act`: generate action to affect environment
`react`: literally, agent do things after receiving feedback from environment
"""
import logging
import numpy as np
from collections import deque... |
52a311bf5ef13b9aae6ac12e3de763f343f2a5c5 | bashiru98/python-object-oriented-programming | /simplecalculator.py | 4,624 | 3.609375 | 4 | import tkinter as tk
def btnClick(num):
global operator
operator = operator + str(num)
text_input.set(operator)
def btnClearDisplay():
global operator
operator= ""
text_input.set(operator)
def equalcom():
global operator
man=(eval(operator))
text_input.set(man)
operator= ""
... |
c8e5b27de74dc1104bdbbe112172c7b2c607a03b | Frootloop11/lectures | /lecture_3/Do this now_!.py | 679 | 4.03125 | 4 | def main():
user_age = 0
is_valid_input = False
while not is_valid_input:
try:
user_age = int(input("age: "))
if user_age < 0:
print("Age must be greater then 0")
else:
is_valid_input = True
except ValueError:
p... |
801f87165fd8036da1aece5348751af8a68dd685 | Frootloop11/lectures | /week 10/warm_up.py | 576 | 4.28125 | 4 | """
Take in a file
Find and return the longest line in that file
print the line number and length character
"""
def main():
line_number, length = find_longest_line("warm_up.py")
print(line_number, length)
def find_longest_line(file_name):
max_line_number, max_length = -1, 0
with open(file_name, 'r')... |
d708d04d1adf4ae33696d1849f62076d75d803b9 | pepecontrapepe/Video_Club_PostgreSQL | /app.py | 906 | 3.546875 | 4 | from user import User
from database import Database
# my_user = User('jose@schoolofcode.me', 'Jose', 'Salvatierra', None)
# my_user = User('pepecontrapepe@gmail.com', 'Jose Ramon', 'Gene Garrigos', None)
# print(my_user)
#my_user.save_to_db()
# the classmethod is called directly from the class
# my_user = User.load... |
a6b1d841e0a1ea165b268add0056a77c35164611 | kradziko/python | /10_11/wytworniki.py | 1,837 | 4.15625 | 4 | # -*- coding: utf-8 -*-
'''
wytworniki (list comprehensions)
'''
l = range(1, 21, 2)
print l
# postac prosta
# podwojenie wartosci
print[2 * x for x in l]
# para x, kwadrat x
print [(x, x * x) for x in range(1, 5)]
# tabela kodowa ASCII
print[(x, ord(x)) for x in "ABCDEF"]
# lista zawierajaca 10 pustych list
prin... |
06e6492146dc1e08ca2aa72428d72cb2c59431be | nick-lehmann/SnakeCharmerGuide | /games/ninjas.py | 744 | 4.21875 | 4 | """
The wall has been breached and cobras are attacking the castle 🏰
We see that there are 50 cobras approaching 🐍
Fortunately we have special ninjas that can defeat the cobras 🥷
Every ninja can defeat 3 cobras.
Can we defeat all the cobras with the ninjas we have?
1. Define a variable "ninjas" and one "cobras" and... |
69fb16118b9622291bc14161e377f7b9ce4bec78 | nick-lehmann/SnakeCharmerGuide | /games/drive.py | 449 | 3.953125 | 4 | class AgeError(Exception):
pass
def drive(age):
age = int(age)
if age < 18:
raise AgeError("young")
if age > 80:
raise AgeError("old")
print('Brumm brumm')
while True:
try:
age = input('What is your age? ')
drive(age)
break
except ValueError:
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.