blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
679d2384682fa2692bab0d2257747e983b2fd3d7
Nikhil14091997/Code-File
/Cracking the Coding Interview/Linked List/palindrome.py
2,205
4.21875
4
# Check a list for palindrome class Node: def __init__(self, data): self.data = data self.next = None class LinkedList: def __init__(self): self.head = None def printList(llist): print("Inside PrintList function:") head = llist.head while head is not None: ...
786c5018ae8d868f8ca6f7ef8b6c0a6acf82fa24
Ilya-Belyanov/Algorithms
/src/alg/greedy.py
509
3.859375
4
def max_activities(activities: list) -> list: """ Input: activities: list of time of activities in format [start_time (int), end_time (int)] Output: list with max count of activities without intersections """ activities.sort(key=lambda x: x[1]) max_size_activities = [activities...
36bb5860c26fa0fc7f2c652728da3bec9e04c233
pilambdagammarho/Anomaly-Detection-Benchmarking
/routine/recorder.py
2,715
3.53125
4
import os import time import matplotlib.pyplot as plt import numpy as np from sklearn.metrics import f1_score, precision_score, recall_score class Record(): """ This class records and stores the loss and metric value across the training and evaluation cycles. Further, this class prints and plots training...
242c93ef71b40da1b87e63be796a9784a6b63246
zabojnikp/study
/Python_Projects/python2_pyladies/handout2.py
800
3.96875
4
from random import randrange tahy = ['kamen', 'nuzky', 'papir'] tah_pocitace = tahy[randrange(3)] tah_cloveka = input("kamen,nuzky nebo papir?") print('pocitac vybral', tah_pocitace) if tah_cloveka == tah_pocitace: print('stejne hodnoty') elif tah_cloveka == "kamen" and tah_pocitace =='nuzky': print('clovek...
5705b6d5a66d3cf83ade8f9bb55b2be7e7af4df5
zabojnikp/study
/Python_Projects/python2_pyladies/vyjimky.py
624
3.703125
4
## -*- coding: utf-8 -*- while True: try: strana = float(input('Zadej stranu čtverce v centimetrech: ')) except NameError: print('To nebylo číslo!') else: if strana <= 0: print('To nedává smysl!') else: break print('Obvod čtverce se stranou', strana, ...
b39e8a50fad2eac2dd7b776a79f9ae29dcaf0c17
zabojnikp/study
/Python_Projects/python2_pyladies/cyklus.py
359
3.921875
4
for cislo in range(5): print(cislo) for pozdrav in 'Ahoj', 'Hello', 'Hola', 'Hei', 'SYN': print(pozdrav + '!') soucet = 1 for cislo in 8, 45, 9, 21: soucet = soucet + cislo print(soucet) from turtle import forward, left, exitonclick, penup, pendown for i in range (20): forward(i) penup() fo...
f1b43588bac1a699cec274b27e0d0701a8617f30
zabojnikp/study
/Python_Projects/hackathon_Brno/beginner/1_prime_number.py
767
3.84375
4
prime_numbers = [] def get_integer(): try: user_input = input("Input any number: ") number = int(user_input) except ValueError as err: print("Error!", err) return number def is_prime(value): if value > 1: for i in range(2, value): if (value % i) == 0: ...
508ba4e4a14b2f6bd9e80e88b0806926af048d9e
zabojnikp/study
/Python_Projects/python3_selfstudy/lekce_6/practice_1.py
412
3.78125
4
class MyDict(dict): pass d = MyDict.fromkeys("VEINS", 3) print(str(d)) #vraci seznam def letter_range_1(a, z): result = [] while ord(a) < ord(z): result.append(a) a = chr(ord(a) + 1) return result print(letter_range_1("m", "v")) #vraci generator def letter_range_2(a, z): while ord(a) ...
934701b17be23bff819a44eb3f340681a6907326
hikkymouse1007/algorithm_and_data_structures_in_python
/code/leetcode/revers_int.py
556
4.03125
4
from typing import List def reverse(x: int) -> int: """ :type x: int :rtype: int """ sign = [1,-1][x < 0] # xが0より小さければ-1を代入 https://stackoverflow.com/questions/55917667/please-explain-1-1x-0 rst = sign * int(str(abs(x))[::-1]) # [::-1]:文字列の反転 abs(x): 絶対値 print(rst, -(2**31)-1 < rst < 2**...
66449ad03218d80be0df062ebab91a6036d9aeaa
SebastianCalle/holbertonschool-higher_level_programming
/0x0B-python-input_output/2-read_lines.py
436
3.984375
4
#!/usr/bin/python3 """Funtion that read n lines of a text file""" def read_lines(filename="", nb_lines=0): """Funtion that read n lines of a text file""" i = 0 with open(filename, 'r', encoding='utf-8') as f: if nb_lines <= 0: data = f.read() print(data, end="") els...
02746ba2849a7148bfd5d888e9f40c4d5eed8816
SebastianCalle/holbertonschool-higher_level_programming
/0x04-python-more_data_structures/9-multiply_by_2.py
233
3.96875
4
#!/usr/bin/python3 # function that returns a new dictionary whit all values mul by 2 def multiply_by_2(a_dictionary): new_dic = a_dictionary.copy() for n, i in new_dic.items(): new_dic[n] = i * 2 return new_dic
ba7201d7910c6d7c2429003727a0e4977a6b8342
SebastianCalle/holbertonschool-higher_level_programming
/0x02-python-import_modules/100-my_calculator.py
770
3.796875
4
#!/usr/bin/python3 from sys import argv from calculator_1 import add, sub, mul, div if __name__ == '__main__': if (len(argv) != 4): print("./100-my_calculator.py <a> <operator> <b>") exit(1) op = argv[2] if (op != '+' and op != '-' and op != '*' and op != '/'): print("Unknown operat...
901e2dc131c1abc57417c6c6b668f3aea2527849
SebastianCalle/holbertonschool-higher_level_programming
/0x0C-python-almost_a_circle/models/square.py
1,926
3.640625
4
#!/usr/bin/python3 """ import models """ from .rectangle import Rectangle class Square(Rectangle): """ Class Square """ def __init__(self, size, x=0, y=0, id=None): """ Initializate attributes """ super().__init__(id=id, x=x, y=y, width=size, height=size) self....
8da4ce94776ec4ca2e1e41ff8ffb783c92d83d30
SebastianCalle/holbertonschool-higher_level_programming
/0x04-python-more_data_structures/102-complex_delete.py
362
4.0625
4
#!/usr/bin/python3 # function that deletes keys with a specific value in a dictionary def complex_delete(a_dictionary, value): list_del = [] for key, val in a_dictionary.items(): if val == value: list_del.append(key) for key in list_del: if key in a_dictionary: del ...
f6323afe2b03e52b7c8040c4527be7793fb72586
S-P-E-C-T-R-3/Python-Projects
/04. Pizza Order/Pizza.py
478
4.0625
4
size=input("Enter size:: S, M or L :") add_pepperoni=input("Do you want pepproni? Y or N:") extra_cheese=input("Do you want extra cheese? Y or N:") bill=0 if size=='S': bill +=15 elif size=='M': bill +=20 elif size=='L': bill +=25 elif add_pepperoni == 'Y' and size == 'S': bill +=2 else: bill +=3 "...
44301225e34556b29b5c16630390ed579a2898ca
knight-apple/Proxies-Get
/QueueCount.py
1,249
3.765625
4
import threading import time import datetime import queue from random import randint class WaitQueue(threading.Thread): def __init__(self, countq): threading.Thread.__init__(self) self.q = countq def run(self): strsize = -1 maxn = self.q.qsize() + 1 cnt ...
ccc48aec14bf202b365bbe78c6dd0bf854fee38d
sherlynpw/Bootcamp-Assigment1
/no3.py
1,496
3.84375
4
class Lift: def __init__(self, enterPeople: int, currentFloor: int, destinationFloor: int, maxPeople = 11, maxFloor = 18): self.enterPeople = enterPeople self.currentFloor = currentFloor self.maxPeople = maxPeople self.destinationFloor = destinationFloor self.maxFloor = maxFl...
0c75a1b501890223a87801f84a3bbcceedc04930
Vikas-viky/Pyml
/BINA.PY
2,729
3.8125
4
# Python code explaining how to Binarize feature values #Importing Libraries import pandas as pd #Importing Data data_set = pd.read_csv('data.csv') print(data_set.head()) age = data_set.iloc[:, 1].values salary = data_set.iloc[:, 2].values print ("\nOriginal age data values : \n", age) print ("\nOrigi...
09a4ec742fd9accc595ac07245b72a1c0eab70a2
faro93/MindGames
/001.py
318
3.625
4
# coding utf-8 import time start_time = time.time() sum = 0 for i in range(1000): if i%3 == 0: print(f'{i} est multiple de 3') sum += i elif i%5 == 0: print(f'{i} est multiple de 5') sum += i print(f'Somme={sum} ') print(f'Durée d\'exécution = {time.time()-start_time}s ')
ebce1d15dc05f4b889be1646969edc56ed0bff40
Sorosliu1029/PythonChallenge
/PythonChallenge5.py
349
3.5
4
""" use pickle to restore from saved file to get a object. it's a quite convenient way to communicate between programs. """ import pickle from urllib import request with request.urlopen('http://www.pythonchallenge.com/pc/def/banner.p') as f: obj = pickle.load(f) print(obj) for line in obj: print(''.join(item[0]...
96e2a4970365f41f696a50d46e3244b36c661a4e
anttitup/python_huft
/helper.py
2,275
3.859375
4
# -*- coding: utf-8 -*- class Tree: def __init__(self, freq = 0): self.freq = freq def __sub__(self, other): return self.freq - other.freq class Leaf(Tree): def __init__(self,charechter,freq): Tree.__init__(self,freq) self.charecter = charechter class Node(Tree): ...
5dd1f7d6be53a6bcf2dbe0574dffc99db3cc942d
KhairulIzwan/Automate-The-Boring-Stuff-With-Python
/coin_flip_streaks.py
1,136
3.546875
4
from __future__ import division # Python 2.7 import random numberOfStreaks = 0 for experimentNumber in range(10000): # Code that creates a list of 100 'heads' or 'tails' values. # creating the empty-array flippedCoins = [] for i in range(100): flippedCoins.append(random.randint(0, 1)) # print("No: {}, Lis...
e88653077e9cf568b1915c86ab5f16da3e30d6ef
2437surya/python-program
/beginner/oddoreven.py
127
4.125
4
input_num = int(input('Enter any number')) if input_num % 2 == 0: print(input_num "EVEN") else: print(input_num "ODD")
9e803c55914295ff4023318c75f5dd408b1a3d04
ashishamodkar/python_practice
/Type_Function.py
251
3.96875
4
# Write the program to know type of input and add two string and number a = "Ashish " b = "Amodkar" c = 64 d = 57.8 print (type(a) , type(b ), type( c ), type(d )) print(a+b) print(c+d) print("We Can't Write do ADDITION Between STRING And NUMBER")
d221c4e5248c97c76876110cb19f299010235875
ashishamodkar/python_practice
/Type_Cast.py
242
4.03125
4
# Basic Use of Type cast # Basic Use of Type cast a = "Ashish " b = "25" c = 25 print(a+b) print(100*" Ashish Amodkar \n") print(100* str(int(b)+c) ) print(int(b)+c) print("print(int(b)+c) b is string we convert it into int using type cast")
32ccfa8b5f7981172e2f73b7de872d47a49871d1
kathleenphan/election_analysis
/PyPoll.py
912
3.9375
4
import csv import os # Assign a variable for the file to load and the path. file_to_load = '/Users/kathleenphan/Desktop/BOOTCAMP/election-analysis/Resources/election_results.csv' # Open the election results and read the file. election_data = open(file_to_load, 'r') # Close the file. election_data.close() # Open the...
a77debbef67853bcb2493cd67cc3ccdb163a5026
tracine3636/Python-While-Loop-Exampe
/whileloops.py
296
3.5625
4
Python 3.7.0 (v3.7.0:1bf9cc5093, Jun 27 2018, 04:06:47) [MSC v.1914 32 bit (Intel)] on win32 Type "copyright", "credits" or "license()" for more information. >>> // Prints out 0,1,2,3,4 count = 0 while count < 5: print(count) count += 1 // This is the same as count = count + 1
142b1cff7bafe9a0063cca4a103b48ac6eaaf43e
w1sec0d/Python
/metodoRuffini.py
5,185
3.859375
4
print("--- DIVISIÓN SINTÉTICA ----\n") error = False # En caso de error esta variable se vuelve True factorizacionParcial = False grado = int(input("* Ingresa el grado de tu ecuación:")) while(grado <= 0): print("* Porfavor, ingresa un número entero positivo") grado = int(input("* Ingresa el grado de tu ecuaci...
f32c3e779883aa1069c21e867f2bd03d12a63940
w1sec0d/Python
/momentoPython.py
82
3.796875
4
a = -3 if a < 0: print("A es menor a 0") else: print("A no es menor a 0")
2e9cd8ee5070c08bdf2ac8b71937f257fb1b9450
w1sec0d/Python
/pyramid.py
73
3.53125
4
i = 1 text = "" while i <= 5: text += "*" print(text) i += 1
74d0de08389352483d0b347e1bd380e9788a236b
w1sec0d/Python
/freeCode.py
1,379
4.25
4
""" # USO BÁSICO DE PRINT Y VARIABLES age = 17 text = "Carlos David Ramírez Muñoz" print("Hi, my name is \'" + text + "\'\nI am " + str(age) + "\n") print(3 ** 2) # OBTENER INPUT DEL USUARIO a = input("Enter a number:") b = input("Enter another number:") print("* The result is", float(a)+float(b)) # LISTAS BÁSICAS su...
40172363fbd1f97ae81298d29ed86af46ecdabf2
krummja/Apparata
/apparata/node.py
1,736
3.75
4
"""Node of a Graph""" from __future__ import annotations from typing import Any, Dict, List, Optional class Node: """Representation of a graph node. A node must have a unique string ID. It may have a label and a number. Graphs update node degrees as the graph is updated.""" def __init__( ...
cba69bc26387632f2442c0ddd36c8bca52941580
nanma80/pythagorea
/problem_13.10.py
487
3.6875
4
#!/usr/bin/env python from pythagorea import * grid = Grid(90) node0 = Node((0, 0)) for node1 in grid.nodes: for node2 in grid.nodes: if node0 < node1 and node1 < node2: sides = sorted([ node0.distance(node1), node0.distance(node2), node2.distance(node1), ]) if...
8df138d8cf6d39de22f088a7a6fb593f846c1785
salazarbrandon1257/Data-Scraping-and-Analysis-
/Graphs/graph3.py
325
3.65625
4
import matplotlib.pyplot as plt #I used SQL to find the average price per rating for the y values x=[1, 2, 3, 4, 5] y=[35.34, 36.21, 37.19, 33.34, 31.27] plt.bar(x, y, width=0.7, bottom=None, align='center') plt.xlabel('Rating') plt.ylabel('Average Price') plt.title('Average Book Price per rating') plt.show(...
9e17989e08495aa4ba8d0b8ffe24b3ee311c6a59
nikalmus/p-s
/pascal-triangle/pascal-backup.py
723
3.65625
4
def pascalFunc(num): rows = [] for n in range(num): rows.append([]) for i in range(n+1): if i == 0 or i == n: rows[n].append(1) else: rows[n].append(rows[n-1][i-1] + rows[n-1][i]) return rows def pascalGen(num): row = [] fo...
08e3658248a9856222e9ee2ceb45c17c8078e45d
nikalmus/p-s
/probability/khan/not_equally_likely_events/five_coin_flips.py
2,136
3.703125
4
import math def allFairCoinPossibleOutcomes(flips, outcomes_per_flip): return outcomes_per_flip ** flips def calculateFairCoinHeadProbability(flips, event, outcomes): combinations = math.factorial(flips) / (math.factorial(event) * math.factorial(flips - event)) p = combinations / allFairCoinPossibleOutcom...
876b7ff362925491a6034424e353e1bfd4c23c43
andrewcrabtree2000/Pi_Packet_Project
/receiver_files/python_files/receive.py
9,254
3.515625
4
"""LCD Interface for Sending Pi. This module is used for displaying information on the LCD, as well as taking in user input, such as configurations for any packet to send out. This IO is not intrinsically coupled with the rest of the program, so if need be, you can write your own IO interface, and couple it with the b...
5ec8876cf5a5bddd085540761418966806a7935b
Northwestern-CS348/assignment-3-part-2-uninformed-solvers-gradywetherbee
/student_code_game_masters.py
10,887
3.546875
4
from game_master import GameMaster from read import * from util import * class TowerOfHanoiGame(GameMaster): def __init__(self): super().__init__() def produceMovableQuery(self): """ See overridden parent class method for more information. Create the Fact object that could be...
405e2ac58762516e525aa036f210b2988564666a
isabel-eng/C-Python-exercises
/Problem5.py
1,560
4.5
4
''' 5. Compute the Matrix Multiplication between a matrix A and B. Don’t use any library. ''' #this function print the matrix def printer(matrix, y): for i in range(0, y): print(matrix[i]) #this function ask the values of each place in the matrix def askMatrix(x, y): matrix = [] for i in range(0,x):...
7c9c7e4608eb6672bcd51bd1527a186dfdefd854
ThiagoCSgit/TAD
/criarmat_git.py
294
3.671875
4
def criamat(): mat = [] qlin = int(input('Quantidade de linhas da matriz: ')) qcol = int(input('Quantidade de colunas da matriz: ')) for i in range(qlin): mat.append([]) for j in range(qcol): mat[i][j].append(int(input('Digite os valores da matriz: '))) return mat x = criamat()
13507cebc3e383db5a746119598a74e287be0c36
kayo289/havel-hakimi2
/havel.py
1,033
3.53125
4
print("数列を半角スペースを入れて入力してください") #splitで半角スペースで入力された値を整数型で配列に格納 data = list(map(int, input().split())) while True: data.sort(reverse=True) #降順 print(data) for i in range(0,data[0]): #0から先頭配列要素-1までループする data[i+1]-=1 if data[i+1]<0 or len(data) <= data[0]: #配列要素内がゼロ以下または,配列数以上の値が存在している時恥数列ではない...
32be7903170d226edac29c3898a93687723afc42
Germany18/file-processing
/week_nine.py
1,034
3.734375
4
import os import csv path = input ("Please enter directory ") file = input ("Enter file name ") fullPath = f"{path}/{file}.csv" name = input ("Enter name ") address = input ("Enter address ") phone = input ("Enter phone ") checkFolder = os.path.isdir(path) def writetofile (fullPath, name, address, phone): with open...
b8732f892638ddfbadee67c45f90529e17317ec4
matheus-pereira/python
/curso-em-video/exercicio-018.py
214
4.0625
4
from math import radians, sin, cos, tan a = int(input('Digite um ângulo: ')) print('O ângulo {} possui seno {:.2f}, cosseno {:.2f} e tangente {:.2f}'.format(a, sin(radians(a)), cos(radians(a)), tan(radians(a))))
23b31279e3bc783e659cfa8419bc74f5a2392d8d
matheus-pereira/python
/curso-em-video/exercicio-008.py
147
3.828125
4
m = int(input('Digite um valor em metros: ')) c = m * 100 mm = m * 1000 print('{} metros são {} centímetros ou {} milímetros'.format(m, c, mm))
24efbd5ed1be1ffc03233f088b3806fd5908029c
Chiragkaushik4102001/Python_1styear
/PYTHON/34_vowels.py
394
3.96875
4
#number of vowels and consonants in a string a=input("enter the string : " ) c=0 d=0 e=0 for i in a: if i=='a' or i=='e' or i=='i' or i=='o' or i=='u': c+=1 elif i==" ": d+=1 else: e+=1 print("number of vowels is {}".format(c)) print("number of consonants is {}"...
d1ae67963b1f1a2c04baa4d7b966db51ce060ed6
Chiragkaushik4102001/Python_1styear
/PYTHON/binary_pattern2.py
114
3.59375
4
#binary number pattern n=int(input("enter size : ")) for i in range(n+1): print(bin(i)[2:])
e0fbe3b8edf458c509b53ea6173a6d3928734bcc
Chiragkaushik4102001/Python_1styear
/PYTHON/36_distance.py
277
4.125
4
#distance between two points from math import * x1,y1=map(int,input("enter X coordinates :").split(",")) x2,y2=map(int,input("enter Y coordinates :").split(",")) a=pow(x2-x1,2) b=pow(y2-y1,2) d=sqrt(a+b) print("the distance between the points is {}".format("%.2f" %d))
384e19e1df293368ba69e6d58a9a3f7a356d05a6
Chiragkaushik4102001/Python_1styear
/PYTHON/functions_set.py
1,202
4.25
4
#functions on set a={1,2,3,4,5,6} b={1,2,3} #1.issubset() print(b.issubset(a)) #boolean result,returns true if subset is present in set and false if subset not present in set #syntax= subset name.issubset(set) #2.issuperset() print(a.issuperset(b)) #boolean result,returns true if all elements of subset are p...
7b5bb9ec6d319a7a77727590c58a3eacc406c69e
Chiragkaushik4102001/Python_1styear
/PYTHON/set.py
1,070
4.375
4
#set concept a={1,1,2,3,4,5,3} print(a) #set avoid duplication of data hence a value is printed only once. b={} # empty brackets will be treated as dictionary print(type(b)) a.add(7) # add() can be used to add elements to a non empty set print(a) s={1,2,3} t={4,5,6} s.update(t) # update can be used to pu...
4592dee02caebf816c073c9d81af77a31dd79f64
L271828R/tech-media-school
/day.02/assignment/demand_supply.py
848
3.546875
4
import csv import matplotlib.pyplot as plt if __name__ == '__main__': print('hello demand supply') supply_arr = [] demand_arr = [] prices_arr = [] arr = [] with open('data.csv', 'r') as csvfile: reader = csv.reader(csvfile) for count, row in enumerate(reader): if c...
0ddcc2a847b9436ef67901e3c3ebf046f041e374
L271828R/tech-media-school
/day.04/mu.py
510
3.9375
4
import matplotlib.pyplot as plt if __name__ == '__main__': print('Welcome to MU grapher') product = input("please enter a product. ") max_quantity = int(input("please enter the max quantity. ")) y = [] x = [] for i in range(1, max_quantity + 1): mu = input("What is your added hap...
72ee324f3a73a94e5f0b4b9330e1c91c0567bac4
akr170/purchase-analytics
/src/purchase_analytics.py
4,068
3.65625
4
import pandas as pd import numpy as np import sys # obtaining the file names passed through the command line pdts = sys.argv[2] #path to input file products.csv that relates products to their departments ordr = sys.argv[1] #path to input file order_products.csv that contain order information outf = sys.argv[3] #path ...
2539c672bba496f52a6a1007dac130e19c5cc70f
cman131/CodeChallenges
/ValidNumberLettersDigits.py
784
3.609375
4
def getValidLetters(digits): valid = {'1':'a','2':'b','3':'c','4':'d','5':'e','6':'f','7':'g','8':'h','9':'i','10':'j','11':'k','12':'l','13':'m','14':'n','15':'o','16':'p','17':'q','18':'r','19':'s','20':'t','21':'u','22':'v','23':'w','24':'x','25':'y','26':'z'} mapping = {} for i in range(len(digits)): ...
6d502c4eb80a54af841beefa13d3a9598ff08132
armenzg/coding
/amazon/string_divisions.py
1,907
3.96875
4
""" Greatest Common Divisor of Strings For two strings s and t, we say "t divides s" if and only if s = t + ... + t (t concatenated with itself 1 or more times) Given two strings str1 and str2, return the largest string x such that x divides both str1 and str2. Example 1: Input: str1 = "ABCABC", str2 = "ABC" Out...
8747a5b0d2dd089a760df1134a3a218b84b403e1
TahaKhan8899/Coding-Practice
/CitiBank_Summer2021/q4.py
939
3.75
4
# you can write to stdout for debugging purposes, e.g. # print("this is a debug message") def solution(G): pointsWithChoiceR = 0 pointsWithChoiceP = 0 pointsWithChoiceS = 0 for i in range(0, len(G)): print(G[i]) # if he chose Rock if G[i] == "S": pointsWithChoiceR ...
11de56a3d5f05f7ff411e9f69485cdb5b50639d0
TahaKhan8899/Coding-Practice
/RiotTest_Summer2020/Q1.py
976
3.90625
4
#!/bin/python3 import math import os import random import re import sys # Complete the 'PrintGardenLayout' function below. def PrintGardenLayout(): # get width and heigth size = sys.stdin.readline().split(',') w = int(size[0]) h = int(size[1]) # generate empty garden garden = [[0 for j in ra...
0207c146949f893c92275e0d8f83940834300014
TahaKhan8899/Coding-Practice
/LeetCode/majorityElement.py
580
3.53125
4
class Solution: def majorityElement(self, nums): print(nums) countDict = {} for num in nums: if num in countDict: countDict[num] += 1 else: countDict[num] = 1 print("Dict: ", countDict) majorityMin = in...
5b62dc2f1bdb809fc83c4faed1bdfd9d134649df
TahaKhan8899/Coding-Practice
/LeetCode/mergeSortedArrays.py
1,220
3.75
4
class Solution: def merge(self, nums1, m, nums2, n): """ Do not return anything, modify nums1 in-place instead. """ endIndex = (m+n)-1 n1End = m-1 n2End = n-1 print("nums1: ", nums1) print("nums2: ", nums2) while (n1End >= 0 and n2End >= 0): ...
39c9750241641b194dd8abd3a62adf1a182510c7
TahaKhan8899/Coding-Practice
/LeetCode/LastStoneWeight.py
1,074
3.765625
4
import MaxHeap class Solution: def lastStoneWeight(self, stones): print("Before Heapify", stones) stoneHeap = MaxHeap.MaxHeap(stones) print("After Heapify", stoneHeap.printHeap()) # while I have more than 2 stones while (len(stoneHeap.heap) > 2): print("...
fc4fdb363045da223461280d0bcbceb2161cd6a4
TahaKhan8899/Coding-Practice
/daily_leetcode_august/q5_copy.py
1,335
3.625
4
class WordDictionary: def __init__(self): self.children = [None] * 26 self.isEndOfWord = False def addWord(self, word: str) -> None: currentNode = self for char in word: charIndex = ord(char) - ord('a') if currentNode.children[charIndex] is None: ...
01236253ca39129acdf5e264f02bf42367781feb
TahaKhan8899/Coding-Practice
/Daily Coding Problems/oct8.py
1,712
3.9375
4
from collections import defaultdict def chainedWords(words): # Fill this in. isAChain = True wordsInChain = [] for i in range(0, len(words)): outterWord = words[i] print("Outer List: ", outterWord) lastLetter = outterWord[len(outterWord)-1] print("Last Letter: ", l...
6612280431ba2fb2a89e1a97a276d5ffed5e6b86
TahaKhan8899/Coding-Practice
/RiotTest_Summer2020/Q2.py
4,109
4.03125
4
#!/bin/python3 import math import os import random import re import sys # Complete the 'PrintGardenLayoutWithIdealSeats' function below. def PrintGardenLayoutWithIdealSeats(): # get width and heigth size = sys.stdin.readline().split(',') w = int(size[0]) h = int(size[1]) # generate empty garde...
e1b3661be85d8b976d5f76d62a21097f85402e7e
TahaKhan8899/Coding-Practice
/HackerRank/pivotArray.py
235
3.8125
4
# Complete the rotLeft function below. def rotLeft(a, d): newArr = [0 for i in range(len(a))] for i in range(0, len(a)): newInd = i - d newArr[newInd] = a[i] return newArr print(rotLeft([1,2,3,4,5,6], 3))
3f6d45afa66b4661e567e716f10a21c63961bdbd
TahaKhan8899/Coding-Practice
/Daily Coding Problems/oct12-MinAndMax.py
586
3.90625
4
def find_min_max(nums): if len(nums) % 2 == 1: # If there are an odd number of elements # Use the last number as the min/max min_n = max_n = nums[-1] else: min_n = max_n = nums[0] for i in range(len(nums)//2): if nums[2*i] < nums[2*i + 1]: min_a = nums[2*...
19594e209bc955c5c76d92f67039435cb410ad04
TahaKhan8899/Coding-Practice
/Roblox2021_HackerRank/q2.py
1,260
3.796875
4
# # Complete the 'compressWord' function below. # # The function is expected to return a STRING. # The function accepts following parameters: # 1. STRING word # 2. INTEGER k # def compressWord(word, k): stk = [] # go through all chars in word for i in range(0, len(word)): # if we havent seen it, ...
c95a76a6b24bd29e7013311abf24a32f46ec80c7
henryh28/coding_practice
/number/majority_element.py
489
3.515625
4
def majorityElement(self, nums): """ :type nums: List[int] :rtype: int """ count_dict = {} max_value = 0 answer = None for value in nums: count_dict[value] = 1 if value not in count_dict else count_dict[value] + 1 ...
65451308d79619d0509007e10fb0f44c733cdcb2
henryh28/coding_practice
/data_structures/spiral_matrix.py
484
3.8125
4
def spiralOrder(self, matrix): """ :type matrix: List[List[int]] :rtype: List[int] """ answer = [] while len(matrix) > 0: # Pop first row of matrix into answer answer.append(matrix.pop(0)) # Rotate remaining matrix matrix = zip(*matrix) matrix = [...
210b388ffba61b56590f3eb208e59eb48d21b50b
henryh28/coding_practice
/number/sherlock_and_the_beast.py
443
3.796875
4
def decentNumber(n): answer = "" quotient = n // 3 remainder = n % 3 if n < 3: print (-1) return while quotient >= 0: if remainder % 5 == 0: remainder = remainder // 5 for i in range(quotient): answer += "555" for i in range(remainder): answer...
b7d096be219236101742b129ee4c0dc3417aabcc
henryh28/coding_practice
/euler/euler_10.py
1,100
4
4
def primes_below(limit): sieve = [0] * (limit + 1) answers = [] # totals = 0 for number in range(3, limit + 1, 2): # unmarked number, will be a prime number if sieve[number] == 0: answers.append(number) sieve[number] = 1 # totals += 1 multiple_of = number for m...
ada36e10c1caf3d206caf04e65594721082cf47f
henryh28/coding_practice
/number/power_of_two.py
373
4.0625
4
def isPowerOfTwo(self, n): """ :type n: int :rtype: bool """ test = 0 power = 1 # Special handling for odd numbers if n % 2 != 0: return (True if n == 1 else False) # Handling for even numbers while test < n: test = 2 ** power power += 1 if test...
d74e2326231c097f0cecb68297bdb585714ad9ea
henryh28/coding_practice
/general/insertion_sort.py
294
4.15625
4
def insertionSort(array): for index in range(len(array)): sorting_value = array[index] position = index while position > 0 and array[position - 1] > sorting_value: array[position] = array[position - 1] position -= 1 array[position] = sorting_value
0f9e3bd2ebab5b1412ebc1217b16a97e5e556920
henryh28/coding_practice
/misc/twilio_hatch.py
1,572
4.03125
4
#!/bin/python3 import math import os import random import re import sys # # Complete the 'split' function below. # # The function is expected to return a STRING_ARRAY. # The function accepts STRING message as parameter. # # Idea for extra credit: # Split incoming 'message' into list of words interspersed with a bl...
87503efca1fa2866f0b32f5fdb2d674df783a66e
henryh28/coding_practice
/general/itertools.py
828
3.71875
4
from itertools import product # Generate cartesian products usin product() a = map(int, input().split()) b = map(int, input().split()) print (*product(a, b)) from itertools import permutations # Print permutations of a string up to length n string, length = input().split() string = sorted(string) length ...
94f90bc8fe9d5515c8ce45ab01451e1f10e87064
henryh28/coding_practice
/general/ice_cream_parlor.py
781
3.53125
4
def icecreamParlor(m, arr): prices = {} for index, value in enumerate(arr): prices[value] = [index] if value not in prices else prices[value] + [index] for index, value in enumerate(arr): second_value = m - value if second_value in prices: indices = prices[second_value] ...
c0eb15bfa45f5598a88f67c5965e11aecae5f721
henryh28/coding_practice
/misc/royal_names.py
1,327
3.796875
4
# Complete the getSortedList function below. def getSortedList(names): from collections import defaultdict answer = [] name_set = [] name_dict = defaultdict(list) roman = ["I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX", "X", "XI", "XII", "XIII", "XIV", "XV", "XVI", "XVII", "XVIII", "XIX", "XX", "XXI"...
cd4a6e7dccb35a68d4fc6db3a18df665b1bf22f5
henryh28/coding_practice
/number/minimum_loss.py
660
3.640625
4
def minimumLoss(price): lowest = max(price) value_and_index = [] for index, value in enumerate(price): value_and_index.append((value, index)) value_and_index.sort(reverse = True) for index in range(len(value_and_index) - 1): # Only process if next value comes after current value ...
b84eb0f165687415fc5bf6b96231b2dd09ffe991
henryh28/coding_practice
/euler/euler_7.py
811
3.859375
4
#By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 6th prime is 13. #What is the 10 001st prime number? def answer(n): primes = [2, 3] answer = primes if n == 1: return primes[0] elif n == 2: return primes[1] # do n - 2 times (minimum n of 3 would be ...
1ad0bf3b90548c83d1f1fed588cc01df289691f2
MrDNA2018/test
/回溯法:N皇后.py
1,230
3.59375
4
def place(self, k): for i in range(k): if abs(k - i) == abs(self.solution[k] - self.solution[i]) or self.solution[k] == self.solution[i]: return False return True class Nqueen: def __init__(self, N): self.N = N self.sum = 0 self.solution = [-1] * N ...
70fa965f07f315de5bacb8ec959ed4823abbea79
anjalirana99/GFG-DSA
/Mathematics/Exactly-3-Divisors.py
406
3.890625
4
def isprime(n): if n==1: return False if n==2 or n==3: return True if n%2==0 or n%3==0 : return False k=5 while(k*k<=n): if n%k==0 or n%(k+2)==0: return False k+=6 return True def exactly3Divisors(N): # code here co=0 i=2 ...
ccca291ba799b61bb8b2eafb8f011034ccce974a
cahillathehun/CA341
/Assignment 1/New folder/calender_imp.py
3,571
4.4375
4
""" implenting the appointments using lists and tuples. days is a list of all days in the week. each of the days in the week is a list of tuples. each of the tuples in a day contains the start time of the appointment @ pos 0 and the end time @ pos 1. as a result of this times cannot be changed unless they ar...
a30d102054673487111a4813ed5d74b78801e08e
hodlerfolyf/Countdown-Timer-quantatask
/Countdown timer.py
454
3.828125
4
# import the time module import time # define the countdown function for 30 Days def countdown(): t = 30 * 24 * 60 * 60 while t: mins, secs = divmod(t, 60) hours, mins = divmod(mins, 60) days, hours = divmod(hours, 24) timer = 'Days:{:02d} Hours:{:02d} Minutes:{:02d} Seco...
5027228a621639667b0ec3a9bb6fc3cab8d74788
Clercy/class6-hwk
/generic_chart.py
4,936
3.921875
4
#!/usr/bin/env python # 1. load a dataset from a file # 2. "organize" that file, so that we can access columns *or* rows of it easily # 3. compute some "summary statistics" about dataset # 4. print those summary statistics # 1. load a dataset # 1a. accept arbitrary filename as arhument # 1b. load the file def theti...
2b24a6a81c42ab59e6a2f4dbefb18143a6023bc3
AlexKolchin/Mentorship
/simple_oop_calc/main.py
337
3.578125
4
class calculator(): x = None y = None z = None def add(x,y): z = x + y return z def substract(x, y): z = x - y return z def multiply(x, y): z = x * y return z def divide(x, y): z = x / y return z result = calculator.multiply(4,...
e87d1a6e26fa17db5f8b656f9a0725e8bcf93ebd
AlexKolchin/Mentorship
/Farm_problem/main.py
412
3.921875
4
chickens_legs = 2 cows_legs = 4 pigs_legs = 4 def animals(chickens, cows, pigs): sum = chickens * chickens_legs + cows * cows_legs + pigs * pigs_legs return sum chickens = int(input("Please enter the number of chickens: ")) cows = int(input("Please enter the number of cows: ")) pigs = int(input("Please enter t...
3159cbc8c9bb34919d94c78b8d9a1758c08fec4a
scholarslab/praxis-code-lab-2018-2019
/Week6/CM_FamousCanadians_QuickAndDirty.py
427
4.0625
4
name= input("Enter a name: ") famous_canadians= {'Celine Dion': ['1968', 'performer', 'goddess'], 'Drake': ['1968', 'performer'], 'Justin Trudeau': ['1971', 'Prime Minister', 'snowboard instructor'], 'Sandra Oh': ['1971', 'actor', 'goddess'], 'Nathan Fillion': ['1971', 'actor'], 'John A. Macdonald': ['1815', '1891',...
47a67d0c2aa49b755cacc6921313b0f06dcb135e
scholarslab/praxis-code-lab-2018-2019
/week9/assignment2_cj.py
2,281
3.53125
4
class Historicalfigures: # existing logic goes here def __init__(self, first_name, last_name): self.first_name = first_name self.last_name = last_name self.century = [] self.expertises = [] def get_full_name(self): return self.first_name + ' ' + self.last_name def...
f92f6c79408e927441d14160525f561095da53fa
ansugpta009/tathastu_week_of_code
/Day 1/Program2.py
93
3.96875
4
num = int(input("Enter the number:")) sqrt = num**0.5 print(\square Root Of",num," = ",sqrt)
b9457b55c64c06cf1dfeb44ec296da85769eee5d
zakarirou/projet-git
/sanstitre1.py
782
3.734375
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon Feb 3 17:13:09 2020 @author: zakaria """ a=['2','3','4','2'] b=list(map(int,a)) c=[int(x) for x in a] d=a.map(lambda x: int(x)) a[len(a)-1] a.reverse() a=set([1,2,3]) b={} c=set() b={3,4,5} c.add(5) class A: def test(self): print("A") ...
90fab2ec6ed003ba76f5f8c55f6f1cd72a5abfca
wwweaponizer/SmoothArray
/smootharray.py
6,436
3.515625
4
#!/usr/bin/env python """ SmoothArray() The SmoothArray() class, a dynamic array with constant-time (not amortized) O(1) append. Some doctests: >>> SmoothArray() SmoothArray() >>> SmoothArray((0, 1, 2, 3)) SmoothArray((0, 1, 2, 3)) >>> sa = SmoothArray((0, 1, 2, 3)) >>> sa.append(4) >>> sa SmoothArray((0, 1, 2, 3...
9fdeb44b8a3334507b9bda5f592d3c82e8add036
priyamehta2772/cracking-the-coding-interview
/Unit 2_ Linked List/2.3_delete_middle_node.py
1,062
3.78125
4
# -*- coding: utf-8 -*- """ Created on Mon Dec 9 18:28:45 2019 2.3 Delete any middle node @author: PriyaMehta """ class LinkedListNode: def __init__(self, val, link): self.value = val self.link = link class LinkedList: def __init__(self, h): self.head = h def print_list(se...
0cc80d70c2cbd822a8f23a43795bbedb5f40d05e
priyamehta2772/cracking-the-coding-interview
/Unit 3_ Stacks and Queues/stack_of_boxes.py
1,390
3.75
4
# -*- coding: utf-8 -*- """ Created on Tue Dec 3 18:08:07 2019 @author: priya Stack of boxes """ class box: def __init__(self, h, w, d): self.height = h self.width = w self.depth = d def hasLargerWidth(self, b2) -> bool: return True if (self.width>b2.width) else Fal...
8799d50ef0bb9a035fb1c3f9f6a78e89d001298d
gsmandur/Daily-Programmer
/339/339_sol.py
1,798
3.703125
4
# Question at: # https://www.reddit.com/r/dailyprogrammer/comments/7btzrw/20171108_challenge_339_intermediate_a_car_renting/ # determines the optimal solution to serve the most rental requests) # uses greedy solution, sorting by the rental finish date # input is n the number of requests and and array of pairs for the ...
c704dac8ebe8b2c7d30263284316c26fc346846e
EvgenChopenko/WarShips
/game/Ship.py
1,286
3.640625
4
class Ship(object): def __init__(self): self.__decks = list() self.__is_alive_ship = None def add_deck(self, deck): self.__decks.append(deck) self.__is_alive_ship = True def make_damage(self, cell): for item in self.__decks: if item.is_located(cell): ...
c1128833a3ba10f2ce7d0df1ffa45b62587d7319
uchenna-j-edeh/dailly_problems
/sorting_algorithm/test_sort.py
940
4.25
4
# # Complete the 'merge_sort' function below. # # The function accepts an integer array as parameter. # def merge_sort_helper(A, start, end): if start <= end: return mid = (start + end) // 2 merge_sort_helper(A, start, mid) merger_sort_helper(A, mid+1, end) i = start j = ...
e60da16cdaeefc14dd8726db9956a59eead8b92c
uchenna-j-edeh/dailly_problems
/recursion/array_nums_permutation.py
1,234
3.703125
4
""" Given [1,2,3], find all it's permutations... """ def helper(S, i, slate, result): if i == len(S): # base case result.append(slate[:]) #print(slate[:]) return # recursive case for p in range(i, len(S)): S[p], S[i] = S[i], S[p] slate.append(S[i]) helper(S,...
f2c72134c063b7a1089ae7f8f10d04c4e375595b
uchenna-j-edeh/dailly_problems
/g_prep/word_squares.py
3,378
4.03125
4
""" https://techdevguide.withgoogle.com/resources/former-coding-interview-question-word-squares/#code-challenge A 'word square' is an ordered sequence of K different words of length K that, when written one word per line, reads the same horizontally and vertically. For example: BALL AREA LEAD LADY Efficeint solution:...
5734160ce22c210b1850c8300deaf3b66f19e18f
uchenna-j-edeh/dailly_problems
/g_prep/rotate_array.py
1,895
4.09375
4
""" Given an array, rotate the array to the right by k steps, where k is non-negative. Follow up: Try to come up as many solutions as you can, there are at least 3 different ways to solve this problem. Could you do it in-place with O(1) extra space? Example 1: Input: nums = [1,2,3,4,5,6,7], k = 3 Output: [5,6,7,1,...
5803bafcd065b9acede80dc89caa7d36b84f1519
uchenna-j-edeh/dailly_problems
/arrays_manipulations_algorithms/compute_min_number_parentheses.py
760
4.1875
4
""" Given a string of parentheses, write a function to compute the minimum number of parentheses to be removed to make the string valid (i.e each open parentheses is eventually closed) For example, given the string "()())()", you should return 1. Given the string ")(", you should return 2, since we must remove all of...
b7217563a1d23f651612d5be29738e27b9522d7e
uchenna-j-edeh/dailly_problems
/heap_problems/three_max_product.py
1,327
4.1875
4
""" Given a list of integers, return the largest product that can be made by multiplying any three integers. For example, if the list is [-10, -10, 5, 2], we should return 500, since that's -10 * -10 * 5. You can assume the list has at least three integers. """ import heapq min_heap = [] min_list = [] max_heap = [] ma...
80dfb39172f94cb64a7c22944cda47f91bc27543
uchenna-j-edeh/dailly_problems
/sorting_algorithm/selection_sort.py
641
3.5625
4
""" This is a brute force algo with running time of O(N^2) asymptotic complexity O(N^2) A = [9,1,5,6,3,4,9,0] """ class Solution: def selection_sort(self, A): for i in range(len(A)): min = i #import pdb; pdb.set_trace() for j in range(i+1, len(A)): if A[j...