blob_id
stringlengths
40
40
repo_name
stringlengths
5
127
path
stringlengths
2
523
length_bytes
int64
22
3.06M
score
float64
3.5
5.34
int_score
int64
4
5
text
stringlengths
22
3.06M
fc76d77781aa102ece095cd1f1060727ffd6e02d
krenevych/programming
/P_03/ex_7.py
795
3.90625
4
""" Приклад 3.7. Дано натуральне число n. Написати програму для обчислення значень многочлена y(x)=x^n+x^(n-1)+...+x^2+x+1 при заданому значенні x. """ x = int(input("x = ")) n = int(input("n = ")) # =========== Спосіб 1 ====================== z = 1 y = 1 for i in range(1, n + 1): z *= x...
478a6af2ee8170a7b3dd92eef63ae3cd17d9acbd
krenevych/programming
/P_09/ex_2.py
719
3.828125
4
""" Приклад 9.2. Згенерувати текстовий файл, що буде містити послідовність чисел Фібоначчі, що обмежена заданим числом. """ N = int(input("Задайте N ")) f_name = input("Введіть ім'я файлу для запису ") f = open(f_name, "w") # Створюємо текстовий файл для запису F1 = F2 = 1 print(F2, file=f) # Записуємо F2 у фай...
0d0f59c515e0ffb55bfba1cdbb884fa089a7f62f
krenevych/programming
/P_04/ex_5.py
774
4
4
""" Приклад 4.4. Визначити найменший з елементів квадратної дійсної матриці порядку N. """ # Блок введення матриці з клавіатури N = int(input("Кількість рядків матриці ")) M = [] # Створюємо порожню матрицю for i in range(N): # Вводимо рядок матриці row з клавіатури row = list(map(float, input("%d: ...
1a9e9d7aa51b7037942cebc1293ba8955b68cffe
krenevych/programming
/P_01/ex_1_.py
825
3.921875
4
""" Приклад 1.1. Знайти суму цифр двозначного числа. Розв’язок. Нехай x – задане двозначне число, наприклад 25. Сума цифр цього числа є сумою першої та другої цифр цього числа: 2 + 5 = 7. Першу цифру цього числа можна знайти як ділення числа x націло на 10. Друга ж цифра цього числа є остачею від ділення числа x на 10....
c1cb3ffe8784487f23b1220b4649d5b797c6ee71
krenevych/programming
/P_03/ex_10.py
878
3.984375
4
""" Приклад 3.10. Задано послідовність чисел, що завершується числом 0, серед елементів якої є принаймні одне додатне число. Потрібно знайти найбільше серед додатних чисел. """ max = 0 # Поточний найбільший член послідовності while True: # Завершення циклу буде через break a = float(input("Задайте член по...
5113d129124225dba7c10a0b4cde1016f6ea8af6
krenevych/programming
/P_08/ex_2.py
488
4.28125
4
""" Приклад 8.2. За допомогою розкладу функції e^x в ряд Тейлора """ # Описуємо функцію exp def exp(x, eps = 0.0001): S = a = 1 n = 0 while abs(a) >= eps: n += 1 a *= x / float(n) S += a return S # головна програма x = float(input("x = ")) y = exp(x) # використовуємо типове з...
c0bc7ddf6906cefc3e67f38416b447d817af479f
krenevych/programming
/P_02/ex_7.py
305
3.78125
4
""" Приклад 2.7. Для введеної з клавіатури точки x знайти значення функції ... (див.підручник) """ x = float(input("x = ")) if x < -1: f = -x ** 2 + 1 elif abs(x) <= 1: f = 0 else: f = x ** 2 - 1 print("f(", x, ")= ", f)
705c60c3ac68948e04d0615f5ed8aa824a4cae38
Dukex1125/IS211_Assignment4
/search_compare.py
4,993
4.34375
4
import time import random my_list = [] def random_list(my_list, list_size): """Fills the empty list with random integers. Args: my_list (list): empty list to be filled with random integers list_size (int): value to determine size of list Returns: my_list (list): list of random val...
0283928071b921c93a5e26c128fa8845a7cc9856
nurruden/training
/day6/test_format.py
1,707
3.59375
4
#-*-coding:utf-8-*- #/usr/bin/env python __author__ = "Allan" #百分号的方式,比较老,支持的功能相对format较少 #format支持的功能较多 # s = "I am %s,age %d" %('Allan',18) # print(s) # s1 = "I am %(n1)s,age %(n1)d" %{"n1":111} # print(s1) # # #右对齐,占位符10个位置, # s2 = "I am %(n1) + 10s" %{"n1":"Allan"} # print(s2) # # #左对齐,占位符10个位置, # s3 = "I am %(n1) ...
48a856e790519eecb81abe37c42f0e503d860d30
nurruden/training
/NonTraining/mock/test.py
555
3.5
4
#-*-coding:utf-8-*- #/usr/bin/env python __author__ = "Allan" import unittest from function import add_and_multiply import mock class MyTestCase(unittest.TestCase): @mock.patch('function.multiply') def test_add_and_multiply(self,mock_multiply): x = 3 y = 5 mock_multiply.return_value =...
740e08bbbb96eceda3172aeb3e9c1ffeca2d1601
rana-ahmed/solutions-YWRtaW4
/problems/problem2.py
984
3.890625
4
class Person(object): def __init__(self, first_name, last_name, father): self.first_name = first_name self.last_name = last_name self.father = father def measure_depth(data, depth_data, level=1): object_type = type(data) if object_type not in (dict, Person) or not data: ret...
0edbe19fc1c3b187309f943ad7c1c1c18383c733
ersmindia/accion-sf-qe
/workshop_ex1.py
697
4.25
4
'''Exercise 1: A) Create a program that asks the user to enter their name and their age. Print out a message that tells them the year that they will turn 50 and 100 years old. B)Add on to the previous program by asking the user for another number and printing out that many copies of the previous message. ''' from date...
471ccbb8ebc75b55236c981adb10c9374f6b1c6a
sendemina/lab-07-conditionals
/spanish.py
185
3.953125
4
word = input("Give me a word in Eglish...") if word == "cat": print("gato") elif word == "dog": print("perro") elif word == "horse": print("caballo") else: print("no entiendo")
e4dbf89c39b76564bd52a7f44f7fcdc3733c86f5
shinn5112/Load-Testing
/Examples/utilTests/timeTest.py
210
3.65625
4
import datetime currentTime = datetime.datetime.now() currentTime = str(currentTime).split(" ") currentTime = currentTime[1] currentTime = currentTime.split(".") currentTime = currentTime[0] print(currentTime)
d3a4e61ecc855309b283f0e0878f1841de733c79
LalitaJaiswar/PythonProjects
/countingelementusingdict.py
213
3.6875
4
string=input() map1={}; for i in range(len(string)): map1.setdefault(string[i],[]).append(i) print(map1) '''l=map1['h'] print(len(l[:l.index(15)]))''' for i in map1: print(len(map1[i]),end=" ")
fbae3f65c93fd29a7bbb4561371516328b585c95
Satyaanilkumar/driveready2021
/program3.py
223
4.0625
4
num=int(input()) d=num%10 num = num//10 while num: r=num%10 num=num//10 if (d%2==0 and r%2==0) or (d%2==1 and r%2==1): print("not in a form") break d=r else: print("wave form")
18d4d0a43390a81711f98f5d43b8efacb5e99a04
Satyaanilkumar/driveready2021
/megaprime16.py
882
4.03125
4
import math as m def prime1(num,z): if num==1: return False if num<10: if (num==2) or (num==3) or (num==5) or (num==7) or (num % z != 0): return True return False elif (num%2==0) or (num%3==0) or (num%5==0) or (num%7==0) or (num%z==0): return False r...
01b054b71b2a16c4d9b60359f50bfbf6ace6ce7e
Satyaanilkumar/driveready2021
/pronic number.py
394
3.796875
4
import math num = input("enter the number: ") temp = set() output = [] for i in range(0, len(num)): for j in range(i, len(num)): substr = int(num[i:j + 1]) temp.add(substr) temp = sorted(list(temp)) print("substrings: ", temp) for num1 in temp: val = int(math.sqrt(num1)); if ...
1e6fc4219e2b3e6c61a05e49ef09692805e319d4
NickLydon/algorithms-and-data-structures
/map.py
965
3.546875
4
class Map: def __init__(self): self.size = 11 self.slots = [None] * self.size def put(self, key, data): slot = key % self.size slot_bucket = self.slots[slot] if slot_bucket == None: slot_bucket = [(key, data)] else: slot_bucket = [(k, v) ...
ef70fcbbedbb6ce19697a9ce17190497c2e54ff9
agvanwin/ABC-age-checker
/ABC_check.py
519
3.8125
4
def abc_store_check(): print "Welcome to the ABC age checker" print "Please enter your age" answer = int(raw_input()) if answer < 21: print "Sorry, you are not old enough to shop at the ABC store" return False elif answer > 21: print "Congratulations, ...
d08c53ba5fe5c06c84b199b253554cfb6cecdc80
standrewscollege2018/2019-year-13-classwork-ostory5098
/Object orientation Oscar.py
1,608
4.6875
5
# This is an intro to Object orientation class Enemy: """ This class contains all the enemies that we will fight. It has attributes for life and name, as well as functions that decrease its health and check its life. """ def __init__(self, name, life): """ the init function runs automat...
5b033b7f6ba236f5804ba08ffd4b2e853ad8558a
OmarIbannez/codility-lessons
/PermCheck.py
575
3.59375
4
import timeit import unittest ''' Input list ''' A = [4, 1, 3] ''' output ''' S = 0 def solution(A): ''' returns 1 if A is a permutation and 0 if it is not ''' if set(A) == set(xrange(1, len(A)+1)): return 1 return 0 def time_test(): ''' Function to test the execution time ''' solution...
50795c335dea478508ea01f3380b3b4e394fca72
geoleowills/Python-App-7-Credit-Card-Checker
/credit_card_checker.py
2,069
4.0625
4
while True: # Takes card number as string input, removes any spaces and converts to and int num = int(input("Number: ").replace(" ", "")) # Possible length of amex, mastercard and visa cards, stores values in list AM_len = [15] MA_len = [16] VI_len = [13, 16] # Possible starting numbers for...
397dd7a50709369aaba647e0095dc526102583be
Ariyanayagam/python_guvi
/multOf7.py
65
3.71875
4
a=int(input()) a%=7 if(a==0): print("yes") else: print("no")
918264eeaa1deb5d960028366b4b316d59579dab
Ariyanayagam/python_guvi
/binaryNumOrNot.py
178
3.703125
4
strin=list(map(int,input())) for i in range(len(strin)): if(strin[i]==0 or strin[i]==1): continue else: break if(i==len(strin)-1): print("yes") else: print("no")
400c2f0004987eebcf016493675e499398a6970c
Ariyanayagam/python_guvi
/alphaNumericstr.py
83
3.8125
4
str1=input() for i in str1: if i.isdigit(): print(i,end="") print(" ")
ee6f1e2389319f2e380017730cb3abd5495f9bd3
hainamnguyen/data-structure-and-algorithm-coursera-ucsd
/Coding/Algorithm_toolbox/Week_2/lcm/lcm.py
384
3.78125
4
# Uses python3 import sys # Uses python3 def GCD(a,b): if b > a: print(a,b) return GCD(b,a) r = a%b if r == 0: return b return GCD(b,r) def LCM(x, y): if x >= y: return int(x*y/GCD(y,x)) else: return int(x*y/GCD(x,y)) if __name__ == '__main...
24a2bd940ca4cec1ecded8f9bea3a7bacbdac83f
hainamnguyen/data-structure-and-algorithm-coursera-ucsd
/Coding/Algorithm_toolbox/Week_5/placing_parentheses/placing_parentheses.py
1,936
3.578125
4
# Uses python3 import sys def get_maximum_value(dataset, start, end, Min_matrix, Max_matrix): #write your code here #print(Min_matrix) #print(Max_matrix) #print(start, end) min_temp = sys.maxsize max_temp = -sys.maxsize for i in range(start,end): #print(Min_matrix) #print(Ma...
5ca1ef9a64c1d95c3b87c7f5f453e23e997f42c9
hainamnguyen/data-structure-and-algorithm-coursera-ucsd
/Coding/Advance_Algorithms_and_Complexity/Week_3/_9415c1b69bc94dafe70a1d2749b673d1_Programming-Assignment-3/cleaning_apartment/sample_code.py
2,004
3.5625
4
# python3 import subprocess import itertools import os n, m = map(int, input().split()) edges = [ list(map(int, input().split())) for i in range(m) ] # Initialize the neighbourlist: neighbourList = [[] for i in range(n + 1)] for i in edges: neighbourList[i[0]].append(i[1]) neighbourList[i[1]].append(i[0]) claus...
a3d457ff813c70b7e43e6903222308eaae6ff7ae
FreeTymeKiyan/DAA
/ClosestPair/ClosestPair.py
2,642
4.4375
4
# python # implement a divide and conquer closest pair algorithm # 1. check read and parse .txt file # 2. use the parsed result as the input # 3. find the closest pair in these input points # 4. output the closest pair and the distance between the pair # output format # The closest pair is (x1, x2) and (y1, y2). # The ...
37ab346b32cddbde6eeaf22c63eb394a149789b5
fuatm16/fuatsproject
/character_input.py
935
3.8125
4
__author__ = 'fuat' name = input("What is your name: ") age = int(input("How old are you: ")) year = str((2017 - age)+100) print(name + " will be 100 years old in the year " + year) if ( age%2 == 0 ): print("you are in even age!" ) else: print("you are in odd age!") def tekrardene(retries=0): if retries >...
7e5f9155c0e22abb671c826d940da51c3ba46294
danmaher067/week4
/LinearRegression.py
985
4.1875
4
# manual function to predict the y or f(x) value power of the input value speed of a wind turbine. # Import linear_model from sklearn. import matplotlib.pyplot as plt import numpy as np # Let's use pandas to read a csv file and organise our data. import pandas as pd import sklearn.linear_model as lm # read the datase...
1e52002323e61f5993ab5d992b97298405b14b8b
Boltzy17/chessai
/chess/__init__.py
18,491
3.5625
4
import chess.pieces import copy import numpy as np class InvalidSquareException(Exception): """Created when trying to make an illegal square""" pass class InvalidEnPassentException(Exception): """ Created when trying to take en passent but on an illegal rank""" pass class InvalidCastleException...
155f348531fe12ae2a58b9b739cadfa31f1caa48
choeunyoung0208/silverzerowaterkite
/200110/waterkite04.py
1,044
3.65625
4
# 리스트 추가 및 삭제 # append() 함수 color = ['red', 'blue', 'green'] # 리스트 선언 color.append('write') # color 리스트에 'white' 추가 (리스트 맨 마지막 인덱스에 새로 값을 추가) print(color) # ['red', 'blue', 'green', 'write'] : 리스트 color 출력 # extend() 함수 color = ['red', 'blue', 'green'] # 리스트 선언 color.extend(['black', 'purple']) # color 리스트에 ['bla...
475cbe8399686caa2f266209228bf2424a6fe51d
bouzaien/battleship
/src/Battleship.py
9,141
3.953125
4
import os import random import sys import time from matplotlib import pyplot as plt import numpy as np from PIL import Image import seaborn as sns class Battleship(object): """ This class is used to start a game: initialize a Field() and randomply place Ship()'s. """ def __init__(self, num_ships=2, s...
80b6dfde38ee834f6ef0ef55b558b36e33b77faa
Gopi30k/DataStructures_and_Algorithms_in_Python
/04_Sorting_Algorithms/03_Insertion_sort.py
562
4.125
4
def insertion_sort(arr: list): # O(N)in best case O(N2) in worst case for i in range(1, len(arr)): currentVal = arr[i] j = i-1 while j >= 0 and currentVal < arr[j]: arr[j+1] = arr[j] j -= 1 arr[j+1] = currentVal return arr if __name__ == '__main__': ...
5372afcfcb1a3b4ffb6368b1b5418c31ac860f92
Gopi30k/DataStructures_and_Algorithms_in_Python
/04_Sorting_Algorithms/01_Bubble_sort.py
1,417
4.03125
4
def bubble_sort_naive(arr: list): # O(n**2) length = len(arr) for i in range(0, length): for j in range(0, length): if j+1 < length and arr[j+1] < arr[j] : temp = arr[j] arr[j] = arr[j+1] arr[j+1] = temp print(arr) def bubble_sort(arr: l...
3610ad5114f0b1ca904a164a9048a80429de1fcc
Gopi30k/DataStructures_and_Algorithms_in_Python
/04_Sorting_Algorithms/04_Merge_sort.py
863
4.03125
4
def merge(arr1: list, arr2: list): results = [] i = 0 j = 0 while i < len(arr1) and j < len(arr2): if arr1[i] < arr2[j]: results.append(arr1[i]) i += 1 else: results.append(arr2[j]) j += 1 while i < len(arr1): results.append(ar...
eb7045f3d5b9f3a02d7b3fc26f90bf795a5ebfbf
Gopi30k/DataStructures_and_Algorithms_in_Python
/02_RecursionProblems/01_powerOfNumber.py
480
4.15625
4
def naivePower(base: int, exponent: int): power = 1 for _ in range(0, exponent): power = power*base return power def recursivePower(base: int, exponent: int): if exponent == 0: return 1 return base * recursivePower(base, exponent-1) if __name__ == "__main__": print(naivePower...
56635b0819e7cdbc8b96ec68bb4de313ca0da587
Woobs8/data_structures_and_algorithms
/Python/Sorting/bubble_sort.py
2,850
4.1875
4
import argparse import timeit from functools import partial import random from sorting import BaseSort class BubbleSort(BaseSort): """ A class used to encapsulate the Bubble Sort algorithm Attributes ---------- - Methods ------- sort(arr, in_place=False) Sorts an array using ...
a3c752623a30aadee0992e07013183e4347c432b
Woobs8/data_structures_and_algorithms
/Python/Sorting/radix_sort.py
4,067
4.21875
4
import argparse import os import timeit from functools import partial import random from itertools import accumulate from sorting import BaseSort class RadixSort(BaseSort): """ A class used to encapsulate the Radix Sort algorithm Attributes ---------- - Methods ------- sort(arr, in_p...
c41fb4d1b209b5ff0f6500fc530417464b0567f2
JackZander/Python-Note
/1.4.3Python小程序/m1.5PrintLocalDateTime.py
255
3.75
4
from datetime import datetime # 引用datetime库 now = datetime.now() # 获得当前日期和时间信息 print(now) now.strftime("%x") # 输出其中的日期部分 now.strftime("%X") # 输出其中的时间部分
02892fe358a7571652380d6e1f4c8cd0769f4e28
hengxuan/PythonWork
/study/little.py
491
3.796875
4
'''---just a work---''' import random say = input('what i want to say:') guess = int(say) secret = random.randint(1,10) time = 1 if guess == secret: print('you are right' + ' wow') else: print('go on ' + 'my bro') while guess != secret and time < 3: if guess > secret: #elseif? ...
815a6fb9358f73eedd5bf16143f66e14600a7219
levYuval1007/NAND2Tetris
/Project 07-Virtual machine part 1/Parser.py
2,826
4.03125
4
class Parser: """ this class is responsible for parsing a given code file and split all lines to its components. """ def __init__(self, vm_file_path): """ initializing a new parser object :param vm_file_path: the path for the current code file """ self.__file...
399c5ef8c21a941dc0a965094f107b4d94464e75
pelmeshka812/py_projects
/simple_tasks/task_2.py
462
3.796875
4
import os filename = input("Enter:").split() if os.path.isabs(filename[1]): f = filename[1] else: f = os.getcwd().join(filename[1]) if filename[0] == 'cd': try: print(os.getcwd()) os.chdir(filename[1]) print(os.getcwd()) except FileNotFoundError: print("File not found") ...
c237fcdbec281a2bd652959c650c0f2732f0c2bd
analistadeperon/curso-programacao-python
/exercicios/exercicios_01/valida_cpf_02.py
1,763
3.71875
4
# Esta função retornará verdadeiro (True) # se todos os números do CPF forem iguais. def todos_numeros_iguais(cpf): i = 0 while i < len(cpf): if cpf[i - 1] != cpf[i]: return False i += 1 return True # Esta função serve para auxiliar no cálculo # para retornar o primeiro ou segun...
7ba389700e764d26b5da83593186c8e68d26f24a
vighneshbirodkar/asp
/asp_pf.py
2,823
3.515625
4
""" Path finder for adverserial shortest path """ import socket import sys import networkx as nx def get_most_unique_path(paths): if len(paths) == 1: return paths[0] picked_path = None penultimates = {} path_penultimate_map = {} # Strategy: Pick the least common entry spot into the desti...
c0be33dc29d61aa419c6c5bbf98dc6b7b50df067
zz-zhang/some_leetcode_question
/source code/701. Insert into a Binary Search Tree.py
918
3.796875
4
from utils import TreeNode from typing import List, Optional class Solution: def insertIntoBST(self, root: Optional[TreeNode], val: int) -> Optional[TreeNode]: if not root: return TreeNode(val) self.insert(root, val) return root def insert(self, node, val): if not n...
e3e202321bec2a06246477db2b32f2fa4a80d8eb
zz-zhang/some_leetcode_question
/source code/79. Word Search.py
1,022
3.5
4
class Solution: def search(self, board, x, y, sub_word, used): if len(sub_word) == 0: return True if sub_word[0] != board[x][y]: return False if len(sub_word) == 1: return True dir = [(0, -1), (0, 1), (-1, 0), (1, 0)] # print(board[x][y]) ...
edea4a84d91489e9662c6c20bf1e8dcd15d363e6
zz-zhang/some_leetcode_question
/source code/1019. Next Greater Node In Linked List.py
927
3.5
4
from random import randint from typing import * from utils import build_list # Definition for singly-linked list. class ListNode: def __init__(self, val=0, next=None): self.val = val self.next = next class Solution: def nextLargerNodes(self, head: Optional[ListNode]) -> List[int]: stack...
94ca0ba6e312e02c8c493f739cd1a4e647dd13c6
zz-zhang/some_leetcode_question
/source code/108. Convert Sorted Array to Binary Search Tree.py
2,534
3.734375
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 build_BST(self, num_list, index, depth): root = TreeNode(num_list[index]) left_sub_list = num_list[:index] right_sub_li...
84740655be9f86ea26793630105fed1fd7f96776
zz-zhang/some_leetcode_question
/Mock Interview/6/Reverse String II.py
1,032
3.640625
4
''' Given a string s and an integer k, reverse the first k characters for every 2k characters counting from the start of the string. If there are fewer than k characters left, reverse all of them. If there are less than 2k but greater than or equal to k characters, then reverse the first k characters and leave the oth...
42aaec577c69635100ff0f33daa15ec502f869ae
zz-zhang/some_leetcode_question
/source code/70. Climbing Stairs.py
254
3.53125
4
class Solution: def climbStairs(self, n): fe = [1, 2] for idx in range(2, n): fe.append(fe[idx-1] + fe[idx-2]) return fe[n-1] if __name__ == '__main__': sol = Solution() n = 4 print(sol.climbStairs(n))
229442e6641d506e732cb1c4f35c39f9b59317b0
zz-zhang/some_leetcode_question
/source code/74. Search a 2D Matrix.py
1,206
3.796875
4
from random import randint from typing import List class Solution: def searchMatrix(self, matrix: List[List[int]], target: int) -> bool: i = 0 j = len(matrix) - 1 while i < j - 1: # breakpoint() mid = (i + j) // 2 if target == matrix[mid][0]: ...
d61c45664c9199210a521ebe49dd8dbf411d163c
zz-zhang/some_leetcode_question
/source code/94. Binary Tree Inorder Traversal.py
745
3.90625
4
# Definition for a binary tree node. class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: result = [] def inorder_travel(self, root): if root.left is not None: self.inorder_travel(root.left) self.result.ap...
9dbf21f59254cdbc966bfc50120e7ed7c6f538af
zz-zhang/some_leetcode_question
/source code/17. Letter Combinations of a Phone Number.py
815
3.59375
4
from typing import List class Solution: def letterCombinations(self, digits: str) -> List[str]: self.dig2chars = { dig: ''.join([chr(97 + 3 * (dig - 1) - 3 + i) for i in range(3)]) for dig in range(2, 7) } self.dig2chars[7] = 'pqrs' self.dig2chars[8] = 'tuv' self....
c92079c845a3d669b31524265982edbf122b92ae
zz-zhang/some_leetcode_question
/source code/222. Count Complete Tree Nodes.py
1,160
3.921875
4
from utils import TreeNode from typing import List, Optional class Solution: def countNodes(self, root: Optional[TreeNode]) -> int: if not root: return 0 route = self.find_last_leaf(root, []) # print(route) res = (2 ** (len(route))) - 1 # print(res) last...
b74877f581a52bb65489d533a297cbd61a3684bd
zz-zhang/some_leetcode_question
/source code/1047. Remove All Adjacent Duplicates In String.py
371
3.765625
4
class Solution: def removeDuplicates(self, s: str) -> str: stack = [] for char in s: if len(stack) == 0 or stack[-1] != char: stack.append(char) else: stack = stack[:-1] return ''.join(stack) if __name__ == '__main__': sol = Soluti...
9485ed25920a81a2722c1b81fe77dae22e27eabf
zz-zhang/some_leetcode_question
/source code/703. Kth Largest Element in a Stream.py
586
3.78125
4
from typing import List class KthLargest: def __init__(self, k: int, nums: List[int]): self.k = k self.nums = sorted(nums, reverse=True)[:self.k] # self.res = self.nums[k - 1] def add(self, val: int) -> int: if len(self.nums) >= self.k and val < self.nums[-1]: retu...
f829ae3e7e94be4b2e37c157c85a8ba63163ba99
zz-zhang/some_leetcode_question
/source code/121. Best Time to Buy and Sell Stock.py
524
3.59375
4
from typing import List import random class Solution: def maxProfit(self, prices: List[int]) -> int: res = 0 min_price = prices[0] for p in prices: res = max(res, p - min_price) # print(p, min_price, res) if p < min_price: min_price = p ...
ec5f9357b58a3bae7a50d8b45df09bfa8cfcbc9f
zz-zhang/some_leetcode_question
/source code/376. Wiggle Subsequence.py
1,097
3.671875
4
from typing import List from random import randint class Solution: def wiggleMaxLength(self, nums: List[int]) -> int: ''' O(n) solution ''' if len(nums) == 1: return 1 left, right = 0, 1 # route = [nums[0]] res = 1 while left <= right <...
e49bbbc5987a86059c87d3e4ab8aa6f72b8a19b9
zz-zhang/some_leetcode_question
/source code/350. Intersection of Two Arrays II.py
687
3.59375
4
from typing import List from random import randint class Solution: def intersect(self, nums1: List[int], nums2: List[int]) -> List[int]: cache = {char: 0 for char in nums1} for num in nums1: cache[num] += 1 res = [] for num in nums2: if num in cache and cach...
a4cd7013f93f5a7a66e567cc801063e95d77bdf1
zz-zhang/some_leetcode_question
/source code/1239. Maximum Length of a Concatenated String with Unique Characters.py
830
3.515625
4
class Solution: def maxLength(self, arr): total = ''.join(arr) total_len = len(total) all_repeated = '' seen = '' for s in total: if s not in seen: seen = seen + s else: all_repeated = all_repeated + s all_repeat...
90977c0a1cd605c2d84f013ff3a57e1956f02dbe
zz-zhang/some_leetcode_question
/source code/817. Linked List Components.py
1,090
3.578125
4
# Definition for singly-linked list. class ListNode: def __init__(self, val=0, next=None): self.val = val self.next = next def create_by_list(l): head = ListNode(l[0]) node = head for num in l[1:]: node.next = ListNode(num) node = node.next ...
4c158fbee60ada82951d230a50f07f007a11d36e
zz-zhang/some_leetcode_question
/source code/56. Merge Intervals.py
1,626
3.703125
4
# Definition for an interval. class Interval: def __init__(self, s=0, e=0): self.start = s self.end = e def take_start(interval): return (interval.start, interval.end) class Solution: def merge_able(self, interval_1, interval_2): if interval_1.start > interval_2.start: ...
697ba3aa40a21e1b0e9fb4eb24f8c9171c2a93ff
zz-zhang/some_leetcode_question
/source code/257. Binary Tree Paths.py
751
3.59375
4
from utils import TreeNode from typing import List, Optional class Solution: def binaryTreePaths(self, root: Optional[TreeNode]) -> List[str]: self.res = [] self.dfs(root, '') self.res = [s[2:] for s in self.res] return self.res def dfs(self, node, path): new_path = f'{...
c3a34c6954ca71247c88fdd64004ca245adc5bf3
Tybarn/Polytech_S9_TAL_Projet
/src/python/extract_text.py
589
3.5625
4
###### Exo 1 : Question 2 ##### import sys import re # Check arguments if len(sys.argv) != 3: raise ValueError("Invalid Arguments : Command line should be 'python extract_text.py <input file> <output file>") # Open input file and create output file inFile = open(sys.argv[1], 'r') outFile = open(sys.argv[2], 'w') ...
08499a5edc9025e4ce44314b9a3aff4e6e02ba9f
binarioGH/dates
/main.py
2,702
4.09375
4
#-*-coding: utf-8-*- from tkinter import * from sys import argv def do_all(date): ret = get_date_in_days(date) if ret == -1: return "Incorrect date." else: return get_day_of_the_week(ret) def get_date_in_days(date): date = date.strip().split("/") try: years = int(date[-1]) months = int(date[0]) days ...
525767711c275bb239b1a63e3767de74700a17de
TimeFlyer28/misc-python-scripts
/While Loops.py
422
4.0625
4
numberr = int(input("choose")) if (numberr % 3) == 0: print ("yes") else: print("no") input('press enter to continue') number = 1 while number <= 100: if (number % 3) == 0: print (str(number) + " - yes") number=number+1 else: print (st...
a32c177cf81ab36851ef9625db99159e0f7e5c7a
politeist/p8s_telegram_bot
/src/features/speech_recognition.py
1,320
4
4
import nltk from nltk.corpus import stopwords from nltk.tokenize import word_tokenize, sent_tokenize # Input text - to summarize text = """ """ # Tokenizing the text stopWords = set(stopwords.words("english")) words = word_tokenize(text) # Creating a frequency table to keep the # score of each word fr...
0eb2e82a8e4bd2baa7ca968f848499b9f3bd7d31
League-Advisor/league-advisor
/league_advisor/string_assets/colors.py
698
3.546875
4
"""This module provides a class to print colored strings to the terminal """ class color: """ This class provides coloration for printed string Methods: None Arguments: None Return: None """ BLACK = "\033[1;30m" RED = "\033[1;31m" GREEN = "\033[1;32m" BLUE = "\033[1;34m" MAGENTA = "\033[1;...
d135336dc618d4e2027e929946c3af52e39182a9
purpleknightleo/PandasDataFrameDemo
/basic.py
5,412
3.796875
4
import pandas as pd from pandas import DataFrame import numpy as np from common import split # construct a dataframe with row/column indices def get_df_1(): return DataFrame(np.arange(1, 19).reshape(6, 3), columns=list('abc'), index=pd.Series(['ZJ', 'LN', 'BJ', 'JS', 'SH', 'XJ'], name='Provi...
453379befa2c33f988598bc0d610edd32d2ea1c7
Lee2907/error-handling
/main.py
1,446
3.765625
4
from tkinter import * from tkinter import messagebox #window root = Tk() root.geometry('500x500') root.title('Login Form') root.config(bg="aqua") #username label and text entry box usernameLabel = Label(root, text="Please enter username:") usernameLabel.place(x=5, y=5) usernameEntry = Entry(root) usernameEntry.place...
6c7fd5cd1ae39b65a46f62503efaa433c87f32ac
birdchan/project_euler
/problems/004/run.py
543
3.875
4
import math def is_palindromic(num): s = str(num) mid_index = int(math.floor(len(s)/2)) # middle is fine for i in range(mid_index): if s[i] != s[-(i+1)]: return False return True def get_largest_palindromic(): largest = -1 for i in range(100, 1000, 1): for j in range(100, 1000, 1): p...
e1165d7c1b955ab0dcb117251aef77a94143042d
birdchan/project_euler
/problems/023/run.py
1,087
3.8125
4
import math def find_proper_divisors(n): if n < 1: return [] divisors = [] up_to = int(math.sqrt(n)) + 1 for i in xrange(1, up_to, 1): if n % i == 0: divisors.append(i) if i != n/i and i != 1: divisors.append(n/i) return divisors def sum_ints_cannot_be_written_as_sum_of_two_abun...
8318887369dcd86369ddfd01a952b07380659d2f
birdchan/project_euler
/problems/015/run.py
1,931
3.828125
4
import math import string # m is horizontal # n is vertical # # m, i -> # # ? ? ? ? 1 # ? ? ? 4 1 # ? ? 6 3 1 # ? 4 3 2 1 # 1 1 1 1 1 # def print_matrix(matrix): for row in matrix: print row print return def build_matrix(m, n): # init matrix = [] for j in range(n+1): row = [] for i in ran...
7ae336a9cebff0aba99a923c9a20f7ec5c7ed86f
ocipap/algorithm
/baekjoon/3009.py
352
3.71875
4
x = [] y = [] def findOneElement (arr): if arr[0] == arr[1] : return arr[2] elif arr[1] == arr[2]: return arr[0] else : return arr[1] for i in range(0, 3) : a, b = map(int, input().split()) x.append(a) y.append(b) answer_x = findOneElement(x) answer_y = findOneElement(...
f07f2facbe4b237b88fafc609bd8b5cd7607e631
dLeandroT/pyCositas
/list_and_dicts.py
940
3.84375
4
def run(): my_list = [1, "hello", True, 4.5] my_dict = {"firtName": "Deyvit", "lastName": "Tenjo"} # Super Lista de Diccionarios super_list = [ {"firtName": "Deyvit", "lastName": "Tenjo"}, {"firtName": "Leandro", "lastName": "Rocha"}, {"firtName": "Jose", "lastName": "...
1977f7c27b98b01bf1a1d11df1fd9675b3ec10b2
a1347539/algorithms-and-data-structure
/LongestPalindrome.py
821
3.515625
4
def LPS(s): start = 0 maxlength = 1 i = 0 #for iteration low = 0 #result n = len(s) high = n if n == 1: return s for x in range(n): low = x high = x + 1 while low >= 0 and high < n and s[low] == s[high]: if ...
d7f3c91ec17e2d7c50900d6a9c7886c049d5c2f2
a1347539/algorithms-and-data-structure
/divide_and_conquer.py
340
3.671875
4
import math def dac(A, target): l = 0 h = len(A)-1 while l<=h: mid = round((h+l)/2) if A[mid] == target: return mid elif A[mid] < target: l = mid + 1 else: h = mid - 1 return "not found" A = [1,4] target = 0 pri...
be6d2fc1e35fbaedb234ae1d11d3466d356fa798
heydharmik/basic-python-programs
/working_with_numbers.py
224
3.765625
4
from math import * temp = 43 print(2) print(2.0234) print(-2.532) print(str(temp) + " is my favourite number") print(temp + " is my favourite number") # This will throw an error # for further details go to documentation
a8fb5388412262c019a28bf5491b25aff84b9470
wyt-wyt/wyt
/singelink.py
1,341
3.546875
4
# coding:utf-8 class Node(object): def __init__(self, elem): self.elem = elem self.next = None class SingleLink(object): def __init__(self): self._head = None def is_empty(self): """链表是否为空""" return self._head == None def length(self): """链表长度""" ...
2e6ebd01b1e1e5b508501d5a2536d5b85883af23
lbray/Python-3-Examples
/file-analyzer.py
370
4.28125
4
# Program returns the number of times a user-specified character # appears in a user-specified file def char_count(text, char): count = 0 for c in text: if c == char: count += 1 return count filename = input("Enter file name: ") charname = input ("Enter character to analyze: ") with open(filename) as f: da...
a33f2ded9c6ebd242890d23c269cd6c95b48fe29
suhridmulay/python_atlas_game
/main.py
3,839
3.59375
4
from functools import reduce from os import path import random from typing import List # Loads data from given country file def load_data(): def trim_and_lcase_string(s: str): return s.strip().lower(); country_file_path = path.join('.', 'assets', 'countries.txt') country_list: List[str...
c217e7cd675ef1a2efb699a3f374722940310c1b
poonyapat/c-with-tutorial
/convertThisToC-1.py
125
3.515625
4
password = 'c' inputPassword = input() while inputPassword != password : inputPassword = input() print("SU SU NAJA")
bc09b1a36ab73b9dee04a93bc305a18ce7f6cdd2
nsnider7/CSE331Repo
/Project7/mimir_testcases.py
4,107
3.609375
4
import unittest from HashTable import HashNode, HashTable, anagrams class TestProject7(unittest.TestCase): def test_double_hashing(self): ht = HashTable() index = ht.double_hashing("abc", True) assert (index == 0) index = ht.double_hashing("def", True) assert (index == ...
7f5e3ede44495e7607129310c81f75dae5c078bd
TheUgKhan/Learn-Python-Full
/Data-Structures-in-Python-master/Full Code/Doubly-Linked-List-in-Python-master/node.py
202
3.703125
4
#Node that contains data and two pointers to point next and previous element(Node) class Node: def __init__(self , value): self.data = value self.next = None self.prev = None
62ec4366130e7820a14e51db1408d2eb0bf74a5e
RRisp/Konane
/src/move.py
1,174
3.5
4
""" this class holds the positions of a valid move from start piece to goal state """ def strip(string, delims): newstring = '' for i in range(len(string)): if string[i] not in delims: newstring+= string[i] return newstring def parse(encoded): print(encoded) retli...
5d90be6e1fa72ccfef5765962db8bd5b96409846
NicolasDhaene/Number-Guessing-Game
/guessing_game.py
3,213
4.34375
4
""" Python Web Development Techdegree Project 1 - Number Guessing Game -------------------------------- For this first project we will be using Workspaces. NOTE: If you strongly prefer to work locally on your own computer, you can totally do that by clicking: File -> Download Workspace in the file menu after you for...
f2e134b91d6050db2743446a13713b347fd4b9c5
xczhang07/leetcode
/python/middle/find_bottom_left_tree_value.py
797
3.78125
4
# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution(object): most_left_val = 1 max_depth = 1 def findBottomLeftValue(self, root): """ :type root: TreeNode ...
de0a38bf5effb34514b6e27ca46e995031db51cc
xczhang07/leetcode
/python/easy/min_stack.py
1,202
4
4
class MinStack(object): def __init__(self): """ initialize your data structure here. """ self.elem_stack = list() self.min_stack = list() def push(self, x): """ :type x: int :rtype: void """ self.elem_stack.append(x) ...
45d1feb13e67e339288d8fe4da788a2bd13ff80b
xczhang07/leetcode
/python/easy/minimum_absolute_difference_in_bst.py
830
3.828125
4
# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution(object): def getMinimumDifference(self, root): """ :type root: TreeNode :rtype: int """ se...
d7ffc293abdaa4e034b99f07c6a066b875862050
jtron82/Python-Data-Analysis
/plot3.py
470
3.734375
4
from data import * import matplotlib.pyplot as plt dataframe = df[['primary_type']] all_crime_count = pd.DataFrame(dataframe.groupby('primary_type').size().sort_values(ascending=True).rename('Crime Count')) data = all_crime_count.iloc[-6:-1] print(data[::-1]) data.plot(kind='line') plt.title("Line Chart") plt.xla...
7bb3d016025ac823a86de341d8fa3f39633d705b
vijaytummala-pythondeveloper/DSA
/maximumpairwiseproduct/maximumpairwiseproductwith_optimization.py
705
3.671875
4
n = int(input("enter numbers count : ")) numbers = input("enter numbers seprated with space : ") numbers_list = [] for i in numbers.split(" "): numbers_list.append(int(i)) print(numbers_list) import time # numbers_list = [i for i in range(1,10000)] begin = time.time() bignum_index = 0 for i in range(0,len(numbers_...
1d1b0dde20967eafb928196f1cc628d177841667
Jotahm/Aplicacion_practica_python
/1.2.1_calculador_salario.py
680
3.890625
4
# EJERCICIO PRÁCTICO # Crea un programa en el que se calcule el salario de un trabajador en el que las primeras 40 horas cobra "p" y de ahí en adelante "p*1.5" la hora. Utiliza los siguientes conceptos: #def computepay(horas, retribución): #return 42.37 #hrs = input("Ingrese horas:") #p = computepay(10,20) #print...
7b8ac0dabddc2eed2e6271d35bee3dd2c8a0744b
ljdongysu/git_pro
/python-demo/pytorch_import/vat_impor.py
214
3.5
4
a= 10 a += 10 print("in file not in Function!\n") def aaa(): print("in Function!\n") def bbb(): print("in function B!\n") def ccc(): print(a) if __name__ == '__main__': aaa() print("in name")
8035f0fcc04cfa796204a5b2c896d89372d32c9a
ljdongysu/git_pro
/moudule/vsearch.py
513
3.875
4
def search4vowels(phrase: str) -> set: """Return any vowels found in supplied pharse.""" vowels = set('aeiou') return vowels.intersection(set(phrase)) def search4letters(phrase: str, letters: str='aeiou') -> set: """Return a set of the 'letters' found in 'phrase'.""" return set(letters).intersecti...
3036a20c471917df24d0deec087e7f8f8d7970cd
ljdongysu/git_pro
/PytorchDemo/algorithm_python/冒泡排序.py
403
3.59375
4
def blobSort(arr:list): if len(arr)<=1: return arr for i in range(0,len(arr)): for j in range(1,len(arr)-i): if arr[j-1] > arr [j]: temp = arr[j] arr[j] = arr[j-1] arr[j-1] = temp return arr def main(): a = [49,23,12,79,36,49,42...
a89c1ed5213483a2f41807e7cb0b71b5bf509e5f
Chi-Chu319/MyNeuralNet
/Functions/Convert.py
1,169
3.5
4
import numpy as np def convert_into_binary(y, nL): binary_y = np.zeros((nL, y.shape[1])) for i in range(0, y.shape[1]): binary_y[:, i][y[:, i]] = 1 return binary_y def convert_into_int_threshold(y_hat, threshold): # i is the index of row; j is the index of column number_matrix = np.array([0,...
4f69aa06b7c3a23bfb194b8b4997210d173674db
Aleksandra-Polakowska/Wisielec
/Wisielec.py
2,173
3.875
4
'''Klasyczna gra w wisielca. Komputer losowo wybiera słowo, a gracz próbuje odgadnąć jego poszczególne litery. Jeśli gracz nie odgadnie w porę całego słowa, mały ludzik zostanie powieszony.''' import random #stałe HANGMAN=(''' +---+ | | | | | | =========''', ''' +---+ ...