blob_id
stringlengths
40
40
repo_name
stringlengths
5
127
path
stringlengths
2
523
length_bytes
int64
22
545k
score
float64
3.5
5.34
int_score
int64
4
5
text
stringlengths
22
545k
9f44f5d1b42a232efb349cd9a484b1eb0d68372f
ChaitDevOps/Scripts
/PythonScripts/advanced_strings.py
2,053
4.4375
4
#!/usr/bin/python # Chait # Advanced Strings in Python. # advanced_strings.py from __future__ import print_function # .capitalize() # Converts First Letter of String to Upper Case s = "hello world" print(s.capitalize()) # .upper() and .lower() print(s.upper()) print(s.lower()) # .count() and .find() # .count() -- W...
9ee8187ccb35cae675519ec0c31f8f97f83cab6b
PanyushkinOOP/oopbase
/datasql.py
2,428
3.546875
4
#-*- coding:utf-8 -*- import os import sqlite3 as db emptydb = """ PRAGMA foreign_keys = ON; create table material (code integer primary key, name text, priceforgramm integer); create table product (code integer primary key, name text, typel text, material integer, weight float, price integ...
b61ca3c977d61a3f8e65daf1af210b9dda9005c6
3sigma/qats
/qats/readers/other.py
2,486
3.578125
4
""" Readers for various time series file formats """ import fnmatch import numpy as np def read_dat_names(path): """ Read time series names from an ASCII file with data arranged column-wise. The names are in the first non-commented row. Parameters ---------- path : str File path ...
50f4413918bd498ae10be024b0380ef0b1824de0
botaklolol/Kattis
/hate9.py
563
3.640625
4
import sys def pow_mod(a,b,n): a = int(a) b = int(b) n = int(n) b = bin(b)[2:] pow_list = [] num = a for i in reversed(b): if int(i) == 1: pow_list.append(num) num = (num**2) % n total = 1 for term in pow_list: total = (term*total) % n retu...
a369eb768bede74a941e6a7f1b78805a3808bd47
botaklolol/Kattis
/lektira.py
391
3.765625
4
import sys def smallest(word): min_sofar = word n = len(word) for i in xrange(1,n+1): for k in xrange(i+1, n): parts = [word[:i],word[i:k], word[k:]] new_w = "".join(["".join(reversed(w)) for w in parts]) if new_w < min_sofar: min_sofar = new_w print min_sofar def main(): small...
fc7132a4d3695d6483c47677f083ad139a20f834
botaklolol/Kattis
/zipfs_law.py
822
3.53125
4
import sys from collections import defaultdict def main(): EOT = "EndOfText" newStart = True veryFirst = True for line in sys.stdin: if newStart: if not veryFirst: print n = int(line.strip()) word_map = defaultdict(int) newStart = False veryFirst = False elif EOT =...
e1e021c6326907a8d0defb801fe7d0841159af70
botaklolol/Kattis
/three_digits.py
321
3.609375
4
import sys def last_3(n): fact = 1 for i in xrange(2, n): fact = fact*i % 1000 while fact%10 == 0: fact /= 10 return str(fact) def main(): n = int(sys.stdin.readline().strip()) ans = last_3(n) if len(ans) >= 3: print ans[-3:] else: print ans if __name__ == '__main__': main()...
f588a8592d6b4c0d14e4ef24e2d6e147d1d27016
botaklolol/Kattis
/safe.py
2,205
3.6875
4
import sys class Matrix: """ A 3x3 Matrix, with a special flip method """ def __init__(self,array): row = () for i in range(len(array)): array[i] = tuple(array[i]) self.data = tuple(array) def flip(self,i,j): new_mat = [] for row in range(3): ...
1726b0860d5e73b50de0f5bf37c89b09e80d281e
botaklolol/Kattis
/virus_rep.py
596
3.515625
4
import sys def count(before, after): min_len = min(len(before),len(after)) front_match = 0 while (front_match < min_len and before[front_match]==after[front_match]): front_match +=1 back_match = 0 i = -1 while(back_match < min_len and before[i]==after[i]): back_match +=1 ...
3c59109e39bc09258172f44b215ef55bea354659
Neoanarika/PytorchTraining
/archive/module2_4_variables.py
817
3.609375
4
# Deep Learning with Pytorch # Module 2.2: Autograd & Variable import torch from torch.autograd import Variable # Create variable for a tensor # a = torch.Tensor([5]) # v_a = Variable(a) # print(a) # print(v_a) # print(v_a.data) # a = torch.Tensor([1,2]) # v_a = Variable(a) # print(a) # print(v_a) # print(v_a.data) ...
e17981bbb306ea0cb6d67a729ba43f0cbe417e3b
Neoanarika/PytorchTraining
/archive/module3_1_linear_regression.py
1,047
3.796875
4
# Deep Learning with Pytorch # Module 3: Regression with Pytorch # Linear Regression Model import torch from torch.autograd import Variable import matplotlib.pyplot as plt # Hyper parameters learning_rate = 0.01 # Setup 1: Setup X_train = [1,2,3,4,5] y_train = [0,-1.1,-1.8,-3.1,-4.5] # Variables X = Variable(torch...
c99ab72379f00c522af178f7741c2afbf81383ac
janak11111/Data-Structure-With-Python
/Array/NextSmallerElementForGivenArr.py
338
3.890625
4
def find_next_smaller_element(arr): ls = [-1 for i in arr] stack = [] for i, x in enumerate(arr): print(i, x) while len(stack) > 0 and x < arr[stack[-1]]: ls[stack.pop()] = x stack.append(i) print(stack[-1]) return ls print(find_next_smaller_eleme...
7ebe3393ea33209ff3a6af15620e6596620be32a
janak11111/Data-Structure-With-Python
/Stack/Balanced_check.py
670
3.71875
4
import Stack def bracket_balanced_check(s): stack = Stack.Stack() open_list = ['[', '{', '('] close_list = [']', '}', ')'] for i in s: if i in open_list: stack.push(i) elif i in close_list: pos = close_list.index(i) if (len(stack) > 0) an...
3731a226f584a2ca6975d0d798e03066a227bf9a
janak11111/Data-Structure-With-Python
/Sorting/BubbleSort.py
240
3.984375
4
def BubbleSort(arr): for i in range(len(arr)-1, 0, -1): for j in range(i): if arr[j] > arr[j+1]: temp = arr[j] arr[j] = arr[j+1] arr[j+1] = temp arr = [21, 31, 11, 55, 44 ] print(arr) BubbleSort(arr) print(arr)
733aa9fce223e24a1f672958a0b7d9bbcd8ff5a0
janak11111/Data-Structure-With-Python
/Sorting/QuickSort.py
404
4.0625
4
def quick_sort(arr): if len(arr) < 2: return arr else: pivot = arr.pop() print(pivot) arr_lower = [] arr_upper = [] for item in arr: if item < pivot: arr_lower.append(item) else: arr_upper.append(item) print("lower", arr_lower) print("upper", arr_upper) return quick_sort(a...
724bf41e116c07f0e2100c3e402fa37faacb30aa
janak11111/Data-Structure-With-Python
/Graphs/Adjacency_Matrix.py
837
3.828125
4
def printmatrix(matrix): r, c = len(matrix[0]), len(matrix[0]) for i in range(r): for j in range(c): print(matrix[i][j], end=" ") print() # Undirected UnWeighted Adjacency Matrix # V, E = map(int, input().split()) # matrix = [[0]*V for i in range(V)] # for k in range(E)...
7ebf78ee3abadb34fb20ab41c397a2a2ea5e3ba0
ggerod/Code
/PY/mazer.py
1,110
3.5
4
#!/usr/bin/python3 def PrintMat(): for i in range(8): print(MAT[i]) print() def MarkAdjacent(i,j): #check N if ((i > 0) and (MAT[i-1][j] == -1)): #mark it and put it on the stack MAT[i-1][j] = MAT[i][j] + 1 stack.append([i-1,j]) #check E if ((j < JRANGE-1) and...
0d2b306e8ab3e02d65f287f47745c17588abc570
ggerod/Code
/PY/Findmissingnum.py
537
3.734375
4
#!/usr/local/bin/python3 nums = [x for x in range(1,101)] del nums[65] print(nums) if (nums[0] != 1): print("the missing number is: 1") exit() for index in range(98): if (nums[index+1] != (nums[index] + 1)): print("the missing number is: ",nums[index] + 1) for i in range(1,101): if (not (i in nums)): print...
fde8e0f55ea61fbb7fecd6c0cd4cc61e0e18ea84
ggerod/Code
/PY/recurseexponent.py
294
4.1875
4
#!/usr/bin/python3 def exponent(num,expo): if (expo==0): return(1) if (expo%2 == 0): y=exponent(num,expo/2) return(y*y) else: y=exponent(num,expo-1) return(num * y) NUM=12 EXPO=25 answer=exponent(NUM,EXPO) print(NUM,"**",EXPO,"=",answer)
cbe52e7a7b07dfc2c720d6fd79c9681ea7d750ea
moppr/435-Homework1
/merge.py
2,539
4
4
class Student: '''A student with a first and last name and graduation year''' def __init__(self, line): self.first, self.last, self.year = line.split() def __lt__(self, other): if self.year < other.year: return True elif self.year == other.year: if s...
35f9dd916a5b5a82d9f6bdb8486d7f1d22a19bb6
Aida99/WebDev21
/week9/task1/1/E/g.py
95
3.609375
4
n = int(input()) a = input().split(" ") for i in reversed(range(0,n)): print(a[i],end=" ")
5b7432f55efe96e9f794718e8e387da6868909eb
WasinUddy/NSC2021-Simplified-SmartFarming-Development-Platform
/program/frontend/playground.py
412
3.546875
4
from tkinter import filedialog from tkinter import * import os def file_save(): #name = filedialog.askopenfilename(initialdir = curr_directory,title = "Select file",filetypes = (("jpeg files","*.jpg"),("all files","*.*"))) dir_path = filedialog.askdirectory() file_name = f"{dir_path.split('/')[-1]}.ino" ...
183d400651e76d097f82c63aece7539e406d3566
akaptur/algebraic_evaluator
/algebra_parser.py
1,860
3.8125
4
# algebra_parser.py # James Wang and Katherine Ye, 18 Jun 2013 """Simple algebraic parser (without using eval)""" def parse(exp): """algebra-parser.parse:: parse(String) Takes a string and returns the evaluated expression as int. Uses Shunting-Yard algorithm. Example: parse('1+3*2') => 7 Ugly a...
047e080338e870a66fe5c01b544af7052c2e628c
shivaram-abhishek/outlier101703028
/outlier101703028/outlier.py
1,146
3.75
4
import numpy as np import pandas as pd import csv import sys def outlier_removal(input,output): try: input_file=pd.read_csv(input) except: print("Input file doesn't exist or path is wrong") else: col=len(input_file.iloc[0,:]) row=len(input_file.iloc[:,0]) ...
0e78684569254e5642b3cf43e07d1405e5595928
KirilldogU/AI-2-Labs
/Gradient_Descent.py
3,483
3.578125
4
import math def equation1(x, y): return 4 * (x * x) - 3 * x * y + 2 * (y * y) + 24 * x - 20 * y def equation1_xDer(x, y): return 8 * x - 3 * y + 24 def equation1_yDer(x, y): return 4 * (y - 5) - 3 * x def equation2(x, y): return ((1 - y) ** 2) + 100 * ((x - (y ** 2)) ** 2) d...
d5df46bfebf3e8fdbf5ef3569dacc9aacb1d28f2
Pigiel/udemy-python-for-algorithms-data-structures-and-interviews
/Array Sequences/Array Sequences Interview Questions/Array Sequence Interview Questions/Anagram-Check.py
1,441
3.9375
4
#!/usr/bim/env python3 """ Solution """ def anagram(s1, s2): s1 = s1.replace(' ', '').lower() s2 = s2.replace(' ', '').lower() return sorted(s1) == sorted(s2) """ Practice """ def anagram2(s1, s2): s1 = s1.replace(' ', '').lower() s2 = s2.replace(' ', '').lower() # Edge Case Check if len(s1) != len(s2): ret...
bcc7ae5bdfe6d3a4f2b0433ca78c7c931a629519
Pigiel/udemy-python-for-algorithms-data-structures-and-interviews
/Array Sequences/Array Sequences Interview Questions/Array Sequence Interview Questions/Sentence-Reversal.py
1,431
4.21875
4
#!/usr/bin/env python3 """ Solution """ def rev_word1(s): return ' '.join(s.split()[::-1]) """ Practise """ def rev_word2(s): return ' '.join(reversed(s.split())) def rev_word3(s): """ Manually doing the splits on the spaces. """ words = [] length = len(s) spaces = [' '] # Index Tracker i = 0 # While ind...
19a3cc106f1dadaf621ef20dd79d62861ab01ac7
Pigiel/udemy-python-for-algorithms-data-structures-and-interviews
/Sorting and Searching/01_Binary_Search.py
754
4.25
4
#!/usr/bin/env python3 def binary_search(arr, element): # First & last index value first = 0 last = len(arr) - 1 found = False while first <= last and not found: mid = (first + last) // 2 # // required for Python3 to get the floor # Match found if arr[mid] == element: found = True # set new midp...
36973fac96c0088ab38dc9d4a3b10f5fbeceffb8
Pigiel/udemy-python-for-algorithms-data-structures-and-interviews
/Recursion/Recursion_Homework_Example_Problems.py
1,628
3.953125
4
#!/usr/bin/env python3 def rec_sum(n): # Base Case if n == 0: return 0 # Recursion else: return n + rec_sum(n - 1) def sum_func(n): # Base Case if n == 0: return 0 # Recursion else: # Performing classing division in Python3 by using // return (n % 10) + sum_func(n // 10) def word_split(phrase, list...
f5c5a2910c1b2d9aec42a7424a8f6aa265c0bd79
Pigiel/udemy-python-for-algorithms-data-structures-and-interviews
/Stacks, Queues and Deques/Stacks, Queues, and Deques Interview Problems/Stacks, Queues, Deques Interview Questions /Balanced-Parentheses-Check.py
1,109
4
4
#!/usr/bin/env python3 def balance_check(s): # Check if even number of brackets if len(s) % 2 != 0: return False # Set of opening brackets opening = set('([{') # Matching pairs matches = set([('(',')'), ('[',']'), ('{','}')]) # Use a list as a "Stack" stack = [] # Check every parenthesis in string fo...
f71428dea34ed0f6bf6a7c0906ffc9e0c6a55844
Pigiel/udemy-python-for-algorithms-data-structures-and-interviews
/Trees/Trees Interview Problems/Binary-Search-Tree-Check.py
1,753
4.09375
4
#!/usr/bin/env python3 class Node: def __init__(self, key, value): self.key = key self.value = value self.left = None self.right = None def tree_max(node): if not node: return float('-inf') maxleft = tree_max(node.left) maxright = tree_max(node.right) return max(node.key, maxleft, maxright) def tree_m...
dbfa142b9708e4bdde15fb219684a5125ebb2cc4
carlosrivera22/DesignPatterns
/BehavioralDesignPatterns/chain_of_responsability/client.py
1,358
3.5
4
# Chain of Responsability avoids attaching the sender of a request to its receiver, # giving this way other objects of possibility of handling the request too. # The objects become parts of a chain and the request is sent from one object to # another across the chain until one of the objects will handle it. # This ...
24b4c7659af229b4a3438c9625557a1b0c3d6e2f
Himself12794/Python-Work
/math/matrix.py
12,305
4.15625
4
###################################### # # Matrix Class # Written by: Philip Whiting # ###################################### from random import randint class InvalidMatrix( Exception ): ''' For handling errors with invalid matrix sizes. Attributes: msg -- Error message ''' def __init__( self, message ): Ex...
ea86952200e505ac2163d80c4c4e469484fca971
Himself12794/Python-Work
/collatz.py
408
3.796875
4
import sys def collatz(start, limit=-1, cycles=1): print(cycles, "-> ", int(start)) if limit == 0 or start == 1: print("Completed %d cycles, stopped at %d" % (cycles, start)) return if start % 2 == 0: return collatz(start / 2, limit - 1, cycles + 1) else: return collatz((start * 3) + 1, limit - 1, cycles...
a8eb530a0ff7c2073e7afa7b4c85b9cf70062883
pastpp/MyProggrams
/WeightMaster.py
915
3.5625
4
import math q = [float(input("ваш рост: ")), float(input("ваш вес: "))] z = q[0] * q[0] / 10000 z = q[1] / z z = math.floor(z) if z < 16: print("ваш индекс: " + str(z) + ". Выраженный дефицит массы тела.") elif z < 18: print("ваш индекс: " + str(z) + ". Дефицит массы тела.") elif z < 25: print...
7767bb864ea45d4f12f7374db0cf37b76159e083
kartik-mewara/pyhton-programs
/Python/26_dictionary.py
231
3.8125
4
hindi_dict={ "pankha":"fan", "aadmi":"man", "kitab":"book", # "kitab":"copy" } print(hindi_dict.keys()) a=input("Enter what you want to search from above\n") print(hindi_dict.get(a)) # print(hindi_dict.get("kitab"))
8c02a7056f42c308a08ffbc7abac88c541bf713a
kartik-mewara/pyhton-programs
/Python/43_fact..py
118
4.125
4
fact=int(input("enter number to do factorial\n")) sum=1 for i in range(1,(fact+1)): sum=i*sum print(sum)
78993e5a2442e7947655a263788fbf83a9c50c0d
kartik-mewara/pyhton-programs
/Python/25_sets_methods.py
672
4.4375
4
s={1,2,3,4,5,6} print(s) print(type(s)) s1={} print(type(s1)) #this will result in type of dict so for making empty set we follow given method s1=set() print(type(s1)) s1.add(10) s1.add(20) print(s1) s1.add((1,2,3)) # s1.add([1,2,3]) this will throws an erros as we can only add types which are hashable of unmutable as ...
a09174ecc2b6c068caca02cfb500dcdd6b631ef0
kartik-mewara/pyhton-programs
/Python/20_marks_input_soted.py
263
3.765625
4
marks=[] a=int(input("Enter subject marks\n")) marks.append(a) b=int(input("Enter subject marks\n")) marks.append(b) c=int(input("Enter subject marks\n")) marks.append(c) d=int(input("Enter subject marks\n")) marks.append(d) print(marks) marks.sort() print(marks)
51fe08037ca0d96b83b0dadded63411c1791aecd
kartik-mewara/pyhton-programs
/Python/05_typecasting.py
593
4.125
4
# a="1234" # a+=5 # print(a) this will not work as a is a string but we expect ans 1239so for that we will type cast a which is string into int a="1234" print(type(a)) a=int(a) a+=5 print(type(a)) print(a) # now it will work fine # similerly we can type cast string to int to string int to float float to in etc b=2.3...
dfbe4ecd646c571f9fa0095d4b14ad4564f39743
kartik-mewara/pyhton-programs
/Python/47_last_pattern.py
164
3.765625
4
n=10 for i in range(n): if(i==0 or i==n-1): print("*"*n) else: print("*",end="") print(" "*(n-2),end="") print("*")
332bb7e70a8168e8194a995f6eca4b1983997400
kartik-mewara/pyhton-programs
/Python/13_string_template.py
255
4.34375
4
letter='''Dear <|name|> you are selected on the date Date: <|date|> ''' name=input("Enter name of person\n") date=input("Enter date of joining\n") # print(letter) letter=letter.replace("<|name|>",name) letter=letter.replace("<|date|>",date) print(letter)
3cda503da2456bb654b861d9fcd8fb72ee463bb6
abhitpahwa/Data-Visualization
/dv_lab6_a.py
2,613
3.96875
4
#GGPLOT FOR PLOTS,SUBPLOTS,SCATTERPLOTS IN PYTHON from ggplot import * #using default dataset graph=ggplot(aes(x='rating', y='length'), data=movies) +geom_line() graph.show() import pandas as pd #reading user defined dataset dataset=pd.read_csv("A:/dv/lab/lab6/dataset_lab6.csv") #line plot graph=ggplo...
251aeec3d597a4539a8be8e012871fa1065e7492
norangebit/koob
/src/koob/kobo.py
5,109
3.65625
4
""" This module includes code to interact with a kobo e-reader. """ import sqlite3 from typing import List, Optional from blkinfo import BlkDiskInfo from koob.types import Book, Highlight class KoboDb: """ This class allows interaction with the kobo sql database. """ def __init__(self, db_path: str)...
f491c8e5706594cd5cb19825051d3e276d91b90a
murugesan-narayan/hr_python
/hr_python/math/medium/AngleMBC.py
141
3.625
4
import math if __name__ == '__main__': ab, bc = map(int, [input(), input()]) print(str(round(math.degrees(math.atan2(ab, bc))))+'°')
8040e4b49659ac08e99f8b1c5cc6db8e935643e2
murugesan-narayan/hr_python
/hr_python/regex_parse/easy/HTMLParserTwo.py
590
3.59375
4
from html.parser import HTMLParser class MyHTMLParser(HTMLParser): def handle_data(self, data): if '\n' not in data: print('>>> Data', data, sep='\n') def handle_comment(self, data): if '\n' in data: print(">>> Multi-line Comment", data, sep='\n') else: ...
ce4c7a44d2abbfdc3ecc89f4a8782fe38ba4ff60
murugesan-narayan/hr_python
/hr_python/collections/easy/DefaultDict.py
361
3.578125
4
from collections import defaultdict if __name__ == '__main__': n, m = list(map(int, input().split())) n_dict = defaultdict(list) for i in range(1, n+1): n_dict[input()].append(str(i)) for i in range(m): word = str(input()) if word in n_dict: print(' '.join(n_dict[word...
957d721fbef6f61747dce67c9e3e2b6449486b36
murugesan-narayan/hr_python
/hr_python/numpy/easy/MinMax.py
219
3.53125
4
import numpy if __name__ == '__main__': a = [] for i in range(int(input().split()[0])): a.append(input().split()) a = numpy.array(a, numpy.int) m = numpy.min(a, axis=1) print(numpy.max(m))
c91a2f030f9058de3a7a8a051d07ba1d43d438f1
alekselaix/python_basics
/les2/task1.py
606
3.84375
4
# 1. Создать список и заполнить его элементами различных типов данных. # Реализовать скрипт проверки типа данных каждого элемента. # Использовать функцию type() для проверки типа. # Элементы списка можно не запрашивать у пользователя, а указать явно, в программе. user_list = [3.14, True, 'text', 199, None] for...
78f1230597a04f9859e15714639f0336a07eb7b6
alekselaix/python_basics
/les2/task2.py
895
3.90625
4
# 2. Для списка реализовать обмен значений соседних элементов, т.е. # Значениями обмениваются элементы с индексами 0 и 1, 2 и 3 и т.д. # При нечетном количестве элементов последний сохранить на своем месте. # Для заполнения списка элементов необходимо использовать функцию input(). user_list = list() count_list =...
5f1eeb21a54f011b88db9af465804ce2e600b684
alekselaix/python_basics
/les2/task3.py
1,420
3.734375
4
# 3. Пользователь вводит месяц в виде целого числа от 1 до 12. # Сообщить к какому времени года относится месяц (зима, весна, лето, осень). # Напишите решения через list и через dict. number_list = [(12, 1, 2), (3, 4, 5), (6, 7, 8), (9, 10, 11)] season_list = ['Зима', 'Весна', 'Лето', 'Осень'] ...
201ac8b0ed1daa9b8e374cf5880bfb0e57a8faa8
faraic/python_challenge
/PyPoll/main.py
2,921
3.78125
4
# loading the needed modules import os import csv # Setting file path for the CSV file election_csv = os.path.join("PyPoll", "Resources","election_data.csv") # Creating the lists/variables to store data. candidate_percentage=[] candidates= [] candidate_numbers=[] count=0 # Opening the csv using the path with open(...
7a83c19492213103f6ad3b19bdf79b89a1b9fe15
shermanator21/Numpy
/MyArrays2.py
3,070
4.03125
4
import numpy as np import random grades = np.array([[87, 96, 70], [100, 87, 90], [94, 77, 90], [100, 81, 82]]) # each row represents a Student # each column represents a Test """ a = grades.sum() b = grades.min() c = grades.max() d = grades.mean() e = grades.std() f = grades.var() g = grades.mean(axis=0) # axis 0 l...
7ef7c88ff55cdf019052e8f43f397fc62b4a7fed
lubical/LeetCode
/LeetCodePython/py59.py
1,172
3.5
4
# 螺旋矩阵 II # 填充1~n*b到按顺时针顺序螺旋排列正方形矩阵 from typing import List class Solution: def generateMatrix(self, n: int) -> List[List[int]]: left = 0 right = n-1 up = 0 down = n-1 result = [[0]*n for _ in range(n)] num = 1 while True: for i in range(left, righ...
ef9e3a6717da3f62ef8a771c6ad1b48789a457e0
lubical/LeetCode
/LeetCodePython/py22.py
699
3.609375
4
# 给出 n 代表生成括号的对数,请你写出一个函数,使其能够生成所有可能的并且有效的括号组合。 from typing import List class Solution: # 生成写法,在n-1对正确的基础上,枚举每一个字符串的每一个位置插入一对括号,并加入集合去重 def generateParenthesis(self, n: int) -> List[str]: if n==0: return [] pre = set({'()',}) for i in range(n-1): ...
4fc9a62651704585786cfcea7dc27ff48deb2529
lubical/LeetCode
/LeetCodePython/py28.py
691
3.859375
4
# 实现 strStr() 函数。 # 给定一个 haystack 字符串和一个 needle 字符串,在 haystack 字符串中找出 needle 字符串出现的第一个位置 (从0开始)。如果不存在,则返回  -1。 class Solution: def strStr(self, haystack: str, needle: str) -> int: if not needle: return 0 if len(haystack) < len(needle): return -1 for i in range(len(ha...
28dcd7e2b3bc0a5a2ea4b2e68801f2a8b53c89c3
lubical/LeetCode
/LeetCodePython/py24.py
666
3.6875
4
# 两两交换链表节点 class ListNode: def __init__(self, x): self.val = x self.next = None class Solution: def swapPairs(self, head: ListNode) -> ListNode: result = ListNode(0) result.next = head pre = result p = head while p and p.next: q = p.next ...
a7cdc61c0c6975feefdfeddb8ae710d7e5988b24
lubical/LeetCode
/LeetCodePython/py86.py
1,750
3.71875
4
# 给定一个链表和一个特定值 x,对链表进行分隔,使得所有小于 x 的节点都在大于或等于 x 的节点之前。 # 你应当保留两个分区中每个节点的初始相对位置。 class ListNode: def __init__(self, x): self.val = x self.next = None class Solution: def partition(self, head: ListNode, x: int) -> ListNode: dummy1 = ListNode(0) dummy2 = ListNode(0) p = du...
427814d999e0e0f60cd2e18cbb9b8aadee2274af
sambasivaguduru/training3
/threading_programing/thread_sync.py
311
3.515625
4
import threading from time import sleep c=0 def fun(): global c for i in range(5): c=c+1 sleep(1) print c t1=threading.Thread(target=fun, name="t1") t2=threading.Thread(target=fun, name="t2") t3=threading.Thread(target=fun, name="t3") t1.start() t1.join() t2.start() print "sdfdsf" t2.join() t3.start()
2de2cfc9927db1707d374ad7b882d003fffa9f89
jpedrojpedro/paa
/app/monitoria/1_7_623_verifica_soma.py
509
3.609375
4
from ordenacao.merge_sort import merge_sort from busca.binary_search import binary_search from utils.list import generate_list def verifica_soma(s1, s2, x): v1 = merge_sort(s1) v2 = merge_sort(s2) for e1 in v1: e = x - e1 p2 = binary_search(v2, e) if p2 is not None: ret...
bb0ec8d44700de8a3e2966e29e2151004ec7b83c
AntonioBretas/hackerank-training
/Exercício/groupgroupsgroupdict.py
197
3.78125
4
import re value = str(input()) regex = r'([a-zA-Z0-9])\1+' # reg = re.compile(regex) m = re.search(regex, value) # m = reg.search(value) if not m: print(f"-1") else: print(f"{m.group(1)}")
93359733305b4b8c5139f2d533c4e3fbd744e9ba
malliswari3/python-programming
/ms.py
81
3.578125
4
ms=int(input()) sum1 = 0 while(ms > 0): sum1=sum1+ms ms=ms-1 print(sum1)
db454f284563b3838fb79729a26c186e6c082676
nxsy/projecteuler
/problems/2/solution.py
860
3.640625
4
#!/usr/bin/env python """ Solves problem 2 of Project Euler http://projecteuler.net/index.php?section=problems&id=2 Problem statement: Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be: 1, 2, 3, 5, 8, 13, ...
0d8e637a82d54036a06ec7dda8dca0cda9763b81
Chigzzer/Rpg-project
/classes.py
3,013
3.53125
4
import random dmg = 100 class ENEMY: def __init__(self, hp, attack, defence): self.hp = int(hp) self.attack = int(attack) self.defence = int(defence) wild_dog = ENEMY(50, 75, 10) class PLAYER: def __init__(self, min_attack, max_attack, defence, hp = 100): self.hp = int(hp) ...
b07bd4dc4deaaa2d24619d49fc9e2ab61b69cbb0
hyungsok/machine_learning
/python_study/ui/sample_turtle_input_draw_polygon.py
269
3.84375
4
# coding: euc-kr import turtle t = turtle.Turtle() t.shape("turtle") angle = int(turtle.textinput("?", "ڸ ԷϽÿ: ")) for i in range(angle): t.forward(100) t.left(360 / angle) for i in range(angle): t.circle(100) t.left(360 / angle)
9863a659bb0342587f2784f6158690f58aa9a66e
hyungsok/machine_learning
/python_study/ui/sample_turtle_draw_square.py
465
3.828125
4
import turtle def draw_square(w, h): print("\t>> draw_square : %d, %d" %(w, h)) t = turtle.Turtle() t.shape("turtle") t.forward(w) t.left(90) t.forward(h) t.left(90) t.forward(w) t.left(90) t.forward(h) s = turtle.textinput("?", "도형을 입력하시오: ") print("도형 : %s" %(s)) if s == "사각형...
77969671394742c491b5cba08eaa9e3e9e0afa2b
JamesRoth/Unit5
/quiz5.py
573
3.78125
4
#James Roth #5/7/18 #quiz5.py def penultimate(list): return(list[-2]) def plusEquals(list, num): for i in range(0,len(list)): list[i]+=num return(list) def smallest(list): small=list[0] for i in range(1,len(list)): if list[i]<small: small=list[i] return(small) ...
a2d19b9399cc841cfddad44f3fcbb1892c219a7a
alnazer/CS50x-2021
/pset6/cash/cash.py
832
3.859375
4
from sys import exit def main(): # Get positive change change = getChange() # printCoins coins(change) def getChange(): while True: change = input("Number: ") try: change = float(change) if (change > 0): break except: c...
7c1e4f5a47a8ec5f755217162a4effc3b0995b72
samahDD/cs115
/Demo Class Sept 21 2018.py
1,412
3.625
4
from cs115 import * def LCS(S1, S2): '''Length of longest common subsequence of two lists''' if S=="" or S2=="": return 0 elif S1[0]==S2[0]: return 1+LCS(S1[1:], S2[1:]) else: return max(LCS(S1, S2[1:]), LCS(S1[1:], S2)) def coinNames(coinInfo): '''assume coinInfo...
fa31ee34467ec5d601cd91d05cde6eef561ea8b5
samahDD/cs115
/lab8.py
4,543
3.859375
4
#Michael Reilly #I pledge my honor that I have abided by the Stevens Honor System # Demo of hmmm, the Harvey Mudd miniature machine # D.Naumann 2015, rev Oct 2018 # When this file is loaded, it runs the program assigned # to variable RunThis. Debug mode is controlled by # variable Mode. Read all the comment...
97995575e77a032dc10e10c616cd0be13275818f
samahDD/cs115
/Demo Class Oct 22 2018.py
3,738
3.8125
4
# two-part exercise from cs115 import map ''' Part 0 Here is a memoized version of edit distance. Your task: make it trace the calls to fastED_help, indented according to recursion depth. Hint: add a parameter to fastED_help. ''' def fastED(first, second): '''Returns the edit distance between the stri...
bf279b58ccf96238080af0cb4d52b4e3bfca4803
samahDD/cs115
/hw4.py
1,999
4.03125
4
#Michael Reilly #I pledge I have abided by the Stevens Honor System from cs115 import * def pascal_row(n): '''Returns a list of the the row n of the pascal triangle''' if n==0: return [1] elif n==1: return [1, 1] elif n<0: return [] def list_add(K): ''...
6d5e3e1eb4df91dc8bbd8fa358236793d630a447
samahDD/cs115
/demoMod0Lect1a.py
542
3.53125
4
from cs115 import * L = [1,2,3] # this is a list M = range(10) # this is also a list s = 'this is a literal string ACT' # this is a string def cat(s,t): return s + t def dbl(n): '''given a number n, returns 2 times n''' return 2 * n def quad(n): '''given a number n, returns 4 times n''' answe...
bb6ae71d8495ab596d9c4a03d3cd87ee255dfb8a
angad664/Image-Classifier
/cnn.py
4,082
3.921875
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Thu Jul 25 20:07:35 2019 @author: angadsingh """ # part 1 building CNN from keras.models import Sequential from keras.layers import Conv2D from keras.layers import MaxPooling2D from keras.layers import Flatten from keras.layers import Dense #initialize th...
be81ad59bbc81f9da6d3108b50d6508c9a1fb3df
pilas/Lab_Python_02
/Lab03a_1.py
670
3.984375
4
import math answer=0 secondanswer=0 print '-------extra credit question 1--------\n\n' code = input( ' enter a number you want encrypt \n' ) width = int(math.ceil(math.log(code,10))) check = int(math.ceil(math.log(code,10)))-1 secret = int(code) for i in range(width): real = secret/10 remainder = secret%10 ...
b33759776d58b9ec213c082e16814306611baf79
DanielTulha/Project-Gutenberg-Analysis---CodePath
/BookAnalysis.py
6,523
3.9375
4
from heapq import * import collections import random bookName = "A Tale Of Two Cities - Charles Dickens.txt" mostCommonWordsFile = "1000mostCommonWords.txt" class BookAnalysis(): def __init__(self, bookName): self.bookName = bookName self.wordList = self.getWordList(bookName) def getWordList(...
1f8ac6d97ca1472c4b3ee9f24722c8304b18357d
Jmete/deepThorin
/scrape/json_scrape.py
610
3.84375
4
import json def open_jason(f): ''' Opens up a json file of tweets, and extracts tweets to a text file. ''' with open(f) as json_file: data = json.load(json_file) # This is the output file. text_file = open("Output_tweets.txt", "w") # Loop through each element in the json file. for p in data: print('Text:...
8fc35b3146127f6232bee7cd7cc2912b8e56b75b
Rohitm911/1BM17CS079
/fib.py
214
3.96875
4
n = int(input("Enter the number of fibonacci Numbers you want to print : ")) fib = [0,1] i = 2 while (i < n): a = fib[i-1] + fib[i - 2] fib.append(a) i+=1 j = 0 while(j < n): print(fib[j]) j+=1
1d92cf71f005c0dba8dbeaee594bd04bcb9634cb
lee-seul/codingdojang
/make_largest_number.py
440
4.09375
4
# coding: utf-8 # make_largest_number.py def make_largest_number(number_list): digit_list = [] result = '' for num in number_list: if len(str(num)) > 1: for x in str(num): digit_list.append(int(x)) else: digit_list.append(num) digit_list.sort() digit_list.reverse() for digit in digit_list: resul...
e3d01440052c28006a90864cae741eac70d91fdc
AbdullaElshourbagy/Hacker-Rank-Solutions
/Python/05 - Math/01_Polar_Coordinates.py
250
3.625
4
#https://www.hackerrank.com/challenges/polar-coordinates/problem #Solution # Enter your code here. Read input from STDIN. Print output to STDOUT from cmath import polar z = complex(input()) tup= (polar(z)) print(tup[0]) print(tup[1])
1adfb8f724c1fc18f233b198d83bd5dae11b712f
AbdullaElshourbagy/Hacker-Rank-Solutions
/Python/09 - Errors and Exceptions/01_Exceptions.py
401
3.703125
4
#https://www.hackerrank.com/challenges/exceptions/problem #Solution # Enter your code here. Read input from STDIN. Print output to STDOUT t=int(input()) for i in range(t): try: a, b = input().split() print(int(a) // int(b)) except ZeroDivisionError as e: print(f'Error Co...
b50f6a53d454c7b3b6766c0c684c8917bc20c1f3
AbdullaElshourbagy/Hacker-Rank-Solutions
/Python/04 - Sets/12_Check_Subset.py
373
3.546875
4
#https://www.hackerrank.com/challenges/py-check-subset/problem #Solution # Enter your code here. Read input from STDIN. Print output to STDOUT T=int(input()) for i in range(T): A=int(input()) A_test_cases=set(map(int, input().split())) B=int(input()) B_test_cases=set(map(int, input().split...
da3f0025b03dc5a4d55d2d359784fc05a53ecd1d
AbdullaElshourbagy/Hacker-Rank-Solutions
/Python/04 - Sets/11_The_Captain_Room.py
437
4.0625
4
#https://www.hackerrank.com/challenges/py-the-captains-room/problem #Solution # Enter your code here. Read input from STDIN. Print output to STDOUT K=int(input()) rooms_list=list(map(int,input().split())) all_rooms=set() temp_rooms=set() for room in rooms_list: if room not in all_rooms: all_roo...
3aab2f4884f8c8ee2b6a706a627ca26efff3f1fd
mdiksha/PYTHON
/120codes/hash_tables.py
665
3.578125
4
class hashtable: def __init__(self, items): self.bucket_size = len(items) self.buckets = [[] for i in range(self.bucket_size)] self.assign_buckets(items) def assign_buckets(self, items): for key, value in elements: hash_value = hash(key) index = hash_valu...
363ac0a4eed2166a5cd60aceb2558862a0d28c28
rio1004666/My_Algorithm
/Recursive_DFS.py
427
3.75
4
graph = { 1: [2, 3, 4], 2: [5], 3: [5], 4: [], 5: [6, 7], 6: [], 7: [3] } def recursive_dfs(v,discovered): # 이미 발견한 노드는 담아놓았다가 나중에 체크할때 사용 discovered.append(v) for w in graph[v]: if not w in discovered: # 이미 방문한걸로 침 discovered = recursive_dfs(w, discovered) ...
0b13fa56ef658102cc52ea8c5dea0b35d47400fb
blester125/path-finding
/path_finding/path.py
11,553
3.75
4
import math from typing import Tuple, Dict, Optional, Callable, List, Sequence from queue import Queue from copy import deepcopy from collections import defaultdict from itertools import combinations, chain from .priority_queue import PriorityQueue from .graph import AdjacencyGraph, Graph, Node, Cost # Back-track is t...
fd6f4950b4fdd76631619868f22938333061c7e3
kheraankit/coursera
/interactive_python_rice/rock_paper_scissors_lizard_spock.py
2,975
4.28125
4
# The key idea of this program is to equate the strings # "rock", "paper", "scissors", "lizard", "Spock" to numbers # as follows: # # 0 - rock # 1 - Spock # 2 - paper # 3 - lizard # 4 - scissors import random # helper functions def number_to_name(number): """ This function accepts a 'number' as a key and ...
805f857d18ae019168428874485149b848a0ec10
drayoden/pytktest
/calc.py
2,810
3.828125
4
from tkinter import * w = Tk() w.title("Calc") e = Entry(w, font=("Calibri",30), width=10, borderwidth=0, justify="right" ) e.grid(row=0, column=0, columnspan=3, padx=10, pady=10) def button_click(n): current = e.get() e.delete(0, END) e.insert(0, str(current) + str(n) ) def button_clear(): e.delet...
b61a53c131f537dbc586ac8f327717bc086e552d
VasiliMachulski/Test_task_Machulski_Vasili
/TASK_2_FUNCTION.py
241
3.765625
4
def get_first_unique_item(my_list): for element in my_list: if my_list.count(element)>1: return element my_list=['a','b','c','c','a'] first_unique_element = get_first_unique_item(my_list) print(first_unique_element)
7fc571c05761ba2ad429d54a9567c5b1a6fe596a
RejiJose/TurtleArtDesgin
/Triangle_madness.py
1,376
3.796875
4
import turtle from Mydesgin import * #calls in another file. turtle.colormode(255)#RGB color format. turtle.bgcolor("black") #makes background black. bob=turtle.Turtle() bob.speed(0)#sets the speed of bob aka(turtle) for times in range(250): bob.color(times,50,100) polygon(bob,50,3) bob.penup()...
2b6117afba9745fddf4f5622132b528848badc9a
bellajcord/Python-practice
/controlflow.py
2,822
4.4375
4
# Logical operators # and (1 > 2) and (2 < 3) # multiple (1 == 2) or (2 == 3) or (4 == 4) ################################## ### if,elif, else Statements ##### ################################## # Indentation is extremely important in Python and is basically Python's way of # getting rid of enclosing brackets like...
8313396f554449f0f17952a0c3429b5fb403a168
klaudial99/mancala-game
/components.py
1,819
3.640625
4
from typing import List from player import Player class Stone: def __init__(self, color): self.__color: str = color @property def color(self): return self.__color @color.setter def color(self, color): self.__color = color def __str__(self): return self.color...
a11867792c24ea30d53b99671bd13f9fb06dd0ad
Twiggecode/patterns
/Q14/Q14.py
400
3.671875
4
def pattern(n): f=1 for i in range(n): cnt=0 for j in range(1,2*n+2): if j>n-i and cnt<f: print(" ",end='') cnt+=1 else: print("*",end='') print() f+=2 print('\n') x=2*n-1 for i in range(n): cnt=0 for j in range(1,2*n+2): if j > i+1 and cnt< x: print(" ",end='') cnt+=1 ...
fc7c24ed77a547bd786367f500d47a40c1ac668c
hsorby/neon.extension.airwaysmask
/src/opencmiss/extensions/airwaysmask/utils.py
1,007
3.53125
4
def generate_offset_cube_coordinates(dimensions): """ Create a set of eight 3D coordinates that are offset by 0.5. In this case the 0.5 is a pixel so that the centre of the voxel is at the integer coordinate location. :param dimensions: A list of size three containing the dimensions of the cube. ...
d35b3436ebd5aee33c9445dd70a0f0cb5156103c
hephaex/deeplearning-note
/3_ETRI-lecture/tictactoe/tictactoe.py
2,182
3.546875
4
# -*- coding: utf-8 -*- import numpy as np class TicTacToeEnv: def __init__(self): self.board = None self.current_player = None self.result = None self.reset() def reset(self): self.board = np.zeros(9, dtype=np.int32) self.current_player = "x" def step(s...
fbc4a8dd4a12d06f5ad44d0224f23b3bea84e693
shmalex/project-euler
/problems-1-10/p0003.py
1,669
3.65625
4
''' The prime factors of 13195 are 5, 7, 13 and 29. What is the largest prime factor of the number 600851475143 ? You are the 487344th person to have solved this problem. You have earned 1 new award: Baby Steps: Solve three problems This problem had a difficulty rating of 5%. The highest difficulty rating you ha...
f63d84c2bbed537d5017c57b06339bcee0d4b71b
SauravAnchlia/leetcode
/1281_subtract_the_product_and_sum_of_digits_of_an_integer.py
328
3.578125
4
from functools import reduce from math import prod class Solution: def subtractProductAndSum(self, n: int) -> int: product = 1 s = 0 for item in str(n): product *= int(item) s += int(item) return product - s obj = Solution() print(obj.subtractProductAndSu...
5f4ec68d838e6c67927cbf58f758aa965f5b41d1
SauravAnchlia/leetcode
/2_add_two_numbers.py
1,085
3.890625
4
# Definition for singly-linked list. class ListNode: def __init__(self, val=0, next=None): self.val = val self.next = next class Solution: def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode: root = head = ListNode(0) carry = 0 while l1 or l2 or carry: ...
0352bb392701674291b3c5d2ce0af52a5834e9d4
NathanontGamer/Multiplication-Table
/multiplication table.py
894
4.46875
4
#define function called multiplication table def muliplication_table (): #input number and number of row number = int(input("Enter column / main number: ")) number_row = int(input("Enter row / number that (has / have) to times: ")) #for loop with range number_row for i in range (1, number_ro...
e61e37b10702d732908841195c6530246e6b11c5
Garimajoshi-star/polynomial_regression
/polynomial_regression.py
911
3.609375
4
# Import libraries. import numpy as np from sklearn.linear_model import LinearRegression from sklearn.preprocessing import PolynomialFeatures #Defining input and output datapoints. x = np.array([3, 6, 12, 24, 48, 96]).reshape((-1, 1)) y = np.array([14, 10, 5, 9, 35, 42]) # Transforming input data points. tr...