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
6de317a5ce24e098ff9cbefe0c53995cc5debbd7
yeukhon/meme-lang
/lexer.py
1,240
3.515625
4
import re from collections import namedtuple Token = namedtuple('Token', ['type', 'value', 'lineno', 'columno']) def tokens(source, definitions, ignore_case=True): """Yield a token if part of the source matched one of the token definitions.""" re_definitions = [ (re.compile(t_def[0], re.I), ...
f27fe6dd57b6229b26d776caceacddf0ef0adb2f
beyondasce/Algorithm
/fingerOffer/9_stack_to_list.py
800
3.578125
4
class my_list: def __init__(self): self.l1 = [] #入 self.l2 = [] #出 def put(self,value): self.l1.append(value) def pop(self): if self.l2: return self.l2.pop(-1) while self.l1: self.l2.append(self.l1.pop(-1)) if self.l2: ...
ca198d683a35f1ad256577de6e23b7ff2d49d698
beyondasce/Algorithm
/fingerOffer/8_find_next.py
418
3.71875
4
class Node(): def __init__(self,value): self.value = value self.parent = None self.left = None self.right = None def get_next(node): p_next = None if node.right: p = node.right while p: p = p.left p_next = p else: while p.parent and p....
04d5ccd877271991befdfd3dfea137e9b290c1f1
beyondasce/Algorithm
/fingerOffer/6_list.py
803
3.625
4
import random class My_list(): def __init__(self,value): self.value = value self.next = None def get_list(li): p = None p1 = p for i in li: n1 = My_list(i) if not p: p = n1 p1 = p else: p1.next = n1 p1 = p1.next ...
e045549ac7c8471b37e10b5e20802f25e60ff9e5
saranya1999/sara
/103.py
169
3.578125
4
jak=int(input()) jak=str(jak) fa=0 for i in range(0,len(jak)): if(jak[i]=='0' or jak[i]=='1'): fa=1 else: fa=0 break if(fa==1): print('yes') else: print('no')
4a9fe514fc9c291f2e2981a4722bae220157226c
saranya1999/sara
/10e.py
107
3.71875
4
nu=[int(i) for i in input().split()] nu1=nu[0]*nu[1] if nu1 % 2 == 0: print("even") else: print("odd")
ec99b836876d4584369b6a98e9118a74a4f7e35c
pavel-malin/practice
/vectors_matrices_arrays/finding_max_min_values.py
341
4.09375
4
import numpy as np # Create matrix matrix = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) # max elements (9) print(np.max(matrix)) # min elements (0) print(np.min(matrix)) # find max elements column (array([7, 8, 9])) print(np.max(matrix, axis=0)) # find max elements stock (array([3, 6, 9])) print(np....
e2951526d6bcc35fa05d4022ab9a55796e14c1a0
Caustic/Project-Euler
/python/factor.py
533
3.953125
4
#! /usr/bin/python2 #simple factorization problem from listprime import listprimes from math import sqrt #simple factorization algoritm that uses a prime # seive to test all factors recursively up to # sqrt of the number def factor(number): factors = list([]) for i in listprimes(sqrt(number)+1): #pri...
8b50de912f85197a510f302e06d6ee7d110c4935
cyrilnavessamuel/StrategyGames
/nimble.py
3,750
4
4
import random class nimble: # Initialisation methods def __init__(self): self.board = []; self.pawn = 0; # Define a new board with n square of board # P maximum no of pawns def newBoard(self, n, p): self.pawn = p; for i in range(0, n): sel...
fae21a63bd70a0c2d2f33b8263490e6b5e2fcca1
Andyt-Nguyen/python-basics
/file.py
493
3.671875
4
# Write Read Create files fo = open('text.txt', 'w') # File Information print('Name',fo.name) print('Is closed?', fo.closed) print('Opening mode', fo.mode) # Write into a file fo.write('I love python') fo.write(', javascript') fo.close() # Add to file.txt fo = open('text.txt', 'a') fo.write(' and I guess php') fo.c...
156d92310a219f1ab56d7774a4dc3376566ef40b
ViktorWase/Frank-the-Science-Bot
/nonparametricDistribution.py
784
3.53125
4
from scienceFunctions import georand from random import randint from random import random def linCombRand(database): """ Takes a random number of points from the database and returns a vector that is a randomly weighted linear combination of the points. """ numPoints = geora...
7932cb303be6e4adb70c7c07bd1daebf422ae38b
ViktorWase/Frank-the-Science-Bot
/Templates/functionTemplate.py
1,784
3.5
4
""" This is a the template for the functions. So far we only have Artificial Neural Networks and Radial Basis Functions. All function classes need the methods described below. """ from tautology import * import random class radialBasisFunctionParameters: def __init__(self, chosenAttributes, ... ...
64f15cdd74fd3e022ba4bec6c437ac8d414e47b0
ThomasB123/Tutoring
/02.py
5,027
3.671875
4
# 1. inFile = open('airports.txt','r') airports = [] for line in inFile: airports.append(line.split('\n')[0].split(',')) inFile.close() intAirports = [] for i in range(len(airports)): intAirports.append(airports[i][0]) ukAirports = ['LPL','BOH'] aircraft = [['Medium narrow body',8,2650,180,8],['Large narro...
b1e90944c9f45ddd1499ede657d1a18e6f951afc
starmon00/161HW
/MatrixMultiplication.py
1,044
3.8125
4
def matrixMultiplication(matrixA, matrixB): if type(matrixA) == int and type(matrixB) == int: return matrixA * matrixB elif type(matrixA) == int and type(matrixB) == list: solution = [] for row in matrixB: solutionRow = [] for col in row: solutionRow.append(col * matrixA) solution.append(solutionRo...
0b142414e09fb32cac27af863fa8c7287b43a010
amohamud23/Python
/trees.py
531
4.0625
4
class Node(object): def __init__(self): self.left = None self.right = None self.data = None root = Node() n1 = Node() n2 = Node() n3 = Node() n4 = Node() n5 = Node() n6 = Node() root.data = "root" root.left = n1 root.right = n2 n1.data = 1 n2.data = 2 n1.left = n3 n1.right = n4 n3.data...
e1d3b4fe36c9b98180365a16034b33e17e59324d
Mahmoud-Elbattah/Top500_Viz_2005-2017
/PythonCode/Counter.py
999
3.6875
4
import pandas countryCoordinates = {} def countryCounts(data,year): counts = {} for (i,country) in enumerate(data["Country"]): if country in counts: counts[country] += 1 else: counts[country] = 1 countryCoordinates[country] = (data.loc[i,"Lat"],data...
61d57d7debbc312a6abcbfd2598f5aab134a4fe2
eirikhoe/advent-of-code
/2022/02/sol.py
976
3.59375
4
from pathlib import Path data_folder = Path(".").resolve() symb_to_num = {"A": 1, "B": 2, "C": 3, "X": 1, "Y": 2, "Z": 3} def parse_data(data): games = [[symb_to_num[symb] for symb in game.split()] for game in data.split("\n")] return games def score(game, new_interpretation): if new_interpretation: ...
c4f3ef7cc86733f3c6749d19442fcb39860f6494
eirikhoe/advent-of-code
/2018/11/sol.py
922
3.796875
4
from pathlib import Path import numpy as np def main(): serial = 8141 print(find_best_square(serial,3)) print(find_best_square(serial)) def find_best_square(serial,square_size=None): size = 300 gen = np.arange(size)+1 X = np.tile(gen,(size,1)) Y = np.copy(X.T) p = X+10 p *= Y ...
204df96c8acb2a833bad5d9dbcfca10a25479dc8
eirikhoe/advent-of-code
/2021/12/sol.py
1,595
3.5625
4
from pathlib import Path from collections import defaultdict data_folder = Path(".").resolve() def parse_data(data): cave_connections = [line.split("-") for line in data.split("\n")] connected_to = defaultdict(list) for line in cave_connections: connected_to[line[0]].append(line[1]) conne...
492503ce1d085ca365be4934606c8746e41c9d3e
rodrikmenezes/ProjetoEuler
/4 LargestPalindromeProduct2.py
1,041
4.1875
4
# ============================================================================= # A palindromic number reads the same both ways. The largest palindrome made # from the product of two 2-digit numbers is 9009 = 91 × 99. # Find the largest palindrome made from the product of two 3-digit numbers. # ========================...
bff174c4bf0b2d4375deb8679c4b59c7cf1211b4
rajasekhar-varikuti/basic_algorithms
/basic_algorithms/sorting_algorithms_helpers.py
1,954
4.0625
4
#helping methods for sorting algorithms def merge_list(array, start, mid, end): left = array[start:mid] right = array[mid:end] k = start i = 0 j = 0 while (start + i < mid and mid + j < end): if (left[i] <= right[j]): array[k] = left[i] ...
37377c07e6f8f2153e3e723d8ede0a7aca395c37
bharathkumarna/Python-Deep-Learning-Lab-Assignments
/Lab-1/Source/Task-2.py
548
4.0625
4
import string #create set with lowercased string alphabets = set(string.ascii_lowercase) #input strings inp = ['How quickly daft jumping zebras vex','How quickly daft jumping zebras'] inp_nospace =[None]*inp.__len__() for i in range(len(inp)): #replace space character (' ') with ('') inp_nospace[i] = inp[i]....
655545225361f6c5bcae9e1188b442b7f258d114
amdel2020/Algorithms
/mergesortedarray.py
1,019
3.6875
4
from queue import PriorityQueue class Node: def __init__(self, index, list_num): self.index = index self.listNum = list_num def merge(sorted_arrays): pq = PriorityQueue(0) res = [] for idx, item in enumerate(sorted_arrays): pq.put((item[0], Node(0, idx))) while not pq.e...
530436f9fe184e0134cb2ac03fe90663bf8adce5
amdel2020/Algorithms
/GradingStudents.py
587
3.78125
4
def gradingStudents(grades): result = [] for grade in grades: if grade < 38: result.append(grade) else: if grade % 5 == 0: result.append(grade) else: count = 0 temp = grade while temp % 5 != 0: ...
fcdae72bb66288329640b052012d5e4f2f60ee15
amdel2020/Algorithms
/13.01.eopi.py
158
3.609375
4
from collections import Counter def check_palindrome(s): return sum( ch % 2 for ch in Counter(s).values()) <= 1 print(check_palindrome("dokilolokido"))
de79189d4622cb8b63b451c92e2d3b59762b4899
amdel2020/Algorithms
/8.7.py
395
3.59375
4
def solve(string): arr = list(string) p = [arr[0:2], arr[1::-1]] for i in range(2, len(arr)): temp1 = [[]] for s in p: for j in range(len(s)): temp2 = s[:] temp2.insert(j, arr[i]) temp1.append(temp2) temp1.pop(0) p...
6afa5b0c4dcad188de0dcf2ba6c492d99e68ce89
petrakri/INF5860-petteakr
/inf5860_oblig1/inf5860/classifiers/softmax.py
4,151
3.828125
4
import numpy as np from random import shuffle def softmax_loss_naive(W, X, y, reg): """ Softmax loss function, naive implementation (with loops) Inputs have dimension D, there are C classes, and we operate on minibatches of N examples. Inputs: - W: A numpy array of shape (D, C) containing wei...
5a91c22b5ee87704cc8991bd6dab3eb2b2684d8b
ivanvi22/repository_name
/HelloWorld.py
323
4.1875
4
# программа для вывода "Hello World" car_color = 'wite' car_type = 'masda' car_count = 2 print("Укажите цвет машины:") car_color = input() print("Укажите тип машины:") car_type = input() print("You have " + str(car_count) + ' ' + car_color + ' ' + car_type) print(2 ** 3)
7dcdb9f9d1ee10795021f722200cc9324744ee29
ctemelkuran/py4e
/ex8.5.py
565
4.03125
4
#From stephen.marquard@uct.ac.za Sat Jan 5 09:14:16 2008 #You will parse the From line using split() and # print out the second word in the line(i.e. the entire address of the person). #Then print out a count at the end. fname = input("Enter file name: ") if len(fname) < 1 : fname = "mbox-short.txt" fh = ope...
9198e83e1836573e6ddd826ccf850ffe5e12db26
JGUO-2/MLwork
/Fibonacci/Fib_recursion.py
743
3.90625
4
# -*- coding: utf-8 -*- """ 实现斐波那契数列 方法五:递归 """ def Fib_list(n) : if n == 1 or n == 2 : #n为项数,若为1、2时,结果返回为1 return 1 else : m = Fib_list(n - 1) + Fib_list(n - 2) #其他情况下,结果返回前两项之和 return m if __name__ == '__main__': while 1: print("**********请输入要打印的斐波拉契数列项数n的...
8aa62e157ceb4c3c7760359cca19152bd9c64c69
JGUO-2/MLwork
/Fibonacci/Fib_generator.py
794
3.90625
4
# -*- coding: utf-8 -*- """ 实现斐波那契数列 方法一:生成器 """ def Fib_yield_while(max): a, b = 0, 1 #设置初始值 while max > 0: a, b = b, a + b max -= 1 yield a #执行yield函数 def Fib_yield_for(n): a, b = 0, 1 for _ in range(n): #循环遍历n次 a, b = b, a + b ...
dd87bfe17b74e88e1b019726695aacc81dfa937c
vsiddhu/qinfpy
/src/qinfpy/basic/zerOutMd.py
876
3.671875
4
#zerOut(mt) : Removes small entries in array import copy import numpy as np __all__ = ['zerOut'] def zerOut(array, tol = 1e-15): r"""Takes as input an array and tolerance, copies it, in this copy, nulls out real and complex part of each entry smaller than the tolerance, returns the copy. ...
1a5f6a490a8aa05fff89a73ac2a015e4f94ca80b
lbvf50mobile/til
/20230808_Tuesday/20230808.py
1,060
3.84375
4
# Leetcode: 33. Search in Rotated Sorted Array. # https://leetcode.com/problems/search-in-rotated-sorted-array/ class Solution: # Copied from: # https://leetcode.com/problems/search-in-rotated-sorted-array/solution/ def search(self, nums: List[int], target: int) -> int: n = len(nums) left, ...
a93434543dfa574acdd4a0093c33ef1d7dad99e5
lbvf50mobile/til
/20230810_Thursday/20230810.py
654
3.625
4
# https://leetcode.com/problems/search-in-rotated-sorted-array-ii/discuss/1891315/Python-or-binary-search class Solution: def search(self, nums: List[int], target: int) -> bool: l = 0 r = len(nums)-1 while l<=r: m=(r+l)//2 if target in [nums[m], nums[r], nums[l]]: ret...
b4a39da185af20c91ac6358a36f427eb84d42830
lbvf50mobile/til
/20230723_Sunday/20230723.py
930
3.734375
4
# Leetcode: 894. All Possible Full Binary Trees. # https://leetcode.com/problems/all-possible-full-binary-trees/ # 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:...
fd3c0a63cf36c2fd364cc1fc6c513d1db4c16f74
lbvf50mobile/til
/20230701_Saturday/20230701.py
1,707
3.515625
4
# Leetcode: 2305. Fair Distribution of Cookies. # https://leetcode.com/problems/fair-distribution-of-cookies/ # = = = = = = = = = = = = = = # Accepted. # Thanks God, Jesus Christ! # = = = = = = = = = = = = = = # Runtime: 1594 ms, faster than 36.20% of Python3 online submissions for Fair # Distribution of Cookies. # Mem...
9af08911cc64efd457bf9616256368a48334dc98
lbvf50mobile/til
/20230722_Saturday/20230722.py
1,608
3.765625
4
# Leetcode: 688. Knight Probability in Chessboard. # https://leetcode.com/problems/knight-probability-in-chessboard/ class Solution: # Based on: # https://leetcode.com/problems/knight-probability-in-chessboard/solution/ def knightProbability(self, n: int, k: int, row: int, column: int) -> float: # ...
a09d4162a16191968c5ae16762a63facf71abafd
lbvf50mobile/til
/20230819_Saturday/20230819.py
3,264
3.84375
4
# Leetcode: 1489. Find Critical and Pseudo-Critical Edges in Minimum Spanning Tree. # https://leetcode.com/problems/find-critical-and-pseudo-critical-edges-in-minimum-spanning-tree/ # = = = = = = = = = = = = = = # Accepted. # Thanks God, Jesus Christ! # = = = = = = = = = = = = = = # Runtime: 1114 ms, faster than 65.38%...
d919df4732a94c3619d678b00e26dad0188684c0
gustavoSaboia97/gamelibapi
/src/game/models/model/Game.py
541
3.578125
4
class Game: def __init__(self, game_dict: dict): self.__name = game_dict["name"] self.__category = game_dict["category"] self.__year = game_dict["year"] @property def name(self): return self.__name @property def category(self): return self.__category @...
98212cc7172cd5103a5631b0fd325bbe0ea120a5
Soonki/drone_contest
/src/scheduler.py
1,295
3.53125
4
#!/usr/bin/env python # -*- coding: utf-8 -*- import time, threading class Scheduler(): def __init__(self,function,step_time): self.stop_event = threading.Event() #停止させるかのフラグ self.inc_event = threading.Event() #刻み幅を増やすかのフラグ self.step_time=step_time self.function=function ...
74ef4502adf08b826bc5b21b3bf427d10ced9f88
wniedziolka/Programowanie-I-R
/speed.py
478
3.5625
4
import time a = float(input("Podaj pierwszą liczbę: ")) b = float(input("Podaj drugą liczbę: ")) c = 0 add_start = time.perf_counter_ns() c = a + b add_stop = time.perf_counter_ns() mul_start = time.perf_counter_ns() c = a * b mul_stop = time.perf_counter_ns() print("czas dodawania to: {0}".format(add_stop-add_star...
cc187912acdbe277fb2de0ed7b4c636e6c0a2012
jake-albert/py-algs
/c17/c17p19.py
20,828
3.90625
4
from operator import xor, add, mul from functools import reduce from math import sqrt, factorial, log2 from random import shuffle # c17p19 # Missing Two: You are given an array with all the numbers from 1 to N # appearing exactly once, except for one number that is missing. How can you # find the missing number in ...
201eb517d7b66b5bb4c7bdd2ef7ebe37b5c1e5bd
jake-albert/py-algs
/c17/c17p11.py
9,202
4.03125
4
from random import randint # c17p11 # Word Distance: You have a large text file containing words. Given any two # words, find the shortest distance (in terms of number of words) between them # in the file. If the operation will be repeated many times for the same file # (but different pairs of words), can you optim...
d95a3e695cf3726436afe59d60e5284555c3b2e1
jake-albert/py-algs
/c16/c16p06.py
3,878
3.71875
4
# c16p06 # Smallest Difference: Given two arrays of integers, compute the pair of # values (one value in each array) with the smallest (non-negative) # difference. Return the difference. # EXAMPLE # Input: {1, 3, 15, 11, 2}, {23, 127, 235, 19, 8} # Output: 3. That is, the pair (11, 8). ###########################...
5db74f2976c19b396a624c8518aab5f7de051164
jake-albert/py-algs
/other_practice/p02_grid.py
7,335
4.15625
4
# The class below simulates a valid grid for p02 as it is produced and has # methods that make writing the recursive algorithm in p02.py very easy. # It could be redesigned to handle square grids of any dimension with some # effort, so long as the rules for valid rows and columns are clarified. (Ex. # What values ar...
4bebbaa17b0ec98c097929740b8bfa9faba7cd84
jake-albert/py-algs
/data_structs/queue.py
2,454
4.03125
4
from .doubly import Doubly from collections import deque class LinkedListQueue: """Queue implemented with my doubly linked list class. Attributes: queue: A Doubly instance that simulates the queue. """ def __init__(self,loads=None): """Inits an empty LinkedListQueueQueue by de...
987837642c25fe151af6d7f60ba30e3125585ff7
jake-albert/py-algs
/c16/c16p26.py
8,444
3.90625
4
from operator import add, sub, mul, truediv from random import randint # c16p25 # Calculator: Given an arithmetic expression consisting of positive integers, # +, -, * and / (no parentheses), compute the result. # # EXAMPLE # Input: 2*3+5/6*3+15 # Output: 23.5 ######################################################...
a4185becd747eea6db3e191612d83b9daf9eea53
jake-albert/py-algs
/c17/c17p02.py
3,613
4.125
4
from random import randint from math import factorial from statistics import median, stdev # c17p02 # Shuffle: Write a method to shuffle a deck of cards. It must be a perfect # shuffle-in other words, each of the 52! permutations of the deck has to be # equally likely. Assume that you are given a random number gener...
cbffb60b5392afe5b4198d7cd342002ca5847345
bastih/banana
/examples/calculator/scenarios/rules.py
613
3.71875
4
from banana import matches from calculator import Calculator @matches(r'^Given the user opens the calculator$') def calculusInit(t): t.calculator = Calculator() @matches(r'^When entering (\d+) and (\d+)$') def calcAddNums(t, num1, num2): t.calculator.num1 = int(num1) t.calculator.num2 = int(num2) @ma...
f9d2ca5e97c35550587983c9ef35770a83cecc2e
tjvonbr/interview_prep
/interview_prop_python/goodrich_practice/minmax.py
208
4
4
def minmax(arr): min = arr[0] max = arr[0] for i in arr: if i < min: min = i elif i > max: max = i else: continue print((min, max)) print(minmax([1, 9, 0, -1, 15]))
ef40d6026aee4d666ef8a15c7b2b5083e69a85cb
pl80tech/CarND-PID-Control-Project
/log/data_visualize.py
1,813
3.546875
4
# Script to visualize multiple log in a figure & save to image for easy comparison # # How to use: # $ python data_visualize.py arg1 arg2 arg3 arg4 arg5 arg6 arg7 arg8 arg9 arg10 # arg1 --> log file 1 # arg2 --> log file 2 # arg3 --> log file 3 # arg4 --> title of the figure # arg5 --> x label of the figure # arg6...
6490618fda77e8b9c88590f5b9a2af5a597c04db
daverave1212/Ppender
/config.py
922
3.578125
4
def parse_config_file(): with open('config.cfg', 'r') as f: # Parse the config file text = f.read() lines = text.split('\n') pairs = [line.split('=') for line in lines if (not line.isspace() and not len(line) == 0)] config = {} for pair in pairs: config[pair[0]....
a1ed74f09083aa09de21700ccf76cd27b4e56365
SotirisKavv/AdventOfCode2020
/day1/product.py
972
3.515625
4
def readFile(filename): f = open(filename) words = f.read().splitlines() words = [int(i) for i in words] f.close() return words def candidate2Product(arr, val): i = 0 j = len(arr) - 1 arr.sort() while i < j: a = int(arr[i]) b = int(arr[j]) if a + b < val: ...
886dc39d2bb61f93ac6d8769b059f38cb7cf34ae
andrewghaly/KMeans-1
/pa6-calendar-student-1/plotK.py
7,180
3.796875
4
import matplotlib.pyplot as plt import numpy as np from math import sqrt import random colors = list('cmyk') class Centroid: def __init__(self, color, position): self.color = color self.position = position self.coordinateList = list() def euclid(self, b): """ Euclidean ...
3beb50957df5443a45e4547846d35f563a71f64a
rickeranderson/LinkedList_Python
/LinkedList.py
2,719
3.890625
4
#project: LinkedList #author: Rick Anderson from ListNode import ListNode class LinkedList: def __init__(self): self.head = None self.tail = None self.count = 0 def insert(self, x): self.insertAtRear(x) def insertAtRear(self, x): if (self.head == None): ...
5bbce3aaa6c5a5d38b2a2848ce856322107a8c91
mirsadm82/pyneng-examples-exercises-en
/exercises/06_control_structures/answer_task_6_2a.py
1,788
4.34375
4
# -*- coding: utf-8 -*- """ Task 6.2a Make a copy of the code from the task 6.2. Add verification of the entered IP address. An IP address is considered correct if it: - consists of 4 numbers (not letters or other symbols) - numbers are separated by a dot - every number in the range from 0 to 255 If the ...
86fc4bc0e652ee494db883f657e918b2b056cf3e
mirsadm82/pyneng-examples-exercises-en
/exercises/04_data_structures/task_4_8.py
1,107
4.125
4
# -*- coding: utf-8 -*- """ Task 4.8 Convert the IP address in the ip variable to binary and print output in columns to stdout: - the first line must be decimal values - the second line is binary values The output should be ordered in the same way as in the example output below: - in columns - column width 10 charact...
192f825f65d935555adb5d1e746a6bcec9d29bdb
aoineza/tic_tac_toe
/t_mechanics.py
1,332
3.796875
4
'Tic-Tac-Toe Mechanics' import copy class game_board(): def __init__(self): self.board = [['','',''],['','',''],['','','']] def add_element(self,element,row,column): if self.board[row][column] != '': return False self.board[row][column] = element return True ...
246036fb9bcfa3b61110f060c4018c8fdb3d7f90
FernandoSSilvaM/Tarea_07
/Tarea.py
2,031
4.03125
4
#Fernando Sebastian Silva M #Da un menu de finciones que puedes utilizar. Tambien te permite salir manuelmente del programa. def probarDivisiones(): #Realiza divisiones con restas. print("Bienvenido al programa para dividir") x = int(input("Dame el Divisor: ")) y = int(input("Dame el Dividendo: ")) re...
cd31fe810e8c006639692ec3985193de75aaf7dc
sneha1sneha/pgms
/pROGRAMS/assessment/Rrotation.py
292
3.921875
4
#list=[1,2,3,4] #list=[1,2,3,4,5,6,7,8,9] #o/p=[3,4,1,2] a=int(input("enter the position from " "which rotation to be performed")) i=a-1 n=len(list) listt=[] for num in range(i,n): listt.append(list[num]) j=0 for num in range(j,i): listt.append(list[num]) print(listt)
270537d5cf5e7ed55853e5b25e258d7b1a549291
sneha1sneha/pgms
/regularexpression/regphnumber.py
248
3.90625
4
from re import * #num=input("enter the number") #rule="(91)?[0-9]{10}" #\d{10} f=open("phonenumber","r") for num in f: rule="(91)?[0-9]{10}" matcher=fullmatch(rule,num) if matcher==None: print("invalid entry") else: print("valid entry")
7fc31cd478cadafacb5712d92d3327d59efca882
yuxuanwu17/leetcode
/lengthOfLIS.py
754
3.515625
4
from typing import List class Solution: def lengthOfLIS(self, nums: List[int]) -> int: memo = {} def recursion(nums: [int], i: int) -> int: if i in memo: return memo[i] # base case if i == len(nums) - 1: return 1 ma...
b3cfe1ba6b28715f0f2bccff2599412d406fd342
n001ce/python-control-flow-lab
/exercise-5.py
670
4.40625
4
# exercise-05 Fibonacci sequence for first 50 terms # Write the code that: # 1. Calculates and prints the first 50 terms of the fibonacci sequence. # 2. Print each term and number as follows: # term: 0 / number: 0 # term: 1 / number: 1 # term: 2 / number: 1 # term: 3 / number: 2 # term: 4 / nu...
763979679c5737080f54ebfbd9e673d20de79c15
KingBing/SigmaGO_GuideDog
/ult_lib.py
1,732
3.5625
4
# Import required Python libraries # ----------------------- import time import RPi.GPIO as GPIO # ----------------------- # Define some functions # ----------------------- class ult(): def __init__(self): GPIO.setmode(GPIO.BOARD) self.GPIO_TRIGGER = 36 self.GPIO_ECHO = 37 ...
75fd4c2cc5721d569a8664dd3eab55469055fb6c
LoveAndHappinesss/Learning-How-to-Use-Git
/TicTacToe.py
6,553
3.9375
4
def display_board(choice, turn, board_position): if turn == 'X': board_position[choice] = 'X' else: board_position[choice] = 'O' print('\n') print(' '+board_position[0]+' | '+board_position[1]+' | '+board_position[2]+' ') print(' ------------') print(' '+board_positio...
e9a72caac8d953e5f30e7268668e6d2ab5b47eb3
teganbroderick/Python-Projects
/Tic Tac Toe/TicTacToe.py
4,730
4.3125
4
#!/usr/bin/env python3 #Tic Tac Toe game #Tegan Broderick, 20190815 #Combined exercises from practicepython.org #Game runs in the terminal using python 3 def game(gameboard, positionlist, running_position_list, turnlist): """Function calculates what turn the game is up to, assigns a player (1 or 2) to that turn, asks...
22b51de6575b2bae03e07d9498d1ba16e083b688
c0ntradicti0n/CorpusCookApp
/logtest.py
575
3.734375
4
import logging, sys class LogFile(object): """File-like object to log text using the `logging` module.""" def __init__(self, name=None): self.logger = logging.getLogger(name) def write(self, msg, level=logging.INFO): self.logger.log(level, msg) def flush(self): for handler i...
4540b64352cbbc636337cd0a1061494dc04c76dd
alopezja/Phyton
/UPB/Ejercicios/jun8.py
618
3.734375
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue Jun 8 18:35:30 2021 @author: exlonk """ print("Ingrese el valor de compra e ingrese un valor de cero para finalizar") contador = 0 monto = None numero_compra = 1 while monto != 0: monto= float(input("Valor compra {0}: ".format(numero_compra))) ...
63547b9b5fda15e875f1dbc359f09da689305ab4
alopezja/Phyton
/UPB/Ejercicios/ejercicio3.py
401
3.859375
4
### Parque de diversiones edad = int(input("Digite su edad:\n >>> ")) if 0<edad<18: print("Solo puede entrar a las atracciones de menores de edad") else: if 18<=edad<60: print("Puede utilizar todas las atracciones del parque") else: if edad>=60: print("Solo puede utilizar unas...
44ffa186670d787e5aafa5b380e669e7763d9e5d
alopezja/Phyton
/UPB/Ejercicios/jun11.py
764
3.84375
4
from os import system system("clear") #Delimitadores para cambiar un string con un separador #para agregar cada argumento por separado a un elemento en una lista s = "Alex-David-Lopez" delimiter = "-" print(s.split(delimiter)) lista = ["Programar","es","lo","mejor"] delimiter = " " print(delimiter.join(lista)) a = ...
6c6ca1405b0b0a73e610f148962c9eea2f4fe62b
rykroon/mongoendjin
/mongoendjin/utils/text.py
268
4.0625
4
import re re_camel_case = re.compile(r'(((?<=[a-z])[A-Z])|([A-Z](?![A-Z]|$)))') def camel_case_to_spaces(value): """ Split CamelCase and convert to lowercase. Strip surrounding whitespace. """ return re_camel_case.sub(r' \1', value).strip().lower()
061aa64d7b81d640feac402dd1840ec8e80b1c7c
advancer-debug/Daily-learning-records
/数据结构与算法记录/习题解答记录/链表/offero6_test.py
2,482
4.125
4
# -*- coding = utf-8 -*- # /usr/bin/env python # @Time : 20-11-28 下午2:02 # @File : offero6_test.py # @Software: PyCharm # 输入一个链表的头节点,从尾到头反过来返回每个节点的值(用数组返回)。 # 方法一递归法 # 利用递归: 先走至链表末端,回溯时依次将节点值加入列表 ,这样就可以实现链表值的倒序输出。 # python算法流程 # 递推阶段: 每次传入 head.next ,以 head == None(即走过链表尾部节点)为递归终止条件,此时返回空列表 [] 。 # 回溯阶段: 利用 Py...
1045bc8666f46dea921581ff515f2d4d5908d729
advancer-debug/Daily-learning-records
/python的魔法使用/test.py
684
3.8125
4
# -*- coding = utf-8 -*- # /usr/bin/env python # @Time : 20-11-18 下午8:25 # @File : test.py # @Software: PyCharm # try/except/else while/else break continue # while True: # reply = input('Enter txt:') # if reply == 'stop': # break # try: # num = int(reply) # except: # ...
8d980ed029b0dc74e4dc6aa0e7785d6af0f95fa7
NiharikaSinghRazdan/PracticeGit_Python
/Code_Practice/list_exercise.py
512
4.21875
4
# Convert string into list mystring="This is the new change" mylist = [] for letter in mystring: mylist.append(letter) print(mylist) # Change string into list with different convert format and in one line mystring1="Hi There" mylist1 =[letter for letter in mystring1] print(mylist1) # Check other usage of this new...
e0a8fb7f830eb8d4faa7cb14ca39d0f9ae33e621
NiharikaSinghRazdan/PracticeGit_Python
/Code_Practice/tuples.py
181
4.09375
4
tuples1=(1,2,3,"age") print(type(tuples1)) print(tuples1[0]) print(len(tuples1)) print(tuples1[-1]) #tuples1[1]="Name", tuple object does not support item assignment. print(tuples1)
bc76d2ae44f894254a3e24c0b53c61db5039f4ff
NiharikaSinghRazdan/PracticeGit_Python
/Code_Practice/arbitary_list.py
1,556
4.1875
4
#retrun the list where the passed arguments are even def myfunc(*args): mylist=[] for item in args: if item%2==0: mylist.append(item) else: continue print(mylist) print(myfunc(-2,4,3,5,7,8,10)) # return a string where every even letter is in uppercase and every odd l...
37b1dce3bcbe2da05065e677491797983588c285
dankolbman/NumericalAnalysis
/Homeworks/HW1/Problem1.py
520
4.21875
4
import math a = 25.0 print("Squaring a square-root:") while ( math.sqrt(a)**2 == a ): print('sqrt(a)^2 = ' + str(a) + ' = ' + str(math.sqrt(a)**2)) a *= 10 # There was a rounding error print('sqrt(a)^2 = ' + str(a) + ' != ' + str(math.sqrt(a)**2)) # Determine the exponent of the float expo = math.floor(math.log10(a...
3ecc8e12c963520b723804c9ca6beebb2544b01f
bravacoreana/python
/files/12.py
245
4
4
a = [1,2,3,4,5,6,7] for element in a: print(element) numbers = [1,2,3,4,5,6,7,8,9,10] for number in numbers: if number % 2 == 0 : print("even number: {}".format(number)) else: print("odd number: {}".format(number))
33d08154e946264256f7810254cd09f236622718
bravacoreana/python
/files/08.py
409
4.34375
4
# if <condition> : # when condition is true if True: print("it's true") if False: print("it's false") number = input("input a number >>> ") number = int(number) if number % 2 == 0: print("even") if number % 2 != 0: print("odd") if number < 10: print("less than 10") elif number < 20: pr...
c9eb65921d784d054c7dd2d2eac5605ab2b462d2
young508/pythonLearn
/main/oop/抽象类.py
526
3.765625
4
import abc # 抽象类必须声明一个类并且指定当前类的元类 class Human(metaclass=abc.ABCMeta): # 抽象方法 @abc.abstractmethod def smoking(self): pass # 定义类的抽象方法 @abc.abstractclassmethod def drink(cls): pass # 定义静态抽象方法 @abc.abstractstaticmethod def play(): pass class Man(Human): ...
bfc1710b45ac38465e6f545968f2e00cd535d2dc
Tarun-Rao00/Python-CodeWithHarry
/Chapter 4/03_list_methods.py
522
4.21875
4
l1 = [1, 8, 7, 2, 21, 15] print(l1) l1.sort() # sorts the list print("Sorted: ", l1) l1.reverse() #reverses the list print("Reversed: ",l1) l1.reverse() print("Reversed 2: ",l1) l1.append(45) # adds to the end of the list print ("Append", l1) l2 = [1,5, 4, 10] l1.append(l2) # l2 (list) will be added print("Append 2"...
fdd7aede3f987bfdbe75d46712b141bffae2ef9c
Tarun-Rao00/Python-CodeWithHarry
/Chapter 8/11_pr-07.py
221
3.828125
4
def remov(strg): word = input("Enter the word you want to remove: ") newStrng = strg.replace(word, "") newStrng1 = newStrng.strip() return newStrng1 strg = input("Enter your text: ") print(remov(strg))
64dfa1b97046bb32385d14a3a17890efdc290cd1
Tarun-Rao00/Python-CodeWithHarry
/Chapter 6/05_pr_01.py
265
3.984375
4
a = int(input("Enter number one: ")) b = int(input("Enter number two: ")) c = int(input("Enter number three: ")) d = int(input("Enter number four: ")) if(a>b and a>b and a>d): print(a) elif(b>c and b>d): print(b) elif(c>d): print(c) else: print(d )
d3116722a51caab7ade845d108d90214533b1b93
Tarun-Rao00/Python-CodeWithHarry
/Chapter 4/05_tuple_methods.py
158
3.796875
4
t = (1, 2, 3, 4, 5, 1, 1) print("Count", t.count(1)) # Returns the number of occurence value print("Index", t.index(5)) # returns the first index of value
0ab24f03f7919f96e74301d06dd9af5a377ff987
Tarun-Rao00/Python-CodeWithHarry
/Chapter 2/02_operators.py
548
4.125
4
a = 34 b = 4 # Arithimatic Operator print("the value of 3+4 is ", 3+4) print("the value of 3-4 is ", 3-4) print("the value of 3*4 is ", 3*4) print("the value of 3/4 is ", 3/4) # Assignment Operators a = 34 a += 2 print(a) # Comparision Operators b = (7>14) c = (7<14) d = (7==14) e = (7>=14) print(b) print(c) print(d...
062cb2773c796daeae0581cad63b05da9e771744
Tarun-Rao00/Python-CodeWithHarry
/Chapter 5/06_pr_01.py
332
4.0625
4
myDict = { "Pankha" : "Fan", "Darwaja" : "Door", "Hawa" : "Air", "Badal": "Clouds", "Aasmaan" : "Sky" } print("options are ", myDict.keys()) a = input("Enter the hindi word\n") # Below line will not throw an error if the key is not present the Dictionary print("The meaning of your word is:\n", my...
d31f727127690b2a4584755c941cd19c7452d9e4
Tarun-Rao00/Python-CodeWithHarry
/Chapter 6/11_pr_06.py
221
4.15625
4
text = input("Enter your text: ") text1 = text.capitalize() num1 = text1.find("Harry") num2 = text1.find("harry") if (num1==-1 and num2==-1): print("Not talking about Harry") else: print("Talking about Harry")
03e0dbdd4929f5992182830a995642a75805704b
Tarun-Rao00/Python-CodeWithHarry
/Chapter 10/05_instance_class_attribute.py
231
3.921875
4
class Employee: company = "Google" salary = 100 harry = Employee() rajni = Employee() # Creating instance attribute salry for both the objects harry.salary = 300 rajni.salary = 400 print(harry.salary) print(rajni.salary)
8a2be0cbdc3ca978a888670067c440c2806a0b81
saratiedt/python-exercises
/semana 2/buscaString.py
217
3.953125
4
palavra = input("Digite uma palavra: ") letra = input("Digite uma letra para ser buscada na palavra: ") if letra in palavra: print(f'Existe {letra} na {palavra}') else: print(f'Não existe {letra} na {palavra}')
f6f79e3ec31c1dac8443d6588028008b02691339
saratiedt/python-exercises
/semana 3/contadorCaracteres.py
177
3.703125
4
nome = input("Digite seu nome: ") sobrenome = input("Digite seu sobrenome: ") tamanhoNome = len(nome) + len(sobrenome) print(f'O nome tem {tamanhoNome} caracteres no total.')
c6564a35f4ac868cb5ebd5898316c8b5f42691ec
jitendrasinghiitg/sonar-python-coverage
/python/calc.py
373
3.734375
4
""" calc.py """ def add(x, y): """ :param x: :param y: :return: sum of x and y """ return x + y def difference(x, y): """ :param x: :param y: :return: returns difference of x and y """ return x - y def multiply(x, y): """ :param x: :param y: :return:...
0a9cf183231f226cdde9a5e8fc829516f534a56e
willmclaughlin13/CS415
/greedy.py
3,379
3.984375
4
from collections import namedtuple # This is our heap class class maxHeap: def __init__(self, array=None): self._heap = [] if array is not None: # The constructor, builds the heap from a list for i in array: self.insert(i) # Insert takes value to inse...
562874a65da4ea0f2119953a021689b201013800
Nanorneirbo/self_driving_car-project
/Lanes/lanes_video.py
3,191
3.5625
4
import cv2 import numpy as np import matplotlib.pyplot as plt # function to run the canny def canny(image): # in - a new image # out - greyscael, smoothed, canny image. #greyscale the image gray = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY) #blur the image blur = cv2.GaussianBlur(gray, (5,5),0) # canny - detect ...
4362c2094c0a0a944a0a74940c77a615f1cb1fbd
okccc/python
/basic/10_线程.py
3,305
3.53125
4
# coding=utf-8 import threading import time def test01(): for i in range(5): print("---test01---%d" % i) time.sleep(0.5) def test02(): for i in range(10): print("---test02---%d" % i) time.sleep(0.5) def main01(): # 多线程实现多任务 # Thread()方法只是创建实例对象,一个实例对象只能创建一个线程且该线程只能开启一...
efe618ae87f00a3f691905cd6987b72809c878f6
okccc/python
/other/cardmanager/card_tools.py
4,373
3.640625
4
# coding=utf-8 """ card_tools: 工具类,包含主程序要用的所有函数 """ # 定义一个空列表存储数据,放在第一行,这样所有函数都能使用该数据 card_list = [] # 显示功能列表 def show_menu(): print("*" * 50) print("欢迎使用【名片管理系统】 V 1.0") print("1.新增名片") print("2.显示全部") print("3.搜索名片") print("0.退出系统") print("*" * 50) # 新增名片 def new_card(): print("新增...
14a80976e094faffcab44a4e0ae049b68b921b5e
jkeller51/ECE448_MP4
/gen_training_data.py
2,057
3.6875
4
# -*- coding: utf-8 -*- """ Created on Sat Apr 28 12:36:57 2018 @author: jkell """ import numpy as np resolution = 10 import random def intersect_line(x1,y1,x2,y2,linex): """ Determine where the line drawn through (x1,y1) and (x2,y2) will intersect the line x=linex """ if (x2 == x1): ...
b53765f11a2ab8b9ecda7607eaa1e6be6849c4e8
varunnair735/Neural-Net
/activation_functions.py
744
3.65625
4
""" Author: Varun Nair Date: 6/25/19 """ import numpy as np def sig(x): """Defines sigmoid activation function""" return (1 / (1+ np.exp(-x))) def sig_prime(x): """Defines the derivative of the sigmoid function used in backprop""" return sig(x)*(1-sig(x)) def RELU(x): """Defines ReLU activation f...
406ad197c1a6b2ee7529aaa7c6ea5a86e10114de
carrenolg/python-code
/Chapter12/optimize/main.py
896
4.25
4
from time import time, sleep from timeit import timeit, repeat # main def main(): """ # measure timing # example 1 t1 = time() num = 5 num *= 2 print(time() - t1) # example 2 t1 = time() sleep(1.0) print(time() - t1) # using timeit print(timeit('num = 5; num *= 2'...
9bbc0b6c797397a5fd72079b649b115fe117879e
carrenolg/python-code
/chapter6/chapter6.py
4,636
4.1875
4
# Chapter6 - Oh Oh: Objects and Classes class Person(): def __init__(self, name): self.name = name soccer_player = Person('Juan Roman') print(soccer_player) # Inheritance class Car(): def exclaim(self): print("I'm a Car!") class Yugo(Car): def exclaim(self): print("I'm a Yugo!...
cfbc5acf0f0493b58b9b86540824bd0fa61bd4f3
carrenolg/python-code
/Chapter12/debugging/main.py
1,320
3.890625
4
"""Chapter 12 - Be a pythonista""" # vars def dump(func): """Print input arguments and output value(s)""" def wrapped(*args, **kwargs): print("Function name: %s" % func.__name__) print("Input arguments: %s" % ' '.join(map(str, args))) print("Input keyword arguments: %s" % kwargs.items(...