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 |
|---|---|---|---|---|---|---|
adb2fb94243ba6b41a5bc063150a7a345dfa62ec | supan30888/Python-Kiso | /初日にやる問題25問/09-Computation-Min_Max_and_Sum.py | 930 | 3.65625 | 4 | # 09-Computation-Min_Max_and_Sum.py
# 最小値、最大値、合計値
# n 個の整数 ai(i=1,2,...n)を入力し、それらの最小値、最大値、合計値を求めるプログラムを作成してください。
# Input
# 1行目に整数の数 n が与えられます。2行目に n 個の整数 ai が空白区切りで与えられます。
# Output
# 最小値、最大値、合計値を空白区切りで1行に出力してください。
# Constraints
# 0<n≤10000
# −1000000≤ai≤1000000
# Sample Input
# 5
# 10 1 5 4 17
# Samp... |
0934c83a40bffa4b7abc9caf0235b71cf2e536fa | cylinder-lee-cn/LeetCode | /LeetCode/819.py | 2,435 | 4.28125 | 4 | """
819. 最常见的单词
给定一个段落 (paragraph) 和一个禁用单词列表 (banned)。返回出现次数最多,同时不在禁用列表中的单词。
题目保证至少有一个词不在禁用列表中,而且答案唯一。
禁用列表中的单词用小写字母表示,不含标点符号。段落中的单词不区分大小写。答案都是小写字母。
示例:
输入:
paragraph = "Bob hit a ball, the hit BALL flew far after it was hit."
banned = ["hit"]
输出: "ball"
解释:
"hit" 出现了3次,但它是一个禁用的单词。
"ball" 出现了2次 (同时没有其他单... |
70f78ccd3cbe944f76a32b61d5e421268c2578a9 | cylinder-lee-cn/LeetCode | /LeetCode/102.py | 1,943 | 4.03125 | 4 | """
102. 二叉树的层次遍历
给定一个二叉树,返回其按层次遍历的节点值。 (即逐层地,从左到右访问所有节点)。
例如:
给定二叉树: [3,9,20,null,null,15,7],
3
/ \
9 20
/ \
15 7
返回其层次遍历结果:
[
[3],
[9,20],
[15,7]
]
"""
# Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
... |
4434747b2ad1a8c80b4dd949ab69166a774440f5 | cylinder-lee-cn/LeetCode | /LeetCode/394.py | 2,295 | 3.78125 | 4 | """
394. 字符串解码
给定一个经过编码的字符串,返回它解码后的字符串。
编码规则为: k[encoded_string],表示其中方括号内部的 encoded_string 正好重复 k 次。注意 k 保证为正整数。
你可以认为输入字符串总是有效的;输入字符串中没有额外的空格,且输入的方括号总是符合格式要求的。
此外,你可以认为原始数据不包含数字,所有的数字只表示重复的次数 k ,例如不会出现像 3a 或 2[4] 的输入。
示例:
s = "3[a]2[bc]", 返回 "aaabcbc".
s = "3[a2[c]]", 返回 "accaccacc".
s = "2[abc]3[cd]ef"... |
07525de1aee006ece8223e30b2cce1f58655a43f | cylinder-lee-cn/LeetCode | /LeetCode/234.py | 1,964 | 3.859375 | 4 | """
234. 回文链表
请判断一个链表是否为回文链表。
示例 1:
输入: 1->2
输出: false
示例 2:
输入: 1->2->2->1
输出: true
进阶:
你能否用 O(n) 时间复杂度和 O(1) 空间复杂度解决此题?
"""
# Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def isPalindro... |
0121c2cc161faf35ee0f65303962e49dc114d0e7 | cylinder-lee-cn/LeetCode | /LeetCode/179.py | 1,447 | 3.640625 | 4 | """
179. 最大数
给定一组非负整数,重新排列它们的顺序使之组成一个最大的整数。
示例 1:
输入: [10,2]
输出: 210
示例 2:
输入: [3,30,34,5,9]
输出: 9534330
说明: 输出结果可能非常大,所以你需要返回一个字符串而不是整数。
"""
class Solution:
def largestNumber(self, nums):
"""
:type nums: List[int]
:rtype: str
"""
import functools... |
70e36243a086f4204690f4d267c62824d7844886 | cylinder-lee-cn/LeetCode | /LeetCode/50.py | 782 | 3.828125 | 4 | """
50. Pow(x, n)
实现 pow(x, n) ,即计算 x 的 n 次幂函数。
示例 1:
输入: 2.00000, 10
输出: 1024.00000
示例 2:
输入: 2.10000, 3
输出: 9.26100
示例 3:
输入: 2.00000, -2
输出: 0.25000
解释: 2-2 = 1/22 = 1/4 = 0.25
说明:
-100.0 < x < 100.0
n 是 32 位有符号整数,其数值范围是 [−231, 231 − 1] 。
"""
class Solution:
def myPow(self, x, n... |
f008aab1032dbb93bf5abe2a93dd9a04eda441ba | cylinder-lee-cn/LeetCode | /LeetCode/190.py | 552 | 3.515625 | 4 | """
190. 颠倒二进制位
颠倒给定的 32 位无符号整数的二进制位。
示例:
输入: 43261596
输出: 964176192
解释: 43261596 的二进制表示形式为 00000010100101000001111010011100 ,
返回 964176192,其二进制表示形式为 00111001011110000010100101000000 。
进阶:
如果多次调用这个函数,你将如何优化你的算法?
"""
class Solution:
# @param n, an integer
# @return an integer
d... |
c30de23d2ac7f09d0b389dcee2b313b231c7daa4 | cylinder-lee-cn/LeetCode | /LeetCode/98.py | 1,808 | 4.375 | 4 | """
98. 验证二叉搜索树
给定一个二叉树,判断其是否是一个有效的二叉搜索树。
假设一个二叉搜索树具有如下特征:
节点的左子树只包含小于当前节点的数。
节点的右子树只包含大于当前节点的数。
所有左子树和右子树自身必须也是二叉搜索树。
示例 1:
输入:
2
/ \
1 3
输出: true
示例 2:
输入:
5
/ \
1 4
/ \
3 6
输出: false
解释: 输入为: [5,1,4,null,null,3,6]。
根节点的值为 5 ,但是其右子节点值为 4 。
"""
... |
2a796cc4da9a6a6836520fc30cac157c336961cb | cylinder-lee-cn/LeetCode | /LeetCode/219.py | 1,049 | 3.640625 | 4 | """
219. 存在重复元素 II
给定一个整数数组和一个整数 k,判断数组中是否存在两个不同的索引 i 和 j,
使得 nums [i] = nums [j],并且 i 和 j 的差的绝对值最大为 k。
示例 1:
输入: nums = [1,2,3,1], k = 3
输出: true
示例 2:
输入: nums = [1,0,1,1], k = 1
输出: true
示例 3:
输入: nums = [1,2,3,1,2,3], k = 2
输出: false
"""
class Solution:
def containsNearbyDuplicate(sel... |
7d5177858ad67f2f7cdc88e832d440982c2fba50 | cylinder-lee-cn/LeetCode | /LeetCode/869.py | 1,600 | 3.921875 | 4 | """
869. 重新排序得到 2 的幂
从正整数 N 开始,我们按任何顺序(包括原始顺序)将数字重新排序,注意其前导数字不能为零。
如果我们可以通过上述方式得到 2 的幂,返回 true;否则,返回 false。
示例 1:
输入:1
输出:true
示例 2:
输入:10
输出:false
示例 3:
输入:16
输出:true
示例 4:
输入:24
输出:false
示例 5:
输入:46
输出:true
提示:
1 <= N <= 10^9
"""
class Solution:
def reorderedPowerOf2(self,... |
7d96767cb170a7bf0ed7c19cc333a6ec74ba3ad8 | cylinder-lee-cn/LeetCode | /LeetCode/443.py | 2,360 | 3.75 | 4 | """
443. 压缩字符串
给定一组字符,使用原地算法将其压缩。压缩后的长度必须始终小于或等于原数组长度。
数组的每个元素应该是长度为1 的字符(不是 int 整数类型)。
在完成原地修改输入数组后,返回数组的新长度。
进阶:
你能否仅使用O(1) 空间解决问题?
示例 1:
输入:
["a","a","b","b","c","c","c"]
输出:
返回6,输入数组的前6个字符应该是:["a","2","b","2","c","3"]
说明:
"aa"被"a2"替代。"bb"被"b2"替代。"ccc"被"c3"替代。
示例 2:
输入:
["a"]
输出:
返回1,输入数组的前... |
982ba3ac897c3e6c8418888996f87800b34c09e0 | cylinder-lee-cn/LeetCode | /LeetCode/848.py | 2,058 | 4.0625 | 4 | """
848. 字母移位
有一个由小写字母组成的字符串 S,和一个整数数组 shifts。
我们将字母表中的下一个字母称为原字母的移位(由于字母表是环绕的, 'z' 将会变成 'a')。
例如·,shift('a') = 'b', shift('t') = 'u',, 以及 shift('z') = 'a'。
对于每个 shifts[i] = x , 我们会将 S 中的前 i+1 个字母移位 x 次。
返回将所有这些移位都应用到 S 后最终得到的字符串。
示例:
输入:S = "abc", shifts = [3,5,9]
输出:"rpl"
解释:
我们以 "abc" 开始。
将... |
fa4bda7d1f8d62a031fabccf911edbd1b9ea538d | cylinder-lee-cn/LeetCode | /LeetCode/test.py | 129 | 3.546875 | 4 | for i in range(6, 0, -1):
for j in range(i - 1, 0, -1):
for k in range(j - 1, 0, -1):
print(i, j, k)
|
30ac6c7db947d9277480e365dbf8ee9dd886d638 | cylinder-lee-cn/LeetCode | /LeetCode/922.py | 954 | 3.78125 | 4 | """
922. 按奇偶排序数组 II
给定一个非负整数数组 A, A 中一半整数是奇数,一半整数是偶数。
对数组进行排序,以便当 A[i] 为奇数时,i 也是奇数;当 A[i] 为偶数时, i 也是偶数。
你可以返回任何满足上述条件的数组作为答案。
示例:
输入:[4,2,5,7]
输出:[4,5,2,7]
解释:[4,7,2,5],[2,5,4,7],[2,7,4,5] 也会被接受。
提示:
2 <= A.length <= 20000
A.length % 2 == 0
0 <= A[i] <= 1000
"""
class Solution:
def sortAr... |
8993e823f45049da1cd2929571cab6fc3e1af7b4 | cylinder-lee-cn/LeetCode | /LeetCode/415.py | 1,753 | 4 | 4 | """
415. 字符串相加
给定两个字符串形式的非负整数 num1 和num2 ,计算它们的和。
注意:
num1 和num2 的长度都小于 5100.
num1 和num2 都只包含数字 0-9.
num1 和num2 都不包含任何前导零。
你不能使用任何內建 BigInteger 库, 也不能直接将输入的字符串转换为整数形式。
"""
class Solution:
def toInt(self, c):
"""
:param c: str
:return: int
"""
ci = {... |
75ddc5e4f711d9b405243a2298e6eed9e1066c39 | cylinder-lee-cn/LeetCode | /LeetCode/295.py | 1,581 | 4.03125 | 4 | """
中位数是有序列表中间的数。如果列表长度是偶数,中位数则是中间两个数的平均值。
例如,
[2,3,4] 的中位数是 3
[2,3] 的中位数是 (2 + 3) / 2 = 2.5
设计一个支持以下两种操作的数据结构:
void addNum(int num) - 从数据流中添加一个整数到数据结构中。
double findMedian() - 返回目前所有元素的中位数。
示例:
addNum(1)
addNum(2)
findMedian() -> 1.5
addNum(3)
findMedian() -> 2
进阶:
如果数据流中所有整数都在 0 到 100 范围内,... |
6cca6e02e1cae61cea6dfb251d77d16d7e9da084 | cylinder-lee-cn/LeetCode | /LeetCode/88.py | 3,876 | 4.125 | 4 | """
88. 合并两个有序数组
给定两个有序整数数组 nums1 和 nums2,将 nums2 合并到 nums1 中,使得 num1 成为一个有序数组。
说明:
初始化 nums1 和 nums2 的元素数量分别为 m 和 n。
你可以假设 nums1 有足够的空间(空间大小大于或等于 m + n)来保存 nums2 中的元素。
示例:
输入:
nums1 = [1,2,3,0,0,0], m = 3
nums2 = [2,5,6], n = 3
输出: [1,2,2,3,5,6]
"""
class Solution:
def merge(self, nu... |
3fdd3a8a29c225dc6f84c1c8b8ba84b2e2f9190e | cylinder-lee-cn/LeetCode | /LeetCode/859.py | 1,860 | 3.953125 | 4 | """
859. 亲密字符串
给定两个由小写字母构成的字符串 A 和 B ,只要我们可以通过交换 A 中的两个字母得到与 B 相等的结果,
就返回 true ;否则返回 false 。
示例 1:
输入: A = "ab", B = "ba"
输出: true
示例 2:
输入: A = "ab", B = "ab"
输出: false
示例 3:
输入: A = "aa", B = "aa"
输出: true
示例 4:
输入: A = "aaaaaaabc", B = "aaaaaaacb"
输出: true
示例 5:
输入: A = "", B = "aa"
输... |
3eb912c82af5a183577f0a3fcb98ed638df8ae9e | cylinder-lee-cn/LeetCode | /LeetCode/532.py | 2,534 | 3.5625 | 4 | """
532. 数组中的K-diff数对
给定一个整数数组和一个整数 k, 你需要在数组里找到不同的 k-diff 数对。
这里将 k-diff 数对定义为一个整数对 (i, j), 其中 i 和 j 都是数组中的数字,且两数之差的绝对值是 k.
示例 1:
输入: [3, 1, 4, 1, 5], k = 2
输出: 2
解释: 数组中有两个 2-diff 数对, (1, 3) 和 (3, 5)。
尽管数组中有两个1,但我们只应返回不同的数对的数量。
示例 2:
输入:[1, 2, 3, 4, 5], k = 1
输出: 4
解释: 数组中有四个 1-diff 数对, (1, 2), (2, 3)... |
0b6edadb30fe0d0ac4d7036baf25d8aa2b48d504 | cylinder-lee-cn/LeetCode | /LeetCode/66.py | 1,660 | 3.96875 | 4 | """
66. 加一
给定一个非负整数组成的非空数组,在该数的基础上加一,返回一个新的数组。
最高位数字存放在数组的首位, 数组中每个元素只存储一个数字。
你可以假设除了整数 0 之外,这个整数不会以零开头。
示例 1:
输入: [1,2,3]
输出: [1,2,4]
解释: 输入数组表示数字 123。
示例 2:
输入: [4,3,2,1]
输出: [4,3,2,2]
解释: 输入数组表示数字 4321。
"""
class Solution:
def plusOne(self, digits):
"""
:type digits... |
8bd7f0c881b93d5836a57cca17561cefed3ab1de | cylinder-lee-cn/LeetCode | /LeetCode/75.py | 1,700 | 4.28125 | 4 | """
75. 颜色分类
给定一个包含红色、白色和蓝色,一共 n 个元素的数组,原地对它们进行排序,
使得相同颜色的元素相邻,并按照红色、白色、蓝色顺序排列。
此题中,我们使用整数 0、 1 和 2 分别表示红色、白色和蓝色。
注意:
不能使用代码库中的排序函数来解决这道题。
示例:
输入: [2,0,2,1,1,0]
输出: [0,0,1,1,2,2]
进阶:
一个直观的解决方案是使用计数排序的两趟扫描算法。
首先,迭代计算出0、1 和 2 元素的个数,然后按照0、1、2的排序,重写当前数组。
你能想出一个仅使用常数空间的一趟扫描算法吗?
"""
class Solutio... |
f0e7e7fa4be74ba0829f5673113d47a64830e02e | cylinder-lee-cn/LeetCode | /LeetCode/581.py | 1,616 | 3.640625 | 4 | """
581. 最短无序连续子数组
给定一个整数数组,你需要寻找一个连续的子数组,如果对这个子数组进行升序排序,那么整个数组都会变为升序排序。
你找到的子数组应是最短的,请输出它的长度。
示例 1:
输入: [2, 6, 4, 8, 10, 9, 15]
输出: 5
解释: 你只需要对 [6, 4, 8, 10, 9] 进行升序排序,那么整个表都会变为升序排序。
说明 :
输入的数组长度范围在 [1, 10,000]。
输入的数组可能包含重复元素 ,所以升序的意思是<=。
"""
class Solution:
def findUnsortedSubarray(se... |
41ac18f36c12aa738d6b0f95623e527187c88319 | cylinder-lee-cn/LeetCode | /LeetCode/326.py | 1,353 | 4.03125 | 4 | """
326. 3的幂
给定一个整数,写一个函数来判断它是否是 3 的幂次方。
示例 1:
输入: 27
输出: true
示例 2:
输入: 0
输出: false
示例 3:
输入: 9
输出: true
示例 4:
输入: 45
输出: false
进阶:
你能不使用循环或者递归来完成本题吗?
"""
class Solution:
def isPowerOfThree(self, n):
"""
:type n: int
:rtype: bool
"""
... |
729f6372d40053d8d5c64a42e4817befc1568ef3 | cylinder-lee-cn/LeetCode | /LeetCode/594.py | 1,211 | 3.625 | 4 | """
594. 最长和谐子序列
和谐数组是指一个数组里元素的最大值和最小值之间的差别正好是1。
现在,给定一个整数数组,你需要在所有可能的子序列中找到最长的和谐子序列的长度。
示例 1:
输入: [1,3,2,2,5,2,3,7]
输出: 5
原因: 最长的和谐数组是:[3,2,2,2,3].
说明: 输入的数组长度最大不超过20,000.
"""
class Solution:
def findLHS(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
... |
dbc3acaf053025fb9caf83a33c3db6b424632719 | cylinder-lee-cn/LeetCode | /LeetCode/648.py | 1,541 | 4 | 4 | """
648. 单词替换
在英语中,我们有一个叫做 词根(root)的概念,它可以跟着其他一些词组成另一个较长的单词——我们称这个词为
继承词(successor)。例如,词根an,跟随着单词 other(其他),可以形成新的单词 another(另一个)。
现在,给定一个由许多词根组成的词典和一个句子。你需要将句子中的所有继承词用词根替换掉。
如果继承词有许多可以形成它的词根,则用最短的词根替换它。
你需要输出替换之后的句子。
示例 1:
输入: dict(词典) = ["cat", "bat", "rat"]
sentence(句子) = "the cattle was rattled b... |
fa615ed874262b048932f6e66a36c78114365ff4 | cylinder-lee-cn/LeetCode | /LeetCode/448.py | 2,057 | 3.6875 | 4 | """
448. 找到所有数组中消失的数字
给定一个范围在 1 ≤ a[i] ≤ n ( n = 数组大小 ) 的 整型数组,数组中的元素一些出现了两次,另一些只出现一次。
找到所有在 [1, n] 范围之间没有出现在数组中的数字。
您能在不使用额外空间且时间复杂度为O(n)的情况下完成这个任务吗? 你可以假定返回的数组不算在额外空间内。
示例:
输入:
[4,3,2,7,8,2,3,1]
输出:
[5,6]
"""
class Solution:
def findDisappearedNumbers(self, nums):
"""
:type ... |
b8a9793d228c4d34d48b28d6d86c402270de4ace | cylinder-lee-cn/LeetCode | /LeetCode/384.py | 1,519 | 4.28125 | 4 | """
384. 打乱数组
打乱一个没有重复元素的数组。
示例:
// 以数字集合 1, 2 和 3 初始化数组。
int[] nums = {1,2,3};
Solution solution = new Solution(nums);
// 打乱数组 [1,2,3] 并返回结果。任何 [1,2,3]的排列返回的概率应该相同。
solution.shuffle();
// 重设数组到它的初始状态[1,2,3]。
solution.reset();
// 随机返回数组[1,2,3]打乱后的结果。
solution.shuffle();
"""
import random
... |
6140d410e7091956e4ae5c7d42f438843ac972b7 | cylinder-lee-cn/LeetCode | /LeetCode/344.py | 507 | 4.3125 | 4 | """
344. 反转字符串
编写一个函数,其作用是将输入的字符串反转过来。
示例 1:
输入: "hello"
输出: "olleh"
示例 2:
输入: "A man, a plan, a canal: Panama"
输出: "amanaP :lanac a ,nalp a ,nam A"
"""
class Solution:
def reverseString(self, s):
"""
:type s: str
:rtype: str
"""
return s[::-1]
... |
6c9dcae483bbb28c0deb224f0a166c0eb7fd8697 | cylinder-lee-cn/LeetCode | /LeetCode/187.py | 1,407 | 3.75 | 4 | """
187. 重复的DNA序列
所有 DNA 由一系列缩写为 A,C,G 和 T 的核苷酸组成,例如:“ACGAATTCCG”。
在研究 DNA 时,识别 DNA 中的重复序列有时会对研究非常有帮助。
编写一个函数来查找 DNA 分子中所有出现超多一次的10个字母长的序列(子串)。
示例:
输入: s = "AAAAACCCCCAAAAACCCCCCAAAAAGGGTTT"
输出: ["AAAAACCCCC", "CCCCCAAAAA"]
"""
class Solution:
def findRepeatedDnaSequences(self, s):
"""
... |
a012a2254bf132917c05470cbba7e0e7e58aa997 | cylinder-lee-cn/LeetCode | /LeetCode/206.py | 1,126 | 4.15625 | 4 | """
206. 反转链表
反转一个单链表。
示例:
输入: 1->2->3->4->5->NULL
输出: 5->4->3->2->1->NULL
进阶:
你可以迭代或递归地反转链表。你能否用两种方法解决这道题?
"""
# Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def reverseList(self, head):
... |
40dc401e3a5503eadeac9ea5c0ab59fb6b0c9b34 | cylinder-lee-cn/LeetCode | /LeetCode/970.py | 2,392 | 4.09375 | 4 | """
970. 强整数
给定两个非负整数 x 和 y,如果某一整数等于 x^i + y^j,其中整数 i >= 0 且 j >= 0,
那么我们认为该整数是一个强整数。
返回值小于或等于 bound 的所有强整数组成的列表。
你可以按任何顺序返回答案。在你的回答中,每个值最多出现一次。
示例 1:
输入:x = 2, y = 3, bound = 10
输出:[2,3,4,5,7,9,10]
解释:
2 = 2^0 + 3^0
3 = 2^1 + 3^0
4 = 2^0 + 3^1
5 = 2^1 + 3^1
7 = 2^2 + 3^1
9 = 2^3 + 3^0
10 = 2^0 + ... |
54dc735d569e57a8866fcae50dfc75254dabde04 | cylinder-lee-cn/LeetCode | /LeetCode/876.py | 2,078 | 4.21875 | 4 | """
876. 链表的中间结点
给定一个带有头结点 head 的非空单链表,返回链表的中间结点。
如果有两个中间结点,则返回第二个中间结点。
示例 1:
输入:[1,2,3,4,5]
输出:此列表中的结点 3 (序列化形式:[3,4,5])
返回的结点值为 3 。 (测评系统对该结点序列化表述是 [3,4,5])。
注意,我们返回了一个 ListNode 类型的对象 ans,这样:
ans.val = 3, ans.next.val = 4, ans.next.next.val = 5, 以及 ans.next.next.next = NULL.
示例 2:
输入:[1,2,3,4,5... |
1d35d4415a85356bf5670594fa331f08020a47a6 | cylinder-lee-cn/LeetCode | /LeetCode/925.py | 2,162 | 4.09375 | 4 | """
925. 长按键入
你的朋友正在使用键盘输入他的名字 name。偶尔,在键入字符 c 时,按键可能会被长按,而字符可能被输入 1 次或多次。
你将会检查键盘输入的字符 typed。如果它对应的可能是你的朋友的名字(其中一些字符可能被长按),那么就返回 True。
示例 1:
输入:name = "alex", typed = "aaleex"
输出:true
解释:'alex' 中的 'a' 和 'e' 被长按。
示例 2:
输入:name = "saeed", typed = "ssaaedd"
输出:false
解释:'e' 一定需要被键入两次,但在 typed 的输出中不是这样。
... |
9ae48945e29033f0e4d653152f2f43f81b605d39 | cylinder-lee-cn/LeetCode | /LeetCode/35.py | 1,517 | 4.03125 | 4 | """
35. 搜索插入位置
给定一个排序数组和一个目标值,在数组中找到目标值,并返回其索引。如果目标值不存在于数组中,返回它将会被按顺序插入的位置。
你可以假设数组中无重复元素。
示例 1:
输入: [1,3,5,6], 5
输出: 2
示例 2:
输入: [1,3,5,6], 2
输出: 1
示例 3:
输入: [1,3,5,6], 7
输出: 4
示例 4:
输入: [1,3,5,6], 0
输出: 0
"""
class Solution:
def searchInsert(self, nums, target):
"""
... |
31199be0e0349f61fe8df709be933f29da645805 | cylinder-lee-cn/LeetCode | /LeetCode/144.py | 819 | 4.125 | 4 | """
144. 二叉树的前序遍历
给定一个二叉树,返回它的 前序 遍历。
示例:
输入: [1,null,2,3]
1
\
2
/
3
输出: [1,2,3]
进阶: 递归算法很简单,你可以通过迭代算法完成吗?
"""
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = No... |
9df1f48a0ea57ba83fec89396f2dfe593fd14b70 | cylinder-lee-cn/LeetCode | /LeetCode/744.py | 1,659 | 4.0625 | 4 | """
744. 寻找比目标字母大的最小字母
给定一个只包含小写字母的有序数组letters 和一个目标字母 target,寻找有序数组里面比目标字母大的最小字母。
数组里字母的顺序是循环的。举个例子,如果目标字母target = 'z' 并且有序数组为 letters = ['a', 'b'],则答案返回 'a'。
示例:
输入:
letters = ["c", "f", "j"]
target = "a"
输出: "c"
输入:
letters = ["c", "f", "j"]
target = "c"
输出: "f"
输入:
letters = ["c", "f", "j"]
t... |
9d557f02cbbfaa882e68b2e617d6f8a09992460a | cylinder-lee-cn/LeetCode | /LeetCode/151.py | 1,100 | 4.3125 | 4 | """
151. 翻转字符串里的单词
给定一个字符串,逐个翻转字符串中的每个单词。
示例:
输入: "the sky is blue",
输出: "blue is sky the".
说明:
无空格字符构成一个单词。
输入字符串可以在前面或者后面包含多余的空格,但是反转后的字符不能包括。
如果两个单词间有多余的空格,将反转后单词间的空格减少到只含一个。
进阶: 请选用C语言的用户尝试使用 O(1) 空间复杂度的原地解法。
"""
class Solution(object):
def reverseWords(self, s):
"""
:... |
ba05240853d5865e4a57d9593bd3bcdf97696bb7 | run-fourest-run/IteratorProtocol | /realpythonitertools/itertoolsintro.py | 539 | 4.1875 | 4 | '''itertools is a module that implements a number of iterator building blocks. Functions in itertools operate
on iterators to produce more complex iterators'''
test_list_0 = [95000,95000,95000,95000]
test_list_1 = [117000,117000,121000,120000]
test_list_2 = ['alex','joe','anthony','david']
'''zip example'''
def see_... |
e0d48e5df6768de714b9928cc4853cb92b121535 | run-fourest-run/IteratorProtocol | /itertoolsdocs/chain.py | 720 | 4.1875 | 4 | import itertools
'''
Make an iterator that returns elements from the first iterable until its exhausted. Then proceed to the next
iterable, until all the iterables are exhausted.
Used for treating consecutive sequences as a single sequence
'''
def chain(*iterables):
for it in iterables:
for element in ... |
e804cd98a5a395a108abc6cd83fd2f25108e97d9 | ganeshprasad21/projects | /image steganography file/main.py | 6,324 | 3.84375 | 4 | from PIL import Image # import image class from Pillow lib
def main():
modes = int(input("""
image steganography python pillow
*******************************************************************************************************
enter 1 )for encoding 8bit rgb png image with extension ("save... |
62ee32cfabd691dbb67300b8baa5f702840d195c | nikhil7913/Lab-4 | /9.py | 300 | 3.859375 | 4 | import string
def stringoperation():
myfile = open("words.txt","r")
punct = string.punctuation
for my in myfile:
my = my.strip()
my = my.replace(" ","")
for c in punct:
my = my.replace(c,"")
my = my.lower()
print(my)
stringoperation()
|
ec7199c351470743b5ead5d6639229d283ecfca7 | bc-uw/IntroPython2016 | /students/bc-uw/session04/trigram.py | 949 | 4.125 | 4 | """
Trigram lab attempt.
Version0.I don't understand what this is supposed to do
"""
import sys
import string
import random
def sourceFile_to_list(input_file):
"""
list comprehension to iterate through source file lines
and add them to textlist
"""
with open(input_file) as f:
textlist = [... |
74a1819636a0e95fa2c93b7a5f7b3e4e1b19e61d | Nordeast/webscraper | /profile.py | 492 | 3.734375 | 4 | from datetime import datetime
program_start_time = datetime.now()
def start():
program_start_time = datetime.now()
def end():
# print how long the program took to run
program_duration = datetime.now() - program_start_time
seconds = program_duration.seconds
hours, remainder = divmod(seconds, 3600)... |
94080eb749fd62c33b0fef435618996608dbf1b2 | handabo/web-spider | /代码/17-zhengze.py | 1,490 | 3.875 | 4 | import re
'''
string = 'i love you very love much'
pattern = re.compile(r'love')
匹配失败返回None
ret = pattern.match(string)
ret = pattern.search(string)
ret = pattern.findall(string)
print(ret)
得到匹配的内容, 只匹配一个,成功立马结束
print(ret.group())
print(ret.span())
'''
'''
# (1)子模式
string = '哈哈<div><span>天青色等烟雨,而我在等你</span></div>嘻嘻... |
fb20ed648a414e4e07031963002e1c3658529aa7 | yangrsdt/yrs_git_space | /Python/regular/regulat_expression.py | 1,180 | 3.703125 | 4 | #!/usr/bin/python
# coding = utf8
# import re
#
# print("请输入")
# test = input()
# if re.match(r"[0-9a-zA-Z\_]+",test):
# print("发邮件")
# else:
# print("格式错误")
from datetime import datetime,timedelta,timezone
import re
def to_stamp(str,utc_str):
t = datetime.strptime(str, "%Y-%m-%d %H:%M:%S")
r = re.co... |
074a50627efab5706821ef2b6271f2b7d9bb71d6 | ShwetaD123/MyPythonDOC | /classmethod.py | 1,888 | 3.78125 | 4 |
class Fullname(object):
def __init__(self,fname,mname,lname):
print('---Inside Constructor --',)
self.firstName = fname
self.lastName = lname
self.middleName = mname
print('First Name --',fname)
print('Middle Name --',lname)
print('Last Name --',mname)
... |
acffb02c3da756efe8eeec8bcf429b54de563e8c | ShwetaD123/MyPythonDOC | /Factorial.py | 1,356 | 4 | 4 |
''' With recurtion function '''
def fact(n):
if n==1:
return n
else :
return n*fact(n-1)
# print(fact(10))
''' With IF Else statement '''
'''
def facto(num):
factorial = 1
if num<0:
print('Factoraial is not found for negative number :',num)
elif num == 0:
... |
51ebba152b36845ef192e0132dedbf0956bc90e8 | rvillebro/machine-learning | /src/machinelearning/networks/layers/layers.py | 5,224 | 3.859375 | 4 | #!/usr/bin/env python3
from machinelearning.networks.activation_functions import ActivationFunction, ReLU
import numpy as np
from numpy import random
class Layer():
"""
Superclass for all layers. Used for defining which methods must be implemented when implementing a new layer.
"""
def __init_subclass... |
56849cd93b3b468be4a71a3a86949b9f7d03d605 | rvillebro/machine-learning | /src/machinelearning/networks/utils.py | 277 | 3.625 | 4 | #!/bin/python
import numpy as np
import random
def shuffle(x, y):
tmp = list(zip(x, y))
random.shuffle(tmp)
x, y = zip(*tmp)
def batch(x, y, batch_size=10):
for i in range(0, x.shape[0], batch_size):
yield (x[i:i + batch_size], y[i:i + batch_size])
|
4fd901a647843480a401ae52f9b5dc2039d7e423 | AmritaMathuriya/Class2019 | /Python/NestedLoops/insertionSortInnerLoop.py | 362 | 3.921875 | 4 | def swap (p1, p2, list1):
temp = list1[p1]
list1[p1] = list1[p2]
list1[p2] = temp
list1 = [2, 3, 4, 10, 12, 1]
len1 = len(list1)
last = list1[len1-1]
lastPos = len1-1
print (list1)
print ("")
for i in range ( len1-2, -1, -1 ):
if list1[i] > last :
swap ( i, lastPos, list1 )
lastP... |
3cfadcc193c8b420ef8065a933d2b17ec9f733d3 | AmritaMathuriya/Class2019 | /Python/NestedLoops/insertionSort.py | 508 | 3.671875 | 4 | def swap (p1, p2, listC):
temp = listC[p1]
listC[p1] = listC[p2]
listC[p2] = temp
def funInner (listC, lastPos):
last = listC[lastPos]
for i in range ( lastPos-1, -1, -1 ):
if listC[i] > last :
swap ( i, lastPos, listC )
lastPos = i
print (listC)... |
6412b189ea6ec330de201b602745e98dcb81a031 | AmritaMathuriya/Class2019 | /Python/WhileLoop/compareWhileForLoops.py | 118 | 3.59375 | 4 |
N = 5
start = 0
for i in range (start,N):
print i
print ()
j = start
while ( j < N ):
print j
j = j+1
|
3a56ed7a7835895a8f511e7083e0b0a49dbdba98 | AmritaMathuriya/Class2019 | /Python/ForLoopExamples/searchStr.py | 274 | 3.96875 | 4 | st1 = "This is an orange "
words = st1.split()
len1 = len(words)
s_word = "is"
foundIt = False
for i in range ( len1 ):
if s_word == words[i]:
print "Found it at: ", i, " ", words[i]
foundIt = True
if foundIt == False:
print "Couldn't find it."
|
a657b581b83914e035255baac0589926c356155d | AmritaMathuriya/Class2019 | /Python/FileRead/wc.py | 403 | 3.953125 | 4 | fileName = "in.txt"
file = open ( fileName, "r" )
data = file.readlines()
print data
numWords = 0
numLines = 0
numChars = 0
for line in data:
numLines += 1
#print line
words = line.split()
numWords += len(words)
for word in words:
numChars += len(word)
print "Number of lines: ", numLine... |
ee8dcb494ecb50f3ffcc8d3faabf436b9bc949b8 | AmritaMathuriya/Class2019 | /Python/seriesSum/seriesSumForLoop.py | 139 | 4 | 4 | num = input("Enter number: ")
num = int(num)
sum1 = 0.0
for i in range ( 1, num+1 ):
frac = 1.0/i
sum1 = sum1 + frac
print sum1
|
d7b5f4ae9a9fd970f4015ccf43a335886880f51e | AmritaMathuriya/Class2019 | /Python/NestedLoops/printSent.py | 200 | 3.78125 | 4 |
st1 = "This is an orange "
words = st1.split()
print words
len1 = len(words)
print len1
for i in range(len1) :
str = ""
for j in range(i+1):
str = str + words[j] + " "
print str
|
d3df1ddc0ae1ece648d8dfa603239a62c4f8421b | AmritaMathuriya/Class2019 | /Python/NestedLoops/sorting2.py | 522 | 3.75 | 4 | numberList = [3, 1, 21, 4, 65, 7, 43, 8]
print (numberList)
num = len(numberList)
for i in range (0,num):
for x in range (i+1, num):
# compare and swap, if number at i is greater than number at x
if(numberList[i] > numberList[x]):
print ("Switching: ", numberList[i], numberList[x])
... |
13988f040592cffdcd58cfef223f8699682be501 | AmritaMathuriya/Class2019 | /Python/Recurssion/Fibnoccci/fibnoacci.py | 631 | 3.625 | 4 |
def fun_fib(N, list1):
if ( N <= 2 ):
return 1, list1
fib_N_1, list1 = fun_fib(N-1, list1)
fib_N_2 = list1[len(list1)-2]
fib_N = fib_N_2 + fib_N_1
list1.append(fib_N)
return fib_N, list1
def main():
fIn = open("input.txt", "r")
fOut = open ("output.txt", "w")
... |
5ae959107523ab20f35367c35471f19b4d6cf31f | Jazende/ProjectEuler | /solved/000-099/problem_019.py | 251 | 3.703125 | 4 | from datetime import date
count = 0
for month in range(1,13):
for year in range(1901, 2001):
try:
if date(year, month, 1).weekday() == 6:
count += 1
except ValueError as e:
pass
print(count)
|
8b073624d1f28b1d73c532137ca2e9195008f275 | Jazende/ProjectEuler | /solved/000-099/problem_063.py | 740 | 3.546875 | 4 | from math import log10
from math import log
from math import ceil
from math import floor
def problem_63():
min_ = 2
def power_of(power):
# log a (x) = q <-> a ^ q = x
min_value = 10**(power-1)
min_range = floor(min_value**(1/power))
# max_range is altijd 10, 10**x => x+1 digits ... |
a225c7f36ae4bbd017c46a320c99645746fad324 | Jazende/ProjectEuler | /solved/000-099/problem_007.py | 638 | 3.78125 | 4 | def problem_7(number=10001):
"""
By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13,
we can see that the 6th prime is 13.
What is the 10 001st prime number?
"""
from itertools import count
primes = [2]
for x in count(3, step=2):
counter = 0
for y in primes:
... |
ede77fdc9218e1f2aed4a4eb7f0de3bad6d6a115 | Jazende/ProjectEuler | /solved/000-099/problem_038.py | 1,397 | 4 | 4 | ##Take the number 192 and multiply it by each of 1, 2, and 3:
##
##192 × 1 = 192
##192 × 2 = 384
##192 × 3 = 576
##
##By concatenating each product we get the 1 to 9 pandigital, 192384576.
##We will call 192384576 the concatenated product of 192 and (1,2,3)
##
##The same can be achieved by starting with 9 and multiply... |
2bf23b619c66640db6b5d464358a3c644af1b96e | Jazende/ProjectEuler | /solved/000-099/problem_003.py | 688 | 3.875 | 4 | def problem_3(number=600851475143):
"""Problem 3
The prime factors of 13195 are 5, 7, 13 and 29.
What is the largest prime factor of the number 600851475143 ?
"""
import time
factors = []
start = 2
start_time = time.clock()
while True:
while True:
if number % star... |
12795b4f2991e974e106efd83cf154979c898299 | Jazende/ProjectEuler | /solved/100-199/problem_120.py | 597 | 3.53125 | 4 | import cProfile
min_a = 3
max_a = 1000
def square_reminder(a, n):
sq = a**2
sub = a-1
sup = a+1
first = 1
second = 1
for x in range(n):
first = (first * sub) % sq
second = (second * sup) % sq
return (first + second) % sq
# sum of all [max square remainder for 1 -> 2a+3 (pe... |
8f995f5ec8b53e07ea81997683fb7acd957a5acc | naymajahan/Object-Oriented-programming1 | /python-regular-method.py | 979 | 4.34375 | 4 | #### object oriented programming in python
class StoryBook:
def __init__(self, name, price, authorName, authorBorne, no_of_pages):
# setting the instance variables here
self.name = name
self.price = price
self.authorName = authorName
self.authorBorne = authorBorne
s... |
c8a9155ec68f09763e64a3bfd39474dfcf2d4d6b | AkashSolankle/Intresting-Programs-in-Python | /assertion.py | 348 | 4.09375 | 4 | Assertions are statements that assert or state a fact confidently in your program. For example, while writing a division function, you're confident the divisor shouldn't be zero, you assert divisor is not equal to zero.
def avg(marks):
assert len(marks) != 0
return sum(marks)/len(marks)
mark1 = []
print("Ave... |
163e740bfcd5763ca0f9f683f05b85be0d7abad8 | muhamedparic/RIM1 | /MMS/LV1/zad1.py | 543 | 4.0625 | 4 | import random
def bubble_sort(array):
for i in range(len(array) - 1):
for j in range(len(array) - 1, i, -1):
if array[j - 1] < array[j]:
array[j - 1], array[j] = array[j], array[j - 1]
def test():
n = 100
size_interval = (1, 100)
for i in range(n):
array = ... |
c4e43081f6c1c1954fafa271a8ffb378643bb3a2 | muhamedparic/RIM1 | /MMS/LV1/zad2.py | 287 | 3.5 | 4 | import math
def max_na_intervalu(f, a, b, step):
cur_max = f(a)
a += step
while a <= b:
cur_max = max(cur_max, f(a))
a += step
return cur_max
print(max_na_intervalu(lambda x: x**2, -8, 9, 1))
print(max_na_intervalu(math.sin, -math.pi, math.pi, 0.001))
|
97624e7c388f57b06d6ffb6c8383d7806393ca59 | Raj-Kumar2208/Recursion-and-BackTracking | /movement in Array.py | 1,042 | 3.546875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon Oct 7 00:44:25 2019
@author: raj.kumar2208@yahoo.in
"""
import numpy as np
def basic_constraints(x):
if ((x < N) & (x >= 0)):
return True
else:
return False
def start_solution(array,M,t):
if((M==0)&(t!=N-1)):
return False... |
9cb7c56d1c30a9c93f7952580cdf91132568701f | selik/dict-grouping | /grouping.py | 725 | 3.640625 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
'''
Rough implementation for the proposed ``dict.grouping``.
'''
from itertools import groupby
def grouping(iterable, key=None):
'''
Group elements of an iterable into a dict of lists.
The ``key`` is a function computing a key value for each element.
Each key corre... |
11f91606c5c98d0823e87e258e21dfcc03ce4c4b | Brandon205/python-game | /game.py | 1,624 | 3.9375 | 4 | # HANGMAN GAME
import random
words = ['Hello', 'Hangman', 'Word', 'Stuff']
string = random.choice(words)
# print(string)
# show = ['_'] * len(string)
# show = ''.join(show)
# print(show)
# print(string)
show_string = string
for char in string:
if char == ' ':
show_string = show_string.replace(char, ' ')
else:... |
a2fcdc266ce38afb83ae49d9a1e079789b47e126 | felipedc09/evaluador-expresiones-2 | /utilidades.py | 764 | 3.625 | 4 | import csv
def readFileCsv(fileName):
elements = []
try:
with open(fileName) as File:
reader = csv.reader(File, delimiter=';')
for row in reader:
elements.append(row)
finally:
File.close()
return elements
def readLinesFile(fileName):
elemen... |
d7c1a5433f8affbeaaaf7108ea3e2db1ee939b82 | GareArc/ML_Coursera_python | /ex2/ex2.py | 1,844 | 3.640625 | 4 | import numpy as np
import costFunction
import plotData
import gradientDescent
import plotDecisionBoundary
import scipy.optimize as op
import matplotlib.pyplot as plt
import sys
sys.path.append("..")
from Utils import loadData
plt.clf() # 清图。
plt.cla() # 清坐标轴。
plt.close("all") # 关窗口
# ============================== 1... |
637df16ea5718f62d0e0fc3ac2bb817f4bfb4755 | GareArc/ML_Coursera_python | /ex2/mapFeature.py | 413 | 3.609375 | 4 | import numpy as np
# return [ x1,x1*x2 ... ] the 27-dimension vector, ignore 1
def map_feature(x1, x2):
m = x1.shape[0]
result = np.zeros((m, 27))
x1 = x1.reshape((-1, 1))
x2 = x2.reshape((-1, 1))
end = 0
for i in range(1, 7):
for j in range(0, i+1):
result[:, end] = np.mul... |
64931a200be3bdd140999859055951e3c2dc0322 | StephanRaab/Tkinter_practice | /notepadLookAlike.py | 635 | 3.6875 | 4 | from Tkinter import *
def doNothing():
print("Don't do anything!")
def quitProgram():
print("You quit the program :(")
root = Tk()
menu = Menu(root)
root.config(menu=menu)
subMenu = Menu(menu)
menu.add_cascade(label='File', menu=subMenu)
subMenu.add_command(label='New Project', command=doNothing)
subMenu.a... |
1209248b8f13267be74fcf3312dff27070649729 | lucasmoeskops/advent-of-code | /2018/day01/program.py | 569 | 3.640625 | 4 | from itertools import accumulate, cycle
from sys import argv
frequencies = tuple(map(int, open(argv[1], 'r').read().split('\n')[:-1]))
# Part 1
answer1 = sum(frequencies)
print('Frequency sum is: {}'.format(answer1))
# Part 2
seen = {0}
answer2 = None
generator = accumulate(cycle(frequencies))
while True:
n... |
80f2a5fea7fe9faa3047771d89fff5ab358fc38b | mpharsha26/face_smile_Detection | /faceRecognition.py | 1,434 | 3.6875 | 4 | #we use OpenCV library for this face recognition
import cv2
#loading the cascades (series of filters to detect our face and eyes)
face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
eye_cascade = cv2.CascadeClassifier('haarcascade_eye.xml')
#func to detect the face and the eyes given the inpu... |
e7349965dd5a5618ebb221e0f5be8109dd5559ab | AdidasOriginals/python-practice | /basic/test-027.py | 1,189 | 3.578125 | 4 | #!/usr/bin/env python
# _*_ coding: utf-8 _*_
# @Time : 2021/1/14 11:38
# @Author : Edison
# @Version:V 0.1
# @File : test-027.py
# @desc :用Python读写CSV文件
print('-' * 20, '将数据写入CSV文件', '-' * 20)
import csv
import random
with open('data/scores.csv', 'w', encoding='utf-8') as file:
writer = csv.writer(file)
# de... |
61dc8f0340ca74c0e931fdece584ffb302250015 | AdidasOriginals/python-practice | /basic_02/basic_04.py | 10,325 | 3.84375 | 4 | #!/usr/bin/env python
# _*_ coding: utf-8 _*_
# @Time : 2021/2/5 16:04
# @Author : Edison
# @Version:V 0.1
# @File : basic_04.py
# @desc : 面向对象相关知识
print('工资结算系统'.center(50, '*'))
"""
月薪结算系统 - 部门经理每月15000 程序员每小时200 销售员1800底薪加销售额5%提成
"""
from abc import ABCMeta, abstractmethod
class Employee(metaclass=ABCMeta):
... |
b9e77744cbaebdba17f37da1b05e557eca254760 | AdidasOriginals/python-practice | /basic_02/basic_01.py | 4,350 | 3.75 | 4 | #!/usr/bin/env python
# _*_ coding: utf-8 _*_
# @Time : 2021/2/3 14:17
# @Author : Edison
# @Version:V 0.1
# @File : basic_01.py
# @desc :重要知识点
print('生成式(推导式)的用法'.center(50, '*'))
# 生成式(推导式)可以用来生成列表、集合和字典
prices = {
'AAPL': 191.88,
'GOOG': 1186.96,
'IBM': 149.24,
'ORCL': 48.44,
'ACN': 166.89,
... |
a51e6285858feaee4d7f934ac159ba4cd6eca1c8 | AdidasOriginals/python-practice | /basic_02/basic_05.py | 1,786 | 3.984375 | 4 | #!/usr/bin/env python
# _*_ coding: utf-8 _*_
# @Time : 2021/2/8 17:19
# @Author : Edison
# @Version:V 0.1
# @File : basic_05.py
# @desc : 迭代器和生成器
print('迭代器和生成器'.center(50, '*'))
print('迭代器'.center(50, '-'))
class Fib(object):
"""迭代器"""
def __init__(self, num):
self.num = num
self.a, self.... |
6dbb1cdb44fb11da6c20a4413fe390048c8b1ab8 | AdidasOriginals/python-practice | /basic_02/basic_03.py | 4,198 | 3.515625 | 4 | #!/usr/bin/env python
# _*_ coding: utf-8 _*_
# @Time : 2021/2/5 11:25
# @Author : Edison
# @Version:V 0.1
# @File : basic_03.py
# @desc : 函数的使用方式
print('高阶函数的用法(filter、map以及它们的替代品)'.center(50, '*'))
items1 = list(map(lambda x: x ** 2, filter(lambda x: x % 2, range(1, 10))))
print(items1)
# x%2 取余结果为0是false,所以[1, 3, ... |
ec6db6a91a1a90534380dbc3d19f166aee116f2f | jkim614/math-around-the-world | /src/AnswerTypein.py | 2,171 | 3.59375 | 4 | import pygame as pg
class AnswerTypein(pg.sprite.Sprite):
'''
The sprite in this class displays the answer typed
by the user
'''
def __init__(self, text_color=(33,206,153), bg_color=(214,213,183,100)):
pg.sprite.Sprite.__init__(self)
self.text_color = text_color
... |
760ffd797ddaf3e62611383e521bf6b398b8c0f6 | biridora/AImath | /AIMath/AImath06.py | 459 | 3.921875 | 4 | # -*- coding: utf-8 -*-
import numpy as np
import matplotlib.pyplot as plt
#y=sinx,y=cosxを実装
def my_sin(x):
return np.sin(x) # sin(x)
def my_cos(x):
return np.cos(x) # cos(x)
x = np.linspace(-np.pi,np.pi) #-πからπ(ラジアン)までの範囲
y_sin = my_sin(x)
y_cos = my_cos(x)
plt.plot(x,y_sin,label="sin")
plt.plot... |
5538f73e7b253b86f6facae747633cc590f433f6 | Firesean/TicTacToe | /TicyTacyToey.py | 2,372 | 3.828125 | 4 | import Player as player
class TicTacToe:
def __init__(self, players=[player.Player("X"), player.Player("O")], board_size=3, in_a_row=3):
self.board = []
self.players = players
self.in_a_row = in_a_row
self.board_size = board_size
# Main
self.current_player = self.pla... |
4cefe976178ca70327602a12328420bd485b2762 | renhongjie/NLP_old | /2numpy.py | 725 | 3.625 | 4 | import numpy as np
mylist=[1,2,3,4,5]
length=len(mylist)
a=10
#list转为矩阵
mymatrix=np.mat(mylist)
#list乘10是重复十次
print(a*mylist)
#矩阵乘法
print(a*mymatrix)
print(type(mylist),type(mymatrix))
#0矩阵
myZero=np.zeros([3,5])
print(myZero)
#1矩阵
myOne=np.ones([5,3])
print(myOne)
#随机矩阵
myRandom=np.random.rand(3,4)
print(myRandom)
#单位... |
4dab3896a64d748746f02ada127472da61721f46 | sanskardudhe09/PPL-Assignment | /PPLAssignment6 shapesmethods.py | 1,683 | 4.0625 | 4 | import math
from math import pi
class Shape:
def __init__(self, name):
self.name = name
def area(self):
pass
def fact(self):
return "I am 2 dimensional shape"
def __str__(self):
return self.name
class Square(Shape):
def __init__(self, length):
sup... |
96aeb7637335059503a278a8704171b6d2f1c7f6 | ssjsndk/pre-education | /quiz/pre_python_02.py | 738 | 4.03125 | 4 | """"2.if문을 이용해 첫번째와 두번 수, 연산기호를 입력하게 하여 계산값이 나오는 계산기를 만드시오
예시
<입력>
첫 번째 수를 입력하세요 : 10
두 번째 수를 입력하세요 : 15
어떤 연산을 하실 건가요? : *
<출력>
150
"""
x = input("첫 번째 수를 입력하세요 : ")
y = input("두 번째 수를 입력하세요 : ")
o = input("어떤 연산을 하실 건가요? : ")
r = None
if o == "+":
r = int(x) + int(y)
elif o == "-":
r = int(x) - int(y)
el... |
aa57cec70292efce7d47d01da2010000ed6f6600 | gsagingaliyeva/gsagingaliyeva.github.io | /FizzBuzz.py | 273 | 3.90625 | 4 | def fizzbuzz():
n=1
while n<1000:
if n%3==0 and n%5==0:
print ("fizzbuzz")
elif n%3==0:
print ("fizz")
elif n%5==0:
print ("buzz")
else:
print (n)
n=n+1
|
752cd493edac4ad35a04b1ce29c7b9449fe6d797 | tarabrosnan/hearmecode | /lesson04/lesson04_events_deduplicate.py | 986 | 4.125 | 4 | # Challenge level: Beginner
# Scenario: You have two files containing a list of email addresses of people who attended your events.
# File 1: People who attended your Film Screening event
# https://github.com/shannonturner/python-lessons/blob/master/section_09_(functions)/film_screening_attendees.txt
#
# ... |
bf9889d74e7da620b29c157b4cdd7ccd91bcb3f8 | buptwxd2/data_structure | /test_NN.py | 8,731 | 3.859375 | 4 | import numpy as np
from sklearn.utils import resample
import matplotlib.pyplot as plt
class Node:
"""
Methods:
forward
backward
Attributes:
gradient
inputs
outputs
"""
def __init__(self, name='', inputs=[]):
self.name = name
self.inputs = inpu... |
7584ec3831aa6222f6bcd2fcfc8e23f4f1454df1 | buptwxd2/data_structure | /array.py | 1,547 | 3.953125 | 4 | # 顺序存储线性表 using python array/list
from array import *
def my_insert(arr, i, value):
original_length = len(arr)
if i > len(arr):
print("")
return None
# add a new element size first
arr.append(None)
idx = original_length - 1
while idx >= i:
arr[idx+1] = arr[idx]
... |
1ee80e54eb16ef1eedf6894998beb62a582f7cf0 | buptwxd2/data_structure | /40_intro_to_dp/knapsack_problem.py | 922 | 3.96875 | 4 | # 用memory + 回溯来解决0-1背包问题
items = [2, 2, 4, 6, 3]
max_weight = 9 # capacity
total_num = len(items)
max_weight_to_store = 0
# add memory
mem = [False] * total_num
mem = [mem for _ in range(max_weight)]
def knapsack_problem(i, current_weight): # going to handle the i-th (starting from zero) item
glo... |
62516a70779b9fcdec76f7ac19977a868820ea27 | darpit-choudhary/Snake-Game | /snake.py | 4,558 | 3.703125 | 4 | import pygame
import time
import random
#initialize the python modules
pygame.init()
#define colors
blue = (0,0,255)
red = (255,0,0)
bg_color = (0,204,106)
green = (255,255,0)
black = (0,0,0)
yellow = (0,255,255)
dis_width = 800
dis_height = 600
dis = pygame.display.set_mode((dis_width, d... |
1e31df19e2c17d58b7fd1ff4db0f4890332e05de | abhishektuf/learning | /age_calculator.py | 733 | 4.09375 | 4 | from datetime import datetime,timedelta,date
from dateutil.relativedelta import relativedelta
birthday_input = input('Your birthday please [dd/mm/yyyy]: ')
def agecalc(birthday):
birthday_date = datetime.strptime(birthday,'%d/%m/%Y')
today = date.today()
rdelta = relativedelta(today, birthday_date)
# m... |
929516b1361dfd48d1d165ab0475a4d0d849edd5 | MalgorzataBlaszczak/Warsztat_1 | /exercise_2.py | 2,219 | 3.578125 | 4 | # czy wprowadzony ciąg znakówjest poprawną liczbą
# czy użytkownik nie wpisał tej liczby już poprzednia
# czy liczba należy do zakresu 1 - 49
#
#
# liczby_uzytkownika = []
# try:
# while len(liczby_uzytkownika) <= 6:
#
# liczba = int(input("Podaj liczbę: "))
# except ValueError:
# print("Takich rzeczy ... |
3b50e9eb168075eb3aea43d8a75418171b5347c2 | HenriqueCostaSI/Python | /reversed.py | 908 | 4.59375 | 5 | """
Reversed-> Inverter o Interável
Obs: Não confunda com reverse() de listas
A função retorna um List Reverse Iterator
"""
# Exemplos
lista = [1, 2, 3, 4, 5]
res = reversed(lista)
# Lista
print(list(reversed(lista)))
# Tupla
print(tuple(reversed(lista)))
# Conjunto
print(set(reversed(lista))) # Em conjunto n... |
aae91a00e84efddf7be4fdb7194b73e9a4d0100f | HenriqueCostaSI/Python | /modulo_random.py | 2,681 | 4.125 | 4 | """
Módulo Random e o que são módulos?
- Em Python, módulos são outros arquivos Python.
Módulo Random -> Possui várias funções para geração de números pseudo-aleatório.
"""
# OBS: Existem duas formas de se utilizar um módulo ou função desempacotamento
# Forma 1 - Importando todo o módulo (Não recomendado).
from ... |
fdad87ebcc7a3644e7715817fead3af699d47543 | HenriqueCostaSI/Python | /Ordered_dict.py | 605 | 4.1875 | 4 |
"""
Ordered Dict
# Em um dicionário a ordem de inderção dos elemtos não é garantida
dict = {'a':1, 'b':2, 'c':3, 'd':4, 'e':5, 'f':6}
for chave, valor in dict.items():
print(f'chave={chave}:valor={valor}')
"""
# Importando
from collections import OrderedDict
dic = orderedDict({'a': 1, 'b': 2, 'c': 3, 'd': 4,... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.