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
7a6b0a8b700b7f3043beea59edc540e2895d6495
cjake90/adventofcode
/day5/part1.py
1,847
3.59375
4
#import the list of guard events from the file input_file = open('input.txt', 'r') polymer = input_file.readlines()[0] #delete new line character polymer = polymer.replace('\n','') #set flags for while loops #complete indicates a full pass through the polymer was completed with no reactions complete = False #reaction...
d2413a6abfe5fd9b12821ccbe832c86b60d2cce8
hirotoyoshidome/python-utils
/neural_network/sigmoid_function.py
483
3.515625
4
#!/usr/bin/python3 import numpy as np import matplotlib.pylab as plt # シグモイド関数 # 自然対数を利用する # 非線形の曲線のグラフになる def sigmoid_function(x): return 1 / (1 + np.exp(-x)) # シグモイド関数にながす sa = np.array([-1.0, 1.0, 2.0]) print(sigmoid_function(sa)) # グラフを設定する x = np.arange(-5.0, 5.0, 0.1) y = sigmoid_function(x) plt.plot(x, ...
88e63e921ebf56ed790e9c9a85887ba82c97e89f
aqqje/MoocPythonNote
/test/02/fibonacciSequ.py
928
3.75
4
""" 描述 斐波那契数列如下: F(0) = 0, F(1) = 1 F(n) = F(n - 1) + F(n - 2) 编写一个计算斐波那契数列的函数,采用递归方式,输出不超过n的所有斐波那契数列元素 调用上述函数,完成如下功能: 用户输入一个整数n,输出所有不超过n的斐波那契数列元素、输出数列的元素和及平均数,输出按照顺序,用英文逗号和空格分割 此题目为自动评阅,请严格按照要求规范输入和输出。 输入 示例1:5 输出 示例1: """ def Feibo(n): if n == 0: F = 0 elif n == 1: F = 1 else:...
537fe03469a96b38179c48529addbd00f04f8021
aqqje/MoocPythonNote
/week02/Tlotc.py
530
3.890625
4
''' 请编写程序,完成米和英寸之间的长度转换,基本需求如下: 输入英寸,转换成米; 输入米,转换成英寸。 英寸采用in标记,放在数值结尾;米采用m标记,放在数值结尾。 1 米 = 39.37 英寸 输入参数请使用input(),不要增加提示字符串信息。 ''' CurStr = input("") if CurStr[-1] == 'm': In = (eval(CurStr[:-1]) * 39.37) print("{:.3f}in".format(In)) elif CurStr[-2:] == 'in': M = (eval(CurStr[:-2]) / 39.37) print("{:.3...
a1eaaf69869b3adddadf59089c3e43ca34bdcdf9
aqqje/MoocPythonNote
/week05/SevenDigitsDrawV2.py
1,906
3.578125
4
import turtle as t def drawGap(): t.penup() t.fd(5) def drawLine(draw):# 绘制单数码管 drawGap() t.pendown() if draw else t.penup() t.fd(40) drawGap() t.right(90) def drawDigit(digit): # 绘制数字 drawLine(True) if digit in [2,3,4,5,6,8,9] else drawLine(False) drawLine(True) if digit in [0,1...
aa873c2b12bbafddbb316e8251614d90fc823eb6
mentalveritas/tensorflow
/01-LinearRegression/linearRegression.py
820
3.6875
4
import tensorflow as tf # Train data set x_data = [1, 2, 3] y_data = [1, 2, 3] # Try to find values for W and b that compute y_data = W * x_data + b # Weight W = tf.Variable(tf.random_uniform([1], -1.0, 1.0)) # Bias b = tf.Variable(tf.random_uniform([1], -1.0, 1.0)) # Hypothesis hypothesis = W * x_data + b # Simpli...
59389611f968e8688e6cad0fda5f5e9d7291aad3
nirav3650/Read-Excel
/excel_reader.py
1,429
3.515625
4
# -*- coding: utf-8 -*- """ Created on Wed Jul 25 11:41:13 2018 @author: NIRAV.KAKKAD """ import os import xlrd import sys class Excel_reader(): rowno, colno = 0, 0 def __init__(self): print("Reading Excel File") def open_excel(self, filename): workbook = xlrd.open_workbook(filename) ...
d2adb2dc619b81e9cf84821f3b79f334f4e8018a
gardenjw28/swExpertAcademy
/6190_정곤이의단조증가하는수.py
864
3.546875
4
T = int(input()) for t in range(1, T+1): N = int(input()) numList = list(map(int, input().split())) multiList = list() #곱한 값 리스트 for a in range(len(numList)-1): for b in range(a+1, len(numList)): multiList.append(numList[a]*numList[b]) for multiIdx in range(len(multiList)): #곱한...
dcbe94018816bda8efcd8e5b702eb328c136d52f
binhyc11/MIT-course-6.0001
/Finger exercise 4.1.1.py
409
4.15625
4
# Write a function isIn that accepts two strings as arguments and # returns True if either string occurs anywhere in the other, and False otherwise. # Hint: you might want to use the built-in str operation in. def isIn (x, y): if x in y or y in x: return True else: return False x...
ab63f7bc30c0423501eaecba41653c0e4c5cd5d6
devd-99/ctcd
/Arrays and Strings/q7.py
566
3.96875
4
m = int(input()) n = int(input()) matrix = [] for i in range(m): t = [] matrix.append(t) for j in range(n): tStr = str(i)+ ", " + str(j) + ": " matrix[i].append(int(input(tStr))) print("\n\n") for i in range(m): for j in range(n): print(matrix[i][j], end=", ") print() f...
8ec37f711400015cddf4002fdae25ec0eeb004bc
slesouef/PurBeurre_FoodFinder
/myconnector.py
6,857
3.53125
4
#! usr/bin/env python3 # -*- coding:utf-8 -*- """contains method to interact with the MySQL database""" import pymysql from conf import * class Database: """Connect to or populate database""" def __init__(self): # initiate user access self.user = USER self.password = PASSWORD ...
fd91665539aaa8a867c6fb7d8aa43f4877a8d0b6
8989670898/Practicing-0.1
/solid_rectangle.py
314
3.9375
4
def solid_rectangle(n,m): for i in range(n,n+1): for j in range(m,m+1): print("*",end="") print() rows=int(input("Enter the no. of rows:")) columns=int(input("Enter the no. of columns:")) solid_rectangle(rows,columns)
0727891d7bb90fcf5cdf57f35826dc033db1047c
Yogini824/NameError
/PartA_q3.py
2,401
4.53125
5
'''The game is that the computer "thinks" about a number and we have to guess it. On every guess, the computer will tell us if our guess was smaller or bigger than the hidden number. The game ends when we find the number.Also Define no of attemps took to find this hidden number.(Hidden number lies between 0 - 100)''' ...
ceaf43928789e3a45e0d54d0b9bf756506f5a251
Yogini824/NameError
/PartB_q3.py
1,082
4.15625
4
'''Develop a Python Program which prints factorial of a given number (Number should be User defined)''' def factorial(n): # calling function to calculate factorial of given number if n<0: # checking if n is positive or not print("Enter a positiv...
00c16e751fd1d948cea4904db4655d3f1e992acf
pagsamo/google-tech-dev-guide
/70_question/searching/shifted_binary_search.py
1,744
3.875
4
# O(log n) time | O(1) space def shiftedBinarySearch(array, target, debug=False, result=True): left, right = 0, len(array) - 1 while left < right: # Select random pivot mid = left + (right-left)//2 # Ensure the left side of the pivot is a monotonic increasing sequence if debug:...
31c8ef5200a3f890577b910f88654595faeef72d
pagsamo/google-tech-dev-guide
/leetcode/google/tagged/medium/valid_sudoku.py
1,004
3.828125
4
from typing import List class Solution: def isValidSudoku(self, board: List[List[str]]) -> bool: """ There is no rows with duplicates There is no columns with duplicates There is no sub-boxes with duplicates """ # initial data dimension = 9 empty = "....
8cfc7a72e4102cfdb1fbdba0a2dee63cb5313a83
pagsamo/google-tech-dev-guide
/leetcode/google/tagged/merge_interval.py
881
3.921875
4
from typing import List class Solution: def merge(self, intervals: List[List[int]]) -> List[List[int]]: """ Time complexity: O(n) Runtime beats 97.84 % of python3 submissions. """ if not intervals or len(intervals) < 2: return intervals output = [] ...
16a14ac9f1688ca7181ceeb652e40638fd941397
pagsamo/google-tech-dev-guide
/70_question/dynamic_programming/make_change.py
995
3.640625
4
# O(nd) time | O(n) space # where d is the number of denominations def numberOfWaysToMakeChange(n, denoms): """ ways[amount] += ways[amount - denomination] ways[amount] = ways[amount - denomination] + ways[amount] for amount - denomination >= 0 base case: ways[amount=0] = number of ways for smallest...
b1390b7aa981e0d85a94a9cafd183e17a5f67967
pagsamo/google-tech-dev-guide
/70_question/string/caesar_cipher_test.py
860
3.5625
4
import caesar_cipher as program import unittest class TestProgram(unittest.TestCase): def test_case_1(self): self.assertEqual(program.caesar_cipher_encryptor("abc", 0), "abc") def test_case_2(self): self.assertEqual(program.caesar_cipher_encryptor("abc", 3), "def") def test_case_3(self):...
a139f9e0778fbd1d1fb3754cdcbd02bd308c5cc9
pagsamo/google-tech-dev-guide
/leetcode/google/tagged/medium/inorder_binary_tree_traversal.py
886
4.1875
4
from typing import List # Definition for a binary tree node. class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: def inorderTraversal(self, root: TreeNode) -> List[int]: """ Time complexity: O(N) since visit exactly N no...
bd56d52304e40ea37ab251c3e82670b300ea6431
pagsamo/google-tech-dev-guide
/leetcode/recursion/pascal_triangle.py
1,803
3.84375
4
from typing import List class Solution: def generate(self, numRows: int) -> List[List[int]]: def helper(output, n): """ practice recursion to generate pascal triangle """ if n > numRows: return output elif n == 1: o...
20f07ae9d39e0b191f52d4cc155a94493d1525b6
pagsamo/google-tech-dev-guide
/leetcode/recursion/reverse_string.py
419
4.15625
4
from typing import List def reverse_string(s:List[str]) -> None: """ To practice use of recursion """ def helper(start, end): if start < end: s[start], s[end] = s[end], s[start] helper(start + 1, end - 1) print("before", s) n = len(s) if n > 1: helper(0, n - ...
636da422469c9da097081e46671c68aa8cb78443
pagsamo/google-tech-dev-guide
/70_question/binary_tree/invert_binary_tree_test.py
3,984
3.875
4
from invert_binary_tree import invert_binary_tree import unittest class BinaryTree: def __init__(self, value): self.value = value self.left = None self.right = None def __eq__(self, other): return isinstance(other, type(self)) and self.__dict__ == other.__dict__ def inser...
98b79934279779691f78a6a1e0c41fbc7aeb1c0f
pagsamo/google-tech-dev-guide
/70_question/dynamic_programming/knapsack.py
1,168
3.71875
4
def knapsack(items, capacity, debug=None): values = [[0] * (capacity + 1) for _ in range(len(items)+1)] # values[i][j] = max { values[i-1][j] if does not fit # values[i-1][j-w] + v if w < j rows, columns = len(values), len(values[0]) for i in range(1, rows): value, we...
520ab4f90c0f8f430ebc0934b9226dd4956db1bc
pagsamo/google-tech-dev-guide
/leetcode/google/tagged/easy/remove_outer_parenthesis.py
2,149
4
4
""" https://leetcode.com/problems/remove-outermost-parentheses/discuss/364944/Simple-Python-Solution-with-commentary Add element after the start of the outermost parentheses. If we set start = 0, we cannot differentiate between the beginning of an outermost parentheses and the ending of outermost parentheses. We need ...
afe7cc4bb76868c66ac475963f0c43f3f06c0fde
pagsamo/google-tech-dev-guide
/70_question/famous_algorithm/topological_sort.py
4,515
3.8125
4
from collections import defaultdict from collections import deque class Graph: def __init__(self, vertices, dependencies): self.graph = defaultdict(list) self.vertices = vertices # Add edge to graph for u, v in dependencies: self.graph[u].append(v) # O(V + E) ti...
3231ef6292673615fafdfb53aa733d57ffc3c61b
pagsamo/google-tech-dev-guide
/70_question/dynamic_programming/water_area.py
1,119
4.1875
4
""" Water Area You are given an array of integers. Each non-zero integer represents the height of a pillar of width 1. Imagine water being poured over all of the pillars and return the surface area of the water trapped between the pillars viewed from the front. Note that spilled water should be ignored. Sample input:...
cf354fa9a68fb43382a23ce1bb57d5fd2f271682
Sander031/Random_Dagje_Uit
/process_uitjes_file.py
1,711
3.78125
4
""" This module contains all the functions that are related to the processing of the csv files. """ import csv from random import randrange import os import set_logger_profile """Set the logger profile""" logger = set_logger_profile.logger(name=str(os.path.basename(__file__)), leve...
bf3055a77a3a43388431bc0acd18df5c598384db
cmaggard/project_euler
/python/017.py
1,372
3.53125
4
import sys ones = ["","one","two","three","four","five","six","seven", "eight","nine"] tens = ["ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen"] ten_mults = ["", "", "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eigh...
8ca8e49f2d4a1afaf248b147bff5f86b19debea5
agoldblo/EIL-DP_Analysis
/Analysis/Code/Census Relative Distance for MVAP.py
3,718
3.6875
4
import pandas as pd import matplotlib.pyplot as plt import numpy as np from matplotlib.ticker import PercentFormatter import os # change path to local path to dataset path_to_data = r'/Users/ari/Documents/PGP/Differential Privacy/Epsilon12.2Data.xlsx' all_data = pd.read_excel(path_to_data) def relative_distance_figu...
3bd9ad0e94a058ca30b0e8262e2fe5f1a9117cf9
ryan-c44/Python-Assignments
/Python Assignments/Assignment3.py
2,964
3.953125
4
# Ryan Castles, 6433236, CSIT110 # Question 1 print("Question 1") print() #Take user input for upper bound and gap upper_bound = input("Enter upper bound: ") gap = input("Enter gap: ") print() #total starts at 0 total = 0 print("Go forward: ", end="") #For loop to go forward through each intege...
76e0cba188351637313bf8e918ad6b4446e1b472
richardhills/public-oxford-hmo-licenses
/scraper.py
37,459
3.515625
4
# This is a template for a Python scraper on morph.io (https://morph.io) # including some code snippets below that you should find helpful # import scraperwiki # import lxml.html # # # Read in a page # html = scraperwiki.scrape("http://foo.com") # # # Find something on the page using css selectors # root = lxml.html.f...
c09ea4f15fbdff5db3748333a56d9377a302c624
sresis/practice-problems
/binary-tree/branch-sums.py
563
3.65625
4
# This is the class of the input root. Do not edit it. class BinaryTree: def __init__(self, value): self.value = value self.left = None self.right = None def branchSums(root): sums = [] calc_branch_sums(root, 0, sums) return sums def calc_branch_sums(node, curr_sum, sums): if node is ...
4983f02c95329f98637ab43444ee4bf4e2da8346
sresis/practice-problems
/CTCI/chapter-1/string-rotation.py
799
4.125
4
# O(N) import unittest def is_substring(string, substring): """Checks if it is a substring of a string.""" return substring in string def string_rotation(str1, str2): """Checks if str2 is a rotation of str1 using only one call of is_substring.""" if len(str1) == len(str2): return is_substring...
882bcfb7b2306ce9d354e3bfa8f91a976324c43a
sresis/practice-problems
/b_practice/sum-of-left-leaves/left-sum.py
1,133
4.03125
4
# Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def sumOfLeftLeaves(self, root: TreeNode) -> int: # go through each node # if it doesn't hav...
7efc21157c1415c8583b5a2630e4a92956f54c70
sresis/practice-problems
/find-duplicates/find-dupes.py
1,032
3.875
4
""" """ def find_duplicates(arr1, arr2): # determine which array is longer and turn it into a st=e if len(arr1) == len(arr2) == 1: if arr1 == arr2: return arr1 if len(arr1) > len(arr2): lookup_array = arr2 iterate_array = arr1 else: lookup_array = arr1 iterate_ar...
23114beb0d00f2b55d54c4c9390c41d6c89dc70e
sresis/practice-problems
/recursion-practice/q6.py
553
4.25
4
""" Write a recursive function that takes in a list and flattens it. For example: in: [1, 2, 3] out: [1, 2, 3] in: [1, [1, 2], 2, [3]] out: [1, 1, 2, 2, 3] """ def flatten_list(lst, result=None): ## if length of item is > 1, flatten it result = result or [] for el in lst: if type(el) is list: ...
9c7466ecfaba7618b433b4236b48c9da2e440f23
sresis/practice-problems
/b_practice/remove-dups/remove-dups.py
536
3.515625
4
class Solution: def removeDuplicates(self, S: str) -> str: # use a stack here # only need to remove 2 duplicates in a row stack = [] new_str = '' for i in range(len(S)): if stack == []: stack.append(S[i]) new_str += S[i] ...
643f5be652176e1c9d3fcba3dd9ae2d8dbac16de
sresis/practice-problems
/3-num-sum/3-num-sum.py
425
4.03125
4
def threeNumberSum(array, targetSum): output = [] # sort array array.sort() for i in range(len(array)): left = i + 1 right = len(array) -1 while left < right: if array[i] + array[left] + array[right] == targetSum: output.append([array[i], array[left], array[right]]) left += 1 right -= 1 elif...
c966618b85f960580c2b9c95da05b4c1c1c7f104
sresis/practice-problems
/recursion/q6.py
288
3.859375
4
def flatten_list(lst1): """flattens list recursively.""" if lst1 == []: return lst1 if isinstance(lst1[0], list): return flatten_list(lst1[0]) + flatten_list(lst1[1:]) return lst1[:1] + flatten_list(lst1[1:]) print(flatten_list([3, 4,[4, [5, 6], 7], 98]))
ef840e1697149c12074ce5a9fb52ee6c8486dc5d
sresis/practice-problems
/contiguous_seq/cont_seq.py
1,000
4.0625
4
"""Given an array of integers. Find the contiguous sequence with the largest sum. Return the sum >>> longest_seq([2, -8, 3, -2, 4, -10]) 5 >>> longest_seq([2, 0, 4, -1]) 6 >>> longest_seq([-2, 8, 2, -5, 6]) 11 >>> longest_seq([-2, 8, 2, -5, 6]) 11 >>> longest_seq([-2, 20, -50, -5, 6]) 20 ...
8e999e679b3bad7366ab32220e84ddcfc20972a8
sresis/practice-problems
/practice/q1.py
540
4.03125
4
"""Given 2 strings, determine if 1 string is a permutation of the other? For example:: >>> is_permutation('cd', 'dc') True >>> is_permutation('aab', 'aba') True >>> is_permutation('zzyy', 'yyyz') False """ def is_permutation(str1, str2): str1 = list(str1) str1.sort() str2 = list(s...
f42294957046f2be516d8140cd2057e404230692
sresis/practice-problems
/get-nth-fib/get-nth-fib.py
109
3.6875
4
def getNthFib(n): if n == 1: return 0 if n == 2: return 1 return getNthFib(n -1) + getNthFib(n - 2)
4cc25e9f2d41918552acacf4cf59ca3abb23209f
sresis/practice-problems
/duplicate-val/duplicate-val.py
453
3.765625
4
def firstDuplicateValue(array): # handle length of 1 if len(array) == 1: return -1 left = 0 right = 1 dupes = [] while left < len(array)-1: if array[left] == array[right]: dupes.append(right) left += 1 right = left + 1 elif right == len(array) - 1: left += 1 right = left + 1 else: ...
c7e4f4eeedc337b7f98a5df5cbe2aa12b966e1d3
sresis/practice-problems
/binary-tree/node-depths.py
673
3.875
4
def nodeDepths(root): depths = [] total = 0 get_node_depths(root, 0, depths) # return sum of each depth for item in depths: total += item return total def get_node_depths(node, curr_depth, depths): if node is None: return depths.append(curr_depth) new_depth = curr_depth + 1 # when you get to end, ...
cf4396897a11a8f02bcc55762a9ee453c650f4fc
sresis/practice-problems
/remove-array-elements/rm-arr-elements.py
759
4.0625
4
""" Remove array elements that are in a given index range. >>> remove_array_elements([-8, 3, -5, 1, 51, 56, 0, -5, 29, 43, 78, 75, 32, 76, 73, 76], [[5, 8], [10, 13], [3, 6], [20, 25]]) [-8, 3, -5, 29, 43, 76, 73, 76] """ def remove_array_elements(arr, ranges): # see if each element is any of the banned r...
60dac873cef134da654dc80db1f3cb9a26f0c43d
Bhartendu-Kumar/Computer-Pointer-Controller
/prototype_2/src/input_feeder.py
1,911
3.5625
4
''' This class can be used to feed input from an image, webcam, or video to your model. ''' import cv2 from numpy import ndarray class InputFeeder: def __init__(self, input_type, input_file=None): ''' input_type: str, The type of input. Can be 'video' for video file, 'image' for image file, ...
59abff6b23ee97a558f84275373833fe2f12d76a
anon-legion/modules
/GCD_euclids_recursion.py
375
3.875
4
# -*- coding: utf-8 -*- """ Created on Sun Nov 8 20:42:41 2020 @author: =GV= """ def gcdRecur(a, b): ''' a, b: positive integers NOTE: function uses Euclid's algorithm' returns: a positive integer, the greatest common divisor of a & b. ''' if b == 0: return a else: ...
eeb02201260901637bc71c9ac2affe87fc0cbf4d
Krupique/cursos-tensorflow
/02_1_Regressão_Linear/08_regressao_linear_sklearn.py
1,314
3.5625
4
import numpy as np import matplotlib.pyplot as plt from sklearn.linear_model import LinearRegression from sklearn.metrics import mean_absolute_error, mean_squared_error x = np.array([[18], [23], [28], [33], [38], [43], [48], [53], [58], [63]]) y = np.array([[871], [1132], [1042], [1356], [1488], [1638], [1569], [1754]...
a1fed8e1c6707debe20f3e74fb5055cf4cba5030
AndreiGutnik/AndreiGutnik
/02 tuple.py
209
3.78125
4
# Картежи - это немзменяемые списки a = ('alex', 22, True) print(a) print(type(a)) print(a[0]) print(a[0:2]) b = list(a) print(b) print(type(b)) c = tuple(b) print(c) print(type(c))
d18626a5afa67e08f335497ef9656d93ffa6d4c5
JaredTPonting/SimpleCalculator
/calTest.py
947
4.03125
4
# -*- coding: utf-8 -*- """ Created on Thu Jun 18 17:48:37 2020 @author: jared """ def add(x,y): return x + y def subtract(x,y): return x - y def multiply(x,y): return x * y def divide(x,y): return x / y print("select operation") print("1. Add") print("2. Subtract") print("3. Multiply") print("4. D...
dbd89843d85f927c8fb764183a2516d10863b26f
KyrillMetalnikov/A01081000_1510_V2
/lab07/exceptions.py
1,761
4.375
4
import doctest """Demonstrate proper exception protocol.""" def heron(number) -> float: """ Find the square root of a number. A function that uses heron's theorem to find the square root of a number. :param number: A positive number (float or integer) :precondition: number must be positive. :...
85ec9f17fd46ec33f706ac7286ef8092b4a39133
KyrillMetalnikov/A01081000_1510_V2
/a2/dnd.py
14,659
4.4375
4
"""Create an iteration of a DND game.""" import random import doctest def roll_die(number_of_rolls, number_of_sides): """ Simulate a dice roll. Simulate a random dice roll by rolling a certain sided dice repeatedly. The computational thinking i used in this function is an algorithm that more accurate...
6962206a6b3052cb75d5887eefc836a25b73df7e
KyrillMetalnikov/A01081000_1510_V2
/lab02/base_conversion.py
1,924
4.40625
4
""" Convert various numbers from base 10 to another base """ def base_conversion(): """ Convert a base 10 number to another base up to 4 digits. A user inputs a base between 2-9 then the program converts the input into an integer and displays the max number possible for the conversion. The use...
172bb4baa8ccabbf9cc56acc8525af451bb65a66
KyrillMetalnikov/A01081000_1510_V2
/lab10/regular_expressions.py
3,120
4.40625
4
"""Demonstrate correct usage of regular expressions.""" import re import doctest def is_email(address: str) -> bool: """ Determine if there's an email inside of a string. Uses regex search method to see if something matches an email within the text inputted. :param address: A string. :preconditio...
2c1c6bcbcdd5c8be760e866f542b72fbaf47b3ee
KyrillMetalnikov/A01081000_1510_V2
/lab05/sparse_vector.py
3,157
3.59375
4
import doctest """Add and do dot-product on sparse vectors.""" def sparse_add(sparse_one: dict, sparse_two: dict): """ Add two sparse vectors. :param sparse_one: A sparse vector in dictionary format with a 'length' key that has the true length of the dict. :param sparse_two: A sparse vector in dictio...
00533d783c63973c57b3ceecb554a05fd52259c6
Noffky/exam
/game_of_the_year.pyde
1,595
3.890625
4
board = list(range(1,10)) def setup(): global board size (340,340) main(board) def draw(): background (120, 120, 120) for y in range (3): for x in range(3): rect(100*x,100*y,100,100) def take_input(player_token): valid = False while not valid: try: ...
b53f62a033970ffbb9162bab06a28dadf15be4cd
fytzzh/LIP
/scripts/dist.py
3,655
3.953125
4
import random """ To compute the n choose k iteratively """ def c(n, k): if (k == 0): return 1 if (k == n): return 1 ret = n / k for i in range(1, k): print(ret) ret *= (n - i) / (k - i) return int(ret) """ The distribution class groundSet - list of element from the universe dist - a distrib...
8e8f11a7b08ee1ed77b931c98d5654b3ac5138e0
Porkenstein/EurogameAI
/ga_ann_lvl4buildings/game.py
38,607
3.953125
4
from game_objects import * # a simulation of a 3-player game of Andreas Seyfarth and Rio Grande Games' " Puerto Rico " # # Meant to be played with a board, where the user moves what the computer says is moved. # # Some assumptions that we're making here: # # 1. The players are placing their buildings in an efficient ma...
450a6b176a5026e0c94fa3da975367ccc31f0281
Melinal23/Strings
/reverse_words.py
617
3.875
4
def reverseWords(s): words = s.split() words_reversed = [] for word in words: words_reversed.append(word[::-1]) return " ".join(words_reversed) print(reverseWords("Let's take LeetCode contest")) #the same as above, just in one line def reverseWords(s): return " ".join([word[::-1] for w...
4770b2b6c1ff0bd2b9b04a851fcb527c3561f2e5
Melinal23/Strings
/valid_string_braces.py
357
3.796875
4
def valid_braces(braces): b = {']' : '[', '}': '{', ')': '(' } stack = [] for brace in braces: if brace in b: if len(stack) == 0: return False if stack.pop() != b[brace]: return False else: stack.append(brace) return...
187cc1e45ab568d694942268add355a14e03066e
Erpriyanka919/TeachMeSelenium
/sum_of_fractional_series.py
286
4
4
''' Created on 08-May-2019 TO find some of fractional series 1 + 1/2 +1/3 + 1/4 +...+ 1/n @author: priyanka.gupta ''' N = int(input("Enter the number : ")) sum = 0 for num in range(1,N+1): sum = sum + 1/num print(sum) print("Sum of fraction numbers from 1 to 1/",N, "is" ,sum)
2e52ac2b6dbf30570f8bb42a6ed64d89bc814506
Erpriyanka919/TeachMeSelenium
/sample.py
190
3.875
4
''' Created on 07-May-2019 @author: Priyanka.Gupta ''' marks = int(input("marks:")) if marks >= 75: print("Distinction") elif marks >= 50: print("PASS") else: print("FAIL")
21c5a6a3cb95d97ec1d211140778e8911ec79472
Erpriyanka919/TeachMeSelenium
/cc_7.py
188
4.3125
4
''' Created on 07-May-2019 @author: priyanka.gupta ''' year = int(input("Enter the year : ")) if year % 4 == 0: print(year,"is a leap year") else: print(year,"is not a leap year")
1c03c5ffe237fb398cf95bc66cfebe9d17c76cd8
Erpriyanka919/TeachMeSelenium
/test_1.py
219
3.53125
4
''' Created on 12-May-2019 test 1 @author: Priyanka.Gupta ''' letter = "hai sethuraman" for i in letter: if i == "a": pass print("pass statement is execute ..............") else: print(i)
26249ccd1febadada36d8e8b9657470593a4e8c1
felipefreitaseg/303-python
/teste4.py
156
3.796875
4
people = int(input("Quantos seram entrevistados? ")) i = 0 while i < people: i = i+1 idadeM = int(input("Qual a idade mental do entrevistado? "))
d08b1ae41586166414499817aa622231d3404680
BorisovDima/_ex
/flask_/example/app/shop/blueprints/core/utils.py
207
3.5
4
from re import compile pattern = compile(r'\w+') def slugify(string): return '_'.join(pattern.findall(string)).lower() def slugify(string): return '_'.join(pattern.findall(string)).lower()
b8695d240fd79a2766ccfafcf18cc89636ef1a3d
ajs/tools
/puzzles/perlweeklychallenge/ident_matrix.py
775
4.03125
4
#!/usr/bin/env python # From : https://perlweeklychallenge.org/blog/perl-weekly-challenge-011/ # Challenge #2 # Write a script to create an Indentity Matrix for the given size. For # example, if the size is 4, then create Identity Matrix 4x4. For more # information about Indentity Matrix, please read the wiki page. ...
8d2da49d2c60c9ba27df15a320b47435ce75b47e
khssupriya/PythonPrograms
/pythtriplets.py
363
3.578125
4
def pythagoreanTriplets(n): count = 0 for a in range(1, n//3 +1): for b in range(a+1, n//2 +1): c = n - a - b if a*a + b*b == c*c: count +=1 return count def peri() -> int: res = [pythagoreanTriplets(i) for i in range(12, 1000)] re...
da57a2a5113e93b6c6163386136f11e090b8af35
khssupriya/PythonPrograms
/expandnum.py
332
3.640625
4
def expand(num): if num == 0: return 0 dig = list() exp = "" while num > 0: dig.append(num%10) num //= 10 dig.reverse() power = len(dig) - 1 for x in dig: if x != 0: exp += str(x*pow(10,power)) + " + " power -= 1 return exp[:-3] print(e...
07803a9fb1fcd0535ddcb6593189c1f84a37c9fb
pingxiao-blue2/test1
/python.py
292
3.703125
4
def make_great(names): current_name=[] while names: name = names.pop()+',The Great' current_name.append(name) print(current_nam56icians = ['Holic','Alice','Lisa'] make_great(magicians[:]) print('Now magicians:') print(magicians) print(magicians) print(magicians)
8c9d72a1f904f5b745c5b10cbffc9337957feb00
pipilove/python_workspace
/Algorithms/Sort/BubbleSort.py
3,020
3.84375
4
#!/usr/bin/env python # -*- coding: utf-8 -*- """ __title__ = '冒泡排序+简单选择排序。O(n^2),稳定' __author__ = 'pipi' __mtime__ = '4/14/17' __email__ = 'pipijob@126.com' # code is far away from bugs with the god animal protecting I love animals. They taste delicious. ┏┓ ┏┓ ┏━┛┻━━━━┛┻━┓ ...
dca7cf3852b82aa454331f75152451f8359df303
pipilove/python_workspace
/Others/CorePyPro/Fun/easyMath.py
1,365
3.671875
4
#!/usr/bin/env python # coding=gbk ''' __title__ = '11.2 - Ϸ' __author__ = 'pi' __mtime__ = '2014.10.14' ''' from operator import add, sub, mul, div from random import choice, randint MAX_TRY = 3 - 1 ops = {'+': add, '-': sub, '*': mul, '/': div} RAND_MAX = 10 RAND_MIN = 0 def doProb(): op = cho...
400e2d32cf962e1bf1a02a9e9cf6c6e72e7fed83
tguterres/projectpython
/exercícios/exer42.py
408
4.03125
4
#triangulos r1 = float(input('Reta 1: ')) r2 = float(input('Reta 2: ')) r3 = float(input('Reta 3: ')) if r1< r2+r3 and r2 < r1+r3 and r3< r1+r2: print('As retas formam um triângulo ', end='') if r1 == r2 == r3: print('equilátero.') elif r1 != r2 != r3 != r1: print('escaleno.') else: ...
481bd1470eac0a2a2748e8c0e1e52ddd984d6a1e
tguterres/projectpython
/aulas/aula07.py
283
3.921875
4
n1 = int(input('Primeiro Número: ')) n2 = int(input('Segundo Número: ')) s = n1 + n2 m = n1 * n2 d = n1 / n2 di = n1 // n2 exp = n1 ** n2 print('A soma é {}, o produto é {}, a divisão é {:.1f}'.format(s,m,d)) print('A divisão inteira é {} \nO expoente é {}'.format(di,exp))
9807120f244da49bcd566d61c3dabac7d898608d
tguterres/projectpython
/exercícios/exer30.py
93
4.03125
4
#exercício 30 n = int(input('Digite um número: ')) print('even' if (n % 2 == 0) else 'odd')
cff2098884a4f25998bee4d366acf79428df1f1c
bee4uchange/SS1
/LAB/Week5/mylib.py
727
3.578125
4
def congruence(a, b, n): # ENTER EQUATION a2 = a if a > n: a = a % n # CALCULATE GCD AND QUOTIENT q = [] n2 = n while a != 0: q.append(n // a) tmp = a a = n % a n = tmp gcd = n # EXTENDED EUCLIDEAN ALGORITHM AND PRINT STEPS p = [0] * (len...
4e565b96bd9b0a2d5320196dccbb0498fb54c793
bee4uchange/SS1
/Homework/Homework2/Sentence_Cap.py
870
3.90625
4
def main(): sentence = input('Sentence: ') if ' ' in sentence: sentence = sentence.replace(' ', ' ') if ' . ' in sentence: sentence = sentence.replace(' . ', '.') if '.' in sentence: sentence = sentence.replace('.', '. ') for i in range(len(sentence)): if i == 0: ...
149e15f3d798d1fd790142acb3766dd800df4b97
bee4uchange/SS1
/Homework/Homework2/Pig_Latin.py
281
3.796875
4
def main(): sentence = input("Enter a sentence: ") print(convert(sentence)) def convert(string): sen = '' list_string = string.split(" ") for str in list_string: str = str.upper() sen += str[1:len(str)] + str[0] + 'AY ' return sen main()
cd294d39471c28da4a64966afd458fff63c1f357
chidhambarambhagavathy/pythonsamples
/inheritence.py
638
3.578125
4
class Student: def __init__(self, name, school): self.name = name self.school = school self.marks = [] def average(self): return (sum(self.marks) / len(self.marks)) @classmethod def friend(cls, origin, friend_name, *args): return cls(friend_name, origin.school, ...
a7993dd4094986911b77d107d1c1062c2d46221d
coderandgamer/Dojo
/bucle for.py
106
3.96875
4
print "vamos a contar"; numero=int(raw_input()); for num in range(numero): print "tu numero es",(num+1);
adf47b3def1fcbae4a09007d21f821d2d1657f34
VFerrari/IntroductionToAI
/Project1/SimulatedAnnealing.py
3,200
3.78125
4
''' Project 1 - Search-based solutions for static Pac-Man game. sa.py: Simulated Annealing search solutions for problem. Subject: MC906/MO416 - Introduction to Artificial Intelligence. Authors: Daniel Helú Prestes de Oliveira - RA 166215 Eduardo Barros Innarelli - RA 170161 Matheus Rotta Alves ...
bbbbf5041ee1a3ab0ef935285ba3baa1f42a7d53
VFerrari/IntroductionToAI
/Project1/bfs.py
3,726
3.78125
4
''' Project 1 - Search-based solutions for static Pac-Man game. bfs.py: breadth-first search solutions for problem. Subject: MC906/MO416 - Introduction to Artificial Intelligence. Authors: Daniel Helú Prestes de Oliveira - RA 166215 Eduardo Barros Innarelli - RA 170161 Matheus Rotta Alves ...
2ee0beeca57035c20d9d40e1a69415bd0920e1e3
Carling-Kody/python_review
/two_sums.py
278
3.625
4
def find_target(A, target): for i in range(len(A)): for j in range(i+1,len(A)): if A[i] + A[j] == target: print(i, j) return [i, j] def main(): A = [2, 7, 11, 15] target = 17 find_target(A,target) main()
367d9b451989fb58890460c5951fe781a49e2faa
bghanchi/Coding-Interview-Question
/Array/17EGICS030_ARRAY_9.py
589
3.640625
4
#Given an array arr[] of n integers, construct a Product Array prod[] (of same size) such that #prod[i] is equal to the product of all the elements of arr[] except arr[i]. Solve it without division #operator and in O(n) import math #input size=int(input(("Enter the size of array: "))) s=size arr=[] result=[] while ...
14ac1a7b4e49230d43e823f662a42c3f5a1be236
bghanchi/Coding-Interview-Question
/Array/Solution_Array_4.py
233
3.8125
4
def RightShift(s,shift): return s[len(s)-int(shift%len(s)):]+s[:len(s)-int(shift%len(s))] n=int(input()) String=input() ShiftPosition=int(input()) print(RightShift(String,ShiftPosition)) #Time Complexity :- O(N)
df177e159fb668e4f5cc087cabd700b010389ba7
bghanchi/Coding-Interview-Question
/Array/17EGICS019_Array_6.py
393
3.625
4
try: n = int(input("Enter Length of Array : ")) arr = [] print("Enter Array Elements :") for i in range(n): arr.append(int(input())) res = max(arr) if arr.count(res) > 1: print("\nProduct : ", res * res) else: arr = list(filter(res.__ne__, arr)) print("\nProdu...
22513f3fe9287a0e53b1833e25fbbddb5c5bc699
bghanchi/Coding-Interview-Question
/Array/17egics031_array_2.py
363
3.78125
4
def minSum(arr,s): s=int(s/2) first=arr[:s] second=arr[s:] sum1=sum(first) sum2=sum(second) return min(sum1,sum2) size=int(input(("Enter the size of array: "))) s=size arr=[] if (s<=1000000 and s%2==0): for size in range(s): num=int(input()) arr.append(num) print("MINIM...
c73699717768bdd1359da2456ae8f05e3d8b793f
bghanchi/Coding-Interview-Question
/Array/17EGICS092_ARRAY_9.py
202
3.578125
4
import numpy n=int(input()) a=[] b=[] c=[] for i in range(0,n): a.append(int(input())) b.append(a[i]) for i in range(0,n): a.remove(a[0]) res=numpy.product(a) c.append(res) a.append(b[i]) print(c)
2561db90eafc1588208265cbce55ab7790993bec
bghanchi/Coding-Interview-Question
/Array/17EGICS019_Array_5.py
687
3.515625
4
try: n = int(input("Enter Length of Array : ")) arr = [] print("Enter Array Elements :") for i in range(n): arr.append(int(input())) subseq = {} start = end = 0 for i in range(len(arr)): if i and arr[i-1] >= arr[i]: start = end end = i if i == ...
cd22a4be46a779f6bd80deca4bbb47057a3c9eca
bghanchi/Coding-Interview-Question
/Array/17EGICS030_ARRAY_8.py
505
3.875
4
#Given an array of positive numbers, find the maximum sum of a subsequence with the #constraint that no 2 numbers in the sequence should not be adjacent in the array. def maxSub(arr): sum=0 curr=arr[0] for i in range(1,len(arr)): res=max(sum,curr) curr=arr[i]+sum sum=res return...
616c2ae3ca8f95635e0d6fe6d8ae092699df4767
pythonmentor/jean-p3
/macgyver.py
829
4.03125
4
class MacGyver: """This class define the position and the characteristic of the hero MacGyver""" def __init__(self, labyrinth): """This method is the constructor of the class MacGyver""" self.labyrinth = labyrinth self.position = self.labyrinth.departure self.labyrinth.macgyver...
4da0ed9197133841ea1009c736ce22eff1ad48e3
paulohbraga/tk
/load_text.py
784
3.546875
4
import tkinter as tk def show_img(): class Image: def __init__(self, master=None): self.frame = tk.Frame(master) self.frame.pack() self.label = tk.Label(self.frame, text="Texto") self.label.pack() self.text = tk.Text(self.frame) self.text["font"] = ("Calibri", "25") self.text["width"] = 50 ...
30476dd46a817f34a0602878da8e189e28a7c409
altear/MiscProjects
/raspi_projects/rgb_led/rgb_button.py
577
3.65625
4
import RPi.GPIO as GPIO import time import itertools GPIO.setmode(GPIO.BCM) pins = {"r":14, "g":15, "b":18} for pin in pins.values(): GPIO.setup(pin, GPIO.OUT) def setcolor(color): for pin in pins.keys(): GPIO.output(pins.get(pin), (color == pin)) GPIO.setup(3, GPIO.IN, pull_up_down=GPIO.PUD_UP) triggered=F...
25a8fb8eacfc8d09523943be35d66b6c80e1fb98
ericvoots/TextStuff
/main.py
4,923
4.4375
4
import re import pandas as pd ''' helpful links https://stackoverflow.com/questions/4289331/how-to-extract-numbers-from-a-string-in-python https://stackoverflow.com/questions/17686809/how-to-find-word-next-to-a-word-in-python # dataframe part to remove placeholders in string columns https://stackoverflow.com/questio...
490e299a401f96464aa0e79b3bff68b1f943307d
leonardo1004/Python
/ejercicio3/ejercicio3.py
393
3.796875
4
# -*- coding: utf-8 -*- """ Created on Sun Sep 6 00:10:29 2020 @author: Leonardo Quintero P """ def tomarpalabra(palabra): primer_caracter = palabra[0] print("El primer caracter es: ", primer_caracter) ultimo_caracter=palabra[len(palabra)-1] print("El primer caracter es: ", ultimo_caracter) ...
817f8ed64ceb267fad55a4ca2d234ddfb6e2c1c3
Kris97777/Hangman-Project
/asciisorter.py
148
3.828125
4
char = input("tpye in sth") if ord(char) >= 65 and ord(char) <= 90 or ord(char) >= 97 and ord(char) <= 122 : print("yay") else: print("nay")
769b092fdd69278d79f78bc1d5914eb8882ee1fb
Akshada-Pawar/Library_Management_System_Case_Study
/sources/library_test.py
813
3.65625
4
import unittest import library as l class Test(unittest.TestCase): books = [] obj = l.Library() def test_add_book(self): book = self.obj.add_book('Python') self.books.append('Python') self.assertEqual(book,self.books) print(book) print(self.books) def test_di...
1a110d074d6b08e44e7d395ed2ec4fd566e9b3c7
TheGitHubGuy1/Machine_Learning_Tutorial_with_Python
/linear_support_vector_classifier.py
1,865
3.796875
4
# NumPy is the fundamental package for scientific computing with Python. It contains among other things: # # a powerful N-dimensional array object # sophisticated (broadcasting) functions # tools for integrating C/C++ and Fortran code # useful linear algebra, Fourier transform, and random number capabilities import num...
9617707413464ce0afcb2c1e9ef09445f7431182
oscar-dev19/CSCI-250
/Programs/Homework/Assignment_2/towers_of_hanoi.py
661
4
4
''' A script that simulates the classic towers of hanoi with three rods. Author: Oscar Lopez. ''' import sys def hanoi_towers(n, fromRod = 1, toRod = 3): if n == 1: print("Move disk from %s to rod %s"%(fromRod, toRod)) return unusedRod = (6 - fromRod - toRod) hanoi_towers(n-1, fromRod, unus...