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 |
|---|---|---|---|---|---|---|
7d4b868400a40c71d447c72ef1fe378884520fcc | andersgoddard/intro-to-ml | /ex2/plotDecisionBoundary.py | 1,207 | 3.71875 | 4 | import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
from plotData import *
def plotDecisionBoundary(theta, X, y, a):
X_plot = pd.DataFrame(X[:, 1:3])
plotData(X_plot, y, False)
if np.shape(X)[1] <= 3:
# Only need 2 points to define a line, so choose two endpoints
... |
2dc69aa8e8d241d82e1f8a4b3248c051abae377a | casp3rus/100DaysOfAlgo | /026ValidateBST/validateBST.py | 587 | 3.640625 | 4 | # Solution
# O(n) time / O(d) space
# d - depth of the tree
class BST:
def __init__(self, value):
self.value = value
self.left = None
self.right = None
def validateBST(tree):
return validateBSTHelper(tree, float('-inf'), float('inf'))
def validateBSTHelper(tree, minValue, maxValue):... |
3aa64e265a91211a2ec905a22629ed4131bd5726 | casp3rus/100DaysOfAlgo | /100SolveSudoku/solveSudoku.py | 1,399 | 3.546875 | 4 | # Solution
# O(1) time / O(1) space
def solveSudoku(board):
solvePartialSudoku(0, 0, board)
return board
def solvePartialSudoku(row, col, board):
currentRow = row
currentCol = col
if currentCol == len(board[row]):
currentRow += 1
currentCol = 0
if currentRow == len(board)... |
b4f3a11b87e5f80e60605e1d5b305e522c1a39cc | casp3rus/100DaysOfAlgo | /045Permutations/permutations.py | 1,134 | 3.671875 | 4 | # Solution 1
# Upper Bound: O(n^2*n!) time / O(n*n!)space
# Roughly: O(n*n!) time / O(n*n!) space
def getPermutations(array):
permutations = []
permutationsHelper(array, [], permutations)
return permutations
def permutationsHelper(array, currentPermutation, permutations):
if not len(array) and len(cu... |
189c894881ecf6bb166d1a55a5f771b2b0df4855 | casp3rus/100DaysOfAlgo | /064ValidStartingCity/validStartingCity.py | 1,363 | 3.515625 | 4 | # Solution 1
# O(n^2) time / O(1) space
def validStartingCity(distances, fuel, mpg):
numberOfCities = len(distances)
for startCityIdx in range(numberOfCities):
milesRemaining = 0
for currentCityIdx in range(startCityIdx, startCityIdx + numberOfCities):
if milesRemaining < 0:
... |
79cb602d9dd0b62c27390fead2c915ca1542cbbf | casp3rus/100DaysOfAlgo | /067CycleInGraph/cycleInGraph.py | 1,901 | 3.5625 | 4 | # Solution 1
# O(v + e) time / O(v) space
# v - number of vertices
# e - number of edges
def cycleInGraph(edges):
numberOfNodes = len(edges)
visited = [False for _ in range(numberOfNodes)]
currentlyInStack = [False for _ in range(numberOfNodes)]
for node in range(numberOfNodes):
if visited[nod... |
9d5b01e37319b4e2ebbcb7eb4ef64e4972c62ee5 | casp3rus/100DaysOfAlgo | /105FirstNon-RepeatingCharacter/firstNonRepeatingCharacther.py | 744 | 3.53125 | 4 | # Solution 1
# O(n^2) time / O(1) space
def firstNonRepeatingCharacter(string):
for idx1 in range(len(string)):
foundDuplicate = False
for idx2 in range(len(string)):
if string[idx1] == string[idx2] and idx1 != idx2:
foundDuplicate = True
if not foundDuplicate:
... |
c8dad10e86848fa12c0c754a8239bb9cd4103dc3 | casp3rus/100DaysOfAlgo | /011SelectionSort/selectionSort.py | 438 | 3.609375 | 4 | # Solution 1
# O(n^2) time / O(1) space
def selctionSort(array):
currentIdx = 0
while currentIdx < len(array) - 1:
smallesIdx = currentIdx
for i in range(currentIdx + 1, len(array)):
if array[smallesIdx] > array[i]:
smallesIdx = i
swap(currentIdx, smallesIdx,... |
5d919bffc3aab3f2b282c0688ec353aa80a0e62f | leolikestocode/uri-exercises | /beginner/1847.py | 498 | 3.8125 | 4 | a, b, c = input().split()
a = int(a)
b = int(b)
c = int(c)
if (b < a and c >= b): # 1
print(":)")
elif (b > a and c <= b): # 2
print(":(")
elif (b > a and c > b and c - b < b - a): # 3
print(":(")
elif (b > a and c > b and c - b >= b - a): # 4
print(":)")
elif (b < a and c < b and abs(c - b) < abs... |
b16c97b37c7a8f3677176197c35bf4cfe6b1c301 | leolikestocode/uri-exercises | /beginner/1983.py | 260 | 3.78125 | 4 | n = int(input())
high = 0
student = 0
for i in range(n):
x, y = input().split()
if (float(y) >= 8 and float(y) > high):
student = int(x)
high = float(y)
if (student == 0):
print('Minimum note not reached')
else:
print(student)
|
1c0939a638b9a5c52b81b66f9f20d0949a93eebb | liquidpele/leapday | /leapday/leapday.py | 4,287 | 4.6875 | 5 | #!/usr/bin/python
from __future__ import print_function
import argparse
from collections import OrderedDict
import json
"""
Script to get the name of the day of the week of the leap day
on given years. Manually calculate due to pretend bugs in stdlib.
Example: ./leapday.py 2000 2004 -f shortname -m json
Assumption... |
8073994ebd55bc9b2f13f9f056cb31c9da8d6931 | Python-lab-cycle/Swathisha6 | /16.swapping.py | 235 | 4.0625 | 4 | str1 = input("enter a first string:")
str2 = input("enter a second string:")
new_a = str2[:2] + str1[2:]
new_b = str1[:2] + str1[2:]
print("the new string after swapping first two character of both strings : " ,(new_b+' '+new_a))
|
65c2f70ca2dae1538060ac49c894702961d52e91 | Python-lab-cycle/Swathisha6 | /2.fibopnnaci.py | 214 | 4.15625 | 4 | n =int(input("enter the number of terms:"))
f1,f2=0,1
f3=f2+f1
print("fibonacci series of first" , n, "terms")
print(f1)
print(f2)
for i in range (3, n+1):
print(f3)
f1=f2
f2=f3
f3=f1+f2
|
cc99254294c493ca8f2ce24b0edab414dec91044 | DengYiping/ADS-2018 | /hw7/binarytree_to_list.py | 860 | 4.03125 | 4 | from linkedlist import Node
from binarytree import TreeNode
def treeToList(root):
"""
This function will convert a tree into linkedlist
>>> tree = TreeNode(5, TreeNode(3, TreeNode(2), TreeNode(4)), TreeNode(9))
>>> lst = treeToList(tree)
>>> lst.data
2
>>> lst = lst.next
>>> lst.data
... |
0c967bf0b3dd652644196149181902259b08a3f7 | DengYiping/ADS-2018 | /hw7/stack.py | 1,681 | 4 | 4 | class StackNode:
"""
A basic linked list implementation
"""
def __init__(self, data = None, nxt = None):
self.data = data
self.next = nxt
class Stack:
"""
Implementation of Stack According to the code in the assignment
>>> s = Stack(2)
>>> s.isEmpty()
True
>>> s.... |
899cccdd60ddcb83f56c18966562d82d0f77703e | LowerDeez/grasp-gof-patterns | /abstract-factory/main.py | 1,864 | 4.3125 | 4 | from abc import ABC, abstractmethod
from typing import List
class TraditionalDish(ABC):
"""Base class for traditional dish"""
name = "traditional dish"
class Lunch(ABC):
"""Base class for lunch"""
name = "lunch"
class Cafe(ABC):
"""Abstract Factory. Base class for specific country food"""
... |
3e048d1176c9cf2cab4eb4815ede137b64ca9bfe | ipcoo43/pythonone | /lesson148.py | 349 | 3.859375 | 4 | print('''
[ while 반복문 ]
- 조건을 기반으로 반복할 때 사용하는 반복문
while <조건>:
<조건이 참일 때 반복할 코드>
[ for 반복문 ]
- 특정 횟구 또는 특정 요소에 대해 반복할 때 사용하는 반복문
for i in range(10):
''')
i = 0
while i < 10:
print('{}번째 반복입니다'.format(i))
i += 1 |
04f4f05daa671f0530aab81699f6b0db58c13d01 | ipcoo43/pythonone | /lesson158.py | 578 | 3.9375 | 4 | print('리스트에서 인덱스와 값을 출력하는 방법')
list_a = ['요소A','요소B','요소C']
print('list_a =',list_a)
print()
print('방법1) 인덱스 변수를 만들어 추가')
i=0
for item in list_a:
print('{}번째 요소는 {} 입니다'.format(i,item))
i += 1
print()
print('방법2) range(len(list_a))')
for i in range(len(list_a)):
print('{}번째 요소는 {} 입니다'.format(i,list_a[i]))
print(... |
c40bb2fd8c2d832b63fc1cd49c3718f6d8b96a87 | ipcoo43/pythonone | /lesson145.py | 758 | 4.21875 | 4 | print('''
[ 범위 만들기 ]
range(<숫자1>) : 0부터 (<숫자1>-1)까지의 정수 범위
range(<숫자1>,<숫자2>) : <숫자1>부터 (<숫자2>-1)까지의 정수의 범위
ringe(<숫자1>,<숫자2>,<숫자3>) : <숫자1>부터 <숫자3> 만큼의 차이를 가진 (<숫자2>-1)까지 범위
[ 범위와 반복문 ]
for <범위 내부의 숫자를 담을 변수> in <범위>:
<코드>
''')
print(range(5))
print(list(range(5)))
for i in range(5):
print('{}번째 반복문입니다.'.format(i))... |
38454c8180749e4b9846b00cb2c94fa040aed595 | ipcoo43/pythonone | /lesson127.py | 682 | 3.9375 | 4 | import datetime
now = datetime.datetime.now()
if 3 <= now.month <= 5: # 3보다 크거나 같거나, 5보다 작거나 같으면
print('이번 달은 {}월로 봄 입니다.'.format(now.month))
if 6 <= now.month <= 8: # 6보다 크거나 같거나, 8보다 작거나 같으면
print('이번 달은 {}월로 여름 입니다.'.format(now.month))
if 9 <= now.month <= 11: # 9보다 크거나 같거나, 11보다 작거나 같으면
print('이번 달은 {}월로 가을 입니다.... |
4909da274835f93e8c646461ba4483c65035f2f1 | ipcoo43/pythonone | /lesson220.py | 590 | 3.5625 | 4 | class Student:
def __init__(self, name, korean, math, english, science):
self.name = name
self.korean = korean
self.math = math
self.english = english
self.science = science
def get_sum(self):
return self.korean + self.math + self.english + self.science
def get_average(self):
return self.get_sum() ... |
4a4ef3a08dc1719f04198fe62ec3b5a6a5bdb3d5 | ipcoo43/pythonone | /lesson169.py | 317 | 3.703125 | 4 | # 함수 선언
def sum_all(start=0, end=100, step=1):
# 변수 선언
output = 0
# 반복문 돌려 숫자 더하기
for i in range(start, end+1, step):
output += i
# 리턴 한다.
return output
# 한수 호출
print('A.',sum_all(0,100,10))
print('B.',sum_all(end=100))
print('C.',sum_all(end=100, step=2)) |
93ee794711ad45ec38eb18e5ac1af0d2a689ae94 | ipcoo43/pythonone | /lesson223.py | 530 | 4 | 4 | print('''
가비지 컬렉터 (Garbage Collector) : 쓰레기를 컬렉터 한다.
- 더 이상 사용하지 않는 변수를 해제 시켜 주는 역할
- 컴퓨터에서 자동으로 메모리가 생성되는데, 사용 후 청소하는 역할
''')
class Test:
def __init__(self,name):
self.name = name
print('{} - 생성되었습니다.'.format(self.name))
def __del__(self):
print('{} - 소멸되었습니다.'.format(self.name))
a=Test('A')
b=Test('B')... |
6c37c578633dae5853723d07e27d394da7ddc02c | OscarLaurberg/PythonNotebooks | /Week 2/exercises03.py | 1,027 | 3.953125 | 4 | import argparse
file = 'read_from_file_ex.txt'
def print_file_conent(file):
with open(file) as file_object:
contents = file_object.read()
print(contents)
print_file_conent(file)
#def write_list_to_file(output_file, lst) that can take a list or tuple and write each element to a new line in file
#create... |
5b58a23abe840827d71fccbe2a20830c10188433 | naughtymonkey1010/ltcode | /链表/141 环形链表/solution.py | 469 | 3.78125 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def hasCycle(self, head: ListNode) -> bool:
l1 = l2 = head
number = 0
while l1 != l2 or number == 0:
if l2 and l2.next:
... |
43aa2e4892a311a75f8e3709f967878e90590315 | uppala-praveen-au7/data_structures_and_algorithms | /linkedlist.py | 4,934 | 3.96875 | 4 | class Node:
def __init__(self,data=None):
self.data=data
self.next=None
class LinkedList:
def __init__(self):
self.head=Node()
def addElement(self,data):
new_node=Node(data)
cur=self.head
while cur.next!=None:
cur=cur.next
cur.next=ne... |
92f8d6d9cc08fe8d483a76a57ad8d40d92b212ae | SuperEpicness/Space-War | /src/level.py | 2,686 | 3.71875 | 4 | import pygame
# Base class for Level objects
class Level:
"""
Base class for Levels, or layers of objects, in the game
"""
def __init__(self, name):
self.background_color = [150,150,150]
self.name = name
self.sprites = []
self.groups = {}
self.texts = [] ... |
44e1f29531394a5cbcffe8d13f083596ca4c0c7f | aghared/weather_route | /best_route.py | 3,239 | 3.828125 | 4 | """
project2
Project 2 - finding the best route
Program: best_route.py
Author: Aghared Alyousif
Last date modified: 5/8/19
"""
import requests
import json
from itertools import permutations
API_KEY = ""
WS_URL = "https://api.openweathermap.org/data/2.5/forecast"
class City:
""" Repres... |
22bb5cd737fcdceda3ee4ee39726cda2a135eb78 | rapmetal/deeplearning.note | /numpy/shape.py | 413 | 3.84375 | 4 | # -*- coding:utf-8 -*-
import numpy as np
# Shape 数组的形状取决于其每个轴上的元素个数
a = np.array([[1, 2, 3, 4], [2, 3, 4, 5], [3, 4, 5, 6]])
print a
# [[1 2 3 4]
# [2 3 4 5]
# [3 4 5 6]]
print a.shape
# (3, 4)
# reshape 改变数组形状
a.ravel()
a.shape=(2, 6)
a.transpose()
print a
# [[1 2 3 4 2 3]
# [4 5 3 4 5 6]]
print a.reshape(4, 3)... |
866d10e9bd7fc99a6449b19b0d8567ef7174c7b1 | mchayapol/aucs-dsa | /sort/selectionsort/selectionsort.py | 280 | 3.84375 | 4 | def find_max(a,i):
m = 0
for i in range(1,i+1):
if a[i] > a[m]:
m = i
return m
def selection_sort(a):
for i in range(len(a)-1,-1,-1):
j = find_max(a,i)
a[i],a[j] = a[j],a[i]
A = [9,8,7,6,5,4,3,2,1]
selection_sort(A)
print A
|
0ce6120eda831d3848717388840c385692fa8148 | mchayapol/aucs-dsa | /trees/bst/bst.py | 3,171 | 4.125 | 4 | # Original code by : OMKAR PATHAK
class Node(object):
def __init__(self, data):
self.data = data
self.leftChild = None
self.rightChild = None
def insert(self, data):
''' For inserting the data in the Tree '''
# Your code goes here
pass
def minimum(self, no... |
433751420b7c77850d50bd4113f3dd5790c61aa1 | mchayapol/aucs-dsa | /_old/graph/priorityqueue0.py | 1,969 | 3.75 | 4 |
# Each obj to be inserted must be a class instance
# A field called 'index' will be added
class Priority_Queue:
def __init__(self, CompareFunc):
self.Comp = CompareFunc
self.a = []
def empty(self):
if self.a == []:
return True
else:
return False... |
d038110954b3326daf08fd6cdb8541d4ed76ffaf | rajkumarsrinivas/leetcode | /issubsequence.py | 348 | 3.78125 | 4 | from typing import List
# better solution O(n) with almost no extra space.
def isSubsequence(a: str, b: str) -> bool:
index = 0
for s in a:
if(s == b[index]):
index += 1
if index >= len(b):
return True
return False
if __name__ == "__main__":
print(isSubsequence(... |
154909d32a0cb3affe3f6c4548eb723d33c7894a | rajkumarsrinivas/leetcode | /longest_valid_parenthesis.py | 924 | 3.53125 | 4 | #
# https://leetcode.com/problems/longest-valid-parentheses/
#
from typing import List
# this approach is by me. I used 2 stack.. but this can be done using one stack as well..
def longestValidParentheses(s: str) -> int:
parenthesis = { "(" : ")"}
arr = list(s)
stack = []
stack_pos = [... |
67f783990475bb8c5fd2aec516868340f7495e50 | kruart/coding_challenges | /hackerRank/python3_/zipped.py | 315 | 3.734375 | 4 | # https://www.hackerrank.com/challenges/zipped/problem
if __name__ == '__main__':
_, x = map(int, input().split())
scores = [list(map(float, input().split())) for _ in range(x)] # get 'x' list of scores
print(*[sum(s) / x for s in zip(*scores)], sep="\n") # zip scores, get sums and then get average
|
6fca883d665e990214b2d41c54de0a598dbff80b | kruart/coding_challenges | /hackerRank/python3_/string-formatting.py | 337 | 4.125 | 4 | # https://www.hackerrank.com/challenges/python-string-formatting/problem
def print_formatted(num):
maxWidth = len(format(num, 'b'))
for i in range(1, num+1):
print("{0:>{width}} {0:>{width}o} {0:>{width}X} {0:>{width}b}".format(i, width=maxWidth))
if __name__ == '__main__':
n = int(input())
pr... |
937245a8adea42b446b50d7bacccaa71b12b83c4 | kruart/coding_challenges | /hackerRank/algorithms/BreakingTheRecords/breaking_the_record.py | 731 | 3.59375 | 4 | # https://www.hackerrank.com/challenges/breaking-best-and-worst-records/problem
def breaking_records(scores):
max_score = scores[0]
min_score = scores[0]
count_max_scores = 0
count_min_scores = 0
for i in range(1, len(scores)):
if scores[i] > max_score:
max_score = scores[i]
... |
c5d385b41cade2187400881bf390d7ffe5eb5c55 | kruart/coding_challenges | /hackerRank/algorithms/DiagonalDifference/diagonal_difference.py | 503 | 4.0625 | 4 | # https://www.hackerrank.com/challenges/diagonal-difference/problem
def diagonal_difference(arr):
return abs(sum([arr[i][i] - arr[i][len(arr)-i-1] for i in range(len(arr))]))
def main():
matrix1 = [
[1, 2, 3],
[4, 5, 6],
[9, 8, 9]
]
matrix2 = [
[11, 2, 4],
[4, 5... |
a75789b9c9a098301dc40809a6496e93f40fef97 | kruart/coding_challenges | /hackerRank/python3_/nested-lists.py | 372 | 3.796875 | 4 | # https://www.hackerrank.com/challenges/nested-list/problem
if __name__ == '__main__':
pairs = []
for _ in range(int(input())):
name = input()
score = float(input())
pairs.append([name, score])
second_lowest = sorted(set([p[1] for p in pairs]))[1]
[print(p[0]) for p in sorted(pa... |
ee934da6f5e0eee00050b8ed0845a2a9f70dd3e7 | katherfrain/Py101 | /tipcalculator2.py | 810 | 4.125 | 4 | bill_amount = float(input("What was the bill amount? Please don't include the dollar sign! "))
service_sort = input("What was the level of service, from poor to fair to excellent? ")
people_amount = int(input("And how many ways would you like to split that? "))
service_sort = service_sort.upper()
if service_sort == "P... |
2efd2878071e1534f85d45a7c3f36badb42c7a96 | katherfrain/Py101 | /grocerylist.py | 447 | 4.125 | 4 | def want_another():
do_you_want_another = input("Would you like to add to your list, yes/no? ")
if do_you_want_another == "yes":
grocery = input("What would you like to add to your list? ")
grocery_list.append(grocery)
print("You have added ", grocery, "to the list")
prin... |
b0d0c3cb9ddecbc04dec26e931bbdf20e97cda5d | Wilson-Wu1/listMerge | /listMerge.py | 2,022 | 3.59375 | 4 | #Wilson Wu
def copyList(newList, original):
for i in range(len(original)):
newList.append(original[i])
return newList
def addList(original,add):
for i in range(len(add)):
duplicate = False
for j in range(len(original)):
if original[j] == add[i]:
dup... |
7da13ff1b189f315a94f9d75862cff886cd8100f | mohitgoel188/Percolation_Testing | /quick_find.py | 901 | 3.75 | 4 | class QFind:
uid=[]
def __init__(self,N):
for i in range(N):
self.N=N
self.uid.append(i)
def connected(self,p,q):
if(self.uid[p]==self.uid[q]):
return 1
return 0
def union(self,p,q):
pid=self.uid[p]
qid=self.uid[q]
for i... |
b5466395f83aa04a6e88d54036b1ca476ff7377f | ChinaraIsabaeva/switch-translate | /lib/translate.py | 165 | 3.5 | 4 | # -*- coding: utf-8 -*-
from .letters import letters
def translate(text):
result = ''
for char in text:
result += letters[char]
return result
|
f658cdaf3774d6e21ceeb1198063b530b505ecc7 | nuria9/PER2018 | /prueba2.py | 130 | 4.09375 | 4 | print("eei estoy probando")
for element in range(0,3):
if element == 1:
print("holi")
else:
print("adios") |
3ff090cb5777a854538b320f8300606cb2c6f77c | choigww/dev-book | /Learn-Python3-The-Hard-Way/ex36.py | 9,574 | 4.4375 | 4 | # Exercise 36
# Designing and Debugging
# Homework
# Now write a game similar to the one that I created in the last exercise.
# Before you start coding you must draw a map for your game. Create the rooms, monsters, and traps
# that the player must go through on paper before you code.
from sys import exit
def game_st... |
013823685a250c14787d5611e347cf992ac8974d | muazniwas/leetcodeanswers | /LRU Cache/146.py | 816 | 3.6875 | 4 | from collections import OrderedDict
class LRUCache:
dic = OrderedDict()
capacity = -1
def __init__(self, capacity: int):
self.capacity = capacity
def get(self, key: int) -> int:
if key in self.dic:
self.dic.move_to_end(key, last=True)
return self.dic[ke... |
58165012baf8c4d3c4a37cc43e2d73b2cf766998 | muazniwas/leetcodeanswers | /Reverse Linked List/206.py | 475 | 3.859375 | 4 | class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]:
linkedlist = []
while head:
linkedlist.append(head.val)
head = head.next
reverse = ListNode(linkedlist[-1])
a... |
b15dd231c59cd9dcdee3858e927e31bec88f8019 | muazniwas/leetcodeanswers | /Add Binary/67.py | 602 | 3.609375 | 4 | def addBinary(a: str, b: str) -> str:
if a == "0":
return b
if b == "0":
return a
max = a
min = b
if len(b) > len(a):
max = b
min = a
ans = ""
bal = 0
for i in range(len(max) - len(min)):
min = "0" + min
for i in range(len(max)-1, -1, -1):
sum = int(min[i]) + int(max[i])... |
c3154e3aa0b2f43f72511f1908fb67faa3171e73 | muazniwas/leetcodeanswers | /Sum of leaves/-1.py | 790 | 3.609375 | 4 | class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def sumOfLeaves(root):
if root is None:
return 0
queue = []
rows = []
queue.append(root)
while(len(queue) > 0):
sumrow = 0
... |
285ed34c888c41ef04704eff4244d51d5e4af05a | muazniwas/leetcodeanswers | /Valid Parantheses/20.py | 316 | 3.828125 | 4 | def is_valid(s: str) -> bool:
pars = []
para_pairs = {
')': '(',
']': '[',
'}': '{'
}
for i in s:
if i in para_pairs.values():
pars.append(i)
else:
if len(pars) == 0 or para_pairs[i] != pars.pop():
return False
return len(pars) == 0
s = "(]"
print(is_valid(s))
|
c90c7e8801efe39b20a8af87d452ca350b940937 | muazniwas/leetcodeanswers | /Counting Elements/countingElements.py | 257 | 3.765625 | 4 | def countingElements(nums):
count = 0
l = len(nums)
d = {}
for i in range(l):
d[i] = nums[i]
for i in d:
if d[i]+1 in d.values():
count += 1
return count
arr = [1, 1, 2, 2]
print(countingElements(arr))
|
bb30b3504ec7a4a14ae82e232fc1e7bae5da5e01 | muazniwas/leetcodeanswers | /Trees/iterative.py | 4,301 | 4.03125 | 4 | def iterativePreorder(root):
# Base Case
if root is None:
return
# create an empty stack and push root to it
nodeStack = []
nodeStack.append(root)
# Pop all items one by one. Do following for every popped item
# a) print it
# b) push its right child
# c) push its le... |
51f78979b5833c093233f1dcfb55175c6b20f864 | wataoka/atcoder | /mitsui2019/c.py | 260 | 3.53125 | 4 | x = input()
s = list(x)
x = int(x)
if len(s) < 3:
print(0)
else:
xx = int(s[-2]+s[-1])
num_item = xx//5
if xx%5 != 0:
num_item += 1
hun = int(''.join(s[0:-2]))
if hun < num_item:
print(0)
else:
print(1) |
aa63e4925b83df45e94b810cc3f6283c372002b0 | wataoka/atcoder | /abc150/c.py | 396 | 3.640625 | 4 | import itertools
# 引数のリストの全ての順列リストを返す
def fact_list(seq:list):
return list(itertools.permutations(seq))
n = int(input())
P = list(map(int, input().split()))
Q = list(map(int, input().split()))
x = fact_list(range(1, n+1))
a = 0
b = 0
for i, xi in enumerate(x):
if list(xi) == P:
a = i+1
if list(x... |
8392ad4454c7e3eb207189abbf6520af62db8440 | wataoka/atcoder | /abc162/practice/c.py | 275 | 4 | 4 | from math import gcd
def gcd3(x, y, z):
return gcd(gcd(x, y), z)
K = int(input())
if __name__ == "__main__":
ans = 0
for a in range(1, K+1):
for b in range(1, K+1):
for c in range(1, K+1):
ans += gcd3(a, b, c)
print(ans) |
73561f8b37b279daf7f23ccc90d8e3c34993e94f | mengalong/public-soft | /algorithm/sort/merge-sort/merge-sort.py | 485 | 3.734375 | 4 | #!/usr/bin/env python
def spli(lists):
if len(lists) <= 1:
return lists
num = len(lists) / 2
left = spli(lists[:num])
right = spli(lists[num:])
return dichotomia_sort(left, right)
def dichotomia_sort(left,right):
l,r = 0,0
result = []
while l < len(left) and r < len(right):
if left[l] < right[r]:
r... |
392d5db8d1e6dfc31ed45b09d67fafe188d75610 | lecture-developer/lecture_website_app_generator | /utils/logger/file_logger.py | 4,715 | 3.65625 | 4 | """
Print logs to screen and saves them in some file
"""
# library imports
import os
from datetime import datetime
class Logger:
def __init__(self, file_path: str, mark_init=False):
if not os.path.exists(file_path):
file = open(file_path, "w+")
file.write("Start log at {}".format(... |
4af737bf5b5b88f0ad448b1133f102aad8fbb681 | MadderPete/reddit-user-behavior-analysis | /(data scraping & sentiment analysis & clustering part in 2013.py | 26,769 | 3.546875 | 4 |
# coding: utf-8
# ## 1. Scraping the data...
# This is the very first process of our project, we scrape the data from reddit which contains the title, text, ups(how many people love the post), downs(how many people don't like the post), comment numbers, main comment's scores and contents, sub comment's scores and con... |
8915f2a6f20611ea53f82a20feb69c156de2f287 | laxmitimalsina/Meme-Generator | /src/meme.py | 1,931 | 3.5 | 4 | """Meme generator that gives out path and quote."""
import argparse
import os
import random
import typing
import PIL
from Ingestor import Ingestor
from MemeGenerator import ImageCaptioner as MemeEngine
from QuoteEngine.Quote import QuoteModel
def generate_meme(path=None, body=None, author=None):
"""Generate a ... |
d6357e8dd854d3421e097edcb293017c6426c112 | darthkedrik/bracketmaker | /bracket.py | 856 | 3.796875 | 4 | '''
This is just a quick little bracket maker and randomizer for work ping pong
tournaments. It should, given a list of registrants, pair them into an
appropriately sized bracket and print out the list of pairs.
May make this print to an excel document, or simply to a document.
(c) Keith Diedrick, 2017
'''
import sy... |
9d19d2fd36c2c18e1fabac66fe3d6d69bd2c6eed | Atik-CSE/Learning-part | /Python/part 1/function parameter.py | 70 | 3.515625 | 4 | def sum(num1,num2):
sum=num1+num2
print(sum)
sum(5,4)
sum(9,5) |
7886ed09f35bf364801f2a84fdd3c20f6ef73423 | Atik-CSE/Learning-part | /Python/part 2/Typecasting2.py | 127 | 4.125 | 4 | num1=int(input("Enter 1st number : "))
num2=int(input("Enter 2nd number : "))
result=num1+num2
print("The result is : ",result) |
de6e363e0319f49f0171603961e1ba84c90d8d62 | ajitnak/py_pgm_strings | /str_swap.py | 208 | 3.59375 | 4 | def str_swap(s):
s = list(s)
end_idx = len(s)-1
for i in range(len(s)/2):
temp = s[i]
s[i] = s[end_idx-i]
s[end_idx - i] = temp
return ''.join(s)
print str_swap("1234567")
print str_swap("123456")
|
1f95cb24e277c9277e60dc58e06837ccdc3f2d36 | Scarlett1309/Romanian-sub-dialect-identification | /Sora_Ioana-Georgiana.py | 7,445 | 3.578125 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[168]:
#Importing Libraries
import numpy as np
import pandas as pd
import seaborn as sn
import csv
import matplotlib.pyplot as plt
from sklearn import svm, preprocessing
from sklearn.metrics import f1_score, accuracy_score,confusion_matrix, classification_report
# In[191]... |
2453ddd24e4c9218d0e2d8abaa44d8d17f195922 | portelaraian/algo-expert | /coding-interview-questions/array-of-products/solution.py | 342 | 3.625 | 4 | # O(n²) time | O(n) space
# where n is the length of the array
def arrayOfProducts(array):
arr_result = []
for i in range(len(array)):
product = 1
for j in range(len(array)):
if i == j:
continue
product *= array[j]
arr_result.append(product)
... |
88fc3202bca57e02fd3645c93a1859369b70ad1f | portelaraian/algo-expert | /coding-interview-questions/tournament-winner/solution_one.py | 1,012 | 3.59375 | 4 | # O(N) Time Complexity | O(K) Space Complexity
# where N is the number of competitions and
# K is the number of teams
def update_scores(team, current_winner, team_winners):
if team_winners == {}:
current_winner = team
if team not in team_winners.keys():
team_winners[team] = 0
team_winners[... |
1b74b8f40ed0ed9d93a5ba9494cbde7da8b201c2 | tomjsstewart/Prime-Sieves | /Sieve of Eratosthenes.py | 543 | 3.65625 | 4 | def SieveOfEratosthenes(limit):
numbers = [x for x in range(2, limit + 1)]
primes = [True] * (limit - 1)
results = []
p = 2
for x in numbers:
if primes[x - 2] == True:
p = numbers[x - 2]
for num in numbers:
if (num * p) > limit:
... |
cbe36f59bfb046d56a75b27102a6174fa2cc9a45 | babushkian/barevo | /grid_tools.py | 1,777 | 3.96875 | 4 | """
в объекте класса "Сетка" содержится список объектов класса "Ячейка" (клетка). В каждой ячейке что-то одно может лежать,
не более.
"""
class Grid:
def __init__(self, res):
self.res = res # размер квадратного цикличного поля
self.cells = [] # все ячейки на поле
for pos in range(res ** 2)... |
32be140dba63aa4e12e5386b360aa8b0a210e7e4 | ampersander-f/URC-Mil-Neigh-App | /code/PressureSensor2Body.py | 1,653 | 3.59375 | 4 | '''
Subclass of PressureSensor, tailored to use the Rice-Lin potential function instead. 2 body potential only
'''
from PressureSensor import PressureSensor
import math
class PressureSensor2Body(PressureSensor):
'''Creates the sensor itself, only defining its location and bounds.
Parameters:
bounds - tuple of ... |
bd3989aa55c7a349c3c3553e5fce0d52324caf23 | LopezN26/Exercices-it | /python/TP21.2.py | 240 | 3.671875 | 4 | import turtle
def spirale (color, epaisseur):
turtle.speed(0)
r=3
turtle.color(color)
turtle.width(epaisseur)
for i in range(100) :
r = r+epaisseur/2
turtle.circle(50*epaisseur-i,90)
spirale('blue',2) |
31123dd780bfee41dbe323144e683b3ab48f3bf1 | Ahnyezi/algorithm-python | /boj/greedy/B1931/n1931_2.py | 1,250 | 3.5 | 4 | # 1. 리스트 정렬
# <정렬방법>
# 1) 시작 시간을 기준으로 (x)
# 2) 회의 지속 시간을 기준으로 (x)
# 3) 종료 시간을 기준으로 (o)
# 2. 정렬된 리스트에서 하나씩 뽑아서 회의 배치
import sys
def greedy(meeting):
end_time = 0 # 이전 회의의 종료시간
meeting_count = 0
for time in meeting:
if end_time <= time[0]: # 이전 회의 종료시간 <= 현재 회의 시작시간
meeting_coun... |
921f0f6002b3eeb6fe071c3cccd6c39e02628c0b | nicklee100/python_practice | /Untitled.py | 182 | 3.8125 | 4 |
def triangleUp(n):
if n == 0: #base case
return
else:
triangleUp(n-1)
print("triangleUp"+str(n))
print(n*("*"))
triangleUp(5)
|
769a1b6c5edbc0c4e43acba36ef6cb22d7e076bd | XingLiangLondon/Deep-Learning-Neural-Network | /Flexible_MultiLayer_Neural_Network.py | 13,628 | 3.703125 | 4 | ################################################################################################
## Deep Learning Neural Network for Nonlinear Regression using Gradient Descent ##
## [Linear->Leaky Relu]*(L-1)->[Linear->Pure Linear]*1 ##
## by... |
e4a1874fe87831a77028b03100153bc86ad42575 | larrymw/civicu-pythonii-fall-2017 | /student_work/larrymw/lesson3/puppy_finder.py | 4,590 | 3.6875 | 4 | #
""" This module finds dogs for adoption """
#
import requests
import csv
from pprint import pprint as pp
# The standard parameters that petfinder.com uses for all dog requests
dog_params = {"key":"900cf5ac938676646decc123b24ab678", "animal":"dog", "format":"json"}
def request(req_url, params={}, print_status=False... |
651575260a2bc203355736d7bfa214c40011150c | xuming0629/xm-study | /xm-study/python-test/NT.py | 245 | 3.75 | 4 | import numpy as np
def sqrt_newton(num):
x=np.sqrt(num)
y=num/2.0
count=1
while abs(y-x)>1e-8:
print (count,y)
count+=1
y=((y*1.0)+(1.0*num)/y)/2.0000
return y
print(sqrt_newton(5))
print(np.sqrt(5))
|
5a16f0bd0cceec2370feb7eb5ae86624e15ccf66 | xuming0629/xm-study | /xm-study/python-test/error1.py | 213 | 3.609375 | 4 | from math import log as ln
def error(h):
return (1.0/h)*abs(df(x)-(f(x+h)-f(x))/h)
def f(x):
return ln(x)
def df(x):
return 1.0/x
x=10
hlist=[]
for h in 0.2,0.1,0.05,0.01,0.001:
print(h,error(h))
|
74ff1457f9dfff1373203f466727e2a839c87ed6 | xuming0629/xm-study | /xm-study/python-test/whi_f.py | 227 | 3.59375 | 4 | i=1
sum_all=0
sum_odd=0
sum_even=0
while i<=100:
sum_all=sum_all+i
if i%2==0:
sum_even=sum_even+i
else:
sum_odd=sum_odd+i
i=i+1
print("和=%d、奇和=%d、偶和=%d"%(sum_all,sum_odd,sum_even))
|
c3bbebeeaa6118e17c9194f80f236f9f1a6b0937 | xuming0629/xm-study | /xm-study/python-test/fsolve.py | 413 | 3.59375 | 4 | """
非线性方程组的求解
例: Missing parentheses in call to 'print'
5x1+3=0
4x0**2-2*sin(x1*x2)=0
x1*x2-1.5=0
"""
import numpy as np
from scipy import optimize
def f(x):
x0,x1,x2=x.tolist()
return [
5*x1+3,
4*x0**2-2*np.sin(x1*x2),
x1*x2-1.5
... |
5fe4fa72a49d2e32370de45780db1ea8d54fd0d1 | xuming0629/xm-study | /xm-study/python-test/9.py | 307 | 3.703125 | 4 | #!/usr/bin/python3
#coding:utf8
def fun(x,y):
if x == y:
print(x,'=',y)
else:
print(x,'!=',y)
#s1 = input("input something:")
#s2 = input("input something:")
#fun(s1,s2)
def mashine(x=3,y='奶油'):
print("生产一个",x,'元',y,'口味的冰机林!')
mashine()
|
cfedf967d0c5218288ec36fe1298a03360afe405 | xuming0629/xm-study | /xm-study/python-test/Hello1.py | 610 | 3.828125 | 4 | from tkinter import * # 导入 tkinter 模块的所有内容
root = Tk()
#创建1个TK根窗口组件root
btnSayHi=Button(root)
# 创建1个按钮组件 btnSayHi,作为 root 的子组件
btnSayHi["text"]="Hello"
# 设置 btnSayHi 的text 属性
btnSayHi.pack()
# 调用组件的pack 方法,调整其显示位置和大小
def sayHi(e): # 定义事件处理程序
messagebox.showinfo("Message","Hello,World!") # 弹出消息框
btnSayHi.b... |
755617a1a942fa662d0ac31f05c6829369ea4125 | xuming0629/xm-study | /xm-study/python-test/sushu.py | 206 | 3.765625 | 4 | import numpy as np
def isPrime(n):
if n<=1:
return False
for i in range(2,int(np.sqrt(n))+1):
if n%i==0:
return False
return True
prime=isPrime(100)
print(prime)
|
66d9399e0ebea197632f9514de1a1d9f1214fb8e | Tanish2001/Py | /print('helloe world').py | 246 | 3.96875 | 4 | print('hello world')
num1=1.5
num2=6.3
sum=num1 + num2
print('the sum of {0} and {1} is {2}'.format(num1,num2,sum))
print(type(num1))
print("Enter no. to add")
number1=input()
number2=input()
sum= int(number1)+ int(number2)
print(sum) |
e5307a7d08617f00b14cadf0bc1cdb849a1a744c | Tanish2001/Py | /health management sys.py | 477 | 3.59375 | 4 | print("Welcome to Health Manage System")
client=input("Plz enter Client Name.\n")
if client=="Tan":
f=open("E:\\Python Programs\\Tan.txt", "r+")
elif client=="Man":
f=open("E:\\Python Programs\\Man.txt", "r+")
elif client=="Kan":
f=open("E:\\Python Programs\\Kan.txt", "r+")
a=f.readline()
print(a)
... |
15cba18ee92d82bf0f612e96ece1dc4a2911d9fc | ghimire007/jsonparser1 | /jsonparser.py | 1,111 | 4.1875 | 4 | # json parsor
import csv
import json
file_path = input("path to your csv file(add the name of your csv file as well):") # takes file path
base_new = "\\".join(file_path.split("\\")[:-1])
file_name = input(
"name of th file that you want to save as after conversion(no extension required):") # takes nam... |
80334df22eddf14bde2b6144fe8e29296726b642 | himala76/Codding_Lesson_1 | /Lectures_Note_Day_1/input.py | 146 | 3.8125 | 4 |
# Use the raw input function to get someones name
users_name = raw_input("Please type your name: ")
print "It's nice to meet you " + users_name
|
84e0a3ba3678e6e5bc8618871e8d7a2eb6cebfe1 | himala76/Codding_Lesson_1 | /Lectures_Note_Day_1/Cancat.py | 352 | 4.4375 | 4 | # This is the result we want to have in the console
#print "Hello, world! My name is Josh."
# Create a variable to represent the name and introduction statement to print
name = "Josh"
# Comment out this line for the moment
# intro_statement = "Hello, world! My name is "
# print the concatenated string
print "Hello, ... |
8cbb5d6729a1c6907ed753d8768709dadffb5bbc | realbad/pystarter | /NetworkXtest.py | 905 | 3.5625 | 4 | import networkx as nx
import matplotlib.pyplot as plt
def searchPath(graph, start, end):
results = []
_generatePath(graph, [start], end, results)
results.sort(key=lambda x:len(x))
return results
def _generatePath(graph, path, end, results):
current = path[-1]
if current == end:
results... |
7a198a6ec1482fca70aaf1ccfae3126c369412fc | Arkady-A/AnkiWordGrabber | /agrab/data/handlers.py | 2,224 | 3.828125 | 4 | class Word():
'''
Class that handles words and their definitions
'''
def __init__(self, word, pronounciations ):
'''
Parameters
----------
word : str
'''
self.word = word
self.pronounciations = pronounciations
# dictionary of structure... |
db5aa21b8edc352f812d8c4798e6a2e18172eb53 | iahmad-khan/python-handson-CERN-4day | /class.py | 403 | 3.765625 | 4 | #!/usr/bin/python
class counter:
def __init__(self, start):
self.count = start
def up(self, n=1):
self.count += n
def down(self, n=1):
self.count -= n
class addcounter(counter):
def __repr__(self):
return 'addcounter({.count})'.format(self)
def __add__(self,other):
... |
ea9fe8e5ea4bbb57aab192bbfa2009d5713eee43 | LaunchCodeEducation/LCHS_movie_sql_project | /db_setup.py | 1,354 | 3.640625 | 4 | import sqlite3
db = sqlite3.connect('project.db')
cursor = db.cursor()
cursor.execute("DROP TABLE IF EXISTS movies")
cursor.execute("DROP TABLE IF EXISTS directors")
sql_query = """
CREATE TABLE IF NOT EXISTS directors
(director_id INTEGER PRIMARY KEY, last_name TEXT, first_name TEXT)
"""
cursor.execute... |
b363668bbe96919d8648ec7be855241b2d6f5aa8 | asenath247/COM404 | /1-basics/3-decision/2-if-else/bot2.py | 208 | 3.625 | 4 | print ("Please enter the activity to be performed")
activity = input()
if activity == "calculate":
print ("Performing calculations")
else:
print ("Performing activity")
print ("Activity completed")
|
f516edc9181ed1fe844a70d44b7b440f22e83bac | asenath247/COM404 | /1-basics/2-input/2-ascii-robot/bot.py | 162 | 3.75 | 4 | eyes = input("What do you want the eyes to look like? ")
print("##########")
print("# "+ eyes + " "+ eyes + " #")
print("# _____ #")
print("##########")
|
4b02cf096cd437659968330d1e2fed228fd2036f | asenath247/COM404 | /1-basics/4-repetition/3-ascii/bot.py | 212 | 4.15625 | 4 | print("How many bars should be charged.")
bars = int(input())
chargedBars = 0
while chargedBars < bars:
print("Charging "+"█" * chargedBars)
chargedBars += 1
print("The battery is fully charged.")
|
1a8a2e189f4ae17a0a9290e4539bf0e0e55a4310 | dhwgithub/Python-GUI | /pygame_learn/movingBird_3.py | 2,529 | 3.53125 | 4 | # 引入
import pygame
import random
from pygame.color import THECOLORS
# 定义小鸟类
class AngryBirdClass(pygame.sprite.Sprite):
def __init__(self, image_file, location, speed):
pygame.sprite.Sprite.__init__(self)
self.image = pygame.image.load(image_file)
self.rect = self.image.get_rect... |
e51656988d8c3db9112f2d7ecf91a2a60e80cd82 | dhwgithub/Python-GUI | /tkinter_learn/listbox.py | 1,302 | 3.65625 | 4 | import tkinter as tk
window = tk.Tk()
window.title('My Window')
window.geometry('500x300')
var1 = tk.StringVar() # 创建变量,用var1用来接收鼠标点击具体选项的内容
l = tk.Label(window, bg='green', fg='yellow', font=('Arial', 12), width=10, textvariable=var1)
l.pack()
# 创建一个方法用于按钮的点击事件
def print_selection():
if lb.curselec... |
d83584c590e6411fe026111a314b311b7f0962c1 | vishal-B-52/Documentation_of_Python | /OOPExercise5.py | 4,645 | 4.78125 | 5 | # Using class method for alternative constructor :-
"""
Suppose a user wants to create an object by giving class as input and then passing a string which will get break down to
"name", "Salary" and "post".
The object must gain it's value from just a string statement and should cover all the 3 arguments of __ini... |
e954e33dc01eb1c568a727cc62d554787e2a6eb7 | vishal-B-52/Documentation_of_Python | /Stone Paper Scissor.py | 2,557 | 3.96875 | 4 |
import names
import random
while 1:
opponent = names.get_full_name()
sep_names = opponent.split(' ')
fname = sep_names[0]
get_name = input("\nEnter your name here: ")
print(f"Welcome {get_name}, You are welcomed to the contest of Stone-Paper-Scissor.")
print(f"We will be arranging yo... |
c996ed636d4b3a494d97aef89b9906dcc10b00d5 | vishal-B-52/Documentation_of_Python | /Recursion.py | 3,805 | 4.34375 | 4 | # Recursion -
"""
It means using function inside a function. Mostly like a loop formation.
"""
# def getstr(a):
# print(getstr(a))
# print("I am" + a)
# getstr("vishal")
"""
When you print it, it will display an error regarding recursion depth exceeding.When the function was called , it
compl... |
151de77afa44a23001ff21b21e3573d8e87fdce9 | vishal-B-52/Documentation_of_Python | /Handling read and write.py | 594 | 3.9375 | 4 | # Reading and writing file at the same time -
"""
You can read and write a file at the same time by special method. You can read the content of a file and write into it
if required. This thing requires 'r+' mode. This mode will automatically grant you permission to read a file and access
it through various purpos... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.