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
c1313fd43e568a5feea7c9ac97405399a9b0d92c
Rusty33/tic-tac
/game_ai_no_d.py
18,325
3.875
4
import random board = [[0,0,0],[0,0,0],[0,0,0]] turn = 1 game = True go = True ##################################################### def print_board(): global board to_print = [""," 1 "," 2 "," 3 ","\n"] x = 0 y = 0 while y <= 2: if board[y][x] == 0: ...
0558a60ba427ae4f2ec0b709c0911ec09e6fa3e7
Liraz-Benbenishti/Python-Code-I-Wrote
/hangman/hangman/hangman-unit5/hangman-ex5.3.4.py
282
3.625
4
def last_early(my_str): my_str = my_str.lower() last_char = my_str[-1] if (my_str[:-1].find(last_char) != -1): return True return False print(last_early("happy birthday")) print(last_early("best of luck")) print(last_early("Wow")) print(last_early("X"))
f3a101700e9798aac4030891e843eaa3d59c0f93
Liraz-Benbenishti/Python-Code-I-Wrote
/next_py/next-py.1.1.2.py
505
3.828125
4
from functools import reduce def add_dbl_char(list, char): list.append(char * 2) return list def double_letter(my_str): """ :param my_str: string to change. :type my_str: string :return: a new string that built from two double appearance of each char in the string. rtype: string """ return "".jo...
c1b15e76e674ba8482922ef77a5a3b1993c4cb7c
Liraz-Benbenishti/Python-Code-I-Wrote
/next_py/next-py.4.1.2.py
430
3.828125
4
def translate(sentence): words = {'esta': 'is', 'la': 'the', 'en': 'in', 'gato': 'cat', 'casa': 'house', 'el': 'the'} translate_generator = (words[i] for i in sentence.split(' ')) ret_lst = [] for string_generator in translate_generator: ret_lst.append(string_generator) ret_str = " ".join(ret_lst) return...
59f598f7eabaadbda9ed96866d3da91bccb63512
Liraz-Benbenishti/Python-Code-I-Wrote
/next_py/next-py.4.1.3.py
518
3.671875
4
def is_prime(n): # Corner case if (n <= 1): return False # Check from 2 to n-1 for i in range(2, n): if (n % i == 0): return False return True def first_prime_over(n): prime_generator = (i for i in range(n+1, (n+2) ** 10) if is_prime(i)) return next(prime_generator) def main()...
cfaf15f6ce9c635ee1a87c2892b9a09cdb91dc47
Liraz-Benbenishti/Python-Code-I-Wrote
/hangman/hangman/hangman-unit7/hangman-ex7.2.4.py
557
3.921875
4
def seven_boom(end_number): """ :param end_number: the number to end the loop. :type end_param: int :return: list in range of 0 and end_number (including), where some numbers replaced by "BOOM". rtype: list """ list_of_numbers = [] for number in range(end_number + 1): list_of_numbers.append(number...
371ed66d667edb14d59347994462ddf30dde6a84
Liraz-Benbenishti/Python-Code-I-Wrote
/hangman/hangman/hangman-unit7/hangman-ex7.3.1.py
836
4.25
4
def show_hidden_word(secret_word, old_letters_guessed): """ :param secret_word: represent the hidden word the player need to guess. :param old_letters_guessed: the list that contain the letters the player guessed by now. :type secret_word: string :type old_letters_guessed: list :return: string that comprise...
ad1a0de49caddf1372e5ae9f749e06577ec2320c
shaoormunir/programming-problems
/Google Problem 1.py
309
3.671875
4
array = [1, 11, 3, 7, 2, 6, 5, 10, 4] sum = 12 for i in range(len(array)): temp_sum = 0 for k in range (i, len(array)): temp_sum += array[k] if temp_sum == sum: print("Starting: {} Ending: {}".format(i, k)) break elif temp_sum > sum: break
0d59a25163228056e84201221068235042726a1c
momotofu/algorithms
/math/fib_even.py
211
4
4
def fib_even(n): sum = 2 a = 1 b = 2 while True: c = 3*b + 2*a if c >= n: break sum += c a += 2*b b = c return sum print(fib_even(100))
b3110a0495a6d52ab0cd4e98f0ef25dbc0c501de
aanzolaavila/competitive-problems
/codeforces/Resueltos/watermelon.py
253
3.578125
4
from sys import stdin def main(): linea = stdin.readline().strip() while len(linea) != 0: w = int(linea) if w % 2 == 0 and w != 2: print("YES") else: print("NO") linea = stdin.readline().strip() main()
8ff7e9be23a5ad7a679ac582e18c59d29eee51f5
aanzolaavila/competitive-problems
/codeforces/Resueltos/A.petya_and_strings.py
542
3.625
4
from sys import stdin import string letters = string.ascii_lowercase def lex(l1, l2) -> str: for i in range(len(l1)): if letters.index(l1[i]) < letters.index(l2[i]): return "-1" elif letters.index(l1[i]) > letters.index(l2[i]): return "1" return "0" def main(): line1 = stdin.readline().str...
210414121ff25d50588e6e766b23cf2109219ecc
Leonardra/parsel_tongue_mastered
/oluwatobi/chapter_seven/question_26.py
114
3.515625
4
number_list = [] for num in range(2, 41): if num % 2 == 0: number_list.append(num) print(number_list)
f41f85c5ade58c5591f6c53abc6f4f3832daf675
mdarifuddin1/Create-a-Dictionary-to-store-names-of-students-and-marks-in-5-subjects
/dictionaries containing.py
556
4.09375
4
students = dict() list1 = [] n = int(input("How many students are there: ")) for i in range(n): sname = input("Enter name of the student: ") marks = [] for j in range(5): mark = float(input("Enter marks: ")) marks.append(mark) students = {'name':sname,"marks" :marks} list...
fda16aa729c019888cb2305fcfb00d782e620db6
cnulenka/Coffee-Machine
/models/Beverage.py
1,434
4.34375
4
class Beverage: """ Beverage class represents a beverage, which has a name and is made up of a list of ingredients. self._composition is a python dict with ingredient name as key and ingredient quantity as value """ def __init__(self, beverage_name: str, beverage_composition: dict): ...
3a2adf0295f13820e2732cc77c5eaa1976d2fc62
akashgiri/merchant
/change_to_roman_numerals.py
501
3.796875
4
#!/usr/local/bin/python # -*- coding: utf-8 -*- def change_to_roman_numerals(input_content): change_to_roman = [] currency = {} print(input_content) for key, value in input_content.items(): if key == 'roman_attributes': for index, number in enumerate(value): change_to_roman.append(number.split()) ## C...
d434667f4c4eeb56c074ed47146921bb0c0013dc
efahmad/laitec-data-science
/002-session/pandas_test.py
536
3.5625
4
import pandas as pan import os import matplotlib.pyplot as plt data = pan.read_csv(os.path.join(os.path.dirname(__file__), "movie_metadata.csv")) likes = [ (name, sum(data['actor_1_facebook_likes'][data['actor_1_name'] == name].values)) for name in data['actor_1_name'].unique() ] likes = sorted(likes, key...
80a3b9c03c7b525182ddc05ee3f3405f552e7b57
priyankapednekar/Graph
/dfs_print_graph.py
1,247
3.875
4
class Node(): ''' node has value and the list of edges it connects to''' def __init__(self,src): self.src = src self.dest = {} self.visit=False class GF(): """docstring for .""" '''key- node data and value is Node''' def __init__(self): self.graph={} def inser...
7762d9a8c0b8ebb97551f2071f9377fe896b686f
itstooloud/boring_stuff
/chapter_3/global_local_scope.py
922
4.1875
4
## ####def spam(): #### global eggs #### eggs = 'spam' #### ####eggs = 'global' ####spam() ####print(eggs) ## ####using the word global inside the def means that when you refer to that variable within ####the function, you are referring to the global variable and can change it. ## ####def spam(): #### global e...
46c128c433288c3eed04ecb148693e52828c6975
itstooloud/boring_stuff
/hello_age.py
358
4.15625
4
#if/elif will exit as soon as one condition is met print('Hello! What is your name?') my_name = input() if my_name == "Chris": print('Hello Chris! Youre me!') print('Your age?') my_age = input() my_age = int(my_age) if my_age > 20: print("you're old") elif my_age <= 10: print("you're young") else: pri...
cb62ae43d94a2e7f99ad875e58cdff60f9d971ef
AlexSamarsky/seabattle
/game.py
5,660
3.546875
4
import os from board import Board from errors import WrongCoords, CoordOccupied, BoardShipsError class Game(): _computer_board = None _player_board = None _playing = False _mounting_ships = False _computer_turn = False def __init__(self): self._playing = True self._mounting...
b643e9a0d72242ed831b4e20b8edcc08258d50ad
summergirl21/Advent-of-Code-2016
/Day03/Day3.py
1,209
3.90625
4
def main(): print("Hello") input = open("Day3_input.txt", "r") #input = open("Day3_input_test.txt", "r") newinput = {0:[], 1:[], 2:[]} for line in input: line = [int(x) for x in line.split()] for i in range(0, 3): newinput[i].append(line[i]) print(newinput[0]) pri...
f85f89d07de9f394d7f95646c0a490232bc3b7bc
whoismaruf/usermanager
/app.py
2,605
4.15625
4
from scripts.user import User print('\nWelcome to user management CLI application') user_list = {} def create_account(): name = input('\nSay your name: ') while True: email = input('\nEnter email: ') if '@' in email: temp = [i for i in email[email.find('@'):]] if...
59406c79354db2ff825e18a503fa35a4883ca51d
avadesh02/fml-project
/srcpy/robot_env/two_dof_manipulator.py
10,894
3.96875
4
## This is the implementation of a 2 degree of manipulator ## Author: Avadesh Meduri ## Date : 9/11/2020 import numpy as np from matplotlib import pyplot as plt # these packages for animating the robot env import matplotlib.pyplot as plt import matplotlib.animation as animation from matplotlib.animation import FuncAn...
f7691a737227df28f71e8c9d647858bf020523e7
sidduGIT/Files_examples
/count_capitals.py
163
3.671875
4
with open('content.txt','r') as fh: count=0 for line in fh: for char in line: if char.isupper(): count+=1 print(count)
ec458e18c02717868cd756367b3c7c1f7eb8b241
pavdemesh/stepik_67
/stepik_67_ex_2_6_spiral_v1.py
512
3.703125
4
number = int(input()) matrix = [[0] * number for h in range(number)] row, col = 0, 0 for num in range(1, number * number + 1): matrix[row][col] = num if num == number * number: break if row <= col + 1 and row + col < number - 1: col += 1 elif row < col and row+col >= number-1: ...
d9247e91833eb5a66e7388dc3f8e4e1ea99de9d3
pavdemesh/stepik_67
/stepik_67_ex_2_6_4.py
827
3.8125
4
# Create empty list matrix = list() # Get input from user while True: line = input() # Check if input == "end", break if line == "end": break # Else convert input to a list of ints and append to the matrix list else: matrix.append([int(i) for i in line.split()]) # Create variables ...
23051e5670e7af0274ea6226d679cf8bed225244
cnguyen-uk/Blockchain
/block.py
1,420
3.609375
4
# -*- coding: utf-8 -*- """ This is our Block class for transaction storage. Note that although every block has a timestamp, a proper implementation should have a timestamp which is static from when a block is finally placed into the blockchain. In our implementation this timestamp changes every time the code ...
aab62b602367c12b4ebbf827a5b79ff4f1de84b9
18lkent/AFPwork
/GC-content.py
682
3.53125
4
dnaSequence = "ACTGATCGATTACGTATAGTATTTGCTATCATACATATATATCGATGCGTTCAT" #The sequence being counted from print("This program will display the gc content of a DNA sequence") seqLen = len(dnaSequence) #Length of the sequence gAmount = dnaSequence.count('G') #Amount of G's in the sequence cAmount = dnaSequence.count('C') #...
0ea8e85c1cc8eee1846c38d7adf6dcbb8de16aa5
cmniccum/Exploring-BikeShare-Data
/bikeshare.py
10,201
3.78125
4
import time import pandas as pd import sys CITY_DATA = { 'chicago': 'chicago.csv', 'new york city': 'new_york_city.csv', 'washington': 'washington.csv' } fname = "" separate = False def log(): """ This is a logging function which will determine whether to log the information t...
7e43010151fd990c1962e1c5847230315ff80d5c
kaka0525/data-strutctures-partII
/merge_sort.py
1,792
3.703125
4
from __future__ import unicode_literals from time import time from random import shuffle def merge_sort(init_list): if len(init_list) <= 1: return init_list list_left = init_list[:len(init_list) // 2] list_right = init_list[len(init_list) // 2:] left = merge_sort(list_left) right = merge_s...
d827875540a6004a7680a82649bdb58dc6f3431a
Aaron-Ramos/parcial-python
/py-parcial-q3-2020/clave_B/clave_b.py
2,257
4.0625
4
from math import pi """ *************************************************************** @@ ejercicio 1 @@ un metodo python que haga la suma de 3 numeros 2+4+6 = 12 """ # start--> def suma(numero1,numero2,numero3): result = numero1 + numero2 + numero3 return result """ *************************...
590e8b488d96bf5961cd747a44386b563a34b76f
richnamk/python_nov_2017
/richardN/pythFundamentals/multSumAve/multSumAve.py
248
3.5
4
#Mult #part 1 for x in range (0,1000): if (x % 2 == 1): print x #part 2 for x in range (5,1000000): if (x % 5 == 0): print x #Sum a = [1, 2, 5, 10, 255, 3] print sum (a) #Ave a = [1, 2, 5, 10, 255, 3] print sum (a) / (len(a))
a5bb79e5269dfb2ac5076f11585d078e404202f5
zazaho/SimImg
/simimg/dialogs/infowindow.py
994
3.765625
4
from tkinter import messagebox as tkmessagebox def showInfoDialog(): """ show basic info about this program """ msg = """ SiMilar ImaGe finder: This program is designed to display groups of pictures that are similar. In particular, it aims to group together pictures that show the same scene. The use case is t...
b9f24efdbaffa1d8c8968c95cafe3025fc01d7e7
nithinp300/texteditor
/texteditor.py
1,377
3.578125
4
from Tkinter import * import tkFileDialog root = Tk("Text Editor") text = Text(root) text.grid() savelocation = "none" # creates a new file and writes to it def saveas(): global text global savelocation t = text.get("1.0", "end-1c") savelocation = tkFileDialog.asksaveasfilename() file1 = open(savelocation, "w") ...
d76be366cdc01b27a2071c7e88a63fa5b8cbb1e5
attainu/python-project-Shiva-dwivedi-au9
/Saanp_Seedhi/Saanp_Seedhi.py
11,487
3.671875
4
import random import time import sys class Saanp_Seedhi: def __init__(self): self.DELAY_IN_ACTIONS = 1 self.DESTINATION = 100 self.DICE_FACE = 6 self.text = [ "Your move.", "Go on.", "Let's GO .", "You can win this." ] ...
c1ba8dbefafd9ea87f4fe74c93e76afa47766fd4
yrachkov/Python_2_online
/lesson9/hw3.py
83
3.609375
4
s = {'n':2,'d':6,'h':4,'u':11} for y,l in s.items(): if l ==2: print(y)
0ab6be587b51f02f0db4f53534281be61c664c01
GuiBritoPy/SimplesPySimples
/Jogo.py
2,323
3.84375
4
# -*- coding: utf-8 -*- while True: ok = "Ok, vamos continuar" nome = str(input("Olá, qual o seu nome? ")) idade = str(input("Quantos anos você tem? ")) sexo = str(input("Qual o seu sexo? (M - Masculino e S - Feminino) ")).upper() if sexo == "F": sexo = Feminino if sexo == "S": s...
33d262c8ef0f4f7de82ecab4a9fa9783c511e3ec
Italodias32/Python-Repository
/Animal.py
1,486
3.6875
4
class Animal(): def __init__(self, aux_nome, aux_peso): self.__nome = aux_nome self.__peso = aux_peso #Getter e Setters do Nome def get_nome(self): return self.__nome def set_nome(self, aux_nome): if isinstance(aux_nome, str): self.__nome = aux_nome ...
411a14d6899d35beeab715b621d75d8052b288c5
Italodias32/Python-Repository
/campeonato.py
1,335
3.65625
4
def vencedor(lista): maior = -1 for i in lista: if i.get_pontos() >= maior: maior = i.get_pontos() campeao = i.get_nome() return campeao class Participante(): def __init__(self, nome, index): self.__nome = nome self.__pontos = 0 self.__in...
c4eff3bd9244d150afd43170f9d11e910237e416
Alparse/artificial_intelligence
/tic_tac_toe.py
7,445
3.765625
4
""" Classic tic tac toe system implemented by Serhat Alpar. Copied from Xxxxxxxxxxxxxxxxx permalink: Xxxxxxxxxxxxxx """ import math import gym from gym import spaces, logger from gym.utils import seeding import numpy as np class TicTacToeEnv(): """ Description: A game of classical tic tac toe is play...
7f0d06254acda9ae0f22b35ddefa6f5d9bf53487
league-python-student/level0-module1-samus114
/_04_int/_2_simple_number_adder/simple_adder.py
523
4.0625
4
""" * Write a Python program that asks the user for two numbers. * Display the sum of the two numbers to the user """ import tkinter as tk from tkinter import messagebox, simpledialog, Tk if __name__ == '__main__': window = tk.Tk() window.withdraw() num1 = simpledialog.askinteger('', 'what is...
19ed2bdb0d0e8098568d9cb987ddb8997124082b
Samson26/code
/minmax.py
146
3.546875
4
a=int(input()) arr=[int(i) for i in input().split()] mini=min(arr) mini1=int(mini) maxi=max(arr) maxi1=int(maxi) print(str(mini1)+' '+str(maxi1))
15e7518c82297499f59d448a23822ee7c8859a8c
Samson26/code
/yesorno.py
74
3.65625
4
b=int(input()) if(b<=10 and b>=1): print("yes") else: print("no")
525d87507fad34cf9a6ae9a4afa5c0f97b9af1aa
Samson26/code
/alpha.py
97
3.75
4
user=raw_input() check=str(user.isalpha()) if check=='True': print "Alphabet" else: print "No"
7190442863bed270614b64bd3e8e6055ec1f4960
akansal1/statsintro_python
/Code/S10_normCheck.py
930
3.515625
4
'''Solution for Exercise "Normality Check" ''' from scipy import stats import matplotlib.pyplot as plt import statsmodels.formula.api as sm import seaborn as sns # We don't need to invent the wheel twice ;) from S12_correlation import getModelData if __name__== '__main__': # get the data data = getModel...
63e81f354f4ecbb4d2689d70815dfbec926c2013
drashti2210/180_Interview_Questions
/merge_sorted_array.py
1,444
3.84375
4
import sys sys.stdout = open('d:/Coding/output.txt','w') sys.stdin = open('d:/Coding/input.txt','r') # Given two sorted integer arrays nums1 and nums2, merge nums2 into nums1 as one sorted array. # Example # INPUT # nums1 = [1,2,3,0,0,0], m = 3 # nums2 = [2,5,6], n = 3 # OUTPUT # [1,2,2,3,5,6] nums1=list(map(i...
45ba4bf16bf612a0b2c9be396a77290ba419215a
drashti2210/180_Interview_Questions
/Mid_of_Linked_List.py
932
3.921875
4
import sys #Day 5 # 2. Middle of Linked List # INPUT:- # 1->2->3->4->5->NULL # OUTPUT: - # 3 # Definition for singly-linked list. class ListNode: def __init__(self, x): self.val = x self.next = None def middleNode(head): # solution 1 # find the length of linked list # iterate upto mi...
b929e51eb223e63930330838af02d7d9fd37c9b7
drashti2210/180_Interview_Questions
/Add_numbers_Linked_List.py
1,159
3.875
4
import sys # Add two numbers as LinkedLis # INPUT:- # 2 linked list # 1->2->3->->NULL # 1->2->3->->NULL # OUTPUT: - # addition # 2->4->6->NULL # Definition for singly-linked list. class ListNode: def __init__(self, x): self.val = x self.next = None def addTwoNumbers(self, l1: ListNode, l2: ListNo...
4e4019378a59f2b0eb3668cc4c4fbb0abcfa2139
drashti2210/180_Interview_Questions
/merge_sorted_LL.py
973
4.03125
4
import sys # Day 1 # 4. Merge Sorted Linked List #Example:- #INPUT:- # 2 sorted linked list # 1->2->4, 1->3->4 #OUTPUT:- # Merged Linked List # 1->1->2->3->4->4 class ListNode: def __init__(self, val=0, next=None): self.val = val self.next = next def merge(self, nums1: List[int], m: int, nums2: ...
5eb0dc3ddab738e7e7d60960ce8e49142ab87a1f
mbaybay/cs686-2018-01
/knn.py
2,023
3.671875
4
from classifier import classifier import pandas as pd import numpy as np from sklearn.model_selection import train_test_split class KNN(classifier): def __init__(self, k=3): self.x = None self.y = None self.k = k def fit(self, x, y): """ :param X: pandas data frame, w...
bd5d648e9f62bc9ba12ade748eddcaf9aba03474
cmdavis4/senior-thesis
/spherical_geo.py
3,242
3.65625
4
#+++++++++++++++++++++++++++++++++++++++ # # Spherical Geometry # # Description: # This file contains the functions for # spherical geometry calcuations # including rotations, coordinate transformations # and angular separations # #--------------------------------------- import numpy as np import numpy.linalg as LA ...
dd50743885e2a849652cef7243486196ce364b33
vikramdayal/RaspberryMotors
/example_simple_servo.py
2,287
4.0625
4
#!/usr/bin/env python3 ''' simple example of how to use the servos interface. In this example, we are connecting a sinle servo control to GPIO pin 11 (RaspberryPi 4 and 3 are good with it) Wiring diagram servo-1 (referred to S1 in the example code) --------------------------------------------- | servo wi...
13a7cd02724849f25e7775b0fd1045364f3a5b98
Dan609/code_learn
/ipython_log1.py
3,943
3.75
4
# IPython log file get_ipython().run_line_magic('logstart', '') class Car: speed = 5 car1 = Car() car2 = Car() car1.engine car2.engine car1.engine = 'V8 Turbo' car1.engine car2.engine Car.wheels = 'Wagon wheels (' c1.wheels car1.wheels Car = Car() Car new_car = Car() Car.speed car1.speed ...
ecb3c2aa29cc645e011d5e599a0ed24eb1f983b2
PraneshASP/LeetCode-Solutions-2
/69 - Sqrt(x).py
817
3.9375
4
# Solution 1: Brute force # Runtime: O(sqrt(n)) class Solution(object): def mySqrt(self, x): """ :type x: int :rtype: int """ sqrt = 1 while sqrt*sqrt <= x: sqrt += 1 return sqrt-1 # Solution 2: Use Newton's iterative method to repeatively "guess"...
3785a9becaf8fad4904ea2ec560aec3e6da7de03
PraneshASP/LeetCode-Solutions-2
/277 - Find the Celebrity.py
1,748
3.796875
4
# Solution 1: This problem is the same as finding a "universal sink" in a graph. # A universal sink in the graph => there is no other sink in the graph, so # we can just iterate through the nodes until we find a sink. Then check if it's universal. # O(n) runtime, O(n) space class Solution(object): def findCelebri...
b535625fb73b96be2ba8156e9f77c789b9b6e29a
PraneshASP/LeetCode-Solutions-2
/90 - Subsets II.py
2,191
3.78125
4
# Solution 1: It is sufficient to just do a lookup to see if we # have already made an existing subset. Runtime = O(nlogn * (2^n)) # You may see the sort in the loop and say it's O(nlogn * (2^n)), which # isn't wrong, but note that there is actually only one subset of length n. # There are exponentially more subsets ...
d68997dde4826ce9781322db961198d8ac537173
PraneshASP/LeetCode-Solutions-2
/300 - Longest Increasing Subsequence.py
5,129
3.828125
4
# Solution 1: An O(n^2) algorithm is to start from the back of the array. # Observe that the last element creates an LIS of size 1. Move to the # next element, this will either create an LIS of size 2 (if it is smaller # than the last element), or a new LIS of size 1. # Repeat this process by moving backwards through t...
4da19128caf20616ecbd36b297022b1d3ccb92ce
PraneshASP/LeetCode-Solutions-2
/234 - Palindrome Linked List.py
1,548
4.1875
4
# Solution: The idea is that we can reverse the first half of the LinkedList, and then # compare the first half with the second half to see if it's a palindrome. # Definition for singly-linked list. # class ListNode(object): # def __init__(self, x): # self.val = x # self.next = None class Solution...
9fa0f80646fcba2e31f4d42327304c335459cf81
indefinitelee/Interview-Stuff
/numbers.py
918
3.703125
4
def main(): f("12365212354", 26) def f(numbers, target): for i in range(1, len(numbers)): current = int(numbers[0:i]) to_end = numbers[i:-1] evaluate(0, current, to_end, target, current) def evaluate(sum, previous, numbers, target, out): if len(numbers) == 0: if sum + previ...
e1557d11a69c703d33d90b123f65d8b34d0c69d2
iainhemstock/Katas
/BinarySearch/python/BinarySearch.py
468
3.78125
4
def find_index_of(value, list): index = -1 if len(list) == 0: index = -1 else: lowpoint = 0 highpoint = len(list) while lowpoint < highpoint: midpoint = int((lowpoint + highpoint) / 2) if value == list[midpoint]: index = midpoint ...
9598e90194eb277fd04ea04f0bb09b10083ab33d
iainhemstock/Katas
/LcdDisplay/python/main.py
1,000
3.703125
4
from lcd_digits import one, two, three, four, five, six, seven, eight, nine, zero def parse(input): switcher = { "1" : one, "2" : two, "3" : three, "4" : four, "5" : five, "6" : six, "7" : seven, "8" : eight, "9" : nine, "0" : zero ...
ac95a08e0f92a66b9d1df15cddf154c33bc1befa
iainhemstock/Katas
/PrimeFactors/python/main.py
916
3.828125
4
import unittest class PrimeFactors(): def of(n): list = [] divisor = 2 while n >= 2: while n % divisor == 0: list.append(divisor) n /= divisor divisor += 1 return list class PrimeFactororizerShould(unittest.TestCase): def ...
b551eb195b0f3f912eb56fbb774f6054488ee8bd
jigarshah2811/Python-Programming
/6-DS-Graph/test_graph.py
1,804
3.796875
4
from Graph import Graph """ TEST CASES """ print("\n============ Directed Graph ==============\n") g = Graph() edges = [ ("A", "B", 7), ("A", "D", 5), ("B", "C", 8), ("B", "D", 9), ("B", "E", 7), ("C", "E", 5), ("D", "E", 15), ("D", "F", 6), ("E", "F", 8), ("E", "G", 9), ("F...
869edf4c975e41ccdee0eacfbda1a636576578fc
jigarshah2811/Python-Programming
/Matrix_Print_Spiral.py
1,741
4.6875
5
""" http://www.geeksforgeeks.org/print-a-given-matrix-in-spiral-form/ Print a given matrix in spiral form Given a 2D array, print it in spiral form. See the following examples. Input: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 Output: 1 2 3 4 8 12 16 15 14 13 9 5 6 7 1...
4d07e9f7c2199352a664077c93d640d55304e84a
jigarshah2811/Python-Programming
/Interviews/Meta/SlidingWindow-PartitionArray.py
1,479
3.859375
4
""" Q: Partition Array so that Sum of all partitions are SAME Given an array of integers greater than zero, find if there is a way to split the array in two (without reordering any elements) such that the numbers before the split add up to the numbers after the split. If so, print the two resulting arrays. === Test c...
5ea6b05ac7cd8c380f3e58b0f667c3ee021a0214
jigarshah2811/Python-Programming
/4-DS-LinkedList/LinkedList.py
1,839
3.953125
4
class Node: def __init__(self, val, next=None): self.val = val self.next = next class LinkedList: def __init__(self, val=0): self.head = None def __append__(self, val): if self.head is None: self.head = self.Node(val) return # Append at the ...
0fdb0ee310f777deb4a7de34085615bfe3d5802b
jigarshah2811/Python-Programming
/1-DS-Array-String/CarParking.py
1,080
3.734375
4
class Solution: def parkingCars(self, parking): freeSlot = len(parking)-1 for i, car in enumerate(parking): if car == i: # If Car#K is already at ParkingSlot#K then no movement required continue # For car#i find target slot#i targe...
1c89bf03246ff0284b01255ec5827ff2866c8041
jigarshah2811/Python-Programming
/Algo-Sorting-Searching/BinarySearch.py
1,014
4.09375
4
from typing import List class Solution: def BinarySearch(self, nums: List[int], target: int) -> int: # Binary search works only for sorted array, so make sure array is sorted # Setup indexes, low and high and move them around low++ or high-- based on mid value low, high = 0, len(nums)-1...
3a369371f4bfaf5ebade5192a371a1d3e0214101
jigarshah2811/Python-Programming
/1-DS-Array-String/Array-Misc-Easy.py
3,101
4
4
from typing import List, Tuple """ STRATEGY: Map, Modify as you go... """ class Solution: def insertionSort(nums): for i, num in enumerate(nums): # Move elements of arr[0..i-1], that are # greater than key, to one position ahead # of their current position ...
8d68737c1826c508a060af1873b139fa083af8f5
jigarshah2811/Python-Programming
/Algo-Sorting-Searching/BS-RandomPickUniformDistribution.py
1,736
3.5625
4
import random class Solution: def __init__(self, w: List[int]): # Generate [1/8, 3/8, 4/8] totalWeight = sum(w) for i, weight in enumerate(w): w[i] = weight / totalWeight # Generate on number line for uniform distribtion betwee 0%-100% # [1/8, 4/8, 1]...
dddd4ff528366a9bde62d630ef80f23abaeaa390
jigarshah2811/Python-Programming
/5-DS-Tree/LL.py
14,608
3.984375
4
from TREE import TreeNode class ListNode(object): def __init__(self, val, next=None): self.val = val self.next = next class DLLNode(object): def __init__(self, item): self.val = item self.next = None self.prev = None # Definition for a Node. class RandomListNode: ...
b766eddd7865f3735da5cc59e44c22225c8cf644
jigarshah2811/Python-Programming
/Algo-DP/Longest_SubString_Without_Repeat.py
1,555
4.03125
4
""" Longest Substring Without Repeating Characters https://leetcode.com/explore/interview/card/top-interview-questions-medium/103/array-and-strings/779/ https://www.geeksforgeeks.org/length-of-the-longest-substring-without-repeating-characters/ """ def longestUniqueSubStr(str): # HashMap {Char --> IndexLastSeen...
56a53a69ddeb8f267a9ff221c3e91a7433af985a
jigarshah2811/Python-Programming
/8-DS-Design/HashMap.py
2,321
3.859375
4
""" https://leetcode.com/problems/design-hashmap/discuss/185347/Hash-with-Chaining-Python """ class ListNode: def __init__(self, key, val): self.pair = (key, val) self.next = None class HashMap: def __init__(self): """ Initialize DS here: A HashMap is List of 1000 nodes, Each...
4a5fc85b209138408683797ef784cbd59dd978fe
jigarshah2811/Python-Programming
/LL_MergeSort.py
2,556
4.625
5
# Python3 program merge two sorted linked # in third linked list using recursive. # Node class class Node: def __init__(self, data): self.data = data self.next = None # Constructor to initialize the node object class LinkedList: # Function to initialize head def __init__(self): s...
34860ea98e636d64ada5e34e3d025dcc898a23b1
jigarshah2811/Python-Programming
/Algo-Greedy/timePlanner.py
1,814
3.578125
4
class Solution(object): def planner(self, slotsA, slotsB, targetDuration): res = [] a, b = 0, 0 start, end = 0, 1 while a < len(slotsA) and b < len(slotsB): A = slotsA[a] B = slotsB[b] if self.overlaps(A, B): print(("Overlapping...
ea993d762ecccbaf00c838eecd5530604263057e
jigarshah2811/Python-Programming
/Algo-Backtracking-Recurssion/5_GraphColor.py
1,598
3.90625
4
class Solution: def graphColor(self, graph, V, numColors): def isSafe(curV, c): # Check if this color is not applied to any connection of V. for i in range(V): print(("Checking vertex: [0]".format(curV))) if graph[curV][i] and c == color[i]: # Ther...
483184733d370d27c5b02dbaf2d578cac47f8701
jigarshah2811/Python-Programming
/7-DS-Heap/TopKFreq.py
1,699
3.78125
4
from typing import List import collections import heapq class Solution: """ DS: Freq Map Algorithm: Bucket Sort FreqMap {num: times} Bucket {times: [num1, num2, num3]} """ def topKFrequent(self, nums: List[str], k: int) -> List[str]: # Create Freq Map # {num: times} freqMap = coll...
f9e0bf6998f5ee9065ca8b27e56baa95907cb486
jigarshah2811/Python-Programming
/Advance-OOP-Threading/OOP/ClassObject.py
1,422
4.53125
5
""" This is valid, self takes up the arg! """ # class Robot: # def introduce(self): # print("My name is {}".format(self.name)) # # r1 = Robot() # r1.name = "Krups" # #r1.namee = "Krups" # Error: Because now self.name wouldn't be defined! # r1.introduce() # # r2 = Robot() # r2.name = "Pasi" # r2.intr...
082fb020db06e9d58f4ff9d06abe8fd3db745131
jigarshah2811/Python-Programming
/Algo-Backtracking-Recurssion/Recur_BackTracking_WordSearch_Matrix.py
1,733
3.734375
4
class Solution(object): def exist(self, board, word): ###### BACKTRACKING ########## # 1) Breath -->: Go through all cells in matrix for i in range(len(board)): for j in range(len(board[0])): # 2) isSafe --> Constraint: Word char match # 3) Depth...
30947d19e31e5d58137168d179d797d3f9c2a333
jigarshah2811/Python-Programming
/3-DS-Stack-Queue/IncreasingStack-LargestAreaRectangle.py
1,666
3.90625
4
def largestRect(hist): stack = list() maxArea = 0 # Go through the hist once i = 0 while i < len(hist): if (not stack) or (hist[i] >= hist[stack[-1]]): # Increasing sequence so keep adding indexes on stack stack.append(i) print(("Push index: {0}, curren...
f8290f38eb41af185b5ae229ea1fe60c9b887fc5
jigarshah2811/Python-Programming
/Pattern_BitManipulation_Sets/Bit_Manipulation.py
1,578
3.578125
4
class Solution(object): def countBits(self, value): count = 0 while value != 0: if value & 1: count = count + 1 value = value >> 1 return count def setBit(self, value, bitNum): value = value | (1 << bitNum) return value def r...
da82f9c03c227499e5f72a758513c8e71a1f43cd
jigarshah2811/Python-Programming
/Algo-Sorting-Searching/Array_BinarySearch.py
5,031
3.875
4
import collections import sys """ Regular Binday Search """ class Solution(object): def binsearch(self, nums, target): low, high = 0, len(nums)-1 while low < high: mid = (low + high) >> 1 if target == nums[mid]: # Check if target is HERE return mid ...
aef347e759278a90472b16dc638a64282aabb574
jigarshah2811/Python-Programming
/Stack_LargestRectangleInHistogram.py
3,616
3.640625
4
from STACK import Stack """ http://www.geeksforgeeks.org/largest-rectangle-under-histogram/ """ def LargestRectangleInHistogram(hist): s = Stack() i = 0 max_area = 0 # Scan through Histogram while i < len(hist): # Increasing ---> Current Hist > Prev Hist if s.isEmpty() or hist[i...
67c3f537284076c7a52854c5d1dc7a58d99d908d
jigarshah2811/Python-Programming
/Algo-DP/DP_LCS.py
607
3.546875
4
""" http://www.geeksforgeeks.org/dynamic-programming-set-4-longest-common-subsequence/ """ def LCS(str1, str2): m = len(str1) n = len(str2) L = [[0]*50]*50 for i in range(len(str1)+1): for j in range(len(str2)+1): if i == 0 or j == 0: L[i][j] = 0 elif s...
8fe0bcd0540ab6b12b3db8f6fa0619f218f0d89b
jigarshah2811/Python-Programming
/Hash_Last2ShortestStrings.py
670
3.828125
4
k = 3 mydict = {} def insert(str): global k global mydict try: mydict[len(str)] = mydict[len(str)].append(str) except KeyError: mydict[len(str)] = [str] sortedKeys = sorted(mydict.iterkeys()) # mydict = sorted(mydict, key=lambda item: item[0], reverse=True) inserted = 0 ...
923c91352c1941344adada6d21014b06ce7add3d
jigarshah2811/Python-Programming
/8-DS-Design/DS_bloom_filter.py
960
3.71875
4
""" Space efficient probablistic DS for membership testing Google uses it before Map Reduce """ from random import seed, sample class BloomFilter(object): def __init__(self, iterable=(), population=56, probes=6): self.population = range(population) self.probes = probes self.data = set() ...
2949f87f4092c51a398b8a3081bb45a42b010432
jigarshah2811/Python-Programming
/Pattern-2-Pointers/2.MultiPassPattern-ProductExceptSelf.py
2,519
3.734375
4
from math import prod from typing import List """ Pattern: Multi-Pass L -----> & <------- R L = Prefix L Running Multiplier R = Suffix R Running Multiplier Result = Multiplier of (Prefix L * Suffix R) Next Q: Trapping Rain Water! """ class Solution: def productExceptSelf(self, nums: List[int]) -> List[int]: ...
6bbd0b28467b15d9d3d5103b41375d6c79999f6c
brunda4/Trees-1
/solution41.py
1,036
3.59375
4
class Solution: prev=None #initializing the global variabe prev to hold the previous node def isValidBST(self, root: TreeNode) -> bool: return self.inorder(root) #caling the inorder function for root def inor...
b510a87a4c15901bfb22b5568623d78be1a35d6d
EFulmer/sorts_of_sorts
/merge_sort.py
895
4.0625
4
# Standard merge sort, done in Python as an exercise. from math import floor from random import shuffle def merge_sort(ls): if len(ls) <= 1: return ls # in smaller arrays, it'd be better to do insertion sort to reduce overhead mid = int(floor(len(ls)/2)) left = merge_sort(ls[0:mid]) right ...
28a8e6ee2b125056cfe0c3056d6e3a92ba5e4a65
sabeeh99/Batch-2
/fathima_ashref.py
289
4.28125
4
# FathimaAshref-2-HelloWorldAnimation import time def animation(word): """this function takes the input and displays it character by character with a delay of 1 second""" for i in word: time.sleep(1) print(i, end="") animation("Hello World")
7fa5ac027e065348e292847aa7b03933fc57bef0
Andriy-Hladkiy/ITEA_Python_Basic
/topic_1/task_4.py
213
3.828125
4
# Напишите программу, которая сортирует заданный список из чисел list = ['topic_1', '23', '435', '143', 'topic_2', 'topic_1'] print(sorted(list, key = int))
56a57411d7f44b8a7c15b69fcbf11ac3001f3ab4
hanucane/dojo
/Bootcamp/bootcamp-python/python_algorithm/lambda.py
245
3.96875
4
def map(list, function): for i in range(len(list)): list[i] = function(list[i]) return list print( map([1,2,3,4], (lambda num: num*num) )) print( map([1,2,3,4], (lambda num: num*3) )) print( map([1,2,3,4], (lambda num: num%2) ))
1fda8b3fd2d9f8aa385c9f365ae983fde0bc711a
hanucane/dojo
/Bootcamp/bootcamp-algorithms/linked-lists/SLists.py
1,353
3.625
4
class Node: def __init__(self, value): self.value = value self.next = None self.prev = None class SList: def __init__(self, value): node = Node(value) self.head = node def printAllValues(self): runner = self.head while runner.next != None: ...
d2f96447565c188fcc5fb24a24254dc68a2f5b60
hanucane/dojo
/Online_Academy/python-intro/datatypes.py
763
4.3125
4
# 4 basic data types # print "hello world" # Strings # print 4 - 3 # Integers # print True, False # Booleans # print 4.2 # Floats # print type("hello world") # Identify data type # print type(1) # print type(True) # print type(4.2) # Variables name = "eric" # print name myFavoriteInt = 8 myBool = True myFloat = 4.2 ...
cdb6fb12e74cffd7dce421a4edd389d02d2b4523
haalogen/hash_table
/func.py
2,197
3.703125
4
"""Basic functionality of the project "Hash_Table".""" def float2hash(f): """Float value to hash (int)""" s = str(f) n_hash = 0 for ch in s: if ch.isdigit(): n_hash = (n_hash << 5) + n_hash + ord(ch) # print ch, n_hash return n_hash class HashTable(ob...
eb392b54023303e56d23b76a464539b70f8ee6e8
shamim-ahmed/udemy-python-masterclass
/section-4/examples/guessinggame6.py
507
4.1875
4
#!/usr/bin/env python import random highest = 10 answer = random.randint(1, highest) is_done = False while not is_done: # obtain user input guess = int(input("Please enter a number between 1 and {}: ".format(highest))) if guess == answer: is_done = True print("Well done! The correct ans...
7a3191f98809ba4587415bae2f7f638446c5d8c6
shamim-ahmed/udemy-python-masterclass
/section-12/examples/condcomp1.py
1,472
3.8125
4
#!/usr/bin/env python menu = [ ["egg", "spam", "bacon"], ["egg", "sausage", "bacon"], ["egg", "spam"], ["egg", "bacon", "spam"], ["egg", "bacon", "sausage", "spam"], ["spam", "bacon", "sausage", "spam"], ["spam", "egg", "spam", "spam", "bacon", "spam"], ["spam", "egg", "sausage", "spam"...
3d1946247a3518c4bd2128786609946be2ae768c
shamim-ahmed/udemy-python-masterclass
/section-4/exercises/exercise11.py
638
4.21875
4
#!/usr/bin/env python3 def print_option_menu(options): print("Please choose your option from the list below:\n") for i, option in enumerate(options): print("{}. {}".format(i, option)) print() if __name__ == "__main__": options = ["Exit", "Learn Python", "Learn Java", "Go swimming", "Have di...
f9610b35b3785f1cd0b5a7ae4f00e2cd9856034a
shamim-ahmed/udemy-python-masterclass
/section-4/examples/strings3.py
279
4.0625
4
#!/usr/bin/env python number = "9,223;372:036 854,775;807" separators = "" for c in number: if not c.isnumeric(): separators += c print(separators) values = "".join([c if c not in separators else " " for c in number]).split() print([int(val) for val in values])
75f04b946796c071f7913bf308f0bf1c40a4c441
shamim-ahmed/udemy-python-masterclass
/section-4/examples/conditions.py
135
4.15625
4
#!/usr/bin/env python3 age = int(input("Please enter your age: ")) if age >= 16 and age <= 65: print("Have a good day at work!")