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 |
|---|---|---|---|---|---|---|
83b2e3222dc30fdfc6ce8930284cc7cd40ac2ced | Petrochenko-VA/Pashalka_N13tech | /pashalka.py | 1,475 | 3.9375 | 4 | import random
import sys
import time
def main():
playGame = (input(`Would you like to play a game? (Y/N) `))
if playGame == (`Y`) or playGame == (`y`):
print (`You answered Y for Yes`)
print()
time.sleep(1.5) # pause for a second and a half
print(`Welcom to the Number Guess... |
ae77ecedca6ffaf87993ae65db4a8adaf59e6f59 | chu-he/rosalind | /062_CTBL/ctbl.py | 6,171 | 3.796875 | 4 | class Node():
def __init__(self, parent=None):
self.name = ''
self.parent = parent
self.children = []
self.weight = 1
self.splits = ''
def __str__(self, indentation=''):
s = f'{indentation}{self.name if self.name else "(No name)"} {self.weight} {self.sp... |
78897ad561e4ca69e754673074ec28a538a74688 | chu-he/rosalind | /013_enumerating_gene_orders/enu.py | 851 | 3.578125 | 4 | def GetAllCombinations(values, prefix = ''):
if values == []:
return [prefix]
combinations = []
for v in values:
newList = list(values)
newList.remove(v)
if prefix == '':
newPrefix = str(v)
else:
newPrefix = prefix + ' ' ... |
a35eea3ee20aed2f88d8924369cd0b44c63da0f8 | chu-he/rosalind | /036_TREE/036_TREE.py | 1,386 | 3.546875 | 4 | file = open('dataset.txt', 'r')
data = file.read().split('\n')
file.close()
n = int(data[0])
adj_list = [[int(k) for k in x.split(' ')] for x in data[1:]]
def debugPrint(adj, group):
for i in range(len(adj)):
print '%3d %8s %s' % (i, adj[i], group[i])
# Create an adjacency list such that for each i,
# A... |
cb8de7a8af206db4ba62a665ea078cd1f99f2a68 | chu-he/rosalind | /066_ITWV/itwv.py | 2,098 | 3.625 | 4 | def can_interweave_helper(s, a, b):
#print(f' can_interweave_helper {s} : {a} x {b}')
# Interweave successful!
if a == '' and b == '': return True
first_chars = []
if a: first_chars.append(a[0])
if b: first_chars.append(b[0])
if s[0] in first_chars:
if a and b and a[0] == ... |
55208d543cd051b3b5e6d6068f73adcb890a9543 | chu-he/rosalind | /030_TRAN/030_TRAN.py | 1,003 | 3.53125 | 4 | def isTransition(a, b):
if (a == 'A' and b == 'G') or \
(a == 'G' and b == 'A') or \
(a == 'C' and b == 'T') or \
(a == 'T' and b == 'C'):
return True
return False
def getTransRatio(s1, s2):
transitions = 0.0
transversions = 0.0
for i in range(len(s1)):
a = s1... |
bf4c95c5bab39db7fcc3257139256d25ca95740d | chu-he/rosalind | /010_finding_shared_motif/find.py | 1,442 | 3.53125 | 4 | import string
nucleotides = ['A', 'C', 'G', 'T']
# in : data - Raw data containing FASTA format
# out: dict - Dictionary containing mapping from name -> sequence
def ReadFASTA(data):
data = data.split('\n')
dict = {}
for i in range(len(data)):
if data[i][0] == '>':
strname = data[i][1... |
48dc0780bab77cc11f2150a20b8b9bb674cab00e | chu-he/rosalind | /057_REAR/057_REAR_old.py | 2,680 | 3.6875 | 4 | def swap(seq, start, end):
newSeq = []
for i in range(0, start):
newSeq.append(seq[i])
for i in range(end, start-1, -1):
newSeq.append(seq[i])
for i in range(end+1, len(seq)):
newSeq.append(seq[i])
print('Swap {0} from {1} to {2} --> {3}'.format(seq, start, end, newSeq))
... |
3d1cbf561e511076d3b90c1a6292941bbf2fe28e | kdetoudom/CS230 | /In-Class Assignments/CodingwithControlStructures.py | 2,670 | 3.78125 | 4 | """
Class: CS230--Section 1
Name: Konnie Detoudom
Description: Coding with Strings
By submitting this assignment, I certify that:
I have completed this programming assignment independently.
I have not copied the code from a student or any source.
I have not shared my code with any student.
"""
# ------------... |
d011c2000c67d01d906f8755ca1b59f13a001ea7 | kdetoudom/CS230 | /In-Class Assignments/guessgame2.py | 719 | 3.9375 | 4 | """
guessing game uses while loop
"""
import math
import random
print("Guessing Game.")
smaller = int(input("Enter the smaller number: "))
larger = int(input("Enter the larger number: "))
myNumber = random.randint(smaller, larger)
count = 0
MAXGUESSES = 5
game_over = False
while not game_over:
us... |
cbf461658ab1d429e13613448d9604732bfb5b85 | soowork/python-programming | /games/hangman.py | 557 | 3.921875 | 4 | import random
words = ['cat','superficial','organization','car','willow']
guess_limit = 3
guesses = 0
object_word = words[random.randint(0,(len(words)-1))]
# shows this works
print(object_word)
dashes = ''
for i in range(0,len(object_word)):
dashes += '-'
print(dashes)
'''
reversed_str = ""
position = len(i... |
f35100ee52b2640c87957cfdd69cdfa35f6be00a | Quantor/Robolab | /group-146/robolab-deploy/ip_check.py | 729 | 4.0625 | 4 | import re
def ip_check():
"""
Asks to enter an IP address and checks its validity
"""
valid_format = re.compile(r'(\d{1,3}\.){3}\d{1,3}$')
final = ''
while True:
raw = input('Please enter the IP address: ')
if valid_format.match(raw) is not None:
sequenc... |
0d695edacdd138121fb95ecb26717a361f8e9248 | ben15021999/CodeRank_November_2020_ThangND47 | /kingdom-connectivity.py | 1,811 | 3.53125 | 4 | #!/bin/python3
import math
import os
import random
import re
import sys
#
# Complete the 'countPaths' function below.
#
# The function accepts following parameters:
# 1. INTEGER n
# 2. 2D_INTEGER_ARRAY edges
#
mod = int(1e9)
visited = [False] * (10000 + 1)
f = [0] * (10000 + 1)
cur_path = []
cycle = set()
path = ... |
5bbc23b42dbd94d05bdd65b36560a64ff0d801e9 | DChang87/Competitive-Programming-Solutions | /ccc12s5.py | 2,309 | 4.0625 | 4 | """
You are a mouse that lives in a cage in a large laboratory. The laboratory is composed of one
rectangular grid of square cages, with a total of R rows and C columns of cages.
To get your exercise, the laboratory owners allow you to move between cages. You can move between cages
either by moving right between two ... |
2579647164dc2a589d1bc112d3ea70aa0216db99 | novas-meng/python-algo | /quicksort.py | 1,427 | 3.65625 | 4 | import numpy as np
'''
快排算法,思想是分治的思想
array=[2,2,34,34,2,6,45,13,68,3,21,9]
举例 首先对于array,取数组的最后一个元素9作为flag,
将数组小于等于9的都放在9的左侧,大于9的放在右侧,如partition函数
其中p表示数组起点,q表示数组最后一个元素,i表示指针,这个指针左侧的元素都是小于等于flag的元素
然后返回这个指针,将数据切分成[:i-1] array[i] array[i+1:] 这样的三部分,然后在递归调用partition,
直到整体都有序
'''
def partition(array,p,q):
i=p-1
x=array... |
3f3c98e63fb738694fda360b622940a063866db2 | leonidg/athena-utils | /mtree/mquery | 851 | 3.515625 | 4 | #!/usr/bin/python
# Given a Moira list and a member, prints whether or not that member
# is on the list or a sublist of that list (or a subsublist, etc.)
import sys
import mtree
def main(list_name, member):
tree = mtree.MoiraTree(list_name).tree[list_name]
def walk(curr_tree):
for element in curr_tr... |
710aebc04b24921c716e0c3ff0b30574773c9c68 | kalu661/desafio | /desafio_1.py | 1,241 | 4.1875 | 4 | print('>-----------------------------------------<')
#Definicion de Variables
palabra = input('Ingrese una palabra ');
palabra1 = int(len(palabra));
palabra2 = int;
palabra3 = int;
es_multiplo = int;
result = int;
a_string = palabra
# Conversion de string a ASCII
ASCII_values = []
for character in a_string:
ASCII_... |
22a3f8bc995da3280c79c290c4fda731f57aab6c | vamsireddy22/FLM-Python | /Principle.py | 1,507 | 4.09375 | 4 | class Person:
# Self points to current object
def __init__(self, name, age, address):
print("I am in person constructor")
self.name = name
self.age = age
self.address = address
def PrintPersonDetails(self):
print("I am in Person class Printing")
... |
cdcfcbf6f7bd90a64676c8f2d784833bbedc36be | vamsireddy22/FLM-Python | /overridingInheritance.py | 457 | 3.6875 | 4 | class Bird:
def Intro(self):
print("I am Bird")
def fly(self):
print("Every bird can fly")
class parrot(Bird):
def fly(self):
print("A parrot can fly upto some hieght")
class Eagle(Bird):
def fly(self):
print("I am eagle I can fly morethan anyother bird")
... |
91da2d88b8fc7bead5b2dc26f7e2e904906d6c80 | tadgallagher1/python-pong | /pong.py | 4,683 | 4.0625 | 4 | import turtle
# create a screen
wn = turtle.Screen()
# give it a title
wn.title("Pong by Tim")
# change the background color
wn.bgcolor("blue")
#change size
wn.setup(width=800, height=600)
#stop window from updating
wn.tracer(0)
# score variables
score_a = 0
score_b = 0
# paddle a
paddle_a = tur... |
7ae51f22b5802e4fae2263c76bdc92fade4dfdf8 | Swapnasheel/Study | /DS/Queue.py | 641 | 3.8125 | 4 | # FIFO -- First in first out
class Queue():
def __init__(self):
self.queue = []
def isEmpty(self):
return self.queue == []
def enqueue(self, data):
self.queue.append(data)
def dequeue(self):
data = self.queue[0]
del self.queue[0]
return data
def sizeOfQueue(self):
return len(self.queue)
def ... |
69627659fbd2c7519428f11c21d49aa7db31fb28 | kkpolak/msc | /Scrabble/creativity/scrabble-statistics/evaluation/best_characters_evaluator.py | 688 | 3.703125 | 4 | from validation.word_validator import WordValidator
class BestCharactersEvaluator(object):
def __init__(self):
self.best_characters = {}
self.word_validator = WordValidator()
def evaluate_best_characters(self, word):
if not self.word_validator.is_word_valid(word):
return
... |
19b6efd62d74c7e69709d2c6f7f28c282252f37b | Foxboron/Project-Euler-Solutions | /Solutions/5.py | 444 | 3.671875 | 4 | #!/usr/bin/env python
def main():
num = 0
answer = 0
ints = [i for i in range(1, 21)]
while True:
for i in ints:
if num % i == 0:
answer = num
else:
answer = 0
break
if answer == 0:
num += 1
... |
42390b14e79234eac60fde7a5511fe5add7cc36a | Foxboron/Project-Euler-Solutions | /Solutions/9.py | 347 | 3.59375 | 4 | #!/usr/bin/env python
from math import sqrt
def main():
n = 1000
for a in range(1, 500):
for b in range(1, 500):
c = pow(a,2) + pow(b,2)
c = sqrt(c)
if pow(a,2) + pow(b,2) == pow(c,2) and a + b + c == n:
print a*b*c
break
if __name__... |
1c04ac0476b566bd98953d1c2f667148ef387e77 | CmdBianchi/UNINTER.L01.E03 | /main.py | 822 | 3.734375 | 4 | ####################################################################################
#--------------- > Execício 03
print('---' * 20)
import random
donor = []
def DonorRecord(nome: str, doacao: float):
donor.extend(((nome + ' ') * int(doacao // 10)).split())
return
def PrizeDraw():
random.shuffle(donor)
... |
c813a4545b1133003bb019ea65b2f33757f28c32 | ZachAH/PYTHON1 | /first_program.py | 3,758 | 4.09375 | 4 | # defining function taking in a phrase assigining variable then capitalizing the first letter of the phrase making capitalized phrase
# if phrase starts with interrogatives then it will return with the first letter capitalized other wise it will return with capitalized without question mark
# if the user types in /e... |
4c46352e04d94a6e4e0a94c841a039fdf5927e0a | Joshua0128/JudgeGirl-Coding-GYM | /一轉示範/進階登入系統 python 示範/Main.py | 1,077 | 3.859375 | 4 | from LoginSystem import *
import User
SIGN_IN, SIGN_UP, LEAVE = (1, 2, 3)
loginSystem = LoginSystem()
def signUp():
name = input("Input name: ")
account = input("Input account: ")
password = input("Input password: ")
user = loginSystem.signUp(account, password, name)
print (str(user))
def signIn(... |
a9ff9122c234551358523a91d1ed685aa64280b7 | LaserBlaster/Blackjack | /main.py | 9,567 | 3.703125 | 4 | from basic_deck import deck
import random
starting_deck = deck()
print("Welcome to the Blackjack card counting app!")
num_decks = int(input("How many decks would you like to use? Enter a number between 1 and 7.\n"))
new_decks = []
money = 1000
count = 0
def shuffle_decks(num_decks):
for i in range(num_decks):
... |
b92eddd1957a3a1be6c6cc72e25adfe89e587b17 | MrBlackred/python | /section10/file_read.py | 490 | 3.96875 | 4 | filename = 'pi_digits.txt'
# with open(filename) as file_object:
# # contents = file_object.read()
# # print(contents)
# for line in file_object:
# print(line)
with open(filename) as file_object:
lines = file_object.readlines()
pi_string = ''
for line in lines:
pi_string += line.strip()
... |
fd8fbbc10b3cf4a4f960a7234229be4d2bd6aa17 | MrBlackred/python | /section3.py | 481 | 4.28125 | 4 | # list
'''
name = ['ame', 'nts', 'fb', 'XQ', 'y']
print(name)
print(name[0].title())
print(name[-1]) # end element
## 3-2 append change del insert
name[0] = 'kaka' #change
name.append('hel')
name.insert(0, 'lx')
name2 = name.pop()
name3 = name.pop(2)
name.remove('kaka')
del name[1]
print(name)
print(name2)
print(... |
0995e5f45cb93b2ca716e858118f514df14bad70 | adomiter/CAAP-CS | /assignment_01 (hw1)/hello.py | 489 | 4.0625 | 4 | #prints hello to screen
def hello_world ():
print("Hello!")
name=input("What is your name?")
color=input("What is your favorite color?")
ice_cream=input("What is your favorite ice-cream flavor?")
#print("Your name is",name,"and your favorite color is",color,". Also, your favorite ice-cream fl... |
b9face6f42591bc28c1941896fdf9d56df9f131b | adomiter/CAAP-CS | /Lab2/game/leaderboard.py | 985 | 3.984375 | 4 | # imports the score class to be used in the leaderboard.
from scores import Score
# leaderboard keeps track of top ten highest ranking players
class Leaderboard(object):
size = 10
board = []
def __init__(self):
for i in range(self.size):
self.board.append(Score("player", i))
# prints the leaderb... |
889fe072686f7c2376300452cea08d619d326540 | adomiter/CAAP-CS | /assignment_2/practice10.py | 548 | 4.1875 | 4 | #modify the above program
def Easter(year):
a = year%19
b = year%4
c = year%7
d = (19a + 24)%30
e = (2b+4c+6d+5)%7
exceptions = {"1954",
"1981",
"2049",
"2079"}
if year == exceptions;
print("The date for Easter in", year,"is April",... |
b646f7450855986272775d37c91eb6644ef1d55e | adomiter/CAAP-CS | /assignment_2/practice16.py | 949 | 3.5 | 4 | #was not able to download graphics.py
from graphics import *
def target():
win = GraphWin()
aCircle= Circle(Point(0,0), 100)
aCircle.setFill("white")
aCircle2= Circle(Point(0,0), 80)
aCircle2.setFill("black")
aCircle3= Circle(Point(0,0), 60)
aCircle3.setFill("blue")
aCircle4= Circle(Poi... |
2111d6fda9adc76a528dd5782c92931b486fba42 | adomiter/CAAP-CS | /Practices_Ch8/quiz_2.py | 327 | 4.15625 | 4 | def word_length(sentence):
sentence_array=sentence.split(" ")
num_words=len(sentence_array)
sum=0
for i in sentence_array:
length_word=len(i)
sum += length_word
return(sum/num_words)
def main():
user_sentence=input("What is the sentence?")
print(word_length(user_sentence))
m... |
c3dd073002883d9c686f7a908aa402a6ada0b1cc | lucashdoa/python-algorithms-and-data-structures | /selection_sort.py | 550 | 3.890625 | 4 | unsorted_list = [9, 7, 5, 8, 2, 6, 3, 4, 0, 1]
def selection_sort(list):
sorted_list = []
min_index = 0
while list:
current_min = list[0]
min_index = 0
if len(list) > 1:
last_index = len(list)
for index in range(1, last_index):
if list[index]... |
9192c3aeb7265b5d99592b5a4306bcbabaebdf5f | wangfmD/pypro | /02_check/02_class/decorator/d6.py | 542 | 3.5625 | 4 | # coding=utf-8
def deco(myfunc):
def _deco(*args, **kwargs):
print "before %s() called." % myfunc.__name__
ret = myfunc(*args, **kwargs)
print "after %s() called. result: %s" % (myfunc.__name__, ret)
return ret
return _deco
@deco
def myfunc(a, b):
print "myfunc(%s,%s) cal... |
d0e4717400314688a3e89a936df17ec18dbafb14 | LuLStackCoder/My-Python-Library | /sorts/QuickSort.py | 1,064 | 3.890625 | 4 | def quick_sort(iterable, fn=lambda x,y: x<y, inplace=True):
'''
Quick sort function
Parameters:
iterable (object): Iterable object
fn (function): Comparsion function
inplace (bool): Sort inplace or make copy
Returns:
object: Return sorted iterable object
'... |
47a327e60b1c67db5904c5f32c58c34d9f208376 | dmitchelldm74/sqllib | /sqllib/__init__.py | 1,879 | 3.671875 | 4 | import sqlite3
class SQL():
def __init__(self, filename):
self.conn = sqlite3.connect(filename)
self.c = self.conn.cursor()
# tname == tablename
def __del__(self):
self.conn.close()
def insert(self, tname, values, *args):
values = ','.join(values)
if len(args)... |
d828e89a69035304280d9da79061e729314ba7d3 | calumptrck/hr-algorithms | /kangaroo.py | 309 | 3.765625 | 4 | #!/bin/python3
import sys
x1,v1,x2,v2 = input().strip().split(' ')
x1,v1,x2,v2 = [int(x1),int(v1),int(x2),int(v2)]
distance = abs(x1-x2)
velocity = abs(v1-v2)
if (v1==v2):
print('NO')
else:
meet = float((x2-x1) / (v1-v2))
if (meet<1 or meet%1!=0):
print('NO')
else:
print('YES') |
c8a092a5ef6048a1b7de4b5b8bba925e807da787 | A-fish-in-Lake-Baikal/python-exercise | /110Questions/58.py | 237 | 4.125 | 4 | # -*- coding: utf-8 -*-
#使用pop和del删除字典中的”name”字段,dic={“name”:”zs”,”age”:18}
dic1 = {"name":"zs","age":18}
dic2 = {"name":"zs","age":18}
dic1.pop("name")
print(dic1)
del dic2["name"]
print(dic2)
|
341872752fcf0e62a40718d7dbbc5bedde9d0f71 | A-fish-in-Lake-Baikal/python-exercise | /other/uniform.py | 207 | 3.59375 | 4 | import random
random.seed()
n=eval(input("请输入一个整数:"))
sum=0
for i in range(n):
f1 = random.uniform(1,100)
sum+=f1
print(f1)
print("the average is:{},sum is {}".format(sum/n,sum))
|
e8d72dfd4f93e260eef894427dd43d7f4cd164e7 | A-fish-in-Lake-Baikal/python-exercise | /erji/汉字or符号统计.py | 534 | 3.5625 | 4 | # -*- coding: utf-8 -*-
# @Author : 马维畅
# @Time : 2020/1/22 10:29
# @File : 汉字or符号统计.py
# 以论语中一句话作为字符串变量 s,补充程序,分别输出字符串 s 中汉字和标点符号的个数。
s = "学而时习之,不亦说乎?有朋自远方来,不亦乐乎?人不知而不愠,不亦君子乎?"
m = 0 # 汉字个数
n = 0 # 符号字数
for l in s:
if '\u4e00' <= l <= '\u9fff':
m += 1
else:
n += 1
print("汉字个数:{},符号个... |
b0e75c30fefdb7de993411e87b254b8bfff9cdc6 | adslyw/python-100-days | /day-5/d5_3.py | 117 | 3.546875 | 4 | def add(*args):
total = 0
for val in args:
total += val
return total
print(add(1, 2, 3, 4, 5))
|
074b5c41d84ebf7a30362101ae6a0c404840b70f | spoorthyvv/Python_workshop | /day2/p5.py | 204 | 4.1875 | 4 | import numpy as np
List=[]
num=int(input("Enter the number of elements"))
print('Enter the elements: ')
for i in range(num):
List.append(int(input()))
print('Average Of The Numbers Is: ',np.mean(List))
|
7d3bf84cd1c9b19bd87c2cd719f846e9839ca71b | spoorthyvv/Python_workshop | /day2/s4.py | 173 | 3.765625 | 4 | n=int(input("Enter no of records"))
d={}
for i in range(1,n+1):
name= input("Enter name %d"%(i))
mark=int(input("Enter mark %d"%(i)))
d[name]=mark
print (d)
|
f2f0f64d3369d7a415e04818fd3fd6ca17970c7e | spoorthyvv/Python_workshop | /day2/e10.py | 235 | 4.0625 | 4 |
#Instead of forementioned 12 lines program, the equivalent 4 lines !
#Pythonic program is here ....
x=0
l=[int(input(x)) for _ in range(int(input("Enter how many elements")))]
l.sort()
print("Second largest element is :",l[-2])
|
57bcf5cd33907e850f05e7f5f10c45c5020960ba | spoorthyvv/Python_workshop | /day1/offline_exercises_session1_day1/program5.py | 480 | 4.1875 | 4 | num1=int(input("Enter the first number: "))
num2=int(input("Enter the second number: "))
num3=int(input("Enter the Third number: "))
num4=int(input("Enter the fourth number"))
def find_Biggest():
if(num1>=num2) and (num1>=num2):
greatest=num1
elif(num2>=num1) and (num2>=num3):
greatest=... |
f486aa918c06369d6524b769becbdc9f57a7782e | shivam0071/DSnAlgoStuff | /DataStructuresAlgorithm/Day1-Complexity/Day1-Complexity.py | 422 | 3.84375 | 4 | import time
def sum_of_n_2(n):
start = time.time()
the_sum = 0
for i in range(1, n+1):
the_sum = the_sum + i
end = time.time()
return the_sum,end-start
# (a,b) = sum_of_n_2(1000000000)
# #print(a)
# print(b)
#for i in range(5):
#print("Sum is %d required %10.7f seconds" % sum_of_n_2(100... |
8652b1476973dac359ca0ae17cd72360d556503c | masakiaota/kyoupuro | /practice/C_ABC/abc134_c.py | 505 | 3.578125 | 4 | # https://atcoder.jp/contests/abc134/tasks/abc134_c
N = int(input())
A = []
max1 = 0
max2 = 0
for _ in range(N):
a = int(input())
# if max1 <= a:
# max2 = max1
# max1 = a
# elif max2 <= a:
# max2 = a
A.append(a)
# for a in A:
# print(max1 if a != max1 else max2)
# でも制約から... |
b58f5aa191ac06dfc697473783470cceec39b6b6 | masakiaota/kyoupuro | /practice/ants_book/114_carmichael_numbers.py | 822 | 4.03125 | 4 | # まず素数じゃないことを確かめてから
# 素直にxを[2,n)まで変化させて成り立つことを確かれば良い
# オリジナルの問題ではもっと高速化させないとTLEになるっぽい(そもそもpowを使わない)けど今はpowの練習なので
def is_prime(x: int):
# 高速素数判定
if x == 1:
return False
if x % 2 == 0: # 定数倍高速化
return x == 2
for i in range(3, int(x**0.5) + 1, 2):
if x % i == 0:
retu... |
e68f25e295ae2c48676cd152cd37c5b8651497bc | masakiaota/kyoupuro | /contests/ABC125/C_correct.py | 1,429 | 3.59375 | 4 | # 入力が10**5とかになったときに100ms程度早い
import sys
read = sys.stdin.readline
def read_ints():
return list(map(int, read().split()))
def read_a_int():
return int(read())
def read_matrix(H):
'''
H is number of rows
'''
return [list(map(int, read().split())) for _ in range(H)]
def read_map(H):
'''... |
11a32ec4905ad102678e7957ca6f8c36e3c7a592 | masakiaota/kyoupuro | /practice/algorithm_datastructure_for_programming_contest/318_DSL_1_A.py | 2,319 | 3.671875 | 4 | # https://onlinejudge.u-aizu.ac.jp/courses/library/3/DSL/all/DSL_1_A
# AtCoderの解説がわかりやすい https://youtu.be/zV3Ul2pA2Fw?t=1425
# この解説を見た上で本を読むとより理解が深まる
# 本とはやや違う実装だがこちらのほうがスマート(だとおもってる)
# あとで自分の解説を書き直し
class UnionFind:
def __init__(self, N):
self.N = N # ノード数
# 親ノードをしめす。負は自身が親ということ。
self.p... |
e15922bdfaeaf56974251e908598add34e02bdea | masakiaota/kyoupuro | /practice/B_ARC/arc020_2/arc020_2.py | 1,964 | 3.59375 | 4 | # https://atcoder.jp/contests/arc020/tasks/arc020_2
# 一行飛ばしでカウントしておけば良い
# もし同色だったら次のいろを使うことにする
import sys
sys.setrecursionlimit(1 << 25)
read = sys.stdin.readline
ra = range
enu = enumerate
def mina(*argv, sub=1): return list(map(lambda x: x - sub, argv))
# 受け渡されたすべての要素からsubだけ引く.リストを*をつけて展開しておくこと
def read_a_int(): ... |
2e6214f6bd558290707cc1d680d13f579cbdc5ec | masakiaota/kyoupuro | /practice/B_ARC/arc023_2/arc023_2.py | 932 | 3.640625 | 4 | # https://atcoder.jp/contests/arc023/tasks/arc023_2
# ちょうどD回で行ける範囲と偶数奇数で分ける
import sys
sys.setrecursionlimit(1 << 25)
read = sys.stdin.readline
ra = range
enu = enumerate
def exit(*argv, **kwarg):
print(*argv, **kwarg)
sys.exit()
def mina(*argv, sub=1): return list(map(lambda x: x - sub, argv))
# 受け渡されたすべての... |
a61b317bba9674bf31d8783224b2bee19b106cef | masakiaota/kyoupuro | /practice/C_ABC/abc004_3/abc004_3.py | 314 | 3.53125 | 4 | # 愚直に操作をじっそうするだけじゃないんか?→Nの制約がめっちゃデカかったわ
# 操作は5*6回ごとにループする
N = int(input()) % 30
cards = list(range(1, 7))
for i in range(N):
a = i % 5
b = a + 1
cards[a], cards[b] = cards[b], cards[a]
print(*cards, sep='')
|
dadae2221ed747383a261c3e1bfd0766367818fc | masakiaota/kyoupuro | /contests/AGC034/A.py | 2,082 | 3.78125 | 4 | # 入力が10**5とかになったときに100ms程度早い
import sys
read = sys.stdin.readline
def read_ints():
return list(map(int, read().split()))
def read_a_int():
return int(read())
def read_matrix(H):
'''
H is number of rows
'''
return [list(map(int, read().split())) for _ in range(H)]
def read_map(H):
'''... |
7872ed87039cb65df47715fa61af4794063cd720 | masakiaota/kyoupuro | /practice/brown_diff/digitalarts_1/digitalarts_1.py | 642 | 3.53125 | 4 | # https://atcoder.jp/contests/digitalarts2012/tasks/digitalarts_1
# まあ愚直でええか
s = input().split()
N = int(input())
T = []
for _ in range(N):
T.append(input())
def is_detect(target: str, source: str):
if len(target) != len(source):
return False
for t, s in zip(target, source):
if t == '*':
... |
eb59943f20e9f687f29d88374a004cfdb4d81b3e | masakiaota/kyoupuro | /practice/C_ABC/abc015_c.py | 1,571 | 3.609375 | 4 | # https://atcoder.jp/contests/abc015/tasks/abc015_3
# 制約はたかだか5**5なので全探索することができる
import sys
read = sys.stdin.readline
def read_ints():
return list(map(int, read().split()))
def read_matrix(H):
'''
H is number of rows
'''
return [list(map(int, read().split())) for _ in range(H)]
# N, K = read_in... |
d99769dec2387717ae3cfeab8a0af657a04558ae | masakiaota/kyoupuro | /practice/algorithm_datastructure_for_programming_contest/384_CGL_1_C.py | 2,219 | 4 | 4 | # https://onlinejudge.u-aizu.ac.jp/courses/library/4/CGL/all/CGL_1_C
# この問題は後の交差判定のところで使う
from math import sqrt
class Vector:
def __init__(self, ls):
'''
ls ... list
'''
self.vec = ls
def __len__(self):
return len(self.vec)
def __getitem__(self, idx):
retu... |
c796122dc11a0b236c44145c89510d7967a33cf1 | masakiaota/kyoupuro | /practice/algorithm_datastructure_for_programming_contest/398_CGL_3_C.py | 2,998 | 3.90625 | 4 | # https://onlinejudge.u-aizu.ac.jp/courses/library/4/CGL/all/CGL_3_C
# 本の説明を図に書き出してみるとよく理解できる。
from math import sqrt
class Vector:
def __init__(self, ls):
'''
ls ... list
'''
self.vec = ls
def __len__(self):
return len(self.vec)
def __getitem__(self, idx):
... |
0108647340d23095a17ae02f72cde95d8a466085 | masakiaota/kyoupuro | /algorithm/bisect_for_reversedlist.py | 1,380 | 3.765625 | 4 | # .sort(reverse=True)にしたリストに対してもbisectできるようにしたい
# 0 1 2 3 4 5 6 7 8
a = [10, 9, 5, 3, 3, 3, 2, -3, -3]
def bisect_left_reverse(a, x):
'''
reverseにソートされたlist aに対してxを挿入できるidxを返す。
xが存在する場合には一番左側のidxとなる。
'''
if a[0] <= x:
return 0
if x < a[-1]:
return len(a)
# 二分... |
5746bee9a57e3871d050c69b40173b6fe558e201 | masakiaota/kyoupuro | /contests/ABC124/D_correct_syakutori.py | 2,215 | 3.609375 | 4 | import sys
read = sys.stdin.readline
def read_ints():
return list(map(int, read().split()))
def read_a_int():
return int(read())
def read_matrix(H):
'''
H is number of rows
'''
return [list(map(int, read().split())) for _ in range(H)]
def read_map(H):
'''
H is number of rows
... |
d533385e00971aeb73151bc2f228b13317a6543b | masakiaota/kyoupuro | /contests/ABC148/F.py | 2,202 | 3.515625 | 4 | # 入力が10**5とかになったときに100ms程度早い
import sys
read = sys.stdin.readline
def read_ints():
return list(map(int, read().split()))
def read_a_int():
return int(read())
def read_matrix(H):
'''
H is number of rows
'''
return [list(map(int, read().split())) for _ in range(H)]
def read_map(H):
'''... |
6cce48f2ba8d23eb9514a377b9e830d0b624fc66 | masakiaota/kyoupuro | /practice/AtcoderBeginnersSelection/Traveling.py | 596 | 4 | 4 | def manhattan(x_1, x_2):
"""
x_1は(x,y)のタプル
マンハッタン距離を返す
"""
return abs(x_1[0] - x_2[0]) + abs(x_1[1] - x_2[1])
def can_or_not(dist, dt):
if dist > dt:
return False
elif dist % 2 != dt % 2:
return False
return True
flgs = set()
t_p, x_p, y_p = 0, 0, 0
N = int(input())
... |
ce35a72ec700f401e54d45ce255d4c57870b6149 | santosh6171/pyScripts | /palindrome.py | 160 | 4.125 | 4 | wrd=input("Please enter a word\n")
wrd=str(wrd)
if wrd[::1]==wrd[::-1]:
print("This word is a palindrome")
else:
print("This word is not a palindrome")
|
057f90b504c71f45eb2e766b9d663f5d767f20b8 | santosh6171/pyScripts | /reverseSentence.py | 246 | 4.375 | 4 |
def get_reverse_string(str):
liststr = str.split()
return " ".join(liststr[::-1])
string = input("Enter a sentence to be reversed\n")
reverseString = get_reverse_string(string)
print ("Reversed string is: {0}" .format(reverseString))
|
d68bc142c433153d3fc3cb02c7b4a88ebfed608e | santosh6171/pyScripts | /listEnds.py | 282 | 3.921875 | 4 | def get_list():
# listofnum = input("Provide a list of numbers\n").split( )
return [ int(x) for x in input("Provide a list of numbers\n").split() ]
def get_ends():
return [ listofnum[0], listofnum[-1] ]
listofnum = get_list()
listofends = get_ends()
print (listofends)
|
cfe8529ae740bddcf31b6af5c7ed2ef0716f1a2f | arthur-sanches/APS_Facial_Recognition | /capture.py | 663 | 3.53125 | 4 | import cv2
def show_webcam(mirror=False):
"""Starts a available webcam and waits for an user input to take a picture or stop"""
cam = cv2.VideoCapture(0)
while True:
ret_val, img = cam.read()
if mirror:
img = cv2.flip(img, 1)
cv2.imshow('Webcam', img)
if cv2.wai... |
3bb06e0cd229090ea957b557f419e5860b9d2c47 | JulianCSalazar/Python_Tutorial | /Python_Part5.py | 3,365 | 4.25 | 4 | # Classes are a manually created data type, much like ints, strings, and lists.
# The key difference now is you get to decide what makes up your data type.
# An instance is a unique use of your new data type. So, if you were to make a
# person class that required name, age, and eye color fields; Julian would be
# ... |
511b227728aa326e3ee10621f3ae9dee499aa76f | L200180015/algostruk | /MODUL_1/6.py | 533 | 3.515625 | 4 | from math import sqrt as sq
def apakahPrima(n):
n = int(n)
assert n>=0 #hanya menerima bilangan non-negatif
primaKecil = [2,3,5,7,11]
bukanPrKecil = [0,1,4,6,8,9,10]
if n in primaKecil:
return True
elif n in bukanPrKecil:
return False
else:
for i in range(2... |
2df3d2e1dd9a86f3e957c7c4f20d975e5e405672 | jesuejunior/math | /euler.py | 393 | 3.59375 | 4 | # _*_ coding: utf-8 _*_
def euler(xi, xf):
x = xi
y = 1
dx = 0.5
nc = (xf - xi)/dx
print [x, y]
for i in range(int(nc)):
dydx = f1(x);
y = y + dydx * dx;
x = x + dx;
print [x,y]
#f'(x)
def f1(x):
return ((-2 * x**3) + (12* x**2) - (20 * x )+ 8.5);
def main... |
a12a74846b394523d997fdf5a5ead2f56aaafe48 | Projet-GIT/Projet-Python | /BruteForce/BruteForce-SIMPLE.py | 502 | 3.75 | 4 | from time import time
import string
liste = string.ascii_letters
def bruteforce(word, length):
if length <= 5: #Longueur du mot de passe
for letter in liste:
if mdp == word + letter:
print("Le mot de passe a été trouvé : " + word + letter)
else:
bru... |
f04b6254f72f05b958e3056cfc5514fc1b65f54a | liuhh02/CodeDecoder | /functions.py | 426 | 3.96875 | 4 | # Return the absolute value of x .
def abs_value(x):
if (x > 0) return x
return -x
# greets the user with the given name
def greet(name):
print("Hello, " + name + ". Good morning!")
# Calculate the youngest age
def youngest(age1, age2, age3):
age = min(age1, age2, age3)
print("The youngest age is ... |
16e7932921f1c2b9819335a758f554ec22239508 | srinathalla/python | /algo/dfs/recoverFromPreorder.py | 930 | 3.609375 | 4 | # Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def recoverFromPreorder(self, S: str) -> TreeNode:
stack, i = [], 0
while i < len(S):
level = 0
val = 0
... |
36297e5a830c34ed7a7d44a4ba4d306b338fb58f | srinathalla/python | /algo/tree/longestUnivalPath.py | 1,029 | 3.6875 | 4 |
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
def longestUnivaluePath(self, root: TreeNode) -> int:
if root is None:
return 0
self.res = 1
def dfs(node):
... |
712a1d0ecb9fa7aa10f872d922f07fb8d459283d | srinathalla/python | /algo/dp/levenshteinDistance.py | 652 | 3.5 | 4 | #
# T.C : O(2n) + O(m) + O(n*m) => O(nm)
# @param {*} str1
# @param {*} str2
#
def levenshteinDistance(str1, str2):
n = len(str1)
m = len(str2)
distances = [[j for j in range(m+1)] for i in range(n+1)]
for i in range(n+1):
distances[i][0] = i
for i in range(1, n+1):
for j i... |
3cfdcb35f1c2803ead3ffb1250676962cf93af97 | srinathalla/python | /algo/dp/medium/wordBreak.py | 759 | 3.546875 | 4 | from typing import List
from functools import lru_cache
class Solution:
def wordBreak(self, s: str, wordDict: List[str]) -> List[str]:
wordDict = set(wordDict)
@lru_cache(None)
def wb(i):
if i == len(s):
return []
if s[i:] in wordDict:
... |
d6df1006f0733964a240d3e3c64b178b9680eee5 | srinathalla/python | /algo/string/groupAnagrams.py | 410 | 3.578125 | 4 | #
# T.C : O(w*nlogn) where n : length of longest word and w : no of words
# S.C : O(w*n)
# #
def groupAnagrams(words):
map = {}
for word in words:
sortedWord = "".join(sorted(word))
if sortedWord not in map:
map[sortedWord] = []
map[sortedWord].append(word)
return lis... |
b91fc18dceeeab75ab202a8fc938a7eedeeb4874 | srinathalla/python | /algo/dp/hard/MinimumDistanceToTypeAWord.py | 988 | 3.65625 | 4 | import string
class Solution:
def minimumDistance(self, word: str) -> int:
def dist(c1, c2):
if c1 is None:
return 0
x1, y1 = keyboard[c1]
x2, y2 = keyboard[c2]
return abs(x1-x2) + abs(y1-y2)
def helper(i, f1, f2):
print(... |
a48437c361f12db04690ec8728035925495949ed | srinathalla/python | /algo/dfs/pathWithMaxMin.py | 777 | 3.5625 | 4 | from typing import List
class Solution:
def maximumMinimumPath(self, A: List[List[int]]) -> int:
self.max = 0
self.min = A[0][0]
def dfs(i, j, arr):
if i >= 0 and i < len(A) and j >= 0 and j < len(A[0]) and A[i][j] >= 0:
if i == len(A) - 1 and j == len(A[0]) -... |
310e9e628d8e34cde1773d4b6b3342eebac6755c | srinathalla/python | /algo/arrays/leet/medium/kthLargest.py | 369 | 3.578125 | 4 | import heapq
from typing import List
class Solution:
def findKthLargest(self, nums: List[int], k: int) -> int:
pq = []
for a in nums:
heapq.heappush(pq, a)
if len(pq) > k:
heapq.heappop(pq)
return heapq.heappop(pq)
arr = [3, 2, 1, 5, 6, 4]
k = ... |
6af20f84a899983d51364de572d426e4c95e83d3 | srinathalla/python | /algo/tree/closestBinarySearchTreeVal.py | 1,234 | 3.796875 | 4 | # Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def closestValue(self, root: TreeNode, target: float) -> int:
values = []
def inorder(node):
if node is None:
... |
a1c6f7dfb979a3590daff9c50fd38c50cfa408e6 | srinathalla/python | /algo/arrays/largestRange.py | 523 | 3.6875 | 4 | def largestRange(array):
itemsSet = set()
for x in array:
itemsSet.add(x)
maxRange = 0
start = -1
for x in array:
if (not(x - 1 in itemsSet)):
count = 0
y = x
while (y in itemsSet):
count += 1
y += 1
if ... |
4295e7f056474a6453ef15da6d17a18ff890e5f1 | surya1singh/Python-general-purpose-code | /multithreading/simple_use.py | 2,024 | 4.1875 | 4 | from threading import Thread, Lock, active_count, current_thread, Timer, enumerate
import time
def first_threads():
first = Thread(target=print, args=("This is print statement is with input :",1))
second = Thread(target=print, args=("This is print statement is with input :",2))
third = Thread(target=print,... |
6f6a21df3ec943812c79190de0ed9ec72ee133d0 | surya1singh/Python-general-purpose-code | /multithreading/case2.py | 890 | 3.828125 | 4 | from threading import Thread, Lock, active_count, current_thread, Timer, enumerate
import time
threadLock = Lock()
class myThreadLock(Thread):
def __init__(self):
super(myThreadLock, self).__init__()
def run(self):
print("Starting" , self.getName())
time.sleep(3)
threadLock.acquire()
... |
c388ee3589e8005e93bad8743d473ade30af69a1 | surya1singh/Python-general-purpose-code | /multiprocessing/simple_pool.py | 437 | 3.5 | 4 | import multiprocessing
import os
import time
def square(n):
print(f"Worker process id for {n}: {os.getpid()}")
time.sleep(2)
return (n*n)
if __name__ == "__main__":
mylist = [1,2,3,4,5,6,7,8,9]
p = multiprocessing.Pool(6) # will create max 6 process
result = p.map(square, mylist)
print(re... |
b52eeb2218a129b27e341a1a096e90d17ffd6c56 | thsmcoding/P_Projects | /Python/COTASKS/Necklace/SOLUTIONS/beads.py | 1,575 | 3.703125 | 4 | """
TASK : beads
"""
def collecting_beads_counting(necklace):
BLUE = False
RED = False
count = 0
for bead in necklace:
if bead == 'r':
if BLUE:
break
else:
RED = True
if bead == 'b':
if RED:
break
... |
4a6cdc92bb87f12be39e44552841000b7c9aac8f | vishwanathprudhivi/interview_solutions | /estimate_pi_using_random_function.py | 1,052 | 4.09375 | 4 | '''
This script tries to use a random number generator
that samples a value from a uniform distribution
between (0,1) to estimate the value of pi.
The intuition behind the function created is that the
ratio of the areas of a circle and a square having a
length equal to the circles ... |
3982b960553ff7ad1ac4bef1955f42762ba450ae | rajneeshshukla1608/GUI_python | /Accepting user input.py | 1,767 | 3.546875 | 4 | from tkinter import *
import tkinter.messagebox as box
root = Tk()
root.geometry("644x344")
root.resizable(0, 0)
Label(root, text="Welcome to traveler agency", font="comicsansns 13 bold", pady=10).grid(row=0, column=3)
name = Label(root, text="Name").grid(row=1, column=2)
phone = Label(root, text="phone").grid... |
eafea7b67e6a0ee4126dd4a3ed5dcc655f61fd57 | TomKemperNL/hu-prog-uitwerkingen | /8_1.py | 469 | 3.671875 | 4 | # Schrijf een while-loop die steeds getallen van de gebruiker vraagt tot deze 0 ingeeft:
#
# Uitvoer:
#
# Geef een getal: 5
# Geef een getal: -1
# Geef een getal: 0
# Er zijn 2 getallen ingevoerd, de som is: 4
getal = int(input('Geef een getal: '))
aantal_getallen = 0
som = 0
while getal != 0:
aantal_getallen = a... |
19d99d655b942323c101ca58f5c307e0020d6474 | TomKemperNL/hu-prog-uitwerkingen | /6_5.py | 548 | 3.71875 | 4 | # Schrijf functie gemiddelde(), die de gebruiker vraagt om een willekeurige zin in te voeren.
# De functie geeft vervolgens de gemiddelde lengte van de woorden in de zin als returnwaarde terug.
# Test je code door de methode aan te roepen en het resultaat te printen.
ingevoerde_zin = input('Geef eens een zin: ')
def... |
3056279816634017662d365dd70255f18fe349fe | TomKemperNL/hu-prog-uitwerkingen | /1_4.py | 814 | 3.515625 | 4 | a = 6
b = 7
c = (a + b) / 2
voornaam = "Monty"
tussenvoegsel = "de"
achternaam = "Piton"
mijn_naam = voornaam + ' ' + tussenvoegsel + ' ' + achternaam
# 1. 6.75 groter is dan a en kleiner b.
resultaat = 6.75 > a and 6.75 < b
print('1:', resultaat)
# of korter
resultaat = b > 6.75 > a
print('1:', resultaat)
# 2. de l... |
5ffc34b7ddadd728a5c01d4baddb42b2406eecca | TomKemperNL/hu-prog-uitwerkingen | /7_3.py | 7,617 | 3.828125 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import traceback, collections
"""
Programming
Practice Exercise 7.2
(c) 2021 Hogeschool Utrecht,
Tijmen Muller en
Bart van Eijkelenburg (bart.vaneijkelenburg@hu.nl)
Opdracht:
Werk onderstaande functie(s) uit.
Voeg commentaar toe om je code toe te lichten.
"""
def gem... |
c24689f969953d6cd9359786f594fdcb0470e140 | corbin737/shopify-2018 | /shopify_data_eng.py | 3,672 | 3.734375 | 4 | #!/usr/bin/python
from argparse import ArgumentParser
import json
def merge_objects(obj1, obj2):
'''
Returns an object with all keys and values from `obj1` and `obj2`.
If a key is shared between the two objects, the value in `obj2` will take precedence.
'''
merged = dict()
merged.update(obj1)... |
b3ef3116bdcc28a740ffeca9ca0e1c2fff74fc78 | AnnaLebed/Python-mini-project | /FileHandler.py | 3,313 | 3.5625 | 4 | import csv
import os
import pathlib
class FileHandler:
file_path = ''
def __init__(self):
self.file_path
self.readen_data = []
def directory(self, file_name):
self.file_path = pathlib.Path(__file__).parent.absolute().joinpath(file_name)
return self.file_path
def load... |
820098f0a63d1ab2d386905e8381942f7ff7d377 | WinonaLyw/BotAndBrexit | /select_tweets.py | 2,844 | 3.53125 | 4 | '''
Select tweets
1. read tweets
2. sum the total tweets per day
3. calculate the moving difference of total tweets for each day
4. selext tweets for a specific day as sample
5. save file
'''
# %% import
import numpy as np
import pandas as pd
import matplotlib.plot as plt
import global_variables as gv
# %% read tw... |
ce2977ae0d04790a6b6dbae6443a32f399ad1041 | Loczi94/PyLove-AdvancedConstructs | /poletrojkata.py | 288 | 3.546875 | 4 |
def calculate_area(points):
A, B, C = points[0], points[1], points[2]
area = 0.5 * abs(A[0]*B[1]+B[0]*C[1]+C[0]*A[1]-C[0]*B[1]-A[0]*C[1]-B[0]*A[1])
print('Pole trojkata wynosi '+str(area))
return area
if __name__ == '__main__':
calculate_area([[0,0],[10,10],[10,0]]) |
6036c92608a3b5a6b11d09815134760d0d9f6600 | seifely/mesa_boxworld | /mesa_boxworld/mesa_boxworld/astar_alt.py | 5,869 | 3.59375 | 4 | from queue import PriorityQueue
import math
# this is a test file to experiment with the A* solver algorithm and workable solutions
# def deliberative_nav():
# .get_nodes() # sets the global 'passable_nodes' to the list of non-obstacle map points
# came_from, cost_so_far = astar_search(pos, goal)
# recon... |
4f62b1caec57928150e9d91a3be84315fedfbc55 | ZahraNaddaf/class-1 | /session_05/is_triangle_function.py | 192 | 4.15625 | 4 | def is_triangle(a, b, c):
out = True
if a < b + c and b < a + c and c < a + b:
return out
else:
out = False
return out
x = is_triangle(3, 4, 5)
print(x)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.