blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
0db9e05a89c426eb2ce0502ad9acb4967e2ac848
Hackin7/Programming-Crappy-Solutions
/Cyber Security/Capture the Flag Competitions/2020/Cyberthon 2020/Online Training/Web/Pangea/test.py
752
3.609375
4
import json flag = open('flag.txt').read().strip() country_code = {} with open('countries.json') as f: country_code = json.loads(f.read()) class Country(object): def __init__(self, name, code): self.name = name self.code = code countries = {x:Country(x, country_code[x]) for x in count...
a2547de23f76fd41d1730130b39bee1ccc621db5
Hackin7/Programming-Crappy-Solutions
/School Exercises/2. NYJC A Level Computing 2019-2020/Practicals/Practical 13/main.py
1,958
4.0625
4
def bubblesort(Admissions): comparisons = 0 UpperBound = len(Admissions) NoSwaps = False while NoSwaps == False: NoSwaps = True for Posn in range(0, UpperBound-1): comparisons += 1 if Admissions[Posn] > Admissions[Posn + 1]: # swap ...
64ecf2f6d7eac5ce5d98ff2407fe0758f4821ef7
Hackin7/Programming-Crappy-Solutions
/School Exercises/2. NYJC A Level Computing 2019-2020/Other School Papers/2020 Prelim/NJC P2/Task_1 Server Client Test/client.py
2,631
3.6875
4
#Task 1.5 ### Socket Code ############################################################ import socket class Connection(): def __init__(self, ip, addr): self.ip = ip self.addr = addr def server(self): self.socket = socket.socket() self.socket.bind((self.ip, self.addr))...
773435c864ab0f724aa09c119887ef7ee564e106
Hackin7/Programming-Crappy-Solutions
/School Exercises/2. NYJC A Level Computing 2019-2020/Practicals/Practical 1/Q2.py
286
3.984375
4
print("a a^2 a^3") # Table header for a in range(1,4+1): square = str(a**2)+ " " cube = str(a**3) # Add a spacing if it is only single digit, # so that the table is spaced properly if int(square) // 10 == 0: square+=' ' print(str(a)+' ',square,cube)
c87a340e88bf81d134e61107bff1ab33117bd50b
Hackin7/Programming-Crappy-Solutions
/School Exercises/2. NYJC A Level Computing 2019-2020/CPDD Tutorials/NoSQL Databases Tutorials/Lesson 2 Using PyMongo/Q9.py
1,393
3.625
4
import pymongo client = pymongo.MongoClient("127.0.0.1",27017) db = client.get_database("db") def insert(coll): title = input("Enter title: ") date = input("Enter date: ") time = input("Enter time: ") venue = input("Enter venue: ") price = int(input("Enter price in dollars: ")) coll.i...
3b7b2b4b9279d5aa09605173d57b16b40bf4e745
Hackin7/Programming-Crappy-Solutions
/School Exercises/2. NYJC A Level Computing 2019-2020/Practicals/Practical 1/Q6.py
291
4.09375
4
gender = input("Are you male(m/M) or female(f/F):") if gender in ['f','F']: print("Female") elif gender in ['m','M']: print("Male") else: #Other conditions print("Invalid character entered. \n" "Please enter 'm' or 'M' for male " "or 'f' or 'F' for female")
f64a4899917b486aea2126de40d638835efba260
BadgerPc/Tutorials-1
/dependency-inject-flask/MyDatabase.py
516
3.75
4
from abc import ABC, abstractmethod class DatabaseBase(ABC): def __init__(self): pass @abstractmethod def connect(self): pass @abstractmethod def get(self): pass class MySqlDatabase(DatabaseBase): def __init__(self): super().__init__() def connect(self)...
e63795a746b7f3063af15d5196ff4a9be4b92e49
VishwaSheth03/StockPredictApp
/StockPredict_website/stock_predict.py
2,330
3.53125
4
import requests import json import matplotlib.pyplot as plt import re import numpy as np import pandas as pd API_KEY = '58SXCV92ZE1JUZ62' STOCK_NAME = 'AAPL' def gradient_descent(alpha, x, y, m, day): theta0 = 1 theta1 = 1 prevJ = 2 J = 0 while abs(J - prevJ) > 1: temp0 = theta0 temp1 = theta1 ...
73fc6181e86b35d3d87e9c7715a4e504c7a2e119
tauCourses/TwoSquareRobotsMotionPlanning
/gen_snake_polygon.py
2,832
3.515625
4
#!/usr/bin/python from __future__ import print_function import argparse ipe_format = False class Point: def __init__(self, x, y): self.m_x = x self.m_y = y def __add__(self, other): return Point(self.m_x + other.m_x, self.m_y + other.m_y) def print_point(p, fp, first=False): if not ipe_format: ...
08068a47448ec5a17af82b4372992c5775677024
KevinHuang8/data-science-and-machine-learning
/algorithms and implementations/CS 156/linear_regression.py
1,441
3.546875
4
import random import matplotlib.pyplot as plt import numpy as np N = 100 # Target function def f(x): return np.dot(true_weights, x) def f_line(x): return true_weights[0] + true_weights[1] * x def h_line(w, x): return w[0] + w[1] * x def generate_data(N): """Generate data based on target function""" data = [] ...
c81b17bfa33ffad71c06c7a01b2cc1883972e04e
pnugues/ilppp
/programs/ch10/python/eliza.py
1,637
3.71875
4
""" A simplified implementation of ELIZA """ __author__ = "Pierre Nugues" import regex as re import numpy as np dialogue_pairs = { '.*I am not (.+)': [ r'Why aren\'t you \1' ], '.*I am (.+)': [ r'How long have you been \1' ], '.*I like (.+)': [ r'Why do you like \1' ], ...
a737062bed2e342e29a4811dceedee615bfb55d8
pnugues/ilppp
/programs/ch05/python/tokenizer.py
2,004
4.03125
4
""" Tokenizers Usage: python tokenizer.py < corpus.txt """ __author__ = "Pierre Nugues" import sys import regex as re text = """Tell me, O muse, of that ingenious hero who travelled far and wide after he had sacked the famous town of Troy.""" def tokenize(text): """uses the nonletters to break the text into wor...
32561c1498eb3448f1496c43866084b17a6a8215
pnugues/ilppp
/programs/ch04/python/gradient_descent_numpy.py
4,419
3.59375
4
"""Gradient descent for linear regression with numpy """ import random import numpy as np import datasets import matplotlib.pyplot as plt __author__ = 'Pierre Nugues' def sse(X, y, w): """ Sum of squared errors :param X: :param y: :param w: :return: """ error = y - X @ w return er...
1e2c1c4b38b6d245b0faa7aec16ca3f881670a9d
EmileClement/Saph_201_RobotCup
/Saph_201_RobotCup-master-2/Com/evaluation/vecteur.py
1,160
3.515625
4
# -*- coding: utf-8 -*- """ Created on Thu May 7 11:36:08 2020 @author: Leopold """ import numpy as np class Vecteur(): def __init__(self, x=0, y=0, theta=0): self.x, self.y, self.theta = (x, y, theta) def __add__(self, other): return Vecteur(self.x + other.x, self.y + other.y, self.theta +...
b3191607803432bc52faccfc7b9940752f51c0b8
charlee120/pythonprojects
/iterating using loop.py
221
3.859375
4
my_list=[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15] rakesh=iter(my_list) n=int(input("Enter a number:")) if n == len(my_list): for i in range(n): print(next(rakesh)) else: print("invalid input")
2579181347f943ad1794e650dee3b41f832ea2c4
Shrey19702/Student_dEV
/Python Projects/basicLR.py
1,093
3.765625
4
import numpy as np from sklearn import datasets, linear_model from sklearn.metrics import mean_squared_error import matplotlib.pyplot as plt diabetes = datasets.load_diabetes() # print(diabetes.keys()) diabetes_X = diabetes.data[:, np.newaxis, 2] # diabetes_X = diabetes.data for +1 features diabetes_Y = dia...
5ed1f9466bf4b2a690d1c8150a85ea1d2666133e
azure0309/international_call_making_rating
/basic.py
940
3.53125
4
class Country(object): def __init__(self, name, country_code, rating): self.name = name self.country_code = country_code self.rating = rating def describe_country(self): country_description = { 'name': self.name, 'country_code': self.country_code, 'rating': self.rating } return country_descripti...
3b2603ecacfd11cedfa47c2507495529c2f90f54
EmiTartarini/Mision_02
/mision 2 resuelto/velocidad con codigo.py
428
3.9375
4
# Autor: tuNombreCompleto, tuMatricula # Descripcion: Texto que describe en pocas palabras el problema que estás resolviendo. # Escribe tu programa después de esta línea. #autor: Emiliano Tartarini #comentario: velocidad promedio tiempo = int(input('teclea el tiempo de viaje en hrs. enteras:')) velocidad = int(input(...
5418c24fc4292bb68022ea902d4a3616998d0d1f
adheepshetty/Problem-Solving-with-Algorithms-and-Data-structures
/Stacks/StacksUsingQueues.py
732
3.875
4
class Queue: def __init__(self): self.items = [] def isEmpty(self): return self.items == [] def enqueue(self, item): self.items.insert(0, item) def dequeue(self): return self.items.pop() def size(self): return len(self.items) def StacksUsingQueues(numbers): ...
1bd7e21855d459b7a5fd6f0b3bc8c2ee8ac82b61
ChukwurahVictor/CodeLagosPythonProjects
/simple_interest.py
499
4.3125
4
#Display the purpose of the program print("This program calculates simple interest") #Prompt the user to enter the principal amount principal = float(input("Enter the principal amount: ")) #Prompt the user to enter the rate rate = float(input("Enter the rate: ")) #Prompt the user to enter the time period time = floa...
48bf019ef2d3dd283ad61a5a029353d13deaf7f7
ChukwurahVictor/CodeLagosPythonProjects
/simple_area_calculator.py
1,240
4.25
4
import math #Display the purpose of the program print("This is a program to calculate the area of different shapes") #Display the instructions print("Select the letter of the option with the shape you want to calculate") #Ask the user to enter the shape you want to calculate for shape = input("Please, enter a shape:...
c29ad84f3431f31a54d8e61a7f9822adf3ea34de
ayanchyaziz123/all-competitive-programming-documents-and-problem-solving
/codecheaf/VOWELTB.py
153
3.59375
4
import sys #sys.stdin = open("input.txt", "r") sr = input() L = ['A', 'E', 'I', 'O', 'U'] if sr in L: print("Vowel") else: print("Consonant")
9cdb7413ed1a32bcadc362898fbaf55cc1d54b22
ayanchyaziz123/all-competitive-programming-documents-and-problem-solving
/codecheaf/1.py
624
3.84375
4
# Python3 code to demonstrate # pair iteration in list # using list comprehension from itertools import compress # initializing list test_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16] # printing original list print ("The original list is : " + str(test_list)) # using list compreh...
dabf9dda305971dff3e832ca8d457279f1e42f84
laychopy/functional_python
/church.py
1,749
4.15625
4
# As a simple demo of pure functional programming, # let's do some math using only functions # We encode numbers so that a number `n` # is the following function, lambda f: lambda x: f^n(x), # where f is a function, and x is some value # `zero` would apply f to x zero times, so would just return x zero = lambda f: l...
ba98fdaa2a2905a45258f4f4a0997a9e3c1b7d69
Pav0l/cracking-the-coding-interview
/Linked_lists/isPalindrome.py
1,179
4.28125
4
""" Palindrome: Implement a function to check if a linked list is a palindrome. """ # Make a copy and reverse original linked list # compare nodes in both linked lists # if they are equal => Linked List is a palindrome from node import pal1, n0, Node def reverse_and_copy(node): # temp variable to hold the next n...
dc464ae72f67261f81e671b157988e0194349556
Pav0l/cracking-the-coding-interview
/HackerRank/2d_array.py
1,183
3.59375
4
""" Given a 2D Array, We define an hourglass to be a subset of values with indices falling in this pattern in graphical representation: a b c d e f g Calculate the hourglass sum for every hourglass in arr, then print the maximum hourglass sum. Constrains: -9 <= arr[i][j] <= 9 0 <= i,j <= 5 """ # Given the small...
d919b236a8c5cc975b0f75ec539b161e6c4dab56
Pav0l/cracking-the-coding-interview
/Sorting_and_Search/quickSort.py
2,048
4.21875
4
""" Quick Sort I Runtime: 0 (n log (n)) average, 0 (n2) worst case. Memory: 0 (log (n) ) . In quick sort, we pick a random element and partition the array, such that all numbers that are less than the partitioning element come before all elements that are greater than it. The partitioning can be performed efficiently ...
2bb4077f3648c06100fb430daefca6c49d13e897
Pav0l/cracking-the-coding-interview
/Codility/missing_integer.py
1,395
3.640625
4
""" Write a function that, given an array A of N integers, returns the smallest positive integer (greater than 0) that does not occur in A. For example, given A = [1, 3, 6, 4, 1, 2], the function should return 5. Given A = [1, 2, 3], the function should return 4. Given A = [−1, −3], the function should return 1. Writ...
d1c44afeef63eceff3aca1568e671859e65749db
prasanthn0/Binary-Tree
/app.py
307
3.71875
4
from node import Node from binary_tree import BinaryTree tree=BinaryTree(Node(9)) tree.addNode(Node(11)) tree.addNode(Node(5)) tree.addNode(Node(4)) tree.addNode(Node(3)) tree.addNode(Node(2)) tree.addNode(Node(1)) tree.addNode(Node(6)) tree.inorder() print('---') print(tree.find(13))
a05d5b27a0d981a7c65065145db85657f2b98bbe
FoxieFountai/IfunnyCrawler
/utils/schedule.py
1,430
3.546875
4
import threading import datetime, time class SimpleTasking(threading.Thread): '''execute some functions based on time //hour is write like: Hour:Minute:Second''' def __init__(self): threading.Thread.__init__(self, daemon=True) self.schedules = {} def on(self, executetime = None, f...
9fabb129d69f69d00c12b1773481b75d94c922a0
Lukkai/Embedded-Systems
/cw10/zegar.py
677
3.75
4
import time import os import threading import keyboard t = time.time() #utc time in seconds since 1970 now = time.gmtime(time.time()) #utc time in calculated time structure tm_year, tm_mon, tm_mday, tm_hour, tm_min, tm_sec, tm_wday, tm_yday, tm_isdst = now def seconds(x : int): time.sleep...
b1d949118b806de0262b4f3b1401cd2d5e7d3ba8
bruno-novo-it/python
/Problem_Solving_With_Algorithms_And_Data_Structures/lists.py
2,351
4.46875
4
# Operation Name Operator Explanation # indexing [ ] Access an element of a sequence # concatenation + Combine sequences together # repetition * Concatenate a repeated number of times # membership in Ask whether an item is in a se...
c3746534567bf6a296e033c4fee470a68e4eb86e
bruno-novo-it/python
/files.py
342
3.9375
4
### Playing With Files ### def print_lines_file(some_file): for line in open(some_file): print(line) f = open('data.txt','w') f.write('Hello ') f.write('world\n') f.close f = open('data.txt') text = f.read() print("Texto lido do arquivo: ",text) print("Texto lido dividido: ",text.split()) print_l...
de081f1e0889cb873b0e2b4d4caac9c45d13e6b7
s-avra/CEBD1100-intro2
/Assignment2/account_types/main_account.py
2,534
3.78125
4
from babel.numbers import format_currency class Account: def __init__(self, balance, interest_rate): self.balance = balance self.starting_balance = 0 + balance self.withdraw_count = 0 ##deposit count starting at zero to keep monthly deposit count accurate. Starting balance not inclu...
ffd7d4f3eb1c36f909736d6afe054cc48adfd531
s-avra/CEBD1100-intro2
/Class 7/bookexample.py
758
3.765625
4
class Book: def __init__(self, isbn, title,used): self.isbn = isbn self.title = title self.owner = "westmount library" self.used = used #book has 3 attributes, only 2 are supplied # self must be first parameter for constructor, # indicates value belongs to class def is_book_used...
90e564c24731edb07d857b21863048014f67e194
s-avra/CEBD1100-intro2
/Class 6/specifying_parameters.py
839
3.640625
4
def describe_pet(pet_name= "spot", animal_type= "dog"): print("Pet name is "+ pet_name) print("Animal type is "+ animal_type) describe_pet() describe_pet("Jack") describe_pet("Jack", "Cat") #how to specify animal type describe_pet(animal_type="fish") #named parameter def generate_namr(first:str, last: str ="Un...
959f30020d330357428b5106793df87bfd807bd4
s-avra/CEBD1100-intro2
/Class 3/ifstatement.py
736
4.375
4
#ask a user to enter their name #tell the user if their name is more than 5 letters x= 5 if x==5: print("the number is 5") else: print("not a 5") user_name = input("what is your name>>>") if len(user_name)<=5: print("Your name has five letters or less") else: print("your name is longer than 5 letters")...
a8315bfac4f5f81163cbb14ebed64f657b89b312
s-avra/CEBD1100-intro2
/Class1/userinput.py
349
4.03125
4
user_name = input("What is your name? >>>") print("Hello " + user_name) num_1 = input("Enter the first number >>>") num_2 = input( "Enter the second number >>>") print(" The sum of the two numbers is " + str(int(num_1) + int(num_2))) ##now make it clean number_sum = int(num_1) + int(num_2) print("the sum of the num...
65c48c658277f72eb5aa478959db5c2c8e35e8c5
leeyubin10/Python_study
/bird.py
421
3.5
4
import random time = random.randint(1,24) print('좋은 아침입니다. 지금 시간은' , str(time),'시입니다.') sunny = random.choice([True,False]) if sunny: print('날씨가 화창합니다') else: print('현재 날씨가 화창하지 않습니다') if time >= 6 and time <= 9 and sunny: print('종달새가 노래를 합니다') else: print('종달새가 노래를 하지 않습니다')
d9df7fbd2938efacbe97d0dd07b1b90fbf509bbe
leeyubin10/Python_study
/9주차 과제_.py
2,936
3.546875
4
from tkinter import * import tkinter.messagebox window = Tk() click = True def btnClick(btns): global click if btns["text"] == "" and click == True: btns["text"] = "X" btns['bg'] = 'yellow' click = False checkForWin() elif btns["text"] == "" and click == False: ...
a666514f311a7de0f3842714f2e7b2966777e7f0
leeyubin10/Python_study
/lab12-3.py
568
3.734375
4
class BankAccount: def __init__(self): self.__balance = 0 def withdraw(self, amount): self.__balance -= amount print("통장에서 ", amount, "가 출금되었음") return self.__balance def deposit(self, amount): self.__balance += amount print(" 통장에 ", amount, "가 입급되었음") ...
c4d4830cdbe616a2c342883a6289154fc72e196a
timaeus321/SuperSyllabus
/SyllabusMain.py
855
3.65625
4
import Syllabus as Syl #examples of how to use the Syllabus class classDays = ["tuesday","thursday"] labDays = ["tuesday","thursday"] class1 = Syl.Syllabus("CSCE315","506",classDays ,labDays ,"11:10 - 12:25","6:40 - 7:30","ZACH","rob.lightcsce315@tamu.edu","Wednesday 9 - 11 am Or by appointment.") print(class1.getAll(...
c81d344bbf647ff809195006954672638fbc61f4
FalcoQc/Casino
/tp1 - copie.py
1,690
3.703125
4
from random import randrange continuer_la_partie = True gains_totaux = 0 print("Pour jouer à la roulette vous devez choisir une case entre 0 et 49 suivi d'une mise") while continuer_la_partie == True: i = 0 while i != 1: try: numero_choisi = int(input("Quelle case choisissez vous \n> ")) mise_de_départ = i...
ff3e928510651499dd8403da43babf88d219cf79
krawsssyy/Python-Basic-OOP-Project
/Domain/FilmValidator.py
1,745
3.8125
4
EPSILON = 0.000000001 class FilmValidator: ''' Represents a validator for a film ''' @staticmethod def representsInt(value): ''' Tests if a value can be safely converted to an integer :param value: - int - to be tested :return: True or False whether the in...
e144c80cbb41af74bde44aea3c96ff84fadf9b60
krzysieknaw/Algorithms_and_Data_Structures
/data_structures/stack_implementation.py
798
3.890625
4
class Stack: def __init__(self): self.items=[] def print_elements(self): elem = [] for i in range(len(self.items)): elem.append(self.items[i]) print(elem) def isEmpty(self): return self.items == [] def push(self, items): ...
c8f46243ac2544da77f989a4c30952252fcacd94
200202iqbal/game-programming-a
/Practice Python/os_library/exercise01.py
491
3.84375
4
#using os library #change directory to temp #creating a folder in temp import os currentDirectory = os.getcwd() targetDirectory = currentDirectory+"/temp" os.chdir(targetDirectory) #change directory to targetDirectory if (os.getcwd() == targetDirectory): print("OK") else: print("Failed") #print(os.getcwd()) ...
509974f2abf2125f7758891dc49a3c093c969464
200202iqbal/game-programming-a
/Paiza/D168.py
242
4
4
#日付の表記 / Year = int(input()) Month = int(input()) Day = int(input()) rule = Year >=1 and Year <= 2050 and Month >=1 and Month <= 12 and Day >= 1 and Day <=31 if(rule): print(Month,end="/") print(Day,end="/") print(Year)
bb0e2cd5f380d7aee4ea95c9dc3496e7fd546788
200202iqbal/game-programming-a
/Lessons 8/testout01.py
215
3.53125
4
year = 2001 event = "abc" print(f'first {year} {event}') yes_votes = 42_572_654 no_votes = 43_132_495 percentage = yes_votes / (yes_votes + no_votes) print( '{:-9} YES votes {:2.2%}'.format(yes_votes, percentage))
6fa0cc4441d4ba9653b68df92bfc96f2f8427512
200202iqbal/game-programming-a
/Practice Python/tkinter_library/label.py
289
4.125
4
import tkinter as tk window = tk.Tk() label = tk.Label( text="Hello Tkinter", foreground = "white", #set the text color to white background = "black", #set the background color to black width=10, #set the width height=10 #set the height ) label.pack() window.mainloop()
2281b30652ef69a1531e3e3aeb84ea59edc0f057
200202iqbal/game-programming-a
/Paiza/D121.py
247
3.734375
4
string = str(input()) first = string[0] second = string[1:] stringlen = len(string) rule = stringlen == 3, string[0] == "H","S","T","A" if(rule): if(first == "A"): first = "R" print(first+second) else: print(string)
324f8f3a0118fcb84ca342779f260f255c483b42
200202iqbal/game-programming-a
/Error/testerror01.py
397
3.828125
4
#while True print("Hello world") #test error sintaks #x = 10 * (1/0) #ゼロ割 / pembagian 0 #spam = 5 #x = 4 + spam * 3 #y = "2" + 2 while True: try: x = int(input("Please enter: ")) break except (RuntimeError,TypeError,NameError): pass except ValueError: #percobaan print("Tr...
4618a95ead90ee9e4382cb8314630e638d772c98
200202iqbal/game-programming-a
/Practice Python/parsingstring.py
654
3.6875
4
data = "From stephen.marquard@uct.ac.za Sat Jan 5 09:14:16 2008" atpos = data.find("@") print(atpos) sppos = data.find(" ",atpos) print(sppos) host = data[atpos+1:sppos] print(host) # creating a method for passing host def parsehost(string): atpos = string.find("@") sppos = string.find(" ",atpos) if(atpo...
8cd47fdb8ded8dfac53b2c521d2ff86a0f3f6e88
satyasashi/Algorithms_Data_Structures
/Datastructures/stack/stack_linked_list.py
1,084
4
4
class StackNode: def __init__(self, data): self.data = data self.next = None class Stack: def __init__(self): self.head = None def is_empty(self): return True if self.head is None else False def push(self, data): new_node = StackNode(data) print("self....
5e5dcd4d628415ec4aea91c2da2e45d6f0d387d9
satyasashi/Algorithms_Data_Structures
/Datastructures/linked_list/whole_operations.py
6,094
4.5
4
# Simple python program for traversal of a Linked List # Node Class class Node: # function to initialise the node object def __init__(self, data): self.data = data # Assign data self.next = None # Initialize next as Null # Linked list class contains a Node object class LinkedList: # Fun...
7089e7e97e5c272ab39d0f490d94d21083ee2bfb
satyasashi/Algorithms_Data_Structures
/algorithms/Searching/Binary-Search.py
1,315
4.15625
4
# BINARY SEARCH O(Logn) # Take list of sorted items, divide the list by half and take the element # Compare with 'target' element, If picked number is less than 'Target', # then ignore all elements towards left. Now starting element will be next # element from element compared just now. def binary_search_rec(arr, targ...
e121eb82b5f4303464f6fa646aa6454423df8427
satyasashi/Algorithms_Data_Structures
/Datastructures/BinarySearchTree/Binary_Tree_To_BinarySearchTree.py
2,689
4.15625
4
""" Binary Tree to Binary Search Tree can be done in 3 Steps: Step 1: Do inorder traversal of the Binary Tree and copy the elements to an Array Step 2: Sort this array with best feasible algorithm Step 3: Do inorder traversal of the same array and Replace the 'data' of the nodes once the checks are validated. ...
25eed6ac82f9770ced658e0f2f6cc2db97e82c0c
satyasashi/Algorithms_Data_Structures
/Practice/algorithms/substring_search.py
1,346
4.03125
4
""" Given a String, and a Pattern(Substring) to search in the original String. Procedure: 1. We Start with beginning of String and matching beginning of Pattern(Substring). i.e., 0th index <--> 0th index 2. If this matches, we start doing exact match for remaining string followed. 3. We return 1, if we looped till end ...
239861331825f21e7c57d50a87cf16b82b8298d8
satyasashi/Algorithms_Data_Structures
/Datastructures/Queue/queue2.py
1,276
4.21875
4
class Queue(): def __init__(self, size): self.front = 0 self.rear = 0 self.size = size self.queue = [] def enqueue(self, element): # check if queue size is reached. if len(self.queue) == self.size: print("Overflow Error") return # else add the element to queue self.queue = self.queue + [elemen...
6c92223230d1c8c04290e25abeec699295381320
satyasashi/Algorithms_Data_Structures
/Datastructures/linked_list/linked_list_delete.py
3,514
4.375
4
# Node Class class Node: # function to initialise the node object def __init__(self, data): self.data = data # Assign data self.next = None # Initialize next as Null # Linked list class contains a Node object class LinkedList: # Function to initialize HEAD def __init__(self): ...
06ff6f6965269cadd94b7c4c58fa2eeeb6714df8
satyasashi/Algorithms_Data_Structures
/Datastructures/Heap/min_heap.py
4,656
4.28125
4
from os import curdir import sys class MinHeap: """Min Heap is a tree datastructure where every element at node is less than its Descendants or child nodes. We use Array as Heap""" def __init__(self, max_size) -> None: self.max_size = max_size self.cur_size = 0 self.heap = [0]*(ma...
0e41752bb5865d2eaab392b3435064237db3d234
Dchment/Altered_or_Redesigned_models
/TextGeneration/Huffman_Encoding.py
1,220
3.671875
4
#Huffman Encoding #Tree-Node Type class Node: def __init__(self,weight): self.left = None self.right = None self.father = None self.weight = weight def isLeft(self): return self.father.left == self #create nodes def createNodes(weights): return [Node(weight) for weigh...
f435660e5d5411ce504bfd874456b41d82134c88
brichi15/Coding-Practice
/merge sorted array (in place).py
847
3.65625
4
class Solution: def merge(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None: """ Do not return anything, modify nums1 in-place instead. """ n1_ind = m-1 if m <= 0: n1_ind = m+1 n2_ind = n-1 z_ind = len(nums1)-1 ...
0ec02a9735ad32660cdb4b465b955119dc53dd63
brichi15/Coding-Practice
/All Nodes Distance K in Binary Tree.py
1,395
3.71875
4
# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None from collections import deque class Solution(object): def distanceK(self, root, target, K): """ :type root: TreeNode :typ...
f548ed49a5ac5cb06aabd8fc089d18f0e125c3d6
brichi15/Coding-Practice
/Group Anagrams.py
643
3.515625
4
class Solution: def groupAnagrams(self, strs: List[str]) -> List[List[str]]: ans = [] h_map = {} scale = ord('a') ## base letter ascii for word in strs: key = [0]*26 ## 26 letters in alphabet for ...
df6ace6b4dfd8473e333666b7304d84d462b3e9a
brichi15/Coding-Practice
/Algorithms/permutations.py
251
3.59375
4
def permute(string): if len(string) == 1: return string perms = [] for i in range(len(string)): for perm in permute(string[:i] + string[i+1:]): perms.append(string[i] + perm) return perms
74c050c8af4a8f8350245be2f084918b637035a6
brichi15/Coding-Practice
/Two Sum II (sorted input).py
466
3.578125
4
class Solution: def twoSum(self, numbers: List[int], target: int) -> List[int]: front = 0 back = len(numbers)-1 while front < back: cur_sum = numbers[front] + numbers[back] if cur_sum > target: back -= 1 ...
bf57d604df0f42212ae0ecbe45d81e239c7f2875
Laufire/ec
/ec/types/basics.py
809
3.90625
4
r""" basics ====== Basic types, like bool and the likes. """ from ..modules.classes import CustomType class YN(CustomType): """The classic y/n input that returns a truthy/falsy value. """ def __init__(self, **Config): if not 'type_str' in Config: Config['type_str'] = 'y/n' CustomType.__init__(self...
e8d7813ef244a78787b97de3590137a242d01209
nirajlalani/feet2meter
/ft2mt.pyw
1,272
3.625
4
from tkinter import Tk, DoubleVar, Label, Entry, Button window = Tk() window.title("Feet to Meter Conversion App") window.configure(background="light green") window.geometry("280x180") window.resizable(width=False,height=False) def convert(): value = float(feet_entry.get()) meter = value * 0.3048 ...
1feddd174a81e949b1df58646efa5c1c20dcc01a
vedantgune99/RockPaperScissor-Game
/game.py
3,312
3.859375
4
from tkinter import * from random import choice ChoiceList = ["rock", "paper", "scissor"] # Function to determine Win/Lose. def gameState(move, cpu_move): if (move == "rock" and cpu_move == "paper"): state = "CPU Won" user_choice['text'] = "Your Choice : " + move cpu_choice['text'] = "CP...
ce027788c129430a46207712b230911b6d6a3e9b
ichbinchicken/COMP1521-Computer-System-Fundamentals
/quizs/quiz_2/remainder theorem.py
147
3.71875
4
#!/usr/bin/python3 a = 1 for i in range(0, 170): a = (a*85)%256 print(hex(a)) b = 1 for i in range(0, 170): b = (b*a)%256 print(hex(b))
a8e79bfdaf6ffce84e294c2553cf229f22dbdc81
satelite54/BUSAN_IT_ACADEMY
/python/Test/ex7.py
252
3.625
4
import random RandomList = [random.randint(1,50) for i in range(7)] print("생성된 집합 : ", end='') print(RandomList) print("집합에서 가장 큰 수 : " + str(max(RandomList))) print("집합에서 가장 작은 수 : " + str(min(RandomList)))
b1611f191a1e0c5e4e23fb13bbfda6350ed9d320
satelite54/BUSAN_IT_ACADEMY
/python/Test/ex9.py
200
3.65625
4
import random lotto=set() i=0 while True: lotto.add(random.randint(1,45)) i=i+1 if len(lotto)>=6: break print("로또 넘버:",sorted(lotto)) print("중복된 난수 횟수 :",i-6)
9fced666ab79f0860fd0acc97dbd70264e066e13
rishitrainer/augustPythonWeekendBatch
/learn_day02/TestLoop.py
370
4.03125
4
print("Hello World") ''' while condition: block of code will iterate condition is true condition modifier Addition of 1 to 10 ''' count = 1 total = 0 while count <= 10: if count == 6: print("Exiting with break") break total = total + count print("Count Value", count) ...
a4fc6f52fa42059370c5be7f68e9053e7ece1d01
rishitrainer/augustPythonWeekendBatch
/learn_day02/ForLoop.py
469
3.90625
4
''' Add 1 to 10 for eachValue in Collection: block of code for iteration ''' # range (start, end, step) for eachLine in range(1,10): if eachLine == 6: print("Executing continue") continue print(eachLine) for eachValue in range(-11,11,3): print(eachValue) data = ['...
6d05244257be33ea0b34da0c8142516c38f679d3
Harchytekt/IPv4-Delmotte
/code/Mask.py
628
3.75
4
class Mask(object): """Creates a subnet mask object.""" def __init__(self, givenMask): """ Initializes the mask. :param givenMask: The mask """ self.mask = givenMask def __str__(self): """ Prints the mask. :return: the mask """ return str(self.mask) def __repr__(self): """ Prints th...
d3d4f97662f045f431999c0656aa65e9d8b71baa
khaito241/python-beginner
/dictionary/is-unique.py
808
3.828125
4
# Is unique: check if a string has all unique characters import unittest def unique(str): #print(str) #hint hash the table => dict: key-value char_set = {} for char in str: #print(char) if char in char_set: return False char_set[char] = True return True #Tes...
5db1ff89f26f56e4c029d7f4e4bf18019257d092
maletzt/Udacity_Stage3
/media.py
393
3.75
4
class movie: """ A simple movie class that takes movie title, movie poster image url and movie trailer url.""" def __init__(self, title, poster_image_url, trailer_youtube_url): self.title = title self.poster_image_url = poster_image_url self.trailer_youtube_url = trailer_youtube_url ...
788200d07790e663bb448d39b8bdf1bc2ee07f09
SviatikKh/Python
/DateAndDays.py
5,722
3.640625
4
from datetime import date import calendar class MyDate: def __init__(self, year, month, day): self.year = year self.month = month self.day = day # визначення назви місяця українською мовою def month_name(self, i): lst = ['сiчня', 'лютого', 'березня', 'квiтня', 'травня', 'че...
feb1a800fb23b062114916ff07fb07f7059f7c57
SviatikKh/Python
/Tkinter/Button3.py
3,205
3.875
4
from tkinter import * #from tkinter import messagebox #window sizes h_win = 400 w_win = 400 size = str(h_win) +"x" +str(w_win) #fixed button dimensions h_btn1 = 30 w_btn1 = 120 #coordinates of the fixed button for its location in the center of the window x_btn1 = (w_win - w_btn1) //2 y_btn1 = (h_win - h_btn1) //2 #mov...
1d0e54f80db696fee5792a7870cf78a9fc9a2104
felipevw/Applied-Deep-Neural-Networks-Exercises
/tensor_03_3.py
4,299
3.53125
4
# -*- coding: utf-8 -*- """ Feedforward Neural Networks Part 3: Zalando dataset improved Created on Tue Oct 1 17:05:24 2019 @author: felip """ import pandas as pd import numpy as np import tensorflow as tf import matplotlib import matplotlib.pyplot as plt # Load csv file # Download it from: https...
66fa6a8a37680981096799bbf1b2373514bbde16
zlatozar/study-algorithms
/sorting/exercises/bubble_sort.py
1,139
4.34375
4
#!/usr/bin/env python # # -*- coding: utf-8 -*- # Exercise 2-2 p. 40 # ___________________________________________________________ # NOTES # Bubble sort, is a simple stable sorting algorithm that repeatedly steps through the list # to be sorted, compares each pair...
649f9910f9ff3a988b1bfd2eabf47f61083b8f10
zlatozar/study-algorithms
/dynamic_programming/optimal_bst.py
2,336
3.640625
4
# -*- coding: utf-8 -*- # Chapter 15 p. 394 # ___________________________________________________________ # NOTES # Having PRINT_OPTIMAL_BST it is possible to build the tree # ___________________________________________________________ # ...
c8c04419dbfa43ec0b3f02a88e43708ee93a12dd
zlatozar/study-algorithms
/sorting/common.py
1,763
3.734375
4
# -*- coding: utf-8 -*- # ___________________________________________________________ # ARRAYS def exchange(A, i, j): tmp = A[i] A[i] = A[j] A[j] = tmp def delete_last(A): del A[-1] def is_sorted_array(A): for index in range(len(A)): n...
4cb10c3ce5fe9e5b5e26adf7eb1e1e740b623121
zlatozar/study-algorithms
/sorting/insertion_sort.py
1,547
4.375
4
#!/usr/bin/env python # # -*- coding: utf-8 -*- # Chapter 2: Insertion Sort p.16-18 # ___________________________________________________________ # NOTES # We start with the second one and traverse previous(sorted one) one for suitable place to # insert it. If we ...
0d0ce0730eefab900121217bb41421d971784a51
FarhatJ/HackerRank
/10DaysOfStatistics/Day 1- Quartiles.py
1,639
4.34375
4
# Objective # In this challenge, we practice calculating quartiles. Check out the Tutorial tab for learning materials and an instructional video! # Task # Given an array, , of integers, calculate the respective first quartile (), second quartile (), and third quartile (). It is guaranteed that , , and are integers...
314a422db9b8eda72d985fc235336c66e1c14d30
FarhatJ/HackerRank
/10DaysOfStatistics/Day 7- Pearson Correlation Coefficient I.py
1,569
4.375
4
# Objective # In this challenge, we practice calculating the Pearson correlation coefficient. Check out the Tutorial tab for learning materials! # Task # Given two -element data sets, and , calculate the value of the Pearson correlation coefficient. # Input Format # The first line contains an integer, , denoting t...
f75c6c2ee476f9f345ab6519e7dc24c39c93c9aa
FarhatJ/HackerRank
/10DaysOfStatistics/Day 4- Binomial Distribution I.py
1,011
4.21875
4
# Objective # In this challenge, we learn about binomial distributions. Check out the Tutorial tab for learning materials! # Task # The ratio of boys to girls for babies born in Russia is . If there is child born per birth, what proportion of Russian families with exactly children will have at least boys? # Writ...
21139773e033bc5d018804dcdb7eef438fea4e3e
urgosxd/Sort-Algorithm
/OrdenamientoSeleccion.py
439
3.765625
4
def selection_sort(vector): nb = len(vector) for actual in range(0,nb): mas_pequeno = actual for j in range(actual+1,nb) : if vector[j] < vector[mas_pequeno] : mas_pequeno = j if min is not actual : temp = vector[actual] vector[actu...
926d0d6c60af2025f933d54102a195fda6eea077
earlwlkr/POICrawler
/POICrawler/address.py
550
3.78125
4
class Address(object): def __init__(self, street_address, district, city): self.street_address = street_address self.district = district self.city = city self.country = "Vietnam" def get_street_address(self): return self.street_address def get_district(self): ...
d9c8595ea624c599eca4155b24c44f4c588bb799
lirlia/AtCoder
/Beginners/ABC081B.py
437
3.515625
4
# -*- coding: utf-8 -*- a = int(input()) b = list(map(int, input().split())) cnt = 0 even = [1, 3, 5, 7, 9] while True: # 配列の各値の一桁目を取得 lastVal = map(lambda x: int(str(x)[-1]), b) # 一桁目が奇数の場合処理を終了する if not set(even).isdisjoint(set(lastVal)): print(cnt) break cnt = cnt + 1 # 配列の各値に対して2で徐算する b = ...
336ce4704dd41e2cdcee235a7e26741e2ef65850
lirlia/AtCoder
/practice/thread.py
711
3.6875
4
import threading counter = 0 # # スレッドによって呼び出される処理 # counterを加算していくだけ # def work(): # スレッド間で共有する変数をglobalから持ってくる # 参考 : https://www.it-swarm.dev/ja/python/%E3%82%B9%E3%83%AC%E3%83%83%E3%83%89%E3%81%A7%E3%82%B0%E3%83%AD%E3%83%BC%E3%83%90%E3%83%AB%E5%A4%89%E6%95%B0%E3%82%92%E4%BD%BF%E7%94%A8%E3%81%99%E3%82%8B/10434...
e0672cdda48190120e80a5c0a25ee5a4dab5a67f
yujmiao-cd/yujma
/valid.py
719
3.84375
4
#!/usr/bin/python # -*- coding: UTF-8 -*- ''' 匹配括号序列。 {[([])]} True {{[([]}} False ''' def isValidiParentheses(s): st = [] for c in s: if ( c == '(' or c == '[' or c == '{' ): st.append(c) else : if not check(c, st): return False return True if n...
a49ae818294e3e49121f1ae2cf3a14251208cf56
yujmiao-cd/yujma
/map.py
130
3.859375
4
#!/usr/bin/python # -*- coding: UTF-8 -*- list1 = [1,2,3,4,5,6,7,8,9] square = map(lambda x : x * x ,list1) print list(square)
b37fe024b53f5086076f5ca14201ff4af28516a9
yujmiao-cd/yujma
/re_test.py
615
3.59375
4
#!/usr/bin/python3 # -*- coding: UTF-8 -*- import re s = '0123abcd' regex = re.compile('[ab]') # matcher = re.match('\d',s) # 锚定索引开始 0 # # print(type(matcher)) # # print(matcher) # # matcher = regex.match(s, 4) # 锚定索引开始的位置在第4个位置 # # print(type(matcher)) # # print(matcher) # matcher = re.search('[ab]', s) # prin...
4c3eeef2da85447b6d810426dd8a2ab6221b0712
yujmiao-cd/yujma
/rand_sum_total.py
1,205
3.65625
4
#!/usr/bin/python3 # -*- coding: UTF-8 -*- ''' 随机产生 10 个数字, 要求: 每个数字的取值范围:[1, 20] 统计重复的数字有几个 统计不重复的数字有几个 ''' import random ''' lst = [] rep = [] no_rep = [] count = 0 for i in range(10): lst.append(random.randint(1,10)) print(lst) ''' same_nums = [] # 记录相同的数字 diff_nums = [] # 记录不同的数字 count = 0 nums = [] for _...
ccd09155601174aa0519f36937d0c17f97f9c970
yujmiao-cd/yujma
/jump_game.py
933
3.90625
4
#!/usr/bin/python # -*- coding: UTF-8 -*- ''' 跳跃游戏,给出一个非负整数数组,你最初定位在数组的第一个位置。 跳跃数组中的每个数字代表你所能跳跃的最大长度。。 判断你是否能到数组的最后一个位置,A= [2, 3, 1, 1, 4],返回 True B = [3, 2, 1, 0, 4] False ''' def jump_game(A): ''' 1. 如果我当前能到k点,那我一定能到比k小的点。 x -> k [x+1, k-1] ''' if not A: return False idx = len(A) ...
697b56c6f3a349fb0e10ad6b3f6493ec5ed68117
satadhitama/satriya_adhitama_dumbwaysid
/2.py
2,272
3.515625
4
# Nama : Satriya Adhitama # Bootcamp : Fullstack Developer # Fungsi untuk mengurutkan kata def urut_kata(kalimat): list_kata = kalimat.split(" ") nomor_kata = 1 kalimat_urut = "" if kalimat != "": while nomor_kata <= len(list_kata): for kata in list_kata: ...
be7adefe6e9365b36cf5f5cde919cc0236ce09ec
CoderTitan/PythonDemo
/PythonStudy/3-函数/2-递归.py
1,334
3.734375
4
'''递归调用 一个函数调用函数本身(凡是循环能做的事情, 递归都能写出来) 方式: 1. 写出临界条件 2. 找这一次和上一次的关系 3. 假设当前函数已经能用, 调用自身上一次的计算结果, 在求本次的计算结果 ''' # 输入一个数(大于1), 求1+2+3+...+n的和 '''常规方式 def sum1(n): sum = 0 for x in range(1, n + 1): sum += x return sum print(sum1(4)) # 结果输出: 10 ''' # 递归方式 def sum2(n): if n == 1: re...
1e03c8b57375aead7732fb6c8a4acefc6c604d52
CoderTitan/PythonDemo
/PythonStudy/6-模块练习/2-修改文件名.py
402
3.546875
4
import os def reName(path): path1 = path + '/' nameList = os.listdir(path) for name in nameList: newName = 'ZXB' + name os.rename(path1 + name, path1 + newName) if os.path.isdir(path1 + newName): reName(path1 + newName) path = r"/Users/quanjunt/Desktop/zcmlcS...
7075c1bfb5f350a30c92549d720f412a082a889d
CoderTitan/PythonDemo
/PythonStudy/9-Tkinter/3-Button.py
2,459
3.65625
4
''' # 主窗口 import tkinter def action1(): print('按钮1') # 创建主窗口 window = tkinter.Tk() # 设置标题 window.title('Titanjun') # 设置窗口大小 window.geometry('400x400') # 创建按钮 button1 = tkinter.Button(window, text='按钮1', bg='orange', height=3, ...