blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
4918d7b880824b5d9f8d99eb20b6b94124f3bb82
Barbariansyah/pyjudge
/test/segiempat/segiempat_7.py
438
3.53125
4
def segiempat_7(n): ret = '' c1 = '*' c2 = '#' if (n==1): ret = c1 elif (n==2): ret = c1+c1+c1+c1 elif (n>2): for i in range(n): ret += c1 ret += '\n' for j in range(n-2): ret += c1 for k in range(n-2): r...
129f133b4d7c7ac05c0dfd37a020fafe203a5f4b
An-ling-TS/LeetCode
/字符串中的单词数.py
665
3.875
4
''' 统计字符串中的单词个数,这里的单词指的是连续的不是空格的字符。 请注意,你可以假定字符串里不包括任何不可打印的字符。 示例: 输入: "Hello, my name is John" 输出: 5 解释: 这里的单词是指连续的不是空格的字符,所以 "Hello," 算作 1 个单词。 ''' import re class Solution(object): def countSegments(self, s): """ :type s: str :rtype: int """ return len(s.split()) if __...
7738d85187b631563aa1801185850aeca18c86b6
liu1002324991/-
/2048.py
5,514
3.703125
4
import random class Game: def __init__(self): self.board_list = [ ['', '', '', ''], ['', '', '', ''], ['', '', '', ''], ['', '', '', ''], ] self.score = 0 #判断空位 坐标 行列 self.board_empty = [] def start(self): ...
7b68ddc7078535eec76ff8db3bda1760324c8bb1
SemsYapar/Basic-HTTP-and-Message-Server
/Server.py
4,233
3.515625
4
#Sems Code #Server import socket class TCPServer: def __init__(self, host): self.host = host def start(self): while True: self.port =input("HTTPServer için ""80"", EchoServer için ""8888"" port numarasını girin ") self.port = int(self.port) #HTTP...
9074a1b18336a11139a9a07e6951f5145e3caab6
TheSundar/euler
/problem41.py
349
3.5
4
import math import itertools def is_prime(n): if n % 2 == 0 and n > 2: return False return all(n % i for i in xrange(3, int(math.sqrt(n)) + 1, 2)) str='987654321' for n in range(9,-1,-1): c=itertools.permutations(str[len(str)-n:], n) for i in c: if is_prime(int("".join(i))): ...
21f553ca47ab6a8c5ce00f4ebbe39b4f57c38d46
sazedul-h/college-python
/chapter7_programs/line_read.py
397
3.796875
4
# this prgram reads and displays the contents # of the philosophers.txt file one line at a time. def main(): # open a file named philosophers.txt infile = open('philosophers.txt', 'r') # read the file's contents line1 = infile.readline() line2 = infile.readline() line3 = infile.readline() ...
f9fe5bf6dbb1839d5aa32c3dab35b6549c6a5448
Isonzo/100-day-python-challenge
/Day 2/Day 2.2 Exercise.py
762
4.34375
4
height = input("Please enter your height in m: ") weight = input("Please enter your weight in kg: ") #Code above can't be changed calculating_bmi = float(weight) / float(height)**2 bmi = str(round(calculating_bmi, 2)) #Under weight is 18.5, normal is 18.5 to 25, Overweight is 25 to 30, Obese is more than 3...
c19a7ebe1f7c194db64931631fe680b042052f6c
vitorpfr/cs50ai
/0-search/degrees/shortest-path-old.py
1,360
4
4
def shortest_path(source, target): """ Returns the shortest list of (movie_id, person_id) pairs that connect the source to the target. If no possible path, returns None. """ # Set goal goal = target # Initialize frontier to just the starting position start = Node(state = source, p...
e24d6f1be4c7ae204cf800b64c15ab6185c14035
CatmanIta/x-PlantForm-IGA
/iga/communication/httpclient.py
2,210
3.5625
4
""" @author: Michele Pirovano @copyright: 2013-2015 """ import urllib2 import urllib class HttpClient: """ Handles communication through http to the web server """ OK = True KO = False def __init__(self, hostName): self.hostName = hostName def destroy(self): pass ...
8c57665054b52c2fca65c6488d5f98feccefb4e8
fatimasalmanmirza/arrays_practice
/pinterest-easy.py
2,100
3.828125
4
def longestCommonPrefix(strs): """Write a function to find the longest common prefix string amongst an array of strings. If there is no common prefix, return an empty string""" if not strs: return "" min_l = min(len(S) for S in strs) for i in range(min_l): s = set() for x in strs: s.add(x[i]) if len...
21416a65f9fa6a262e34f6ff4d49f4ac82fdcc5c
9a24f0/USTH
/AS/generator.py
333
3.984375
4
#!/usr/bin/env python3 group = [] i = 0 g = int(input("Enter generator: ")) base = int(input("Enter base: ")) while True: if str(pow(g, i, base)) not in group: group += str(pow(g, i, base)) i += 1 else: break # Sort for better visualization group.sort() print("Your cyclic group...
bd2b4f80a6d4cc966219113f239cd6af255bbdce
yasssshhhhhh/DataStructuresAndAlgo
/arrays/minimizeTheHeight.py
330
3.78125
4
# def Average(lst): # return sum(nums) / len(nums) # nums = [2, 6, 3, 4, 7,2,10,3,2,1] # nums.sort() # print(nums) # average = Average(nums) # k = 5 # for i in range(len(nums)): # if nums[i] < average: # nums[i]+=k # if nums[i] > average: # nums[i]-=k # if nums[i] == average: # n...
4f183ba19e2aaaa3dff9208d9be59fb145760aad
oftensmile/thunder
/python/thunder/viz/colorize.py
4,175
3.65625
4
from numpy import arctan2, sqrt, pi, array, size, shape, ones, abs, dstack, clip, transpose, zeros import colorsys from matplotlib import colors, cm class Colorize(object): """Class for turning numerical data into colors Can operate over either points or images Parameters ---------- totype : ...
1ea7c254b61751247b8bcee26832806ac3909e6c
Guruscode/getting-started-with-python
/data-types/basics.py
3,757
4.40625
4
# in python, everything is an object a, b, c = 1, 1.0, 'Hello World!' print( type(a), type(b), isinstance( c, str ) ) #---------------------------------------# ''' https://medium.com/@larmalade/python-everything-is-an-object-and-some-objects-are-mutable-4f55eb2b468b # https://stackoverflow.com/a/27460468 # https://s...
cb386aa037f21e994068e0bb508837fcf7d407b6
hwang018/Leetcode
/339. Nested List Weight Sum/.ipynb_checkpoints/solution-checkpoint.py
426
3.5
4
class Solution: def depthSum(self, nestedList: List[NestedInteger]) -> int: def dfs(nestedList, depth): total = 0 for element in nestedList: if element.isInteger(): total += (element.getInteger() * depth) else: t...
512ae24981a90f8832ba58e329c0e9c2460c1cf5
SarmenSinanian/Intro-Python-II
/src/adv.py
3,619
3.96875
4
from room import Room from player import Player # Declare all the rooms room = { 'outside': Room("Outside Cave Entrance", "North of you, the cave mount beckons"), 'foyer': Room("Foyer", """Dim light filters in from the south. Dusty passages run north and east."""), '...
bb22b6adbf00fedd5940ebc60313b5aba2de0696
tsushiy/competitive-programming-submissions
/AOJ/AOJ vol.28/aoj2881.py
185
3.578125
4
while True: s = input() if s=="#": break g, y, m, d = s.split() y, m, d = int(y), int(m), int(d) if y>=32 or (y==31 and m>=5): g = "?" y -= 30 print(g, y, m, d)
5fc14c440079923decd9c052539542135ce9180e
xmhGit/exercise_python_summer_school
/python/ex2_earth.py
1,275
4.15625
4
import numpy as np from sys import argv def cal_cir(r): cir = 2*np.pi*r*10**3 return cir # script,r = argv # r = float(r) # argv's method also input the type of string # pi=3.14 # constant pi # r=6378 # the radius of the earth's equator, unit: km\ # r = float(raw_input("Input the radius of the earth(unit:km):\n"...
cba5f6f13b55032eb738895058b7fe9ecc994c22
spencerdispenced/Snake
/Images/draw_image.py
660
3.609375
4
""" Script to draw background images """ import pygame def draw_background(): """ Draw image of certain color, in checkered pattern """ surface = pygame.display.set_mode((480, 480)) for y in range(0, 480): for x in range(0, 480): if (x + y) % 2 == 0: # every even square ...
d6f5ea2ffb331a0746b3a8cb7669716379aeac73
tmnik/Python_HSE
/round_rus.py
216
3.5625
4
#округление по русским правилам from math import floor, ceil n = float(input()) r = n - int(n) a = float('{0:.1}'.format(0.5)) if r >= a: print(ceil(n)) elif r < a: print(floor(n))
70c5d6d671ead348a8dd858e4efaf87699a7efcc
HenryBalthier/Python-Learning
/Leetcode_easy/hash/242.py
325
3.5625
4
class Solution(object): def isAnagram(self, s, t): """ :type s: str :type t: str :rtype: bool """ l1 = sorted(s) l2 = sorted(t) return l1 == l2 if __name__ == '__main__': s = Solution() s2 = "anagram" t = "nagaram" print(s.isAnagram(s2...
33ed8bf54750f59ef0d407f682845cf2b13be458
Sildinho/PPBA2021_AndreIacono
/ppybaAndreIacono_79.py
975
4.5
4
# -- coding utf-8 -- """ Udemy - Programação Python do Básico ao Avançado 2021 - Andre Iacono - Seção 10: OOP (Python Object-Oriented Programming) - Aula: 79 """ # 79. Criando Construtores # classes # utilizamos para criar objetos (instances) # objetos sao partes dentro de uma class (instancias) # classes...
257211fd157a6ed74ceb4be2a9d7991ab346f209
ngocdang1999/project_euler
/bai-20.py
157
3.5
4
a=0 b=1 for i in range (100): if i>1: b=b*i print b str1=len(str(b)) str2=str(b) for i in range (1, str1+1): a=a+int (str2 [i-1]) print a
8b5e87ff30d31335a16f84dba140e713ef9b401d
medasuryatej/infix_to_postfix
/infix_to_postfix.py
5,448
3.609375
4
# Need the below package for printing the output in a tabular format try: import sys from prettytable import PrettyTable except ImportError as e: print (f"Missing Python package for {e}") print ("pip install prettytable") sys.exit() __author__ = "Meda Sai Krishna Pavan Suryatej" __contact...
2750c59ce5fc52652913b4809de3ed5e893ec779
faroit/audiomate
/audiomate/utils/jsonfile.py
655
3.984375
4
""" This module contains functions for reading and writing json files. """ import json def write_json_to_file(path, data): """ Writes data as json to file. Parameters: path (str): Path to write to data (dict, list): Data """ with open(path, 'w', encoding='utf-8') as f: js...
fae11c8f87362de031fb1235bd5494d9ad433005
JayWelborn/ChooseYourOwnAdventure
/ChooseYourOwnAdventure/story_fragment/story_fragment.py
1,771
3.703125
4
from string import ascii_uppercase import sys from typing import Mapping, List from .choice import Choice from prompt_reader.prompt_reader import PromptReader class StoryFragment: """Class to represent one fragment of a Choose Your Own Adventure Story. StoryFragments are composed of one Prompt, and an array ...
8f3bda04e66dfd3e6cab6ae96ab5eb22713f7a35
GGRMR/python-study
/homework/stack_functions.py
493
3.96875
4
# -*- coding: utf-8 -*- """ stack_functions 함수와 리스트를 이용해서 스택 구현하기 @author: Park Jieun """ def pop(stack = []): #== def pop(stack) stack.pop() return stack def push(stack = []): value = input("PUSH: ") stack.insert(len(stack)+1, value) return stack def stack_list(stack = []): print("stack = ...
cea57511f74a87fe06cd42d03a3b716ba0389424
Rahul0506/Python
/Worksheet2/13.py
586
3.890625
4
number = int(input("Please enter a positive integer: ")); a = 2; def checkPrimeRec(number, current): if current > (number**0.5 + 1): return True; elif number == 1: return False; elif (number % current) == 0: return False; else: current += 1; return checkPrimeRec(number, current); def che...
4b4d16930ed4947a4149f009c2518f700ac050dc
digant0705/Algorithm
/LeetCode/Python/158 Read N Characters Given Read4 II.py
1,563
3.71875
4
# -*- coding: utf-8 -*- ''' Read N Characters Given Read4 II - Call multiple times ====================================================== The API: int read4(char *buf) reads 4 characters at a time from a file. The return value is the actual number of characters read. For example, it returns 3 if there is only 3 char...
cbf37c978635e2b81e716c5543e461d8f6c80496
Shraddhasaini/Project-Euler
/x014.py
352
3.5625
4
def collatz(n): lst = [] while n > 1: lst.append(n) if (n % 2 == 0): n = n//2 else: n = 3*n +1 lst.append(1) return lst def number(): dict = {} for i in range(1,1000000): x = len(collatz(i)) dict.update({i : x} ) return max(dic...
f898f78a6d479b0971b2dc58d9c837a46ef4db5a
FeHeap/PythonPractice
/basic/ShoppingCart.py
1,159
4.15625
4
# -*- coding = utf-8 -*- # @Time: 2021/7/9 上午 05:07 # @Software: PyCharm products = [["iphone",6888],["MacPro",14800],["Mi6",2499],["Coffee",31],["Book",60],["Nike",699]] print("----- product list -----") for index,product in enumerate(products): if(len(product[0]) < 6): print("%d %s\t\t%d"%(index,product[...
8c9824e79adaffc0d82b70faf2fbf5cd8b5fc11e
keerthz/luminardjango
/Luminarpython/collections/listdemo/pattern.py
170
3.65625
4
lst=[3,5,8]#output[13,11,8] #3+5+8=16 #16-3=13 #16-5=11 #16-8=8 output=[] total=sum(lst) for item in lst: num=total-item#16-3=13 output.append(num) print(output)
be4573d83712bac861c3f3f64ff4595396e9ce8c
SamGoodin/c200-Assignments
/LectureCoding/11-2.py
909
3.546875
4
#Stack LIFO (Last In, First Out) #s = stack() #Queue #s.push(23) [23] #s.push(45) [45, 23] #s.push(67) [67, 45, 23] #s.pop() = 67 [45, 23] #s.empty() True if stack is empty, False if not. class MyStack: def __init__(self): self.stack = [] def push(self, x): self...
abcbd91b0f00d035f7a20de6fa1abdd89f0e2eeb
jemappellesami/INFOH410
/TP_S/src/tp_s_template.py
1,842
4.03125
4
#!/usr/bin/python3 import queue import heapq from collections import deque def q1(): print("Q1:") # using a stack: d = [] # ... # using a queue # ... # using a PrioQueue or heapq # ... def q3(): """the graph can be stored using a adjency list or an adjency matrix. Usually, ...
dda61d3335ef8d2c05d9b6a52edc3f0992b05a08
TomNguyen-0/Artificial-Intelligence
/checkers/src/abstractstrategy.py
3,656
3.921875
4
''' Created on Mar 1, 2015 @author: mroch ''' import checkerboard class Strategy: """"Abstract strategy for playing a two player game. Abstract class from which specific strategies should be derived """ def __init__(self, player, game, maxplies): """"Initialize a strategy pla...
8110fe506f72becfbc1b44d453af8950adbab328
ColeAnderson7278/Daily_Practice
/practice_5-03/prac.py
914
3.890625
4
def find_streak(arr): longest_streak = [] current_streak = [] for n in arr: if len(current_streak) == 0 or n in current_streak: current_streak.append(n) if len(current_streak) > len(longest_streak): longest_streak = current_streak elif len(current_stre...
b084fe23a8094f9fe76d383817ae38090df9b0d4
Alb4tr02/holbertonschool-machine_learning
/math/0x00-linear_algebra/5-across_the_planes.py
474
4.0625
4
#!/usr/bin/env python3 """function def def add_matrices2D(mat1, mat2): adds two 2D matrices:""" def add_matrices2D(mat1, mat2): """INPUT: two arrays OUTPUT: two arrays element-wise added: """ if len(mat1) != len(mat2) or len(mat1[0]) != len(mat2[0]): return None result_matrix = [] f...
c92ac0e263ad9cc2f42dba650618f3e8d025c0e4
taritro98/DSA_Prac
/thirdlargest.py
316
4.15625
4
def thirdLargest(arr): x = max(arr) arr.pop(arr.index(x)) maxval = 0 for a in arr: if a>maxval: maxval = a arr.pop(arr.index(maxval)) maxval = 0 for a in arr: if a>maxval: maxval = a return maxval print(thirdLargest([2,4,1,3,5]))
75d63e5f856162cb843e4c1081e301b544a761ea
pandyakavi/Data-Structure
/Stack_Class.py
407
3.75
4
# Peek, Pop, isEmpty, Push, size() class Stack_Class: def __init__(self): self.items = [] def Peek(self): return self.items[-1] def Pop(self): #k = self.items[-1] #self.items.remove(k) return self.items.pop()#k def isEmpty(self): return self.items == [] def Push(self,val): self.items.append(val...
6e48785ebb7cba78c490bfccb5856b410e795ef0
willreadscott/Convex-Hulls
/grahamscan_t.py
4,514
4
4
""" Graham-scan Algorithm Tester Author: William Scott Date: 01/06/2015 Student Number: 11876177 """ import sys import operator import math def file_to_points(): """Converts file into usable points""" points = [] file = open(sys.argv[1]) # First line not needed for how .dat file is re...
dd406bbda6c56415beb0e1594cd8043b6590c269
chyavan-mc/My-Solutions-to-Leetcode-problems-using-Python-3
/Palindrome Linked List.py
980
3.75
4
# Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: def isPalindrome(self, head): """ :type head: ListNode :rtype: bool """ lis = [] ptr = head while(ptr!=None):...
d9c57a52b0e16c410d5012a5b9ca3f08a6e6d950
somuchpancakes/Py_Expense_template
/expense.py
1,452
3.609375
4
import os import csv from PyInquirer import prompt expense_questions = [ { "type":"input", "name":"amount", "message":"New Expense - Amount: ", }, { "type":"input", "name":"label", "message":"New Expense - Label: ", }, { "type":"list", ...
7ddaaaf78b7d6941276c049a2f3f032df83a39ae
razorRun/ud036_StarterCode
/media.py
439
3.640625
4
class Movie(): def __init__(self, title, year, trailerUrl, boxUrl, screenWriter): """This class can be used to create instence of movies, consttructor can be called using Movies(title, year, trailerUrl, boxUrl, screenWriter)""" self.title = title self.year = year sel...
46c1b23eddf9d2243d1a9bbc4b47422a4277690c
YannCedric/Machine-Learning
/Main.py
4,368
3.546875
4
# -*- coding: utf-8 -*- from graphics import * from random import randint import math # init pop def create_person(): num = randint(0,4) return num def _init(pop_size, dna_size): poputation = [] for i in range(pop_size): new_dna = [] for j in range(dna_size): new_person = ...
d70ea3fc9401f2f7244093d7edbf14bd2e39f400
sravi97/I210_Information_Infrastructure1
/Lecture/Lecture 18/selection_starter.py
1,233
4.46875
4
#import the tools file so we can use swap from tools import * #define a function called selection_sort that takes a list of items def selection_sort(items): # make a copy of the list so we don't destroy the original data # because lists (like items) pass by reference ordered = items.copy() # ...
aac625c0417676c6f4f501612dbb16933453dfb9
AcubeK/LeDoMaiHanh-Fundamental-C4E23
/Season 4/D4/ex_2.py
534
3.640625
4
p = [ { "Name": "Huy", "Hours": 30, "MPH":50, }, { "Name": "Quan", "Hours":20, "MPH": 40, }, {"Name": "Duc", "Hours": 15, "MPH": 35, } ] print("Numbers of hours of each person:") for q in p: print(q["Name"], q["Hours"], sep = ": ") print() print("Wage of ...
249bb62d7426492303300ef436751c1ae7430e3f
drahmuty/Algorithm-Design-Manual
/03-26.py
2,280
4.28125
4
""" 3-26. Reverse the words in a sentence. i.e., My name is Chris becomes Chris is name My. Optimize for time and space. """ # Reverse the words in a sentence def reverse_sentence(sentence): # Create sentence object and linked list sentence_obj = Sentence(sentence) sentence_list = LinkedList() # Ad...
5fc239aa51f5e3396d37468f3fbb654a9cfc86bd
TechInTech/Interview_Codes
/杂题/LinkNodeCopy.py
1,039
3.5
4
# -*- coding:utf-8 -*- class LinkNode: def __init__(self, val=None, next=None): self.val = val self.next = next class CreateLink: def __init__(self, lyst): self.lyst = lyst self.length = len(lyst) def get_link(self): p = link = LinkNode() i = 0 whil...
0ae6e70b0ce1e2dc8a99e7badb8d295049c0b8ec
JosephLevinthal/Research-projects
/5 - Notebooks e Data/1 - Análises numéricas/Arquivos David/Atualizados/logDicas-master/data/2019-1/224/users/4345/codes/1692_1099.py
629
4.03125
4
from math import* # Leitura dos lados do triangulo a, b, and c a=float(input("Lado 1: ")) b=float(input("Lado 2: ")) c=float(input("Lado 3: ")) print("Entradas:", a, ",", b, ",", c) if (a>0) and (b>0) and (c>0): # Testa se medidas correspondem aas de um triangulo if ((a < b+c) and (b< c+a) and (c<a+b)): if ((a==b ...
5dd06da63a2e0d506a95e63180bdc1668f84d746
rajeshvermadav/XI_2020
/controlstatements/oddnumber1_8.py
102
3.984375
4
#display odd numbers 1 to 8 for y in range(1,9,2): print("odd numbers between 1 to 8:-",y)
f56d2a93c288e04901e4efedc369f3ea705c9d34
christostsekouronas/learnpython
/second/challenge.py
226
4.1875
4
name = input("Please enter your name: ") age = int(input("How old are you? ")) if 18 <= age < 31: print("Welcome club 18-30 holidays, {0}".format(name)) else: print("I'm sorry, our holidays are only for cool people")
f2cbee3f72ab72282bb4b169792864cdf52b21ce
vilvamoorthy/Python
/Numerical Tables.py
157
3.90625
4
# Enter the table number: num = int(input("Enter the table number you want: ")) # Using for loop: for i in range(1, 11): print(num, "x", i, "=", num*i)
078c0d5f4f664b34eda46f5ee586716acb6daf5a
moshekagan/Computational_Thinking_Programming
/frontal_exersices/recitation_solutions_2/ex2_part_B.py
579
4.3125
4
number = input("Insert a 3 digits number: ") if len(number) != 3 or not number.isdigit(): print("Invalid input") else: number = int(number) first_digit = number // 100 second_digit = number // 10 % 10 third_digit = number % 10 is_middle_greater = second_digit > first_digit and second_digit > ...
2aaba7f2b33584f4c9226254025af78706f02747
terrantsh/Python--
/third/func.py
1,243
4.09375
4
#-*- coding = utf-8 -*- #@Time : 2020/4/28 8:24 #@Author : Shanhe.Tan #@File : func.py #@Software : PyCharm ''' #函数的定义 def printinfo(): print("---------------------") print(" Hello World ") print("---------------------") #函数的调用 printinfo() ''' ''' #带参数的函数 def add2Num(a, b): c =...
7e18e1076e272a3d0966ae631445c92345040e0b
saiteja2816/guva
/sort.py
236
3.640625
4
list=[int(x) for x in raw_input().split()] a=[] for num in range(len(list)): for i in range(num+1,len(list)): if(list[num]==list[+i]): a.append(list[num]) l=set[a] for i in range(len(l)): print(l[i],end=" ")
789628ac0da916322971d0bcfca85d3391f60899
Cking351/Sprint-Challenge--Data-Structures-Python
/reverse/reverse.py
1,524
4.03125
4
class Node: def __init__(self, value=None, next_node=None): self.value = value self.next_node = next_node def get_value(self): return self.value def get_next(self): return self.next_node def set_next(self, new_next): self.next_node = new_next class LinkedList...
48a73dc8d8f03be39a6b86dd3c4a16a7aef04822
OdedraBharat303/data-science
/core-python/loop1.py
86
3.734375
4
a=int(input("enter number :")) i=1 s=0 while i<=a : s=s+i i=i+1 print(s)
7945dbddc5968844ee50f380dbb84f617b56adc6
Pavche/python_scripts
/counter.py
182
3.890625
4
def count(sequence, item): result = 0 for elem in sequence: if elem == item: result += 1 return result print count(['one','two','three',1,2,3,'one','two'],"three")
4589c495e72c94032e6a7e48764e4a9ada33edb1
vishalb007/Assignment3
/Assignment3_2.py
450
3.875
4
def GetElements(num): lis=[] for i in range(num): print("Enter element : ",i+1) n=int(input()) lis.append(n) return lis def Max(lis,num): max=lis[0] for i in range(num): if(lis[i]>max): max=lis[i] return max def main(): num =int(input("Enter number of elements : ")) lis=[] print(...
5f489efa8461791bd1255c4854a21949e5b4eb88
avdg/pysudokudemo
/sudokuSolver.py
4,139
4
4
""" Specialised in solving sudoku's """ class SudokuSolver: """ Constructor """ def __init__(self): self.reset() """ Resets the sudoku status for a normal 9x9 grid sudoku """ def reset(self): self.sudoku = [[range(1, 10) for y in range(9)] for x in range(9)] self.relation = { ...
238d63d161e3bfd1ef353088992f9f50a7d4d621
Jasonhou209/notes
/leetcode/20_valid_parentheses.py
1,284
3.96875
4
""" 20.给定一个只包括 '(',')','{','}','[',']' 的字符串,判断字符串是否有效。 有效字符串需满足: 1. 左括号必须用相同类型的右括号闭合。 2. 左括号必须以正确的顺序闭合。 注意空字符串可被认为是有效字符串。 示例 1: 输入: "()" 输出: true 示例 2: 输入: "()[]{}" 输出: true 示例 3: 输入: "(]" 输出: false 示例 4: 输入: "([)]" 输出: false 示例 5: 输入: "{[]}" 输出: true """ class Solution: def __init__(self): self.d =...
a01c2066969ed2af100cb2e668ed50845375ef49
py-john/workoutloader
/workout.py
1,594
3.890625
4
#!/usr/bin/env python3 """workout.py: Opens video files for daily workouts based on a workout calendar. """ from time import sleep from datetime import datetime import create PROGRAM_START_DATE = datetime(2018, 3, 19, 5, 0) def print_calendar(day): """Draws a calendar with X's for completed days""" print(...
269072279248f97df7c6a7595d8b527be56d494f
artkpv/code-dojo
/yandex.ru/Yandex2016Algo/pr3_shashmati.py
6,185
3.625
4
""" https://contest.yandex.com/algorithm2016/contest/2497/problems/C/ Строить дерево ходов. Для текущего хода кого-нибудь, найти такой ход при котором будет выигрыш, knight (w), shashka (black) a b c d 1 2 3 w 4 b 0 a3, b4, b (a3) 1 a3, c3, w 2...
961b9352e6c975d49d366d149a044eb2683b8a15
gordonje/dl_depository
/utils.py
515
3.640625
4
from datetime import timedelta def time_diff (tdelta): # if more than a day if tdelta.total_seconds() > 86400: return '{} days'.format(abs(tdelta.total_seconds() / 86400)) # if more than an hour elif tdelta.total_seconds() > 3600: return '{} hours'.format(abs(tdelta.total_seconds() / 3600)) # if more than a ...
a01d26c64c94877bb4a46aed37d912a6aabdcd82
aleksamarkoni/uvasolutions
/10646 - What is the Card/main.py
3,757
3.984375
4
import sys class Card(object): """Represents a standard playing card. Attributes: suit: integer 0-3 rank: integer 1-13 """ suit_names = ["C", "D", "H", "S"] rank_names = [None, None, "2", "3", "4", "5", "6", "7", "8", "9", "T", "J", "Q", "K", "A"] def __...
4957f01191aa20a4f752908b89ad57b08c384dda
s654632396/learnPython
/regularExpression/p1.py
376
3.6875
4
# coding=utf-8 import re str1 = 'StuDy python' # print str1.startswith('study') # print str1.endswith('python') # # p = re.compile(r'study', re.I) # m = p.match(str1) # print m.group() # print m.span() # print m.string # p = re.compile(r'_') # m = p.match('this is a _string') # print m.group() # err ,m is None # ...
fb8d0486394b4d0137e7e5c27dea43f2f9f89945
guys79/SerachEngine
/StopWordsHolder.py
885
3.953125
4
# This class will save the stop words in a list so we can access the list fast class StopWordsHolder: list_of_stop_words = [] # this list will contain all the stop words # The constructor will initialize the list with the stop words def __init__(self): try: file = open("stop_words.txt"...
31d7796e61cecd875c2aab6a7bfcc3f7c6b6e078
stuycs-softdev-2014-2015/classcode
/fall-5/tdd/utils1.py
838
3.71875
4
def validate_password(pword): if len(pword)<6 or len(pword)>8: return False return True def test_password_length(): r1 = validate_password("aaa") if r1 != False: print "short password test failed" else: print "short password test passed" r2 = validate_password("aaa...
59b08bedd46f3c4ae4ddca84107f393cc3a3086c
kavikamal/PythonPractice
/rna-transcription/rna_transcription.py
570
3.8125
4
def to_rna(dna_strand): dna_strand = dna_strand.upper() rna_strand="" for i in dna_strand: if i=="G": rna_strand = rna_strand + "C" elif i=="C": rna_strand = rna_strand + "G" elif i=="T": rna_strand = rna_strand + "A" elif i=="A": r...
b31458154872a18e572992f676e0481c2c95192d
SebasBaquero/taller1-algoritmo
/uri_juego/punto1002.py
68
3.734375
4
r= float(input()) a= 3.14159*(r**2) print("A="+'{:.4f}'.format(a))
9fb876bbed1ee65bde603cb7b7faae9e2f8d339b
judong93/TIL
/algorithm/0824~/0826/중위순회.py
610
3.59375
4
def inorder(n=1): if n: inorder(left[n]) print(word[n], end='') inorder(right[n]) for tc in range(1, 11): N = int(input()) arr = [list(input().split()) for _ in range(N)] word = [0] left = [0] * (N+1) right = [0] * (N+1) for i in arr: word.append(i[1]) fo...
ab993d54196604e168dadd5490ae44f0345500c6
blairza/01-IntroductionToPython
/src/m6_your_turtles.py
1,829
3.703125
4
""" Your chance to explore Loops and Turtles! Authors: David Mutchler, Vibha Alangar, Matt Boutell, Dave Fisher, Aaron Wilkin, their colleagues, and Zane Blair. """ ######################################################################## # DONE: 1. # On Line 5 above, replace PUT_YOUR_NAME_HERE with your o...
6d055210a9a31326f748511302d219d25ca7b6ab
bl4cklabel88/Network-Tools
/PycharmProjects/Password_Cracker/password_cracker_all.py
2,477
3.625
4
#!/usr/bin/env python # Doesnt work right now.... import hashlib counter = 1 available_hashes = hashlib.algorithms_available pass_in = raw_input("Please enter the Hash: ") hash_type = raw_input("From the following list: " + '\n' + str([ 'md4', 'md5', 'sha1', 'sha224', 'sha384', 'sha256', ...
c471bdf7f6e66dc14a661bec51eda019686b4572
pars3c/model_weight_improvement_1
/__main__.py
1,053
3.890625
4
import numpy as np # learning rate value learn_rate = 0.01 # Input pretended target target_value = input("Insert the number value of your target: ") # turn input str into integer target_value = int(target_value) # number of epochs epochs = input("Insert the number of cicles( Remember, the more ammount of cicles ...
03c3b033e8ed361308fa763621355b975c214db1
amanprakash9299/pythonacadview2
/class 6/q3.py
131
3.953125
4
l=[] for x in range(5): l.append(int(input("enter the number:"))) print(l) l1=[] for x in range(5): l1.append(l[x]**2) print(l1)
3aff6257c145cbe3d6bc5d4485125acd6309374d
evantoh/unittest
/contact_test.py
3,635
3.703125
4
import unittest # Import the unittest module import pyperclip from contact import Contact #Importing the contact Class class TestContact(unittest.TestCase): ''' Test class that defines test cases for the contact class behaviours. Args: unittest.TestCase: TestCase class that helps in creating test ca...
ddef8f70281c53b3c948d65a2a40b1df8f370e6e
dansmyers/IntroToCS
/Examples/2-Conditional_Execution/fortune.py
742
4.0625
4
""" Print a randomly chosen message each time the program is run. """ # Import the random function from the random module from random import random # Generate a random value in [0, 1) r = random() # Use r to choose one of the output options if r < .20: print("The course of true love never did run smooth. - A Mid...
69f03aaefcca27e575021ce3b78ecf6b9ac799be
yatengLG/leetcode-python
/question_bank/lowest-common-ancestor-of-a-binary-search-tree/lowest-common-ancestor-of-a-binary-search-tree.py
2,009
4
4
# -*- coding: utf-8 -*- # @Author : LG # Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None """ 执行用时:80 ms, 在所有 Python3 提交中击败了99.61% 的用户 内存消耗:17.7 MB, 在所有 Python3 提交中击败了86.69% 的用户 解题思路: 因为是二叉搜索树,左节点值必定小于...
628bdae5e9f30dd7eea6d4936f4a6048efa4ea6c
Catarina607/Python-Lessons
/exer02.py
667
4
4
def do_n(n): if n <= 0: return if n > 0: print(n) do_n(n - 1) # do_n(n - 1) def robot(): x = '' while x != 'okay!': x = input('can i have the control of the whole world ?'.lower()) if x != 'okay': print('just say okay. '.lower()) if x ...
87f29e22fdb3f68ef94366543805b0578bdda3df
Alek-dr/GraphLib
/core/algorithms/connected_components.py
1,301
3.515625
4
from collections import deque from typing import Generator, Set, Union from core.graphs.graph import AbstractGraph, edge def _dfs( graph: AbstractGraph, origin: Union[str, int], target: Union[str, int] = None, ): if (target is not None) and (not graph[target]): raise Exception("There no targe...
c1b8fb35f3fe6c0acb4eeb8e2421f3a975c63dcc
Rafaheel/Curso-de-Python
/30-exercicio.py
229
4.03125
4
# programa deve ler se um numero é par ou ímpar n = int(input("Digite um numero: ")) resultado = n % 2 if resultado == 0: print(f"O numero escolhido é par") else: print(f"O numero escolhido é impar")
5ffdeb0b3078c85ac854422097275a7cb92e4088
gomanish/Python
/basic/4th.py
366
4.09375
4
# Pig Latin problem def piglatin(word): first_letter = word[0] if first_letter[0] in 'aeiou': pigword = word + 'ay' else: pigword = word[1:] + first_letter + 'ay' print(pigword) ''' if word start with vowel ,add 'ay' to end if word do not start vowel ,put first letter at the end ,then add 'ay' ''' piglati...
f3d28e76d47f52fec0742a76f37c75a16295bd20
KVooys/AdventOfCode2015
/day21.py
10,205
3.5
4
""" --- Day 21: RPG Simulator 20XX --- Little Henry Case got a new video game for Christmas. It's an RPG, and he's stuck on a boss. He needs to know what equipment to buy at the shop. He hands you the controller. In this game, the player (you) and the enemy (the boss) take turns attacking. The player always goes first...
85d5b95d660f4d035cb319f7bdd94f9953ddb24b
dhimanmonika/PythonCode
/Regex/Substring.py
292
3.984375
4
"""You are given a string . Your task is to find the indices of the start and end of string in .""" import re S,k=input(),input() results= list(map(lambda x:(x.start(1),x.end(1)-1),re.finditer(r"(?=(%s))"%k,S))) if results: for x in results: print(x) else: print("(-1, -1")
63f444bb548d5f5e0342764419f31a5ba90ddf9d
steslic/markov_stock
/matrix_ops.py
3,883
3.609375
4
import numpy as np import warnings def swapRows(A, i, j): """ interchange two rows of A operates on A in place """ tmp = A[i].copy() A[i] = A[j] A[j] = tmp def relError(a, b): """ compute the relative error of a and b """ with warnings.catch_warnings(): warnings.sim...
6f58de063d077045a233b52849866d620d53f88e
TimWeiHu/Guess_number
/guess.py
527
3.84375
4
import random m = input('請輸入數字範圍下限:') M = input('請輸入數字範圍上限:') m = int(m) M = int(M) num = random.randint(m, M) count = 0 while True: count = count + 1 print('') print('第', count, '次') guess = input('請猜數字:') guess = int(guess) if guess < num: print('答案比', guess, '大') elif guess > num:...
ce4cd862f219633350a8837c87f5be75f8245905
omakasekim/python_algorithm
/01_알고리즘 구현/알고리즘구현복습/정렬알고리즘들.py
6,429
4.0625
4
# 선택정렬 def selection_sort(list): ans = [] while list: min_value = list[0] for num in list: min_value = min(min_value, num) ans.append(min_value) list.remove(min_value) return ans array = [3, 6, 2123, 4, 76, 47, 2, 94, 143, 2, 5] print(selection_sort(array)) # Ti...
2aa6ddcf7fa852827846cbbea0a9fd49a3017d47
JuyeoungJun/algorithm
/pretest/SamsungTest1.py
1,400
3.65625
4
#def dfs(graph, start, goal): def dfs_paths(graph, start, goal): st = [] st = st+graph[start] visit = [] while st: a = st.pop() if a == goal: return 1 if a not in visit: visit.append(a) st.extend(graph[a]) return 0 def bfs(graph, start_nod...
011a019a4f4096149d6f3315fb239903942b2af8
higashigawa/add_password
/add_password.py
193
3.640625
4
import string import random chars = string.ascii_letters + string.digits #print(random.choice(chars)) n = 8 s = '' mystr = s.join([random.choice(chars) for i in range(n)]) print(mystr)
9f3b93d324c3a9a38f7c5e5d0ed846e2a5cbf86e
vpc20/python-misc
/FlattenGenerator.py
514
3.921875
4
# def flatten(lst): # for item in lst: # if isinstance(item, list): # for i in flatten(item): # yield i # else: # yield item def flatten(lst): for e in lst: if isinstance(e, list): yield from flatten(e) else: yield...
e0718c4da08f34fa622e4f2ec51ba0f199c25992
DylanPerdigao/TreesDataStructures
/LinkedList.py
3,372
3.75
4
#!/usr/local/bin/python3.8 # -*- coding: utf-8 -*- import sys import os import re import time import random class Node(object): def __init__(self, word, line): self.word = word self.line = [line] self.right = None class LinkedList(object): def insert(self, root, word, line): if root == None: return Node(...
a394501e390797b6659d7b0a2cd4db644fd627a1
picuzzo2/Lab101and103
/Lab9/Lab09_1_600510532.py
657
3.5625
4
#600510532 SEC1 def main(): n = int(input()) square_frame(n,sep = ' ') def square_frame(n, sep=' '): start = 1 stop = (n*n) - (n-2)*(n-2) for i in range(n-1): print('%02d'%start,end='') print(sep,end='') start += 1 print('%02d'%start) start+=1 for i in rang...
862ada0946b8057ccf30bb2170451b64fb23229b
Jane-Zhai/target_offer
/eg_47_gift.py
1,346
3.546875
4
""" 在一个mxn的棋盘的每一格都放有一个礼物,每个礼物都有一定的价值(价值大于0),你可以从棋盘的左上角开始拿格子里的礼物,并每次向右或者向下移动一格,直到到达棋盘的右下角。给定一个棋盘及其上面的礼物,请计算你最多能拿多少价值的礼物? 解题思路:这是一个典型的能用动态规划解决的问题。 定义f(i,j)表示到达坐标(i,j)的格子能拿到的礼物总和的最大值。则f(i,j)=max(f(i-1,j),f(i,j-1))+gift(i,j) 利用循环写代码较为高效。 """ def maxGift(array, row, col): if array==[] or row<=0 or col<=0: retu...
2a089e1d341415edea70a862e0bdb75b9eeb20e8
etrochim/Project-Euler
/problem41.py
708
3.859375
4
#!/usr/bin/env python def eratosthenes_sieve(n): # Create a candidate list within which non-primes will be # marked as None; only candidates below sqrt(n) need be checked. candidates = list(range(n+1)) fin = int(n**0.5) # Loop over the candidates, marking out each multiple. for i in xrange(2...
630ce3ca780f6143e0f3f251bab264cfcdfdda98
FibreBit/Computer-Applications
/Year 3/CA314 OO Analysis and Design/src/Rack.py
1,766
3.5625
4
from Board import * import pygame import random class GameObject: """ Parent class """ def __init__(self, x=0, y=0): self.x = x self.y = y def update(self): pass def draw(self): pass class Rack(GameObject): """ Class to create the rack ...
b5a4eae2c533e520b0dc97919cfc863569ff9262
noym94/noy_repo
/openUni/Data_structures_and_Algorithms/maman14.py
2,363
3.640625
4
import mmh3 import sys from nodes import SingleLinkedList from nodes import ListNode def main(): # get m and K fro the user global m global K global T m = int(input("Insert the value of m: \n")) K = int(input("Insert the value of K: \n")) # initialize T array T = [{"Key": 0, "Valu...
a299f09fc986a558bd56b8c76757d694948bda9d
garimasinghgryffindor/holbertonschool-machine_learning
/supervised_learning/0x11-attention/11-transformer.py
2,156
3.53125
4
#!/usr/bin/env python3 """ Creates encoder for transformer """ import tensorflow as tf Encoder = __import__('9-transformer_encoder').Encoder Decoder = __import__('10-transformer_decoder').Decoder class Transformer(tf.keras.layers.Layer): """ Class to create an encoder for a transformer """ def __init...
00de4f55ab4384d085f423a248e9e894049a51f5
Al153/Programming
/CPU 10/Original Python Emulator/Memory.py
1,516
3.859375
4
def append_bytes(byte_list): """converts a list of bytes (such as on a bus) to a binary value""" result = 0 for byte in byte_list: result<<=8 result += byte return result def bytify(binary): """turns a number into bytes""" bytes = [0,0,0,0] i = 3 while binary: bytes[i] = binary&255 binary >>= 8 i -= ...
87fe801e002f882982bd77b8a6a90532a027cbd8
xtreia/pythonBrasilExercicios
/02_EstruturasDecisao/09_ordem_descrescente.py
581
4.0625
4
num1 = int(raw_input('Informe um numero: ')) num2 = int(raw_input('Informe outro numero: ')) num3 = int(raw_input('Informe mais um numero: ')) if (num1 >= num2) and (num1 >= num3): print num1 if (num2 >= num3): print num2 print num3 else: print num3 print num2 elif (num2 >= ...
b4c90bedfbe45457d3364be29dace775ab856200
AdamZhouSE/pythonHomework
/Code/CodeRecords/2640/60705/258421.py
483
3.546875
4
def contains(a, b): for i in range(0, len(b)): if b[i] not in a: return False return True s = input() t = input() sub = [] for i in range(0, len(s)): for j in range(i+1, len(s)+1): if contains(s[i:j], t): sub.append(s[i:j]) if len(sub) == 0: print("") else: ...