blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
b13a000c04a31069ef7492ca6a436aa88000b091
zack4114/Amazon-Questions
/FindAllPathsFromTopLeftToBottomRightInMatrix.py
1,075
4.03125
4
# Print all possible paths from top left to bottom right of a mXn matrix # The problem is to print all the possible paths from top left to bottom right of a mXn matrix with the constraints that # from each cell you can either move only to right or down. # Examples : # Input : 1 2 3 # 4 5 6 # Output : 1 4 5 6...
5c84e79182f3eb14e67bc137e867cf461b0c5824
kevin-sharp24/Capstone-1
/code/statistical inference.py
4,482
3.765625
4
#!/usr/bin/env python # coding: utf-8 # In[3]: # import libraries import matplotlib.pyplot as plt import seaborn as sns import pandas as pd import numpy as np # read in data df_diabetes = pd.read_csv('2014_BRFSS_post_processing.csv') df_diabetes.head() # As discussed in the section on exploratory data analysis,...
b3bb0dd64b52a55256d7c364960e09b53a9c319d
aleks225/BD
/SP/Lessons2/sp4.py
399
3.921875
4
a=float(input("введите длину стороны a ")) b=float(input("введите длину стороны b ")) c=float(input("введите длину стороны c ")) if (a+b>c) and (a+c>b) and (b+c>a) and (a>0) and (b>0) and (c>0): print("такой треугольник существует") else: print("такой треугольник не существует")
aa9ae39ff535887dc042a6a54e03983727873cb9
mfreyipj/SE_01-Dojo
/3x3 + lowest score/grid.py
4,055
3.984375
4
grid = [[1, 8, 2], [4, 3, 5], [7, 6, 0]] ''' Control grid -> to test the evaluate function grid = [[1, 2, 3], [4, 5, 6], [7, 8, 0]] ''' max_number = len(grid)**2 def reset_grid(): grid = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 0, 15]] ret...
493097d2efb16b6fb8a36a38e2ed1012ca1c61fc
Rifia/DSX
/labvsu/first.py
1,263
3.8125
4
# Лабораторная работа №1 # Input: мартрица MxN # Output: одномерный массив с номерами тех строк матрицы где есть одинаковые элементы # Если таких строк нет, вывести соответствующее сообщение import sys def fill_matrix_from_file(): with open('res/matrix.txt') as f: matrix = [list(map(float, row.split()))...
f94e235e67d7d7805b28052dd95ae40ebb2ef88c
VideojogosLusofona/PyXYZ
/pyxyz/camera.py
5,012
3.9375
4
"""Camera class definition""" import math import numpy as np from quaternion import as_rotation_matrix from pyxyz.vector3 import Vector3 from pyxyz.object3d import Object3d class Camera(Object3d): """Camera class. It allows us to have a viewport into the scene. Each scene has a camera set.""" def __init_...
83ddeee62cc82516ea0742eb84b409206c5c0dbd
jhustles/py_sql_student_uploader_db
/roster.py
1,265
3.9375
4
# Write a program that prints a list of students for a given house in alphabetical order. import sys import sqlite3 as sl def main(): if len(sys.argv) != 2: sys.exit("Usage: python roster.py <house_name>") # print(sys.argv[1]) con = sl.connect('students.db') con.row_factory = dict_factory ...
f6d00c731be94bc8db0cff0f8706eaa8b1c88276
CarolineSantosAlves/Exercicios-Python
/Exercícios/ex63Fibonacci.py
196
3.84375
4
n = int(input('Quantos termos você quer mostrar? ')) t1 = 0 t2 = 1 cont = 3 print(t1, t2, end=' ') while cont <= n: t3 = t1 + t2 cont += 1 print(t3, end=' ') t1 = t2 t2 = t3
b3cadff826a7e00211176744ddde1b41767e43f4
Abishek-Git/HackerRank
/Finding the percentage-HackerRank/Finding the percentage.py
1,011
4.1875
4
""" HACKERRANK https://www.hackerrank.com/challenges/finding-the-percentage/problem Practice > PythonBasic > Data Types > Finding the percentage The provided code stub will read in a dictionary containing key/value pairs of name:[marks] for a list of students. Print the average of th...
51e4dc50a2ad58d7c98bfdce8a94c4bfab7c7386
lunar0926/python-for-coding-test
/python/list comprehension.py
1,181
3.875
4
# 리스트 컴프리헨션은 리스트를 초기화하는 방법 중 하나. 코드 길이를 줄일 수 있음 ## 0~19까지의 수 중에서 홀수만 포함하는 리스트 ''' # 일반적인 소스코드 list = [0, 1] for i in range(2, 20): if i % 2 == 1: list.append(i) print(list) # 리스트 컴프리헨션 이용 list = [i for i in range(1,20) if i % 2 == 1] print(list) # for문과 if문에서 : 가 없이 나열되는 것이 특징 ## 1부터 9까지의 수의 제곱 값을 포함하는 ...
64ab234863beaabbd6ca3b5ae30c84256c109736
pmjonesg/FaceTracker
/Algorithms/webcam.py
1,150
3.734375
4
# This script performs face recognition and draws a green box around a detected face. import cv2 import sys # The argument this script takes is a haarcascade.xml file which contains face parameters to be recognized. cascPath = sys.argv[1] faceCascade = cv2.CascadeClassifier(cascPath) # Start the capture video_capture...
5a1b728bfe31321dbf51e2f49fe1e575c6946436
cmychina/Leetcode
/leetcode_深度广度优先遍历_被围绕的区域.py
952
3.59375
4
class Solution: def solve(self, board): m=len(board) n=len(board[0]) def dfs(i,j): if not 0<i<m or not 0<j<n or board[i][j] !="O": return #标记O board[i][j]="#" dfs(i, j-1) dfs(i, j-1) dfs(i+1, j) ...
a7189d6863ba125dd6d80e088d9ecce285d6431b
srijithub/python
/simplecalculator.py
1,359
4.125
4
choice = int(input('''Please choose what you want to do from the list below 1. Addition 2. Subtraction 3. Multiplication 4. Division 5. Exponentiation ENTER YOUR CHOICE HERE ''')) #Addition module i...
1bde93d04fe527297c78b47294dd35c789bf2862
ashishjayamohan/competitive-programming
/Practice/fence.py
202
3.546875
4
line = input().split() n = int(line[0]) h = int(line[1]) width = 0 line = [int(i) for i in input().split()] for j in line: if(j>h): width += 2 else: width += 1 print(str(width))
8e34fba794343d2287d0f44242e3c8f2935f2fee
zioan/python_basics
/the_basics/user_input.py
279
3.953125
4
def weather_condition(temperature): if temperature >7: return "Warm" else: return "Cold" user_input = float(input("Enter temperature:")) print(weather_condition(user_input)) #user_input = input("Enter temperature:") #print(weather_condition(int(user_input)))
b195fbb35fffc0ca76a4e73908df397ad2e52016
eronekogin/leetcode
/2022/maximum_length_of_a_concatenated_string_with_unique_characters.py
607
3.59375
4
""" https://leetcode.com/problems/maximum-length-of-a-concatenated-string-with-unique-characters/ """ class Solution: def maxLength(self, arr: list[str]) -> int: dp = [set()] for w in arr: if len(set(w)) < len(w): # Skip word having duplicate chars. continue ...
a75df04f6b07e9b1a6caa63691d6cf0c9193bd57
gaborsoter/phd_codes
/python/tricks_lists.py
156
3.921875
4
x_list = [1, 2, 3] y_list = [2, 4, 6] for i in range(len(x_list)): x = x_list[i] y = y_list[i] print(x, y) for x, y in zip(x_list, y_list): print(x,y)
112c7137b057524b3ff12cb8106d22a4317a59bd
kaushik4u1/Python-100-programming-tasks-with-solutions-Data-Types-
/13-Coding Exercise.py
271
3.9375
4
#Trim all spaces and newline charactes '\n' from the 'word' variable. Save the result in the 'new_word' variable. #Expected result: # hello_world word = ' h\nel lo_ \nwor ld ' new_word = word.replace(' ','').replace('\n','') print(new_word) #Output: 'hello_world'
e1c5f240653ba6b174bea9d4ceec0858c5af34af
mechanicalamit/learning_python
/project_euler/problem_016.py
220
3.734375
4
"""2^15 = 32768 and the sum of its digits is 3 + 2 + 7 + 6 + 8 = 26. What is the sum of the digits of the number 2^1000?""" s=0; x=0; from math import pow x=int(pow(2,1000)) a=str(x) for i in a: s=int(i)+s print(s)
682ecfdb479989eaea03a7cf3dea0d5b3458309d
Adem54/Python-Tutorials
/4.Week-2/python3.py
631
3.796875
4
# liste.append(7) liste listesinin sonuna eleman ekler # meyveler.insert(2, "kivi") bu da meyveler listesinin 2. sırada elemanı olarak "kivi" yi ekler # liste.index("elma") indisi buluruz def oncesine_ekle(liste, referans_eleman, yeni_eleman): liste.insert(liste.index(referans_eleman), yeni_eleman) def ardina_e...
ed58c11c4eb53505d47bfb29cfed35390890d571
Ivy-Walobwa/PythonGames
/RockPaperScissors.py
1,040
4.125
4
import random def rock_paper_scissors_game(): weapons = ['r', 'p', 's'] random_number = random.randint(0, 2) comp_weapon = weapons[random_number] user_weapon = input('Rock(r), Paper(p) or Scissors(s)? ').lower() print(f'You picked {user_weapon}') print(f'Computer picks {comp_weapon}') if ...
b733e66bfea75f02e8b6fde3cf32f1f806ce5676
whyj107/Algorithm
/BaekJoon/4949_균형잡힌 세상.py
1,328
3.609375
4
# 문제 # 균형잡힌 세상 # https://www.acmicpc.net/problem/4949 # 나의 풀이 import sys input_str = sys.stdin.readline().rstrip() while input_str != '.': try: if input_str[-1] != '.': print("no") else: tmp1 = [] for i in input_str: if i == '(' or i == '[': ...
1796324a61f79d402f6e45128d6ae1ca671d62a0
jasonpark3306/python
/.vscode/SWDesign/MathFunctions.py
1,062
3.859375
4
""" LIST FUNCTIONS """ def get_max(list) : mx = float("-inf") for num in list: if num > mx : mx = num return mx def get_min(list) : mn = float("inf") for num in list : if num < mn : mn = num return mn def get_average(list) : return sum(list) ...
119007e36107b3ad8e4269a4772dcee6e991753d
westondlugos/Dlugos_Weston
/ProgrammingLesson_07/averagedigits.py
246
4.3125
4
number = int(input("Enter a number:")) digits = 0 num = number avg = 0 while num > 0: digits = digits + 1 avg = (avg + (num % 10)) num = int(num / 10) print("The average of the digits of ",number,"is",avg / digits)
383ea393bb3a039c0dd61e21f4bc2b02ea327f31
G8A4W0416/Module4
/input_validation/validation_with_try.py
1,850
4.15625
4
""" Program validation_with_try.py Author: Greg Wilhelm Last date modified: 2/14/2020 The purpose of this program is to prompt the user for their first name, last name, age, and three scores and then calculate the average of their three scores via a function call. What the user entered and the average of their score...
4c8460965400494098e6adfb8eeb864c3688b2c7
NeuroYoung/LPTHW
/ex19_extra.py
163
3.890625
4
def sum_two(a1, a2): a3 = float(a1) + float(a2) print "%r" % a3 a1 = raw_input("the first number?") a2 = raw_input("the second number?") sum_two(a1, a2)
4badd1cbcde6d9717c3782d9a0491b66312b9f49
Bubujka/python-learning
/code/array/array_unique.py
202
3.609375
4
#!/usr/bin/env python3 """ Получить только уникальные значения из массива """ arr = [1, 2, 3, 5, 2, 4, 'bubujka', 'zuzujka', 'bubujka'] print(list(set(arr)))
599f1035745804bddbdff675694a0aff36302e82
k-kondo-s/eight-queen
/models/model.py
2,697
4.3125
4
from abc import ABCMeta, abstractmethod from typing import List, Tuple, Union class Queen(): pass class Board(): def __init__(self, n: int) -> None: """ Args: n (int): length of the chess board """ self.n: int = n self.board: List[List[Union[None, Queen]]]...
097f6e935b3b6608c1da2144580ccec2fc73de07
artag/Training
/Bill Lubanovich - Introducing Python/04_comprehensions.py
1,587
4.4375
4
# Включения - спосособ создания структуры данных из одного и более итераторов. # Включение списка number_list = [number for number in range(1, 6)] print(number_list) # 1 2 3 4 5 print('---') number_list = [number - 1 for number in range(1, 6)] print(number_list) # 0 1 2 3 4 print('---') odd_numbers = [numb...
1379113b9630fb4367862c640879ccb59f9b79cf
owl-sec/Project_Euler
/P10.py
622
3.75
4
prime = True prime_sum = 0 prime_counter = 0 for num in range(int(200000000)): prime = True for i in range(2, num): if num%i ==0: j=num/i #print('%d equals %d * %d' % (num,i,j)) prime = False break else: prime = True if prime == Tru...
c46c5bb2ff090627f41c1684b9627961896354af
ybao2000/javaIntro
/PokerPlay.py
5,099
3.5625
4
import random from enum import Enum class Suit(Enum): Spade=4 Heart=3 Diamond=2 Club=1 class Rank(Enum): RoyalFlush = 10 StraightFlush = 9 FourOfAKind = 8 FullHouse = 7 Flush = 6 Straight = 5 ThreeOfAKind = 4 TwoPairs = 3 OnePair = 2 HighHand = 1 class Card: ...
8da9bf9eeb75cd0ceb3ca9ef637f9ef2e4ed5092
whorlwater/lockpick
/lockpick.py
5,650
3.53125
4
from random import shuffle, randint from re import search import sys import os import simplejson HIGHSCORES_FILENAME = ".lockpick_highscores.json" def makeLock(): lock = [] i = 0 while i < 5: pin = randint(1,5) pin = str(pin) lock.insert(i,pin) i += 1 shuffle(lock) ...
a53c6da9e035a3f230f343c339de9c2f1c8ec532
tomatih/AdventOfCode2020
/Day13/gold.py
974
3.5625
4
#!/usr/bin/env python # from https://rosettacode.org/wiki/Chinese_remainder_theorem#Python from functools import reduce def chinese_remainder(n, a): sum = 0 prod = reduce(lambda a, b: a*b, n) for n_i, a_i in zip(n, a): p = prod // n_i sum += a_i * mul_inv(p, n_i) * p return sum % prod ...
1a3a4288276ff924fd8aef981da04c20942d6534
aana5i/python_library
/BrutalPython/basic/polygon_class.py
2,072
3.578125
4
import math class Polygon: def __init__(self, n, R): self._n = n self._R = R def __repr__(self): return f'Polygon(n={self._n}, R={self._R})' @property def count_vertices(self): return self._n @property def count_edges(self): return self._n @prope...
1c2279e873195f476ad6e749666980ee46309241
miltonsarria/teaching
/dsp2019/assignments/A1Part2.py
629
3.515625
4
import numpy as np #A1-Part-2: Generar una sinusoidal compleja def genComplexSine(k, N): """ Inputs: k (integer) = indice de la frecuencia con la que se calculara la sinusoidal compleja para la DFT N (integer) = longitud de la sinusoidal compleja en numero de muestras Output: La fun...
500a160c149db1c356e5f48a045c92e341b3c01b
aziddddd/parameter-estimation
/Minimiser.py
1,835
3.609375
4
""" NumRep CP2: Minimiser, a class for for minimising a function of a parameter to find the best value of parameter Authors: Azid Harun Date : 05/10/2018 """ # Import required packages import numpy as np import iminuit as im from iminuit import Minuit class Minimiser(object): """ Class for...
58121849f0be38ef65824fd12ef91978b52de243
majdalsado/coding-challenges
/python/factorials.py
319
3.90625
4
# The Challenge: # The recursive function for this challenge should # return the factorial of an inputted integer. # factorial(4) = 4! = 4 x 3 x 2 x 1 = 24 = Output def factorial(n): # The base case if (n==0): return 1 # The recursive return n*factorial(n-1) # Test case print(factorial(20))
e63ad8cf5001c30fa6ebd729bcd05358da16a7c6
QuentinDuval/PythonExperiments
/combinatorics/NumberOfWaysToPaintN3Grid_hard.py
1,686
4.03125
4
""" https://leetcode.com/problems/number-of-ways-to-paint-n-3-grid/ You have a grid of size n x 3 and you want to paint each cell of the grid with exactly one of the three colours: Red, Yellow or Green while making sure that no two adjacent cells have the same colour (i.e no two cells that share vertical or horizontal...
fa6a3d19b62aa747a9a8d4b49a2941be1c0f26a5
nishanthegde/bitesofpy
/115/indents.py
313
3.890625
4
def count_indents(text: str) -> int: """Takes a string and counts leading white spaces, return int count""" return len(text) - len(text.lstrip(' ')) # def main(): # print('thank you for everything...') # print(count_indents(' string')) # if __name__ == '__main__': # main()
6a5eceeab887df952199b0511eafa2cc141b1c84
jossrodes/PYTHONFORDUMMIES
/162_findall_function.py
195
3.59375
4
mystring = 'Your father smelt of elderberries!' print re.findall('[aeiou]', mystring) mystring = 'Your father smelt of elderberries!' vowels = re.compile('[aeiou]') vowels.findall(mystring)
f63f4e5fe8285939a1d1917b91facce8c026d679
generic-smith/3d-maze
/gen3dmaze.py
1,760
3.609375
4
from random import randrange from prim2dmaze import gen2dmaze as genMaze # key: # 0 = path # 1 = wall # 2 = entry/start point # 3 = entrance to layer above # 4 = entrance to layer below # 5 = endpoint def gen3dMaze(width, height, depth, verbose=False): maze = [] for z in range(depth): # build the layers of ...
a64d8d6ee3f15bf1c0a5c58b34073103a16eeb0b
hooyao/Coding-Py3
/LeetCode/Problems/36_valid_sudoku.py
2,757
3.578125
4
import sys class Solution: def isValidSudoku(self, board): """ :type board: List[List[str]] :rtype: bool """ if len(board) != 9 or len(board[0]) != 9: raise Exception() # test block for i in range(3): for j in range(3): ...
bbfe68afb3f22880860bc60b6601796fe2d12d81
terwilligers/Text-Summarization
/text_rank_implementation.py
6,713
3.609375
4
''' An implementation of the TextRank algorithm. Generally this consists of: -constructing a weighted graph of sentences -applying the weighted PageRank algorithm to this graph -selecting the top-n ranked sentences Source for algorithmic description: https://www.aclweb.org/anthology/P04-3020 ''' import nltk import ma...
18ade64937893fe3067b6110f4b1666004d28b07
arguelloj/CFB-study
/CFB- LHEB/Chapter 2/gum.py
254
4.0625
4
#This function is used to write a string of words many times def gum(times): ''' Apologizes for chewing gum a given number of times. :) ''' for line in range(times): print(' I promise to no longer chew gum in class. :(')
1d6df90938fbb630b1ad4c1f972411762d02b436
wearewcc/wcc
/Python/hello_world.py
126
3.609375
4
print('Hello World!' * 3) # Rounds pi to 3.0 #print(round(3.1459)) #print(round(3.1459, 2)) # Rounds pi to 2 decimal places
ee99c757061e93e494d7dc2018893058a0aa4fe6
mousepad01/tema_sd_1
/sortari.py
8,483
3.6875
4
import time import random # functia de testat validitatea sortarii def sortedtest(nume_sortare): global vaux daux = {} # dictionar pentru retinerea frecventelor in vectorul sortat de nume_sortare if len(vaux) != n: print(nume_sortare + " nu a reusit sa sorteze; lungimea vectorulu...
3fc0277b0e2791d64daaf7f84e8b756b7a385df8
satyam-seth-learnings/python_learning
/Harshit Vashisth/Chapter-5(List)/K-More About Lists/97.index_method_in_list.py
217
4.03125
4
# index method in list numbers=[1,2,3,4,5,6,7,8,9,10] number1=[1,2,3,4,1,5,6,7,8,1,9,10] print(numbers.index(1)) print(number1.index(1)) print(number1.index(1,3)) print(number1.index(1,5)) print(number1.index(1,5,12))
3ceae6ff1bc1ff8355a156b0603898066710840a
JimmyLamothe/autofront
/autofront/autofront.py
17,199
3.59375
4
""" Main module for autofront, the automatic front-end This module lets users start a simple one-page Flask server from which they can trigger functions and scripts and see the result of their print calls and return values in the browser. It also replaces regular input calls with a version that gets user input in the ...
39809ab54e15c9ca475c79a489601fce1fd89c84
bojinyao/projGroup
/part-1/final_solver.py
4,311
3.515625
4
import networkx as nx import os # extra imports from solver.py import metis import math ########################################### # Change this variable to the path to # the folder containing all three input # size category folders ########################################### path_to_inputs = "./inputs" ##########...
bbf60ab8acfa6d3a65817195b2b213881e8c93ee
HaneulParkSky/sun_python
/Day 13~16/15A_typing_타자게임.py
694
3.5625
4
# 15A_typing.py # 타자 게임 만들기 import random import time # 단어 리스트 w = ['cat', 'dog', 'fox', 'monkey', 'mouse', 'panda', 'frog', 'snake', 'wolf'] # 문제 번호 n = 1 # 안내 메세지 출력 print('[타자 게임] 준비 되면 엔터!') input() # 시간 측정 st = time.time() # 문제 출제 q = random.choice(w) while n <= 5: prin...
6fea5cbf862fa8c9010b6ba9b2f915cbecba637f
hue113/complete-python
/04-list-methods.py
1,432
3.828125
4
# https://www.w3schools.com/python/python_ref_list.asp basket = [1, 2, 3, 4, 5] # ADD: append, insert, extend none_list = basket.append(100) new_list = basket print(basket) # [1, 2, 3, 4, 5, 100] print(none_list) # none print(new_list) # [1, 2, 3, 4, 5, 100] # ========================================== # REMO...
ba4ab2ad5049771daef27f188c7c09aec85ee688
chenpc1214/test
/11-9.py
879
3.875
4
def isTriangle(s1, s2, s3): if s1 + s2 < s3: return False if s1 + s3 < s2: return False if s2 + s3 < s1: return False return True def area(s1, s2, s3): p = (s1 + s2 + s3) / 2 return (p * (p - s1) * (p - s2) * (p - s3)) ** 0.5 d1, d2, d3 = eval(input("請輸入3個邊長 : ")) if ...
5ed6567d68a7e35e45aba93bdbc7da258dbecdf7
zsmn/competitive_programming
/basic.py
283
3.875
4
numero = int(input("Digite o número para saber sua raiz cúbica: ")) count = 1 a = 0 while count < numero**0.5: if count*count*count == numero: a = 1 print("A raiz cúbica de",numero, "é",count) count += 1 if a == 1: pass else: print("Não tem")
e7c862403e80382fc34603bf41b11e1f4dadbced
jici2016/pytest
/pickle/pickletest.py
1,350
3.671875
4
# __author liuming # 2018-04-11 ''' pickle 可以将一个方法加密后保存到文件,其他地方只管拿到文件后使用 ''' import pickle def hello(): str=''' 将进酒 唐代:李白 君不见,黄河之水天上来,奔流到海不复回。 君不见,高堂明镜悲白发,朝如青丝暮成雪。 人生得意须尽欢,莫使金樽空对月。 天生我材必有用,千金散尽还复来。 烹羊宰牛且为乐,会须一饮三百杯。 岑夫子,丹丘生,将进酒,杯莫停。 与君歌一曲,请君为我倾耳听。(倾耳听 一作:侧耳听) 钟鼓馔玉不足贵,但愿长醉不...
81a43737b809529189e56df09f1a864718121806
zeyuzhou91/PhD_dissertation
/network_slicing/model_1/auxiliary.py
3,221
3.8125
4
import numpy as np def argmax_of_array(array): """ Find the index of the largest value in an array of real numbers. Input: array: an array of real numbers. Output: index: an integer in [K], where K = len(array) """ # Simple but does not support random selection i...
47609b3f35f031e857b3c17b96e8e3ada032555e
lportinari/URI
/URI1042.py
207
3.765625
4
a, b, c = input().split(' ') a = int(a) b = int(b) c = int(c) unsorted = [a, b, c] sort = [] sort = sorted(unsorted) for i in sort: print(i) print() for i in unsorted: print(i)
bea9451483bc21a39f964dfa1cbcd9d0f9bb3f63
kami39/practice
/pythonTest/re/文本处理/sub.py
155
3.640625
4
import re p = re.compile(r'(\w+) (\w+)') s = 'i say, hello world!' print p.match(s).group(1).title() print p.match(s).group(2) print p.sub(r'\2 \1', s)
02335a3f9695fdd34b2d41d9f49c3d72f33a2ca0
rashmipai2000/python
/tuple.py
466
3.90625
4
def inputval(): x="a=b,c=d,e=f,g=h" return x def compute(x): m=x.split(",") for i in range(len(m)):#to use 1 for loop insted of 2 for loops m[i]=m[i].split("=") m[i]=tuple(m[i]) return m def output(m):#pass parameters to output function print(m) def main(): x=inputval()#as...
53d304df04e32a7da628d8efa8966eaf7652b53b
Bansi-Parmar/Python_Basic_Programs
/python_program-020.py
342
3.921875
4
## 20. SUM = 1 + 8 + 27 + 64 + … and so on print('\n\t Calculation(1 + 8 + 27...) of First given No') print('\t................................................\n') no = int(input("Enter number :- ")) s = 0 for i in range(1,no+1): s = s + (i**3) print("Calculation (1 + 8 + 27...) of First {} Number is :...
1d130446b60706a31bfd8123b5ff06d8c8772295
KartikKannapur/Algorithms
/00_Code/01_LeetCode/507_PerfectNumber.py
865
3.828125
4
""" We define the Perfect Number is a positive integer that is equal to the sum of all its positive divisors except itself. Now, given an integer n, write a function that returns true when it is a perfect number and false when it is not. Example: Input: 28 Output: True Explanation: 28 = 1 + 2 + 4 + 7 + 14 Note: The in...
4f7be251eee388b2d1e112a21b34be49b40bd3a8
ScarletMoony/py_from_scratch_to_top
/OOP/03.py
832
3.828125
4
class Date: def __init__(self, month, day, year): # Класс может иметь только один self.month = month # конструктор self.day = day self.year = year def display(self): return f"{self.month}-{self.day}-{self.year}" @classmethod # Метод похо...
ecfcb0f253fc2aa1641680e1ab7ae2391e701ce4
Mocha-Pudding/Scrapy-Redis_Demos
/Thread_demo/demo3.py
500
3.796875
4
# 多线程共享全局变量的问题 以及锁机制 import threading VALUE = 0 gLock = threading.Lock() #创建锁 def add_value(): global VALUE #使用全局变量,需要用global关键字来声明 gLock.acquire() #上锁 for x in range(1000000): VALUE += 1 gLock.release() #释放锁 print('value: %d' %VALUE) def main(): for x in range(3): ...
b85aa5d6cc838013952eb629ae346584218bc723
hackingmath/projectEuler
/euler031Recursion.py
402
3.578125
4
"""Euler 31 with Recursion""" coins = [200,100,50,20,10,5,2,1] def find_poss(money,maxcoin): """Finds the number of ways to make money.""" output = 0 if maxcoin == 7: return 1 for i in range(maxcoin,8): if money-coins[i]==0: output += 1 if money-coins[i]>0: ...
cd6ce6e990d2f958678308e7966431068ec841a9
paragshah7/Python-CodingChallenges-LeetCode
/LeetCode_New/group_anagrams.py
739
4.21875
4
""" https://leetcode.com/problems/group-anagrams/ Given an array of strings strs, group the anagrams together. You can return the answer in any order. Input: strs = ["eat","tea","tan","ate","nat","bat"] Output: [["bat"],["nat","tan"],["ate","eat","tea"]] """ def group_anagrams(words): word_dict = {} for wor...
491bee39b76c5252187bc734dddd247aa017ed7d
thomasyu929/Leetcode
/Tree/symmetricTree.py
1,436
4.21875
4
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: # 1 Recursive # def isSymmetric(self, root: TreeNode) -> bool: # if not root: # return True # ...
226043c73e1a755608522363a34d3ea735a03c4e
0x54454545/Hangman-
/server.py
7,345
3.703125
4
#Server import socket from sys import argv from random import * from game import * def main(): # Parse command line args if len(argv) != 2: print("usage: python3 server.py <word to guess or '-r' for random word>") return 1 print("Server is running...") HOST = '' # Symbolic name meani...
a2ac689de2e9fccadc4d06f26de8df21712948ee
cocoon333/lintcode
/178_solution.py
1,603
4.03125
4
""" 178. Graph Valid Tree Given n nodes labeled from 0 to n - 1 and a list of undirected edges (each edge is a pair of nodes), write a function to check whether these edges make up a valid tree. Example Example 1: Input: n = 5 edges = [[0, 1], [0, 2], [0, 3], [1, 4]] Output: true. Example 2: Input: n = 5 edges = [...
617715229da8588138a8bf575083cea4a39867b9
lic3as/trabalho-python
/jokenpo.py
1,167
3.578125
4
import random vitorias = 0 aux = 1 while aux <= 5: jogadaPlayer = input("SUA JOGADA:") jogadaComputador = random.randrange(0,2) jogadas = ["pedra", "papel", "tesoura"] print("Player:", jogadaPlayer) print("Computador:", jogadas[jogadaComputador]) if jogadaPlayer == jogadas[jogadaComputador...
bab6f524b12ceacceffd16c15de81a2d315027c8
gabriellaec/desoft-analise-exercicios
/backup/user_379/ch26_2019_04_11_19_40_08_254458.py
326
3.734375
4
a=int(input('digite a quantidade de dias')) b=int(input('digite a quantidade de horas')) c=int(input('digite a quantidade de minutos')) d=int(input('digite a quantidade de segundos')) def calcula_segundo(a,b,c,d) y=(a*86400)+(b*3600)+(c*60)+(d*1) return y print('isto dá um total de'{0}'segundos').format...
e9ba3e2c5e9853277e13c7d8ff0a92c4be3478ef
vatsalpatel1000/Python-Programs
/Fibbnacci.py
432
3.703125
4
import time def fib_decorator(func): def inner(): starttime=time.time() value=func() endtime = time.time() runtime = endtime-starttime print("time taken=",runtime) return value return inner @fib_decorator def fib(): a, b = 0, 1 while True: yield a...
486ca2ec43f2cc68239eeaf446741732399c4b71
pololee/oj-leetcode
/companies/oracle/p101/Solution.py
1,194
4.09375
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 isSymmetric(self, root): """ :type root: TreeNode :rtype: bool """ if not root: ...
a269bbb439ad2e2d3d9bf3bc7b4aa00e1de2b003
larsgroeber/prg1
/EPR/sheet3/sixteen_is_dead.py
3,658
3.921875
4
import random as r from time import sleep def roll_dice_sensible(num_dice=1, faces=6): return [r.randint(1, faces) for i in range(num_dice)] def get_num_dice(): num_dice = input("Please enter the number of dice (default is 1): ") if num_dice == '': return 1 elif num_dice.isdigit() and 1 <= i...
6a26eacdbf4fcfedf87837b4c1e4855ce70906d9
kylemaa/Hackerrank
/String/mars-exploration.py
444
4.15625
4
# https://www.hackerrank.com/challenges/mars-exploration/problem # this function checks for every letter, x, in step of 3 of a string def marsExploration(s): s = list(s) count = 0 for i in range(0,len(s)): x = i % 3 if x == 0 and s[i] !='S': count += 1 elif x == 1 and s[...
de144dd6ce68109a8defae0cb7c278003fc8edaa
MuhammadSyaugi13/Experient-Learning
/Dasar Python/continue.py
189
3.59375
4
# continue for i in range(1, 30): if i % 2 == 0: continue print(i) # break while True: data = input("Masukan Data : ") if data == "x": break print(data)
1b75aef7b73f5a415450d64e9a760585b03d1288
undefinedmaniac/AlexProjects
/Basic Python Concepts/variables and arrays.py
756
4.4375
4
# Variables store information in the computer's memory # This is how you create a variable # <variable_name> = <value> variable1 = 0 # Variables can be re-assigned like so variable1 = 5 # You can use the variable name to access the data inside the variable print(variable1) # Arrays (AKA Lists in Python) are group...
d731f83178ee86085f54fd6ab00c837749c2311f
machenxing/my-algorithm-training
/python/q-series/Q8.4.py
1,149
4.125
4
''' Power Set: Write a method to return all subsets of a set. ''' def getSubsets(setz, index): allSubsets = [] if len(setz) == index: if [] not in allSubsets: allSubsets.append([]) else: allSubsets = getSubsets(setz, index + 1) item = setz[index] moreSubsets = ...
b70e775d45ed6af85a90365d670dc3ae075fcc54
luiz-vinicius/IP-UFRPE-EXERCICIOS
/aula_lista_ex_1.py
138
3.9375
4
lista = [] for x in range(5): v = int(input("Digite o valor: ")) lista.append(v) for i,p in enumerate(lista): print(i+1, "º = ",p)
3289061ddd3f9309184391ed48003e1090860b5d
Forrest-Keyper/spaceman_repo
/spaceman.py
3,468
3.78125
4
import random guessCount = 0 launch_word = None blank_counter = [] launch_word_list = [] def launch_word_load(): # we'll use this one function to load, split and save our word as a whole word and a list f = open('word_bank.py', 'r') words_list = f.readlines() f.close() space_list = words_list[...
6d993fefff607da376007bd034ad3ed58c737df5
0xCyberY/Penetration-Test---python3
/sockt.py
576
3.75
4
#Socket programming is a way of connecting two nodes # on a network to communicate with each other. #mporting the socket library and making a simple socket. import socket host = input('Enter the host IP OR loopback IP or (localhost) IP ex:127.0.0.1\n') port = int(input('Enter the port Number ex: 9999\n')) s ...
b7bbb0ecedd5fb562b81a62bd19ec1b6469b595a
ablaze03/skillfactory_rds
/sf_module_0/Guess_number.py
1,248
3.6875
4
import numpy as np import random count = 0 # счетчик попыток number = random.randint(1,100) # загаданное число max_level = 99 # верхняя граница min_level = 1 # нижняя граница predicat = round((min_level+max_level)/2) # предсказание while True: # бесконечный цикл count+=1 # cчитаем количество попыток угады...
3093dbb9b5d0b08e32d03e325f699f3b93d753d3
ChihYunPai/Data-Structure-and-Algorithms
/Leetcode_Algorithm/Python3/437_Path_Sum_III.py
1,540
3.875
4
""" You are given a binary tree in which each node contains an integer value. Find the number of paths that sum to a given value. The path does not need to start or end at the root or a leaf, but it must go downwards (traveling only from parent nodes to child nodes). The tree has no more than 1,000 nodes and the val...
2d43dad360cbc9f7c976509bf4f374a3e214019b
ishantk/GW2019C
/venv/Session26B.py
255
3.765625
4
print(">> App Started") num1 = int(input("Enter Number 1: ")) num2 = int(input("Enter Number 2: ")) num3 = 0 try: num3 = num1 / num2 except ZeroDivisionError as zRef: print(">> Error: ",zRef) print(">> Result is:",num3) print(">> App Finished")
ce356c0d634a8adab148d315103181b99c151693
williamchermanne/EcoFamily
/Code/product.py
1,008
3.5625
4
class Product: def __init__(self, name): self.name = name self.ListOfIngredients = [] self.PriceOfIngredients = [] # Prix par kg self.QuantityOfIngredients = [] # Quantité en kg self.Value = 0 def add_ingredient(self,ingredient, price, quantity): self.ListOfIngredients.append(ingredient) self.PriceOfI...
f46b7f91f114866780993085e6ff818213d8e68d
mondler/leetcode
/codes_python/0005_Longest_Palindromic_Substring.py
1,473
3.859375
4
# 5. Longest Palindromic Substring # Medium # # 13511 # # 801 # # Add to List # # Share # Given a string s, return the longest palindromic substring in s. # # Example 1: # # Input: s = "babad" # Output: "bab" # Note: "aba" is also a valid answer. # Example 2: # # Input: s = "cbbd" # Output: "bb" # Example 3: # # Input:...
e4328de990b783d66338ec4b4915944a9cbf5bdb
robbailiff/file-operations
/download_file.py
583
3.765625
4
""" A simple code made whilst playing around around with the file and urllib modules. It simply downloads data from a webpage and writes it to a text file. """ from urllib.request import urlopen, Request headers = { 'user-agent': "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Ch...
cc29f8ef1b889fd4bf2bbd87c686eaedf927ab57
iftekkhar/py-concepts
/functions/main.py
406
3.59375
4
''' Home work : 2 Topic : Create Functions ''' # Defing Functions def artist(artist): result = artist print(result) def title(title): result = title print(result) def year(year): result = year print(result) def songDeatils(title, artist, year=2016): print(title) print(artist) ...
505b587536817346c04ae07fcb2fe3906af24e2c
affanfarid/DailyProblems
/longestMountain/longestMountain.py
2,531
4.15625
4
''' Let's call any (contiguous) subarray B (of A) a mountain if the following properties hold: B.length >= 3 There exists some 0 < i < B.length - 1 such that B[0] < B[1] < ... B[i-1] < B[i] > B[i+1] > ... > B[B.length - 1] (Note that B could be any subarray of A, including the entire array A.) Given an array...
7a1c77e84e1ba5128629d6b8c9bcafe544b3d5d2
Michel-Manuel/Data-Structures-Projects
/Practice1.py
204
3.59375
4
def NumberofWords(a): sentence = a.split() print("The number of words are " ,len(sentence)) def main(): NumberofWords("The quick brown fox jumps over the lazy dog") main()
2e0b9f6116f830915359c64b638ea11511eb571b
JoeDurrant/rubiks-cube-solver
/solve-cube.py
1,329
3.796875
4
from Cube import Cube def solve_cube(state): #TODO: Logic of cube solving cube = Cube(state) return cube_sides = [ [['W','W','W'], ['W','W','W'], ['W','W','W']],#top [['G','O','G'], ['G','O','G'], ['G','Y','Y']],#left [['R','R','B'], ['Y','G','O'], ['O','O','Y']],#front [[...
f8eb4c7a51e339ea67ac88e4bbe476bab8dc4d6e
HariprasadPoojary/Python-Projects
/guess_the_number_user.py
471
4.1875
4
from random import randint def guess(max_num): guess_num = randint(1, max_num) user_guess = 0 while user_guess != guess_num: user_guess = int(input(f"Guess a number between 1 and {max_num}: ")) if user_guess > guess_num: print("Please guess a lower number 👎🏽") elif us...
9f7786c5fcbc5890c38fe6dd0156cb35854ece7f
adler-kosma/daybook_diary
/diary_5.py
11,038
3.8125
4
from tkinter import * #class that defines entries in diary class DiaryEntry: def __init__(self, date, city, text): """Constructor. Creates new diary entry. Inparametrar: self, date, text, city Returnerar: inget""" self.date = date #string self.city = city #string sel...
b19f62943cf43971f0d2331712eaa67b138575c5
shaun-rogers/A_Level_GUI_Intro
/Answers/5 - NumberSystemsCalculator.py
12,445
4.0625
4
'''Creator: S Rogers Title: NumberSystemsCalculator Created: July 2017 Purpose: Demonstration of how to create a GUI for a simple APP. This app allows the user to enter a number in Decimal, Binary or Hex and convert to a number system of their choice To Do: Test with normal and extreme values To Do: Adapt the app so t...
7dca1acf33fa97118abc48ba33e9abc71866bc98
adamclmns/ObjectOriented-Python-2014
/VirtualPet/GettingStarted/threadedWindow.py
3,014
3.53125
4
__author__ = 'Adam Clemons' #Importing Python Standard Library Modules for Python 3.4. Importing as for compatibility with code written for 2.7 import tkinter as tk import logging as logger import _thread as thread from time import sleep import queue as Queue # This queue's actions so that two threads don't try to ac...
610d29f11ae67ced1fdd06584bc8dbb7c94c0dc8
ywyz/IntroducingToProgrammingUsingPython
/Exercise02/2-7.py
376
3.890625
4
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Date : 2019-06-07 18:59:37 # @Author : ywyz (admin@ywyz.tech) # @Version : 1.0.0 # Compute years minuteNumbers = eval(input("Enter the number of minutes: ")) days = minuteNumbers // 60 // 24 % 365 years = minuteNumbers // 60 // 24 // 365 print(minuteNumbers, "minutes...
33af46f692332eed1c2261dc9db698114a95f105
PrincessMagnificent/studiousRotaryPhone
/DictRANDOM/parseWordType.py
538
3.5625
4
##the purpose of all of this is to help me identify what is a verb, a noun or an adjective in a dictionary file import sys #command line argumnts args = sys.argv #list of word types, either verbs nouns or adjectives listOfWordTypes = ("v","n","adj") #this is how we make "v, --v and .v" all the same for argument in ...
8994ba244d550233dd746deceddfde1f7be6c121
tiwaripulkit99/pythonpractice
/pythonpractice/decorators.py
497
3.609375
4
def div(a, b): print(a / b) def clonediv(func): def inner(a, b): if a < b: a, b = b, a return func(a, b) return inner div1 = clonediv(div) div1(2, 4) """def decorator_function(passed_function): def inner_decorator(): print('this happens before') passed_f...
f796b4f05f82b4927f75767b9c29e82d1a347304
adatechschool/lu-tdd-toma
/Appliquer/fizzbuz.py
656
3.734375
4
class FizzBuzz: def __init__(self): pass def test(self, n: int, stage: int) -> str: if type(n) != int or type(stage) != int: return "'n' and 'stage' should be of type int" else: return self._fizzbuzz(n,stage) def _fizzbuzz(self, n: int, stage: int) -> str: string = "" ...
45b754ad05f99338da863519ba92c59da844d084
hackerearthclub/LetUsCode
/Search/Binary search/Binary_Search.java
1,000
3.5
4
class Binary_Search { // Function for binary search public static int BinarySearch(int[] array, int size, int desired) { int left = 0, right = size - 1, middle; while (left <= right) { middle = left + (right - left) / 2; if (array[middle] == desired) ...
28a41acaa07162aaf94e5b8198708cb78a922af9
wwclb1989/python
/itcast-python/cn/itcast/chapter11/demo.py
4,984
4.1875
4
# 第11章 面向对象(下) # 封装、继承、多态 # 封装:把属性定义为私有,在属性名前面加“__”,提供setter与getter方法 # 继承:子类不能继承父类的私有属性和方法,也不能在子类中直接访问 # 子类通过“_类名__私有元素”可以访问父类的私有属性和私有方法,但是这种方法不建议 # isinstance(obj, type)用于检查对象是否属性类的实例 # insubclass(cls, cls)用于检查前者是否是后者的子类 # python支持多继承,同名的方法,先继承哪个就会调用哪个父类的方法 # 也可以子类中以变量名=父类名.变量名的方式指定变量是继承于哪个父类 # 子类也可以重写父类的方法,并通过supe...
232b03854eb239de0fde52f44aa9ffb8cd0af560
Vo7ice/PyProject
/chapter11/oddnogen.py
319
3.71875
4
#!/usr/bin/env python from random import randint as ri def odd(n): return n % 2 allNums = [] #for eachNum in range(9): # allNums.append(randint (1,99)) #print filter(odd, allNums) #print filter(lambda n:n%2,allNums) #print [n for n in allNums if n%2] print [n for n in [ri(1,99) for i in range(9) ] if n%2]