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 |
|---|---|---|---|---|---|---|
8338b3eed9c07c738e1ebf4e59496fd43361d7da | serban/dotfiles | /python/mondays | 455 | 3.5625 | 4 | #!/usr/bin/env python3
import calendar
import datetime
import sys
year = datetime.date.today().year
if len(sys.argv) > 1:
year = int(sys.argv[1])
first_day = datetime.date(year, 1, 1)
last_day = datetime.date(year, 12, 31)
first_monday = first_day + datetime.timedelta(
days=((calendar.MONDAY - first_day.week... |
477011a5fb1bb6e0be8f97d0b8d22a2eac57dcd1 | Dominic-Groshong/practice | /python/LeetCodingProblems/leet/__init__.py | 4,587 | 4.15625 | 4 | #!/usr/bin/env python
# Testing default function
def sum(arg):
total = 0
for val in arg:
total += val
return total
def printNum(n):
string = ""
y = n
while y > 0:
string += str(n)
# do something
y -= 1
return string
def printPat(n):
"""
Given a n... |
0fd112e01e2545fb78af3211f1f1d12dd0159d24 | Lukhanyo17/Intro_to_python | /Week7/acronym.py | 538 | 4.15625 | 4 | def acronym():
acro = ''
ignore = input("Enter words to be ignored separated by commas:\n")
title = input("Enter a title to generate its acronym:\n")
ignore = ignore.lower()
ignore = ignore.split(', ')
title = title.lower()
titleList = title.split()
titleList.append("end"... |
cff8f82a62cee3f23764073ddb62add53b63ebc1 | siva-ram/python-map-reduce | /map.py | 304 | 3.578125 | 4 | #!/usr/bin/env python
import sys
import csv
# read the csv data
data = csv.reader(sys.stdin)
for line in data:
if line[0] != 'DATE': #ignore the header row
for i in range(24, 29): #vehicle type code columns
if line[i]:
print('%s\t%s' % (line[i].strip(), 1))
|
8dd9d09f01617b387fa4c9a373eb927efa64b966 | 1s0m0rph/RecitalSchedulingGenetic | /src-python/gene.py | 3,353 | 3.796875 | 4 | import numpy as np
"""
Contains the gene representation of a class ordering (candidate solution), as well as all of the operations done on that gene involving *only* that gene
"""
class Gene:
"""
ordering specifies what order the classes come in. It's a permutation of the class indices
"""
def __init__(self,mutat... |
dfe58376845428fe8c8383711a8f3b1cf802d576 | bambrozim/Zumbi-Python | /lista03b_ex05.py | 167 | 3.953125 | 4 | '''
Faça um programa que peça um inteiro positivo e o mostre invertido. Ex.: 1234 gera 4321
'''
n = str(input("Digite um número inteiro positivo:"))
print(n[::-1])
|
361df74d5f8dee32a2363ad69645395947d97335 | bambrozim/Zumbi-Python | /lista03b_ex02.py | 805 | 3.890625 | 4 | '''
Indique como um troco deve ser dado utilizando-se um número mínimo de notas. Seu algoritmo deve ler
o valor da conta a ser paga e o valor do pagamento efetuado desprezando os centavos.
Suponha que as notas para troco sejam as de 50, 20, 10, 5, 2 e 1 reais, e que nenhuma delas
esteja em falta no caixa.
'''
conta = ... |
296474cb2f896f46f79de0658ffa5f69ba02e5b3 | bambrozim/Zumbi-Python | /010_fatorialn_while.py | 152 | 3.90625 | 4 | n = int(input("Digite um número inteiro a ser gerado o fatorial: "))
i = n
fat = 1
while i >= 1:
fat *= i
i -= 1
print("%d! = %d" %(n, fat))
|
62fce34810572aa42180fb68e629efb2b9a3fdba | bambrozim/Zumbi-Python | /lista03b_ex01.py | 492 | 4.03125 | 4 | '''
Dizemos que um número natural é triangular se ele é produto de três números
naturais consecutivos. Exemplo: 120 é triangular, pois 4.5.6 = 120. Dado um
inteiro não-negativo n, verificar se n é triangular.
'''
n = int(input("Digite um número inteiro positivo: "))
istriangular = False
for i in range(1,int(n/2)):
... |
8e142cb37a3ed8ed3e1448294f881b3b3ebe87d8 | bambrozim/Zumbi-Python | /lista01_ex01.py | 138 | 3.90625 | 4 | num1 = int(input("Digite um número inteiro: "))
num2 = int(input("Digite um número inteiro: "))
print("A soma é: %d." %(num1 + num2))
|
83757e7960c326658a268503ce4806b8c147a03d | bambrozim/Zumbi-Python | /005_Numeropar_while.py | 115 | 3.96875 | 4 | user_n = int(input('Digite um número inteiro: '))
n = 2
while n <= user_n:
print(n)
n += 2
|
a51357020c8422857735e9092ed7b35fa3992060 | samvelarakelyan/ACA-Intro-to-python | /Practicals/Practical5/Modules/pretty_print.py | 667 | 4.25 | 4 |
def simple_print(x:int):
"""
The function gets an integer and just prints it.
If type of function argument isn't 'int' the function print 'Error'.
"""
if isinstance(x,int):
print("Result: %d" %x)
else:
print("Error: Invalid parametr! Function parametr should be integer")
def... |
0c4fda0b780b6fabd259c69cf98eae44f17bacf7 | samvelarakelyan/ACA-Intro-to-python | /Homeworks/Homework6/home6.py | 2,837 | 3.75 | 4 |
class Person:
def __init__(self, name:str, last_name:str, age:int, gender:str, student:bool, password:str):
self.name = name
self.last_name = last_name
self.age = age
self.gender = gender
self.student = student
self.__password = password
def set_passwo... |
3a94e38288c303819ae18a3ec228da79d2d507c8 | samvelarakelyan/ACA-Intro-to-python | /Practicals/Practical6/pract6.py | 5,248 | 3.84375 | 4 |
#1)
class Circle:
def __init__(self, radius:float, color:str):
self.radius = radius
self.color = color
def getDesc(self):
print("A %s color circle with radius %.2f" %(self.color, self.radius))
c1 = Circle(3.14, "red")
c2 = Circle(6.28, "green")
c3 = Circle(... |
193d299bf7780aaeb3024104f5c0f9ba2de06f20 | samvelarakelyan/ACA-Intro-to-python | /Homeworks/Homework2/problem5.py | 1,061 | 4 | 4 | import calendar
import datetime
import time
"""
2)
"""
#a)
print(datetime.date(2000,8,18))
#b)
print(datetime.date(2000,8,18).year)
#c)
print(datetime.date(2000,8,18).month)
#d)
print(datetime.date(2000,8,18).day)
#e)
wd_num=calendar.weekday(2000,8,18)
wd_name=calendar.day_name[wd_num]
print(wd_name)
#f)
year = ... |
65d04110c49dc0b6e926274501e24201c2f7fc33 | simranmahadik1199/data-sciences-statistics- | /uniion,diff,inter.py | 506 | 4.09375 | 4 | l1=[1,2,3,4,5]
list1=set(l1)
print(list1)
l2=[2,5,6,4,8,9]
list2=set(l2)
print(list2)
def union(list1,list2):
list_union=list1.union(list2)
return list_union
def intersection(list1,list2):
list_intersect=list1.intersection(list2)
return list_intersect
def difference(list1,list2):
list_diff=list1.dif... |
cc2d7fe6a2337179bafc72473dfff71e436c3e3b | jenildesai25/LeetCode | /LongestCommonPrefix/LongestCommonPrefix.py | 825 | 3.828125 | 4 | # Input: ["flower","flow","flight"]
# Output: "fl"
class LongestCommonPrefix:
def __init__(self, input):
self.input = input
def longest_common_prefix(self):
if len(self.input) == 0:
return False
if len(self.input) == 1:
return self.input
self.input.sort... |
242d8a5f375ea6aa82438ffbae3909be50ce612f | jenildesai25/LeetCode | /MergeTwoSortedLists/MergeTwoSortedLists.py | 1,001 | 3.953125 | 4 | # Input: 1->2->4, 1->3->4
# Output: 1->1->2->3->4->4
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
def __repr__(self):
return '{}->{}'.format(self.val, self.next)
class MergeTwoSortedLists:
def merge_two_sorted_lists(self, list_node_1, list_node_2):
... |
6a1437416678f353108bdd1c990812c9a1f2656f | CameronHunt5812/GitHub | /working_file.py | 691 | 3.578125 | 4 | from Tkinter import *
root = Tk()
drawpad = Canvas(root, width=630, height=630, background='white')
drawpad.pack()
player = drawpad.create_line(20,20,80,20)
derection = 0
key = None
def KeyStorage (c):
global key
key = c.char
def KeyInput(Key):
global key
derection = 0
if (key != None):
i... |
d424612c7979f5279bc8b10011045d964d65708e | rachidtahiri/PythonMission1 | /bonus_balla_tahiri_najid.py | 1,824 | 3.5625 | 4 | # utilisation des compteurs pour savoir combien de fois le nombre est grand et combien de fois est petit
# le compteur i est incrementé si 'a' est grand
#le compteur j est incrementé si 'a' est petit
i=0
j=0
#le compteur k est incrementé si 'b' est grand
#le compteur l est incrementé si 'b' est petit
k=0
l=0
#le compt... |
ccef16a1d859538729f5f8c5cb12da3f9f05a5dc | ranisharma20/loops | /harshad_number.py | 179 | 3.71875 | 4 | n=int(input("enter the any number"))
sum=0
c=n
r=0
while c>0:
r=c%10
sum=sum+r
c=c//10
if n%sum==0:
print('Harshad number')
else:
print('not hardhad number')
|
eadaa33b854038033ff321e0541adaded40cd3f7 | ItzelMM/first-repository | /HW1/ZyLab1.py | 136 | 3.96875 | 4 | # Itzel Munoz Monroy PSID: 1888446
number = int(input("Please enter an integer: "))
num_sq = number**2
print("Your number squared is:", num_sq)
|
c5a9ffaf0a3bbfead2cab2d50bf5b8d73013ecb7 | ItzelMM/first-repository | /HW3/ZyLb3.py | 1,196 | 4.0625 | 4 | # Itzel Munoz Monroy PSID: 1888446
class ItemToPurchase:
def __init__(self):
self.item_name = "none"
self.item_price = 0
self.item_quantity = 0
def print_item_cost(self):
print(self.item_name, self.item_quantity,
"@ ${:.0f} = ${:.0f}".format(self.item_pric... |
eca134c7367ce4bc9867e0ff41c0778aca7ecdd9 | ItzelMM/first-repository | /HW2/ZyL2.py | 547 | 3.5625 | 4 | # Itzel Munoz Monroy PSID: 1888446
a1 = int(input("Enter an integer: "))
b1 = int(input("Enter an integer: "))
c1 = int(input("Enter an integer: "))
a2 = int(input("Enter an integer: "))
b2 = int(input("Enter an integer: "))
c2 = int(input("Enter an integer: "))
x = "no"
y = "no"
for r in range(-10, 11):
... |
51e121577a3af82bf1478b2b3bc11cf3a42fac25 | ItzelMM/first-repository | /HW3/ZyLb1.py | 1,313 | 3.828125 | 4 | # Itzel Munoz Monroy PSID: 1888446
class FoodItem:
def __init__(self, name="None", fat=0.00, carbs=0.00, protein=0.00, num_servings=0.00):
self.name = name
self.fat = fat
self.carbs = carbs
self.protein = protein
self.num_servings = num_servings
def get_calories... |
b99a549777ed3a8d854552b528d38c92db6bdb2c | sharat910/selenium-youtube | /logger.py | 488 | 3.515625 | 4 | import logging
def create_logger():
"""
Creates a logging object and returns it
"""
logger = logging.getLogger("youtube_player")
logger.setLevel(logging.INFO)
# create the logging file handler
fh = logging.FileHandler("/path/to/test.log")
fmt = '%(asctime)s - %(name)s - %(levelname... |
422570c5bc14e67c35bfeeefe684e725dfaaf3c2 | thuatngk/c6 | /file.py | 428 | 3.625 | 4 | def main():
# name=input("input your full name: ")
# file_write=open("write.txt",'w')
#
# file_write.write(name)
# file test a file reference variable
file_test = open("write.txt", 'r') #read only
line = file_test.readline() #read line
while line != '':
print(lin... |
71b27879abea714f3ab79556c97bbc400d9e71df | ibrahim775/Python-Algorithms | /Period of Non-Linear Pendulum (Physical Pendulum).py | 1,595 | 3.8125 | 4 | from math import sqrt
from math import pi
from math import sin
from math import pow
from matplotlib import pyplot
R = 1
g = 9.81
T_ln = 2*pi*sqrt(R/g)
f_ln = 1/T_ln
phi = []
for i in range(158):
phi += [i/100]
def double_factorial(r):
if r <= 1:
return 1
else:
return r*double_factorial(r... |
3c18ddcd78bf10b9b0dfa4d1e7228ce721451d4b | asaluja/spectral-scfg | /parameter-estimation/tree.py | 2,441 | 3.578125 | 4 | #!/usr/bin/python -tt
import sys, commands, string, gzip, re
class tree:
'''
Tree class is a recursive data structure used for feature extraction.
Since the features we use are based on the tree structure, it's
important to convert the per sentence minimal grammar to the tree
so that we can ex... |
b7d9d94cbe4231eaae6116f6c0debca3d2517ca5 | marcus6255/estudo | /programa2.py | 171 | 3.859375 | 4 | '''
PROGRAMA 2 CRIADO NO LAPTOP
'''
nome = input ('Digite seu nome: ')
idade = int (input('Sua idade: '))
print ('Olá {}! Sua idade é de {} anos' . format(nome,idade))
|
76e9d759bbee0884ff88b287e491ae097580f41b | imsk003/Python | /reverse_words.py | 224 | 4.25 | 4 | def reverseWords(input):
inputWords = input.split(" ")
inputWords=inputWords[-1::-1]
output = ' '.join(inputWords)
return output
if __name__ == "__main__":
input = 'hello python'
print(reverseWords(input))
|
f6cc4b3fb2083e6881e75c479d8feac664cafce2 | stevexnx/a-pasar-esta-wea | /juegoDeUno.py | 204 | 3.578125 | 4 | colores = ["A","AM","V","R"]
valores = ["masDos"] + [v for v in range(2,11)] + ["MasC", "salto", "retorno","cambioColor"]
baraja = [(valor, color ) for color in colores for valor in valores]
print(baraja) |
27ab319f161969fa9fa51d61670f1d2da83d664e | konrad-hod-kowalczyk/Python_exercises | /phone_number.py | 417 | 3.921875 | 4 | def create_phone_number(n):
x = ""
i=0
for number in n: #simple program taking a list of numbers and writing it into american phone number style, in particular places in number besides adding the number from list it also adds special character
if i==0:
x=x+"("
if i==2:
... |
b85b453a8bff6af95f15c02aa6ac0117dad25381 | SCIAUN/lecture3 | /1_1_break_statement.py | 118 | 3.546875 | 4 | a=10
b=20
while a<100:
while b<100:
if(b%50==0):
break
print(b)
b+=1
a+=10 |
5844373d6e4ee976dd926053636d8d5815756cf8 | tm2josep/eulerPy | /problem1.py | 246 | 3.953125 | 4 | #Euler problem 1
#Find the sum of all multiples of 3 or 5 below 1000.
multiples = []
def getMultiples(n):
for x in range(3, n):
if x % 3 == 0 or x % 5 == 0:
multiples.append(x)
getMultiples(1000)
print(sum(multiples))
|
2f8b197f1c069e91317889562ef9d9497430155c | ygh929/rosalind_alg_code | /Insert_sort.py | 327 | 3.671875 | 4 | def insert_sort(A,l):
n=0
for k in range(l):
while k>0 and A[k]<A[k-1]:
temp=A[k-1]
A[k-1]=A[k]
A[k]=temp
k=k-1
n=n+1
return (n)
f=open('rosalind_ins.txt','r')
l=int(f.readline().strip())
A=map(int, f.readline().split(" "))
print insert_so... |
78443e818b3b594005d9ab5f46b168d5b115e90d | himanshu2801/Geeksforgeeks | /Google kickstart Round H(Retype).py | 2,954 | 3.515625 | 4 | """
Problem
After spending many hours studying for programming competitions, you decided to take a rest and play video games. You are currently playing an adventure game called Quick Start.
This game has N levels, and you are currently on the K-th level. Unfortunately, you just realized that to beat the boss at the fi... |
656882d312948c2213d42e89ee216536865b2e4b | himanshu2801/Geeksforgeeks | /Index Of an Extra Element .py | 812 | 3.96875 | 4 | """
Given two sorted arrays of distinct elements. There is only 1 difference between the arrays. First array has one element extra added in between. Find the index of the extra element.
Example 1:
Input:
N = 7
A[] = {2,4,6,8,9,10,12}
B[] = {2,4,6,8,10,12}
Output: 4
Explanation: In the second array, 9 is
missing and i... |
6c0201b62681186880347bf11cfd61f44fa3701b | himanshu2801/Geeksforgeeks | /Amount of Water.py | 1,310 | 3.71875 | 4 | """
An array A containing heights of building was given. Its a rainy season. Calculate the amount of water collected between all the buildings.
Histograms with no space in between
Input:
The first line of input contains an integer T denoting the number of test cases. The first line of each test case is N, N is the ... |
7d46118e1ac39608ad4ddca83d75190e3a8a7a54 | himanshu2801/Geeksforgeeks | /Equilibrium point.py | 1,076 | 3.984375 | 4 | """
Given an array A of N positive numbers. The task is to find the first Equilibium Point in the array.
Equilibrium Point in an array is a position such that the sum of elements before it is equal to the sum of elements after it.
Example 1:
Input:
N = 1
A[] = {1}
Output: 1
Explanation: Since its the only
element h... |
b4cf50d648809cb757ac1fafa0d87cc52edb87c5 | lauranewland/hb-labs | /dicts-word-count/wordcount.py | 804 | 4.03125 | 4 | # put your code here.
import sys
filename = sys.argv[1]
def word_counter():
#file_text = open(filename)
word_count = {}
for line in open(filename): #loops through each line in the file
line = line.strip()
words = line.split(" ") #stores each word in a list
for word in words: #lo... |
4b8b50f6a13741d997a986f891a8e018383f0623 | romulovieira777/22-Tabuada | /22_Tabuada.py | 347 | 3.890625 | 4 | num = int(input())
if num >0:
print(num,"X 1 =",num*1)
print(num,"X 2 =",num*2)
print(num,"X 3 =",num*3)
print(num,"X 4 =",num*4)
print(num,"X 5 =",num*5)
print(num,"X 6 =",num*6)
print(num,"X 7 =",num*7)
print(num,"X 8 =",num*8)
print(num,"X 9 =",num*9)
else:
print("Digite umm... |
bfedfb21b838cea44a4a0b10bad1292b8811cf1b | yuvakurakula/BFS-1 | /BinaryTreeRightSideView.py | 865 | 3.953125 | 4 | # Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
# Time Complexity - O(n)
# Space Complexity - O(n)
class Solution(object):
def rightSideView(self, root):
""... |
eae72e8c8f644a7110c968edec9de9995b19d8f4 | ander758/HackerRank | /algorithms/Warmup/time-conversion.py | 660 | 3.65625 | 4 | from random import randrange
"""
www.hackerrank.com/challenges/time-conversion
github.com/ander758/HackerRank
Convert AM/PM to 24hr format
input= '12:01:00PM' -> output= 12:01:00
input= '12:01:00AM' -> output= 00:01:00
hackerrank.com/challenges/time-conversion/
"""
def timeConversion(s):
hh = s[:-8]
if '... |
4842cc9deec13fd4a163ca6efb867329696dc080 | ander758/HackerRank | /python/strings/alphabet-rangoli.py | 1,858 | 3.5 | 4 | import string
# TODO: Fix testcase 0, 4 and 4
"""
www.hackerrank.com/challenges/alphabet-rangoli/
github.com/ander758/HackerRank
"""
def print_rangoli(size):
arr = []
for i in range(size - 1, 0, -1):
indices = ''
for k in range(size - i):
indices += str(k)
arr.append(ind... |
5eba92dce908737a6b5bd72c2215e19b61eb5611 | ander758/HackerRank | /python/Built-Ins/any-or-all.py | 290 | 3.890625 | 4 | """
www.hackerrank.com/challenges/any-or-all
github.com/ander758/HackerRank
Check if all are positive and if any int is palindrome
"""
arr = ['12', '9', '61', '5', '14', '121']
if all([int(i) > 0 for i in arr]) and any([j == j[::-1] for j in arr]):
print(True)
else:
print(False)
|
0e5e1075fdaa03a13f7d727b27a486065917b0dd | ander758/HackerRank | /python/Basic-Data-Types/python-lists.py | 779 | 4.03125 | 4 | """
https://www.hackerrank.com/challenges/python-lists/problem
github.com/ander758/HackerRank
"""
arr = []
inputs = ['12', 'insert 0 5', 'insert 1 10', 'insert 0 6',
'print', 'remove 6', 'append 9', 'append 1',
'sort', 'print', 'pop', 'reverse', 'print']
for _input in inputs[1:]:
_input = _i... |
090ade52c6e8e4d1dc6ba9e5717456cf7b2da7bc | ander758/HackerRank | /algorithms/Warmup/a-very-big-sum.py | 344 | 3.703125 | 4 | """
www.hackerrank.com/challenges/a-very-big-sum
github.com/ander758/HackerRank
input=
5
1000000001 1000000002 1000000003 1000000004 1000000005
output=
5000000015
"""
def calculate_sum(arr):
return sum(arr)
if __name__ == '__main__':
arr = [1000000001, 1000000002, 1000000003, 1000000004, 1000000005]
pr... |
cbc42ea56b2b003962ec592d66d71e81d3ef4e54 | ander758/HackerRank | /python/strings/whats-your-name.py | 293 | 3.640625 | 4 | """
www.hackerrank.com/challenges/whats-your-name
github.com/ander758/HackerRank
"""
def print_full_name(a, b):
print(f'Hello {a} {b}! You just delved into python.')
if __name__ == '__main__':
first_name = 'Ross'
last_name = 'Taylor'
print_full_name(first_name, last_name)
|
36df5a77ef30f27fbd6fa1891f6ac21c1a47a508 | AnupreetMishra/overload-constructor-method-in-python | /main.py | 224 | 3.828125 | 4 | class student:
def __init__(self,name):
self.name = name
def __init__(self,name,email):
self.name = name
self.email = email
st=student("anu","anu@gmail.com")
print("Name:",st.name)
print("Email id:",st.email) |
c7ee04d2b9ccb3f32a3bbd02db9182cf03fabe22 | move-z/adventofcode2015 | /src/24_it_hangs_in_the_balance.py | 1,222 | 3.59375 | 4 | #!/usr/bin/env python3
import itertools
import operator
from functools import reduce
def first(*packages):
group_weight = sum(packages) // 3
i = 2
while True:
legs = itertools.combinations(packages, i)
legs = [l for l in legs if sum(l) == group_weight]
if not legs:
i ... |
92b02c4fdfb9e43b8f562c00f54acb00f96acbc6 | Tygrak/ultimate-ttt | /analyzer.py | 3,199 | 3.59375 | 4 | import matplotlib.pyplot as plt
class Result:
def __init__(self, player1Iters, player2Iters, gameResult, gameTurns):
self.player1Iters = player1Iters
self.player2Iters = player2Iters
self.gameResult = gameResult
self.gameTurns = gameTurns
def getResultsWhere(results, player1Iters, ... |
636aae44bd5c23edc5cab659259f947e74568475 | hxiaoCS/Tic_tac_toe | /tic_tac_toe.py | 4,127 | 4.03125 | 4 | # Han X Sep 10, 2018
import random
def show_board(board):
print(' ' + board[1] + ' | ' + board[2] + ' | ' + board[3])
print('-----------')
print(' ' + board[4] + ' | ' + board[5] + ' | ' + board[6])
print('-----------')
print(' ' + board[7] + ' | ' + board[8] + ' | ' + board[9])
de... |
feb9196def87097e224ad8861dc5d1a22349d620 | karafont/Python-Programs | /6.9 Average Revised.py | 634 | 3.953125 | 4 | def main():
try:
numFile = open( "numbers.txt", "r")
total = 0
numLines = 0
line = numFile.readline()
while line != "":
numLines += 1
total += int( line )
line = numFile.readline()
average = total / numLines
except I... |
07cf3429ae0a0ee1fb08c0e35683c1b5136a51d1 | karafont/Python-Programs | /6.11.py | 553 | 3.53125 | 4 | def getName():
userName = input ( "Enter your name: " )
return userName
def getBio():
userBio = input ( "Please enter a sentence or two that describes yourself: " )
return userBio
def webPage(userName, userBio):
web = "biopage.html"
openFile = open(web, "w+")
openFile.write("<html>\n<head>\n</head>\n... |
fdcacaa7aeeb599c8a687dcec37c3d7fd0a0e84f | Aleksandr848/Lesson_08 | /ex_07.py | 746 | 3.75 | 4 | class ComplexNumber:
def __init__(self, a, bi):
self.a = a
self.bi = bi
def __add__(self, other):
if (self.a * other.bi + self.bi * other.a) >= 0:
i = 1
sign = '+'
else:
i = -1
sign = '-'
return f'{self.a + other.a} {sign} ... |
6ca26100985fc23524b13578e97cde54a42f2f70 | twhay/Python-Scripts | /Dice Simulator.py | 509 | 4.21875 | 4 | # Python Exercise - Random Number Generation - Dice Generator
# Import numpy as np
import numpy as np
# Set the seed
np.random.seed(123)
# Generate and print random float
r = np.random.rand()
print(r)
# Use randint() to simulate a dice
dice = np.random.randint(1,7)
print(dice)
# Starting step
step = 50
# Finish th... |
668b2b0125f1e07583c840c4f509feaec4cedad4 | RodrigoWasp/Ejercicios-b-sicos-de-python | /16funcional.py | 465 | 3.921875 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
def lower(elementos): return elementos.lower()
lista = ["RoDRiGo", "jUaN","dIEgO"]
print(list(map(lower,lista)))
print([cad.lower() for cad in lista])
def saludo(idioma):
def saludo_es():
print("hola")
def saludo_en():
print("hello")
idioma_fu... |
83e67752058183d09db98ca170c444d0419060c1 | RodrigoWasp/Ejercicios-b-sicos-de-python | /14iteracion.py | 336 | 3.5 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
archivo = open("texto.txt","r")
for linea in archivo:
print(linea)
"""
#iteracion sencilla y facil de entender
#generadores
def numeros():
n = 1
while True:
yield n
n = n+1
i = numeros()
print(i)
print(i.__next__())
print(i.__next__())
prin... |
a670aed50a81c8b1105df77588a54b101effae82 | mstoiovici/module3 | /ch4_Unit_testing/test_is_prime.py | 1,935 | 3.8125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon Jan 28 10:41:51 2019
@author: maria
"""
"""
import unittest
from is_prime import is_prime
class PrimesTest(unittest.TestCase):
def test_prime_float(self):
self.assertTrue(is_prime(4))
if __name__=="__main__":
unittest.main()
"""
"""
import unittest
fr... |
07862aaad9dac66496a01b75681423a436c2a57d | minhthe/practice-algorithms-and-data-structures | /Contest/176/01_bs.py | 343 | 3.53125 | 4 | '''
https://leetcode.com/problems/count-negative-numbers-in-a-sorted-matrix
'''
import bisect
class Solution(object):
def countNegatives(self, grid):
m = len(grid)
if m==0: return 0
n = len(grid[0])
if n== 0: return 0
cnt = 0
for arr in grid:
arr.reverse()
pos = bisect.bisect_left(arr, 0, 0, n)
... |
9387744811c15326ce6ea1f91ebfeaf56931dabd | minhthe/practice-algorithms-and-data-structures | /BST/print_Inorder.py | 574 | 3.84375 | 4 | '''
https://leetcode.com/problems/binary-tree-inorder-traversal/
All 3 ways:
iteration
recurison
not 2 above
'''
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def inorderTraversa... |
057c9ff2ee6ac63f6696a9106356cc285ae6af57 | minhthe/practice-algorithms-and-data-structures | /pramp-condility-3month/odd-even-linked-list.py | 548 | 3.84375 | 4 | '''
https://leetcode.com/problems/odd-even-linked-list/
'''
class Solution:
def oddEvenList(self, head: ListNode) -> ListNode:
if head is None: return head
odd = head
even = None
if head.next: even = head.next
fix_even = even
while odd and even:
if odd.next:
odd.next = odd.next.next
if odd.next:... |
aae9b504c3c712f526fa4ef16d04104d938aeee6 | minhthe/practice-algorithms-and-data-structures | /PomodoroPractice/plusOne_3Recursion.py | 415 | 3.5625 | 4 | '''
https://leetcode.com/problems/plus-one/
'''
class Solution:
def plusOne(self, digits: List[int]) -> List[int]:
if digits[-1] < 9:
digits[-1] +=1
return digits
else:
def f(pos):
if pos == -1:
return [1] + digits
if digits[pos] < 9:
digits[pos] += 1
return digits
else:
... |
0afc09a819f4123dabcf8c28b93c989b66c56bf8 | minhthe/practice-algorithms-and-data-structures | /String/group-anagram.py | 461 | 3.65625 | 4 | '''
https://leetcode.com/problems/group-anagrams/
'''
class Solution(object):
def groupAnagrams(self, strs):
"""
:type strs: List[str]
:rtype: List[List[str]]
"""
rst = []
mp = {}
for item in strs:
tmp = ''.join(sorted(item))
mp[tmp] = ... |
3f93f293501e07a991a381612a74e8edc3bcbd25 | minhthe/practice-algorithms-and-data-structures | /PomodoroPractice/reverseWordInStr03.py | 337 | 3.734375 | 4 | '''
https://leetcode.com/problems/reverse-words-in-a-string
'''
class Solution:
def reverseWords(self, s: str) -> str:
ss = list(item for item in s.split(" ") if len(item)>0)
i, j= 0 , len(ss)-1
while(i < j):
ss[i], ss[j] = ss[j],ss[i]
i+=1
j-=1
re... |
33bac61afdc51d8fc2d76e1bdc103ec6c364db67 | minhthe/practice-algorithms-and-data-structures | /pramp-condility-3month/pramp_bucket_sort.py | 1,240 | 3.546875 | 4 | '''https://www.pramp.com/challenge/W5EJq2Jld3t2ny9jyZXG'''
def word_count_engine(document):
pass # your code goes here
def convert(s):
tmp = ""
for c in s:
if ord('a') <= ord(c) <= ord('z'): tmp+=c
return tmp
words = document.split(" ")
mp = {}
max_v = 0
setences = []
for i, w... |
dd1cf09aad517f209a6024fc0051effb3eb79290 | minhthe/practice-algorithms-and-data-structures | /Explore/May 31 days/08_theLine.py | 715 | 3.640625 | 4 | '''
https://leetcode.com/problems/check-if-it-is-a-straight-line/
[[1,2],[2,3],[3,4],[4,5],[5,6],[6,7]]
[[1,1],[2,2],[3,4],[4,5],[5,6],[7,7]]
[[-7,-3],[-7,-1],[-2,-2],[0,-8],[2,-2],[5,-6],[5,-5],[1,7]]
***careful with edge case: 0
'''
class Solution:
def checkStraightLine(self, coordinates: List[List[int]]) -> bool:... |
4d9272e8f8205106a43fbfc26115cda9836739d1 | minhthe/practice-algorithms-and-data-structures | /String/valid_email.py | 416 | 3.53125 | 4 | '''https://leetcode.com/problems/unique-email-addresses'''
class Solution:
def numUniqueEmails(self, emails: List[str]) -> int:
rst = []
def convert(s):
tmp = ""
p1,p2 = s.split("@")
for c in p1:
if c == "+":
return tmp + "@" + p2
if c == ".":
continue
tmp += c
return t... |
8e30aabe7c23c8904abe94415b1a9ed5439af94f | minhthe/practice-algorithms-and-data-structures | /Contest-Biweekly/29/03_longestSubdel1.py | 850 | 3.53125 | 4 | '''
https://leetcode.com/problems/longest-subarray-of-1s-after-deleting-one-element/
'''
class Solution:
def longestSubarray(self, nums: List[int]) -> int:
#[1,1,0,0,1,1,1,0,1]
mp = {}
n = len(nums)
k = len([x for x in nums if x == 1])
if k == n :return n -1
... |
cd1433d8468f3a5927b65e8953473f142aea23b3 | minhthe/practice-algorithms-and-data-structures | /PomodoroPractice/bst_traversal_order7.py | 526 | 3.703125 | 4 | '''
https://leetcode.com/problems/binary-tree-level-order-traversal-ii/
'''
import collections
class Solution:
def levelOrderBottom(self, root: TreeNode) -> List[List[int]]:
if root is None: return []
mp = collections.defaultdict(list)
rst = []
def f(root, level):
mp[level].append(root.val)
if root.left:... |
6a25893986809e8a5df20205685c910a06d07ce6 | minhthe/practice-algorithms-and-data-structures | /Explore/August 31 days/26_min_ticket.py | 872 | 3.6875 | 4 | '''https://leetcode.com/problems/minimum-cost-for-tickets/'''
class Solution:
def mincostTickets(self, days: List[int], costs: List[int]) -> int:
memo = {}
def f(pos):
if pos >= len(days):
# memo[(pos,d)] = 0
return 0
if pos in memo: ... |
efe4593a38964eb0b1edfb45dc55c9e1ef5d9892 | minhthe/practice-algorithms-and-data-structures | /Binary Search/find_range.py | 431 | 3.578125 | 4 | '''
https://leetcode.com/problems/find-first-and-last-position-of-element-in-sorted-array/
'''
import bisect
class Solution:
def searchRange(self, nums: List[int], target: int) -> List[int]:
if len(nums) == 0 :return [-1,-1]
a, b = bisect.bisect_left(nums, target), bisect.bisect_left(nums, target+... |
316f61889ced6a3d53f18e81600de9d5148d008f | minhthe/practice-algorithms-and-data-structures | /pramp-condility-3month/pivot-sum.py | 595 | 3.5625 | 4 | '''
https://leetcode.com/problems/find-pivot-index/
'''
class Solution:
def pivotIndex(self, nums: List[int]) -> int:
idx = -1
n = len(nums)
left, right = [0]*(n+2),[0]*(n+2)
for i,item in enumerate(nums):
left[i+1] = left[i] + item
for i in range(n-1, -1, - 1):
... |
5aa9a51967a41056925a668268bcbc66c919c357 | minhthe/practice-algorithms-and-data-structures | /PomodoroPractice/searchSuggestion7.py | 402 | 3.5 | 4 | '''
https://leetcode.com/problems/search-suggestions-system
'''
import bisect
class Solution:
def suggestedProducts(self, products: List[str], searchWord: str) -> List[List[str]]:
products.sort()
rst = []
tmp = ""
for c in searchWord:
tmp += c
pos = bisect.bisect_left(products, tmp)
rst.appe... |
f6cf3f531ce48d776c43e21b2053abc5a60def34 | minhthe/practice-algorithms-and-data-structures | /Sorting/insertion-sort.py | 325 | 4.0625 | 4 | def insertion_sort(a):
for i in range(1, len(a)): # [7,2,4,1,5,3] -> [2,7,4,1,5,3]
key = a[i] # 2
j = i - 1 # 0
while j >=0 and a[j] > key:
a[j+1] = a[j]
j -= 1
a[j+1] = key
return a
if __name__ == "__main__":
a = [7,2,4,1,5,3]
print('before', a)
a = insertion_sort(a)
print('after... |
4597874db6fe072119eacd6a70b671f2fac13d5c | minhthe/practice-algorithms-and-data-structures | /Greedy/min_operation_root_arr.py | 379 | 3.515625 | 4 | '''https://leetcode.com/problems/minimum-numbers-of-function-calls-to-make-target-array/'''
class Solution:
def minOperations(self, nums: List[int]) -> int:
s = 0
while(sum(nums) != 0):
odd = False
for i,v in enumerate(nums):
if v & 1:
odd = True
s+=1
nums[i] = v - 1
if not odd :
... |
51730d3c9dc996060272482d937d62c156c9c25a | minhthe/practice-algorithms-and-data-structures | /Binary Search/imp_sqrt.py | 554 | 3.703125 | 4 | '''
https://leetcode.com/problems/sqrtx/
2 importance points:
1) initilize array A will be TLE with x greater 1e9
2) if in edge case l = 0 or l = 1 -> return that value
'''
class Solution:
def mySqrt(self, x: int) -> int:
# a = [i for i in range(0, int(x/2) + 1)]
l , r = 0, int(x/2)
... |
951764df6c632f6de6354ea666ff6ae4ea8ecb28 | minhthe/practice-algorithms-and-data-structures | /String/permutation-palindrome.py | 636 | 3.8125 | 4 | '''
https://www.hackerearth.com/problem/algorithm/palindrome-check-2-1/description/
'''
'''
# Sample code to perform I/O:
name = input() # Reading input from STDIN
print('Hi, %s.' % name) # Writing output to STDOUT
# Warning: Printing unwanted or ill-formatted data to output will cause the t... |
3a11bc84f2878105f2c00e3d3613d8571c2cc263 | minhthe/practice-algorithms-and-data-structures | /BST/traversal-order.py | 512 | 3.640625 | 4 | '''
https://leetcode.com/problems/binary-tree-level-order-traversal/
'''
from collections import deque
from collections import defaultdict
class Solution:
def levelOrder(self, root: TreeNode) -> List[List[int]]:
if root is None: return []
mp = defaultdict(list)
def f():
stk = deque([(root, 0 )])
while(l... |
8b53764ff853bb46a3be4b4bba016f20b2b30b07 | minhthe/practice-algorithms-and-data-structures | /PomodoroPractice/palindrome-1.py | 484 | 3.671875 | 4 | '''
https://leetcode.com/problems/valid-palindrome
'''
class Solution:
def isPalindrome(self, s: str) -> bool:
i , j = 0 , len(s) - 1
def violate(c):
if ord('a') <= ord(c) <= ord('z') or ord('A') <= ord(c) <= ord('Z') or ord('0') <= ord(c) <= ord('9'):
return False
return True
while i < j :
i... |
9cba083da762cb9e86edfa6a8bfda097d797684b | minhthe/practice-algorithms-and-data-structures | /DP_Pattern2/01_recursion-unique-paths.py | 637 | 3.734375 | 4 | '''
https://leetcode.com/problems/unique-paths
Using DFS Recursion + memo to AC
***next level:
https://leetcode.com/problems/unique-paths-ii/
'''
def dfs(i,j, m,n, memo):
if(i == m -1 and j == n-1):
return 1
if (i,j) in memo:
return memo[(i,j)]
if(i in range(m) and j in range(n)):
... |
c5d1cc77ac3196f665f5f896df9275d8bf7e2cf8 | minhthe/practice-algorithms-and-data-structures | /pramp-condility-3month/insertion-sort-2.py | 260 | 3.921875 | 4 | def insertion_sort(a):
for i in range(1, len(a)):
current = a[i]
j = i - 1
while j >=0 and a[j] > current:
a[j+1] = a[j]
j-= 1
a[j+1] = current
return a
if __name__ =='__main__':
a = [6,3,9,1,23,8]
print(a)
insertion_sort(a)
print(a) |
b8b0ad49ba4f0c0f67fb60100aa96cb7a2841c87 | minhthe/practice-algorithms-and-data-structures | /Contest-Biweekly/29/01_averageSalary.py | 282 | 3.671875 | 4 | '''
https://leetcode.com/problems/average-salary-excluding-the-minimum-and-maximum-salary/
'''
class Solution:
def average(self, salary: List[int]) -> float:
n = len(salary)
u, v = min(salary), max(salary)
return ( sum(salary) - u - v) / (n -2) |
3a570973978bf56d1b370e069f6394c25ffa6856 | minhthe/practice-algorithms-and-data-structures | /pramp-condility-3month/bst-build-inorder-preorder.py | 603 | 3.546875 | 4 | '''
https://leetcode.com/problems/construct-binary-tree-from-preorder-and-inorder-traversal
'''
class Solution:
def buildTree(self, preorder: List[int], inorder: List[int]) -> TreeNode:
mp={inorder[i]:i for i in range(len(inorder))}
left, right = 0 , len(preorder) - 1
idx = [0]
def buildBS(left , right):
if... |
ec28544be6ec29f958e41dfdd4d6dde43f8187bb | minhthe/practice-algorithms-and-data-structures | /PomodoroPractice/bst_traversal_last3.py | 884 | 3.765625 | 4 | '''
https://leetcode.com/problems/binary-tree-level-order-traversal-ii
'''
from collections import defaultdict
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
... |
361da5fd12c5ec64b7bbf77915aec8c0f15764eb | minhthe/practice-algorithms-and-data-structures | /Easy/candies_01.py | 423 | 3.53125 | 4 | '''https://leetcode.com/problems/distribute-candies-to-people'''
class Solution:
def distributeCandies(self, candies: int, num_people: int) -> List[int]:
n = num_people
arr = [0] * (n)
t = 0
k = 0
while(candies > 0):
for i,v in enumerate(arr):
t = (i+1) + k*(n)
if candies > t:
arr[i] = t + ... |
d80e9bd88818edfd7b8d796ba1d3cc4f7585571e | minhthe/practice-algorithms-and-data-structures | /PomodoroPractice/narray-tree-traversal07.py | 413 | 3.640625 | 4 | ''''
https://leetcode.com/problems/n-ary-tree-level-order-traversal/
'''
class Solution:
def levelOrder(self, root: 'Node') -> List[List[int]]:
if root is None: return []
rst = []
traversal = [root]
while( traversal):
curr , next = [], []
for node in traversal:
curr.append(node.val)
for child in ... |
0e7599fc6cbbef182f11567a649da83c1e4284d1 | minhthe/practice-algorithms-and-data-structures | /PomodoroPractice/bst_order_traversal3.py | 517 | 3.703125 | 4 | '''
https://leetcode.com/problems/binary-tree-level-order-traversal/
'''
import collections
class Solution:
def levelOrder(self, root: TreeNode) -> List[List[int]]:
if root is None: return []
mp = collections.defaultdict(list)
def f(root):
deque = [(root,0)]
deque = collections.deque(deque)
while(... |
df634baf21b6b314128cce1c3cbb17e5118cf0af | minhthe/practice-algorithms-and-data-structures | /Linked List/reverse-ll-ii.py | 1,025 | 3.90625 | 4 | '''
https://leetcode.com/problems/reverse-linked-list-ii/
'''
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def reverseBetween(self, head: ListNode, m: int, n: int) -> ListNode:
l = n - ... |
24b51e16c7daa8e3bfb6cb1e2c3357b9c8bf35fd | minhthe/practice-algorithms-and-data-structures | /Explore/September 30 days/05_merge_2bst.py | 1,020 | 3.796875 | 4 | '''https://leetcode.com/problems/all-elements-in-two-binary-search-trees'''
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def getAllElements(self, root1: ... |
16668ad33dd3bea4493a803899fb323f2e37fe5e | minhthe/practice-algorithms-and-data-structures | /Binary Search/invert-binary-tree.py | 273 | 3.6875 | 4 | '''
https://leetcode.com/problems/invert-binary-tree/
'''
class Solution:
def invertTree(self, root: TreeNode) -> TreeNode:
if root is None: return None
ll = root.left
rr = root.right
root.left = self.invertTree(rr)
root.right = self.invertTree(ll)
return root |
9a0ba032bb7f524d5e47991b41eb73627a4e4cf7 | minhthe/practice-algorithms-and-data-structures | /Easy/happyNumber1.py | 1,369 | 3.59375 | 4 | '''
https://leetcode.com/problems/happy-number/
approach: hash + recursion
*** learn more:
1) not using the power 2
https://leetcode.com/problems/happy-number/discuss/445373/Python-Dictionary-and-Set-beat-99-time-and-100-space
def isHappy(self, n: int) -> bool:
dict = {'0':0,'1':1,'2':4,'3':9,'4':16,'5':2... |
353aad15ade0fedd85346dd9005ee88fa015dbfd | minhthe/practice-algorithms-and-data-structures | /pramp-condility-3month/bst-print-order-vertical.py | 670 | 3.6875 | 4 | '''https://leetcode.com/problems/vertical-order-traversal-of-a-binary-tree'''
class Solution:
def verticalTraversal(self, root: TreeNode) -> List[List[int]]:
if not root: return []
mp = {}
rst = []
stk = [(root,0, 0 )]
while(stk):
u , v , y = stk.pop()
if v not in mp:
mp[v] = [(-y,u.val)]
heap... |
2fcdf4cc744ca22c32b131903089d004780ac982 | minhthe/practice-algorithms-and-data-structures | /Explore/May 31 days/20_sortChar.py | 438 | 3.5625 | 4 | '''
https://leetcode.com/problems/sort-characters-by-frequency/
'''
class Solution:
def frequencySort(self, s: str) -> str:
mp = {}
for e in s:
if e not in mp:
mp[e] = [1, ord(e) * (-1)]
else:
mp[e][0] += 1
rst = []
# print(mp)
for item in sorted(mp.items(), key = lambda x : x[1], reverse = Tr... |
e37867950ca7a03afeb884937e6044af240335d7 | minhthe/practice-algorithms-and-data-structures | /BST/n-arr-preorder.py | 286 | 3.53125 | 4 | '''
https://leetcode.com/problems/n-ary-tree-preorder-traversal
'''
class Solution:
def preorder(self, root: 'Node') -> List[int]:
if root is None: return []
rst = []
def f(root):
rst.append(root.val)
for child in root.children:
f(child)
return rst
return f(root) |
d7d9c9ec7b7608339fd19446c800152276f2b9c4 | minhthe/practice-algorithms-and-data-structures | /Contest/187/01_des2.py | 587 | 3.734375 | 4 | '''
https://leetcode.com/problems/destination-city/
Time Complexity : O(n)
Space Complexity : O(n)
'''
class Solution:
def destCity(self, paths: List[List[str]]) -> str:
des = {}
root = {}
for item in paths:
start, end = item[0], item[1]
root[start] = True
if start in des: # ... |
b4fe044a7edae41608633455bc942e2a742497ff | minhthe/practice-algorithms-and-data-structures | /Glider.AI/Algo/string_all_permutation.py | 776 | 3.796875 | 4 | '''https://app.glider.ai/practice/problem/algorithms/generate-all-permutations-of-a-string/problem'''
# Note: Proper indentation is required
# Click HELP above to see examples of handling input/debug/output
# INPUT: n = input()
# DEBUG: print(n)
# OUTPUT: print(result)
# Write the code to solve the problem below,... |
cc28457fc49b60f349e3b72b9d4cfcbc5c6b7bad | minhthe/practice-algorithms-and-data-structures | /Explore/June 30 days/21_longestDupSubstring_TLE.py | 430 | 3.671875 | 4 | '''
https://leetcode.com/problems/longest-duplicate-substring/
'''
class Solution:
def longestDupSubstring(self, S: str) -> str:
l = len(S)
mp = {}
def f(k):
hs = {}
for i in range(l-k+1):
tmp = S[i:i+k+1]
# print(tmp)
if tmp in hs:
return True, tmp
else:
hs[tmp] = True
re... |
8cd58c0999fb10547bf954248e07e04c9d30a2e2 | minhthe/practice-algorithms-and-data-structures | /Binary Search/bs_simple.py | 452 | 3.53125 | 4 | '''
https://leetcode.com/problems/binary-search/
Time Complextiy: O(log(n))
Space Complexity: O(1)
'''
class Solution:
def search(self, nums: List[int], target: int) -> int:
l , r = 0 , len(nums)-1
while(l<=r):
mid = int ((r -l)/2 + l)
if(nums[mid] == target): ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.