blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
a96460884671ac529b17f3849c045df9324eb5e5
drsagitn/algorithm-datastructure-python
/algorithms/num_of_islands.py
1,424
3.640625
4
""" Given a 2d grid map of '1's (land) and '0's (water), count the number of islands. An island is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. You may assume all four edges of the grid are all surrounded by water. Example 1: Input: 11110 11010 11000 00000 Output: 1 Exam...
92de33609c63e7d5c6514e4dac887dd9da9027df
William-King977/eng84_python_variables
/variables.py
450
4.03125
4
# pseudo coding # Testing the env with hello world # print("Hello world") # What is a variable? course_name = "DevOps 84" # string student_name = "William" # string age = 18 # integer hourly_wage = 8.75 # float # print(student_name) # print(hourly_wage) # print(age) # User interaction name = input("Enter your name: ...
1e50888103ab72cb7bb539fd0ce44ec8d5374d51
dials/dials
/src/dials/algorithms/refinement/rotation_decomposition.py
4,614
3.671875
4
from __future__ import annotations import math from scitbx import matrix """A Python version of the Rotation::euler_explicit method from Pointless""" def solve_r3_rotation_for_angles_given_axes( R, e1, e2, e3, smaller_phi2_solution=True, return_both_solutions=False, deg=False ): """decompose 3*3 rotation m...
ce2cac1649e230cca274dc9c1b72512b4edb0a7e
riccardo-lomazzi/projects
/Python/Regex/regexes1.py
771
3.890625
4
import re #first approach def firstMethod(word, toSearch): m = re.compile(toSearch) #cambiare la split if(m.search(word)): return 'MATCH FOUND FOR ' + toSearch else: return 'NO MATCH FOUND FOR' + toSearch def secondMethod(word, toSearch): if(bool(re.search(toSearch,word))): ret...
cb7aec130362ca3e8f31fc0714eeb1586a67a879
watsonsam/grace
/maze.py
4,753
3.703125
4
import cell import random from timeit import default_timer as timer # TODO: Get rid of class class Maze: def __init__(self, width, height): self.width = width self.height = height self.grid = {} self.graph = {} self.build_grid() self.build_maze() def build_grid...
b962c796eff080a61cb56da1cefac6fdde98289e
wenxinjie/leetcode
/backtracking/python/leetcode78_Subsets.py
818
3.703125
4
# Given a set of distinct integers, nums, return all possible subsets (the power set). # Note: The solution set must not contain duplicate subsets. # Example: # Input: nums = [1,2,3] # Output: # [ # [3], # [1], # [2], # [1,2,3], # [1,3], # [2,3], # [1,2], # [] class Solution(object): def subset...
8a081b0ae2f985314029d012afa20b7427a57d3f
kerr-hannah/nlp-Markov-Chatbot
/code_and_corpus/cleanData.py
2,382
3.828125
4
""" This file takes the Cornell Movie Dialog Corpus as it is downloaded and formats the data from the several files into one file of dialog lines. Based off code by Matthew Inkawhich posted in a tutorial using this same corpus (Only the code for pre-processing the data is used as the rest of the tutorial covers a dif...
8eb45aa2baa570623778db0cf0303ff6146cb4a0
dee12452/PracticeProblems
/Python/src/Cracking the Coding Interview Problems/One_Three.py
709
3.8125
4
"""1.3 Given two strings, write a method to decide if one is a permutation of the other.""" def main(): s1 = raw_input("Please Enter A String: ") s2 = raw_input("Enter another to see if it is permutation of the first string: ") print is_permutation(s1, s2) return def is_permutation(s1, s2): # do...
5bc452b8daddc85266de8e5b6139e3613f225bd2
valeri1383/Python-Fundamentals
/Inbox Manager.py
846
3.796875
4
command = input() username_dict = {} while command != 'Statistics': token = command.split('->') username = token[1] if token[0] == 'Add': if username in username_dict: print(f"{username} is already registered") else: username_dict[username] = [] elif...
331a8164e212e5e167a0c82f7dd1745c3b5f7c07
KenMwaura1/python-hacks
/anagrams.py
302
3.9375
4
""" Check if two strings are anagrams of each other """ from collections import Counter def anagram_checker(string_1, string_2): return Counter(string_1) == Counter(string_2) anagram_checker('pqrs', 'rqqs') # evaluates to true anagram_checker('pqrs', 'rqqs') # evaluates to false
271f0a6ddf7827cb313681c6acd959488efede22
squeevey/Random52CardPickup
/Random52CardPickup.py
911
4.03125
4
#File: Random52CardPickup.py # If you were to randomly find a playing card on the floor every day, # how many days would it take to find a full deck? # Based on the reddit question here # https://www.reddit.com/r/askscience/comments/6y93j8/if_you_were_to_randomly_find_a_playing_card_on/?utm_content=title&utm_medium=ho...
2d717af7a36fc718a3d7cbdf545f17b5b8e472c8
10mincode/10mincode
/maxfinderfromlist.py
291
4.0625
4
list=[] noofnum=int(input("Enter the number of numbers you want to compare: ")) for i in range(noofnum): ui=input(f"Enter the {i+1} number") list.append(ui) max=list[0] for i in range(len(list)): if list[i] >max: max=list[i] print(f"The maximum number is {max}")
1100308de3cbafe2eb34e20e35e5a299aea5c3b3
Johnnyboycurtis/neural-networks
/basic/sklearn_example.py
1,170
3.609375
4
import numpy as np import matplotlib.pyplot as plt from sklearn.neural_network import MLPRegressor def MSE(y, yhat): return np.mean((y - yhat)**2) def example_data(rows = 20, columns = 3): #np.random.seed(123) X = np.random.normal(size=(rows, columns)) X[:, 0] = np.linspace(start=-10, stop=10, num=row...
38d83eaac0dd6af9c4147b659dff7bfcf2e509fb
poorvavm/dsalgos
/stringMan/getsubstring.py
165
3.90625
4
# substring of a string m_str= input("enter string") def get_substr(x,y): r_str="" for i in range(x,y): r_str+=m_str[i] print r_str #a= get_substr(5,11) #print a
152bbb10710fde42c0aa84c72d1cf9e957a432a8
Aishwarya-260180/260180_daily_commits
/if-else-if-4.py
457
4.15625
4
number=input("ENTER A INPUT:") if type(number) == type(1): print("Entered number is a Real Number...") elif type(number) == type(1.0): print("Entered number is a Float Number...") elif type(number) == type("Abc"): print("Entered number is a String...") elif type(number) == type(1 + 2j): prin...
43217385040f7153d403d4983aa57c77e15d8d64
lbvalcke/Classwork
/lbvalcke-master-122/lbvalcke-master-a3fa9d442dc280c08a0ff3fd54751bb1bdff6871/kattis/pet.py
1,362
3.546875
4
import sys # Skeleton code for problem https://uchicago.kattis.com/problems/pet # # Make sure you read the problem before editing this code. # # You should focus only on implementing the solve() function. # Do not modify any other code. # This function takes a single parameters containing a list # with exactly five e...
2c03df6132dd31b98026c78f1c4998e18224993f
AdamZhouSE/pythonHomework
/Code/CodeRecords/2445/60833/300725.py
127
3.71875
4
s=input().split(',') s1=s[0][2:] s1=sorted(s1) s2=s[1][2:] s2=sorted(s2) if(s1==s2): print('true') else: print('false')
d223ac9adf24c9705d204bb8c1cfd94eafc3688c
forrestabouelnasr/university_enrollment
/main.py
2,578
3.5
4
import mysql.connector from local_password import database_password def query(query_string): cnx = mysql.connector.connect(user='root', password=database_password, host='127.0.0.1', database='university_enrollment') cursor = cnx.cursor(prepared=True)...
f35dfca8ad57a50afbf58bbf4d99a12286b6cd6d
Blond11516/AdventOfCode2018-python
/d6/Coordinates.py
691
3.53125
4
from __future__ import annotations import re class Coordinates: def __init__(self, x: int, y: int) -> None: self.x = x self.y = y def calculateManhattanDistance(self, x: int, y: int) -> int: return abs(x - self.x) + abs(y - self.y) def isInsideArea(self, minX: int, maxX: i...
874505df85127cc040db26d643dcc6ae2cd57656
MercyTrabe/Bootcamp-7
/day-4/test_super_sum.py
435
3.625
4
import unittest from super_sum import super_sum class SuperSumTestCase(unittest.TestCase): def test_empty_input(self): self.assertEqual(super_sum(), 0) def test_sum_of_integers(self): self.assertEqual(super_sum(1,2,3), 6) self.assertEqual(super_sum(-1,1), 0) def test_sum_of_items_in_one_list(self): sel...
65d4130f372dd1ccf7099dbf0aa90537aebf3805
Patrick-Ali/PythonLearning
/Day.py
487
3.875
4
# Testing Try Except statements and Error Riasing def numToDay(n): Mtup = (" ", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun") try: if n > 7: raise ValueError("There are only 7 days!") ## elif type(n) is not int(): ## raise TypeError("This is not a numerical valu...
c34826a6747f07ad3d93c2c8bad311c307d9512c
charan556/52-week-challenge
/PythonLab/mySource/PropertiesTest.py
472
4.03125
4
class Item(object): """Base class""" @property def name(self): if not hasattr(self, '_name'): self._name = '' return self._name @name.setter def name(self, value): self._name = value def __init__(self, name, value): self.name = name ...
c6688916cd7ca9460b5655118e9df951940b98ad
sanidhyamangal/NumpyScripts
/numpy_tuto.py
1,339
4.0625
4
# -*- coding: utf-8 -*- """ Created on Thu Jan 18 11:06:34 2018 @author: Sanidhya """ import numpy as np #generate a single dimesion array x1 = np.random.randint(10,size=6) #generate a two dimension array x2 = np.random.randint(10,size=(3,4)) #genareate a 3 dim array x3 = np.random.randint(10,size=(3,4,5)) #so...
3ab9a6bf87104c331493324f61a4e1a2a11a5023
cs-ufm/cs101-2020
/code/python/functions/kargs.py
256
3.828125
4
def plus(*args): return sum(args) def plus2(*args): total = 0 for i in args: print(f"Adding this value: {i}") total += i return total # Calculate the sum print(plus(1,4,5)) print(plus(1,4)) print(plus2(1,4,100,9,6,5,4,2,98))
6450eb58656052fb0323be5128150a8db0dc72f3
ramaramayadeepika/guvi11
/19.py
47
3.734375
4
num = int(input("") n = 5 while num>0: n=n*num
232162c93b3e92d14d9b4b895540785cce1b3405
TheScouser/algorithms
/arrays/2_unique_string_chars.py
619
3.71875
4
import unittest from collections import defaultdict def is_unique(string): SIZE = 128 unique_chars = defaultdict(list) char_hash = 0 if len(string) > SIZE: return False for char in string: char_hash = hash(char) char_index = char_hash % SIZE if (len(unique_chars[char_index]) != 0) and (unique_chars[cha...
7284a113d44f90392af35525f24caef343921c9d
Michael-Data-Science-spec/Lab7-Task3
/_221_happy.py
1,232
4.25
4
""" this module tells if a specific number is happy and generating a list of happy numbers """ def is_happy(num): """ int -> boolean Tells user whether the n number is happy or not >>> is_happy(32) True >>> is_happy(33) False """ num = str(num) iter_lst = [] # list...
d1199ab0c611d83a1eb3c9e379f8a6f0a06972ef
Angelsan720/RandomThings
/BFInterpreter/BFI.py
3,385
3.5
4
""" Angel A. Sanquiche Sanchez angelsan720@gmail.com angel.sanquiche@upr.edu OK this has been a long standing project for me since some time back and being without highspeed internet makes me do some strange things so of course the natural thing to do is make a Brainfuck interpreter. My recent Theory of computability...
61453c5cb564380d050f8f676236d0145e567f86
Gustacro/learning_python
/become_python_developer/4_Ex_Files_Python_Essentials/Exercise Files/Chap08/dict.py
1,486
4.46875
4
#!/usr/bin/env python3 # Copyright 2009-2017 BHG http://bw.org/ def main(): # animals = { 'kitten': 'meow', 'puppy': 'ruff!', 'lion': 'grrr', # 'giraffe': 'I am a giraffe!', 'dragon': 'rawr' } # Same as dictionary above, but better to read and easy interpretation animals = dict(kitten= 'meow', puppy= 'ruff!', l...
23de6c5a8284a4e6b47863ad2b9b77471fb76da1
Godsmith/adventofcode2016
/day12/computer.py
2,643
3.609375
4
class Computer: def __init__(self): self.registers = {} self.instruction_index = 0 def evaluate(self, instructions): while self.instruction_index < len(instructions): self.execute(instructions) self.instruction_index += 1 def execute(self, instructions): ...
e813e8a43f5436f7e764885a3d55a902ccfe5271
nhlong9697/automate-the-boring-stuff
/chapter5/isValidChessBoard.py
866
3.828125
4
chess_board = {'1h': 'bking', '6c': 'wqueen', '2g': 'bbishop', '5h': 'bqueen', '3e': 'wking'} def is_valid_chess_board(chess_board): is_one_king = True is_valid_space = True is_black_or_white = True number_white_king = 0 number_black_king = 0 for v in chess_board.values(): if (v[0] != '...
7787f26efb8de7b871eae28f88b152488300d73b
lestieve/ODATAF
/app_dictionary.py
3,354
3.8125
4
import json import pickle dict_languages = {} dict_lang = {} def load_dictionary(dictionary_path="dictionary.json", binary_path="dictionary.dat", lang="fr"): """Load the dictionary from the file dictionary.dat (pickle) If it's not found, it tries to create a new dictionary.dat file from the ot...
d9137a4095eb2b7a5c42b0ab395f6af7f49c5b6f
LintaPaul/unisys_new
/ocr_server/test2.py
1,894
3.546875
4
# importing modules import cv2 import pytesseract # reading image using opencv from pytesseract import Output image = cv2.imread(r"C:\Users\LINTA\Downloads\Dataset\pan\pan_37.jpg") # converting image into gray scale image gray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) # converting it to binary image by Threshold...
9db46475ab455bb485dca0ebd4e965eef0fafbd2
kioni-collab/Python-Code
/TestLinkedList.py
10,143
4.0625
4
# File: TestLinkedList.py # Description: In this program, it builds its own data structure function for linkedlist, and applys to list. # Student Name: Mengjie Yu # Student UT EID: my3852 # Course Name: CS 313E # Unique Number: 53260 # Date Created:3/18/13 # Date Last Modified: 3/18/13 class Link (ob...
c0c5882b0ff4018a63402743e7344317d1253aba
jtraver/dev
/python3/enumerate/enumerate1.py
709
3.59375
4
#!/usr/bin/env python3 # https://medium.com/better-programming/stop-using-range-in-your-python-for-loops-53c04593f936 import sys VT100_BOLD = "" VT100_RED = "" VT100_GREEN = "" VT100_STOP_MARKUP = "" def main(): ret1 = 0 ret1 += enumerate1() if ret1: print("%sFAIL %s%...
43724b20cfa14880d0940b6c43867cd5690ba3aa
Sexypanda8888/Ero_pic_project
/Web/app1/utility.py
635
3.578125
4
#返回一个当日时间限制 #time_setting本来应该是一个22:22:00的类型,但是方便起见就变成整点了 import datetime import re def today_limit(date,time_setting): #date遵循xxxx-xx-xx Searchobj=re.search(r'([0-9]{4})-([0-9]{2})-([0-9]{2})',date) if not Searchobj: print("Wrong type of input") a=datetime.datetime(int(Searchobj.group(1)),int(Se...
a9037f9c41813638dae24a1659eb777dac4a3a35
Arquedy/atom
/par_impar.py
196
3.953125
4
print("Digita qualquer numero") num = float(input("Vou falar se o numero é par ou impar, digita ae: ")) if num % 2 == 0: print("esse numero é par") else: print("Esse numero pe impar")
bd7a55c6fb7e1e4077a0f353e5301f4004e9c36e
itc-n21003/lesson
/z45g63j.py
140
3.71875
4
tv = ["GOT", "Narcos", "Vice"] 2 i = 0 3 for show in tv: >> 4 new = tv[i]: >> 5 new = new.upper() 6 tv[i] = new 7 8 9 print(tv)
b84ab85383008e2158f89dfcbb8f04a9f01bfe89
Satupathe/OC-Projet-2
/scraping/pictures.py
604
3.609375
4
"""Module to scrape picture from https://books.toscrape.com""" import os import urllib.request def pictures_scraping(list_of_dicts, category_name): """scraping and naming of each book picture""" img_url_list = [] img_name = [] for d in list_of_dicts: img_url_list.append(d["Picture URL"]) ...
6789e11bb5d4ee2df8277a2cf06f9ff8651e4d7a
jbischof/algo_practice
/udacity/knapsack.py
1,450
4.09375
4
class Item(object): def __init__(self, weight, value): self.weight = weight self.value = value self.added = False def _clear_items(items): for item in items: item.added = False def binary_knapsack(items, total_weight): """ Solves the knapsack problem for binary inclusion. Args: items: An array of Item ...
b98c76144c87c5839894643e0c8fdca2f3ae4861
MaxyLee/CryptoLab
/Lab1/lab1_21_1.py
1,051
3.703125
4
ciphertext = 'EMGLOSUDCGDNCUSWYSFHNSFCYKDPUMLWGYICOXYSIPJCKQPKUGKMGOLICGINCGACKSNISACYKZSCKXECJCKSHYSXCGOIDPKZCNKSHICGIWYGKKGKGOLDSILKGOIUSIGLEDSPWZUGFZCCNDGYYSFUSZCNXEOJNCGYEOWEUPXEZGACGNFGLKNSACIGOIYCKXCJUCIUZCFZCCNDGYYSFEUEKUZCSOCFZCCNCIACZEJNCSHFZEJZEGMXCYHCJUMGKUCY' sub = { 'A':'v', 'B':'x', 'C':'e', 'D':'b', ...
307d7176579b46758ff6c9c46f3b455f38532985
juvham/learn-python
/python基础/5.字符串/2.详解字符串-字符串相关操作.py
1,457
4.25
4
#!/usr/bin/python # -*- coding: utf-8 -*- # 字符串相关操作 # - 字符串 + 操作 vara = '君不见,黄河之水天上来,奔流到海不复回.' varb = '君不见,高堂明镜悲白发,朝如青丝暮成雪' # res = vara + varb res = '将进酒 '+'李白' print(res) # - 字符串 * 操作 vars = '鸡你太美,' * 5 print(vars) # 鸡你太美鸡你太美鸡你太美鸡你太美鸡你太美 # - 字符串 [] 切片操作 **** # 字符串的索引操作,字符串中只能使用[]下标 访问,不能修改 ''' 0 1 2 3 4 5 6 7 8 9...
6aa7e06aa8ffb8591a9b711fc61a0eebfb928bd8
abi26anamo/python-codeforces
/617b chocolate.py
480
3.625
4
limit = int(input()) space = ' ' for i in range(0, limit + 1): print(space * (limit - i), end='') for j in range(2 * i + 1): if j > i: print(i - (j - i), end=' ') else: print(j, end=" ") print() for i in range(0, limit)[::-1]: print(space * (limit - i), end...
0e10de01c532bd71b868857c7c1e7ce9a969264b
samreachyan/programiz-python
/Basic/Inheritance2.py
750
3.890625
4
class Polygon: def __init__(self, no_of_sides): self.n = no_of_sides self.sides = [0 for i in range(no_of_sides)] def inputSides(self): self.sides = [float(input("Enter side "+str(i+1)+" : ")) for i in range(self.n)] def dispSides(self): for i in range(self.n): ...
179028b831c37133c15a43ee0d2361394f165f8c
simjxu/Other-MachineLearning
/MachineLearningPy35/basicNN_mnist.py
4,099
3.5625
4
import tensorflow as tf # ------------------------------------------- DATA IMPORT SECTION ---------------------------------------------------- # # Import mnist data: Requires internet connection to collect from tensorflow.examples.tutorials.mnist import input_data # Formatting data so the classification is more machi...
0d198c00f90e8b6788b726b00c2e421dbca095bb
ohmema/interview
/python/interviews/ConcurrentAndMultiThreading/basic_thread.py
854
3.609375
4
from threading import Thread import threading import time def do_some_work(t, txt): for i in range(1): print("{} doing some work in thread {}".format(threading.current_thread().getName(), txt)) time.sleep(t) print("{} end of thread {}".format(threading.current_thread().getName(), txt)) sho...
6ced1184315aad62ef99214744e78fc36b4c403b
chlee1252/dailyLeetCode
/decodeString.py
1,079
3.5
4
class Solution: def decodeString(self, s: str) -> str: self.i = 0 s = "1[" + s + "]" def decode(): if self.i >= len(s): return "" if s[self.i].isdigit(): j = self.i while s[self.i].isdigit(): self.i += 1 ...
48be4e1168485f64bb987e21a952815bfa80f145
rodrigobn/Python
/Lista de exercício 4 (laços)/ex02.py
387
4
4
""" 2 - Escreva um programa que calcula a média de 30 alunos e informa a situação (reprovado, aprovado ou recuperação). """ for i in range(30): nota1 = float(input("Primeira nota: ")) nota2 = float(input("Segunda nota: ")) media = (nota1 + nota2) / 2 if 0 <= media < 4: print("Reprovado") elif 4 <= media...
8751f260397c30af500fdbd34ad3e343bd8ce55b
mbohekale/Python2019-20
/lecture3/lab3.1.py
282
4.15625
4
def is_YearLeap(year): leap = False if year%400==0: leap = True elif year%100==0: leap = False elif year%4==0: leap = True return leap year = int(input("Enter a year:")) print("Is it a leap year? : ",is_YearLeap(year))
757c04861fab7d8f0543bbe20afe1131699c5f52
spryor/Sorting-Algorithms
/Python/sort_bubble.py
262
3.828125
4
#Author: Stephen Pryor #Date: September 26, 2012 def sort_bubble(lst): updated = True while updated: updated = False for i in range(len(lst)-1): if lst[i] > lst[i+1]: lst[i], lst[i+1] = lst[i+1], lst[i] updated = True return lst
1edd5b063fe9027d338b5980633b8a8da87f746a
chenfan2014/CFgit
/Python/ListArray/sliceList.py
466
3.640625
4
#!usr/bin/env python #-*- coding:utf-8 -*- lst = [] for i in range(11): lst.append(i*i) print lst lst2 = [x * x for x in range(1,11)] print lst2 print [m + n for m in "ABC" for n in "XYZ"] l = [x * x for x in range(1, 11)] print l g = (x * x for x in range(10)) print g for i in range(10): print g.next() p...
aa9f039917fa15f75f6d040d758802f6fd2ebbde
learning-Kong/python-object-oriented
/python-组合.py
2,004
3.9375
4
# -*- coding:utf-8 -*- # author:"Xianglei Kong" class People: school = "CUIT" def __init__(self,name,gender,age): self.name = name self.gender = gender self.age = age class Teacher(People): def __init__(self,name,gender,age,level,salary): super().__init__(name,gender,age) ...
2f1f8605c554a6a489ce6af51ea87fe56b1b6d12
aukraine/Python
/lab6_4.py
1,316
4.34375
4
text = ['Hello,Hello, my dear!', 'to understand recursion you need first to understand recursion...', 'Mom! Mom! Are you sleeping?!!!'] def find_most_frequent(text): def get_words(text): word = text[0] words = [] for l in range(1, len(text)): if (text[l] >= 'a' ...
e14390fe587175f815a5d1b0ca9e648a132edf88
GCCSD/DojosGCCSD
/20110108/cesar.py
1,045
3.75
4
#!/usr/bin/env python __authors__ = ( "Apu", "Sigano", "InFog", "Paulo", "Doug", "ExHora" ) import string class Cesar(object): def __init__(self): self.INICIO = 65 self.FIM = 90 self.ESPACO = 32 def crypt(self, entrada = "", chave = 0): saida...
3711e353184633ecad5841695759d9f5466eb8cc
yyHaker/PythonStudy
/algorithms/structure/graph/graph_adjlist.py
1,592
3.796875
4
#!/usr/bin/python # coding:utf-8 """使用邻接表实现图. (该处实现的是有向图) @author: yyhaker @contact: 572176750@qq.com @file: graph.py @time: 2019/4/11 21:54 """ class Vertex(object): def __init__(self, key): self.id = key # the id of vertex self.connectedTo = {} def addNeighbor(self, key, weight=0): ...
f99a356d961abb54425d83b341c4456b042adf16
Achonger09/lotus
/src/server/server.py
835
3.5625
4
#!/usr/bin/env python # -*- coding: utf-8 -*- import socket class Server: def __init__(self,host,port): print("init server with host:%s,port:%d" % (host,port)) self.host = host self.port = port def runServer(self): isRun = True tcpSock = socket.socket(socket.AF_INET, s...
e7702047c035bc9bae39688cc0b2873c2b0a6629
abhi9321/python_repo
/encapsulation/get_set.py
767
4.5
4
""" Using getter and setter methods to access private variables To access and change private variables accessor (getter) methods and mutator (setter methods) should be used which are part of the class. """ class Account: def __init__(self): self.cust_name = 'Abhishek' # public self.__account_no =...
0b810ccc468b3609429767c032ac4749ab6cdf3f
karbekk/Python_Data_Structures
/Interview/Python_Excercises/Files/Seek().py
486
4.03125
4
# Seek is a pointer to keep track where we are in the file. # Before reading or writing seek pointer is set to zero. # it moves by one position after writing a character to file # Before reading we must again set it back to zero. # Eg: myFile = open("a.txt", "r") # # myFile.read(10) read 10 bytes # ...
bc5ab6dccc7a07e6dc3c0316cb01190ccafe4f5f
landry-ming/leetcode_python
/剑指offer/52_ l两个链表的第一个公共节.py
1,263
3.71875
4
# Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None #### 哈希指针是最简单的思路 class Solution: def getIntersectionNode(self, headA: ListNode, headB: ListNode) -> ListNode: hashtable = set() index1 = headA index2 = hea...
b2ccc572cd52ec56b95ca3dca43b17449de027c2
jdanray/leetcode
/largestCombination.py
800
3.625
4
# https://leetcode.com/problems/largest-combination-with-bitwise-and-greater-than-zero/ class Solution(object): def largestCombination(self, candidates): bit = collections.Counter() for c in candidates: i = 0 while c > 0: bit[i] += (c & 1) i += 1 c >>= 1 return max(bit.values()) """ After I s...
47376f65ef7042b344e2f270667d7c99069fbb7a
abebinder/randompython
/derp.py
674
3.71875
4
distro_dict ={ 2:1, 3:2, 4:3, 5:4, 6:5, 7:6, 8:5, 9:4, 10:3, 11:2, 12:1 } def check(a,b,n): counter =0 for a_item in a: for b_item in b: if a_item + b_item == n: counter+=1 return counter def recursive(a,b,n): val = chec...
32a01732624a7f1ed652c53a95139d5543558f47
rivaidya/507_final_project
/database/database_accessor.py
9,459
3.671875
4
import sqlite3 DATABASE = 'YelpDatabase.sqlite' class DatabaseAccessor: city_table_name = "city_table" zip_code_table_name = "zip_code_table" categories_table_name = "category_table" business_data_per_city_table_name = "business_data_per_city_table" business_data_per_zip_code_table_name = "busine...
e617fcfb901e66938a4e1faf1f8b27b3a2fa0284
zachrickert/data_structures
/src/heap.py
4,293
3.859375
4
# -*- coding: utf-8 -*- """Testing module for the Heap classes.""" class Heap(object): """Heap class implementation.""" def __init__(self, min_max='max'): """Initialize Heap.""" self._heap = [] self.size = 0 heap_types = ['max', 'min'] if min_max.lower() in heap_types:...
0ea509243f58b4052b5e43106b6a9cc910d1eb76
aimers1975/APTFall2014Amy
/hw1/test_student.py
5,070
3.734375
4
from student import student def test_create(): name = 'student' GPA = 0.0 age = 16 amyStudent = student() assert amyStudent.name == name assert amyStudent.GPA == GPA assert amyStudent.age == age name = '1' GPA = 1 age = 2 amyStudent = student(name,GPA,age) assert amyStudent.name == name assert amyStudent...
39562b7a9c31b98ea26289ad1ab12329b9501908
sky8785/JerryHW
/0326/source/cacu.py
196
3.921875
4
# coding: utf-8 # In[5]: def ans(a,b,x): if x == "+": return a+b elif x == "-": return a-b elif x == "*": return a*b elif x == "/": return a/b
d78d0cc171358dfab66f7dc44891c95c8fb11758
bksrocks/CofC-SchoolProblems
/CSCI220 - Computer Programming I/HW02_workingTime/working_time.py
4,906
4.28125
4
# Name: Barbara Szwabowski # working_time.py # Purpose: Calculate the total time worked in a company, in minutes, # hours and days and output the numbers in the correct formats # (60 minutes/24 hours) # Certification of Authenticity: I certify that this lab is entirely my # own work but I discussed it with Dr. Kebin ...
e62bde488644d588df78dd00f9ddfd316af70b84
z19960702/my-pratice
/leetcode/leetcode104.py
821
3.734375
4
class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: def maxDepth(self, root: TreeNode) -> int: self.maxDeep = 0 def preorder(node: TreeNode,deep : int): # 先序遍历 if node is None: ...
c3a23ee226772d5c6d815ae7ca121c06ad347718
953250587/leetcode-python
/ArrayNesting_MID_565.py
1,863
3.75
4
""" A zero-indexed array A of length N contains all integers from 0 to N-1. Find and return the longest length of set S, where S[i] = {A[i], A[A[i]], A[A[A[i]]], ... } subjected to the rule below. Suppose the first element in S starts with the selection of element A[i] of index = i, the next element in S should be A[A...
1870e4ef26c574744c2c0ae7c02f5166e9cf70ef
komministern/euler_project
/problem_14_klart.py
658
3.84375
4
def iterate(n): if n % 2 == 0: return n / 2 else: return 3*n + 1 list_of_start_values = [0] * 1000001 def iterations(n): if n == 1: return 1 elif n > 1000000: counter = 1 while n > 1: n = iterate(n) counter += 1 return counter elif list_of_start_values[n] == 0: list_of_s...
d517d689bfd23acb452a2c1e69977e09ea981b4a
ichbinchicken/COMP2041
/w7/count_word.py
257
3.734375
4
#!/usr/bin/python import sys,re words=[] count=0 for line in sys.stdin: words=re.findall(r'(\b[A-Za-z]+\b)',line) for each in words: if(each.lower() == sys.argv[1].lower()): count+=1; print sys.argv[1].lower(),"occurred",count,"times";
e94117bb67342920c54958942c98f8d8c607b4b9
tingtingths/PyCC
/pycc.py
3,075
3.578125
4
# Chinese characters convert tool # Traditional <--> Simplified, from any encoding to utf-8. import sys import chardet import os import glob import argparse from collections import deque def detect(bytes): encoding_swap = {"big5":"cp950", "gb2312":"gbk"} codec = chardet.detect(bytes)["encoding"] ...
0db0c89c0f86e9691b4d3c649cb50cd03760ccd2
cosmos-nefeli/practice_python
/maps.py
545
4.21875
4
""" Python Maps also called ChainMap is a type of data structure to manage multiple dictionaries together as one unit. """ import collections dict1 = {'day1': 'Mon', 'day2': 'Tue'} dict2 = {'day3': 'Wed', 'day1': 'Thu'} res = collections.ChainMap(dict1, dict2) # Creating a single dictionary print(res.maps,'\n'...
b2e23f15aae4229cdeec944fcbcc3e6496cbee9f
2sjeong918/study_python
/강의자료/03. 파이썬/contact/Contact.py
1,839
3.546875
4
class Contact: def __init__(self, name, cell_phone, email='', address='', birthday=''): self.__name = name self.__cell_phone = cell_phone self.__email = email self.__address = address self.__birthday = birthday def get_name(self): return self.__name def set_...
f2394f1cf5e3e873714f7d461798c6610b5db041
itsaliazadi/A-simple-calculator-with-python
/widgets.py
3,264
3.9375
4
import tkinter as tk from calculate import calculate SCREEN = tk.Tk() SCREEN.geometry("300x510") text_bar = tk.Text(SCREEN, height=5, width=20) text_bar.place(y=20, x=80) math_operation = '' # We'll store the math operations taken by the user in this variable. text_bar.insert(tk.END, math_operation) # This func...
2b6f08145d542406c7e53d960a4e350d6fae26cc
wuyb518/python-learn
/高级教程/007数据库/001mysql.py
980
3.5625
4
#!/usr/bin/env python # _*_ coding:UTF-8_*_ import MySQLdb conn=MySQLdb.connect(user='test',passwd='test123',host='localhost') cursor=conn.cursor() cursor.execute('create database test;') # cursor.commit() MySqldb开启了自动提交所有不用手动commit cursor.execute('use test;') cursor.execute('create table friend(name nvarchar(50),age ...
661fd841cb2c20ece8fb3717e1d4dad7571a531c
pythonCore24062021/pythoncore
/HW/homework01/rrasi/task 01.py
386
3.953125
4
# Task 1 a = int(input('Please enter number a:')) b = int(input('Please enter number b:')) print('a+b=' + str(a+b)) print('a-b=' + str(a-b)) print('a*b=' + str(a*b)) print('a/b=' + str(a/b)) # Task 2 name = input('What is your name?') age = input('How old are you?') city = input('Where do you live?') print('Hello,' ...
34a909873f359568c719656c178e8913ec3cf8de
raminrazi/test
/direct0822/ODEs/lorenz96.py
10,416
3.921875
4
import numpy as np def lorenz96_ode(t, x, params): ''' This is the ODE function f(x,params). This function will be sent as a parameter to the scipy.integrate.ode(). To see how this works, please look at the simulate.py file. Input: t: time. This should always be the first parameter. x:...
f389871c30065dbcf49e54af6fbbc234025d3b0f
gongzhiyao/FirstTest
/venv/test/practice.py
1,830
4.15625
4
#!/usr/bin/env python # coding=utf-8 print(u"哈哈哈") classmates = ['Michael', 'Bob', 'Tracy'] print classmates print len(classmates) print classmates[0] print classmates[1] print classmates[2] # 取最后一个 print classmates[-1] classmates.append("Adam") print classmates classmates.insert(1, "Jack") print classmates prin...
a800f4194fb50c8bd6e9d0ab1ca695e13b77c460
huboa/xuexi
/liaoxuefeng/03-gao-advance/05-high.py
397
3.953125
4
##小九九 n = 9 i = 0 while (i < n): i += 1 j = 0 L = [] while(j < i): j += 1 s = j * i # print(j,"*",i ,"=",s) L.append("%s*%s=%s"%(j,i,s)) print(L) ##汉诺塔 # def move(n,a,b,c): # if n==1: # print(a,'->',c) # else: # move(n-1,a,c,b) # ...
5692a1179da267314a49965f2dac93b7f59d9d4e
GreyCosSil/Coursera-USP
/Ex-sem7-retangulo.py
347
4.09375
4
largura = int(input('digite a largura: ')) altura = int(input('digite a altura: ')) while largura<0 or altura<0: largura = int(input('digite a largura: ')) altura = int(input('digite a altura: ')) continue y = 1 while y <= altura: x = 1 while x <= largura: print('#', end = "") x +=...
64ea9257f02d3e80136f772b75efd5bb4b293b92
komoto415/COSC2316
/Homeworks/HW04/heap.py
7,523
4.125
4
# YOUR NAME HERE # heap.py # 3/15/21 # This program contains implementation for a basic heap structure. # We will expand on this for in class practice and for the homework # A heap is a semi sorted datastructure that gives us instant access # to the item of most priority in the structure, typically the minimal # or max...
4cd7daea0a7912370d13db8ccbda074c7950e556
MohaHayat/ML-Self-Teaching
/Neural Network 1.py
3,323
4.03125
4
import tensorflow as tf from tensorflow import keras # an API for tensorflow, essentially you write less code - high level import numpy as np import matplotlib.pyplot as plt data = keras.datasets.fashion_mnist # getting fashion_mnist data set # like the ML series, split the data into testing and...
c6295c2899b7f3f292e5abfa9de439a5ff54c152
rusantsovsv/CookBook
/1_list_and_dict/1.19_convolution.py
1,510
3.59375
4
""" Вам нужно выполнить функцию сокращения (т. е. sum(), min(), max()), но сначала необходимо преобразовать или отфильтровать данные. Есть весьма элегантное решение для объединения сокращения (свертки) и преоб- разования данных – выражение-генератор в аргументе. Например, если вы хотите подсчитать сумму квадратов, поп...
0a61444cad200d91f0cf7d48d6ca3cb6a7ca89d8
DerwinAkbarNugroho/Phython
/Tahun Kabisat.py
387
3.703125
4
Tahun = int(input('Tahun Yang Dicari ')) if (Tahun % 4) == 0: if (Tahun%100) == 0: if (Tahun%400) == 0: print('{0} adalah tahun kabisat'. format(Tahun)) else: print('{0} bukan tahun kabisat'. format(Tahun)) else: print('{0} adalah tahun kabisat'. format(...
b0c2d125af3ff3c58833fc5dfdc97f1fbbd522e3
theJSK/PythonLang
/ListChecker.py
530
3.796875
4
# -*- coding: utf-8 -*- """ @author: Jung Soo """ int_list = [] i = 0 j = 0 inOrder = True message = "" while i < 10: integer = int(input("Enter an integer.\n")) int_list.append(integer) i += 1 """print(int_list[j])""" while j < 9: if (int_list[j] <= int_list[j + 1]): inO...
17612a62b31c7573ebcfb2ecc015023c0c2f0fcf
nairnikhil848/Hackerrank-Solved-codes
/Sudoku_solver.py
2,612
3.8125
4
import matplotlib as plt import numpy as np from tkinter import * def print_board(B): # prints the board for i in range(len(B)): if i % 3 == 0 and i != 0: print("- - - - - - - - - - - - - ") for j in range(len(B[0])): if j % 3 == 0 and j != 0: print(" | ",...
3527225879805bd2c6751e1f45326d9a81dcc7c6
astroML/astroML_figures
/book_figures/chapter3/fig_gamma_distribution.py
2,425
4.25
4
""" Example of a Gamma distribution ------------------------------- Figure 3.18. This shows an example of a gamma distribution with various parameters. We'll generate the distribution using:: dist = scipy.stats.gamma(...) Where ... should be filled in with the desired distribution parameters Once we have defined...
823bd881e87e72b55516c8a589e197989c7d52c7
renanmat/ExPython
/ex050.py
179
4.0625
4
soma = 0 for cont in range(0, 6): num = int(input('Ditite um numero: ')) if num % 2 == 0: soma += num print('A soma dos numeros pares é igual a {}'.format(soma))
deb0509d524e0d218f0a1d8feeabb21668246109
nkoukou/University_Projects_Years_1_and_2
/Optical_Ray_Tracer/ray.py
3,179
4.34375
4
""" ray.py defines a class of rays that can be represented in space. A ray propagates in the optical system and can be refracted, reflected or dispersed. Each instantiation is hence described by several line segments in space which are determined by their endpoints and directions. The final segment determines the curr...
9c50854f304129cf2b4603114c1953a48ef05303
SorawatSiangpipop/Python
/membership_op.py
434
3.8125
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sat Jun 22 13:01:31 2019 @author: ssiangpipop """ """ flowers = "illy", "rose", "daisy", "tulip" if "rose" in flowers: print("available") else: print("not available") """ """ sentence = "over the rainbow" if "Rain" in sentence: print("okay") e...
5069af05ee55a5f14ba74370bf09fbdb71a8aebd
kecarrillo/monopoly
/Monopoly/Pawn.py
15,855
3.796875
4
import random from Monopoly.Auction import Auction from Monopoly.Owner import Owner class Pawn(Owner): """ This class represents the avatar of the players. """ def __init__(self, name, money): """This method is the constructor of the class. :param form: Form of the pawn. :ty...
5218bbb8d082805fb1993d6b53bf4d6f7a8e2ace
franwatafaka/funciones_python
/ejercicios_practica/ejercicio_4.py
2,324
4.53125
5
# Funciones [Python] # Ejercicios de práctica # Autor: Inove Coding School # Version: 2.0 # IMPORTANTE: NO borrar los comentarios # que aparecen en verde con el hashtag "#" # Ejercicios con funciones y módulos import random # -------------------------------- # Aquí dentro definir la función lista_aleat...
9c2c3be4fd37b3bf648bbb96e241c15a7bb1c230
Bradley94/misc-theory-work
/sorting_lists_with_comprehension.py
1,962
4.34375
4
''' You have an array of numbers. Your task is to sort ascending odd numbers but even numbers must be on their places. Zero isn't an odd number and you don't need to move it. If you have an empty array, you need to return it. Example sort_array([5, 3, 2, 8, 1, 4]) == [1, 3, 2, 8, 5, 4] *******************...
02e94a1a31317fb0ac2fcc83c5a3e4d0b4347b03
rjchow/adventofcode
/3/main.py
610
3.640625
4
class Node: def __init__(self, x, y): self.x = x self.y = y def __str__(self): return str(self.x) + ',' + str(self.y) class Grid: def __init__(self, width, height): self.width = width self.height = height self.grid = dict() for x in ...
b4bb861bcf50471cc934e35e2e2579200c1a505d
JosephLevinthal/Research-projects
/5 - Notebooks e Data/1 - Análises numéricas/Arquivos David/Atualizados/logDicas-master/data/2019-1/225/users/3987/codes/1592_2425.py
90
3.875
4
dt = float(input("d:")) cg = float(input("c:")) cm = dt/cg t = round(cm,3) print(t,"km/l")
42c122ccc01923ce5c70c5d39bf0a7db7effd8a8
AmpasTheodoros/Auto-Email-Sender
/MulyEmail.py
977
3.734375
4
# Python code to send email to a list of # emails from a spreadsheet # import the required libraries import pandas as pd import smtplib # email and password your_email = "your email" your_password = "password" #Login in server = smtplib.SMTP_SSL('smtp.gmail.com', 465) server.ehlo() serve...
8c6fec4967004e3e6ebd11c0f77cbf27edec8619
learnwithvidya/Python-OTP-GUI
/otpveripage.py
2,235
3.90625
4
#https://thecleverprogrammer.com/2020/08/24/otp-verification-gui-with-python/ from tkinter import * from tkinter import messagebox import tkinter import time import os Window=Tk() Window.geometry("800x600") Window.title("Verification Screen") count = 3 #global variable for count calculation. Initially ther...
e388b34506e997e65f96fdf72c654b58e1cfc23e
wangpengda1210/Robogotchi
/Problems/Stack class/main.py
348
3.71875
4
class Stack: def __init__(self): self.values = [] def push(self, el): self.values.append(el) def pop(self): to_pop = self.peek() self.values.pop() return to_pop def peek(self): return self.values[len(self.values) - 1] def is_empty(self): r...
591b8c95e21e491d292936552cd3e50f8b31a44a
ethender/pythonlearn
/Lectures/Lecture17/rec7.py
1,660
4.0625
4
""" Recitation 7: Distributions, Monte Carlo, and Regressions """ """ Distributions 1. Normal 2. Uniform 3. Exponential Uniform 1/b-a """ import math import pylab import random def show_discrete_uniform(a,b, num_points): points = [] for s in range(num_points): points.append(random.randint(a,b)...
75b30668455118f3ebedb45d043a3b3f5f0c6521
Hedgehuug/python_30
/day6/tutorial.py
688
3.78125
4
""" Day 6: Reduce higher order function takes (function,sequence) as input uses the first 2 elements of the sequence for the calculations NEEDS TO BE IMPORTED """ from functools import reduce test_list = [1,5,3,7,4] #The function has to take 2 inputs def add(num_a,num_b): return num_a + num_b print(reduce(add,t...