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 |
|---|---|---|---|---|---|---|
cce00bbeff1a917c85b84d6593184e9ab1817164 | VaskovaTK/leetcode | /isSymmetric.py | 2,755 | 3.65625 | 4 | class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
def isSymmetric(self, root: TreeNode) -> bool:
leftArr = []
rightArr = []
self.recursLeft(root.left,leftArr)
self.recursRig... |
001c5b5bf702077f5b3b74ea1a15f9364f7e6760 | VaskovaTK/leetcode | /deleteNode.py | 382 | 3.5625 | 4 | class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def deleteNode(self, node):
while True:
if node.next:
node.val = node.next.val
if node.next.next:
node = node.next
else:
... |
900957a2b907d55de11b2e362731616ea9326a90 | VaskovaTK/leetcode | /isRecOver.py | 3,206 | 3.546875 | 4 | class Solution:
def isRectangleOverlap(self, rec1: list, rec2: list) -> bool:
flag = False
if rec1[0] == rec1[2] or rec2[0] == rec2[2]:
return False
if rec1[1] == rec1[3] or rec2[1] == rec2[3]:
return False
if rec2[0]>rec1[0] and rec2[0] < rec1[2]:
... |
f1f2c7d831e640e08bb06b75a8491ee44dfaa572 | VaskovaTK/leetcode | /climbStairs.py | 1,689 | 3.625 | 4 | class Solution:
class Solution:
def climbStairsHelper(self, n, dp):
if n == 2:
return 2
if n == 0 or n == 1:
return 1
if dp[n - 1] == -1:
step1 = self.climbStairsHelper(n - 1, dp)
dp[n - 1] = step1
... |
40ee9d6b9d39b1cc88aa19bf7c7ddf2b2392ddd3 | VaskovaTK/leetcode | /reverseLinkedList.py | 960 | 3.90625 | 4 | from collections import deque
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution:
def reverseList(self, head: ListNode) -> ListNode:
if head == None:
return head
linkedQue = deque()
while head.next:
... |
54b666907a71fff0f8fe79a660559b67214093e0 | jmackay-doterra/challenges | /_common/fibonacci.py | 323 | 3.734375 | 4 | from functools import lru_cache
class Fibonacci():
@lru_cache(maxsize = 1000)
def generate_fibonacci(num):
if num == 1:
return 0
elif num == 2:
return 1
elif num > 2:
return (Fibonacci.generate_fibonacci(num - 1) + Fibonacci.generate_fibonacci(num - ... |
1ea80bf4ac7979036601cb4214b80c7796f04e57 | sanyam-jain21/internship-project-2nd-year | /project 1.py | 547 | 3.96875 | 4 | l=[]
def read(l):
print(l)
def insert(l):
e=int(input("Enter a element :"))
l.append(e)
def remove(l):
i=int(input("Enter the index to remove :"))
l.pop(i)
while True:
print('''1)Print the given list.
2)Insert an element in a list.
3)Delete a element from a list.
4)Exit.''')
ch... |
0f9abd3df92f203a089bf8fc291d7bf0ac71fca7 | DRKn1ght/C-e-Python | /exercicio 04 da lista.py | 1,275 | 3.953125 | 4 | # -*- coding: utf-8 -*-
"""
@author: Guilherme P. RA: 112679
"""
import numpy
print("Este programa resolve o exercício 07 da lista 02 de maneira geral.")
print("Para utilizar, ensira todas as coordenadas na mesma linha, separado por vírgula, exemplo:\nVetor 1: 1,2,3")
#Declaração das variáveis
index = 0
d ... |
1c09f5bef3a6d12421bde11f65162d47d502bbf8 | brianweku/BrianWeku_ITP2017_Exercise2 | /Palindrome.py | 263 | 3.59375 | 4 | #Palindrome
x=input("input word: ")
x=x.casefold()
reversex=reversed(x)
if list(x) == list(reversex):
print ("True")
else:
print ("False")
#Fibbonaci
x=[0, 1]
for i in range(1, 15):
lol=x[i-1] + x[i]
x.append(lol)
print(x)
|
dffe70a213003df3b04d2840e877f66f3d234413 | gustavofernandeztwk/pythonlogica | /comparacion.py | 292 | 3.875 | 4 | #if; else;
numero1 = int(input("ingrese numero1"))
numero2 = int(input("ingrese numero2"))
4#if()()
if numero1 == numero2:
print("los numeros son iguales")
elif numero1 > numero2:
print("el numero mayor es", numero1)
#else()
else:
print("el numero mayor es", numero2)
type(1)
| |
084f15cf395819a80da558990f9f3da6c1e4b73e | gustavofernandeztwk/pythonlogica | /prueba 1.py | 740 | 3.96875 | 4 | x = int(input("da el primer numero: ")) #se pide al usuario que ingrese un numero a eleccion
y = int(input("da el segundo numero: ")) #se pide al usuario que ingrese un numero a eleccion
z = int(input("da el tercer numero: ")) #se pide al usuario que ingrese un numero a eleccion
a = min(x, y, z) #se invoca la funcion ... |
be78f51047590c4263336f13a60e50e991023d3f | LittltZhao/code_git | /069_Sqrt.py | 346 | 3.71875 | 4 | # -*- coding:utf-8 -*-
def mySqrt(x):#折半查找
if x==0:
return 0
i,j=1,x/2+1
while i<=j:
center=(i+j)/2
if center**2==x:
return center
elif center**2<x:
j=center-1
else:
i=center+1
return j#循环结束后必然有i>=j,故返回j
print mySqrt(1)
|
1ebc8360faaf8e6b3e030207fc1330c83cd0f85d | LittltZhao/code_git | /461_Hamming_Distance.py | 221 | 3.8125 | 4 | def hammingDistance(x,y):
count=0
z=x^y
while z:
if z%2==1:
count+=1
z/=2
return count
def hammingDistance2(x,y):
return bin(x^y).count('1')
print hammingDistance2(12,13)
|
1738ad927ad1aa0842856dbe055014a76f81da43 | LittltZhao/code_git | /027_Remove_Element.py | 286 | 3.65625 | 4 | # -*- coding:utf-8 -*-
def removeElement(nums,val):
i=0
while i<len(nums):
if nums[i]==val:
nums.remove(nums[i])#移除元素后索引依然为原来的值,故要减去1
i-=1
i+=1
return len(nums)
print removeElement([1,13,4,5,1],1)
|
53c935628a3bcee64d664a7304417cc509031e12 | LittltZhao/code_git | /342_Power_of_Four.py | 202 | 4.125 | 4 | # -*- coding:utf-8 -*-
#判断一个数是否为4的幂数
def isPowerOfFour(num):
return num>0 and (num&(num-1))==0 and (num-1)%3==0#(num&(num-1))==0判断是否为2的幂
print isPowerOfFour(16)
|
4fcf1979722ca09d770b34700c0c6abe124e2465 | LittltZhao/code_git | /237_Delete_Node_in_A_Linked_List.py | 605 | 3.921875 | 4 | # -*- coding:utf-8 -*-
# 删除给定节点
# 解决策略:只给了要删除的节点,将下一节点的值赋予本节点,然后删除下一节点
class ListNode(object):
def __init__(self,x):
self.val=x
self.next=None
def DeleteNode(node):#删除指定节点
node.val=node.next.val
p=node.next
node.next=p.next
def removeElements(head,val):#给出链表,删除指定节点
dum=ListNode(0)
... |
ec4030fa14128f11e3354b789203588dddf333ff | flashlightli/math_question | /leetcode_question/mid_question/29_Divide_Two_Integers.py | 2,103 | 4.125 | 4 | """
给定两个整数,被除数 dividend 和除数 divisor。将两数相除,要求不使用乘法、除法和 mod 运算符(取余)。
返回被除数 dividend 除以除数 divisor 得到的商。
整数除法的结果应当截去(truncate)其小数部分,例如:truncate(8.345) = 8 以及 truncate(-2.7335) = -2
示例 1:
输入: dividend = 10, divisor = 3
输出: 3
解释: 10/3 = truncate(3.33333..) = truncate(3) = 3
示例 2:
输入: dividend = 7, divisor = -3
输出: -2... |
cbabb745d29b004c700fa4edfa9c16c1d4424d5a | flashlightli/math_question | /leetcode_question/mid_question/114_Flatten_Binary_Tree_to_Linked_List.py | 1,404 | 4.25 | 4 | """
给定一个二叉树,原地将它展开为一个单链表。
例如,给定二叉树
1
/ \
2 5
/ \ \
3 4 6
将其展开为:
1
\
2
\
3
\
4
\
5
\
6
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/flatten-binary-tree-to-linked-list
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
"""
class TreeNode:
def __init... |
38dc535f13c3c41c239be2cc78eab784ed89f6d8 | flashlightli/math_question | /leetcode_question/mid_question/113_Path_Sum_II.py | 1,345 | 3.875 | 4 | """
给定一个二叉树和一个目标和,找到所有从根节点到叶子节点路径总和等于给定目标和的路径。
说明: 叶子节点是指没有子节点的节点。
示例:
给定如下二叉树,以及目标和 sum = 22,
5
/ \
4 8
/ / \
11 13 4
/ \ / \
7 2 5 1
返回:
[
[5,4,11,2],
[5,8,4,5]
]
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems... |
f43eeee8cf7f3ed7bc88cf56202c9883076910c3 | flashlightli/math_question | /leetcode_question/mid_question/56_Merge_Intervals.py | 1,196 | 3.65625 | 4 | """
给出一个区间的集合,请合并所有重叠的区间。
示例 1:
输入: [[1,3],[2,6],[8,10],[15,18]]
输出: [[1,6],[8,10],[15,18]]
解释: 区间 [1,3] 和 [2,6] 重叠, 将它们合并为 [1,6].
示例 2:
输入: [[1,4],[4,5]]
输出: [[1,5]]
解释: 区间 [1,4] 和 [4,5] 可被视为重叠区间。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/merge-intervals
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
"""
class Sol... |
a265f2c32beed0966ec9974f2636ac257f1b1e35 | flashlightli/math_question | /leetcode_question/mid_question/152_Maximum_Product_Subarray.py | 1,260 | 3.625 | 4 | """
给你一个整数数组 nums ,请你找出数组中乘积最大的连续子数组(该子数组中至少包含一个数字),并返回该子数组所对应的乘积。
示例 1:
输入: [2,3,-2,4]
输出: 6
解释: 子数组 [2,3] 有最大乘积 6。
示例 2:
输入: [-2,0,-1]
输出: 0
解释: 结果不能为 2, 因为 [-2,-1] 不是子数组。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/maximum-product-subarray
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
"""
class Solution:
d... |
a1b37510c60ac168d1e0c19e0ab8238ebf23f8e5 | flashlightli/math_question | /leetcode_question/mid_question/75_Sort_Colors.py | 1,522 | 4.09375 | 4 | """
给定一个包含红色、白色和蓝色,一共 n 个元素的数组,原地对它们进行排序,使得相同颜色的元素相邻,并按照红色、白色、蓝色顺序排列。
此题中,我们使用整数 0、 1 和 2 分别表示红色、白色和蓝色。
注意:
不能使用代码库中的排序函数来解决这道题。
示例:
输入: [2,0,2,1,1,0]
输出: [0,0,1,1,2,2]
进阶:
一个直观的解决方案是使用计数排序的两趟扫描算法。
首先,迭代计算出0、1 和 2 元素的个数,然后按照0、1、2的排序,重写当前数组。
你能想出一个仅使用常数空间的一趟扫描算法吗?
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problem... |
1c1120cba1d344166f578dea327315be056a3607 | flashlightli/math_question | /leetcode_question/mid_question/120_Triangle.py | 1,180 | 3.859375 | 4 | """
给定一个三角形,找出自顶向下的最小路径和。每一步只能移动到下一行中相邻的结点上。
相邻的结点 在这里指的是 下标 与 上一层结点下标 相同或者等于 上一层结点下标 + 1 的两个结点。
例如,给定三角形:
[
[2],
[3,4],
[6,5,7],
[4,1,8,3]
]
自顶向下的最小路径和为 11(即,2 + 3 + 5 + 1 = 11)。
说明:
如果你可以只使用 O(n) 的额外空间(n 为三角形的总行数)来解决这个问题,那么你的算法会很加分。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/triangl... |
469a78da9f71bb8e6d96fc64cfcab3d632621bce | flashlightli/math_question | /leetcode_question/mid_question/98_Validate_Binary_Search_Tree.py | 1,765 | 3.75 | 4 | """
给定一个二叉树,判断其是否是一个有效的二叉搜索树。
假设一个二叉搜索树具有如下特征:
节点的左子树只包含小于当前节点的数。
节点的右子树只包含大于当前节点的数。
所有左子树和右子树自身必须也是二叉搜索树。
示例 1:
输入:
2
/ \
1 3
输出: true
示例 2:
输入:
5
/ \
1 4
/ \
3 6
输出: false
解释: 输入为: [5,1,4,null,null,3,6]。
根节点的值为 5 ,但是其右子节点值为 4 。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/prob... |
c2eab3124bfb59df5d278cd59db140c6916a1d4c | flashlightli/math_question | /leetcode_question/book/57_dp_bag.py | 585 | 3.78125 | 4 | """
背包问题
有n个重量和价值分别为wi vi的物品, 从这些物品中挑选出总重量不超过W的物品,求所有挑选方案中价值总和的最大值
PS: 在这里, 每种物品可以挑选多件
n = 3
things_list = [(3,4),(4,5),(2,3)]
w = 7
"""
def get_max_value(n, w, thing_list=[]):
# 普通DP算法
tmp = []
for i in range(n + 1):
curr = []
for j in range(w + 1):
curr.append(0)
tmp.... |
064d3a1795d60c280b6d8636324460aeb3a65bf2 | flashlightli/math_question | /leetcode_question/mid_question/43_Multiply_Strings.py | 821 | 3.578125 | 4 | class Solution:
def multiply(self, num1: str, num2: str) -> str:
# 基本的乘式计算
if num2 == "0" or num1 == "0":
return "0"
list_a, list_b = list(num1), list(num2)
total_arr = [0] * (len(num1) + len(num2))
for index_i, value_i in enumerate(list_a):
for index... |
20e8d2d717d4fa894e708c9074a7e5d5f4d2ff05 | flashlightli/math_question | /leetcode_question/easy_question/88_Merge_Sorted_Array.py | 1,272 | 3.984375 | 4 | """
给你两个有序整数数组 nums1 和 nums2,请你将 nums2 合并到 nums1 中,使 nums1 成为一个有序数组。
说明:
初始化 nums1 和 nums2 的元素数量分别为 m 和 n 。
你可以假设 nums1 有足够的空间(空间大小大于或等于 m + n)来保存 nums2 中的元素。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/merge-sorted-array
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
"""
class Solution:
def merge(self, nums1... |
bef1a019ca8eeee487cba30f74fb4c4415c63aca | flashlightli/math_question | /leetcode_question/mid_question/96_Unique_Binary_Search_Trees.py | 1,203 | 3.703125 | 4 | """
给定一个整数 n,求以 1 ... n 为节点组成的二叉搜索树有多少种?
示例:
输入: 3
输出: 5
解释:
给定 n = 3, 一共有 5 种不同结构的二叉搜索树:
1 3 3 2 1
\ / / / \ \
3 2 1 1 3 2
/ / \ \
2 1 2 3
来源:力扣(LeetCode)
链接:https://leetcode-cn.co... |
6095f1d91d9478c27219be28ff4945c75f1f6eb4 | flashlightli/math_question | /leetcode_question/easy_question/53_Maximum_Subarray.py | 2,519 | 3.828125 | 4 | """
给定一个整数数组 nums ,找到一个具有最大和的连续子数组(子数组最少包含一个元素),返回其最大和。
示例:
输入: [-2,1,-3,4,-1,2,1,-5,4],
输出: 6
解释: 连续子数组 [4,-1,2,1] 的和最大,为 6。
进阶:
如果你已经实现复杂度为 O(n) 的解法,尝试使用更为精妙的分治法求解。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/maximum-subarray
"""
class Solution:
def maxSubArray(self, nums):
# 44ms 14.2MB
... |
55fe7d5ac97391d4c98b80a28d1b022e2a6cb4db | burnchar/cryptshell | /vigenere.py | 3,214 | 3.953125 | 4 | #!/usr/bin/python
import sys
class Vigenere:
def __init__(self, string, key):
#list used to match letter of the alphabet and their index
self.letters = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z']
#create matrix
#each row contain... |
d59f5e3f78c7fea8d7c941ee32ef679abcabd546 | Savior-Hayne/PYpractice | /52week.py | 2,144 | 4.03125 | 4 | """
功能: 52周存钱挑战
更新: 1.记录每周的金额
2.改用for循环
3.可以根据用户自定义每周存入金额,递增金额,总共周数,并封装成函数
4.根据用户输入的日期,判断是一年中的第几周,然后输出相应的存款金额
"""
import math
import datetime
def save_money_in_n_weeks(money_per_week, increase_money, total_week):
"""
计算n周内的存款金额
"""
money_week_list = [] # 记录每周存款数的列表
saved_money_l... |
0508b7e249d0967822228c21b2546f581240e224 | yassineameur/pystork | /pystork/costs/binary_classfication.py | 1,378 | 3.78125 | 4 | """
This file represents the cost function for binary classification
"""
import math
import numpy as np
from pystork.costs.abstract_cost import AbstractCostFunction
class BinaryClassificationCost(AbstractCostFunction):
def compute(self, y_pred: np.array, y_labels: np.array) -> float:
# This function wo... |
142f1545134e9e290280e3a52553fbd71e16ae9c | ASravanthi1/python1 | /40.py | 328 | 3.578125 | 4 | n=int(input(""))
a=1
b=1
count=0
c=0
k=" "
if(n==0):
print(a)
elif(n<0):
print("negative number")
else:
while(count<n):
if(c==0):
print(a,end="")
else:
print("",end=k)
print(a,end="")
nexterm=a+b
a=b
b=nexterm
count+=1
... |
ca5cf63d3deae564c489fe956503a4124da888cf | Hanlen520/Leetcode-4 | /src/95. 不同的二叉搜索树 II.py | 1,297 | 3.84375 | 4 | """
给定一个整数 n,生成所有由 1 ... n 为节点所组成的二叉搜索树。
"""
# 这个题我想了很久,之前一直想用递归来做,从上往下,没有办法估计具体的建树数目
# 所以无奈只能看解答,然后从下往上进行
# 某根节点的建树数目是他可建左子树和右子树数目的乘积
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
... |
002e164dc7da45f63c4a9f24c9d0772ebf7e35bc | Hanlen520/Leetcode-4 | /src/101. 对称二叉树.py | 1,298 | 4.03125 | 4 | # 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 helper(p, q):
if not p and not q:
return Tru... |
e17ba41598320f2e61e7c71f27b5598c0911c338 | Hanlen520/Leetcode-4 | /src/125. Valid Palindrome.py | 362 | 3.625 | 4 | class Solution:
def isPalindrome(self, s):
"""
:type s: str
:rtype: bool
"""
import string
table = str.maketrans('','',string.punctuation+' ')
s = s.translate(table).lower()
for i in range(len(s)//2):
if s[i]!=s[-(i+1)]:
ret... |
995f6d12975dfe9ac70b06aed87145240fe4d2d5 | Hanlen520/Leetcode-4 | /src/19. 删除链表的倒数第N个节点.py | 507 | 3.71875 | 4 |
# Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode:
phead = ListNode(0)
phead.next = head
p1, p2 = phead, phead
for _ in range(n... |
8d1ac4eefbd2be4eba74f38be9f4b7c815e33a4e | Hanlen520/Leetcode-4 | /src/78. Subsets.py | 401 | 3.5625 | 4 | class Solution:
def subsets(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
sol = []
def dfs(nums, path, sol):
if len(nums) == 0:
sol.append(path)
else:
dfs(nums[1:], path+[nums[0]], sol)
... |
3d4d4bed3d93ff5e28e6212c0b41cb2d0d96a06c | Hanlen520/Leetcode-4 | /src/50. Pow(x, n).py | 407 | 3.53125 | 4 | """
实现 pow(x, n) ,即计算 x 的 n 次幂函数。
"""
# 分情况讨论
# 一个递归二分法,复杂度O(logn)
class Solution:
def myPow(self, x: float, n: int) -> float:
if n < 0:
return self.myPow(1/x, -n)
if n == 0:
return 1
if n % 2:
return self.myPow(x*x, n // 2) * x
else:
... |
457ac15fcea68d766279c72296236295daa866d1 | Hanlen520/Leetcode-4 | /src/114. 二叉树展开为链表.py | 1,746 | 4.1875 | 4 | """
给定一个二叉树,原地将它展开为链表。
"""
# Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
# 其实就是先序遍历,下面采用迭代的方法
class Solution:
def flatten(self, root: TreeNode) -> None:
"""
Do not return anything, modify root... |
11cb3ba121490a7bfa38481ef3e636ec6cc4f019 | Hanlen520/Leetcode-4 | /src/129. 求根到叶子节点数字之和.py | 1,171 | 4.03125 | 4 | """
给定一个二叉树,它的每个结点都存放一个 0-9 的数字,每条从根到叶子节点的路径都代表一个数字。
例如,从根到叶子节点路径 1->2->3 代表数字 123。
计算从根到叶子节点生成的所有数字之和。
说明: 叶子节点是指没有子节点的节点。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/sum-root-to-leaf-numbers
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
"""
# Definition for a binary tree node.
class TreeNode:
def __init__(self,... |
f5370b34c68c4b73beb64d65d9d1b57bd37bf6fb | ShuangLiBCM/local_lr_unsup | /local_lr/BCM_tf.py | 7,518 | 3.71875 | 4 | # Impletment BCM class and related functions in tensorflow
# inference() - Builds the model as far as is required for running the network forward
# training() - Use the local learning rule to update the weights and thresholdss
import numpy as np
import tensorflow as tf
def inference(input_single, inputs, n_output = 2,... |
c6767ce98febf75ca4d8d7648200248b74815ce1 | hokou/pphelp_part1 | /20210301/week02.py | 3,541 | 3.9375 | 4 | # 要求一:函式與流程控制
print("== 01 ==")
def calculate(min, max):
# 請用你的程式補完這個函式的區塊
total = 0
for i in range(min,max +1):
total = total + i
print(total)
calculate(1, 3) # 你的程式要能夠計算 1+2+3,最後印出 6
calculate(4, 8) # 你的程式要能夠計算 4+5+6+7+8,最後印出 30
# 要求二:Python 字典與列表、JavaScript 物件與陣列
print("== 02 ==")
def av... |
3e9ded9e500aa74ffd6c1859bc7bf859834a82eb | Rick-Houser/holbertonschool-higher_level_programming | /oop_can_manage_your_family/family.py | 3,121 | 3.90625 | 4 | from datetime import datetime
''' This class describes a circle '''
class Person():
''' Class attributes '''
EYE_COLORS = ["Blue", "Green", "Brown"]
GENRES = ["Female", "Male"]
''' Constructor '''
def __init__(self, id, first_name, date_of_birth, genre, eyes_color):
''' Private and Public attributes '''
self.... |
dcbefd33a6443904c6f4a2866ebe6f6e16f527b1 | ayodeletolu12/Python-Projects | /timeOneHasLived.py | 882 | 4.03125 | 4 | # scripts that calculate the number of second, minutes, hours, days, months a person has lived
number_of_years = int(input('Enter the number of years you have lived: '))
number_of_months = number_of_years * 12
number_of_weeks = number_of_years * 52
number_of_days = number_of_years * 365
number_of_hours = number_of_day... |
5fe39c177e067bb7d720748e19dd58bcfa841393 | pxz000git/python-se | /module/object/extends_self.py | 427 | 3.984375 | 4 | #!/usr/bin/python3
# -*- coding: utf-8 -*-
# @Author:Pxz
# @Time :2019/1/8 0008下午 4:20
"""
继承中的self相关
self始终是原始调用的类的self
"""
class A(object):
def a(self):
print("A--a--self--%s" % self)
class B(A):
def b(self):
print("B--b--self--%s" % self)
if __name__ == "__main__":
b_instance = B()... |
d5a5515e2050bf05fda3b7af347fbb7ee5bb1601 | pxz000git/python-se | /module/param/change_param.py | 696 | 3.921875 | 4 | #!/usr/bin/python3
# -*- coding: utf-8 -*-
# @Author:Pxz
# @Time :2018/12/26 0026上午 10:35
"""
可变参数
"""
# 传入一个列表,严格地说这不是可变参数
def calc(l):
sum = 0
for n in l:
sum += n
return sum
# 这才是可变参数,虽然在使用上和列表没有区别,
# 但是参数nums接收到的是一个tuple(这些参数在传入时被自动组组装为一个元祖)
def calc_ch(*nums):
sum = 0
for n in num... |
5db4736365308d8ab84203f048a43b043ea5d827 | pxz000git/python-se | /module/mysocket/tcp/tcp_server.py | 835 | 3.5 | 4 | #!/usr/bin/python3
# -*- coding: utf-8 -*-
# @Author:Pxz
# @Time :2019/1/17 0017下午 5:28
import socket
def server_tcp():
s_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
ip = '172.18.22.2'
port = 8005
address = (ip, port)
s_socket.bind(address)
s_socket.listen(5)
while True:
... |
bca09c600dbb8bc4c42555df3ccd74b098aa0dd0 | adrodin/okrety | /src/button.py | 2,702 | 3.546875 | 4 | import pygame
from constants.colors import BUTTON_COLOR,BUTTON_TEXT_COLOR
class Button:
def __init__(self,x,y,width,height,color=BUTTON_COLOR,text='',text_color=BUTTON_TEXT_COLOR ):
"""
Inicjalizacja przycisku
:param x: pozycja x przycisku
:param y: pozycja y przycisku
:pa... |
ba50f4c8c88ab725ca9cbed37d1744b59eb9c2a9 | luangcp/visao_computacional_openCV | /.vscode/suavizacao_pela_mediana.py | 1,079 | 3.75 | 4 | """
A mediana é semelhante a media, mas ela despreza valores muito altos ou muito baixos que podem distorcer
o resultado. A mediana é o número que fica exatamente no meio do intervalo.
A função utilizada é a cv2.mediamBlur(imagem, 3) e o unico argumento é o tamanho da caixa ou janela usada
é importante notar que est... |
6464e79a748057a12f082930257c56e77544a004 | luangcp/visao_computacional_openCV | /.vscode/metodo_Canny_detector_de_bordar.py | 1,783 | 3.734375 | 4 | """
Em inglês canny pode ser traduzido para esperto, E o carry Hedge
Detector ou detector de bordas caany realmente é mais inteligente que os outros.
Ele se utiliza de outras tecnicas como o Sobel e realiza multiplos passos para
chegar ao resultado final.
Basicamente o Canny envolve:
1 - Aplicar um filtro gaussiano pa... |
52f6eecd6091cc2e1dba430233e99d81ae657deb | luangcp/visao_computacional_openCV | /.vscode/Metodo_Sobel_deteccao_de_bordas.py | 1,067 | 3.734375 | 4 | """
Não encontraremos na explicação matematica de cada metodo mas
é importante notar que o Sobel é direcional, então temos que
juntar o filtro horizontale o vertical para teruma transformação completa
"""
# Importando bibliotecas
import cv2
import numpy as np
# Lendo a imagem
imagem = cv2.imread('imagem/ponte.jpg')
# ... |
5f58223731738c6023ceee03d02e36585c7fa474 | crefeld-coding/python_regex_exercises | /problem_set_1.py | 2,916 | 3.6875 | 4 | import re
import unittest
class BasicMatching(unittest.TestCase):
"""Fill in a regular expression that will match the
target strings, without matching the other strings.
"""
def test_mentions_pet(self):
with_pet = [
"I like my cat.",
"A cat is a person's best friend.",... |
8137d76c1b0b161df43fa0a052d4a9185132c330 | sjtu-hxj/algorithm016 | /Week_07/70.爬楼梯.py | 721 | 3.65625 | 4 | class Solution:
def climbStairs(self, n: int) -> int:
"""
爬到第n楼的方法,为爬到第n-1楼和n-2楼的方法之和
因为爬到n-1楼后,再爬1楼就能到达n楼
爬到n-2楼同理
因此只需初始化爬到1楼和爬到2楼分别有多少种方法,便可以推导出爬到n楼的方法
"""
fst = 1 # 爬到1楼只有1种方法
scd = 2 # 爬到2楼有两种方法
res = 0 # 初始化爬到n楼的方法
f... |
a8bdbc1d37527f14ce08ae0f8e15c5877d28aed4 | ericka1599/radio | /radio.py | 1,968 | 3.703125 | 4 | class Radio ():
def __init__ (self, marca ):
self.encendido = True
self.estacion_FM = 88.00
self.estacion_AM = 300
self.en_FM = True
self.marca = ""
self.volumen = 0
def encender (self):
self.encendido = True
return "Encendido"
def apagar (s... |
4508866832b2578a43788e47e00c3e9781bb6b44 | cesarmarroquin/blackjack | /blackjack_outline.py | 2,089 | 4.1875 | 4 | """
I need to create a blackjack Game. In blackjack, the player plays against the dealer. A player can win in three
different ways. The three ways are, the player gets 21 on his first two cards, the dealer gets a score higher than 21,
and if the player's score is higher than the dealer without going over 21. The deale... |
82d20bbd941bc662554635fc914e15f1995a37ed | erickthered/dictionary-generator | /go.py | 2,228 | 3.609375 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import hashlib
import string
import sys
import getopt
alphabet = list(string.printable)
alphabet = alphabet[0:-5] + [u"á", u"é", u"í", u"ó", u"ú", u"Á", u"É", u"Í", u"Ó", u"Ú", u"ñ", u"Ñ", u"ü", u"Ü"]
def md5(string):
m = hashlib.md5()
m.update(string.encode('utf... |
39aab71bd690fb6676d2a9706452cbe292dc8f33 | Nayan95/Advance-Software-System | /Assignment 3/f_name and l_name.py | 121 | 3.671875 | 4 | f_name=input("First Name : ")
l_name=input("Last Name : ")
print("\nLAST and FIRST name : " + l_name + " " + f_name )
|
71216f0ac32a1da0a356fbf21710bc22335b224c | perfect-parabola/deeplearning-study | /Lecture2_1.py | 680 | 3.625 | 4 | import tensorflow as tf
#simple linear regression using tensorflow
x_train = [1,2,3]
y_train = [1,2,3]
w = tf.Variable(tf.random_normal([1]), name = 'weight')
b = tf.Variable(tf.random_normal([1]), name = 'bias')
#tensor flow 에서 variable은 조금 다름 trainable 의 의미 => 알아서 바꿈
hypothesis = x_train*w + b
cost = tf.reduce_me... |
be65a6a080f66cb51503b5e3f0abc9906af3574e | matesmoliere/pythonlager | /17.es_palindromo.py | 603 | 3.921875 | 4 | def es_palindromo(texto):
'''
El texto no debe tener otros signos de puntuación que el
apostrofe (') y los espacios entre palabras. En cualquier
otro caso no funcionará
>>> es_palindromo("Go hang a salami I'm a lasagna hog")
True
>>> es_palindromo("I roamed under it as a tired nude M... |
3883f41652fa43d96be453f5d5434aead2cf3ead | mohit131/python | /project_euler/14__Longest_Collatz_sequence.py | 1,095 | 4.21875 | 4 | '''The following iterative sequence is defined for the set of positive integers:
n → n/2 (n is even)
n → 3n + 1 (n is odd)
Using the rule above and starting with 13, we generate the following sequence:
13 → 40 → 20 → 10 → 5 → 16 → 8 → 4 → 2 → 1
It can be seen that this sequence (starting at 13 and finishing ... |
c7404efed6d6384bcf49df15f0dc508c01a7fef5 | mohit131/python | /project_euler/9__Special_Pythagorean_triplet.py | 490 | 4.125 | 4 | '''A Pythagorean triplet is a set of three natural numbers, a < b < c, for which,
a^2 + b^2 = c^2
For example, 3^2 + 4^2 = 9 + 16 = 25 = 52.
There exists exactly one Pythagorean triplet for which a + b + c = 1000.
Find the product abc.'''
for m in range(1,5000):
for n in range(1,500):
if m>n:
a=m*... |
ea9735c637f6ab4374f12c8fa965781d95546ef6 | psoerens/Euler8 | /Euler8.py | 964 | 3.6875 | 4 | from LargeNumberReader import LargeNumberReader #useing the large number reader
lnr = LargeNumberReader('1000digit.txt') #initialize the reader
large = lnr.getLarge() #get the large number in a list format
index = 0 #initial index
lens = 13 #length of lens
length = len(large) #length of the list
last = length... |
733cd8027e2fcb3af0adce61cdee44a8cad984dc | AmirthaRajan/Python_Courses | /Udemy/blockchain/course_assignments/assignment_two.py | 284 | 3.984375 | 4 | names = ['Abilash','Rajan',"Naruto","Ram"]
for index in range(len(names)):
if len(names[index]) > 5:
print(names[index])
if 'n' in names[index] or 'N' in names[index]:
print(names[index] + " has N/n char")
while len(names) > 0:
names.pop()
print(names) |
e25b61132ac6200bad1a76c4f885361b84f87e0e | Strait21/Heap_Sort_Python | /Heap.py | 2,040 | 3.9375 | 4 |
class Heap:
"""this is a max heap and will heap for a sort of max to min
ex.... [19,18,17,16,15,14]
if you want a min heap just change all the ">" in the methods heapup and heapdown to a "<"
"""
def __init__(self):
self.stuff = []
self.length = 0
... |
51b09d8652ad18c7fc6a133abb1a1ef05e6247dc | saraswat/props | /props/utils/lf_utils.py | 6,798 | 3.546875 | 4 | """
Collection of routines to simplify logic forms, primarily by removing default
structure, moving to a variable free (de Bruijn) representation, etc.
"""
import copy
from pprint import pprint
def simplify_single_dict(lf, feat):
"Replace {feat:v} by v everywhere in lf."
if isinstance(lf, dict):
if ... |
dfe05086f23c5c6afa98864aa99632583063648a | HXXFX/crcp3310project04 | /songs.py | 311 | 3.515625 | 4 | #py ver rdb
import sqlite3
DB_FILE_NAME = "songs.sqlite3.db";
SQL_SELECT_GENRES = "SELECT name FROM genres;"
db_connection = sqlite3.connect(DB_FILE_NAME)
cursor = db_connection.cursor() #cursor is where we are in the db
for row in cursor.execute(SQL_SELECT_GENRES):
print (row)
db_connection.close()
|
3ed64e40a6724c590fa51719fce1324468901a99 | JaySurana0710/Commandline-Games- | /rpsls.py | 2,504 | 3.578125 | 4 | from random import randint
import os
import time
options=['ROCK','PAPER','SCISSOR','LIZARD',"SPOCK"]
while True:
computer=randint(0,4)
player=int(input('1.ROCK\n2.PAPER\n3.SCISSOR\n4.LIZARD\n5.SPOCK\n'))-1
if options[player]==options[computer]:
print('TIE')
elif options[player]=='ROCK':
if opt... |
ea3369e4b7da43378345094c5390b95e63ab27fd | harshal9876/MISC | /dev.py | 9,517 | 3.734375 | 4 | import pandas as pd
import numpy as np
import matplotlib as pl
def main_menu():
print('\n')
print(70*'*')
print('***Read Data Frame File in Different Way***')
print('1.Read Complete csv File...')
print('2.Reading complete csv File Without Index...')
print('3.Reading File With New Column Names...')
print(5... |
7e30a56fa4a6cf57f711a779b9519f9bd4246505 | Vertmo/ACM-ICPC-Algorithms | /BackTracking/RatInAMaze/ratmaze.py | 892 | 3.8125 | 4 | """
Solving the Maze problem using backtracking
maze = [[1, 0, 0, 0], [1, 1, 0, 1], [0, 1, 0, 0], [1, 1, 1, 1]],
where 1s are the safe cells
"""
# Maze size
N = 4
def isSafe(maze, x, y):
if x >= 0 and x < N and y >= 0 and y < N and maze[x][y] == 1:
return True
return False
def solveMaze(maze):
so... |
c223e5a812b8ebb271aa932e660dcb0cc06615d5 | Vertmo/ACM-ICPC-Algorithms | /DFS/python/DFS.py | 569 | 3.859375 | 4 | """
Print the DFS traversal of a graph.
Internally the graph is represented as an adjacency dict
"""
from collections import defaultdict
class Graph:
def __init__(self):
self.graph = defaultdict(list)
def addEdge(self, u, v):
self.graph[u].append(v)
def DFSUtil(self, v, visited):
... |
5a97036b637ec09c393d8fae0178db26b3db1603 | adidrmwan/basic-python | /leapYear.py | 503 | 4.1875 | 4 | def is_leap(year):
leap = False
leap_year = year % 4
leap_year_divided_100 = year % 100
leap_year_divided_400 = year % 400
if leap_year == 0:
leap = True
if leap_year_divided_100 == 0:
leap = False
if leap_year_divided_400 == 0:
leap = ... |
df01dc415a7750095dcd99b64690469a7c41b983 | Chittadeepan/P342 | /lab5_q2.py | 1,328 | 4.1875 | 4 | #importing everything from math module
from math import *
#importing all functions from library
from library import *
#poly_f(x) function
def poly_f(x,coeff,n):
sum=0
for i in range(1,n+1):
sum=sum+coeff[i-1]*x**(n-i)
return sum
#main program
def main():
#initialising fi... |
dabdc27f848af91aa7aa406d914e13d95a19854d | Chittadeepan/P342 | /lab1_q3.py | 252 | 3.78125 | 4 | #initialising sumand index
sum=0
index=1
#using while loop to find sum
while 1/index>=0.001:
sum=sum+1/index
index+=1
#displaying output
print('Summing over 1 + 1/2 + 1/3... till sum does not change by more than 0.001 :',sum)
print('\n\n') |
7ed33c12f940dddde1402957b1f34c579db54ae9 | TrangHo/cs838-code | /src/lib/features/feature15.py | 514 | 3.71875 | 4 | import re
# 15(T). Whether it has the form: "... colege(s) like <...> or <...>"
# - Whether it has the form: "... universities like <...> or <...>"
# - private colleges like <pos>Middlebury</pos> or <pos>Champlain</pos>
# ⁃ universities like <pos>Harvard</pos>
def test(str, prefix):
prefix = re.sub(r'\b(of... |
6029d2f524af42d7d013826751adb4315d4dab53 | Ogawa1406/Ogawa1406 | /exercicio5.py | 70 | 3.734375 | 4 | x=10
y=12
div=x%y
print("O resto da divisão entre x e y é: ",div) |
e73b589dfe10c7d3c8ec22fcad2806f64a32f526 | Ogawa1406/Ogawa1406 | /exercicio16.py | 171 | 4.0625 | 4 | x=int(input("Digite um número inteiro: "))
x1=x/2
x2=x*2
x3=x**4
print("O valor de X é",x,",sua metade é",x1,",seu dobro é ",x2,"e seu valor elevado à 4 é ",x3) |
8352dc99283f0f27739f54c36e0b0f71ff2e5372 | debayant9/HelloToPy | /py_prog4.py | 227 | 3.9375 | 4 | def findfact(arg):
sum = 1
if arg != 0:
for i in range(1,arg+1):
sum = sum *i
print(sum)
else:
print("Please give a valid number")
n = input("Enter a number: ")
findfact(int(n))
|
96d3b83e998a8841490bd3ed15e1952e3e8560f6 | bbbranjan/wine-recommender | /query_popularity.py | 1,161 | 3.5625 | 4 | import pandas as pd
df = pd.read_csv('./wine-reviews/popular_terms.csv')
# Get top 3 most popular terms
def get_popular_terms(query=''):
term_dict = {}
for index, row in df.iterrows():
term_dict[row['query']] = row['count']
query = query.strip()
# if no terms
if len(query) == 0:
... |
14aecc146828d664bf37b3f967eeca758c3f3d44 | rohitmanjhi/Py_multithreading | /activethreadex.py | 522 | 3.578125 | 4 | from threading import *
import time
def display():
print(current_thread().name,'started\n')
time.sleep(3)
print(current_thread().name,'ended\n')
print('The number of active thread',active_count())
t1 = Thread(target=display,name='Child thread-1\n')
t2 = Thread(target=display,name='Child thread-2\n')
t3 = T... |
4323fe8b5c52a05ccbc565dfdf52f66b1bbbda52 | RNHTTR/stock-tracker | /stock.py | 1,498 | 3.625 | 4 | '''
Various functions to utilize Alpha Vantage API stock data
TODO: Refactor to instantiate time_series objects in this file
NOTE: Throttling occurs sometimes when calling alpha vantage api
'''
from alpha_vantage.timeseries import TimeSeries
def get_stock_data(period: str, ticker: str): # TODO: Refactor to instantia... |
d32cfb712b22020e38f312cd848a243b08fe9216 | danielwilson2017/Picture | /picture.py | 1,994 | 3.84375 | 4 | """
picture.py
Author: Daniel Wilson
Credit: none
Assignment:
Use the ggame library to "paint" a graphical picture of something (e.g. a house, a face or landscape).
Use at least:
1. Three different Color objects.
2. Ten different Sprite objects.
3. One (or more) RectangleAsset objects.
4. One (or more) CircleAsset o... |
559596166f14f830bf564ea4904183520982ddb5 | Par2002/Pythonflask | /day2.py | 334 | 3.609375 | 4 | a='AB de-villiers'
print(a,type(a))
b=9577
print(b,type(b))
d=53.5
print(d,type(d))
e=37
print(e,type(e))
print(f"My favorite player is {a}. And his ODI runs is {b} ",end=" ")
print("And his one day international batting avg is {} and his age is {} ".format(d,e))
d2=int(d)
print(d2,type(d2))
b1=float(b)... |
2155d65c8bc9adfd4a3dd5cc85f44a7d28a46c64 | miltondts/exercises-notes | /grokking-algorithms/chapter_4/quicksort.py | 297 | 3.890625 | 4 | def quicksort(array):
if len(array) < 2:
return array
pivot = array[0]
under = filter(lambda x: x < pivot, array)
over = filter(lambda x: x > pivot, array)
return quicksort(under) + [pivot] + quicksort(over)
array = [2, 5, 13, 21, 8, 3, 1]
print (quicksort(array))
|
591876e78c3f90a962a83e1856a0bd0ea65c050e | miltondts/exercises-notes | /python/shuffle.py | 1,425 | 3.578125 | 4 | #!/usr/sbin/python
#TODO:
# Add tests
import itertools
import random
import time
N = 10000
deck = list('abc')
def get_occurences(ndecks, pattern):
return len(list(filter(lambda x : x == pattern, ndecks)))
def nshuffle(n, shuffle, deck):
t = time.time()
decks = list()
for i in range(n):
decks.append(tuple(sh... |
e537efac5d4877eb9b8516a4b02cee19f7985323 | PratheekH/Python_sample | /comp.py | 201 | 4.28125 | 4 | name=input("Enter your name ")
size=len(name)
if size<3:
print("Name should be more than 3")
elif size>50:
print("Name should not be more than 50")
else:
print("Name looks fine") |
845843d4dc91e7ed96fd8a3c73e36fe973321991 | Steven1791/seq2seq | /Walkest1_Code/clean_corpora.py | 2,276 | 3.53125 | 4 | #!/usr/bin/env python3
# -*- coding: iso-8859-1 -*-
# just above is the Encoding declaration for ,, !!
import argparse
import os
import re
from collections import Counter
import string
parser = argparse.ArgumentParser(description='preprocess ground truth text, manly removing/replacing characters, according to the vo... |
9f37963cb25772f35cb1649f1f53a544e78d2ff2 | shauncuier/py | /HackerRank/30daysOfCode/day2/day2.py | 468 | 3.765625 | 4 | import sys
#def solve(meal_cost, tip_percent, tax_percent):
if __name__ == '__main__':
meal_cost = float(input().strip())
tip_percentage = int(input().strip())
tax_percentage = int(input().strip())
tip_amount = meal_cost * tip_percentage / 100
tax_amount = meal_cost * tax_pe... |
8eb0c3f0df95f86a49a839e77d7d23918b121656 | Vishwajeetbamane/passwordgenerator | /passwordgenerator.py | 817 | 4.0625 | 4 | import string
import random
print("Welcone to Password Generator\n")
forwhat = input("Enter the website or application for which you want to generate password:\n")
length = int(input("Enter the length of password(Max-94)\n"))
if length >= 94:
print("Max length crossed.")
quit()
s1 = list(string.ascii_lowercase)
s... |
d93024ced7c5cabdefe11d271fbf2189fa6757ad | WSU-CASAS/AL | /features.py | 15,633 | 3.515625 | 4 | #!/usr/bin/python
# Contains functions to calculate features from sensor data.
# Written by Diane J. Cook, Washington State University.
# Copyright (c) 2020. Washington State University (WSU). All rights reserved.
# Code and data may not be used or distributed without permission from WSU.
import os
import datetime... |
636aec929445abf361f574e24a967f7aff281652 | LenaBencina/Advent-of-code2020 | /problem1.py | 493 | 3.796875 | 4 | # part1
with open('input1.txt', 'r') as input:
num_list = [int(line) for line in input]
def get_two_nums(num_list):
for i in num_list:
for j in num_list:
if i + j == 2020:
return i * j
print(get_two_nums(num_list))
# part2
def get_three_nums(num_list):
for i in num_... |
effce089e0dc4c2085258a543f9ce983768ba2f1 | Iliya-Yadegari/weekly-tax-with-tkinter | /weeklyTaxModule.py | 595 | 3.53125 | 4 | from tkinter import *
import sys
def tax_cal(hourEntered_e):
grossPay = int(hourEntered_e) * 15
if grossPay < 450:
messagebox.showerror('Error','You have not earned enough to be taxed properly.')
else:
grossRemaining = grossPay - 37.4 - 45
grossRemain... |
4fb203c6a90660f24b482b489aceae1c11c8b0d6 | honghsien5/Pi-GPIO-control | /pi_gpio.py | 853 | 3.984375 | 4 | #Filename: pi_gpio.py
#Author: Shien Hong
#Description: GPIO pin toggling
#import libraries
import RPi.GPIO as GPIO
import time
#Configure the GPIO pin
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
#Assign LED pin
led = int(raw_input('Please provide the LED pin number: '))
GPIO.setup(led, GPIO.OUT)
flag = 0
GPIO... |
aeea37cfad9f4d0ab04aa409329e3a4f03c4e484 | AntiLibrary5/AI_utopia | /def_grabber.py | 1,144 | 3.5625 | 4 | from bs4 import BeautifulSoup
import requests
from IPython.display import Markdown, display
from pathlib import Path
def find_closest_wiki(term):
wiki_base = 'https://en.wikipedia.org/'
term_with_plus = term.replace(" ", "+")
url = f"https://en.wikipedia.org/w/index.php?search={term_with_plus}"
... |
76eab43089da4f63a236324f6b9341b18f43344d | dogewzy/checkio | /JZ_offer/矩形覆盖.py | 499 | 4.09375 | 4 | """
我们可以用2*1的小矩形横着或者竖着去覆盖更大的矩形。请问用n个2*1的小矩形无重叠地覆盖一个2*n的大矩形,总共有多少种方法?
如果n是偶数的话,可以拆分成2*2位的n/2个正方形,每个正方形有两种方法
如果n是奇数的话,必须有一个位置竖的放,但是这个位置不能是奇数位,然后就等同于上面这种情况了
上面的思想错误了
还是跳台阶问题
"""
def solution(n):
return 2**(n-1) |
2bb61dac3ff839ebed6f610fa7cc978f42c9bbc7 | dogewzy/checkio | /Verify Anagrams.py | 393 | 3.859375 | 4 | def verify_anagrams(first_word, second_word):
first_word = [word.upper() for word in first_word]
second_word = [word.upper() for word in second_word]
d1, d2 = {}, {}
[d1.__setitem__(k, first_word.count(k)) for k in first_word if k != ' ']
[d2.__setitem__(k, second_word.count(k)) for k in second_word if k != ' ']
... |
6156e19fb2f4525ea7e313859a2a29553e86eec1 | dogewzy/checkio | /JZ_offer/008-旋转数组.py | 1,107 | 3.515625 | 4 | """
把一个数组最开始的若干个元素搬到数组的末尾,我们称之为数组的旋转。输入一个非递减序列的一个旋转,输出旋转数组的最小元素。
数组{3,4,5,1,2}为{1,2,3,4,5}的一个旋转,
该数组的最小值为1。
"""
# 无论怎么样,最小的元素就在最大的元素后面,注意边界问题吧,这个时间复杂度和移动的距离有关
def solution(input):
for idx, value in input[:-1]:
if value > input[idx + 1]:
return input[idx + 1]
# 分治法,最小的元素是两个有序数组的分割线,不停地取中间的元... |
f0a45690a59e0b8b7046904995638330f123a844 | dogewzy/checkio | /JZ_offer/调整数组顺序使奇数位于偶数前面.py | 618 | 3.796875 | 4 | """
输入一个整数数组,实现一个函数来调整该数组中数字的顺序,使得所有的奇数位于数组的前半部分,
所有的偶数位于数组的后半部分,并保证奇数和奇数,偶数和偶数之间的相对位置不变。
"""
# 这个解法直接过了……
# 说的细一点就是用两个辅助数组,分别存放奇数偶数
# 还有些大同小异的,用一个辅助数组,然后把偶数remove出来到一个新数组里面,最后合并进去
def solution(l):
odds = [i for i in l if i % 2 == 1]
even = [i for i in l if i % 2 == 0]
return odds + even
|
2b60b5ceb2992971e99c2511fec6b037de194abd | HassanElDesouky/ProblemSolving | /CTCI/1-Arrays_and_Strings/1_is_unique.py | 292 | 3.78125 | 4 | def is_unique_1(str1):
di = set()
for c in str1:
di.add(c)
return len(str1) == len(di)
def is_unique(str1):
li = list(str1)
li.sort()
for i in range(1, len(li)):
if li[i] == li[i-1]:
return False
return True
print(is_unique('hello'))
|
a15e07fd8320253937b28f3bc98e40cbba052ad1 | ravenannn/Python-Projects | /student_tracking_assignment/student_tracking_assignment_gui.py | 3,419 | 3.84375 | 4 | ##Python Ver: 3.9
##
##Author: Raven A. Sumner
##
##Purpose: Create a student tracking system application
## using Python with Tkinter and SQLLite3
##
##Tested OS: This code was written and tested to work with
## Windows 10.
from tkinter import *
import tkinter as... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.