blob_id
stringlengths
40
40
repo_name
stringlengths
5
119
path
stringlengths
2
424
length_bytes
int64
36
888k
score
float64
3.5
5.22
int_score
int64
4
5
text
stringlengths
27
888k
d429a3e7b34a32a6d5cfc1d142b3f42c28a1d072
Tr4shL0rd/mathScripts
/uligheder/støreEndMindreEnd_Minus_num.py
324
3.734375
4
try: def main(): while True: a = int(input("a = ")) b = int(input("b = ")) c = int(input("c = ")) b = b+c result = b/a print(f"\nx = {result}\n======") main() except KeyboardInterrupt: print("\nGoodBye...
c8c6a921a5ece023c24c0d87c02d8b9e90f138df
bosshentai/pythonLearning
/regular_Expressions/teste.py
328
3.515625
4
import re pattern = re.compile('this') string = 'search inside of this text please!' #print('search' in string) a = pattern.search(string) b = pattern.findall(string) c = pattern.fullmatch(string) d = pattern.match(string) # print(a.span()) # print(a.start()) # print(a.end()) # print(a.group()) print(b) print(c) p...
13aaa497401f0d871d728846d8c8dda7515cd151
hrssurt/lintcode
/leetcode/234. Palindrome Linked List.py
1,757
3.875
4
"""*************************** TITLE ****************************""" """234. Palindrome Linked List.py""" """*************************** DESCRIPTION ****************************""" """ Given a singly linked list, determine if it is a palindrome. Example 1: Input: 1->2 Output: false Example 2: Input: 1->2->2-...
c1aae258433b14ea1f5cec822df0073b6e4cc1dd
pedrosimoes-programmer/exercicios-python
/exercicios-Python/aula13.py
559
3.859375
4
for c in range(1, 7): print(2 * c) print('') for c in range(6, 0, -1): #-1 é a forma que o for realizará a contagem, ou seja, contando de -1 em -1 print(c) print('') for c in range(0, 12, 2): # 2 é a forma que ele vai fazer a contagem, ou seja, de 2 em 2 print(c) print('') i = int(input('Início: ')) f...
1a7ad7284e9bd64e23cd44a9a2df2fabd9376456
jayventi/primes_n_e
/prime_pattern_engine/primes_sieve_generator.py
2,003
4.34375
4
""" generates a sieve list of prime numbers up to a maximum given as a parameter primes_sieve_generator based on ideas from: https://jeffknupp.com/blog/2013/04/07/improve-your-python-yield-and-generators-explained/ Jay Venti September 8th, 2016 """ import math import json def is_prime(number, primes_table): """...
28c0dbe5f7745522aebffff555079a66bc6376c0
pigmonchu/BZ5_k2_romanos
/cromanos.py
3,455
3.53125
4
class RomanNumber(): __symbols = {'M':1000, 'CM':900, 'D':500, 'CD':400, 'C':100, 'XC':90, 'L':50, 'XL':40, 'X':10, 'IX':9, 'V':5, 'IV':4, 'I':1, } def __init__(self, valor): ...
2dee56e2231536b6e501cad14177ba342459aa54
Danilo282/python-port
/Leitores_for_while/aposentadoria.py
217
3.78125
4
id = int(input('Digite a sua idade: ')) ts = int(input('Digite o tempo de serviço: ')) idts = id + ts if idts >= 85 or id >= 65 or ts >= 30: print('Pode se aposentar.') else: print('Não pode se aposentar.')
d9f47cb1a99b9089135c49c947a3c55609dbbdad
Mehvix/competitive-programming
/Codeforces/Individual Problems/P_118A.py
199
3.515625
4
fin = list(input().strip()) vowels = ["a", "e", "i", "o", "u"] for pos in range(len(fin)): if [s for s in fin if str(fin[pos]).lower() in s]: del fin[pos] # TODO NOT DONE print(fin)
902465ed5dbc2d9f9d028e8a0525d723b8b948a9
teja463/python
/oops.py
892
3.84375
4
class Employee(): #name = "Teja" company = "Mindtree" mail = "teja463@gmail.com" __sal = 22000 def __init__(self): self.name = "Pramod" def getSal(self): return self.__sal obj1 = Employee() #print (Employee.name) print (obj1.name) print (obj1.getSal()) prin...
ccc12beab6b025ab7cd2afeccb3219f5f3fbe69e
daniele-canavese/fingerprinting
/classification/ml/classification.py
848
3.59375
4
""" Classification functions. """ from typing import Any from typing import Dict from typing import Tuple from pandas import DataFrame from pandas import Series def classify(model: Dict[str, Any], x: DataFrame, classes: Dict[int, str]) -> Tuple[Series, DataFrame]: """ Classifies some data. :param model:...
d112500b3f9e2121be7c98316b65f3ac4856c2c5
cristian341/First-Python-Programm
/Project.py
21,310
3.65625
4
import math from statistics import mode from graphics import * from bar_chart import * from pie_chart import * def area_of_square(x): return print(f"Area of square is {round(x**2, 3)}cm²") def perimeter_of_square(x): return print(f"Perimeter of square is {round(4*x, 3)}cm") def volume_of_cube(x): return p...
df2d8489e45b603f514502f3d1d5b07e9ef912f4
shuixingzhou/learnpythonthehardway
/ex41.py
1,351
4.25
4
#!usr/bin/env python3 #-*- coding: utf-8 -*- class TheThing(object): def __init__(self): self.number = 0 def some_function(self): print('I got called.') def add_me_up(self,more): self.number += more return self.number #two different things a = TheThing() b = TheThing() a.some_function() b.some_function() ...
cc1fb8c301c4f941c82b20ed8b7eeb652650be83
xCrypt0r/Baekjoon
/src/8/8712.py
398
3.515625
4
""" 8712. Wężyk 작성자: xCrypt0r 언어: Python 3 사용 메모리: 29,380 KB 소요 시간: 64 ms 해결 날짜: 2020년 9월 17일 """ def main(): n = int(input()) l = [] for i in range(n): l.append([j for j in range(n * i + 1, n * (i + 1) + 1)]) for i, v in enumerate(l): print(*(v[::-1] if i & 1 else v), sep=' ') if _...
fd8a06c8b32e1488ab3ff8b875a2d6a76f336a70
ExpertSeahorse/SimpleCode
/Same checker.py
492
3.75
4
def comp(array1, array2): if None in (array1, array2) or len(array1) != len(array2): return False newarray = [] for entry in array1: newarray.append(entry * entry) if ' '.join(map(str, sorted(newarray))) == ' '.join(map(str, sorted(array2))): return True else: retu...
bab4a15d231c8308dedb1d0856e6b005b06567d4
yifengjin89/bank_system
/atm.py
4,472
3.625
4
# 2/12/2020 # atm info from card import Card from user import User import random class Atm(object): def __init__(self): self.all_users = {} def atm_interface(self): print("***********************************************************************") print("* ...
451ed08b43cf35a88ae06fb9b94a0b4e43c83c98
Anz131/luminarpython
/polymorphism/method overriding.py
1,785
3.90625
4
#overriding - same method name same no of args # class Parent: # def properties(self): # print("abcd") # def marry(self): # print("abc") # class Child(Parent): # def marry(self): # print("abc") # c=Child() # c.marry() # class Person: # def properties(self,name): # self....
5053af671e27ca9b3094f57995f874f186d387e8
AstinCHOI/book_effective_python
/8_production/55_repr_for_debugging_output.py
796
3.5625
4
print('foo bar') print('%s' % 'foo bar') print(5) print('5') # >>> # foo bar # foo bar # 5 # 5 ## human readable, but type? a = '\x07' print(repr(a)) b = eval(repr(a)) assert a == b # >>> # '\x07' print(repr(5)) print(repr('5')) print('%r' % 5) print('%r' % '5') # >>> # 5 # '5' # 5 # '5' class OpaqueClass(objec...
21cec749f446a0715e0e12a03d051833af552509
YANGYANTEST/Python-development
/stage one/day04/作业.py
1,236
4.1875
4
''' 第一题: num_list = [[1,2],[‘tom’,’jim’],(3,4),[‘ben’]] 1. 在’ben’后面添加’kity’ 2. 获取包含’ben’的list的元素 3. 把’jim’修改为’lucy’ 4. 尝试修改3为5,看看 5. 把[6,7]添加到[‘tom’,’jim’]中作为第三个元素 6.把num_list切片操作: num_list[-1::-1] 第二题: numbers = [1,3,5,7,8,25,4,20,29]; 1.对list所有的元素按从小到大的顺序排序 2.求list所有元素之和 3.将所有元素倒序排列 ''' num_list = [[1,...
fc38d0286381ac904103b33b8be811a376b79e2e
KenRishabh/BtechCSE
/function_in_function.py
575
4
4
def greater(a,b): if a>b: return a return b def greatest(a,b,c): if a>b and a>c: return a elif b>a and b>c: return b else: return c #function inside function #greater(a,b)--------> a or b #greater (a or b, c)------->greatest # # def new_greatest...
ac7295fde7939e476733f7aa05ee1e7e67f90217
yameenjavaid/bigdata2019
/01. Jump to python/Chap05/174_class_calculator.py
689
4.09375
4
class Calculator : # 사용자 정의 클래스 def __init__(self): # 생성자(Constructor) : 객체 생성시 최초로 수행되는 함수 self로 인해 일반 함수와 비교 self.result = 0 # Class의 멤버 변수 def adder(self, num): # 멤버 함수(Member Function) print("[%d]값을 입력 받았습니다." %num) self.result += num+100 self.num1 = 100 # 멤버변수로 등록은 가능하나 가독성...
7f26fce622b7ec0bba23aa048797558ddfac6155
Terencetang11/Sudoku_Puzzle
/Sudoku_Algorithm.py
4,439
4
4
# Author: Terence Tang # Class: CS325 Analysis of Algorithms # Assignment: Portfolio Project - Sudoku Puzzle Game # Date: 3/8/2021 # Description: Algorithms for checking the validity of a sudoku solution / certificate and for deriving a solution for # a given instance of sudoku. Checking the validity o...
3a9eaf40139bfeecb7c286683c50c7874a2229c8
MarleneDraganov/teste
/ex048.py
148
3.828125
4
soma = 0 for n in range(1, 501, 2): if n % 3 == 0: soma = soma + n print('A soma de todos os valores solicitados foi {}'.format(soma))
82ad980798802ecf4c357da824a8989da1caa4fd
DomWeldon/SecretSanta
/nice.py
708
4.28125
4
"""The Nice Way This way simply shuffles the list of people and then treats them as a circle and produces a Hamiltonian path by assigning each person the next person in the cycle. Sequence approach means it works for an odd number of people. """ from itertools import cycle from random import sample # remember shuffle...
363f22244544473070d7807e6acdb01528d8d37f
Xenom-msk/Exercises-from-Teach-Your-Kids-to-Code-by-Bryson-Payne
/Exercises-for Teach Your Kids to Code by Bryson Payne/Color_spiral_input.py
706
4.65625
5
# Color spiral input import turtle t=turtle.Pen() turtle.bgcolor("black") # Set up a list of any 8 color names colors=["red", "green", "blue", "yellow", "orange", "pink", "white", "purple"] #Ask the user for the number of sides, betwen 1 and 8, with default of 4 sides=8 # Draw a colorful spiral with the u...
cabc250d21bdefbf18f1aaa5731c48e1191d7de4
Rasenku/LeetCodeProblems
/fifthLargest.py
244
4.15625
4
# In a list, return the fifth largest problem nums = [2, 3, 76, 1, 34, 98, 45, 2, 8] def fifthLargest(nums): """ Returns the fifth largest number in a array of n numbers """ nums.sort() return nums[-5] fifthLargest(nums)
f3ec8410aeaac7b85940c816d60b49de95bea011
jvaquino7/trabalho-extra
/dificil.py
406
3.8125
4
conta = float(input("INFORME SUA CONTA:")) senha = float(input("INFORME SUA SENHA:")) saque = float(input("INFORME SEU SAQUE:")) if conta == 999 and senha ==456: print("BEM VINDO") else: print("CONTA E/OU SENHA INCORRETAS") dinheiro = 100 - saque if saque > 100: print("SALDO INSUFICIENTE") else: pr...
0c3546a3fdcaa1da9ff8ff893aa24bb3cfa9d2c5
privateOmega/coding101
/geeksforgeeks/palindrome-count.py
427
3.828125
4
def palindromeCount(list_a): count = 0 for num in list_a: temp = num rev = 0 while temp > 0: rev = rev * 10 + temp % 10 temp = temp / 10 if num == rev: count = count + 1 print('Total number of palindromes in list', count) def main(): ...
bc88f18a5b0595012d81106e38ce5a9b39bea480
fyujn/project1ML
/scripts/ml_methods.py
8,377
3.8125
4
# Useful starting lines import numpy as np import matplotlib.pyplot as plt import importlib from proj1_helpers import * #initial_w is the initial weight vector #gamma is the step-size #max_iters is the number of steps to run #lambda_ is always the regularization parameter #from scripts.proj1_helpers import * def h...
a5dcb388425e44e4d981b9410d4ddcee8e57522a
ElliottBarbeau/Leetcode
/Problems/triplet sum.py
859
4
4
def search_triplets(arr): triplets = [] arr.sort() for i in range(len(arr) - 2): if arr[i] == arr[i+1]: continue left, right = i + 1, len(arr) - 1 while left < right: sum = arr[i] + arr[left] + arr[right] if sum == 0: triplets.appe...
994f7083edc55bfc0b03405937f60cb028ed11f8
xvicxpx/Stat-535-Project
/Visualization.py
545
3.734375
4
#Visualization """ Takes a dictionary of lists Creates a new Dictionary with the same keys but values are the average of the lists of the original Then plots them in a bar plot After examination we will make graphs of the best and worst performances """ import matplotlib.pyplot as plt import Combinations as c rates...
4025f531f13e511d2e8b49c857c084ffb28e3fca
huioo/SPEC-py2.7-tornado4.5
/utils/probability.py
1,188
3.84375
4
#!/usr/bin/env python # -*- coding: utf-8 -*- """ 概率方面的通用工具 """ import random def is_win_prize1(win=0.5): """ 按几率中奖,返回结果是否中奖 :param win: 中奖几率,取值范围0~1 :return: True / False """ result = False percent = random.random() if percent < win: result = True return result def is_win...
de93927a48d5b1ab4724615840c895b41b8737d5
Neocryan/Reinforcement_Learning
/Mountain-Car/agent.py
11,128
3.53125
4
__author__ = 'Xiaoyu' import numpy as np """ Contains the definition of the agent that will run in an environment. """ class r0: def __init__(self): self._w = np.random.random([2, 3]) self._olds = np.random.random([2, 1]) self._gamma = 0.05 self._alpha = 0.01 self._lambda ...
4efcf81ba322e6dad3356ad42fb7453b775841c9
hnzhangbinghui/selenium
/26、冒泡排序.py
2,315
4.125
4
''' 概念:冒泡排序(Bubble Sort),是一种计算机领域的较简单的排序算法。 它重复地走访过要排序的数列,一次比较两个元素,如果他们的顺序错误就把他们交换过来。 走访数列的工作是重复地进行直到没有再需要交换,也就是说该数列已经排序完成。 这个算法的名字由来是因为越大的元素会经由交换慢慢“浮”到数列的顶端,故名。''' '''算法原理: 冒泡排序算法的运作如下:(从后往前) >比较相邻的元素。如果第一个比第二个大,就交换他们两个。 >对每一对相邻元素作同样的工作,从开始第一对到结尾的最后一对。在这一点,最后的元素应该会是最大的数。 >针对所有的元素重复以上的步骤,除了最后一个。 >持续每次对越来越少的元素重复上面的步骤,直到...
37278111378e572d1a2dc2c078efabe27cef97e3
Aaron1011/code_challenges
/keypad_2.py
1,435
3.6875
4
def load_words(): wordfile = open('/usr/share/dict/american-english', 'r') lines = wordfile.read().split('\n') wordfile.close() return lines def make_trie(words): root = dict() for word in words: curr_dict = root for letter in word: curr_dict = curr_dict.setdefault(l...
e47bc08a8b5ca8a0f6d67a0006baab297c8f8845
csuvis/MCGS
/utils/load_graph.py
1,057
3.921875
4
import csv import networkx as nx def loadGraph(graph_name): """Load the graph file and return the graph object. Parameters ---------- graph_name : string The name of the graph. Returns ------- G : Graph object The graph data object with nodes, edges and other graph attri...
a49b2b65962fc5caf3518a89636d1b0d725837f3
SaiPranay-tula/DataStructures
/PY/ABS.py
338
3.640625
4
from abc import ABC,abstractmethod class Interface(ABC): @abstractmethod def abs_method(self): pass @staticmethod def absmethod(): print("abs in interface") class NEW_CLASS(Interface): @staticmethod def abs_method(): print("abs in class") a=NEW_CLASS() a.abs_meth...
bdc7784bdf069d1374fad0e7f8e8872f27a33893
luoshao23/Data_Structure_and_Algorithm_in_Python
/ch04_Recursion/bisearch.py
480
3.921875
4
def binary_search(data, target, low, high): if low > high: return False mid = (low + high) // 2 if target == data[mid]: return mid elif target < data[mid]: return binary_search(data, target, low, mid - 1) else: return binary_search(data, target, mid + 1, high) if _...
48299963bcbd1aaed290c6b62a6d8a4a60c9bacc
TehyaStockman/TextMining
/text_processing.py
589
3.734375
4
def processing_file(filename): """processing initial file, stripping out guttenberg extra stuff""" fp = open(filename) all_text = fp.read() index_start = all_text.find('CONTENTS') index_end = all_text.find('End of Project Gutenberg') content = all_text[index_start: index_end] new_story = [] for line in cont...
67e0e47dd758dae04d8613916ad890c0d3e9b3cb
smartinsert/CodingProblem
/coin_change.py
626
3.859375
4
""" Given a value N, if we want to make change for N cents, and we have infinite supply of each of S = { S1, S2, .. , Sm} valued coins, how many ways can we make the change? The order of coins doesn’t matter. """ from typing import List def minimum_number_of_coins(coins: List[int], amount: int) -> int: dp = [amou...
0b398b593a907e3f8a190817e2ea83c8e1628ada
Sequd/python
/Examples/test.py
670
3.71875
4
import re def test_function(): """I print 'Hello, world!'""" print("Hello, world!") maxValue = 250 startPoint = maxValue / 4 for i in range(0, maxValue, 1): currentPoint = i / 2 + startPoint print('{0} = {1}'.format(i, currentPoint)) test_function() def t1(data: str) -> bool: ...
1c91f69ad179d216ead3812e4d604ab0c91487d5
jincheol5/2021_python
/8주차/8-2.py
166
4.09375
4
def multiply(n1,n2): s=n1*n2 return s def divide(n1,n2): s=n1/n2 return s n1 = int(input()) n2 = int(input()) print(multiply(n1, n2)) print(divide(n1, n2))
e6ee3652a054328f44c6c1b4dc352415ef1a792f
Sujan0rijal/LabOne
/LabTwo/four.py
452
4.34375
4
'''4. Given three integers, print the smallest one. (Three integers should be user input)''' integer1=int(input('enter first number:')) integer2=int(input('enter second number:')) integer3=int(input('enter third number:')) if integer1<integer3 and integer1<integer2: print(f'smallest number is {integer1}') elif in...
9e7e503d01f89a0f5dd9bb45716fab9c7da2533e
KHWeng/pYthOn-Camp-Day1
/16條件判斷式 成績等第.py
371
3.859375
4
score = int(input("Enter your score Here:")) if 100>score and score>= 90:#標準寫法,通常這樣寫才過 print("Aaa") elif 90>score >= 80:#非標準寫法,可能只在蟒蛇限用 print("Bbb") elif 80>score >= 70: print("Ccc") elif 70>score >= 60: print("Ddd") elif 0<=score < 60: print("Eee") else: print("不要亂來")
5bdb2565e6376c63cf4ecda314b0730954b38ab5
juingzhou/Python
/递归.py
106
3.609375
4
def test(num): if num==1: return 1 else: return num * test(num-1) print(test(5))
25976aa1ce78f660b5ee97261b897816ff1bc408
henriqueconte/Challenges
/LeetCode/2.py
1,057
3.703125
4
# Definition for singly-linked list. from typing import final class ListNode: def __init__(self, val=0, next=None): self.val = val self.next = next class Solution: def addTwoNumbers(self, l1, l2): firstNumberMultiplier = 1 l1Copy = l1.copy() while l1Copy.next: ...
52065631b728642ef94759c67d1be84f76dbf19c
Susanta-Nayak/S
/code/main.py
837
3.71875
4
import parser import lexer def main(): # Variable to store the contents of the file content = "" with open('test.lang', 'r') as file: # reading and storing the contents of the file content = file.read() ############################ # Lexer # ######################...
0397fcacbc63f578e80b4eb32f740c4cef8a627c
AndreySperansky/TUITION
/_STRUCTURES/Set(Множество)/set_handle_III.py
953
4.09375
4
myset = {1.23} myset.add((1, 2, 3)) print(myset) # {1.23, (1, 2, 3)} # но с кортежем таких проблем нет print(myset | {(4, 5, 6), (1, 2, 3)}) # Объединение: то же, что и myset.union(...) #{1.23, (4, 5, 6), (1, 2, 3)} print((1, 2, 3) in myset) # Членство: выявляется по полным значениям #True print((1,...
5fa0c45670740edd31f25342cabd996a80ef1883
mryangxu/pythonPractice
/常用内建模块/itertools/practice_takewhile.py
175
3.78125
4
# 通过takewhile()可以根据条件判断截取一个有限的序列 import itertools x = itertools.count(1) y = itertools.takewhile(lambda x: x <= 10, x) print(list(y))
058a512a454014692dbaf9a5a35b9257d53d9fe7
TaiCobo/practice
/checkio/fight.py
1,049
3.84375
4
class Warrior: attack = 5 health = 50 is_alive = True class Knight(Warrior): attack = 7 def fight(unit_1, unit_2): term = 0 while unit_1.health > 0 and unit_2.health > 0: if term % 2 == 0: unit_2.health -= unit_1.attack else: unit_1.health -= unit_2.a...
cb0d955fa9f2be5a83b4bb18bd0a8eb3e073b8e1
kenwilcox/compare
/compare2.7.py
1,276
3.71875
4
def dict_compare(d1, d2): d1_keys = set(d1.keys()) d2_keys = set(d2.keys()) intersect_keys = d1_keys.intersection(d2_keys) added = d1_keys - d2_keys removed = d2_keys - d1_keys modified = {o : (d1[o], d2[o]) for o in intersect_keys if d1[o] != d2[o]} same = set(o for o in intersect_keys if d...
7c8919bb63dbc49f6bec6c8e5b5a51f4670055be
fernandoeqc/calculadora_binaria
/main.py
2,816
3.671875
4
from prettytable import PrettyTable from prettytable import PLAIN_COLUMNS """ SAÍDA PARA CALCULOS SIMPLES: print("bin| 1100 + 0011 = 1111") print("dec| 12 + 3 = 15") print("hex| C + 3 = F") print("oct| 1100 + 0011 = 1111") print("asc| - + - = -") """ table = PrettyTable(["Bases"...
592fa886eef7bc1f231f8ec28a994091cc93a6d2
delroy2826/Programs_MasterBranch
/password_picker.py
588
3.921875
4
import random import string print("Password Picker") q =True while q: z=0 for i in range(3): common = random.choice(['a','b','c','e','z']) names = random.choice(['qa','we','as','rt']) special_char = random.choice(string.punctuation) num = str(random.randint(100,900)) a =...
3136edd16a91abcfef5a7dff23ca2d2558186f00
Yash-YC/Source-Code-Plagiarism-Detection
/gcj/gcj/188266/Simon.Rodgers/168107/0/extracted/a.py
966
3.5
4
def sum_of_squares( n, base, seen ): i = n; r = 0; while i > 0: r += (i % 10)**2; i /= 10; seen[n] = True; return convert_to_base( r, base ) def test_happy( n, base ): seen = dict(); i = convert_to_base(n, base); while i > 1 and (i not in seen): i = sum_of_squares( i, base, seen ); return (i == 1); ...
aff05634dd9df485e9c5f910ecbb09fce7475f83
MarRoar/Python-code
/05-OOP/07-property-.py
964
4.3125
4
''' property 方法的使用 ''' class Employee: def __init__(self, name, salary): self.__name = name self.__salary = salary # 如果用修饰器来写的话 # property 就相当于 getter 方法 @property def salary(self): return self.__salary # 给 salary 设置 setter 方法 @salary.setter def salary(se...
286e354e9058cccf639085859bc1773bc164bdad
Elaech/Game-of-GO
/game_graphics.py
12,724
3.640625
4
import pygame import pygame.freetype """ This is the graphical module for the project Game-Of-GO It contains methods for initializing and drawing on the GUI The GUI for the project consists of mainly 3 parts: The Board for the game The Scores of the players A place to display game messages/errors """ # Va...
095c29d015955d1e84ae6ddf8ce33a47023d9ac4
syurskyi/Python_Topics
/125_algorithms/_exercises/templates/_algorithms_challenges/leetcode/LeetCode_with_solution/815 Bus Routes.py
3,154
3.859375
4
#!/usr/bin/python3 """ We have a list of bus routes. Each routes[i] is a bus route that the i-th bus repeats forever. For example if routes[0] = [1, 5, 7], this means that the first bus (0-th indexed) travels in the sequence 1->5->7->1->5->7->1->... forever. We start at bus stop S (initially not on a bus), and we want...
1dfacfe675b336fbc2bb5521e7a37d65eff1fe65
joaocbjr/EXERCICIOS_curso_intensivo_de_python
/exe4.6.py
364
4.1875
4
print() print('4.6 – Números ímpares:\n Use o terceiro argumento da função range() para criar uma lista de números ímpares de 1 a 20. Utilize um laço for para exibir todos os números.') print() impar = list(range(1,21,2)) print('Os números ímpares da lista: ',impar) print('Todos os números da lista são: ') for todo in ...
7f0d9776c13f464c603bbb48eb927691f989e6d1
jgoenawan407/Linear-Algebra
/matrix_arithmetic.py
1,968
3.875
4
# Jackson Goenawan, 8/23/21 import copy def scale(scalar, matrix): scaled = copy.deepcopy(matrix) for r in range(len(matrix)): #r starts at 0 and goes until end of matrix (exclusive of last index) for c in range(len(matrix[0])): scaled[r][c] = scalar * matrix[r][c] return(scaled) ...
5ab4759f7f7620b1b7bd331602b4f375b9cc339f
aussieyang/summer_python
/lesson2.py
678
4.09375
4
#Guessing the number game import random guessesTaken = 0 myName = raw_input("What's your name >>") number = random.randint(1, 10) print "I'm thinking of a number between 1 and 10." while guessesTaken < 3: guess = raw_input("Guess what number >>") guess = int(guess) guessesTaken += 1 #this means add one...
fec4b4867b0caff31535b287ed7883a8840b86c9
carines/ProjetOCR
/addition.py
232
3.78125
4
#!/usr/bin/python3 # -*- coding: utf8 -*- # message de bienvenue print ("Bonjour à tous") entierSaisi1 = int(input("Saisir un nombre :")) entierSaisi2 =int(input("Saisir un autre nombre :")) print(entierSaisi1+entierSaisi2)
e9f5ca62030ab0a8d99adec761567f61fdcd780e
SimoneNascivera/Avoid_obstacle_RL
/Avoid_obstacle/trained/avoidobstacle.py
5,246
3.609375
4
# This code is based on https://github.com/wh33ler/QNet_Pong/blob/master/pong.py # This code was by wh33ler. I changed it to be suitable for my scope and documented it. import pygame # simple library to develop simple python games import random # simple library to generate random numbers #size of our window WINDOW_W...
f9572e3e444d1349e9acce536d32b85a9766fba3
liseyko/CtCI
/leetcode/p0111 - Minimum Depth of Binary Tree.py
720
3.75
4
from collections import deque # Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def minDepth(self, root): """ :type root: TreeNode :rtype: int """ ...
ea6ede59600608798fd6cc4a2d6a3871de2c4a76
saenuruki/Codility
/Arrays/oddOccurrencesInArray.py
2,214
4.09375
4
#A non-empty array A consisting of N integers is given. The array contains an odd number of elements, and each element of the array can be paired with another element that has the same value, except for one element that is left unpaired. # #For example, in array A such that: # # A[0] = 9 A[1] = 3 A[2] = 9 # A[3] = ...
fe46d37c3d8c50513e86403eb3eb1adfd1c9a13b
Joffenmoses/Python-Assignment6
/Untitled2.py
202
3.890625
4
#!/usr/bin/env python # coding: utf-8 # In[2]: list1=[1,2,3,4,5,6,7,8] list2=['a','b','c','d','e'] dict1={} len1=min(len(list1),len(list2)) print({list1[each]:list2[each] for each in range(len1)})
03e984c0d26fa168de16bf3b4e4f1a4a4e03f1d7
eszka/moje_programy
/cursera_list_8_4.py
1,272
3.9375
4
__author__ = 'Agnieszka' # C:\Users\Agnieszka\Desktop\ITC\Python Cursera\romeo.txt fname = raw_input("Enter file name: ") fh = open(fname) lst = list() for line in fh: li = line.rstrip().split() # li = a.split() for item in li: if item in lst: continue else: lst.append(item) p...
cd1766e5a04f43ad0702fd4e7ce899d333029112
MahbubHossainFaisal/Artificial-Intelligence
/new.py
581
3.921875
4
studentID=input("Give your student id:") if (studentID[2] == '-' and studentID[8]=='-' and len(studentID)==10 ): print("It is a valid ID") a=1 else: print("It is not a valid id") a=0 if a==1: if(studentID[0]=='2'): print("Student is in the 1st year") elif(studentID[0]=='1' and studentID...
198276790ab7bbbe7db142f7780c986e2eaa0d0a
MD-Shibli-Mollah/pythonProject-geeksforgeeks
/hr_list.py
636
3.78125
4
if __name__ == '__main__': my_list = [] n = int(input()) for i in range(0, n): my_inp = input() my_val = my_inp.split() if my_val[0] == "insert": my_list.insert(int(my_val[1]), int(my_val[2])) if my_val[0] == "print": print(my_list) if my_val[0...
16ce1a6311c5a7468e8fab8a8ef54f7ddbad34e1
simpsons8370/cti110
/P4LAB2_OutOfRange_SimpsonShaunice.py
237
4.0625
4
first_num = int(input()) second_num = int(input()) if second_num < first_num: print('Second integer can\'t be less than the first.') while first_num <= second_num: print(first_num, end=' ') first_num += 5 print()
f0d1f8befb39c9b48607464c1e7da8c492c64c6b
seongbeenkim/Algorithm-python
/Programmers/Level2/올바른 괄호(correct parenthesis).py
359
3.5
4
# https://programmers.co.kr/learn/courses/30/lessons/12909 def solution(s): count = 0 for p in s: if p == "(": count += 1 else: count -= 1 if count < 0: return False return count == 0 print(solution("()()")) print(solution("(())()")) print(sol...
771d7e83254a85896bff71606cf89203f1f8bf2c
WesleyEspinoza/CS-PythonWork
/CS1.3/search.py
2,166
4.3125
4
#!python import math def linear_search(array, item): """return the first index of item in array or None if item is not found""" # implement linear_search_iterative and linear_search_recursive below, then # change this to call your implementation to verify it passes all tests #return linear_search_recur...
d06df4b39d4075752454d2349a611db8e966d61f
ron71/PythonLearning
/Input_Output(I_O)/BinaryI_OUsingShelve.py
4,683
4.34375
4
# Drawback of pickle is that, whenever we wanted any data we have to restore entire file in memory # via making their objects. So it is not good of very large files. # Therefore python has one more module called shelve, # this module is too recommended to not to be used with untrusted file sources like internet # It st...
d3eed8aa92cc1349d90a2357ceb5015ad8c8eb07
bingoshu/Python123
/二叉树.py
340
3.96875
4
import turtle as t def tree(length,level): #树的层次 if level <= 0: return t.forward(length) #前进方向画 length距离 t.left(45) tree(0.6*length,level-1) t.right(90) tree(0.6*length,level-1) t.left(45) t.backward(length) return t.pensize(3) t.color('green') t.left(90) tree(100,6)
ba1595173b666a2e8df43e7d98f8f1992e633586
youjiajia/learn-leetcode
/solution/295/solution.py
1,582
3.65625
4
import heapq class MedianFinder(object): def __init__(self): """ initialize your data structure here. """ self.big_queue = [] self.small_queue = [] heapq.heapify(self.big_queue) heapq.heapify(self.small_queue) def addNum(self, num): """ ...
ce25a3fdcc94809df4534ba7cc57a49c9642e4c7
AlimyBreak/PythonStudy
/日常笔记/do_not_return_dict.py
680
3.796875
4
# -*- coding: utf-8 -*- """ Created on Wed Apr 24 14:00:35 2019 来源: B站UP主:哲的王 的稿件<<大兄弟,写Python请别返回Dict>> https://www.bilibili.com/video/av20963030/ @ File author: AlimyBreak """ # 方案一: def some_func(): d = dict() d['field_1'] = 1 d['field_2'] = 2 return d # 方案二: from collections i...
377e9306e430bbec0410f82ae83be3c1a94fda8c
vagdevik/ML_DL
/My-Machine-Learning/100_Days_of_ML_code/Basic_Neural_net/nn.py
1,333
3.78125
4
import numpy as np def sigmoid(x): return 1/(1+np.exp(-x)) def derivative_sigmoid(x): return x*(1-x) np.random.seed(0) #input X = np.array([[1,0,0],[0,0,1],[0,1,0],[1,0,1],[1,1,1]]) Y = np.array([[1],[0],[0],[1],[1]]) #initialize neurons and learning rate input_neurons = X.shape[1] #number of features in dat...
03da43cd9836b7a76540e0f0c32087ed378ba108
Omarfos/Algorithms
/54.spiral-matrix.py
2,158
3.8125
4
# # @lc app=leetcode id=54 lang=python3 # # [54] Spiral Matrix # # https://leetcode.com/problems/spiral-matrix/description/ # # algorithms # Medium (33.55%) # Likes: 2205 # Dislikes: 556 # Total Accepted: 356.8K # Total Submissions: 1.1M # Testcase Example: '[[1,2,3],[4,5,6],[7,8,9]]' # # Given a matrix of m x n...
97180e6aac0dff7e31f913d5f02027a26b7a63f4
jdowers20/2041-ass1
/demo03.py
292
3.75
4
#!/usr/bin/python3 # written by andrewt@cse.unsw.edu.au, adapted # retrive course codes import fileinput, re course_names = [] for line in open("course_codes"): m = re.match(r'(\S+)\s+(.*\S)', line) if m: course_names.append(m.group(2)) for course in course_names: print("%s"%(course))
b925648bfaad882235a27dce43e62d33ce852ffe
vilkoz/wolf3d
/res/gen_map.py
13,617
3.53125
4
#!/usr/bin/env python3 import random def randint(a, b): if a < b: return random.randint(a, b) return a MIN_SIZE = 6 class Node: def __init__(self, x1, x2, y1, y2): self.childs = [] self.border = ((x1, y1), (x2, y2)) self.room = None self.connected = False de...
a4e4a1c1d36af978397f32679aee705f8aaa737a
bonicim/technical_interviews_exposed
/src/algorithms/blind_curated_75_leetcode_questions/longest_substring_without_repeating_characters.py
2,595
4.21875
4
""" Given a string, find the length of the longest substring without repeating characters. Example 1: Input: "abcabcbb" Output: 3 Explanation: The answer is "abc", with the length of 3. Example 2: Input: "bbbbb" Output: 1 Explanation: The answer is "b", with the length of 1. E...
9894f39a43c008d523ac9f4ef4417d796a3b5845
ozan-san/AI-Homeworks
/03-search/heuristics.py
280
3.71875
4
# -*- coding: utf-8 -*- """ Created on Sun Mar 8 16:30:15 2020 @author: Ozan Şan """ from math import sqrt def heur(first, second): ''' Returns Euclidean distance between two points as tuples. ''' return sqrt((first[0] - second[0])**2 + (first[1] - second[1])**2)
8076fc2f60d0526ac5a1feed7941882ebdd72704
luizfranca/project-euler
/python/p09.py
302
4.09375
4
# Special Pythagorean triplet import math def pythagorean_Triplet(n): number = 0 for a in range(1, n): for b in range(1, n): c = math.sqrt(a ** 2 + b ** 2) if c % 1 == 0: number = a + b + int(c) c = int(c) if number == n: return a * b * c print pythagorean_Triplet(1000)
1a3a24db6f4c5c411f0c9564a49e696af941fb4a
ranjuinrush/excercise
/ex4/untitled6.py
215
3.8125
4
# -*- coding: utf-8 -*- """ Created on Tue Jul 24 17:13:38 2018 @author: user """ d={'A':10,'B':20,'C':30} print("Total sum of values in the dictionary:") s=1 for key in d: s=s*d[key] print(str(s))
322b61f918997a09b0311a6e8ec00883b26b4f50
coderwyc/leetcode-python
/sqrt_int.py
505
4.125
4
""" Implement int sqrt(int x). Compute and return the square root of x. """ class Solution: # @param x, an integer # @return an integer def sqrt(self, x): if x == 0: return 0 low = 1 high = x/2 + 1 while(low <= high): mid = (low + high) / ...
236605132158eb24b70e6bd3bb3453f76e8c86f9
munkhtsogt/algorithms
/BackspaceStringCompare.py
658
3.71875
4
class Solution(object): def backspaceCompare(self, S, T): """ :type S: str :type T: str :rtype: bool """ s, t = [], [] for c in S: if c != '#': s.append(c) elif len(s) != 0: s.pop() for c in T: if c != '#': ...
b2c786750783bb2278b97fd5196c5c2c69e52835
tomhettinger/simplestone
/gameboard/Deck.py
467
3.53125
4
from random import shuffle as shuf class Deck(object): def __init__(self, side=None): self.side = side self.cards = [] self.size = len(self.cards) def add_card(self, card): self.cards.append(card) self.size += 1 def draw_card(self): if self.size <= 0: ...
074780e053d5a2d75a4a08f15de0430a06f49bdd
lemzoo/magic-mock
/tools.py
896
3.75
4
#!/usr/bin/env python def add(first_arg, second_arg): return first_arg + second_arg def sub(first_arg, second_arg): return first_arg - second_arg def mul(first_arg, second_arg): return first_arg * second_arg def div(first_arg, second_arg): return first_arg / second_arg class Calculette: de...
db33940855cd12a6675db31ff4f779c1fa75d966
aman-singh7/training.computerscience.algorithms-datastructures
/09-problems/lc_461_hamming_distance.py
1,491
4.21875
4
class Solution_3: """ It optimized the previous solution It uses the trick: """ def hammingDistance(self, x: int, y: int) -> int: # 1. Find x's and y's bits that are different x ^= y # 2. Count the number of 1 bit_1_count = 0 whi...
499b753c4a9a6d2e519f5fd7b215fa55f144df09
mohitreddy1996/GenderFromName
/main.py
482
3.5625
4
from api_classifier import Genderize genderize = Genderize() while True: names = raw_input("Enter Names : (Break if you want to discontinue) ") names = names.split(' ') for name in names: flag, gender, prob = genderize.get_gender(name=name) if flag == 0: print "Name : " + name + ...
15c7fc87068ec2232aaa3c0e541b57873433426a
vishnoiprem/pvdata
/lc-all-solutions-master/053.maximum-subarray/test.py
296
3.578125
4
class Solution: def maxSubArray(self,arr): print(arr) preSum=arr[0] maxSum=arr[0] for j in range(1,len(arr)): preSum=max(preSum+arr[j],arr[j]) maxSum=max(preSum,maxSum) return maxSum if __name__ == "__main__": print (Solution().maxSubArray([-2,1,-3,4,-1,2,1,-5,4]))
f8fe973133b7d30328007b33bcba57b351a92fbc
microprediction/pandemic
/pandemic/city.py
2,938
3.640625
4
import random, math import numpy as np def sprawl( geometry_params, num ): """ Chinese restaurant inspired sprawl model """ r = geometry_params['r'] s = geometry_params['s'] e = geometry_params['e'] b = geometry_params['b'] def bound(pos,b): return ( (pos[0]+b) % (2*b) - b , (pos[1]+b...
e10006587869a9420d9b7032f78472d52086d2db
venkyp1/Misc
/python_bits/dynamic_class_gen.py
1,331
4.25
4
###################################################### # Venky, Tue Aug 22 20:18:30 2017 # ###################################################### #This code to demonstrate ways of how a method can be added to a class instance dynamically (at run time). from types import MethodType class classA : ...
24b399829721b2b76f4b606a19368078a8c347e6
imran9217/oop_practice_M_IMRAN
/TASK/EVEN-ODD-NUMBER-WHILE-LAB-2-TASK.py
713
4.40625
4
#IMRAN LIAQAT #BAIM-S20-003 # EVEN ODD WITH WHILE LOOP ################################################################ Minimum = int(input(" Please Enter the Minimum Value : ")) Maximum = int(input(" Please Enter the Maximum Value : ")) number = 1 Minimum = number while number <= Maximum: if (number % 2...
995a8e5f5ba43db1a0177b4e79512ddf2dd71e3a
piplani/doubly_linked_list
/add_after_given_node.py
1,082
4.25
4
class Node: def __init__(self, data): self.data = data self.next = None self.prev = None class DoublyLinkedList: def __init__(self): self.head = None def printlist(self): temp = self.head while temp: last = temp print temp.data, ...
18b7ebf4d30430b59406c6b3ec5ea1e6f856e19b
Mysyka/Skull
/Школа Х5/Урок 1/loops.py
591
4.15625
4
# Iterating over a single char in the string: for char in '123456789': print(char + '!') # Iterating over a single char in the string: for char in '123456789': if char == '2': continue print(char + '!') count = 10 while count > 0: print(count) count = count - 1 ...
54401806a4486f133fb98f609246f3874ec9bc38
Maarten-vd-Sande/Rosalind-BioInformatics-Stronghold
/REVC/revc.py
310
3.703125
4
""" Solution to: http://rosalind.info/problems/revc/ """ with open("rosalind_revc.txt", 'r') as f: DNA = ''.join(f.readlines()) REV_COMPLEMENT = {'A': 'T', 'T': 'A', 'C': 'G', 'G': 'C'} print(''.join([REV_COMPLEMENT[nuc] for nuc in reversed(DNA)]))
9a0b0db5c01ba78f224f2fe2ec9d189b00e798c4
Mohit-121/Arjuna_files
/Arjuna 25-8-19/DisneyPass.py
703
4.03125
4
def mincostPass(days,costs): ans=[0]*366 #ans is used to store ans for i in range(1,366): if (i not in days): ans[i] = ans[i - 1] #Non travel day cost is same as previous day #On travel day it is minimum of yesterday's cost plus single-day ticket, # or cost for 8 days ago plus 7-day pass...
7c2d8ef6be8537af29d5493613dc72be77c14689
MohamedSafoury/Groking_Algorithms_exercises
/chapter4_QuickSorting/qsort.py
378
3.78125
4
def quickSort(array): #base case if len(array) < 2 : return array #recusive case else : pivot = array[0] less = [i for i in array[1:] if i <= pivot] greater = [i for i in array[1:] if i > pivot] return quickSort(less) + [pivot] + quickSort(greater) print(qu...
c619c12e17c5a738e9c86059a0e82ad2918e53bf
ArjunChattoraj10/AChatt10
/Fun/Name Generator/Name Generator.py
2,950
4.15625
4
import string, random # Functions def length_asker(): """ This function is an i/o function that asks the user for a number that will be the length of the name, and returns the input. Any input that is not a positive integer is rejected and a sarcastic comment is printed, and the user is prompted for a different i...
156ca024e6be1c7f02a133619583f34e79f7d703
NSMobileCS/pyfun
/pyfun10.py
432
3.625
4
from random import randrange def toss5K(): l = [randrange(2) for _ in range(5000)] headcount = 0 for idx, result in enumerate(l): sidename = 'tail' headcount += result if result: sidename = 'head' print("Attempt #{}: Throwing a coin... It's a {}... got {} heads a...
f09129e5e714810d27c980fe29ef30eb8728ee85
Shiji-Shajahan/Python-Programs
/Creating course Report using Sets & Dictionaries.py
4,528
4.8125
5
#Lesson 6 Homework print('Lesson 6 Homework') course_name= "Introduction to Magic" print(f'The course name offered by ReDI School is {course_name}') print(f"This is a report about the \'{course_name}\' course.") print('\n') # Here, we define a list of students in the class. students = ['Michael', 'Kate', 'Scott', 'Lau...