blob_id
stringlengths
40
40
repo_name
stringlengths
5
127
path
stringlengths
2
523
length_bytes
int64
22
545k
score
float64
3.5
5.34
int_score
int64
4
5
text
stringlengths
22
545k
03d93db6b7eddddb37d57b2a07d5595e22c9874a
Armstrong251/File-Share
/client.py
3,346
3.5
4
from socket import * import select,sys,socket HOST = socket.gethostbyname(socket.gethostname()) # The remote host PORT = 5001 # The same port as used by the server SPORT = 5006 MYIP = '127.0.0.1'#if the ip's of the 2 clients are the same issues will arrise s = socket.socket(socket.AF_INET, socket.SOCK_DG...
7dff3442023dd51a7b13eaebcb8c36586522ce9c
chengguobiao/test
/Algorithm_collection/string_quick_sort.py
1,357
3.671875
4
#!usr/bin/env python #encoding:utf-8 ''' __Author__:沂水寒城 功能:对字符串进行快速排序输出 ''' def get_string_quick_sorted(one_str_list, left, right): ''' 输入:待排序的字符串列表,起始位置下标 输出:标志位下标位置,作为递归的划分界限 ''' start=left end=right tmp=one_str_list[start] while start<end: while one_str_list[end]>tmp and st...
4c73daad6e73d9d77343cdda1c0652afa8757351
bmschick/DemoProject
/Unit_1.1/1.1.8/answerKey.py
4,749
4.09375
4
# student names: '''Conditionals & The if statement''' # 1. Prediction: # 2. Did the program work exactly like you thought it would? # 3 '''Nested Conditionals''' # 4. # 5. # 6. # 7. '''The elif Statement''' # 8 & 9. # 10 & 11. '''College Board''' '''Nested for loop Iteration''' # 12-14. # Predicti...
ab88ff7a1b5ebad88c6934741a0582603b9313ea
bmschick/DemoProject
/Unit_1.2/1.2.1/Temp_1.2.1.py
1,482
4.15625
4
'''1.2.1 Catch-A-Turtle''' '''Abstracting with Modules & Functions''' # 0.1 How does the college board create a “function”? # 0.2 What is “return” # 1 # Quiz: '''Events''' # # '''Click a Turtle''' # 2 through 14 (Make sure you comment the code!!): # 14 Did you have any bugs throughout this section of cod...
483dd16f68fee23cfa9cf83d8ae2b5a3ef2c92ec
akankshajogdand/Py
/Assignments/Assign2/userinput.py
240
3.953125
4
a=input("Enter the first number") c=int(a) b=input("Enter the second number") d=int(b) print("Addition:",c+d) print("Difference:",c-d) print("Multiplication:",c*d) print("Division:",c/d) print("Integer Division:",c//d) print("Power:",c**d)
f3a48a7ad4ac52342c0ac041ea01a524f5aee40c
akankshajogdand/Py
/Assignments/Assign7/main.py
863
4.03125
4
import AreaOfShapes def Input(): a=input('Select the shape of which you want to calculate the area 1.Circle 2.Square 3.Rectangle') p=int(a) if(p==1): c=input('Enter the radius of the circle :') r=int(c) result=AreaOfShapes.Circle(r) print(result) elif(p==2): s=input(...
4866ce4bf6d9f6e9d5112b6714d1566f707eb1b7
nodesense/deloitte-aws-spark-db-aug-2021
/S004_Partition.py
1,224
3.703125
4
# Databricks notebook source data = range(10) # 8 parallism [community edition] print("Default min partition", sc.defaultMinPartitions) print("Default min parallism", sc.defaultParallelism) rdd = sc.parallelize(data, 4) # takes default partitions from sc.defaultParallelism # for each v.core, we can have minimum 3 to...
b3fdb069df5d85abe72e2d3221cf6f69a18755d7
kalaivanan07/sideProjects
/01_sudoku_v2.py
6,253
3.875
4
# -*- coding: utf-8 -*- """ Created on Tue Apr 13 01:59:24 2021 @author: r.kalaivanan rule based method set theory is used """ import numpy as np import math from functools import reduce def input_sudoku(): global g_size global g_values global g_puzzle global g_rs # square root si...
dfcd482c0af8226a824bc365baac9e5895d7e085
HeatDeath/PythonNetworkProgrammingCookbook
/1.2打印设备名和IPv4地址.py
442
3.71875
4
import socket def printMachineInfo(): hostName=socket.gethostname() #该函数没有参数,返回所在主机或本地主机的名字 print("Host name is %s " %hostName) print("------------------------------") IpAddress=socket.gethostbyname(hostName) #该函数接受一个参数hostname,返回对应的IP地址 print("IP address is %s " %IpAddress) if __name...
77244a8edec8f482e61cfe7cb2da857d989206cb
jesse10930/Similarities
/mario.py
830
4.3125
4
#allows us to use user input from cs50 import get_int #main function for the code def main(): #assigns the user input into the letter n while True: n = get_int("Enter an integer between 1 and 23: ") if n == 0: return elif n >= 1 and n <= 23: break #iterates ...
0bbd167058b52a26c7b90564523e466e2d8dc715
Kanchan528/assignment2
/q_3.py
244
4
4
# Write code that will print out the anagrams (words that use the same # letters) from a paragraph of text. import random word = "kanchan" word = list(word) print(word) for words in word: random.shuffle(word) print(''.join(word))
fbb550f2716947e2d9d7ec3652ad40734027a97c
Kanchan528/assignment2
/q_14.py
343
4
4
# Write a function that reads a CSV file. It should return a list of # dictionaries, using the first row as key names, and each subsequent # row as values for those keys. import csv def csv_file(): with open('person.csv', 'r') as per: reader = csv.DictReader(per) for value in reader: p...
7db343f504d9bcce070d832d836580f52f40b2c2
Shivanshgarg-india/python-programming
/pythin for loop.py
370
4.0625
4
# for loop for i in range(10): print(i, end=" ") print() #For loop using break for letter in 'Shiavsnh': if letter == 'i' or letter == 'n': break print('Current Letter :', letter) # for loop using continue for letter in 'Shivansh': if letter == 'i' or letter == 'n': con...
42ca6948fe97286b2cd5385410b02b2aa63a7faa
mf734/target_offer
/17.打印从1到最大的n位数.py
871
3.625
4
''' 打印从1到最大的n位数 输入数字n,按顺序打印出从1到最大的n位十进制数, 比如输入3,则打印出1、2、3一直到最大的3位数999. 解题思路:需要考虑大数问题,这是题目设置的陷阱。 可以把问题转换成数字排列问题,用递归让代码更简洁。 ''' class Solution: def printToMax(self, n): if n <= 0: return number = ['0']*n for i in range(10): number[0] = str(i) self.helper(number, n, 0) def prin(self, numb...
a72843e2dbe224aa08e9bd2ed100a91126ad20ea
slaweklink/hackerRankprograms
/linesplitandjoin.py
119
3.5625
4
def splitandjoin(s): s = s.split(" ") s = "-".join(s) return(print(s)) s = input() splitandjoin(s)
e7d5d51a0ba37a8ac8efc4d025356b438c250cbf
Adeon18/Solver_Algorithms
/graph_colorizer/main.py
3,325
3.875
4
''' Realizing graph colorizing by backtracking. ''' def read_file(path): ''' Reads from file and converts info into graph. ''' with open(path) as file: lines = file.readlines() lines = [x for x in lines] new_lines = [] for line in lines: new_line = line.strip().split(" ") ...
09cbea0ef775b53ea69662770087aeb18ff1fc22
Patricia-Kasapa/starting_github_anew
/stars.py
369
3.921875
4
## ##K = 3 ##for i in range(0, 4): ## k = 3 ## for j in range(0, k): ## print("* ", end = "") ## print() ## ## ##k = 1 ##for i in range(0, 4): ## for j in range(0, k): ## print("* ", end = "") ## k = k + 1 ## print() ##for i in range(0, 5): ## for j in range(0, k): ## print...
668d182e56f5388f9700825a912e88c2f2c6bc9d
Patricia-Kasapa/starting_github_anew
/map_example.py
348
3.796875
4
##def is_even(): ## numbers = [1,56,234,87,4,76,24,69,90,135] ## t = [number for numbers % 2 in numbers] ##def is_even(x): return (x % 2 ==0) ##t = [1,56,234,87,4,76,24,69,90,135] ##g = list(filter(is_even, t)) ## ##print(g) ## Not working yet items = [1, 2, 3, 4, 5] squares = map((lambda x: x % 2 == 0 ), ...
788414b9e3af22f0eb8e5ea55413ee1fbe655d09
jezradek/life_game
/life_game/rules/base.py
1,410
3.921875
4
#!/usr/bin/env python import random class EvolutionRule(object): """Base class for evolution rules. Each specific rule must inherit from this class and override the `apply` method. """ def apply(self, organism, species_occurrence_d, **kwargs): """This method must be overriden in sub...
5bd4f2a37dc4b9ec1ca6a9c3a58abbb5ff3160b8
jezradek/life_game
/life_game/models/state.py
1,630
4
4
#!/usr/bin/env python class State(object): """Represents the state of the game. Attributes: cells_cnt (int): Amount of cells in the game. species_cnt (int): Amount of species in the game. iterations_cnt (int): Value of current iteration in the game. organism_l (list)...
bd8a17e032b296b20a86a4d907c9538a472ce79e
qichen90/web_crawler
/glassdoor_scraper/queryDB.py
1,587
3.671875
4
__author__ = "QiChen" '''database query class: is used to access the data in the database''' from db_setup import Base, Interviews from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker class queryDB: engine = create_engine('sqlite:///interviews.db') Base.metadata.bind = engine DBsession = se...
348bb7171e18d1a17c53ac297918bce5cce9ce86
sashnat/Homework
/stepik_python_practice/2_2 lesson.py
1,093
3.5
4
# Вася планирует карьеру и переезд. Для это составил таблицу, # в которой для каждого региона записал зарплаты для разных интересные ему профессий. # Таблица доступна по ссылке # https://stepik.org/media/attachments/lesson/245267/salaries.xlsx. # Выведите название региона с самой высокой медианной зарплатой # (мед...
8376cc705fbcbd4a25d5e6f2a30704d8eaf61105
overtime3/overtime
/overtime/algorithms/centrality/pagerank.py
3,158
3.609375
4
""" Algorithms for computing temporal PageRank scores from temporal graph objects """ def temporal_pagerank(graph, alpha=0.85, beta=0.5, intervals=None): """ Returns the temporal PageRank score of nodes in a directed temporal graph. Parameter(s): ------------- graph : TemporalDiGr...
664066925f2061180647a1db3dee7161a9bc9bf3
mqasemi/python-ez
/dragon/dragon.py
3,337
3.734375
4
import random,sys, platform, os door=(0,0) dragon=(0,0) gamer=(0,0) gride=[] gride_size=2 valid_moves=[] gameover=False find_door=False def draw_gride(size,show_dragon=False): "draw game gride" print("",end="") for i in range(0,size): print(" ___",end="") print("") for i in range(0,size): ...
1e4d47d294dc599fd5d4ae275f0f17bddbd3f558
cedadev/nappy
/nappy/utils/right_strip.py
1,468
3.9375
4
#!/usr/bin/env python """ right_strip.py ============== Holds the rightStripCurlyBraces() function used to right strip any curly braces annotations from lines in a text file. E.g.: In: 36 1001 {NLHEAD FFI} Out: 36 1001 In: Tout (C) {Out-boarding air temperature} Out:...
00a228c6c6c7af8283825b755c5fcefde929fbcc
aconcan/Exercism
/word-count/word_count.py
106
3.5625
4
def count_words(sentence): parsed = map(split for word in sentence: if count[word]:
ca6ffdb3d4d70c074f0a3b38d95ba1fe61f0cae1
aconcan/Exercism
/phone-number/phone_number.py
1,594
3.578125
4
# class PhoneNumber: # def __init__(self, number): # self.number = ''.join([num for num in number if num.isdigit()]) # if self.number[0] == '1': # self.number = self.number.replace(self.number[0], '') # if len(self.number) != 10: # raise ValueError('.+') # ...
243671a6ea4dc482f0501243ed2b34071c180a72
JonoInSpace/exercism
/isbn_verifier.py
538
3.640625
4
def is_valid(isbn): check_sum = 0 isbn_no_dashes = '' for char in isbn: if char != '-': isbn_no_dashes += char if len(isbn_no_dashes) != 10: return False else: for i in range(10): digit = isbn_no_dashes[i] if digit in '0123456789': ...
d667ac25d2bbb757a4df4f5a42fa36b38cee620f
JonoInSpace/exercism
/anagram.py
274
3.890625
4
def find_anagrams(word, candidates): anagrams = [] for candidate in candidates: if word.lower() != candidate.lower(): if sorted(list(word.lower())) == sorted(list(candidate.lower())): anagrams.append(candidate) return anagrams
b41a291ec67c1e8befa932dfed3df2e0145f9e4e
JonoInSpace/exercism
/allergies.py
417
3.65625
4
ALLERGENS = ['eggs','peanuts','shellfish','strawberries','tomatoes','chocolate','pollen','cats'] class Allergies: def __init__(self, score): self.score = score self.allergy_lst = [x for x in ALLERGENS if self.score & 2**ALLERGENS.index(x)] def allergic_to(self, item): ...
c7c417864b59da124266adb5382e428bd2c43693
Viktorgild/-4
/задание 1.py
303
3.90625
4
def my_func(arg_1, arg_2, arg_3): res = arg_1 * arg_2 + arg_3 return res - (res * .13) x = int(input("Введите выработку в часах :")) y = int(input("Введите вашу ставку :")) s = int(input("Введите вашу премию :")) print(my_func(x, y, s))
ed297f5b51319c2d7441579670989b2b9e252602
31062/zombies
/create_zambies_database.py
1,340
3.59375
4
import sqlite3 def create_maps_table(): while sqlite3.connect("zambies.db") as db: cursor = db.cursor() sql = """create table Map( MapID integer, MapName text, primary key(MapID))""" cursor.execute(sql) db.commit() ...
689fe62e3365e686e26c0d301ba3043b7cb9408f
edendahan/Gauss_Sidel_And_Jacobian
/Gauss_Sidel_And_Jacobian.py
9,993
3.625
4
Eden Dahan 318641222 Ruth Avivi 208981555 import sys def determinant_recursive(A, total=0): # Section 1: store indices in list for row referencing indices = list(range(len(A))) # Section 2: when at 2x2 submatrices recursive calls end if len(A) == 2 and len(A[0]) == 2: val = A[0][0]...
834b47017d4bec8d092fe9c4dff35a78174f502f
riiichard/Machine_Learning_Exercises
/KNN (k-nearest neighbours)/knn.py
1,131
3.8125
4
""" Implementation of k-nearest neighbours classifier """ import numpy as np from scipy import stats import utils class KNN: def __init__(self, k): self.k = k def fit(self, X, y): self.X = X # just memorize the trianing data self.y = y def predict(self, Xtest): R, C = X...
a60078217f6904b00657d99dd64f5d449b819efd
Tobias-Braun/gym-dingnet
/gym_dingnet/envs/protocol.py
4,926
3.546875
4
from __future__ import annotations from typing import List import sys import socket import os from enum import Enum from time import sleep """ DingNet Communication Protocol This is a simple protocol for Communication with the DingNet Server. Messages are send using stdin and stdout There are four client message types...
6b5cf844f6234549275c2e87297ef37eb38c65f0
jyoti140180/test
/python.py
94
3.703125
4
student=input("are u a student") if student=="yes": print("study") else: print("play")
a07d85fd72dcd5b2ab7a6f5ddc6b9b12d15b335e
MMiknich/traffic_donkey
/Plot.py
418
3.625
4
import matplotlib.pyplot as plt def multiply(): c = 12345*6789 print('The result of 12345 x 6789 :', c) return c with open('Barcelona_net.tntp') as tbtp bebebe = [][][] with open('AverageTimes') as at: averTimes = [] for line in at: averTimes.append([float(x) for x in line.split()...
a4f38f9b8ca337652da1ebc50be6311c8900f089
wangyijie11/pypractice
/base/多线程-互斥锁.py
641
3.671875
4
#!/usr/bin/env python # -*- coding:utf-8 -*- import threading import time number = 0 lock = threading.Lock() def plus(lk): global number with lk: # with语句,实现锁管理,自动加锁、解锁 for _ in range(100000): number += 1 print("子线程%s运算结束后,number = %s" % (threading.current_thread().getName(), n...
0b85badaee710a64eddd4f45888e7b2adad1dec3
wangyijie11/pypractice
/base/encoding.py
222
3.640625
4
#!/usr/bin/env python # -*- coding:utf-8 -*- dec = int(input("输入数字:")) print("十进制数:", dec) print("二进制数:", bin(dec)) print("八进制数:", oct(dec)) print("十六进制数:", hex(dec))
cf9a7b3d15a801cf72a3326602611216b97a7257
wangyijie11/pypractice
/base/数据类型-字符串.py
908
3.703125
4
#!/usr/bin/env python3 # -*- coding:utf8 -*- st1 = ' wo shi, Cheng Long da ge ! ' st2 = '12' print(st1.capitalize()) print(st1.center(40)) print(st1.count('da')) by = st1.encode(encoding='utf-8', errors='strict') print(type(by)) st3 = by.decode(encoding='utf-8', errors='strict') print(type(st3)) print(st1.endswith('...
588c1ceee44a18d5b4153c8933defc9ff2cacd49
sandeep0704/MyCaptain1
/positive number.py
263
4.0625
4
mylist=[] n=int(input("enter no. of elements:")) print("enter ",n," elements:") for i in range(0,n): e=int(input()) mylist.append(e) print("your list:",mylist) print("The +ve no. are :-") for a in mylist: if a>0: print(a)
2c55104e100681e13599c5e033a4750fc3c453d6
gorkemunuvar/Data-Structures
/algorithm_questions/3_find_the_missing_element.py
1,569
4.125
4
# Problem: Consider an array of non-negative integers. A second array is formed by shuffling # the elements of the first array and deleting a random element. Given these two arrays, # find which element is missing in the second array. import collections # O(N) # But this way is not work correctly cause # arrays can h...
5dfc092677c9f2a020ccb79fd3063b718b3e8e89
gorkemunuvar/Data-Structures
/data_structures/deque.py
690
4.03125
4
class Deque(object): def __init__(self): self.items = [] def is_empty(self): return self.items == [] def size(self): return len(self.items) def add_front(self, item): self.items.append(item) def add_rear(self, item): self.items.insert(0, item) def rem...
155cd6d8900b67703026b495f8950ce0ed8d15a1
gorkemunuvar/Data-Structures
/algorithm_questions/2_array_pair_sum.py
912
3.71875
4
# Problem: Given an integer array, output all the unique # pairs that sum up to a specific value k. # O(N^2) def first_pair_sum(arr, k): if len(arr) < 2: return 0 counter = 0 for i in range(len(arr) - 1): # n step for j in range(i + 1, len(arr)): # n-j = n step if arr...
82bb54b9fda5352b1b338a7806a824b4dc2c0e29
Deshan-Chathuranga/WeirdScripts
/Python/Random_quotes/main.py
1,573
3.625
4
import random list1 = ["A friend asks only for your time not your money.", "A fresh start will put you on your way.", "A dubious friend may be an enemy in camouflage.", "You have a secret admirer.", "A faithful friend is a strong defense.","Good fortune will be yours.", "Be passionate and to...
c9fedf6472e0ff6fb20b7e640572f26b38cd52d5
CompThinking19/python-project-Jacob2148
/pythonproject.py
4,687
4.1875
4
#README #An attempt at creating a text adventure and escape room #Plan to have the user/player start in one area and try to make their way through a house for necessary things #premise of the program is for the user to guide themselves throughout the building and out of the small courtyard through a gate #throughout th...
351e79d71059e89664cddd394ac4db110beab3d3
hsyun89/PYTHON_ALGORITHM
/FAST_CAMPUS/링크드리스트.py
746
4.125
4
#파이썬 객체지향 프로그래밍으로 링크드리스트 구현하기 from random import randrange class Node: def __init__(self,data,next=None): self.data = data self.next = next class NodeMgmt: def __init__(self, data): self.head = Node(data) def add(self, data): if self.head =='': self.head = Node...
90aa399d25711fc18b758b9a3f9a1c26b9694b47
hadyan12/Basic-Project-Python
/segitiga.py
982
4.03125
4
def luas_segitiga(): alas = float(input('Masukan alas segitiga: ')) tinggi = float(input("Masukan tinggi segitiga: ")) luas = 1 / 2 * alas * tinggi print("Luas segitiga : ", luas) return luas def keliling_segitiga(): s1 = float(input("Masukan sisi 1 segitiga: ")) s2 = float(input("Masukan s...
9b01757389f8ea008b09920b0561a3d2bb242f6c
hadyan12/Basic-Project-Python
/keuangan.py
783
3.796875
4
def fungsi(): hasilnow = float(input("Masukan Koin Anda Sekarang : ")) jalan = hasilnow + float(20) print("Berikut Menu yang tersedia: ") print("1. Silahkan tulis ( y atau yes ) di bawah jika koin bertambah 20 di input di bawah ini") print("2. Silahkan tulis ( s atau no) setelah itu, Input nominal k...
809d62c6053a0fc38b48c5c367643b14f096faa6
Niranjanreddytalapa/PRACTICE
/Untitled.py
5,695
3.796875
4
#!/usr/bin/env python # coding: utf-8 # In[1]: s1 = """Python is an interpreted high-level general-purpose programming language. Python's design philosophy emphasizes code readability with its notable use of significant indentation. Wikipedia""" # In[3]: s1 = """Python is an interpreted high-level general-purpos...
061e78416ceb0aed35d23d414f184af28e5ce5b4
vpandeliev/Evaluation-Portal
/lib/AlphaCabbage-22f5512/alphacabbage/django/choices/__init__.py
3,167
3.859375
4
''' Classes: ChoiceList ''' class ChoiceList(object): """ChoiceList object. Instantiate by passing a multiline string, with names of each choice on single lines. For example, >>> choices = ChoiceList(''' ... First Choice ... Second Choice ... Final ... ''') Each choice is a...
4ba779de92e8a6cc58e60ff44d081ac7af3d0a06
bemarble96/python_test
/test4.py
422
3.546875
4
def mer(base1,base2,n): if n ==1: return base2 k_mer = [] for seq1 in base1: for seq2 in base2: k_mer.append(seq1+seq2) return mer(base1,k_mer,n-1) base1 = ["A","C","G","T"] base2 = ["A","C","G","T"] n = 7 mer_7=mer(base1,base2,n) Result = [] for sequence in mer_7: ...
46393081477c0443986e257fb8a8fd12d883f8b6
technolingo/design_patterns
/state/classic.py
896
3.9375
4
""" A contrived and convoluted example of a classic implementation of the state pattern. """ from abc import ABC class StateABC(ABC): def on(self, switch): print('Light is already on.') def off(self, switch): print('Light is already off.') class OnState(StateABC): def __init__(self):...
e82b4bbe52b0c9d20a01f91ba942943458533c5f
technolingo/design_patterns
/visitor/classic_dynamic.py
2,714
3.546875
4
""" This alternative implementation of the visitor pattern uses duck typing to simplify the classic 'double despatch' implementation and removes the `accept` method. """ from abc import ABC # ↓↓↓ LIBRARY CODE ↓↓↓ # taken from https://tavianator.com/the-visitor-pattern-in-python/ # Stores the actual visitor methods ...
2be25fff1e9334cc9c3d0cd2512c3ef43ea01b9a
technolingo/design_patterns
/Builder/pretty.py
1,794
3.609375
4
class Person: def __init__(self): self.company = None self.title = None self.income = None self.address = None self.postcode = None self.city = None def __repr__(self): return f'{self.__class__.__name__}(company={self.company}, ' \ f'title={s...
3b5fb53c3fd06a00c8259b43c87a384ede87bd87
technolingo/design_patterns
/proxy/protection.py
738
3.8125
4
class Car: def __init__(self, driver): self.driver = driver def drive(self): print(f'The car is being driven by {self.driver.name}.') class CarProxy: def __init__(self, driver): self.driver = driver self._car = Car(driver) def drive(self): if self.driver.age...
aff13f50a367e276114db102ec95222bdd7779cd
technolingo/design_patterns
/observer/event.py
943
3.578125
4
class Event(list): """ A composite event type that holds an array of observers as well as events. """ def __call__(self, *args, **kwargs): for item in self: item(*args, **kwargs) class Patient: """ An observable class that represents patients who generate medical events. ...
4882d2620859f0be5d720a6db1c6bab5ff0a5c9f
ziyun-li/Algorithms
/Bit_Manipulation_Recursive.py
642
3.53125
4
# Given a exponentially large number, n, find the most efficient method reach 1, given that only 3 operations can be performed: # 1) Add one # 2) Remove one # 3) Divide the entire group by 2 solution_list = {1:0,} #memoize n as key, number of solution as value def solution_recursive(n): n = long(n) if n in so...
b84bfba0be7dd5bc68d805f424a618c2e39d3cf7
RajGohire/Minesweeper-Python
/GUI/Minesweeper.py
7,178
3.53125
4
from random import randrange from tkinter import messagebox from tkinter import * from time import time window = None firstClick = True size = 0 numMines = 0 flagged = 0 defused = 0 btns = [] mines = [] board = [] move = "" def format_time(elap): hours = int(elap / 3600) minutes = int(elap / 60 - hours * 60.0...
003bbc22a25876e6b83c5d1092da7a189db37d79
renzyndrome/kaizend
/session-3/products_csv_parser.py
729
3.65625
4
import csv import argparse parser = argparse.ArgumentParser() parser.add_argument('filename', help='the file to read') args = parser.parse_args() output_filename = input("Enter filename of the CSV output file: ") with open(args.filename, "r") as file: reader = csv.DictReader(file) with open(output_filename,...
3faba4724a47a7a209bacfa6b102a78a477b1ed9
Taurin190/prime_numbers
/judge_prime_numbers.py
1,904
4.0625
4
# coding: utf-8 MAX_NUMBER = 1000 error_message = '有効な入力は{}までの正の整数です。\n'.format(MAX_NUMBER) def get_prime_numbers(max_num): tmp_prime_number_list = [2] for i in range(3, max_num): has_prime = False for prime_num in tmp_prime_number_list: if i % prime_num == 0: has_p...
8beabeafadd974e9290b1406611d4f6845f0d333
IsmaBH/Python-Pruebas
/Pygame-Course/Adivinanza/Adivinanza.py
839
3.921875
4
#Juego de adivinar un numero import random #Variables intentos = 0; #Saludo personalizado print("Hola, ¿como te llamas?") nombre = input() print("Muy bien, "+nombre+", he pensado un numero entre 1 y 100, A ver si lo adivinas") #Generamos un numero aleatorio numero = random.randint(1,100) #Inicio del bucle while intento...
665c705a19fcd4d233a25a16659e3692a3e2b65b
am2786/NYC-taxi-data-analysis
/coordinate-neighborhood mapping/coordinate_neighborhood_mapper.py
2,275
3.515625
4
import json from shapely.geometry import Point, Polygon import time import datetime import numpy as np import dask.dataframe as dd #This function takes the longitude and latitude of a pickup or dropoff location and maps it to a neighborhood (or state, county, etc.). #Take note that this function uses dask dataframes ...
a7ec934da1a6a5d8cde42438eef75458c7197501
avaala/NAOBot
/python/motion_cartesianArm1.py
1,518
3.546875
4
#-*- coding: iso-8859-15 -*- ''' Cartesian control: Arm trajectory example ''' import config import motion def main(): ''' Example showing a path of two positions Warning: Needs a PoseInit before executing Example available: path/to/aldebaran-sdk/modules/src/examples/ py...
b940ab9607b6b56189a9ba23ea1e8c4c15216e31
tigranl/Algorithms
/Python/search/binary_search.py
448
4.09375
4
"""Binary search algorithm Args: values: unsorted list target: value to find Returns: mid: index of value """ def search(values, target): values = sorted(values) min = 0 max = len(values) - 1 while min <= max: mid = (min + max) // 2 if target < values[mi...
b7257eeaca56f6b0b66e02b7b4b19bb69163a5a3
isp5708/Algorithm_python_bj_2cotae
/퀵정렬/main.py
767
3.890625
4
array= [5,7,9,0,3,1,6,2,4,8] def quick_sort(array,start,end): if start>= end: return pivot= start left= start+1 right= end #왼쪽이 작음 오른쪽이 큼 while left<=right: while array[left]<=array[pivot] and left<=end: left+=1 while array[right]>=array[pivot] and right>s...
2bc58f97455d2db4917721c561b7ab2c7c868276
isp5708/Algorithm_python_bj_2cotae
/곱하기 혹은 더하기/main.py
224
3.78125
4
data=input() result=int(data[0]) for i in range(1,len(data)): if data[i]==0 or result==0: result+= int(data[i]) else: result *=int(data[i]) print(result) ''' 입력값#1 02984 입력값#2 567 '''
e02442b00cf41f9d3dd1933bee6b63122225e3b6
johnehunt/python-datastructures
/trees/list_based_tree.py
1,441
4.1875
4
# Sample tree constructed using lists test_tree = ['a', # root ['b', # left subtree ['d', [], []], ['e', [], []]], ['c', # right subtree ['f', [], []], []] ] print('tree', test_tree) print('left subtree = ', test_tree[1])...
070be4d1e2e9ebcdbff2f227ec97da5a83c45282
johnehunt/python-datastructures
/abstractdatatypes/queue.py
1,055
4.15625
4
class BasicQueue: """ Queue ADT A queue is an ordered collection of items where the addition of new items happens at one end, called the “rear,” and the removal of existing items occurs at the other end, commonly called the “front.” As an element enters the queue it starts at the rear and ma...
ce138fa8e5f288a1a774522a725cc3b7d5f14fa8
benwardswards/ProjectEuler
/problem031coinSums.py
1,013
3.515625
4
"""Coin sums Problem 31 In the United Kingdom the currency is made up of pound (£) and pence (p). There are eight coins in general circulation: 1p, 2p, 5p, 10p, 20p, 50p, £1 (100p), and £2 (200p). It is possible to make £2 in the following way: 1×£1 + 1×50p + 2×20p + 1×5p + 1×2p + 3×1p How many different ways can £2...
ff29b9b245fed6ed009e5f34651455563ffc99f3
benwardswards/ProjectEuler
/problem016longpower.py
486
3.96875
4
import numpy as np import sys # 2**15 = 32768 and the sum of its digits is 3 + 2 + 7 + 6 + 8 = 26. # # What is the sum of the digits of the number 2**1000 print("2**1000 doesn't fit in a 64-bit int. Luckily python 3 int isn't fix precsion") longpower: int = 2 ** 1000 print("number of bytes of longpower is :", sys.ge...
5161067252616d40c63e6518597609ce26f9cb2b
benwardswards/ProjectEuler
/problem029Distinct_Powers.py
711
4.03125
4
"""Consider all integer combinations of ab for 2 ≤ a ≤ 5 and 2 ≤ b ≤ 5: 22=4, 23=8, 24=16, 25=32 32=9, 33=27, 34=81, 35=243 42=16, 43=64, 44=256, 45=1024 52=25, 53=125, 54=625, 55=3125 If they are then placed in numerical order, with any repeats removed, we get the following sequence of 15 distinct terms: 4, 8, 9, 1...
8d3196dc4cb5674eeede7dbfd2514d3075d6c5d5
benwardswards/ProjectEuler
/problem014Collatz.py
772
3.609375
4
# runs fast on pypy or with jit compared to cpython from numba import jit @jit(nopython=True) def collatzLength(num: int) -> int: length: int = 1 while num != 1: length += 1 if num % 2: num = 3 * num + 1 else: num = num // 2 return length assert collatzLe...
ad133e4c54b80abf48ff3028f7c00db37a622ec5
benwardswards/ProjectEuler
/problem038PanDigitMultiple.py
1,853
4.21875
4
"""Pandigital multiples Problem 38 Take the number 192 and multiply it by each of 1, 2, and 3: 192 × 1 = 192 192 × 2 = 384 192 × 3 = 576 By concatenating each product we get the 1 to 9 pandigital, 192384576. We will call 192384576 the concatenated product of 192 and (1,2,3) The same can be achieved by starting with...
03360430704d318487bf9a7e6c9b465705abd334
benwardswards/ProjectEuler
/problem047DistinctPrimeFactors.py
1,698
3.75
4
"""Distinct primes factors Problem 47 The first two consecutive numbers to have two distinct prime factors are: 14 = 2 × 7 15 = 3 × 5 The first three consecutive numbers to have three distinct prime factors are: 644 = 2² × 7 × 23 645 = 3 × 5 × 43 646 = 2 × 17 × 19. Find the first four consecutive integers to have ...
a6edc5258143f990a6f669e0454ea0895cd784ce
benwardswards/ProjectEuler
/problem042Coded_Triangle_Numbers.py
1,937
3.9375
4
"""Coded triangle numbers Show HTML problem content Problem 42 The nth term of the sequence of triangle numbers is given by, tn = ½n(n+1); so the first ten triangle numbers are: 1, 3, 6, 10, 15, 21, 28, 36, 45, 55, ... By converting each letter in a word to a number corresponding to its alphabetical position and...
5060816c484289bf55b348d174969e8122a130c7
Dzhonson64/FrameworkOfNeuralNetwok
/framework_NN/layers/Sequential.py
824
3.734375
4
# Слой для последовательно хранения других слоёв from layers.Layer import Layer class Sequential(Layer): def __init__(self, layers=None): super().__init__() if layers is None: layers = list() self.layers = layers def add(self, layer): self.layers.appe...
1362ec74ae0c72c10bf26c69151e8d6c8d64105c
hopesfall23/Fizzbuzz
/fizzbuzz.py
530
4.125
4
#William's Fizzbuzz program n = 100 #Hard coded upper line # "fizz" Divisible by 3 # "buzz" #Divisible by 5 #"Fizzbuzz" Divisible by 3 and 5 c = 0 #Current number, Will hold the value in our while loop and be printed for c in range(0,n): #Will run this loop from 0 to 100 then terminate if c <= n: ...
12a66687afc85a33d4e87328cf5b5394386582e1
ErmirioABonfim/Exercicos-Python
/Exercios Em Python/ex014.py
149
3.953125
4
tempC = float(input('Informe a temperatura')) tempF = float(tempC * (9/5))+32 print('A temperatura de {}°C corresponde a {}°F'.format(tempC,tempF))
7995cc9b3cad7130634c5eacd4e97926aef0723a
ErmirioABonfim/Exercicos-Python
/Exercios Em Python/ex30.py
118
3.875
4
num = int(input('Digite um número')) resultado = num % 2 if resultado == 0: print('Par') else: print('Impar')
2e320fca30f601e704d8bc623e81792fdce7f3c1
ErmirioABonfim/Exercicos-Python
/Exercios Em Python/ex074.py
413
3.703125
4
import random num = int (random.randint(0,9)) num2 = int (random.randint(0,9)) num3 = int (random.randint(0,9)) num4 = int (random.randint(0,9)) sorteado = (num, num2,num3,num4) print('Os números sorteados foram:{}'.format(sorteado)) print('Os números ordenados são: {}'.format(sorted(sorteado))) print('O maior núme...
5ce15745ef237429b5d72e0bbc8d9488b54da008
just-lana-l/module12
/task_9.py
3,349
3.625
4
print('Задача 9. Недоделка') # Вы пришли на работу в контору по разработке игр, # целевая аудитория которых - дети и их родители. # # У прошлого программиста было задание # сделать две игры в одном приложении, чтобы пользователь мог выбирать одну из них. # # Однако программист, на место которого вы пришл # и, перед ...
4d6a978ba0418250f5a79bada5a7cc648b219803
jasonmpittman/100-days-of-alife-code
/simple-flock.py
1,862
3.734375
4
#!/usr/bin/env python3 # Created on 05/07/2018 # @author: Jason M. Pittman # @license: MIT-license # Purpose: example of two agent flocking behavior # Explanation: import pygame import sys import random import math pygame.init() window_height = 800 window_width = 600 black = (0,0,0) white = (255,255,255) block_size ...
c87e215c6cb8da63201234316866aa4d84ffaba7
otmanesabir/HackerRank
/Language Proficiency/Python/string-validators.py
526
3.90625
4
if __name__ == '__main__': s = raw_input() alphanum = False alphabet = False digit = False lower = False upper = False for x in s: if x.isdigit(): digit = True alphanum = True elif x.isalpha(): alphanum = True alphabet = True ...
b78c84d8d49a4a92fa4ec3324cd7298b93ce58a0
jcdaly97/cs-module-project-algorithms
/test.py
559
4.09375
4
def list_multiples(num, length): new_arr = [] for i in range(1, length + 1): new_arr.append(i*num) return new_arr print(list_multiples(12,10)) def majority(arr, needed = None): if not needed: needed = len(arr)/2 x = arr[0] if arr.count(x) > needed: return x elif len...
78abee84d176a75dd342429734961fda7c42d6b9
gbrau/maiwen
/orchestration/graph.py
6,657
4.3125
4
class Graph(object): def __init__(self, graph_dict={}): """ initializes a graph object """ self.__graph_dict = graph_dict def vertices(self): """ returns the vertices of a graph """ return list(self.__graph_dict.keys()) def edges(self): """ returns the edges of a g...
8d4d8b4471bfddb9a88a4351541ece7bf98fa30a
PApostol/WasItLeaked
/check_password.py
1,617
3.6875
4
""" An API call is made with the first 5 characters of SHA1 of your password(s), which returns a list of matches and their occurrences. The full password hash is then checked locally for matches. More occurrences means worse password. """ import hashlib import sys from typing import List, Tuple import reques...
2f2338fd2b131c7240a206ff08683b6727411832
GlennShooter/Colour-Sorting-algorithms-
/Assignment_rand_serch.py
4,700
4
4
""" A random search algorithm, enter the amount of random searches you would like the algorithm to do, it will then perform the amount of random serches entered nd return the best solution found """ # Import required libraries import matplotlib.pyplot as plt import numpy as np from random import randint from ra...
3aa80df007d1300fb02a3830d878d273c36cfe2a
olgakirova/lab_python
/lesson4/lesson4.exs4.1.py
76
3.671875
4
import math x = int(input("x=")) print ('{:.{x}f}'.format(math.pi,x = x))
51d89acafdd9cac787a525f620612f6c4ed66514
olgakirova/lab_python
/lesson5/less 5.1.py
384
3.671875
4
import random s = ["самовар","весна", "лето"] a = random.randint(0, len(s)-1) b = random.randint(0, len(s[a]) - 1) print (s[a][0:b] + "?" + s[a][b+1: ]) x = input ("Введите букву: ") def check (x): if x == s[a][b]: return "Победа" else: return "Увы! Попробуйте в другой раз!" print (che...
b28f32582cd07f2b6978b70afdcefb7027ed9e58
olgakirova/lab_python
/lesson6/lesson6.7.py
108
3.921875
4
sum = 0 while True: text = input() if text == "Stop": break sum +=int(text) print(sum)
6bb6d3cb4fe269a0c06786d9bfef8062f71a714b
AkashPatel18/Basic
/video1/Q8.py
144
3.5
4
''' def fac(n): if n ==0: return 1 return n*fac(n-1) print(fac(5)) ''' n= 6 f=1 t=1 while(t<n): f=f*n n=n-1 print(f)
f5e58b47dc75761eabee0fa1546a76b548ca9f0d
AkashPatel18/Basic
/video 5.2/Q3.py
196
3.625
4
#armstrong num n = 1634 order=len(str(n)) sum=0 temp = n while (temp>0): ld=temp%10 sum = sum+ld**order temp =temp//10 if n==sum: print("armstrong") else: print("not")
2f9f4aa028cf5c415973b036110eeea7e3661d22
mealsOrder/Python_Tetris
/test.py
4,973
3.796875
4
""" tittle : Practice for python with Tetris author : Jang Yun Jae last modified: 2020.07.02 """ import wx import random ### 클래스 선언 부분 ### ##테트리스 클래스 생성 class Tetris(wx.Frame): ##생성자 def __init__(self,parent): wx.Frame.__init__(self,parent,size=(180, 380), ## 창크기를 180x380으로 설정 및 각종 설정 ...
4dc90406b087c3db9d51d385d5c82ad48d7702cf
ic-labs/django-icekit
/icekit/utils/attributes.py
765
3.53125
4
def resolve(obj, attr, fallback=None): """ Resolves obj.attr to a value, calling it as a function if necessary. :param obj: :param attr: a string name of a property or function :param fallback: the value to return if none can be resolved :return: the result of the attribute, or fallback if objec...
cfa3ef75cb859421b77b3468ca9d99e02f42ab35
mario2100/Spring_All
/try/py_try/6_closure.py
1,083
4
4
# 闭包 也是函数 函数嵌套 # # def func(): # a = 1 # b = 2 # print(a + b) # 闭包:外部函数变量被内部函数引用 # def sum(a): # def add(b): # return a + b # # return add # add 函数引用 # add() 函数调用 # num1 = func() # print(type(num1)) # # num2 = sum(2) # print(type(num2)) # print(num2(4)) # 实现计数器 # 外部函数 # def counter(...
ab195e73f4b45c7a516a2b950c9da47750f86e52
loganathan6/test
/alpha_no.py
126
3.84375
4
from string import ascii_lowercase if raw_input().lower() in list(ascii_lowercase): print "Alphabet" else: print "No"
5329f12c5967bdfa924732724a441a6f49078b26
elxiseulo/youtube_lahacks
/connect.py
1,002
3.515625
4
import json import urllib.request import urllib.parse from pprint import pprint API_KEY = 'AIzaSyB2nClBJR9aP5clL6c15uIkPhJACccZmOM' URL = 'https://www.googleapis.com/youtube/v3/videos?id=' TEST_URL = 'http://gdata.youtube.com/feeds/api/videos/91lYBbBkftA/comments?orderby=published&alt=json&max-results=30&start-index=...
9963f58af892ed7ceb5bd02f68f6803325446464
akarshsomani/social-network
/BFS.py
577
3.890625
4
#BFS in networkx network import networkx as nx def BFS(G,start): neigh=[] queue=[] queue.append(s) record=[] record.append(s) while(queue != []): current=queue.pop(0) #print(current) neigh=list(G.neighbors(current)) neigh.sort() #print(neigh) for...
d8585e38ce24e01056de2bfb9f663f6cd537d753
perykarion/kawa1
/test.py
2,268
3.75
4
import unittest import numbers_with_prime_divisors class IsNaturalTestCase(unittest.TestCase): def test_is_natural_negative(self): test_values = [-5, -2.5, 0, 2.5, "a", (4, 6)] for number in test_values: self.assertFalse(numbers_with_prime_divisors.is_natural(number)), "Number at test i...