blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
1ad240d2be895a7dcf3352e3fe5c4c9de2ae7a63
Hvs911/CODE2RACE
/SOLUTIONS/BeginnersProblem2.0.py
108
4
4
#Beginners problem #python n = input() for i in range(0,n) num = input() if num%2 == 0: print(num)
e2b1c83cab6d50c0c143e5ed5ffc7b2e1f6da01b
EnriqueL8/adventofcode
/2022/2/script.py
1,311
3.578125
4
def calculateScoreOfShape(shape): if shape == 'A' or shape == 'X': return 1 if shape == 'B' or shape == 'Y': return 2 if shape == 'C' or shape == 'Z': return 3 def calculateScore(player1, player2): player1Score = calculateScoreOfShape(player1) player2Score = calculateScoreO...
58bc7e11cbc1f850d24100c9dceea498d37697d7
kely-n/hackerRank
/ipGenerator.py
3,783
3.671875
4
from itertools import permutations #This problem was asked by Snapchat. #Given a string of digits, generate all possible valid IP address combinations. #IP addresses must follow the format A.B.C.D, where A, B, C, and D are numbers between 0 and 255. Zero-prefixed numbers, such as 01 and 065, are not allowed, except ...
e7fc4242a421916b48c7d2ee3d54760da71bc273
aaadlane/githubactiontest
/check_palindrome.py
114
3.859375
4
def check_palindrome(string): isPalin = string == string[::-1] if isPalin : return "yes" else: return "no"
c8118ac6b7b263cad73021d3f5693fb3a0047738
UgoData/smartticket---Notebook
/Code/classification/utilCsv.py
1,633
3.546875
4
# coding: utf-8 import cStringIO import codecs import csv import decimal class UnicodeWriter: """ A CSV writer which will write rows to CSV file "f", which is encoded in the given encoding. """ def __init__(self, f, dialect=csv.excel, encoding="utf-8", **kwds): # Redirect output to a qu...
86f22be8836e23821ba4a5f9c674c2774c817e0c
cforsythe/Steganography
/hideTextInImage.py
5,342
3.90625
4
#Resources #http://pillow.readthedocs.org/en/3.1.x/handbook/tutorial.html #http://stackoverflow.com/questions/11064786/get-pixels-rgb-using-pil #https://docs.python.org/2/tutorial/modules.html from PIL import Image import functions def processingImage(imagepath, txtpath): #This loads orignal image originalImage = ...
95f2bec9ccc273b62e194364be24257232072b3b
mrgmcs/Equation-solution-Python
/equation soloution.py
1,416
4.28125
4
def calculationx2(): #form of a equation : a*x^2 + b*x + c=0 print ("ax^2 + bx + c=0") a = input("Enter a number: ") b = input("Enter b number: ") c = input("Enter c number: ") print("\n") #find value of delta delta = (int(b) * int(b)) - (4 * (int(a) * int(c))) delta = float(delt...
05cb01852ae6145e722cd7264774593ee4437d29
Koushik-Saha19/dxc
/Python_Assignment/Mixed_Cipher.py
1,378
3.890625
4
keyword = input('Please enter a keyword') keyword = keyword.lower() lst_keyword = list(map(lambda e:e, keyword)) lst_keyword = list(dict.fromkeys(lst_keyword)) plain_text = 'abcdefghijklmnopqrstuvwxyz' print("Plaintext:", plain_text) lst_plain_text = list(map(lambda e:e, plain_text)) lst_check = list(map(l...
8506e642fb21725c52b8200bbffc118f097e2d1e
SriSivaC/The-Spark-Workshop
/Chapter11/Exercise11_03/Exercise11_03.py
842
3.640625
4
from pyspark.sql import SparkSession # Create a Spark Session spark = SparkSession\ .builder\ .appName("My Spark App")\ .master("local[2]")\ .getOrCreate() sc = spark.sparkContext # create a sample set of data as an RDD categorized_animals = [("dog", "pet"), ("cat", "pet"), ("bear", "wild"), ("cat", ...
9d9ac13aa6fd867df51395716ed393f7a2181677
teredet/Python-scripts
/FizzBuzz.py
395
4.0625
4
# basic varsion def fizzbuzz(number): if number % 3 == 0 and number % 5 == 0: return 'FizzBuzz' elif number % 3 == 0: return 'Fizz' elif number % 5 == 0: return 'Buzz' else: return number for number in range(1, 101): print(fizzbuzz(number)) # advanced version for ...
9cb9bae3ba216ff6ccd71fdec5488945acc34fae
teredet/Python-scripts
/sorting_a_dictionary_by_value.py
264
4.0625
4
def sort_by_value(xs): ''' Takes in an unsorted dictionary and returns the sorted version by value. ''' return sorted(xs.items(), key=lambda x: x[1]) if __name__ == "__main__": xs = {'a': 4, 'b': 3, 'c': 2, 'd': 1} print(sort_by_value(xs))
fc59a33f5cff64e8bae77ec2b705326b811f795a
Gimppy042/tools
/power.py
406
4.03125
4
def power_of(number, power): if number % power == 0: x = float(number) while True: #print x x = x / float(power) if x == 1.0: print "{0} is a power of {1}".format(number, power) return 1 elif x < 1.0: ...
907913fc8805870a051dfdaf73c890515c3b24ff
DILLORG/CIS189
/Module 12/abstractClass/vehicles.py
1,183
4.0625
4
from abc import ABC, abstractmethod class Vehicle(ABC): """Calling this class Vehicle instead of rider as rider usually refers to the operator not the machine""" @abstractmethod def power_delivery(self): pass @abstractmethod def number_passengers(self): pass class Bicylce(V...
fb8f2cc38e4499e956fefe7742c467157e82ddb0
DILLORG/CIS189
/Module 11/peopleDerivedDriver.py
577
3.75
4
""" Program: peopleDerived Author: Dylan Kennedy Last date modified: 04/06/2021 The purpose of this program is to construct student objects and test that the respective functions work as intended. """ from peopleDerived import Student if __name__== '__main__': my_student = Student(900111111, 'Song', 'River') p...
28f251c6d5a175d9e23c2c5ce9e7f960bf36c9cd
DILLORG/CIS189
/Module 6/validateInputInFunctions.py
998
4.46875
4
""" Program: validateInputInFunctions Author: Dylan Kennedy Last date modified: 03/02/2021 The purpose of this program is to validate that the test score is in between the range 0 and 100 and is an integer. """ def score_input(testName, testScore=-1): """ Determine if a given score is withing the range 0-100...
16acec3786dd40c17548a40714453938d7024ab2
DILLORG/CIS189
/Module 3/couponCalculations.py
1,537
4.0625
4
""" Program: couponCalculations Author: Dylan Kennedy Last date modified: 02/03/2021 The purpose of this program is to calculate the customers total. """ from re import match def decoder_ring(prompt, error, pattern): while True: var = input(prompt) if(match(pattern, var)): return va...
2e8829419b8045df47e0886cc52e175f0f13d236
DILLORG/CIS189
/Module 11/managerDriver.py
660
3.8125
4
""" Program: managerDriver Author: Dylan Kennedy Last date modified: 04/06/2021 The purpose of this program is to construct manager objects and test that the respective functions work as intended. """ from manager import Employee, Manager from datetime import date if __name__ == '__main__': employees = [] ...
00867e4e449b15beb6e29a9340786e86179a85d6
rpatil524/rltk
/rltk/similarity/metaphone.py
4,557
3.734375
4
import rltk.utils as utils def metaphone(s): """ Metaphone fundamentally improves on the Soundex algorithm by using information about variations and inconsistencies in English spelling and pronunciation to produce a more accurate encoding, which does a better job of matching words and names which sound simila...
25435821192e320565fbf6a3484aac26459540f3
jerickleandro/teste_webdrive_python
/funcoes_erick.py
17,573
4.25
4
def saudacao(): print('Olá, digite seu nome: ') nome = input() while(True): print('{}, digite o numero referente a opção desejada:'.format(nome)) print('\n') print('1 - Novo pedido') print('2 - Alteração de pedido') print('3 - Mais opções') op = int(input()) ...
904a893b7495a25fc43bb14f22448d6a894f30aa
yongkwangshin/tensorflow
/cnn.py
3,250
3.640625
4
# cnn.py: MNIST image recognition with CNN # written by Sung Kyu Lim # limsk@ece.gatech.edu # 12/18/2017 # B1: import tensorflow import tensorflow as tf import os os.environ['TF_CPP_MIN_LOG_LEVEL']='2' # B2: MNIST data set up from tensorflow.examples.tutorials.mnist import input_data mnist = input_data.re...
fdd8e795fd0a1ff87277eea3bd1293c1b8a4adf6
Aleksandr-Kolbas/training_python_scripts
/api_number.py
552
3.9375
4
import requests def get_math_fact_from_api(number): """Shows an interesting math fact (if any) about the requested number from the API of the website http://numbersapi.com/""" api_url = "http://numbersapi.com/{}/math?json=true".format(number) res_from_api = requests.get(api_url) data_in_json =...
7a5708ea394cbdc44e3628043e7b094c31038e6c
MigueMonje/PythonColegio
/bloqueo.py
649
3.609375
4
from time import sleep # Contraseña e input del usuario password = "1234" guess = "" # Mientras que el usuario no ponga la contraseña correcta while guess != password: # Mientras tenga intentos attempt = 0 while attempt < 3: # Conseguir el input guess = input("Contraseña: ") # Si es ...
241fd9433d29b532c3556caee790d8cb3d123c23
MigueMonje/PythonColegio
/calculadora.py
277
3.8125
4
# ''' a = float(input()) sign = input()[0] b = float(input()) c = 0 if sign == "+": c = a + b elif sign == "-": c = a - b elif sign == "*": c = a * b elif sign == "/": c = a / b elif sign == "%": c = a % b print(f"={c}") # ''' # print(f"= {eval(input())}")
79b80181bcd5a51b107732db0e1835c5840db0a4
MigueMonje/PythonColegio
/sortinput.py
584
3.875
4
from random import randint def quicksort(l, pivot = None): """ Ordenar una lista usando el algoritmo Quicksort. """ if not pivot: pivot = l[randint(0,len(l)-1)] a = [] b = [] for e in l: if e < pivot: a.append(e) else: b.append(e) ...
a8930f2aaf2cb413f78352ab80f63f815a555f37
Eliy271308/Practice
/practice2.py
352
4.09375
4
#Написать функцию is_year_leap, принимающую 1 аргумент — год, и возвращающую # True, если год високосный, и False иначе. def is_year_leap(x): if x % 4 != 0 or x % 100 == 0 and x % 400 != 0: print("False") else: print("True") is_year_leap(1860)
961b6c8fdf816a03a3c2a992468e5eb0ff4d1200
TaylorWx/shiyanlou
/python/实验楼-挑战:玩转函数-代码/Code/MinutesToHours.py
389
3.765625
4
#!/usr/bin/env python3 import sys def Hours(): time=int(sys.argv[1]) if time < 0: try: raise ValueError("the type is wrong") except ValueError: print("ValueError: Input number cannot be negative") else: hours,minutes=divmod(time, 60) print("{} H, {}...
970d49e8bab03e5be24b0d35227786224626acb3
AkankshaVarshney01/PyTuts
/Hacker_QuestionNo4.py
470
4.3125
4
# Read two integers and print two lines. The first line should contain integer division, // . The second line should contain float division, / . # You don't need to perform any rounding or formatting operations. first_number=int(input("Enter first number of your choice : ")) second_number=int(input("Enter second nu...
71e6ed4686d723afec129446fe391c63db43a56c
heartlesshound/python-pygame-experiments
/numpy_mouse_grid.py
3,189
3.71875
4
import pygame import numpy as np # Define some colors BLACK = (0, 0, 0) WHITE = (255, 255, 255) BLUE = (0, 0, 255) GREEN = (0, 255, 0) YELLOW = (255,255,0) BROWN = (124, 85, 17) DARKGREEN = (36, 94, 36) # Set the width and height of each grid location WIDTH = 10 HEIGHT = 10 # Set the width of the gridlines MARGIN = ...
a02d7ee5445c776a1d1d1f5c9e8b6d97365893e6
Tarunkal/Ceasar_cipher_app
/caesar_cipher_app.py
4,141
4.25
4
import tkinter.font as tkfont from tkinter import * from tkinter.ttk import * import tkinter as tk # Creating a window root = tk.Tk() #For changing the title of the title bar root.title("TEXT Encrytor-Decryptor") root.iconbitmap(r'Lock.ico') root.geometry("400x500") # Creating a canvas canvas = tk.Canvas(root,heigh...
f2217faf8733012f2b68e66dcfece39a337b096d
jessica-alcott/Python-challenge
/PyBank/main.py
2,760
4.125
4
## PyBank #Import the file and file path import os import csv budget_csv = os.path.join("Resources","budget_data.csv") #Print csv to look at the data with open(budget_csv) as csvfile: csvreader = csv.reader(csvfile, delimiter=',') print(next(csvreader)) month = [] revenue = [] revenue_change = [] monthly_...
438bd13791270fa303fc9e755cfa111465b3ad1d
ehallenborg/hackerrank
/DaysofCodeChallenges/10daysofStatistics/day6/central-limit-theorem-I.py
674
3.890625
4
''' A large elevator can transport a maximum of 9800 pounds. Suppose a load of cargo containing 49 boxes must be transported via the elevator. The box weight of this type of cargo follows a distribution with a mean of 205 pounds and a standard deviation of 15 pounds. Based on this information, what is the probabil...
59999d2ff02ee0465aca2d3f42fd3662190bcf98
ehallenborg/hackerrank
/DaysofCodeChallenges/10daysofStatistics/day6/central-limit-theorem-III.py
566
3.734375
4
''' You have a sample of 100 values from a population with mean 500 and with standard deviation 80. Compute the interval that covers the middle 95% of the distribution of the sample mean. In other words, compute A and B such that P(A<x<B) = 0.95. Use the value of z=1.96. Note that z is the z-score. ''' # Enter your co...
230592aa94538bb003815ac25ec716e7d05c0e90
ehallenborg/hackerrank
/DaysofCodeChallenges/10daysofStatistics/day4/geometric-distribution-II.py
333
3.796875
4
''' The probability that a machine produces a defective product is 1/3. What is the probability that the 1st defect is found during the first 5 inspections? ''' # Enter your code here. Read input from STDIN. Print output to STDOUT n, d = list(map(float, input().split(" "))) v = int(input()) print(round(1 - (1 - (n /...
35e179799647337ae377f407ffcb90b93f565bf0
ehallenborg/hackerrank
/DaysofCodeChallenges/30daysHackerrank/Day8/dictionaries-and-maps.py
429
3.59375
4
n = int(input()) phonebook = {} # read lines into phonebook & remove for i in range(n): name, num = input().strip().split(' ') name, num = [str(name), int(num)] phonebook[name] = num while True: try: lookup = str(input()) if lookup in phonebook: print(''.join('%s=%r' % ...
0bcb74253402efbe8dfa90b74cef7514b37a1f8e
ehallenborg/hackerrank
/DaysofCodeChallenges/10daysofStatistics/day4/geometric-distribution-I.py
395
3.921875
4
''' The probability that a machine produces a defective product is 1/3. What is the probability that the 1st defect is found during the 5th inspection? ''' # Enter your code here. Read input from STDIN. Print output to STDOUT def exp(n, p): return (1-p)**(n-1) def g(n, p): return exp(n, p) * p n, d = list(ma...
a0f591c64cb5fabbcc5dba8f08feb36a36288b74
Far4Ru/tic-tac-toe
/main.py
6,985
3.578125
4
import random def board_view(b): b11, b12, b13=str(b[0][0]), str(b[0][1]), str(b[0][2]) b21, b22, b23=str(b[1][0]), str(b[1][1]), str(b[1][2]) b31, b32, b33=str(b[2][0]), str(b[2][1]), str(b[2][2]) print(b11+' | '+b12+' | '+b13) print('---------') print(b21+' | '+b22+' | '+b23) print...
d060ab49892dcc29d817dc3cb330d8da2edf4af7
upendra431/python
/If Statement/ifstmt.py
367
4
4
#if is a conditinal stmt """ Ex: checking a person age. Ex: checking the price of the item. """ def check_if(age): if age>=18: print("Riht to vote! {} age people.".format(age)) check_if(18) #below method won't print any out put , if condition is not satisfied. for this we needto use if else stmt. check_if...
807ef875aa011ea2e4e550083f8b6e8838aa8a42
RyanGreenup/pandoku
/json_fix_stdin.py
1,128
3.515625
4
#!/usr/bin/env python import sys import json # Read Json from STDIN data = json.load(sys.stdin) # for word in data['blocks']: # print(word) for i in range(len(data['blocks'])): # Go through each block, which is like a chunk of syntax block = data['blocks'][i] # the current block block_t...
38412d2e3ac88976fe4007e59debd916b26fb9af
logogin/coursera_algo
/algo1/hw06/2sum.py
2,671
3.65625
4
""" Download the text file here <https://d396qusza40orc.cloudfront.net/algo1%2Fprogramming_prob%2F2sum.txt>. (Right click and save link as). The goal of this problem is to implement a variant of the 2-SUM algorithm (covered in the Week 6 lecture on hash table applications). The file contains 1 million integers, both ...
d63e2f367a76f106ae7bd78c74a59c32d98d55f1
KiraOldeen/ralph
/database/__init__.py
28,679
3.515625
4
from typing import List from typing import Tuple from typing import Union from psycopg2.extensions import AsIs from database.base import Base """ Модуль, содержащий класс с методами для работы с БД, выполняющих конечную цель """ class Database(Base): """Класс для методов работы с БД, выполняющих конечную цель ...
ec9413ff1e1f3778414d842da7ed2fb6bd250f44
juanjopruebas7890/holbertonschool-higher_level_programming
/0x0B-python-input_output/7-save_to_json_file.py
224
3.859375
4
#!/usr/bin/python3 """ writes an object to a text file """ import json def save_to_json_file(my_obj, filename): """ will write an object """ with open(filename, mode="w") as file: json.dump(my_obj, file)
8c0aace83bd96286d1a7f386f78494949f49bea4
juanjopruebas7890/holbertonschool-higher_level_programming
/0x07-python-test_driven_development/tests/6-max_integer_test.py
1,020
4
4
#!/usr/bin/python3 """ Unittest """ import unittest max_integer = __import__('6-max_integer').max_integer class TestMaxInteger(unittest.TestCase): """ unittest """ def test_without_arg(self): """ in case no argument is passed """ self.assertIsNone(max_integer()) def test_negative_num(sel...
c36cfc4a888441e232cae9e906e400453ce19d4d
juanjopruebas7890/holbertonschool-higher_level_programming
/0x0B-python-input_output/8-load_from_json_file.py
238
3.671875
4
#!/usr/bin/python3 """ will create an object """ import json def load_from_json_file(filename): """ create an obj from json """ with open(filename, mode="r", encoding="utf-8") as file: return (json.loads(file.read()))
b5e7dd2413c24cffb5fb703795e2f35d2368599c
sgtpanic/advent-of-code-2016
/day1.py
768
3.5625
4
def get_distance(input_position): return abs(input_position.imag) + abs(input_position.real) with open('./day1.txt', 'r') as f: instructions = f.read().split(', ') position = 0 + 0j direction = 1j positions = set() repeated = None found_first_repeat = False for instruction in instruct...
9c94989edc95fd496051f36d557e6084689d6aac
Louis-Gabriel-TM/wf3_poo_en_python
/ch08_tp_tkinter/exo_8.5.py
2,393
4.03125
4
from tkinter import Button, Canvas, Tk, LEFT, BOTTOM from random import choice def draw_line(): global y1, y2 """ Pour essayer les méthodes 'create_rectangle', 'create_arc', 'create_oval' et 'create_polygon', décommenter la ligne correspondante. """ """Avec 'create_rectangle', (x1, y1) correspond...
03ceba2a3b0ad94feb1aba03b9e8e02509ebd32d
Louis-Gabriel-TM/wf3_poo_en_python
/ch10_tp_datatypes/1_tp_strings/exo_10.5alt.py
998
3.625
4
"""La bibliothèque standard 'collections' contient de nouvelles structures de données qui peuvent s'avérer bien utiles. On trouve sur le site Hackerrank une série de puzzles pour s'initier aux principales structures de données apportées par 'collections' : https://www.hackerrank.com/domains/python?filters%5Bsubdomains%...
510f99b50fabd5007671109f3f40eaa1fbb0bb61
Louis-Gabriel-TM/wf3_poo_en_python
/ch10_tp_datatypes/4_tp_dictionnaries/exo_10.46.py
646
3.90625
4
def exchange_keys_values(dictionnary): """Cette fonction renvoie un dictionnaire 'result' où les couples clé / valeur du dictionnaire 'dictionnary' ont été renversés. """ result = {} for key, value in dictionnary.items(): result[value] = key return result # Créons un petit dictionnaire ang...
057443d89f8a4078ad585af583ab821c8ad6ca8a
kang-jaeseok/python_202104
/p20210330_05_if.py
5,103
3.859375
4
# #조건문 # a = -10 # if a > 0: # print('양수') # print(a) # else: # print('음수') # print(a) # # print('프로그램 종료') # 실습) 회원등급 출력 # a가 90보다 크면 good 아니면 try출력 # a = int(input('입력 :')) # if a > 90: # print("good") # else: # print("try") # # 실습) 비밀번호 체크 # # 비밀번호가 일치하면 '문이 열립니다' # # 일치하지 않으면 '다시 확인 하세요'...
5cb84ce6ca9b31f0e2aa9c85b5b0d6dff2ef8721
alex1the1great/Assignment
/function/question3.py
162
3.984375
4
numbers = [10, 2, -3, 4, 3] def multiple(numbers): product = 1 for num in numbers: product *= num return product print(multiple(numbers))
1eb3e0f256caf8bafa6f528f5f85874420ee8736
alex1the1great/Assignment
/data_types/question1.py
189
4.21875
4
string = input('Enter a string: ') character_frequency = {} for s in string: character_count = string.count(s) character_frequency[s] = character_count print(character_frequency)
9e847bce9f0e57e6ae5db759cc40508c52e17d35
alex1the1great/Assignment
/data_types/question34.py
189
3.875
4
dic1 = {} dict_count = int(input('Enter data range: ')) for i in range(dict_count): key = input('Enter key: ') value = input('Enter value: ') dic1[key] = value print(dic1)
2a70f124268bb43cfa5cedb8ad9cab559d4bd444
alex1the1great/Assignment
/data_types/question31.py
131
3.515625
4
sample_dict = {'mon': 'Monday', 'tue': 'Tuesday', 'wed': 'Wednesday'} for key, value in sample_dict.items(): print(key, value)
63f911c3281ec084d1389eefb77621260e48961f
alex1the1great/Assignment
/function/question11.py
150
3.609375
4
# lambda add function add_num = lambda num: print(num + 15) add_num(15) #lambda multiple function multiple = lambda x, y: print(x * y) multiple(3, 2)
b7f339552633e38dec39c857888da96e92ab8b53
alex1the1great/Assignment
/function/question8.py
197
4.03125
4
def check_append(numbers): new_list = [] for i in numbers: if i not in new_list: new_list.append(i) return new_list print(check_append([1, 2, 3, 3, 2, 4, 5, 5]))
e9fe46b9642321ae34c38ca800c59f353ec7d587
cappuccinoX/qta_demo
/test1.py
1,158
3.5
4
class AbstraceFactory(object): def getSize(self): return Size() def getColour(self): return Colour() class Size(AbstraceFactory): @staticmethod def sizeFactory(type): if type == 'A4': return A4() if type == 'A3': return A3() class A4(Size): ...
3c7ca47ee30e4ec4446ab3eb4b19a1508f5d520e
PYKSOJ/Rock-Paper-Scissors-Game
/play.py
859
3.8125
4
def play(player): # m = ["r", "p", "s"] d = {"r": "rock", "p": "paper", "s": "scissors"} # computer = m[random.randrange(len(m))] computer = random.choice(list(d.keys())) if player == computer: result = "tie" elif player == "r": if computer == "s": result = "player wi...
06fbd08f991a4b5a0937944fa8e0380c25e20811
BogdanArtem/python-education
/algorithms/algorithms/factorial.py
298
4.21875
4
"Module that implements factorial recursive function" def factorial(num: int): """Find factorial of n. This algorithm uses recursion to find factorial of n n: int number to find factorial """ if num in (1, 0): return num return num * factorial(num - 1)
0eb37095b3e5896c0c04aadfa770788a3193d259
BogdanArtem/python-education
/algorithms/data_structures/binary_tree.py
2,622
4.1875
4
"""Implementation of binary search tree This module is created to practice binary search tree implementation""" class BinaryTree: """Recursive binary tree""" def __init__(self, value): self.value = value self.count = 1 self.left = None self.right = None def _traverse_tree...
c3f5d0848630364f39121afad31f6faebf174aad
BogdanArtem/python-education
/algorithms/data_structures/hash_table.py
2,108
3.953125
4
"""Implementation of binary search tree This module is created to practice hash table implementation""" from array import Array from linked_list import LinkedList class KeyValue: def __init__(self, key, value): self._key = key self._value = value @property def key(self): return...
53212835eb878c072d485c77d509aa38f8551d20
BogdanArtem/python-education
/algorithms/data_structures/test_stack.py
739
3.59375
4
"""Tests for queue implementation""" import pytest from stack import Stack def test_push(): """Add the 'The quick brown fox jumps over the lazy dog' to linked list""" lst = Stack() lst.push("first") lst.push("second") lst.push("third") lst.push("fourth") assert lst.pop() == "fourth" ...
69852036014721c8f73d0ccd105826f1fd362e24
BogdanArtem/python-education
/python_module/tic-tac-toe/player.py
1,406
4.1875
4
"""This module tracks winning and loosing of players""" class Player: """Representation of player that has name and sign""" def __init__(self, name, sign): self._name = name self._sign = sign def __repr__(self): return f"Player[name={self.name}, sign={self.sign}]" def __eq__...
d669573d953b180a6b6086589be0ee82cc06baa9
darnoceloc/Leetcode
/Robot Area.py
1,614
3.515625
4
class Robot: def __init__(self, mapping, i, j): self.mapping = mapping self.i = i self.j = j def move(self, dir): if dir == 0: if self.j == len(self.mapping[0]) - 1 or self.mapping[self.i][self.j + 1] == 1: return False self.j += 1 if dir == 1: if self.i == 0...
44da8e9342ecac915cea2a829f3fbb55ac658937
wlmgithub/ecar
/play/find_rotation_index.py
570
3.71875
4
def findit(A): if len(A) <= 1: return 0 if len(A) == 2: if A[0] <= A[1]: return 0 else: return 1 # len(A) > 2 for i, w in enumerate(A): if w > A[i+1]: return i+1 if __name__ =='__main__': words = [ 'ptolemaic'...
f4e8ae14c135e1166e039720dc51a9b99563c537
wlmgithub/ecar
/play/max_stock_profit.py
683
4.15625
4
""" Given a array of numbers representing the stock prices of a company in chronological order, write a function that calculates the maximum profit you could have made from buying and selling that stock once. You must buy before you can sell it. For example, given [9, 11, 8, 5, 7, 10], you should return 5, since you c...
f10361d6bd6ad6886348850ba3b5bee50ee08b19
wlmgithub/ecar
/play/binary_search_tree_serializer_deserializer.py
1,538
3.625
4
from collections import deque class TreeNode: def __init__(self, val, left=None, right=None): self.val = val self.left = left self.right = right bst = TreeNode(50, TreeNode(20, TreeNode(10), TreeNode(40)), TreeNode(70, TreeNode(60), ...
943387d26a270edb48c303a39a648a42b5a91399
wlmgithub/ecar
/play/sort_sorted_lists.py
369
3.6875
4
#import heapq A = [[10, 15, 30], [12, 15, 20], [17, 20, 32]] print(A) def mergeit(A, B): res = [] while A and B: if A[0] < B[0]: res.append(A.pop(0)) else: res.append(B.pop(0)) return res + A + B def sortit(A): res = [] for a in A: res = mergeit(r...
3d1b7437d78c90416a45e17a8549195014ced102
wlmgithub/ecar
/play/find_two_ints_add_up_to_given.py
744
3.578125
4
def testme(A, K): if len(A) < 2: return False # len(A) >= 2 for i, n in enumerate(A): rest = A[:i] + A[i+1:] s = K - n print(i, n, s, rest) if s in rest: return True return False def find_indexes(A, K): hash_table = {} for i, num in enumerate(A):...
98b1fa27227cbaa1a31e95fc50d9fe9c1ebc4560
wlmgithub/ecar
/play/decode_msg.py
1,797
3.578125
4
#char_map = {} #char_map['1'] = 'a' #char_map['2'] = 'b' #char_map['3'] = 'c' #char_map['4'] = 'd' #char_map['5'] = 'e' #char_map['6'] = 'f' #char_map['7'] = 'g' #char_map['8'] = 'h' #char_map['9'] = 'i' #char_map['10'] = 'j' #char_map['11'] = 'k' #char_map['12'] = 'l' #char_map['13'] = 'm' #char_map['14'] = 'n' #char_...
f611bfe2a9b2d31ffc08100edf6bd1aefb5a62b3
mattlee95/Riddler
/Nov1_2019/sultanSim.py
4,958
3.828125
4
import math import random from itertools import permutations # THRESHOLD is a list of int type variables meant to represent the mininum standing # of the suiter at that index compared to those rejected in order to be selected # # For example THRESHOLD[i] = n # The program will compare the candidate at index i to the...
0969f0bede30555d78b24261b5c08b334d37f923
thiago-a-souza/MachineLearning
/NaiveBayesSpamFilter.py
2,355
3.609375
4
''' AUTHOR: Thiago Alexandre Domingues de Souza LANGUAGE: Python3 TRAINING DATASET: Input file should have three fields delimited by a single space: word spam_count not_spam_count TESTING DATASET: Input file should have the contents of a given email OUTPUT: Given testing dataset should be classified as "spam" ...
589c2950e91efe597d101252a56b64cfac9ab4be
MsClaudz/SSD-Simulator
/Partitioning.py
4,303
3.578125
4
import math # Given update frequency ratio, compute number of partitions def num_partitions_from_ratio(freq_dict, ratio): '''(dict of int:int, number) -> int Given update frequency ratio, calculates the minimum number of partitions required to ensure ratio is not exceeded (Update frequency ratio is the ra...
b31625ea561a78fb3c0a7ed6c035c95eafca5adf
crispyfalafel/books-manager
/test_convert_dict_to_text_line.py
1,553
3.515625
4
from unittest import TestCase from books import convert_dict_to_text_line class TestConvertDictToTextLine(TestCase): def test_convert_dict_to_text_line_full_dictionary(self): value = {'author': 'Dupre', 'title': 'Skyscrapers', 'publisher': 'BD&L', 'shelf': '12', 'category': 'Architecture...
fc3ebba1edac3508dcfef5972141d6d11da8eca8
andy-son/python
/curses/ncurses_programs/basics/addstr_example.py
828
3.96875
4
#!/usr/bin/env python # based on the printw_example.c of the ncurses example code import curses mesg = "Just a string" # message to be appeard on the screen row = None # to store the number of rows of the screen col = None # to store the number of columes of the scr...
a18b92fc9d22728875214740f4a2fa25c28cbe06
andy-son/python
/curses/ncurses_programs/basics/simple_key.py
2,323
3.734375
4
#!/usr/bin/env python # based on the simple_key.c of the ncurses example code import curses WIDTH = 30 HEIGHT = 10 choices = [ "Choice 1", "Choice 2", "Choice 3", "Choice 4", "Exit" ] def print_menu(menu_win, highlight): # the following doesn't seem to work on python 2.7, aborts # wit...
09aa7ab41aa48453219b39631e5104cd4efd8f79
susiebeep/Software-Engineering-II
/Week 5/check_pwd.py
974
4
4
def check_pwd(password): # list of allowed symbols valid_symbols = ['~', '`', '!', '@', '#', '$', '%', '^', '&', '*', '(', ')', '_', '+', '-', '='] # reject empty passwords if len(password) == 0: return False # reject passwords less than 8 characters # or gre...
64c70524430601da21cc33224879f72559bbf94e
x-coder01/secret-messages
/caesar.py
1,128
3.9375
4
import string from ciphers import Cipher class Caesar(Cipher): FORWARD = string.ascii_uppercase * 3 def __init__(self, offset=3): self.offset = offset self.FORWARD = string.ascii_uppercase + string.ascii_uppercase[ :self.offset + 1] sel...
ba2b79eebd858f13b7ea168509ae9de85814dfca
dean/PythonGames
/Deck.py
1,032
3.75
4
#Card.py #This class represents a Deck of cards used for card games. from Card import Card from Player import Player import random class Deck(object): def __init__(self): self.arr = [] def create_default_deck(self): suits = ["Hearts", "Diamonds", "Spades", "Clubs"] idx = 0 for i in range(1, 5, 1): for k in...
f86e4ed04c4df91b2ea1af5795a36398da2bc1ab
josephw1234/Finals-Game-Good-version-
/map.py
1,397
3.953125
4
from tabulate import tabulate import second_day as second # Note: map for first day is located in first_day.py to avoid circular import def print_map(): """Function for printing grid map of Campbell""" # vairables for classrooms english = "English" math = "Math" french = "French" history = "...
dda784876bf7413067ac5777ae97190a97324004
docxed/codeEjust
/[Final 2018] Digit V2.py
526
3.921875
4
"""main""" def numdict(num): """lenght of number""" if "thousand" in num: lenght = 4 elif "hundred" in num: lenght = 3 elif "teen" in num or "ty" in num or "twelve" in num or "eleven" in num or "ten" in num: lenght = 2 else: lenght = 1 return lenght def main(): ...
d42e614506bd4353d87b4b90fd19a8d742868e2b
docxed/codeEjust
/OneTwo.py
768
3.921875
4
"""main""" def main(): """string concate is poor way but list slicing is better one""" num = int(input()) if num >= 3: list1, list2 = [num], [] while list1 != []: first = list1[0] list1.pop(0) if first == 2: list2.append(first) ...
5bda88efe0321fdf248f96ce4cce48bb13d933f4
docxed/codeEjust
/HelloWorldComeBack.py
195
3.984375
4
"""main""" def main(): """main function""" txt = input() if "A" <= txt[0].upper() <= "Z": print("Hello", txt + ".") else: print("สวัสดี", txt) main()
2db6fce43f02d5f2c8a1af447da15441bdaa3aea
docxed/codeEjust
/[Midterm 2015] MacaronBoxSML.py
374
3.859375
4
"""main""" def main(): """main docx""" desert = int(input()) high, medium, small = 0, 0, 0 high += desert // 24 desert %= 24 if desert > 12: high += 1 desert = desert - 12 elif 6 < desert <= 12: medium += 1 desert %= 12 elif 0 < desert <= 6: small ...
cd530c4678e15e7ae5e5ff01bd74056bc3051bd9
docxed/codeEjust
/FibonacciRecursionV1.py
354
3.71875
4
"""main""" def goloop(): """mafia loop""" stop = int(input()) if stop == 0: print(0) return main(0, stop-1, 0, 1) def main(current, stop, first, newfirst): """main docx""" if current == stop: print(newfirst) return new = first + newfirst main(current+1...
03fad35ce10fbd0affc99d9776be5371a07ed954
docxed/codeEjust
/Largest Number.py
962
4.0625
4
"""main""" def main(): """main docx""" num1, num2, num3, world_method = int(input()), int(input()), int(input()), list() if num1 >= 0 and num2 >= 0 and num3 >= 0: world_method.append("%d%d%d"%(num1, num2, num3)) world_method.append("%d%d%d"%(num1, num3, num2)) world_method.append("%d...
f0e4e57b35c86753de638a8db95a477900e1ff91
docxed/codeEjust
/SurprisingVote.py
620
4.03125
4
"""main""" def looping(current, stop, point, low, high): """loop function""" if current == stop: if high - low > 2: print("Surprising") return print("Not surprising") return if 0 <= point + current/10 <= 10 and 0 <= point - current/10 <= 10: low = poin...
f117d28ba49edd5b22ec943bdb15052a7a8d7334
docxed/codeEjust
/Nearer.py
414
3.6875
4
"""main""" def main(): """main func""" lst = [] alice, bob, ice = int(input()), int(input()), int(input()) world_alice = abs(ice - alice) lst.append(world_alice) world_bob = abs(ice - bob) lst.append(world_bob) if lst[0] < lst[1]: print("Alice", lst[0]) if lst[1] < lst[0]: ...
4c2f7bbf2673fe76310ad0ca63b3ac3c05c4b511
docxed/codeEjust
/HorizontalHistogram.py
832
3.671875
4
"""main""" def main(): """main docx""" txt = input() rawlow = [i for i in txt if i.islower()] rawhigh = [i for i in txt if i.isupper()] low = sorted(list(set([i for i in txt if i.islower()]))) high = sorted(list(set([i for i in txt if i.isupper()]))) for i in low: pipe = "-"*rawlow.c...
121874ba5125985eb1fc2574dbf20ea1dc86dd41
docxed/codeEjust
/Amicable.py
896
3.5
4
"""main""" def main(): """main docx""" end = int(input()) first_vector, second_vector, amicable = [1], [1], [] for number in range(1, end+1): for vector in range(2, int(number**.5)+1): if number % vector == 0: first_vector.append(vector + (number//vector)) dif...
2eee2e0f97cfb6dc0bc1c22d1931e838651fab35
docxed/codeEjust
/WordSequence I.py
129
3.625
4
"""main""" def main(): """main docx""" txt = input() for i in range(1, len(txt)+1): print(txt[0:i]) main()
7b7b9b06524b6b6a975fc6281591d654fe04b6b8
docxed/codeEjust
/[Final 2018] Semiprime.py
458
3.796875
4
"""main""" def semiprime(num): """progress semiprime""" cnt = 0 for i in range(2, int(num**.5)+1): while num % i == 0: num /= i cnt += 1 if cnt >= 2: break if num > 1: cnt += 1 return True if cnt == 2 else False def main(): """main"...
12b1f1a12b14891c5b5cbab89ea2e85b54faa330
docxed/codeEjust
/Run Length Decoding.py
478
3.546875
4
"""main""" def main(): """main""" txt = input() alpha = [i for i in txt if i.isalpha()] tmp, digit, get, keep = [], [], "", "" for i in txt: if not i.isdigit(): tmp.append(get) get = "" get += i for i in tmp: for j in i: if j.isdigit():...
6d72f4d96fad378640e1bfb180da4ae57f9976bf
docxed/codeEjust
/Gram_v1.py
472
3.640625
4
"""main""" def main(): """main docx""" raw = input() txt = [i for i in raw] gram, quan = [], [] cnt = 0 for i in range(len(txt)): if i > 0: gram.append(txt[i-1] + txt[i]) for i in gram: for j in range(len(raw)): if j > 0: if raw[j-1] + ...
8559c30bce2d2f2d22a9ba46963026065a71fdec
docxed/codeEjust
/Diamond I.py
411
3.546875
4
"""main""" def main(): """main docx""" hole = int(input()) position = int(input()) pigeonhole = [list(map(int, input().split())) for _ in range(hole)] diamond_bag, count = [], [] for i in range(position): for j in range(len(pigeonhole)): count.append(pigeonhole[j][i]) ...
4c136d2b6d674225ebaf642cd969901c0f8e48bd
docxed/codeEjust
/Sequence IV.py
197
3.90625
4
"""main""" def main(): """main function""" num = int(input()) for i in range(0, num**2, num): for j in range(1, num+1): print(j+i, end=" ") print() main()
06504d0c84906dd2dd7adca404ffcd75f9837d50
Francisco-222/CodingBat-Python
/List-2/sum13.py
129
3.796875
4
def sum13(nums): nums.insert(0, 0) return sum(0 if nums[i - 1] == 13 or n == 13 else n for i, n in enumerate(nums))
7b19069e4f4c5928f7d46f83302e3c8220a36af5
wrom-debug/private
/python/并行程序/多线程/07_生成-消费模型.py
863
3.84375
4
""" 线程中也有queue队列,使用队列大小判断线程是否执行相关 操作 """ import time import threading from queue import Queue def scz(): cp=0 global q while True: if q.qsize()<1000: for i in range(100): cp+=1 sp="商品 id:"+str(cp) print("正在生产:"+sp) ...
d7a4de278e42a6ec9c5e362e609f0ec9cb45b1d1
toolcoi/OnSkills
/Python/oneArr.py
1,953
3.90625
4
# SẮP XẾP TĂNG DẦN def sap_xep_tang_dan(numbers): lenth = len(numbers) # Lặp từ phần tử đầu đến kế cuối, # Vì khi đến phần tử cuối là đã sắp xếp thànhcông for i in range(0, lenth - 1): for j in range(i + 1, lenth): if (numbers[i] > numbers[j]): # Hoán đổi vị trí ...
69e6f12c0f004dba16b66e58ef6fcf6b9d775c51
fedcuit/EffectivePython
/main/chapter1/enum.py
678
4.125
4
from collections import namedtuple __author__ = 'edfeng' # the problem with all the ways above to achieve enum in python is that: # value can be duplicated and can take part in meaningless operation # 1. use collections.namedtuple to define enum in python Season = namedtuple("Season", "Spring Summer Autumn Winter")....
6494ad021aea97bc7fa7359dcedff88ba7412456
de0gee/ideas
/scratch/database.py
4,470
3.625
4
import sqlite3 import os import time try: os.remove('test2.db') except: pass table_name1 = 'my_table_1' # name of the table to be created table_name2 = 'my_table_2' # name of the table to be created new_field = 'my_1st_column' # name of the column field_type = 'INTEGER' # column data type # Connecting to the...
4b53c8eb17ab4a430e2f0fc921a0cbd51f0e00ae
Programming-The-Next-Step/prisonersdilemma
/test_prisonersdilemma_functions.py
1,987
3.953125
4
# -*- coding: utf-8 -*- """ Created on Sat May 30 16:59:51 2020 @author: katha """ import unittest from prisonersdilemma import run ''' This is a function that tracks the sentence count in the prisoner's dilemma game. I'm gonna test it by setting sentcounto and sentcountp to 0 and then setting response == ...