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 |
|---|---|---|---|---|---|---|
44fd50322f2782158a91295fc48605001ea4bf71 | goraci0/Lesson5 | /divisor_master.py | 312 | 3.6875 | 4 | def simpl(n):
for i in range(2,n):
if n%i == 0: return 0
return 1
def list_div(n):
list_d = [1]
for i in range(2,n+1):
if n%i == 0: list_d.append(i)
return list_d
def max_div(n):
list_d=list_div(n)
list_d.reverse()
for i in list_d:
if simpl(i): return i
|
5cbc6fd2b4a9f6a1530a2e9c617a060f668aaeef | xxrom/grokaem_0_simple | /multipleOutputs.py | 382 | 3.546875 | 4 | def ele_mul(number, vector):
output = [0, 0, 0]
assert (len(output) == len(vector))
for i in range(len(vector)):
output[i] = number * vector[i]
return output
weights = [0.3, 0.2, 0.9]
def neural_network(input, weights):
pred = ele_mul(input, weights)
return pred
wlrec = [0.65, 0.8, 0.8, 0.9]
inpu... |
107aa621895a8236da00f78d0cf90f86080bd4eb | Sushmi-pal/pythonassignment2 | /Q5.py | 347 | 3.671875 | 4 | myinfo=('Sushmita','Palikhe',22)
liofpeople=[]
liofpeople.append(myinfo)
moreinfo=('Sanima','Palikhe',25)
liofpeople.append(moreinfo)
more=('Sabin','Palikhe',20)
liofpeople.append(more)
print('sorting by age')
liofpeople.sort(key=lambda x:x[2])
print(liofpeople)
print('sorting by firstname')
liofpeople.sort(key=lambda ... |
3429d11fc52227a3321c0fa58f52decb11ec6062 | Sushmi-pal/pythonassignment2 | /Q19.py | 423 | 3.765625 | 4 | class valid:
def __init__(self,text):
self.text = str(text)
def val(self):
for i in range(0,len(self.text)-1,2):
if ((self.text[i]== '{') and (self.text[i+1]=='}')) or ((self.text[i]== '(') and (self.text[i+1]==')')) or ((self.text[i]== '[') and (self.text[i+1]==']')):
if (i==len(self.text)-2)... |
fb60ccd505a4a9a922eb69f2d4844ce2efc6d8fa | sshalu12/Calculator | /main.py | 1,549 | 4 | 4 | from art import logo
from replit import clear
print(logo)
def cal(no1,op,no2):
if(op=="+"):
return no1+no2
elif(op=="-"):
return no1-no2
elif(op=="*"):
return no1*no2
else:
return no1/no2
def calculator():
a=float(input("What's the first number: "))
print("+\n-\n*\n/\n")
ends=True
while ... |
3badf06f5b01c0db6993d0dafd819ed022a2a4ae | ibocon/coding-interview-notes | /정렬/TopologySort_위상정렬.py | 1,526 | 3.59375 | 4 | # Topology sort 위상정렬
# 순서가 정해져 있는 일련의 작업을 수행할 순서로 정렬
# 1. 진입차수가 0 인 노드를 큐에 추가
# 2. 큐에서 노드를 꺼내, 노드에서 출발하는 간선 제거
# 3. 새롭게 진입차수가 0 인 노드를 큐에 추가
# * 모든 원소 방문 전, 큐가 비면 사이클 존재
# * 큐에 노드 개수 2 이상 추가 시, 경우의 수 발생
from collections import deque
import sys
rl = sys.stdin.readline
def topology():
""" Topology sort 위상 정렬 함수 "... |
f7c332f14e479dadb8b3d758dfdf15d015fa3616 | zhouyzhao/Python_Test | /Python2_test/ex33.py | 261 | 4.0625 | 4 | # -*- coding: utf-8 -*-
# ex33.py
i = 0
number=10
numbers = []
while i < number:
print "At the top i is %d " % i
numbers.append(i)
i= i+1
print "Numbers now:", numbers
print "At the bottom i is %d" %i
print "The numbers:"
for num in numbers:
print num |
b57723b01cbdc3bf74943fd43849369ba48de3bc | kaharkapil/Python-Programs | /addn1.py | 184 | 3.9375 | 4 | a=int(input("enter a:"))
b=int(input("enter b"))
print(a)
print(b)
c=a+b
print("sum is:",c)
c=a-b
print("difference is:",c)
c=a*b
print("product is:",c)
c=a/b
print("division is:",c)
|
e6631f96b9e4114ab647c59347555d85da8658ad | Thinushika/Practice_Projects | /Python/CoolCalculator/app.py | 3,754 | 3.59375 | 4 | from tkinter import*
import tkinter
# styles for the gui window
window = tkinter.Tk()
window.geometry("312x324")
window.resizable(0,0) # prevent from resizing the window
window.title("Cool Calulator")
def btn_click(item):
global expression
expression = expression + str(item)
input_text.set(expression)
d... |
c2116fd8a0f67c58868e832a9468a41713833893 | kyle-fricke/Labchart-Dropout-Detection | /Python/ReadDirectory.py | 759 | 3.90625 | 4 | ## Search directory for File Type
## This script (Function) will take a path and list all files of specific type in the folder
## Output will return series of file paths
import os
#Returns all Files of set type in all directorys - root down
def OutputFileNames(File_Path,Type):
File_List=[]
for r, d,... |
f85801ad2f8ba74b1e63f21c0ba37e6be29a52af | lesser618/python-projects | /test.py | 81 | 3.65625 | 4 | def col(x):
if x%2 == 0:
return x/2
else:
return (3*x)+1
|
911c306c8eee67fa2cae3fb878fe0a41635c8564 | WMBYCK/Iteration | /ClassExercises_Statements_Helpingness2.py | 185 | 4.1875 | 4 | number = 1
total = 0
while number != -1:
number = int(input("Please enter number"))
if number > 0 :
total = total + number
total = total /
print(total)
|
23d68a0cc1716f2c39003ff9e329a6b89ebe4048 | WMBYCK/Iteration | /Starter_Task_1.py | 314 | 3.90625 | 4 | # William Craddock
# 20/10/2014
# Starter - Task - 1
total = 0
counter = 1
while counter < 6:
number = int(input("Please enter number {0} in the series: ".format(counter)))
total = total + number
counter = counter + 1
print()
print("The total of the numbers you entered is {0}".format(total... |
eba924d5e70d3e71fc450d8c9e7cedf202a60624 | simonsenh/L1-Python-Tasks | /PRIME.py | 393 | 4.03125 | 4 | b = 1
a = 2
c = 1
n = int(input("What is your number"))
while c <= n:
c += 1
a = 2
while a <= n:
if c * a == n:
b = 2
a = a + 1
if n == 1:
b = 2
if b == 2:
print("It is not a prime number")
if b == 1:
print("It is a prime number")
#This code will only go up to around 4 ... |
49200c3d434122ed151fab86804bcaf6863e4f1b | haoccheng/pegasus | /leetcode/btree_level_traversal.py | 433 | 3.90625 | 4 | # Given a binary tree, return bottom-up level order traversal.
def level_order_bottom(root):
if root is None:
return []
ret = []
curr = [root]
while len(curr) > 0:
row = []
next = []
for node in curr:
row.append(node.val)
if node.left is not None:
next.append(node.left)
... |
e4e9e348cbbcda786f08eca235b41059c23b2c3f | haoccheng/pegasus | /coding_interview/bst2linedlist.py | 1,304 | 4.03125 | 4 | # convert a binary search tree into a sorted double-linked list without creating new nodes.
class Node:
def __init__(self, value, left=None, right=None):
self.value = value
self.left = Node(left) if left is not None else None
self.right = Node(right) if right is not None else None
self.prev = None
... |
cfbe6b1a34a616b9ac29be02392c832eee9ba18b | haoccheng/pegasus | /leetcode/strstr.py | 768 | 4.03125 | 4 | # strstr()
# Return the index of the first occurrence of needle in haystack, or -1 if needle is not part of the haystack.
#
# A few things I think about.
# bruteforce, use suffix tree, KMP.
def strstr(haystack, needle):
if len(haystack) == 0 or len(needle) == 0:
return -1
elif len(needle) > len(haystack):
... |
a5f272c3fea3f52fe838cf1cadb3ea9ade81e96a | haoccheng/pegasus | /leetcode/triangle.py | 557 | 3.78125 | 4 | # triangle: find the minimum path sum from top to bottom.
# Each step, you may move to adjacent numbers on the row below.
def pathsum(triangle):
if len(triangle) == 0:
return 0
curr = [-1] * len(triangle)
curr[0] = triangle[0][0]
for i in range(1, len(triangle)):
print curr
next = [-1] * len(triang... |
83f13c14f5798213582b81e2ee1188b5b5e402dd | haoccheng/pegasus | /leetcode/min_rotate_sort_array.py | 559 | 3.828125 | 4 | # find minimum of rotated sorted array.
# https://leetcode.com/problems/find-minimum-in-rotated-sorted-array/
def pivot(nums):
start = 0
end = len(nums) - 1
while (start <= end):
mid = (int)((start + end) / 2)
v1 = nums[start]
v2 = nums[mid]
v3 = nums[end]
if v1 > v2:
end = mid
elif... |
f8d38ef5ba690a50e58554b0edfb0ecdf3610f95 | haoccheng/pegasus | /leetcode/insertion_sort_list.py | 1,396 | 4.125 | 4 | # insertion sort in linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
def create_list(values):
root = None
curr = None
for v in values:
n = ListNode(v)
if root is None:
root = n
curr = root
else:
curr.next = n
cu... |
a58c7b34f9f3bf327d5ea59492a40159b90aafef | haoccheng/pegasus | /leetcode/google/subarray_sum.py | 872 | 3.671875 | 4 | # determine if there is a subarray sum to target. (positive integers).
def subarray_sum(input, target):
start = 0
end = start
cumsum = input[start]
com = []
while (True):
while (end < len(input)-1 and cumsum < target):
end += 1
cumsum += input[end]
if cumsum == target:
com.append(in... |
7ed5174a51a7b91a18a40a23dc544a2dfb5fc908 | haoccheng/pegasus | /coding_interview/maze_path.py | 1,660 | 3.8125 | 4 | # Implement a function to check whether there is a path for a string in a matrix of characters.
# The path cannot enter the same cell twice.
#
# a b c e -> bcced (yes)
# s f c s -> abcd (no).
# a d e e
class Node:
def __init__(self, x=None, y=None):
self.child = []
self.x = x
self.y = y
def build_ro... |
44804d6066bb01fe8ee9c45a8f42455bb0fb4de7 | haoccheng/pegasus | /leetcode/multiply_string2.py | 908 | 3.671875 | 4 | # Given two numbers represented as strings, return mulplications of the numbers as string.
# numbers are arbitrary long and non-negative.
def multiply(num1, num2):
result = [0] * (len(num1)+len(num2))
for i in range(len(num1)):
for j in range(len(num2)):
zlen = len(num1)-1-i + len(num2)-1-j
pos = l... |
c5b409cb26178c2b603e7763e23d238545ca4432 | haoccheng/pegasus | /leetcode/populate_next_right.py | 382 | 3.84375 | 4 | # populate next right pointers in each node in complete binary tree.
def connect(left, right):
if (left is None) and (right is None):
return
left.next = right
if left.left is not None:
connect(left.left, left.right)
connect(left.right, right.left)
connect(right.left, right.right)
def connect(roo... |
11cc9885c5b7c17104ca150d77153176a9a65449 | haoccheng/pegasus | /leetcode/quicksort.py | 851 | 3.828125 | 4 | # quick sort.
def quicksort(input, start, end):
count = end - start + 1
if count <= 1:
return
elif count == 2:
if input[start] > input[end]:
t = input[start]
input[start] = input[end]
input[end] = t
else:
pivot = input[start]
i = start + 1
j = end
while (i < j):
... |
a9799d351c087bf5eec29609fa70a87781324cae | haoccheng/pegasus | /coding_interview/reverse_list.py | 1,579 | 4.09375 | 4 | # reverse a linked list
class Node:
def __init__(self, value):
self.value = value
self.next = None
def create(values):
root = None
curr = None
for v in values:
n = Node(v)
if root is None:
root = n
curr = n
else:
curr.next = n
curr = curr.next
... |
72f8aba0e3de7401fc6d78ba8a54671f17cd45c6 | haoccheng/pegasus | /leetcode/unique_paths_ii.py | 613 | 3.5625 | 4 | # https://leetcode.com/problems/unique-paths-ii/
# mxn matrix.
# How many unique paths from top-left to bottom-right obstacles..
def unique_paths(obstacle):
m = len(obstacle)
n = len(obstacle[0])
rows = []
for i in range(m):
row = [0] * n
rows.append(row)
for i in range(m):
if obstacle[i][0] == 1... |
8df34a506a8f2ecb8e99b141dcdb56a4488b43fc | haoccheng/pegasus | /leetcode/facebook/skyline.py | 1,509 | 4.03125 | 4 | # https://leetcode.com/problems/the-skyline-problem/
def compare(p1, p2):
# (start/end, time, height)
if p1[2] == p2[2]: # same time point.
if p1[1] == 'start' and p2[1] == 'end':
return -1
elif p1[1] == 'end' and p2[1] == 'start':
return +1
else: # same start/end type.
if p1[0] < p2[... |
56eb2611b5e1e082d2b2179a872f2de9e7b81070 | haoccheng/pegasus | /leetcode/sort_array_btree.py | 391 | 3.703125 | 4 | # convert sorted array to height-balanced BST.
def bst_base(nums, start, end):
if (start > end):
return None
if (start == end):
return TreeNode(nums[start])
else:
mid = (int)((start + end) / 2)
root = TreeNode(nums[mid])
if start < mid:
root.left = bst_base(nums, start, mid-1)
if mi... |
c5874000fe713f1c233b353223dee5f2bc177aa7 | haoccheng/pegasus | /leetcode/google/integral_image.py | 578 | 3.703125 | 4 | # compute integral image
# [i,j]: sum of values from [0,0] to [i,j]
def integral(matrix):
scores = []
for i in range(len(matrix)):
row = [0] * len(matrix[i])
scores.append(row)
tmp = 0
for j in range(len(matrix[0])):
tmp += matrix[0][j]
scores[0][j] = tmp
for i in range(len(matrix)):
tmp ... |
e831bdee15db343318aab42c80ef99bf1b8755e0 | haoccheng/pegasus | /leetcode/count_say.py | 735 | 3.875 | 4 | # count-and-say sequence is the sequence of integers as below:
# 1, 11, 21, 1211, 111221, ..
#
# 1 -> 'one 1' -> 11
# 11 -> 'two 1' -> 21
# 21 -> 'one 2 one 1' -> 1211
# Given n, generate the nth sequence.
def count_say_base(ns):
stack = []
ret = ''
for c in ns:
if len(stack) == 0:
stack.append(c)
... |
b8c79c64b1f91888afb0fadaf80e9af7921f191d | haoccheng/pegasus | /leetcode/power_of_two.py | 416 | 4.375 | 4 | # Given an integer, determine if it is a power of two.
def power_of_two(n):
if n <= 0:
return False
else:
value = n
while (value > 0):
if value == 1:
return True
else:
r = value % 2
if r != 0:
return False
else:
value = value / 2
retur... |
640c0f7d89e947bd519524ae86a5961714516156 | haoccheng/pegasus | /leetcode/jump_game_ii2.py | 498 | 3.625 | 4 | # [2,3,1,1,4] -> 2.
def jump(nums):
if (len(nums) == 0) or (len(nums) == 1):
return 0
prev_max = 0
curr_step = 1
curr_max = nums[0]
while (curr_max < len(nums)-1):
next = 0
for s in range(curr_max, prev_max, -1):
next = max(next, s + nums[s])
if next >= len(nums)-1:
return curr_st... |
fe52e7a05e1abf998edf9f016e1798041fe1fbd5 | haoccheng/pegasus | /leetcode/google/integer_str.py | 1,556 | 3.78125 | 4 | # convert integer to string. 1000 -> one thousand.
def int2str10(value):
if (value > 0) and (value < 10):
m = {1:'one', 2:'two', 3:'three', 4:'four', 5:'five', 6:'six', 7:'seven', 8:'eight', 9:'nine'}
return [m[value]]
def int2str100(value):
if (value > 0) and (value < 10):
return int2str10(value)
e... |
05e6b8a692ed714dccaf6b6d2af704c34a4aad4e | haoccheng/pegasus | /coding_interview/binary_num1.py | 342 | 3.828125 | 4 | # Implement a function to get the number of 1s in the binary representation of an integer.
# 9 : 1001 in binary. -> 2.
# integer 32-bit.
def count1(input):
count = 0
for i in range(32):
bit = (1 << i)
v = input & bit
if v != 0:
count += 1
return count
print count1(0)
print count1(1)
print coun... |
1192482b1968eab7df6c920e88c7a7eb20cd3e9e | haoccheng/pegasus | /coding_interview/path_sum.py | 1,078 | 3.84375 | 4 | # Given a binary tree and an integer value, print all paths where the sum of node values equal to given integer.
# All nodes from root to leaf compose a path.
class Node:
def __init__(self, value, left=None, right=None):
self.value = value
self.left = Node(left) if left is not None else None
self.right =... |
37dbed487e8cb71189f656b8caf83bfba80d9ac2 | haoccheng/pegasus | /leetcode/sort_colors.py | 468 | 3.90625 | 4 | # array of n objects in red/white/blue, sort them so that objects of same color
# are adjacent, in order red/white/blue.
# 0/1/2 represent red/white/blue.
def sort_color(nums):
h0 = 0
h1 = 0
h2 = 0
for v in nums:
if v == 0:
h0 += 1
elif v == 1:
h1 += 1
elif v == 2:
h2 += 1
x = 0... |
d51e2ea297208ba200f8a97f55c9bff13b67dff4 | haoccheng/pegasus | /coding_interview/combination.py | 1,330 | 3.6875 | 4 | # generate all combination of a given string.
# Combination of 'abc' -> 'a', 'b', 'c', 'ab', 'bc', 'ac', 'abc'
# bit representation. 000 -> 001 ..
# only thing to watch out is for arbitrary length of string.
# This calls for a BigInt implementation.
class BigInt:
def __init__(self):
self.bits = ['1']
def nex... |
c17c5f659191eb5af106f09a82be8ca935278387 | haoccheng/pegasus | /leetcode/btree_pre-inorder2.py | 729 | 3.578125 | 4 | # build binary tree from preorder/inorder traversal sequences.
def build_base(preorder, inorder):
if len(preorder) == 0:
return None
elif len(preorder) == 1:
return TreeNode(preorder[0])
root_value = preorder[0]
root_index = inorder.index(root_value)
root = TreeNode(root_value)
preorder.pop(0)
in... |
1999d699e76c6b0476793e5ce4a4ee7984be7f17 | haoccheng/pegasus | /leetcode/google/connected_component2.py | 1,084 | 3.625 | 4 | # connected component of undirected graph.
# input: set of edges.
def connected_component(edges):
cluster = {}
for (start, end) in edges:
if start not in cluster and end not in cluster:
c = start if start < end else end
cluster[start] = c
cluster[end] = c
elif start not in cluster:
... |
226c3a1737744e1d66c90fa73772a827a0b9b222 | haoccheng/pegasus | /leetcode/house_robber.py | 445 | 3.546875 | 4 | # Each house has a certain amount of money.
# If two adjacent hourses were broken into, it will trigger the alarm.
# Determine the maximum amount of money that can rob without trigger tha alarm.
def rob(nums):
if len(nums) == 0:
return 0
yes = nums[0]
no = 0
for i in range(1, len(nums)):
yes1 = no + nu... |
a4ebc99bfecf72d338751cae4190d3009f9646f2 | haoccheng/pegasus | /leetcode/surround_region.py | 1,770 | 3.5 | 4 | # surrounded region.
# https://leetcode.com/problems/surrounded-regions/
def dfs(board, x, y):
if board[x][y] == 'X':
return
elif board[x][y] == 'B':
return
elif board[x][y] == 'O':
board[x][y] = 'B'
if (x-1) >= 0:
if board[x-1][y] == 'O':
dfs(board, x-1, y)
if (x+1 <= len(boar... |
9ee0fcb390630b362f0568094c630d8fedc68900 | haoccheng/pegasus | /leetcode/plus_one.py | 498 | 3.875 | 4 | # Given a non-negative number represented as an array of digits, plus one to the number.
# The digits are stored such that most significant digit is at the head of the list.
def plus_one(digits):
carry = 1
ret = []
for i in range(len(digits)-1, -1, -1):
v = digits[i]
if carry + v == 10:
ret.insert(... |
f44e98bff08c28e45896e340b2a5444e31831ad3 | haoccheng/pegasus | /leetcode/product_array.py | 628 | 3.75 | 4 | # product of all elements in the array except itself.
# given [1,2,3,4], return [24,12,8,6].
def product(nums):
if len(nums) == 0:
return []
left = [0] * len(nums)
right = [0] * len(nums)
left[0] = nums[0]
for i in range(1, len(nums)):
left[i] = left[i-1]*nums[i]
right[-1] = nums[-1]
for i in ran... |
5606d75d47a6b64df8d8a06fcd84b416d10adb5d | haoccheng/pegasus | /leetcode/restaurant.py | 686 | 3.578125 | 4 | # Given price of each dishes.
# A target amount to spend.
# Find all combination of ordering dishes to use up the money.
def dish_base(prices, target):
if len(prices) == 0:
return []
out = []
for i in range(target / prices[0] + 1):
remain = target - prices[0] * i
if remain == 0:
out.append([(pr... |
812718ccc2b55e4b1348dafdc0b858349fa0df4e | haoccheng/pegasus | /leetcode/group_anagram.py | 398 | 3.875 | 4 | # Given an array of strings, group anagrams together
# [eat, tea, tan, ate, nat, bat]
# ate/eat/tea, nat/tan, bat.
from collections import defaultdict
def group_anagrams(strs):
hits = defaultdict(list)
for s in strs:
key = ''.join(sorted(s))
hits[key].append(s)
ret = [sorted(e) for e in hits.values()]
... |
a57cc25d97a8d86cee0a790cb26e7a8cbc81b4ab | haoccheng/pegasus | /leetcode/single_number.py | 250 | 3.90625 | 4 | # single number.
# In the array of integers, each element appears twice except one.
def single_number(numbers):
value = 0
for v in numbers:
value = value ^ v
print value
single_number([1, 2, 3, 2, 3])
single_number([1, 2, 3, 2, 3, 1, 4])
|
d32a5cd73825a901eee5fc3a4072feb6c88fbaab | haoccheng/pegasus | /leetcode/majority_element_ii.py | 757 | 3.875 | 4 | # Given an array of size n, find all elements that appear more than n/3 times.
# Linear time + O(1) space.
def majority(nums):
major1 = None
count1 = 0
major2 = None
count2 = 0
for value in nums:
if value == major1:
count1 += 1
elif value == major2:
count2 += 1
elif count1 == 0:
... |
2029924ab34ced3e322083702d175366ba02b12e | haoccheng/pegasus | /coding_interview/list_sort.py | 965 | 4.125 | 4 | # implement a function to sort a given list.
# O(n2): each iteration locate the element that should have been placed in the specific position, swap.
class Node:
def __init__(self, value, next_node=None):
self.value = value
self.next = next_node
def take(self):
buffer = [self.value]
if self.next i... |
afb0ad130f378441bf648ac1f786a2d6dc6bfb3d | haoccheng/pegasus | /coding_interview/sorted_seq_sum.py | 523 | 3.734375 | 4 | # Given an increasingly sorted array and a number s.
# Is there a pair of two numbers in the array whose sum is s.
# {1,2,4,7,11,15} target=15 -> (4,11)
def sorted_seq_sum(inputs, target):
i = 0
j = len(inputs) - 1
while (i < j):
vi = inputs[i]
vj = inputs[j]
s = vi + vj
if s == target:
ret... |
8855b1c60b16f50dcb59f598d4b623e9dd77b17b | Syzygianinfern0/Pika-Chute | /main.py | 534 | 3.921875 | 4 | def pikachucount(pi):
prv = ""
nprv = 0
pikachu = 0
pi = pi.strip().split(' ')
for a in range(len(pi)):
if pi[a] == "pi" or pi[a] == "pika" or pi[a] == "pikachu":
if nprv == 1 and prv == pi[a]:
return pi[a] + " " + pi[a] + " " + pi[a] + " found "
elif... |
1b1db81038e13ff6a2618ea270b185af5af099c8 | Andresdn14/X80---PF | /GUI.py | 359 | 3.625 | 4 | from tkinter import *
window = Tk()
window.title("First Try")
window.geometry('350x200')
lbl = Label(window, text="Hello", font=("Arial Bold", 50))
lbl.grid(column=0, row=0)
def clicked():
lbl.configure(text="Button was clicked !!")
btn = Button(window, text="Click Me",bg="black",fg="red",command=clicked)
btn.gri... |
77e04d6bd43dc22e68befafcacf831e7f5a96491 | mwd29/Python2 | /project/files2.py | 224 | 3.65625 | 4 | f=open('File2.txt', 'a') #open the file in the append mode
f.write('\nSome appended text') #write to the file
f.close()
f=open('File1.txt')
lines=f.readlines()
for line in lines:
print(line,end='')
f.close() |
775a842a778cd50b58532d55643bc1aef4da2005 | gforc/MyLeetCode | /Python/118Pascal'sTriangle.py | 663 | 3.59375 | 4 |
class Solution:
def generate(self,numRows):
result = [[1]]
if numRows == 0:
return 0
elif numRows == 1:
return result
for i in range (1,numRows):
middle = []
for j in range(i+1):
... |
3ed97cfe06ce29ae45fcd7c304d9f6696e7471f3 | gforc/MyLeetCode | /Python/169MajoritElement.py | 506 | 3.703125 | 4 | '''
Created on 2017年9月14日
@author: evan
this script is done
'''
import collections
class solution():
def majorityElement(self,nums):
dict = collections.defaultdict(int)
for i in range(len(nums)):
dict[nums[i]] += 1
for item in dict:
if dic... |
5dd5492a350c80d1f6653c7176f6e615aaf6c17b | gforc/MyLeetCode | /Python/167TwoSum_II_InputArrayIsSorted.py | 540 | 3.71875 | 4 | '''
Created on Feb 23, 2019
@author: evan
'''
class solution():
def twoSum(self,numbers,target):
start = 0
end = len(numbers)-1
while start != end:
sum = numbers[start] + numbers[end]
if sum > target:
end-=1
elif sum < target:
... |
963162725075e8a2cf90d90f906a8afc3ac94a54 | SAMIFIX/Training_Data_Structure | /mutability.py | 1,292 | 4.8125 | 5 | """
Mutable :
هي امكانيه تغير القيمه للمتغير
Immutable:
غير ممكن تغير القيمه للمتغير
Mutable Object:
list, dict, set
Immutable Object:
Integer, float, string, tuple, bool , frozenset
"""
# Example in Mutable Objects:
# list
sami = []
sami.append(1)
sami.append("Hello")
sami.append("For")
sami.append(True)
prin... |
494febbef4291b6f02fd34ab3da3c2c13eb617d0 | akshatasawhney/PreCourse_1 | /Exercise_4.py | 2,353 | 3.8125 | 4 | """
// Time Complexity : O(n)
// Space Complexity : O(n)
// Did this code successfully run on Leetcode : Yes, checked for inorder function
// Any problem you faced while coding this : slight difficulty while building up logic for traversals
"""
# Python program to insert element in binary tree
from collections im... |
9a60314b631748627743dd456eadb7fc54f51226 | m-bansal/build_up | /gross.py | 219 | 3.890625 | 4 | h=float(input("Enter hours"))
r=float(input("Enter rate per hour"))
n=input("Enter name")
pay=0
if h<=37.5 :
pay=r*h
elif h>37.5 :
pay=(r*37.5) + ((h-37.5)*1.5*r)
print(n,"your gross pay is",pay,"CAD")
|
f23f1cfd3da00f419783d71900f3c7b13407265c | m-bansal/build_up | /Company Logo.py | 159 | 3.59375 | 4 | from collections import Counter
if __name__ == '__main__':
s = input()
c = Counter(sorted(s)).most_common(3)
for i in c:
print(*i)
|
c165079e81b5aff822766262f7c4271ba5d8ec88 | m-bansal/build_up | /graphic figures.py | 850 | 4.125 | 4 | import turtle
t = turtle.Turtle()
t.pensize(4)#for thickness
t.hideturtle()
#line
line=int(input("Enter the number of pixels by which a turtle should be moved to draw a line: "))
t.forward(line)#distance moved by turtle
t.penup()#move the turtle head
t.goto(0, -200)#no outline drawn by turtle
t.pendown()... |
3a32b6b0a105d6bf5c3fbe77176674863a8ea8f0 | m-bansal/build_up | /area of circle.py | 245 | 3.65625 | 4 | class a:
def __init__(self,radius):
self.radius=radius
self.area=3.14*self.radius*self.radius
def display(self):
print('radius = %f'%self.radius)
print('area = %f'%self.area)
ob=a(2)
ob.display()
|
3932a9c0c5fd407632b12188ebbe2d20b087f783 | FranciscaAlliende/HW5-ShortestPath | /ShortestPath.py | 933 | 3.8125 | 4 |
def BFS_prev(graph, S):
prev = {}
# visited nodes
visited = []
# Query
Q = []
# First we append the node S on the query
Q.append(S)
# While we have nodes on query:
while Q:
current = Q.pop()
for child in graph[current]:
if child not in visited: # havent b... |
a14f5a6a45ba8380e498cc4a97737ed531bc4221 | iasharief/PythonLearning | /calculatorv1.py | 1,072 | 4 | 4 | operation = str(input("Type 'a' for addition, 's' for subtraction, 'm' for multiplication, 'd' for division, 'sq' for square root, or 'e' for exponents: "))
while True:
try:
# Note: Python 2.x users should use raw_input, the equivalent of 3.x's input
operation = str(input("Type 'a' for addition, 's'... |
9919dc297f0adbd5a7bb4b431595aad1d9b361e1 | djcjeevana/projectibay | /IBay/location.py | 1,132 | 3.578125 | 4 | import json
def readJson(filename):
with open(filename, 'r') as fp:
return json.load(fp)
def get_country():
""" GET COUNTRY SELECTION """
filepath = './static/data/countries_states_cities.json'
all_data = readJson(filepath)
all_countries = [('-----', '---Select a Coun... |
f6df8e2f28aa3f7ff5cb30c7918e63c51be35b0c | Dismemb3r/OOP-hw | /main.py | 6,061 | 3.671875 | 4 | class Student:
students_list = []
def __init__(self, name, surname, gender):
self.name = name
self.surname = surname
self.gender = gender
self.finished_courses = []
self.courses_in_progress = []
self.grades = {}
self.students_list.append(self)
def me... |
5ca3c133c63549ef5c4c2dc75e83b2e2dd06e454 | xartiou/algorithms-and-structures-python | /task_8_l2.py | 1,330 | 4.28125 | 4 | # 8. Посчитать, сколько раз встречается определенная цифра в введенной последовательности чисел.
# Количество вводимых чисел и цифра, которую необходимо посчитать, задаются вводом с клавиатуры.
# Запросить количество вводимых чисел (n) и цифру для подсчета (d).
n = int(input("Введите сколько будет чисел?: "))
d = int(... |
3f6c4d1f0b362444e84e36ca4d0ff3943bfc6bed | xartiou/algorithms-and-structures-python | /task_1.py | 822 | 4.34375 | 4 | # 1. Найти сумму и произведение цифр трехзначного числа, которое вводит пользователь.
# - просим пользователя ввести целое трехзначное число
three_digit = int(input('Введите целое трехзначное число: '))
# - выделяем цифры из числа
one_d = three_digit // 100
two_d = (three_digit % 100) // 10
three_d = three_digit % 10... |
b43f93147f9100bfec66a5178815b1dfff01719b | xartiou/algorithms-and-structures-python | /task_2_l3.py | 1,464 | 3.625 | 4 | # 2. Во втором массиве сохранить индексы четных элементов первого массива.
# Например, если дан массив со значениями 8, 3, 15, 6, 4, 2,
# то во второй массив надо заполнить значениями 1, 4, 5, 6 (или 0, 3, 4, 5 - если индексация начинается с нуля),
# т.к. именно в этих позициях первого массива стоят четные числа.
# Со... |
1763f1b2de90d1a5da476b9f5ae0a54252d5c384 | dheerajgss/DSWithPython | /Stack/binTodec.py | 587 | 3.828125 | 4 | class Stack:
def __init__(self):
self.things=[]
def push(self,item):
self.things.append(item)
def popp(self):
return self.things.pop()
def is_empty(self):
if(self.things == []):
return True
else:
return False
def convert(num):... |
9260fe8f07080e578d6b56628faa9a5c7ba23ac6 | Chandan-aV/python-1BM17CS023 | /employee.py | 2,292 | 3.8125 | 4 | import sqlite3
conn = sqlite3.connect('test.db')
#print ("Opened database successfully")
try:
conn.execute('''CREATE TABLE Employee
(ID INT PRIMARY KEY NOT NULL,
NAME TEXT NOT NULL,
AGE INT NOT NULL,
ADDRESS CHAR(50),
... |
9923aa2c6afffcfcdad71ca0c5a2b4f6b4a3d4cd | ismaelconejeros/100_days_of_python | /Day 23/23_crossing_the_road/crossing_classes.py | 2,982 | 4.03125 | 4 | from turtle import Turtle
import random
WIDTH = 900
HEIGHT = 450
CAR_COLORS = ['black', 'red', 'orange', 'blue', 'purple', 'white']
class Chicken(Turtle):
def __init__(self):
super().__init__()
self.color('green')
self.shape('turtle')
self.setheading(90)
self.penup()
... |
dd4cee21d30f2655271d764cfea4a47dc7b53054 | ismaelconejeros/100_days_of_python | /Day 26/26_NATO_Alphabet/nato_alphabet.py | 367 | 3.90625 | 4 | import pandas as pd
data = pd.read_csv('100_days_of_python\Day 26\\26_NATO_Alphabet\\nato_phonetic_alphabet.csv')
df = pd.DataFrame(data)
df2 = df.to_dict()
nato_dict = {df2['letter'][i]:df2['code'][i] for i in range(len(df2['letter']))}
while True:
name = input("Enter a word: ").upper()
nato_name = [nato_di... |
9cb6bc62c648f66140ca8cc97a7eb264ce21a88c | ismaelconejeros/100_days_of_python | /Day 04/exercise_01.py | 521 | 4.4375 | 4 | #You are going to write a virtual coin toss program. It will randomly tell the user "Heads" or "Tails".
#Important, the first letter should be capitalised and spelt exactly like in the example e.g. Heads, not heads.
#There are many ways of doing this. But to practice what we learnt in the last lesson, you should gene... |
1be3880c9dbce5695a23b3aa8fb6cd4fa043c8bc | ismaelconejeros/100_days_of_python | /Day 03/exercise_05.py | 2,192 | 4.21875 | 4 | #write a program that tests the compatibility between two people.
#To work out the love score between two people:
#Take both people's names and check for the number of times the letters in the word TRUE occurs.
# Then check for the number of times the letters in the word LOVE occurs.
# Then combine these numbers to... |
ca0ed659cc70708dd2e607cebbb40d89c68b0ad7 | ismaelconejeros/100_days_of_python | /Day 84/84_watermark_gui/main.py | 1,970 | 3.5 | 4 | from tkinter import *
from tkinter import filedialog
from PIL import ImageTk, Image, ImageDraw, ImageFont
def add_img():
global img, tk_img
file_img = filedialog.askopenfilename(title="Image to add watermark")
img = Image.open(file_img)
if img.mode in ("RGBA", "P"):
img = img.convert("RGB")
... |
abc95dacfffd2a010308dd94dd1436f5b84afac3 | ismaelconejeros/100_days_of_python | /Day 27/27_milt_to_km_converter/mile_to_km_converter.py | 1,235 | 3.734375 | 4 | import tkinter as tk
window = tk.Tk()
window.title("Mile to KM converter")
window.minsize(300,300)
def mile_to_km():
miles = float(input_box.get())
kms = miles * 1.6
label_input.config(text=f"{miles} MILES")
label_result.config(text=f"{kms} KMS")
def km_to_mile():
kms = float(input_box.get())
... |
9778a6819ae39c5276f44af800fd31f680de04a8 | ismaelconejeros/100_days_of_python | /Day 26/list_comprenhension.py | 399 | 4.09375 | 4 | #List Comprehension
numbers = [1,2,3]
new_list = [n*2 for n in numbers]
print(new_list)
name = "Ismael"
new_list = [letter for letter in name]
print(new_list)
new_list = [i*2 for i in range(1,5)]
print(new_list)
list1 = [1,2,3,4,5,6,7,8,9,10]
new_list = [i for i in list1 if i%2==0]
print(new_list)
names = ["Alex", ... |
e4a073969fa4db71d84abcc2a138868f1dfad1e6 | ismaelconejeros/100_days_of_python | /Day 46/46_spotify_playlist/spotify_billboard.py | 1,553 | 3.515625 | 4 | from bs4 import BeautifulSoup
import requests
import spotipy
from spotipy.oauth2 import SpotifyOAuth
date = input("Week of the Top 100's ? (YYYY-MM-DD)\n")
my_request = requests.get(url=f"https://www.billboard.com/charts/hot-100/{date}")
data = my_request.text
soup = BeautifulSoup(data, "html.parser")
artists = soup.... |
e74cd05e637a8d8f584ba164d2346a36bb14018b | ismaelconejeros/100_days_of_python | /Day 04/04_rock_paper_scissors/rock_paper_scissors.py | 1,018 | 3.921875 | 4 | import random
import time
rock = '''
_______
---' ____)
(_____)
(_____)
(____)
---.__(___)
'''
paper = '''
_______
---' ____)____
______)
_______)
_______)
---.__________)
'''
scissors = '''
_______
---' ____)____
______)
__________)
... |
6afa7436044aaa0e1463799d2d7b7ccfb1c1db35 | Eder-Berno/Practica9_EDA1 | /area_circulo.py | 130 | 3.796875 | 4 | #Acosta Rodríguez Eder Alberto
#Área del círculo
radio = 3
pi = 3.1416
area = pi* (radio ** 2)
print ("El área del Círculo es: " +str(area))
|
ddf509e78ba215cf43719d00ba8233a615210568 | dobleuber/cursos-platzi-ia | /CursoProgramacionEstocastica/coordenada.py | 360 | 3.796875 | 4 | class Coordenada:
def __init__(self, x, y):
self.x = x
self.y = y
def move(self, delta_x, delta_y):
return Coordenada(self.x + delta_x, self.y + delta_y)
def distance(self, other_coord):
delta_x = self.x - other_coord.x
delta_y = self.y - other_coord.y
ret... |
a5b39aec77a04693499049e27f6ee26ab3ff66e6 | Malcolm-Tompkins/ICS3U-Unit4-01-Python-While_Loops | /While_Loops.py | 695 | 4.125 | 4 | #!/usr/bin/env python3
# Created by Malcolm Tompkins
# Created on May 12, 2021
# Determines sum of all numbers leading up to a number
def main():
# Input
user_input = (input("Enter your number: "))
try:
user_number = int(user_input)
loop_counter = 0
while (loop_counter < user_nu... |
e37cb75f5da75f5c0e24a79fde1551f7debf8799 | exeptor/TenApps | /App_2_Guess_The_Number/program_app_2.py | 873 | 4.25 | 4 | import random
print('-------------------------------------')
print(' GUESS THE NUMBER')
print('-------------------------------------')
print()
random_number = random.randint(0, 100)
your_name = input('What is your name? ')
guess = -1
first_guess = '' # used this way in its first appearance only; on the seco... |
cdc175250203b44760a0c6b808ed6162243290f1 | burniechen/ML | /HW/HW01/HW01_py/matrix_func.py | 4,442 | 3.734375 | 4 | # 矩陣相加
def AddMatrix(a, b):
tmp = []
x = len(a)
y = len(a[0])
for i in range(0, x):
tmp.append([])
for j in range(0, y):
val = a[i][j] + b[i][j]
tmp[i].append(val)
return tmp
# 矩陣相減
def SubtractMatrix(a, b):
tmp = []
x = len(a)
y = len(a[0])
... |
59112fbf44fd555041852e0274f232e041ca19ca | carsin/python-projects | /tictactoe.py | 3,737 | 4 | 4 | gameMap = None
currTurn = None
changeTurn = None
turnNum = None
playing = None
def main():
global gameMap
global currTurn
global changeTurn
global turnNum
global playing
gameMap = [["_" for i in range(3)] for j in range(3)]
currTurn = "O"
changeTurn = True
turnNum = 0
# main gam... |
a652f4d6fe21470a256e46939984928ea2906b29 | carsin/python-projects | /school/unit7/assignment7.py | 806 | 3.890625 | 4 | '''
In this assignment, you will write a program that will process data in the jokes.txt and answers.txt files. Set up your program so that it will do the following tasks:
1) Display the number of jokes in jokes.txt
2) Ask the user for the number of a joke
3) Display the joke
3) Display the requested joke
4) Displa... |
9ac51bc45b2f5dfb09bb397ce0aa9c1e5ae06034 | engineerpassion/Data-Structures-and-Algorithms | /DataStructures/LinkedList.py | 2,417 | 4.1875 | 4 | class LinkedListElement():
def __init__(self, value):
self.value = value
self.next = None
class LinkedList():
def __init__(self):
self.head = None
def is_empty(self):
empty = False
if self.head is None:
empty = True
return empty
def ... |
9a254744b34322e9a62aa407bbf62105397103e3 | engineerpassion/Data-Structures-and-Algorithms | /Algorithms/KnuthShuffle.py | 573 | 3.890625 | 4 | import random
def swap(a, i, j):
c = a[i]
a[i] = a[j]
a[j] = c
return a
def knuth_shuffle(a):
if a is not None and len(a) > 1:
n = len(a)
for i in range(1, n):
index_to_swap = random.randint(0, i)
a = swap(a, i, index_to_swap)
return a
def main():
a... |
ad665e3a3bc934aff4d52b5afe591f313bb4fe03 | csaezcalvo/advent-of-code2018 | /day 5-1.py | 1,271 | 3.71875 | 4 | def inv(word):
new_word=''
for letter in word:
if letter.lower() == letter:
new_word += letter.upper()
else:
new_word += letter.lower()
return new_word
def concat(word1,word2):
redword1 = word1
redword2 = word2
while (len(redword1)>0 and len(redword2)>0 a... |
3709b9094572051b7d96aab3a1ebb991ee6cd3ff | kerenskybr/python_oop_book | /case_study_supplies/supplies.py | 886 | 4.03125 | 4 | # Notice the use of a build in method "list"
class ContactList(list):
def search(self, name):
"""Return all contacts that contain the
search values in their name"""
matching_contacts = []
for contact in self:
if name in contact.name:
matching_contacts.append(contact)
return matching_contacts
class ... |
750292721fe25af74fcdc5042d74cd06da938360 | ayangtj/Air-Quality-Monitor | /package/simulator.py | 3,535 | 3.5 | 4 | '''
simulates data generation in the format of a wave
https://stackoverflow.com/questions/14058340/adding-noise-to-a-signal-in-python
'''
import seaborn as sns; sns.set()
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import random as rd
import datetime
import os
def generate_simulated_data(sc... |
adb4c805fc542e37dfb1680f8aff2cb69bf40427 | edisongaibor/fp-utpl-18-evaluaciones | /eval-parcial-primer-bimestre/valor.py | 129 | 3.671875 | 4 | print("Ingrese un valor en segundos")
segundos=input()
minutos=segundos/60
print("El valor de segundos a minutos es de:"+minutos) |
dd223a6e02364d4f8c9da29e2e10f94703aaa6a6 | kristiansantos11/datastructure-and-algorithms | /algorithms part 1/linked_lists/multidimensional_array_find.py | 208 | 3.703125 | 4 | colours = [["red", "blue", "orange"],["green", "black"],["gray"]]
c = "black"
x = next(((i, colour.index(c))
for i, colour in enumerate(colours)
if c in colour),
None)
print(x[0])
|
f5c55cbb548958ea0bdac0510c76303374192d84 | kristiansantos11/datastructure-and-algorithms | /algorithms part 1/stacks/LinkedList_StackOfStrings.py | 1,516 | 3.859375 | 4 | ''' This code is exactly the same with the princeton algorithm part 1 class'''
''' Please refer to the Stacks lesson specifically '''
class LinkedList_StackOfStrings:
def __init__(self, nodes=None):
self.head = None
if nodes is not None:
node = self.Node(nodes.pop(0))
... |
c29d736a57f1d3868b7ab2d6dc3d4b5c661df7d9 | ashnel/codingdojoassignments | /Python/tuples.py | 375 | 3.546875 | 4 | my_dict = {
"Speros": "(555) 555-5555",
"Michael": "(999) 999-9999",
"Jay": "(777) 777-7777"
}
'''def unzip(dictionary):
final = []
temp = []
for i in dictionary:
newKey = i
newVal = dictionary[i]
temp.append(newKey)
temp.append(newVal)
final.append(temp)
temp = []
print final'''
def unzip(... |
7dad6545e8890e27664d4bdf0dfb94fec17e198e | Eddie02582/CodeWars | /Kata 6/Consecutive strings/Consecutive strings.py | 506 | 3.515625 | 4 |
def longest_consec(strarr, k):
if k > 0 and len(strarr) >= k:
return ""
result = ""
for index in range(len(strarr) - k + 1):
s = ''.join(strarr[index:index+k])
if len(s) > len(result):
result = s
return result
def longest_consec(strarr, ... |
4c7a7827e532cb7ad69c1e98eec91445c68eb74e | Eddie02582/CodeWars | /Kata 4/Validate Sudoku with size `NxN`/Validate Sudoku with size `NxN`.py | 1,382 | 3.78125 | 4 | class Sudoku(object):
def __init__(self, data):
self.data = data
self.n = len(data)
self.r = int(self.n**0.5)
def isSafe(self,x,y):
print (self.data[x][y])
if self.data[x][y] not in range(1,self.n + 1) or type(self.data[x][y]) == bool or type(self.data[x][y]) ==... |
9cadd58882689b841a747465ae242a11e5c4861a | Eddie02582/CodeWars | /Kata 6/Title Case/Title Case.py | 507 | 3.734375 | 4 | def title_case(title, minor_words=""):
return " ".join( s.title() if s not in minor_words.lower().split(' ') or i==0 else s for i,s in enumerate(title.lower().split(' ') ))
def title_case(title, minor_words=''):
words=[ word.lower() for word in minor_words.split(' ')]
titles=title.split(' ')
for i... |
36f602f4ec875536e28771747191b0ecd875ffef | Eddie02582/CodeWars | /Kata 4/All Balanced Parentheses/新文字文件.py | 453 | 3.59375 | 4 | def solution(string,markers):
import re
if not markers:
return string
res = string.split('\n')
if not markers:
return string
express = '[{0}].*'.format(key)
for i in range(len(res)):
res[i] = re.sub(express,"",res[i])
res[i]... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.