blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
8a043957d6ac5de1c8dd0a89c93ff4b0f393ea31 | weizhixiaoyi/leetcode | /nowcoder/company/0904-bilibili/02.py | 440 | 3.5625 | 4 | # -*- coding:utf-8 -*-
def solve(nums):
if not nums: return 0
nums_len = len(nums)
max_value = nums[0]
cur_sum = nums[0]
for i in range(1, nums_len):
if cur_sum < 0:
cur_sum = 0
cur_sum += nums[i]
max_value = max(max_value, cur_sum)
return max_value
if __n... |
f2f179fb4a25b011f6ac736d5e305c629ca4ebc3 | weizhixiaoyi/leetcode | /list/23.merge-k-sorted-lists.py | 2,229 | 3.84375 | 4 | # -*- coding:utf-8 -*-
from typing import List
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
def printList(l):
while l:
print(l.val, end=' ')
l = l.next
print()
class Solution:
# 方法一: 依次合并两个链表
"""
def mergeKLists(self, lists: List[List... |
ee627977bf3b8fc5da0b8fdf4b3cd3046f7201c7 | weizhixiaoyi/leetcode | /array/26.删除排序数组中的重复项.py | 574 | 3.671875 | 4 | # -*- coding:utf-8 -*-
from typing import List
class Solution:
def removeDuplicates(self, nums: List[int]) -> int:
if not nums: return 0
nums_len = len(nums)
l, r = 0, 0
while r < nums_len:
while r < nums_len and nums[r] == nums[l]:
r += 1
... |
9532187ad94d636613879f387029c306c42bb93e | weizhixiaoyi/leetcode | /backtrack/77.组合.py | 640 | 3.625 | 4 | # -*- coding:utf-8 -*-
from typing import List
class Solution:
def combine(self, n: int, k: int) -> List[List[int]]:
if k > n: return []
nums = [i + 1 for i in range(n)]
from copy import deepcopy
ans = []
def dfs(idx, path):
if len(path) == k:
... |
42228234d2d0b4fc58ee77588ba7cdf047a15a88 | weizhixiaoyi/leetcode | /dp/887.鸡蛋掉落.py | 626 | 3.5625 | 4 | # -*- coding:utf-8 -*-
class Solution:
def superEggDrop(self, K: int, N: int) -> int:
self.memo = {}
def dfs(K, N):
if N == 0: return 0
if K == 1: return N
if (K, N) in self.memo:
return self.memo[(K, N)]
res = float('inf')
... |
5657e86dad2daf336327b26ad8f2e81b08a13dec | weizhixiaoyi/leetcode | /dfs/97.交错字符串.py | 1,478 | 3.5 | 4 | # -*- coding:utf-8 -*-
class Solution:
"""
def isInterleave(self, s1: str, s2: str, s3: str) -> bool:
self.ans = False
s1_len, s2_len, s3_len = len(s1), len(s2), len(s3)
if s1_len + s2_len != s3_len: return False
# 1. s1[i] == s3[k] or s2[j] == s3[k]时候再进行递归
# 2. 带有记忆的递归... |
b7038c05f1ae7cff517e4febf394ab17701d884d | weizhixiaoyi/leetcode | /lcof/1/55.2平衡二叉树.py | 864 | 3.890625 | 4 | # -*- coding:utf-8 -*-
# Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def isBalanced(self, root: TreeNode) -> bool:
def helper(root):
if root is None: return 0
... |
21aed87ee2b3b1fcb51a5a2036b152190f6424f0 | weizhixiaoyi/leetcode | /nowcoder/company/0918-唯品会/01.py | 534 | 3.546875 | 4 | # -*- coding:utf-8 -*-
def solve(nums):
nums_len = len(nums)
# from collections import Counter
# nums_count = Counter(nums)
nums_count = {}
for num in nums:
if num in nums_count:
nums_count[num] += 1
else:
nums_count[num] = 1
for key, value in nums_count... |
b1fa1c51a2d82210ea0f33a310b82080fe4062ae | weizhixiaoyi/leetcode | /lcof/1/22.链表中倒数第k个节点.py | 972 | 3.875 | 4 | # -*- coding:utf-8 -*-
# Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
def printList(head):
while head:
print(head.val, end=" ")
head = head.next
print()
class Solution:
def getKthFromEnd(self, head: ListNode,... |
9bf834e0ea56bcb4205eee1c4c3e1f7369772cc4 | weizhixiaoyi/leetcode | /stack/84.largest-rectangle-in-histogram.py | 1,020 | 3.671875 | 4 | # -*- coding:utf-8 -*-
from typing import List
"""
基本思路是针对每个高度,向周围进行寻找,找到小于当前高度的值,然后便能够得到当前矩阵面积,复杂度O(n**2)。
通过单调栈方法,维持整个数组的单调递增栈。
"""
class Solution:
def largestRectangleArea(self, heights: List[int]) -> int:
hlen = len(heights)
if hlen == 0: return 0
heights.insert(0, 0)
heights.... |
ff5d759e49acedac2984359b3bc108e910e5dec5 | weizhixiaoyi/leetcode | /binarysearch/367.valid-perfect-square.py | 527 | 3.59375 | 4 | # -*- coding:utf-8 -*-
class Solution:
def isPerfectSquare(self, num: int) -> bool:
left, right = 0, 50000
while left <= right:
mid = left + (right - left) // 2
cur_num = mid * mid
if cur_num == num:
return True
if cur_num < num:
... |
57819f3c57924b529a3bdd645ce7aa91809d1cf6 | weizhixiaoyi/leetcode | /lcof/1/55.1二叉树的深度.py | 610 | 3.875 | 4 | # -*- coding:utf-8 -*-
# Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def maxDepth(self, root: TreeNode) -> int:
if root is None: return 0
left = self.maxDepth(root.left)
... |
aede7b8456ff4dabe2999a4e4d69c453abf6bd24 | weizhixiaoyi/leetcode | /lcof/1/43.1~n整数中1出现的次数.py | 690 | 3.671875 | 4 | # -*- coding:utf-8 -*-
class Solution:
def countDigitOne(self, n: int) -> int:
digit, res = 1, 0
# 2304; high = 23, cur = 0, low = 4
high, cur, low = n // 10, n % 10, 0
while high != 0 or cur != 0:
print(cur)
if cur == 0:
res += high * digit
... |
f30f0d87ccf0752ebf1bd66089dc6ee223704bb0 | weizhixiaoyi/leetcode | /list/203.remove-linked-list-elements.py | 1,490 | 3.796875 | 4 | # -*- coding:utf-8 -*-
# Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
def printList(head):
while head:
print(head.val, end=' ')
head = head.next
print()
class Solution:
# 头部节点不好处理, 可增加在头部增加哨兵节点, 将头部节点转变为中间节点
... |
f685dbe87e9dab673739eb1d633d9b148d424953 | weizhixiaoyi/leetcode | /lcof/1/18.删除链表的节点.py | 1,021 | 3.84375 | 4 | # -*- coding:utf-8 -*-
# Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
def printList(head):
while head:
print(head.val, end=' ')
head = head.next
print()
class Solution:
def deleteNode(self, head: ListNode, va... |
daa40b3a3ff415032ab299429a96585d58171218 | weizhixiaoyi/leetcode | /lcof/1/63.股票的最大利润.py | 634 | 3.5 | 4 | # -*- coding:utf-8 -*-
from typing import List
class Solution:
def maxProfit(self, prices: List[int]) -> int:
if not prices: return 0
prices_len = len(prices)
min_value = prices[0]
max_ans = 0
for i in range(1, prices_len):
cur_ans = prices[i] - min_value
... |
89bf44958f6ab3c539ba3938f3a0c885a44daa7d | weizhixiaoyi/leetcode | /tree/113.path-sum-ii.py | 1,388 | 3.609375 | 4 | # -*- coding:utf-8 -*-
from typing import List
# Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def pathSum(self, root: TreeNode, sum: int) -> List[List[int]]:
import copy
self... |
81c8464ccd4372246b8271531b14d9cc7aad74b2 | weizhixiaoyi/leetcode | /nowcoder/company/0816-奇安信/2.py | 1,040 | 3.53125 | 4 | # -*- coding:utf-8 -*-
def solve(s):
s = s.strip().split()
if not s: return ''
flag = False
for c in s:
if c != "undo" and c != "redo":
flag = True
if flag is False: return ''
s_len = len(s)
stack1 = []
stack2 = []
no = 0
for k in range(s_len):
if s[... |
76ac9af8a4654a40d51c2c184a89f324cdae02b6 | weizhixiaoyi/leetcode | /lcof/1/41.数据流中的中位数.py | 2,183 | 3.703125 | 4 | # -*- coding:utf-8 -*-
"""
class MedianFinder:
def __init__(self):
self.nums = []
self.nums_len = 0
def addNum(self, num: int) -> None:
# 顺序插入保证插入复杂度为O(n)
if not self.nums:
self.nums.append(num)
self.nums_len += 1
return
flag = False... |
b3853ba5b60e43c2b08c15b0629a8562a74164d1 | weizhixiaoyi/leetcode | /binarysearch/378.有序矩阵中第K小的元素.py | 1,478 | 3.5 | 4 | # -*- coding:utf-8 -*-
from typing import List
class Solution:
"""
def kthSmallest(self, matrix: List[List[int]], k: int) -> int:
if not matrix: return 0
m, n = len(matrix), len(matrix[0])
import heapq
val = []
for i in range(m):
for j in range(n):
... |
9bb8d385bb21fb101cff3d527615a5eead61f280 | weizhixiaoyi/leetcode | /math/172.factorial-trailing-zeroes.py | 372 | 3.84375 | 4 | # -*- coding:utf-8 -*-
import math
class Solution:
# ans = n / 5 + n / 25 + n / 125 + ...
def trailingZeroes(self, n: int) -> int:
ans = 0
while n > 0:
ans += n // 5
n = n // 5
return ans
if __name__ == '__main__':
n = 25
ans = Solution().trailingZero... |
e8f770d44336f0453cbbe9ba8a1d6322fe3eafd8 | weizhixiaoyi/leetcode | /nowcoder/company/0826-广联达/03.py | 501 | 3.546875 | 4 | # -*- coding:utf-8 -*-
def solve(nums_len, nums):
nums = [val - 1 for val in nums]
nums_sort = sorted(nums)
# print(nums)
# print(nums_sort)
ans = 0
for i in range(nums_len):
while i != nums[i]:
ans += 1
tmp = nums[i]
nums[i] = nums[tmp]
... |
7cb0df1fa7b772f1de99a36eaa46c7b057180f30 | GeekyAmit5/Othello | /othello.py | 2,712 | 3.59375 | 4 |
import numpy as np
import random as rd
n = 4
grid = [[" " for x in range(n)] for y in range(n)]
grid[(n - 2) // 2][(n - 2) // 2] = grid[(n - 2) // 2 + 1][(n - 2) // 2 + 1] = "X"
grid[(n - 2) // 2][(n - 2) // 2+1] = grid[(n - 2) // 2+1][(n - 2) // 2] = "O"
def printGrid(grid):
print()
print("----... |
f75a4ce7dcc670f57ca6893c8ec9c1102fe91e9b | rdashrdash/PythonCoding | /CodesOnline/oopsPy.py | 662 | 3.78125 | 4 | class Student:
def __init__(self):
self.name = "Vir"
self.grades = (45, 85, 96, 72)
def average(self):
return sum(self.grades)/ len(self.grades)
student = Student()
# print(student.name)
# print(Student.grades)
# print(Student.average(student))
print(student.average())
class Studs:
... |
7bd250c4bb5f964f236f649f9e9ef8b047f9d387 | parthadroja5795/network_automation | /netman_lab8/netman_lab8_sshInfo.py | 805 | 3.515625 | 4 | #script to generate JSON file containing all SSH login information
#!/usr/bin/env python
import json
if __name__ == "__main__":
ssh_info={}
R1={'device_type':'cisco_ios',
'username':'netman',
'password':'netman',
'ip':'198.51.100.10'
}
R2={'device_type':'cis... |
ca93425bbfb81bbb9aac71921e8cf2bae0839655 | carlypecora/import-csv-file | /import.py | 2,406 | 3.53125 | 4 | import csv
import argparse
NEW_CSV_LIST = []
def reformat_csv(csv_filename):
with open(csv_filename, "r") as f:
readable_csv = csv.reader(f)
header = next(readable_csv)
beginning_range_index = 9
ending_range_index = 24
i = 0
for row in readable_csv:
j = ... |
94775707414828a68e4c39d91a443e0438d82c78 | conniechu929/Algos | /MinHeap.py | 1,445 | 3.96875 | 4 | class MinHeap:
def __init__(self, items=[]):
super().__init__()
self.heap = [0]
for i in items:
self.heap.append(i)
self.__floatUp()
def push(self, data):
self.heap.append(data)
self.__floatUp(len(self.heap) - 1)
def peek(self):
if se... |
f2c068d02356ceb16f4d397d95bf4383e0b09182 | conniechu929/Algos | /word_in_list.py | 165 | 3.890625 | 4 | def word_search(string, word_list):
string_list = list(list(letter) for letter in string)
if sorted(string_list) == sorted(word_list):
return string
|
d4681cf01a7f9523ce8d0dd8f5021527a5603660 | conniechu929/Algos | /SingleNum.py | 537 | 3.828125 | 4 | # Given an array of integers, every element appears twice except for one. Find that single one.
#
# Note: Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?
#
# Example :
#
# Input : [1 2 2 3 1]
# Output : 3
class Solution:
# @param A : tuple of integers
... |
58877c19ccd2bd9132be7e912a2b24b9a542c852 | conniechu929/Algos | /lengthOfLongestSubstr.py | 994 | 3.875 | 4 | # Given a string, find the length of the longest substring without repeating characters.
#
# Examples:
#
# Given "abcabcbb", the answer is "abc", which the length is 3.
#
# Given "bbbbb", the answer is "b", with the length of 1.
#
# Given "pwwkew", the answer is "wke", with the length of 3. Note that the answer must be... |
a19c5ea343fcd5e7a98dde49a6a2c8f67eb284ba | conniechu929/Algos | /GraphTraversal_DFS.py | 1,642 | 3.859375 | 4 | class Vertex(object):
def __init__(self, n):
self.name = n
self.neighbors = list()
self.discovery = 0
self.finish = 0
self.color = 'black'
def add_neighbor(self, v):
nset = set(self.neighbors)
if v not in nset:
self.neighbors.append(v)
... |
66c1aac29c02db45c21ca1880a2bcf878dd47068 | conniechu929/Algos | /SwapNodeLevel.py | 1,869 | 3.796875 | 4 |
class Node(object):
def __init__(self, info):
self.info = info
self.left = None
self.right = None
class BinarySearchTree:
def __init__(self):
self.root = Node(1)
self.level = [self.root]
self.current = self.root
self.current_level = 0
... |
982459071bff3965dbfdda0ed94c99c40edb0975 | conniechu929/Algos | /LetterComboOfPhoneNums.py | 1,241 | 4.09375 | 4 | # Given a digit string, return all possible letter combinations that the number could represent.
#
# A mapping of digit to letters (just like on the telephone buttons) is given below.
#
# Input:Digit string "23"
# Output: ["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"].
class Solution(object):
def letterCom... |
aecad79e56e93f9867d1be25d5b9cb5fd972242f | conniechu929/Algos | /arrange.py | 490 | 3.65625 | 4 | # Input: {WWWB} , K = 2
# Output: 0
#
# Explanation:
# We have 3 choices {W, WWB}, {WW, WB}, {WWW, B}
# for first choice we will get 1*0 + 2*1 = 2.
# for second choice we will get 2*0 + 1*1 = 1.
# for third choice we will get 3*0 + 0*1 = 0.
#
# Of the 3 choices, the third choice is the best option.
def arrange(self, A... |
0f881ff3b77a41e580257e4acbc4e77a9150ae40 | poornapragnarao/hackerrank | /mergethetools.py | 512 | 3.640625 | 4 | def merge_the_tools(string, k):
# your code goes here
n = len(string)
number_of_splits = int(n/k)
for split_num in range(number_of_splits):
split = string[split_num*k:split_num*k+(k)]
unique_string = ''
for char in split:
if char in unique_string:
do_n... |
00e8e9ffd4ba26bdebef560e3a3db4a622f63bdd | fabiopavesi/carrellata_informatica | /slide01.py | 233 | 3.78125 | 4 | from math import sqrt
A = {'x': 0, 'y': 0}
B = {'x': 3, 'y': 8}
C = {'x': 12, 'y': -5}
AB = sqrt((A['x'] - B['x']) ** 2 + (A['y'] - B['y']) ** 2)
BC = sqrt((C['x'] - B['x']) ** 2 + (C['y'] - B['y']) ** 2)
ABC = AB + BC
print(ABC)
|
385759b11b8575b4ab510aa2cd59dd52f3c4eb56 | nauticafs31/programming_with_python_capstones | /TomeRater.py | 6,564 | 3.828125 | 4 | class User(object):
def __init__(self, name, email):
self.name = name
self.email = email
self.books = { }
def get_email(self):
return self.email
def change_email(self, address):
self.email = address
return self.email+" has been changed to: "+address
def... |
f18052c0a7149abff8277125c165dca9d5abde02 | sabreensalama/Crowd-Funding-console-app | /registeration.py | 2,570 | 3.71875 | 4 | import re
import json
user_id = 0
def register_inputs():
global user_id
user_id = user_id + 1
first_name = input("Enter your First_name :")
first(first_name)
last_name = input("Enter your Last_name :")
last(last_name)
email = check_mail()
password = input("Enter your password :")
... |
521385855f8167cb18a1bd470046f337590970b3 | guyuzhilian/Programs | /Python/project_euler/problem12_optimized.py | 837 | 3.859375 | 4 | # -*- coding:utf-8 -*-
# author: Administrator
# date: 2015-07-15 15:23
def main():
primes = [2, 3]
n = 2
while True:
num = n * (n + 1) / 2
num_copy = num
factors = {}
for prime in primes:
while num % prime == 0:
if prime in factors:
... |
61e2a197370bedb86447f116014a1c3c6a7b373b | guyuzhilian/Programs | /Python/project_euler/problem14.py | 705 | 4.21875 | 4 | # -*- coding:utf-8 -*-
# author: Administrator
# date: 2015-07-15 18:36
def len_of_collatz_chain(starting_number):
# chain length including starting_number
count = 1
while starting_number > 1:
if starting_number % 2 == 0:
starting_number /= 2
else:
starting_numbe... |
0315366321e30bbd27e77939ef595036435ef639 | devinitpy/devinitpy.github.io | /mid/assignement.py | 2,366 | 3.875 | 4 | '''
Assement Test 1
Each qn carries 10 marks, bonus qn carries 20 marks, Passmark is 50%
Given a list containing dictionaries of students
write functions that interacts with the data as stated in the comments
'''
from operator import itemgetter, attrgetter
data = [{"name":"nelson","marks":70},
{... |
fcf759597fa67c3a386e014cd8cabb9fc6e8d089 | devinitpy/devinitpy.github.io | /mid/writing.py | 455 | 3.8125 | 4 | print "Opening the file..."
filename="C:/Users/USER/devinitpy.github.io/mid/will.txt"
file = open(filename, 'w')
print "Now I'm going to ask you for three lines."
line1 = raw_input("line 1: ")
line2 = raw_input("line 2: ")
line3 = raw_input("line 3: ")
print "I'm going to write these to the file."
file.write(line1)... |
03aefd63ce00a9f1defef3bea9eed46521236eca | BOVAGE/Mini-Expert-System | /expertsys.py | 1,693 | 3.78125 | 4 | import tkinter as tk
from tkinter import messagebox, simpledialog
class App():
def __init__(self, window, textfile):
self.textfile = textfile
self.window = window
window.withdraw()
def readFromFile(self):
with open(self.textfile) as file:
contents = file.... |
f6e8c3ef8a12fc42eaebfd3a028e3b27d076d483 | PRAVEEN11KUMAR/Love | /Love.py | 725 | 3.78125 | 4 | import turtle
import time
def curveSection(length=200):
for _ in range(length):
turtle.right(1)
turtle.forward(1)
def halfHeart(angle, forward, left):
if left:
turtle.left(angle)
turtle.forward(forward)
curveSection()
else:
turtle.left(120)
cu... |
6229ed228b07ac6ca323381b1754b1a003e14385 | kmemonahmed/Apropi-algorithm-calculation-implementation | /associaton_rule.py | 8,059 | 3.75 | 4 | iteration = int(input("Enter How Many Pattern : "))
# iteration = 7
pattern = []
# pattern = [['Beef', 'Chicken', 'Milk'], ['Beef', 'Cheese'], ['Cheese', 'Boots'], ['Beef', 'Chicken', 'Cheese'], ['Beef', 'Chicken', 'Clothes', 'Cheese', 'Milk'], ['Chicken', 'Clothes', 'Milk'], ['Chicken', 'Milk', 'Clothes']]
unique ... |
ebad439c364dbad44e58d13d979abbe581851686 | guiaiy/pythonstudy | /day07/zhishu2.py | 1,184 | 3.8125 | 4 | #!/usr/bin/env python3
import datetime
def time_contro(func):
def time_spend():
begin = datetime.datetime.now()
print(func())
finish = datetime.datetime.now()
return (finish - begin).seconds
return time_spend
def num_input(): ###输入一个数字,输出数字(包含)以内的所有质数
while True:
... |
360fe04f41727da3df0a808040959481f5dd5ebe | kthotav/Data-Science-with-Python | /learning_material/Python-Programming-Beginner/Python Basics-256.py | 1,708 | 4.3125 | 4 | ## 1. Programming And Data Science ##
print(1288)
print(639)
print(1288 + 639)
## 2. Arithmetic Operators ##
sum = 749 + 371 + 828 + 503 + 1379
avg = sum / 5
print(avg)
## 3. Variables ##
albuquerque = 749
anaheim = 371
anchorage = 828
arlington = 503
atlanta = 1379
print(anaheim)
## 4. Data Types ##
atlanta_str... |
d1064e83752cef920619ee50eeb399f4f4d33771 | kthotav/Data-Science-with-Python | /learning_material/Python-Programming-Beginner/Introduction to Functions-270.py | 2,590 | 3.796875 | 4 | ## 1. Overview ##
f = open("movie_metadata.csv", "r")
data = f.read()
rows = data.split("\n")
movie_data = []
for row in rows:
row_split = row.split(',')
movie_data.append(row_split)
print(movie_data[0:5])
## 3. Writing Our Own Functions ##
def first_elts(list):
return list
movie_names = first_elts([mo... |
e4ce1bad87e2dd95d9db1ef86dd9b7dbcb4c6422 | dharmik-thakkar/dsapatterns | /python/patterns/slidingwindow/longest_substring_k_distinct_char.py | 1,671 | 4.03125 | 4 | #######################################################################################################################
# Given a string, find the length of the longest substring in it with no more than K distinct characters.
#
# Input: String="araaci", K=2
# Output: 4
# Explanation: The longest substring with no more ... |
30a6edd65e4d1cd8da113e52d379315e1399246f | robihidayat/PythonExpert.io | /data-model/data-model.py | 891 | 3.890625 | 4 | # some behaviour that i want to implement -> write some __function__ (data model methode)
# comment pattern,
# top level function or top level syntax-> corresponding __
# Pattern
# x + y --> __add__
# init --> __init__
# reprt(x) --> __repr__
# x() --> __call__
class Polynomial:
def __init__(self, *coeffs):
... |
fdaf10a57b8d7c60561d188f72aea2de9af28f23 | cpe202spring2019/lab1-jubenjam | /lab1.py | 1,425 | 4.125 | 4 |
def max_list_iter(int_list): # must use iteration not recursion
if type(int_list) != list:
raise ValueError
if len(int_list) == 0:
return None
max = int_list[0]
for i in int_list:
if i > max:
max = i
return max
"""finds the max of a list of numbers a... |
eb5f382672f0dbe8b765f620290f6483e3fc35e6 | achmadafriza/DDP1 | /Random Shiz/WS11.py | 1,829 | 3.59375 | 4 | from tkinter import *
def number3():
window = Tk()
window.title('Counter with Lambda')
counter = IntVar()
counter.set(0)
Button(window, text="Up", bg = "Yellow", command=lambda:counter.set(counter.get()+1)).pack()
Button(window, text="Down", bg = "Cyan", command=lambda:counter.set(c... |
04af7e4dbe8e31742938da65cd5b391d8d506b70 | misho88/latex-template | /bin/gscholar | 12,527 | 3.890625 | 4 | #!/usr/bin/env python3
"""Searches Google Scholar and gives back a BibTeX citation
Users can add BibTeX bibliographies like this:
$ scholar.py -o references.bib search tokens
which brings up a few search results and the user picks the one they want.
The way to get a citation normally goes a bit like this:
1. Sear... |
33fe03f405a9f584bdc7c1cb5e2fb4a495b6a02a | sheraz10/task1 | /question4sol.py | 118 | 3.734375 | 4 | var=input("Enter alphabet: ")
if (var in "aeiou"):
print("vowel")
else:
print("consonent")
|
57449879a5a4c0a6bd33dc6483f55ad094fe79fb | yuhow/my_work | /algorithm_thinking/course_1/application_1_1.py | 3,566 | 3.71875 | 4 | """
Algorigthm thinking Project 1
2015/06/08
author: You-Hao Chang
"""
import urllib2
import matplotlib.pyplot as plt
CITATION_URL = "http://storage.googleapis.com/codeskulptor-alg/alg_phys-cite.txt"
def load_graph(graph_url):
"""
Function that loads a graph given the URL
for a text repre... |
2760adc1b0bb05a631a1b9c042899e356944c527 | yuhow/my_work | /algorithm_thinking/course_4/application_4_8.py | 2,008 | 3.796875 | 4 | """
Algorithm thinking application 4-8
data: 2015/07/30
Author: You-Hao Chang
"""
import alg_application4_provided as app4
import AT_project_4 as pj4
import application_4_7 as sol4_7
import random
import time
def check_spelling(checked_word, dist, word_list):
"""
To iterates through word_list ... |
f53593cb594ad729e984f8a41659066337cba7bb | David-rn/bib-number-detector | /dataset_creation/dataset_creation.py | 4,185 | 3.703125 | 4 | import argparse
import cv2
from imutils import paths
import os
import csv
def open_csv_file(file_name):
'''
This function is used to open a csv file
'''
try:
with open(file_name, 'r') as read_file:
reader = csv.reader(read_file)
lines = list(reader)
read_... |
9717a8f886dcfbfa334d11ef33f3ff7e996d65cd | gituser01mtk/python_codes | /arrow_pattern.py | 146 | 3.75 | 4 | x=13
#x= int(input())
k=(x//2)
for i in range (k+1):
print((" "*(i))+("* "*(i+1)))
for i in range (k):
print((" "*(k-i-1))+("* "*(k-i)))
|
4b17630b504a876007aae481a8988be6ab7f9784 | yan0728/xuelei | /study/xxClass.py | 760 | 3.96875 | 4 | #!/usr/bin/env python
"""
@author:闫学雷
@project:test
@file: 类.py
@time:2020/6/29 0029
"""
# 1 定义一个类需要使用class关键字,然后基础object类
# 2 在类定中定义方法,第一个参数是self,self代表的是当前的对象
class Person(object):
# 构造方法:初始对象p1的属性,添加了name和age
def __init__(self,name,age):
# self == 创建的对象,即对象p1拥有了name和age属性
self.name = name... |
c1104bec681151743307af77461f8d39887e0656 | and-why/PythonProjects | /us-states-game-start/main.py | 1,462 | 3.75 | 4 | import turtle
import pandas
screen = turtle.Screen()
screen.title("U.S. States Game")
image = "blank_states_img.gif"
screen.addshape(image)
turtle.shape(image)
# GET STATE LOCATIONS
# def get_mouse_click_coor(x, y):
# print(x, y)
#
# turtle.onscreenclick(get_mouse_click_coor)
# turtle.mainloop()
data = pandas.rea... |
4b42ad21c017f1285ce2367095cbce71036b75ba | TakeEasy/BlackHatPython | /testIDE.py | 326 | 3.75 | 4 | def test_sum(number_one, number_two):
number_one = convert_integer(number_one)
number_two = convert_integer(number_two)
result = number_one + number_two
return result
def convert_integer(number_string):
converted_integer = int(number_string)
return converted_integer
answer = test_sum("1",... |
0521833907e7e88946c7f96d0d0505a98451a007 | ckjq202682/AS41 | /main.py | 772 | 3.71875 | 4 | # AS41
import random
def makequestion():
question = ""
for i in range(7):
a = random.randint(0, 1)
question = str(a) + question
count = 0
pa = ["Even", "Odd"]
parity = random.choice(pa)
for b in range(len(question)):
if question[b] == "1":
coun... |
e7f6cd61bbfabc0713b52e31716149485058d6c8 | qige96/programming-practice | /Standford-Algorithms/divide-and-conquer/quicksort.py | 743 | 3.703125 | 4 | import random
def _partition(arr, start, end):
p = random.randint(start, end-1)
arr[start], arr[p] = arr[p], arr[start]
pivot = arr[start]
i, j = start+1, start+1
while j < end:
if arr[j] < pivot:
arr[i], arr[j] = arr[j], arr[i]
i += 1
j += 1
arr[start], ... |
ca095721b24f160dece3b99971a729c258ff550c | qige96/programming-practice | /Standford-Algorithms/divide-and-conquer/int_mul.py | 324 | 3.6875 | 4 | import os
def grade3_multiply(a:str, b:str)->int:
intermediate = []
int_a = int(a)
lb = list(b)
lb.reverse()
for i, num in enumerate(lb):
intermediate.append(int(num) * int_a * 10**i)
return sum(intermediate)
def _karatsuba(a:str, b:str)->int:
pass
if __name__ == "__main__":
p... |
2864e2d88606600210076275daab661ee93de4e0 | haxiaocao/python-study | /plot/matpyt2.py | 8,632 | 3.65625 | 4 | import matplotlib.pyplot as plt
import numpy as np
# reference:https://www.runoob.com/w3cnote/matplotlib-tutorial.html
# 用来正常显示中文标签
plt.rcParams['font.sans-serif'] = ['SimHei']
def plot_default():
X = np.linspace(-np.pi, np.pi, 256, endpoint=True)
C, S = np.cos(X), np.sin(X)
plt.plot(X, C)
plt.plot(... |
a015e8a2db61c3593ce3c632ddf3026e9be431ae | rvdmtr/python | /Eric_Matthes/chapter_1/10/learn_in.py | 544 | 3.609375 | 4 | ####10-1
filename = 'txt_files/learning_python.txt'
with open(filename) as file_object:
lines = file_object.readlines()
print(lines)
#print('\n')
#for line in lines:
# lang = 'Python'
# print(line.rstrip())
# if lang in line:
# print(line.replace('Python','C'))
print('\n\n####### 10-2 #######\n')
message = 'I ... |
d87773159a53e88d16dd5e92cbcf8cdc174627a5 | rvdmtr/python | /Eric_Matthes/chapter_1/10/word_count.py | 1,113 | 4.09375 | 4 | def count_words(filename):
"""Подсчет приблизительного количества строк в файле."""
try:
with open(filename) as f_obj:
contents = f_obj.read()
except FileNotFoundError:
#msg = 'Sorry, the file ' + filename.lstrip('txt_files/') + ' doesn`t exist.'
#print(msg) # Выводим сообщение - файл не найден
pass # нич... |
5ebb060e5dac458a493907567bdbcb20e6d238ea | rvdmtr/python | /Eric_Matthes/chapter_1/7/7-10_vacations.py | 456 | 3.890625 | 4 | vacations = {}
polling_active = True
while polling_active:
name = input('What is your name? ')
vacation = input('Where your want to taste your vacation? ')
vacations[name] = vacation
cont = input('Would you like to answer another person? (yes /no) ')
if cont == 'no':
polling_active = False
print('\n --- Poll... |
2fe91e582af30b1e881f6082241205e76d71dd41 | rvdmtr/python | /Eric_Matthes/chapter_1/9/imp_user.py | 1,310 | 3.890625 | 4 | class User():
# """Простая модель пользовательского профиля"""
def __init__(self,first_name,last_name,age,height,secret):
# """Инициализирует атрибуты экземпляра"""
self.first_name = first_name
self.last_name = last_name
self.age = age
self.height = height
self.secret = secret
self.login_attempts = 0
... |
22243a5e7e5686614572fe5b7eb71ad419091bb8 | rvdmtr/python | /Eric_Matthes/chapter_1/11_unittest/survey.py | 822 | 3.59375 | 4 | #survey.py
class AnonymousSurvey():
"""Сбор анонимных ответов на опросы"""
def __init__(self,question):
"""Сохраняет вопрос и готовится к сохранению ответов"""
self.question = question
self.responses = []
def show_question(self):
"""Выводит вопрос."""
print(self.question)# self.question ссылка на атрибу... |
859c0adb4f00f63755c68d0d47c8107d5450c81a | rvdmtr/python | /Eric_Matthes/chapter_1/8/8-6_city_country.py | 294 | 3.734375 | 4 | def city_country(city,country):
"""Вывод города и страны"""
place = city + ', ' + country
return place.title()
vacation = city_country('moscow','russia')
vac2 = city_country('berlin','germany')
vac3 = city_country('new york','usa')
print(vacation)
print(vac2)
print(vac3) |
e38f871ec53fa3801aca2bd008c322d9ce6e0152 | alyashafira/labpypraktikum4 | /Praktikum 4.py | 1,333 | 3.734375 | 4 | #PROGRAM MENAMBAHKAN DATA DAN MENENTUKAN NILAI AKHIR MAHASISWA
NML =[]
NIML =[]
NTL =[]
NUTSL =[]
NUASL =[]
NAML=[]
print(" PROGRAM MENAMBAHKAN DATA DAN MENENTUKAN NILAI AKHIR MAHASISWA ")
print("")
jawab ="y"
while jawab == "y" :
NM=input("Nama Mahasiswa :")
NIM=input("NIM :")
NTUGAS... |
1ee848f7274bf47a33f00003bc96d7bf25ee702b | CheGevarAa/Pyhton_practicum | /Linux_practice_Popov_PI19_2-main/client.py | 911 | 3.828125 | 4 | #!/usr/bin/env python
import socket
sock = socket.socket()
sock.setblocking(1)
host=input("Type in the host: ")
port=int(input("Type in the port: "))
if not ((0<=port<65536) and isinstance(port, int)):
print('Wrong port id, the default one will be used (9080)')
port=9080
try:
try:
prin... |
c7b53eee6f850d0d681e0218417ea6aac1dd022b | Jane2308/Games | /Crazy_stories.py | 916 | 4.0625 | 4 | loop = 1
while (loop < 10):
print("Welcome to your crazy story")
person = input("Enter a name")
verb = input("Enter an 'ing' verb")
adjective = input("Enter an adjective")
noun = input("Enter a country or state")
print ("Computer Science students at Rice University created ",person,... |
fa63815c1a4b27689993a9af12697ef8c88ac30b | kacsem/semraukacperinformatyka | /zad4/sortowanie ciągu.txt | 394 | 3.578125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sat May 15 08:06:45 2021
@author: colib
"""
print ('Hello Word')
'sortowanie liczb ciągu'
x=[4,5,2,9,8,5,6]
n=7
i = 0
j = i +1
for i in range (0, n-1):
for j in range (i+1,n):
if x[i] > x[j]:
z=x[i]
x[i] = x[j]
... |
e8c5339897639186df72b23f571f6da4c255e2a2 | dotrungkien3210/AI4E_Course | /hw2/bt3.py | 806 | 3.671875 | 4 | import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
data = pd.read_csv('data_linear.csv')
N = data.shape[0]
print(data)
x = data.iloc[:, 0]
x = x.values.reshape(-1, 1)
print(x)
y = data.iloc[:, 1]
y = y.values.reshape(-1, 1)
plt.scatter(x, y)
plt.xlabel('Diện tích')
plt.ylabel('Giá')
np.ones((N, 1))... |
91eb3cd38f359f17190a608168420c6d1605a94c | dotrungkien3210/AI4E_Course | /hw2/bt4.py | 760 | 3.734375 | 4 | import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
data = pd.read_csv('data_square.csv')
N = data.shape[0]
x = data.iloc[:, 0]
x = x.values.reshape(-1, 1)
y = data.iloc[:, 1]
y = y.values.reshape(-1, 1)
def predict(X,theta):
return X @ theta
xHeight = len(x)
xWidth = len(x[0])
theta = np.zeros(... |
6653532ef2c07e625244be5fae6683367d1cc989 | chxj1992/leetcode-exercise | /14_longest_common_prefix/_1.py | 967 | 3.6875 | 4 | import unittest
from typing import List
class Solution:
def longestCommonPrefix(self, strs: List[str]) -> str:
class DiffPrefix(Exception):
pass
if not strs:
return ''
i = 0
prefix = ''
first_len = len(strs[0])
while True:
if i >... |
85b3d20257296d9fcaec0ff0ded892786362e889 | chxj1992/leetcode-exercise | /860_lemonade_change/_1.py | 1,046 | 4.0625 | 4 | import unittest
from typing import List
class Solution:
def lemonadeChange(self, bills: List[int]) -> bool:
wallet = {5: 0, 10: 0, 20: 0}
for bill in bills:
wallet[bill] += 1
if bill == 10:
if wallet[5] >= 1:
wallet[5] -= 1
... |
46eb9710df70341123583137607e384fe4ccb1cc | chxj1992/leetcode-exercise | /subject_lcof/57/_1.py | 789 | 3.984375 | 4 | import unittest
from typing import List
class Solution:
def findContinuousSequence(self, target: int) -> List[List[int]]:
res = []
start = 1
end = 2
while end > start:
s = int((start + end) * (end - start + 1) / 2)
if s == target:
res.append... |
6afc44f953cf880e53ed06f3687aabd399d236b9 | chxj1992/leetcode-exercise | /subject_lcof/28/_1.py | 1,062 | 4.21875 | 4 | import unittest
# Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def isSymmetric(self, root: TreeNode) -> bool:
def symmetric(sub1: TreeNode, sub2: TreeNode):
if not sub1 an... |
0ea5d15a5b558cc238fec89650995adaff1e0cae | chxj1992/leetcode-exercise | /subject_lcof/26/_1.py | 1,304 | 4.15625 | 4 | import unittest
# Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def isSubStructure(self, A: TreeNode, B: TreeNode) -> bool:
def recur(a: TreeNode, b: TreeNode):
if not b:
... |
e2b4dcfa1a750ffb98b32072fa691186c9841fa0 | chxj1992/leetcode-exercise | /191_number_of_1_bits/_1.py | 394 | 3.796875 | 4 | import unittest
class Solution:
def hammingWeight(self, n: int) -> int:
res = 0
while n > 0:
res += n % 2
n //= 2
return res
class Test(unittest.TestCase):
def test(self):
s = Solution()
self.assertEqual(3, s.hammingWeight(int('000000000000000... |
4e4f9748e51f4ea12cc172c61f9cd5ff96ef305f | chxj1992/leetcode-exercise | /weekly_contest/5347_minimum_cost_to_make_at_least_one_valid_path_in_a_grid/_1.py | 1,902 | 3.90625 | 4 | import unittest
# Definition for singly-linked list.
from typing import List
class Solution:
def __init__(self) -> None:
self.min_cost = 10000
def minCost(self, grid: List[List[int]]) -> int:
"""
Timeout!
"""
steps = {
1: (0, 1),
2: (0, -1),
... |
ea8730850919ee6422e8f5b203b539e0c6030875 | chxj1992/leetcode-exercise | /69_sqrtx/_1.py | 571 | 3.65625 | 4 | import math
import unittest
class Solution:
def mySqrt(self, x: int) -> int:
if x <= 1:
return x
start, end = 0, x
while end > start + 1:
mid = (start + end) / 2
if mid * mid <= x:
start = math.floor(mid)
else:
... |
ece0ed976fa0454c220f266ec52485320bebe259 | chxj1992/leetcode-exercise | /98_validate_binary_search_tree/_2.py | 1,888 | 3.828125 | 4 | import unittest
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def isValidBST(self, root: TreeNode) -> bool:
stack = []
prev = None
while root is not None or len(stack) > 0:
while root is not ... |
cf6764cdbead2ac7028837b41a9f9da022082240 | chxj1992/leetcode-exercise | /572_subtree_of_another_tree/_1.py | 1,680 | 4.125 | 4 | import unittest
# Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def isSubtree(self, s: TreeNode, t: TreeNode) -> bool:
if s is None and t is None:
return True
elif ... |
86daf006746eff06c4fd8754219782712424bdc8 | chxj1992/leetcode-exercise | /21_merge_two_sorted_lists/_2.py | 1,174 | 3.96875 | 4 | import unittest
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:
if l1 is not None and l2 is not None:
if l1.val < l2.val:
l1.next = self.mergeTwoLists(l1.... |
f469ecf2490195c304aa6761b77f0e4e4b87cd76 | chxj1992/leetcode-exercise | /88_merge_sorted_array/_2.py | 1,823 | 3.953125 | 4 | import unittest
from typing import List
class Solution:
def merge(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None:
"""
Time: O(m*n)
Space: O(1)
"""
last = m
for i in range(n):
if m == 0:
nums1.insert(last, nums2[i])
... |
82509f2c1dd43591c50b74ed32a4ed3be8ccfa8e | chxj1992/leetcode-exercise | /22_generate_parentheses/_3.py | 915 | 3.84375 | 4 | import unittest
from typing import List
class Solution:
def generateParenthesis(self, n: int) -> List[str]:
def backtrack(_n: int, prefix: str):
if _n == 0:
result.append(prefix)
return
left_count = prefix.count('(')
right_count = prefix... |
00f459559c334863fad29965d808470fe4812a72 | chxj1992/leetcode-exercise | /51_n_queens/_1.py | 1,327 | 3.765625 | 4 | import unittest
from typing import List
class Solution:
def solveNQueens(self, n: int) -> List[List[str]]:
result = []
def backtrack(total: int, curr: int, solution: List[str]):
if curr == total:
result.append(solution)
for i in range(total):
... |
093d7d37b4ea21dc042777327500efa18b7b7dbc | chxj1992/leetcode-exercise | /367_valid_perfect_square/_2.py | 509 | 3.734375 | 4 | import unittest
class Solution:
def isPerfectSquare(self, num: int) -> bool:
prev, curr = num, 0
while prev - curr > 1:
prev = curr if curr > 0 else num
curr = (prev + num / prev) / 2
return int(prev) * int(prev) == num
class Test(unittest.TestCase):
def test... |
0432faf47f08ec47d61d247877b6f7bd8d9a7c1c | chxj1992/leetcode-exercise | /11_container_with_most_water/_2.py | 741 | 3.828125 | 4 | import unittest
from typing import List
class Solution:
def maxArea(self, height: List[int]) -> int:
"""
Time: O(n)
Space: O(1)
"""
left = 0
right = len(height) - 1
area = 0
while left < right:
area = max(area, (right - left) * min(heigh... |
e3162379f9e56ebe99f376762f3715118688b77f | chxj1992/leetcode-exercise | /28_implement_strstr/_1.py | 631 | 3.734375 | 4 | import unittest
class Solution:
def strStr(self, haystack: str, needle: str) -> int:
if needle == "":
return 0
hl = len(haystack)
nl = len(needle)
for index, char in enumerate(haystack):
if index + nl > hl:
return -1
if haystack[i... |
419dc4b7dc1cf6d26fdee89539e00bb735e22640 | chxj1992/leetcode-exercise | /198_house_robber/_1.py | 618 | 3.765625 | 4 | import functools
import unittest
from typing import List
class Solution:
def rob(self, nums: List[int]) -> int:
if len(nums) == 0:
return 0
@functools.lru_cache(maxsize=256)
def _rob(i: int):
if len(nums[i:]) <= 2:
return max(nums[i:])
r... |
396f031b2e8958d72bfa8cdb862cf1a7cfe80e64 | chxj1992/leetcode-exercise | /3_longest_substring_without_repeating_characters/_2.py | 873 | 3.828125 | 4 | import unittest
class Solution:
def lengthOfLongestSubstring(self, s: str) -> int:
i, j, l, curr, longest = 0, 0, len(s), 0, 0
char_set = set()
while l > j >= i:
if s[j] not in char_set:
char_set.add(s[j])
curr += 1
longest = max(... |
e3586f7d1c51ceb201507eb3a8b32920e846af01 | chxj1992/leetcode-exercise | /weekly_contest/5170_validate_binary_tree_nodes/_3.py | 1,585 | 3.640625 | 4 | import unittest
from typing import List
class Solution:
def validateBinaryTreeNodes(self, n: int, leftChild: List[int], rightChild: List[int]) -> bool:
queue = [0]
visited = set()
while queue:
next_level = []
while queue:
i = queue.pop()
... |
76ec034c3a9ad418afcb02c3b7c6945f72bc7df1 | chxj1992/leetcode-exercise | /subject_lcof/07/_1.py | 1,720 | 4.15625 | 4 | import unittest
# Definition for singly-linked list.
from typing import List
# Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def buildTree(self, preorder: List[int], inorder: List[int]) -> Tr... |
c40c8d6087d256d82263bb63bb42828c90c21114 | chxj1992/leetcode-exercise | /104_maximum_depth_of_binary_tree/_2.py | 1,188 | 4.09375 | 4 | import unittest
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def maxDepth(self, root: TreeNode) -> int:
max_depth = 0
if root is None:
return 0
stack = [root]
while stack:
... |
436e10419edf095f9710ba5e0a807b44fee55409 | chxj1992/leetcode-exercise | /77_combinations/_2.py | 1,236 | 3.703125 | 4 | import unittest
from typing import List
class Solution:
def combine(self, n: int, k: int) -> List[List[int]]:
combined = list(range(1, k + 1))
res = []
stack = []
while combined[0] < n + 1 - k:
res.append(combined.copy())
combined[-1] += 1
while ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.