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 |
|---|---|---|---|---|---|---|
cc726350a1aeb82295bc788c582fc1b2164faed3 | mindful-ai/28092020LVC | /day_02/labs/lab_01.py | 660 | 4.1875 | 4 | # -------------------------------------------------
# LAB 1
# -------------------------------------------------
L = ['red', 'red', 'green', 'blue', 'orange']
# Removed one red: ['red', 'green', 'blue', 'orange']
L.remove('red')
# 'golden' was added: ['red', 'green', 'blue', 'orange', 'golden']
L.append('go... |
ecaf58ae492a1655d764d35ffebf3c8430905a61 | mindful-ai/28092020LVC | /day_02/labs/lab_02_alternate_pythonic.py | 365 | 4.25 | 4 | # -------------------------------------------------
# LAB 2 - Determine if a number is prime or not
# -------------------------------------------------
# input
n = int(input('Enter a number: '))
# process
for i in range(2, n):
if(n % i == 0):
print('The number is not prime')
break... |
0b67dc3efcb4978ad4635dc6a7e371ea7d0c1bff | arihantb2/dynamic_programming | /memoization/fib.py | 376 | 3.640625 | 4 | # n = fibonacci series index
#
# Brute force:
# time : O()
# space: O()
#
# Memoized:
# time : O()
# space: O()
def fib(n, memo={}):
if n in memo:
return memo[n]
if n <= 2:
return 1
memo[n] = fib(n-1, memo) + fib(n-2, memo)
return memo[n]
if __name__ == '__main__':
print(fib(6))... |
470faa2737760adfe82637a868ad6cc0242fab7e | arihantb2/dynamic_programming | /tabulation/grid_traveler.py | 662 | 3.515625 | 4 | import numpy as np
# m = number of rows
# n = number of cols
# Time : O(m * n)
# Space: O(m * n)
def grid_treveler(m, n):
table = np.zeros((m + 1, n + 1), dtype=int)
table[1, 1] = 1
for i in range(0, m+1):
for j in range(0, n+1):
curr = table[i, j]
if i + 1 <= m:
... |
6720500fb751b9fabd7374f241ec19432158081f | dushyantsapra/Algorithms | /org/ds/sortingAndSearching/Sorting.py | 4,490 | 3.953125 | 4 |
class Sorting:
@staticmethod
def insertionSort(tempList):
tempValue = 0
for iValue in range(len(tempList)):
tempValue = iValue
for jValue in reversed(range(iValue)):
if tempList[tempValue] < tempList[jValue]:
tempList[tempValue], tempL... |
745500e7f9e4f9fd5e3f0bd8f266e98ce4513365 | dushyantsapra/Algorithms | /org/ds/tree/Trie.py | 4,385 | 3.578125 | 4 | '''
Created on Jul 26, 2016
@author: Dushyant Sapra
'''
class Trie:
def __init__(self, isEndOfWord):
self.charMap = {};
self.isEndOfWord = isEndOfWord;
def insert(self, word):
if word[0] in self.charMap:
if len(word) == 1:
self.charMap[word[0]].isEndOfWord ... |
d607a2b02547ae284fd1e7d7ea643c62a12645c4 | dushyantsapra/Algorithms | /org/ds/arrays/SubArrayWithMaximumSum.py | 1,000 | 3.515625 | 4 | '''
Created on Aug 14, 2017
@author: xdussap
'''
def sub_array_with_max_sum(inp_arr):
max_i = 0
max_j = 0
curr_i = 0
curr_j = 0
max_so_far = inp_arr[0]
curr_max = inp_arr[0]
arr_size = len(inp_arr)
for index in range(1, arr_size):
if inp_arr[index] > max_so_far +... |
6b0a0aa267e56742b19200b66dc781f39e2ed58d | dushyantsapra/Algorithms | /org/ds/linkedList/CircularLinkedList.py | 2,548 | 3.59375 | 4 | '''
Created on Jun 29, 2016
@author: Dushyant Sapra
'''
from org.ds.linkedList.SinglyLinkedNode import SinglyLinkedNode
class CircularLinkedList:
def __init__(self):
self.head = None;
self.tail = None;
self.length = 0;
def add(self, data):
node = SinglyLinkedNode(data);
... |
457cfc8adfe5f3e256d4bdee9b8279073f17fca8 | Oliver-sumo-sudo/Olivers-Dark-corner | /Rando code/The_Bank.py | 693 | 3.546875 | 4 | import json
def login(users):
uN = input("Name: ")
pW = input("Password: ")
if uN in users:
if pW == users[uN]:
print("Welcome back.")
else:
print("Incorrect password.")
return False
else:
print("Hello, new person.")
users[uN] = pW
... |
54e0b14da3745b6e8986746191c7a2fa2551d3e5 | himank254/pythongames | /snake.py | 3,922 | 3.71875 | 4 | import turtle
import time
import random
delay = 0.15
score = 0
high_score = 0
#Set up screen
wn = turtle.Screen()
wn.title("VINTAGE Snake Game")
wn.setup(width=600, height=600)
wn.bgcolor("green")
wn.tracer(0) #turns off screen updates
#Make snake head
head = turtle.Turtle()
head.speed(0)
head.sh... |
b4d7abeb7470255c43a96dc3001865a627c4178d | LucienKoot/pythonproject1 | /whileloop wijnkelder.py | 159 | 3.625 | 4 | # whilel loop, per 3 laten tellen
wijnkelder = 0
while(wijnkelder<30):
print('Aantal flessen: ', wijnkelder)
wijnkelder = wijnkelder + 3
|
4b5349a3dc166059b547cd05617ca755930693a4 | LucienKoot/pythonproject1 | /whilelloop teller2.py | 203 | 3.78125 | 4 | # whilel loop, teller
teller = 6
while (teller < 5):
print("Kleiner dan:", teller)
teller = teller + 1
if teller == 5 :
print("Gelijk aan:", teller)
elif teller > 5:
print("Groter dan: 5")
|
b1a404998e7c7867520db2f3c0bb41b53c62615b | LucienKoot/pythonproject1 | /classes.py | 722 | 3.671875 | 4 | class Hout:
"Deze class bevat alle eigenschappen van onze houtsoorten"
aantHout = 0
def __init__(self, naam, gewicht, lengte, breedte):
self.naam = naam
self.gewicht = gewicht
self.lengte = lengte
self.breedte = breedte
Hout.aantHout += 1
def displayCount(se... |
bb023dfb9addee809a0c50198632e3d10f5ffecb | AlfredodlRC/github-upload | /ejercicio3.py | 260 | 4.125 | 4 | print("Desea continuar:")
entrada=input()
if entrada == "no" or entrada =="n":
print("Saliendo")
elif entrada =="si" or entrada =="s":
print("continuando")
print("Completado!")
else:
print("Por favor la proxima vez conteste con si o no")
|
16a16d3f85a35b8794d9053ace4fee2d7ad85ced | AlfredodlRC/github-upload | /bifurcacion.py | 174 | 3.671875 | 4 | valor ='711'
if valor =='7':
print("el valor es 7")
elif valor == '71':
print("el valor es 71")
else:
print("el valor no es 7 ni 71")
print("programa realizado") |
e2c25aebaa06682cdb20f8c31670e03241bde131 | gadolinis/Basic_exercises | /The Hangman game.py | 903 | 3.84375 | 4 | import random
word_file = "Random words"
WORDS = open(word_file).read().splitlines()
wordW = random.choice(WORDS)
word = wordW.lower()
length = len(word)
wordl = str("_" * length)
print(" ".join(wordl))
z = input("Please enter the letter: ")
x = z.lower()
print(x)
i = 10
while i != 0:
i = i - 1 #i -... |
5cca04aa0d808fab47ebf9abedef1d779310e06c | SandeepB70/Blackjack | /hand.py | 1,566 | 4.0625 | 4 | class Hand:
'''
Represents a hand that can be held by a player or dealer.
Attributes:
cards: The hand of cards the player has. Each card is an object of the Card class.
total: How much the hand is currently worth.
ace_11: The number of aces being counted as 11.
'''
def __in... |
70dbef3e266ee7b61417b37099278c4d0cc0a3f7 | QAQUQvQ/Learn_Python | /learn/basic/start.py | 2,579 | 4.21875 | 4 | #!/usr/bin/python3
print("看到我了吗?")
# 第一种注释
'''
第二种注释
第二种注释
'''
"""
第三种注释
第三种注释
"""
print('上面的都没有执行。')
if True:
print("True")
else:
print("False")
word = '字符串'
sentence = "这是一个句子。"
paragraph = """这是一个段落,
可以由多行组成"""
str = 'Runoob'
print(str) # 输出字符串
print(str[0:-1]) # 输出第一个到倒数第二个的所有字符
print(str[0]) # 输出字... |
67cafd6b9ff81e39dc12d94ae632c86aa2888959 | 3rror/computer-vision-project | /Sudoku/sudoku.py | 2,635 | 3.546875 | 4 | import pathlib
import sys
import cv2
import numpy as np
if len(sys.argv) > 2:
input_image_path = sys.argv[1]
output_image_path = sys.argv[2]
else:
program_dir = pathlib.Path(__file__).parent.resolve()
input_image_path = str(program_dir / "sudoku.png")
output_image_path = str(program_dir / "output.... |
04ede030c0a067ae5fa8c2901c34ce0930b91057 | dedekinds/pyleetcode | /438_Find All Anagrams in a String_easy.py | 1,398 | 3.78125 | 4 | '''
438. Find All Anagrams in a String
2017.12.26
'''
最下面写的是一个暴力O(mn)的算法,下面的这个是O(n)的算法
import collections
class Solution:
def findAnagrams(self, s, p):
"""
:type s: str
:type p: str
:rtype: List[int]
"""
res = []
left = right = 0
... |
47a6031058541497fa8a64ca0f7940201efaf526 | dedekinds/pyleetcode | /784_Letter Case Permutation_medium.py | 523 | 3.640625 | 4 | '''
784. Letter Case Permutation
2018.2.22
'''
class Solution(object):
def letterCasePermutation(self, S):
"""
:type S: str
:rtype: List[str]
"""
#temp.isalpha() 方法检测字符串是否只由字母组成。
if not S:return [S]
temp=self.letterCasePermutation(S[1:])
i... |
5581b4248c693213ccebf36fcadaf49ba05f76b9 | dedekinds/pyleetcode | /base_datastructure/二分.py | 311 | 3.984375 | 4 | def binsearch(nums,target):
left = 0
right = len(nums)-1
while left <= right:
mid = (left + right)>>1
print(mid)
if nums[mid] > target:
right = mid - 1
elif nums[mid] < target:
left = mid + 1
else:
return mid
return -1
|
f03a04009b09371b4b4f6649e118c372db3d39c0 | dedekinds/pyleetcode | /151_Reverse Words in a String_medium.py | 262 | 3.859375 | 4 | '''151. Reverse Words in a String
2017.7.26
'''
class Solution(object):
def reverseWords(self, s):
"""
:type s: str
:rtype: str
"""
temp=s.split()
temp.reverse()
return ' '.join(temp) |
4279d53104172daa756fc4ca7bebae63324939d3 | dedekinds/pyleetcode | /637_Average of Levels in Binary Tree _easy.py | 812 | 3.703125 | 4 |
'''637. Average of Levels in Binary Tree
2017.7.20
'''
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
用层次遍历,其中中途用个新的tempQ代替一层的所有结点
class Solution(object):
def averageOfLevels... |
7b604a2c58b9252aed961df44dcfb218cf2b3480 | dedekinds/pyleetcode | /442_Find All Duplicates in an Array_medium.py | 1,089 | 3.703125 | 4 | '''442. Find All Duplicates in an Array
2017.9.30
'''
——————————————————————————————————————————————————
实际上就是字母统计,采用常规-1交换法,无额外空间+O(n)居然被长样例TLE了
class Solution(object):
def findDuplicates(self, nums):
"""
:type nums: List[int]
:rtype: List[int]
"""
if len(... |
eabbe413e84fa5607228d676e79b4b8c991ea3dc | dedekinds/pyleetcode | /565_Array Nesting_medium.py | 662 | 3.5625 | 4 | '''
565. Array Nesting
2018.2.2
'''
class Solution:
def arrayNesting(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
#遍历每一个点,访问过就变成-1,然后计算最长的圈
def findcircle(index):
cnt=0
while nums[index]>=0:
cnt+=1
... |
12353fdc6b9a37f66c28d50dad97c982ef981e31 | dedekinds/pyleetcode | /633_Sum of Square Numbers _easy.py | 1,199 | 4.0625 | 4 | '''633. Sum of Square Numbers
2017.7.3
'''
神器:math.sqrt(121).is_integer()
_______________
import math
class Solution(object):
def judgeSquareSum(self, c):
for a in range(1+int(math.sqrt(c))):
temp=c-a*a
if abs(math.sqrt(temp)-int(math.sqrt(temp)+0.5))<0.000001:#完全卡这个... |
8b63fda04c98c3b20c7c4f9f52724deb739772d5 | dedekinds/pyleetcode | /993. Cousins in Binary Tree_easy.py | 1,341 | 3.765625 | 4 | # Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def isCousins(self, root, x, y):
"""
:type root: TreeNode
:type x: int
:type y: int
... |
578b4118ab4e3a35abafb1be28d507bee8210e03 | dedekinds/pyleetcode | /337_House Robber III_medium.py | 755 | 3.671875 | 4 | '''
337. House Robber III
2018.3.8
'''
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def rob(self, root):
"""
:type root: TreeNode
... |
01fc23bc1d5c5ca6f84e75c78d4da0d7342fb2f1 | dedekinds/pyleetcode | /109_ Convert Sorted List to Binary Search Tree _medium.py | 2,052 | 3.953125 | 4 | '''109. Convert Sorted List to Binary Search Tree
2017.8.20
'''
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# ... |
1b3d5b3264512a890098a48a1bd4b0409a13d970 | dedekinds/pyleetcode | /342_Power of Four_easy.py | 1,520 | 3.9375 | 4 | '''342. Power of Four
2017.6.15
'''
______________________
数值方法:
import math
class Solution(object):
def isPowerOfFour(self, n):
"""
:type num: int
:rtype: bool
"""
if n<=0:
return False
else:
temp=int(0.5+math.log(n,4))
... |
0e5abecc788c64b05d906f9f0a6c99dd87941a3b | dedekinds/pyleetcode | /1014. Capacity To Ship Packages Within D Days_medium.py | 1,137 | 3.6875 | 4 |
最小的最大重量肯定在 max(weights)和 sum(weights)之间,对它进行二分
class Solution(object):
def check(self,weights,limit):
nums = 0
ans = []
tempsum =0
length = len(weights)
i = 0
while i<length:
tempsum += weights[i]
if tempsum > limit:
ans.appen... |
8ac01d708714839ca1b49c0468fdf67e2a1b27db | dedekinds/pyleetcode | /350_Intersection of Two Arrays II_easy.py | 659 | 3.671875 | 4 | '''
350. Intersection of Two Arrays II
2017.11.23
'''
用hash表来记录元的数量,暴力,实际上也就是O(max(m,n))
import collections
class Solution:
def intersect(self, nums1, nums2):
"""
:type nums1: List[int]
:type nums2: List[int]
:rtype: List[int]
"""
if len(nums1)>len(nums2... |
82518092e34735e77b67ba9e9fa9e1db3e60e958 | dedekinds/pyleetcode | /459_Repeated Substring Pattern_easy.py | 511 | 3.578125 | 4 |
'''
459. Repeated Substring Pattern
2017.12.15
'''
看自己的博客
class Solution:
def repeatedSubstringPattern(self, s):
"""
:type s: str
:rtype: bool
"""
temp=s*2
return temp[1:-1].find(s)!=-1
'''
#O(n)
for x in range(int(l... |
655f4230fb240cf9fc3057606a4eda5d8ca3fada | dedekinds/pyleetcode | /861_Score After Flipping Matrix_medium.py | 1,657 | 4 | 4 | 纯贪心了一下,首先看第一列1的个数是否超过一半,如果超过了,那么就不管,否则就对第0行进行一个操作
然后用行操作将第0列全部变为1,然后后面呢就怼不超过一半1的列做操作
但是为什么能成功呢?2^n > 2^ n−1+2^ n−2+⋯+2^0
class Solution:
def get_col(self,A,col):
check_col_sum = 0
n = len(A)
for i in range(n):
check_col_sum += A[i][col]
return check_col_sum >= (n+1)/2
... |
3905ab034867db2d909a682ca7465fe8467b23dd | dedekinds/pyleetcode | /A_jzoffer/字符串的排列.py | 708 | 3.78125 | 4 | 有必要最后sorted吗?
# -*- coding:utf-8 -*-
class Solution:
def finpermutation(self,s,res,ptr):
if ptr == len(s):
candi = ''.join(s)
if candi not in res:
res.append(''.join(s))
for i in range(ptr,len(s)):
temp = s[ptr]
s[ptr] = s[i]
... |
367855f914d147f47f535356659e5d120f87bfb1 | dedekinds/pyleetcode | /A_jzoffer/二叉搜索树的后续遍历序列.py | 1,010 | 3.875 | 4 |
首先是后序遍历,所以最后一个值是根节点,此时,由于是二叉搜索树,所以左子树的值都比右子树的值要小,我们找到
左右子树,然后判断一下右子树是不是都大于根节点(左子树不用判断因为在找左子树的时候已经判断了)
然后递归判断左子树和右子树满足不满足就好了
# -*- coding:utf-8 -*-
class Solution:
def VerifySquenceOfBST(self, sequence):
# write code here
if len(sequence) <= 0:
return False
root = sequence[-1]
... |
1387b71cf652b1cbd25211647724c33d5a281a06 | dedekinds/pyleetcode | /988. Smallest String Starting From Leaf_medium.py | 924 | 3.765625 | 4 | # Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
从叶子开始合并,一直到最上面
class Solution(object):
def smallestFromLeaf(self, root):
"""
:type root: TreeNode
:rtype: str
"""
... |
145d81d592b902481b81c7e6de19a48f5bdc44ba | dedekinds/pyleetcode | /257_Binary Tree Paths_easy.py | 829 | 4.0625 | 4 | '''
257. Binary Tree Paths
2017.12.9
'''
深度优先搜索
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def binaryTreePaths(self, root):
"""
:type root: TreeNode... |
19fe2b1a744a9fc989c60296d65bf98df8af207c | dedekinds/pyleetcode | /523_Continuous Subarray Sum_medium.py | 1,730 | 3.703125 | 4 | '''523. Continuous Subarray Sum
2017.9.14
'''
数论的一个很常规的做法,对前i个数求和取模k
若存在两个前i,j个数的和同余,那么作减法即得到连续的数之和能被k整除
反过来,也成立,是充要的
class Solution(object):
def checkSubarraySum(self, nums, k):
if k==5:
if nums==[5,2,4]:
return False#特判定
if len(nums)==1:
... |
072cb645d9826a768ac025912688d05148639d4b | dedekinds/pyleetcode | /290_Word Pattern_easy.py | 844 | 3.703125 | 4 | '''
290. Word Pattern
2018.1.22
'''
和同构字符串那题一样,构造单射满射即可
class Solution(object):
def wordPattern(self, pattern, S):
"""
:type pattern: str
:type str: str
:rtype: bool
"""
s=S.split()
if len(pattern)*len(s)==0:
return False
i... |
f61099e6eb43a59dbca43ab5feb439c36d2c5ed1 | dedekinds/pyleetcode | /617_Merge Two Binary Trees_easy.py | 2,487 | 4 | 4 | '''617. Merge Two Binary Trees
2017.7.25
'''
#思路先是计算高度,然后层次遍历
def height(tree):
if tree==None:
return 0
return max(height(tree.left),height(tree.right))+1
class Solution(object):
def mergeTrees(self, t1, t2):
tree_height=max(height(t1),height(t2))
#解决空树的情况
... |
91e8ea35519c3b2d1512ae1b7fdd853351c595dc | dedekinds/pyleetcode | /136_Single Number_easy.py | 903 | 3.609375 | 4 | '''136 Single Number
2017.5.17
162ms
beats 1.50%
'''
class Solution(object):
def singleNumber(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
#统计一个数组的元素出现次数,查一查
temp=sorted(nums)
temp.append('A')
print(temp)
for... |
b6645952b6b8e1628a94d802062c77b95e20a333 | dedekinds/pyleetcode | /345_Reverse Vowels of a String_easy.py | 644 | 3.71875 | 4 |
'''
345. Reverse Vowels of a String
2017.12.21
'''
前后双指针
class Solution:
def reverseVowels(self, S):
#[a.] [b.]失败
length=len(S)
left=0
right=length-1
vowels=['a','e','i','o','u','A','E','I','O','U']
s=list(S)
while True:
while left... |
855951af96243c0cc63ed55b522e35210620f152 | ChelseaTolnai/Data-Structures | /doubly_linked_list/doubly_linked_list.py | 8,206 | 4.34375 | 4 | """Each ListNode holds a reference to its previous node
as well as its next node in the List."""
class ListNode:
def __init__(self, value, prev=None, next=None):
self.value = value
self.prev = prev
self.next = next
"""Wrap the given value in a ListNode and insert it
after this node. Note that this no... |
57f38e0b112037b40e7fdce23d24617ad5d2085a | raunit-x/Labs | /Cryptography codes/ElgamalEncryption.py | 1,852 | 3.546875 | 4 | import os
import random
def generate_prime_number(prime_bit_length='512'):
command_line_key = os.popen('openssl prime -generate -bits ' + prime_bit_length).readlines()
return int(command_line_key[0].rstrip('\n'))
def fast_exponentiation(a, b, n):
if b == 0:
return 1 if a else 0
temp = fast_e... |
baaa2d040b2f7adf5342d95d8f09b34de03d1610 | raunit-x/Labs | /Multimedia Lab codes/LZW/LZW.py | 1,145 | 3.765625 | 4 | def compress(text, initial_dict):
i, index, curr_index, curr_string, result = 0, max(len(initial_dict) - 1, 0), 1, '', []
entries = initial_dict
while i < len(text):
flag = False
while curr_string in entries:
curr_index = entries[curr_string]
curr_string += text[i]
... |
775b78b734e95c5cb3eb5158c9f62ec26b060f89 | bitsar/python-ml-tutorial | /stats.py | 1,113 | 3.765625 | 4 | import numpy
from statistics import mean
import matplotlib.pyplot
from matplotlib import style
style.use('ggplot')
# Define NumPy arrays and explicitly bind dataTypes
xs = numpy.array([1,2,3,4,5], dtype=numpy.float64)
ys = numpy.array([5,4,6,5,6], dtype=numpy.float64)
# Calculate regression
# Calculate mean of xs ar... |
5eea12122a9ff7e636d3e6e6d7c81eff21adaa5a | RachelKolk/Intro-Python-I | /src/lists.py | 808 | 4.3125 | 4 | # For the exercise, look up the methods and functions that are available for use
# with Python lists.
x = [1, 2, 3]
y = [8, 9, 10]
# For the following, DO NOT USE AN ASSIGNMENT (=).
# Change x so that it is [1, 2, 3, 4]
# YOUR CODE HERE
x.append(4)
print(x)
# Using y, change x so that it is [1, 2, 3, 4, 8, 9, 10]
... |
2c3c351b3b34a0a6435c80d36ba1cea9ad45a37d | TechInTech/pCode | /pHashTable/hashtable.py | 4,049 | 3.65625 | 4 | """
File: hashtable.py
Description: This file implements the class hashtable and some test functions as auxliary
Author: Larry Yu
Initiated Data: Jan 2nd, 2019
"""
from pArray.arrays import Array
class HashTable(object):
"""
To represent HashTable
"""
#Class Variables
EMPTY = None
... |
59feffd2431fb5023dd5f3f9683c24e36b30083d | TechInTech/pCode | /pArrayList/arraylist.py | 2,481 | 4.03125 | 4 | #!/usr/bin/python3
#-*-coding:utf-8-*-
"""
File: arraylist.py
Description: This file defines the class array list
Author: Larry Yu
Initial Date: Dec 3rd, 2018
"""
import sys
sys.path.append("/mnt/d/repo/pCode")
from pArray.arrays import Array
from pArray.arraylistiterator import ArrayListIterator
from pAb... |
4f3c2ce409feec3a78909f831e2d22f290379d49 | TechInTech/pCode | /pLinkedList/linkedlist.py | 3,796 | 3.890625 | 4 | #!/usr/bin/python3
#-*-coding:utf-8-*-
"""
File: linkedlist.py
Description: This file defines the class linkedlist
Author: Larry Yu
Initial Date: Dec 3rd, 2018
"""
import sys
sys.path.append("/mnt/d/repo/pCode")
from pAbstractlist.abstractlist import AbstractList
from pTwoWayNode.twoWayNode import TwoWayNo... |
03c37402c52ed5f5692bd79b6bb67e0725982418 | Raul-lozano/TRABAJO-DE-INVESTIGACI-N | /Lista.py | 981 | 3.8125 | 4 | class Lista():
def _init_(self,lista=[]):
self.li = lista
def presentarLista(self):
for item in self.li:
print(item)
def buscarLista(self,valor):
for item in self.li:
if valor == item:
print(i... |
351e1043c5261fde44557d9f0cdd679fcbfe6ca4 | Svetlanamsv/paried_number_1 | /main.py | 157 | 3.984375 | 4 | print("Input number: ", end="\n")
number=int(input())
if number%2==0:
print("Number",number,"is paried")
else:
print("Number",number,"is no paried")
|
f73825065f2bd67c2b36947b143ebe90a9ec2ce1 | Elisenochka/.vscode | /classes.py | 1,207 | 4.21875 | 4 | numbers = [1, 2]
# Class: blueprint for creating new objects
# Object: instance of a class
#Class: Human
# Objects: John, Mary, Jack
class Point:
default_color = "red"
def __init__(self, x, y):
self.x = x
self.y = y
def draw(self):
print(f"Point ({self.x},{self.y})")
def __... |
0f65a069cd882e3aac41649d09c1adbfe901a479 | vskemp/2019-11-function-demo | /list_intro.py | 2,910 | 4.65625 | 5 | # *******How do I define a list?
grocery_list = ["eggs", "milk", "bread"]
# *******How do I get the length of a list?
len(grocery_list)
# ******How do I access a single item in a list?
grocery_list[1]
# 'milk'
grocery_list[0]
# 'eggs'
#Python indexes start at 0
# ******How do I add stuff to a list?
grocery_list.appe... |
e6b63d631c4bcffa4e4df98b77c0e29236752198 | psanogo/marco-polo-cli | /cli.py | 574 | 3.78125 | 4 | #!/usr/bin/env python
import click
def marco(name):
if name == "Marco":
return "Polo"
return "No!"
@click.command()
@click.option(
"--name",
prompt="Pass in a name",
help="This is the name you pass into the Marco Polo function",
)
def func(name):
"""A command-line tool that accepts a n... |
64741797976bac3520bd16fc6f76391b3d16dc1b | marcopaglio/AlberoRicoprenteMinimo | /UnionFind.py | 2,317 | 3.515625 | 4 | from LinkedList import *
class UnionFind():
def __init__(self):
self.collection = [] ###insieme di insiemi (liste linkate) della union-find###
self.delegates = {} ####per avere i rappresentatnti delle liste a tempo costante li tengo in memeoria###
###... |
a24468a6f969152c8796b75ff1ea747116b52b08 | guscerin/Curso-de-Introduccion-a-Machine-Learning | /ejercicio 5.py | 572 | 3.734375 | 4 | def g(pesos, a, b):
salida = (pesos[0] + pesos[1]*a + pesos[2]*b)
if salida < 0:
return 0
else:
return 1
if __name__ == '__main__':
a = [0,0,1,1]
b = [0,1,0,1]
pesos_or = [-10,20,20]
pesos_and = [-30,20,20]
salida_or = []
salida_and = []
for i in range(len(a)):
... |
d7cb166dfe3ff68f47a9be3f3588684072dc2855 | brokkoligirl/kimtweets | /tweet_grabber.py | 4,623 | 3.609375 | 4 | import GetOldTweets3 as Got3
import csv
import datetime
import pandas as pd
import tweepy
import configparser
def grab_all_tweets(usr_name, n, filename, mode='w', date_since=None):
"""
returns a csv file with the n most recent tweets of a twitter user
:param usr_name: twitter user name whose tweets are ... |
622a0e8d01d5b4e4ea9c19a079f2f51565c0c6de | djnugent/AccessPlusAutomator | /AccessPlusAutomator/Course.py | 599 | 3.71875 | 4 |
class Course():
def __init__(self, department, course, section = None, status = None):
self.department = department
self.course = course
self.section = section
self.status = status
def isEqual(self,other):
return (self.department == other.department and self.course == other.course and self.section =... |
596a742cc5fd7336602e6b2425e409311b2b935e | netashiloh/WorldOfGames | /GuessGame.py | 745 | 3.703125 | 4 | import random
from Helpers import in_range
def difficulty_level(difficulty):
return difficulty * 5
def generate_number(level):
return random.randrange(1, level+1)
def get_guess_from_user(level):
guess = input("Please choose a number between 1 to " + str(level) + ": ")
guess = in_range(guess, 1, le... |
81e42c23911fce65155e1da44ca35666e507bd6e | helaahma/python | /loops_task.py | 1,296 | 4.125 | 4 | #define an empty list which will hold our dictionary
list_items= []
#While loop, and the condition is True
while True:
#User 1st input
item= input ("Please enter \"done\" when finished or another item below: \n")
# Define a conditional statement to break at "Done" input
if item == "done" or item=="Done":
break... |
b55dfd6fe18a15149ff4befa6199165655c60011 | mspang/sprockets | /stl/levenshtein.py | 1,949 | 4.40625 | 4 | """Module for calculating the Levenshtein distance bewtween two strings."""
def closest_candidate(target, candidates):
"""Returns the candidate that most closely matches |target|."""
return min(candidates, key=lambda candidate: distance(target, candidate))
def distance(a, b):
"""Returns the case-insensitive Le... |
708d793321ac26deedbbe9cc617ed73c2838bbdf | Jmusi/leetcode-python | /9isPalindrome.py | 606 | 3.984375 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Created by cheng on 2020/12/27
# Solution:
def isPalindrome(x):
str_x=str(x)
left,right=0,len(str_x)-1
while left<right:
if str_x[left]!=str_x[right]:
return False
left+=1
right-=1
return True
def isPalindromev2(x):
... |
10a45de86530806609dbb912500bc6c86e3d1ee4 | RamonAsuncion/pi-camera | /camera.py | 781 | 3.609375 | 4 | from datetime import datetime
from gpiozero import Button
from time import sleep
import picamera
# Connected to GPIO14 pin on the rasberry pi
button = Button(14)
running = True
def timestamp():
# Gets the date and time.
timestamp = datetime.now()
# Saves the file name as "picture + (date and time) + png"... |
a68213b4a02f49a61a98276f169bfd6adcd8b482 | ahmadianlab/tc-gan | /tc_gan/utils/sign_change.py | 1,161 | 3.71875 | 4 | import numpy
def sign_changings(data):
"""
Calculate indices of sign-changing locations in 1D array `data`.
aka zero-crossing
>>> # * * * * # changes
>>> # 0 1 2 3 4 5 6 7 8 # index
>>> data = [1, 2, 0, -3, -4, 7, 8, -2, 1]
>>> sign_changin... |
e61b7a2c4dac185c59714b50f77bcfdc4b5f6ccb | a2606844292/test | /北京图灵学院习题课/面向对象/demo2.py | 469 | 4.0625 | 4 | import random
#定义一个变量用于存取初始分数
while 1:
num = input('输入1,2,3三个数字:')
if num =='-1':
break
rand_num = random.randrange(1, 4)
num = int(num)
rand_num = int(rand_num)
source = 0
if num > rand_num:
print('输入的数比随机数大')
elif num == rand_num:
source += 100
print(... |
f7231c772008937caa8f7780154bacc5b40ad7ee | a2606844292/test | /北京图灵学院/opp/python10基础opp-抽象.py | 1,568 | 3.71875 | 4 | # 抽象
class Animel():
def sayhello(self):
pass
class dog(Animel):
print('闻一哈')
class Person(Animel):
def sayhello(self):
print('telling....')
d = dog()
d.sayhello()
xiaobai = Person()
xiaobai.sayhello()
# 抽象类的实现
import abc
# 声明一个类并且指定当前类的元类
class Human(metaclass=abc.ABCMeta):
... |
46673bb2e6a0aa8b4e96f49e9862a7164e53ea35 | a2606844292/test | /北京图灵学院习题课/课时58-66基础练习/09dict和set.py | 1,266 | 3.9375 | 4 | # 写一个程序来管理用于登陆系统的用户信息:登陆名字和密码。
# 登陆用户账号建立后,已存在用户可以用登陆名字和密码重返系统,
# 新用户不能用别人的用户名建立用户账号
# 模拟从数据库里取出来的用户名和密码
user_pass={'xiaobai':'123456','xiaoming':'654321'}
def create_user(username,password):
"""
username:用户建立账号的用户名
password:用户建立账号的密码
"""
# 判断 用户输入的账号是不是已经存在
usernames = user_pass.keys()
if... |
160dabebcdadfcc07ad73354c86b8882c7db988c | a2606844292/test | /北京图灵学院/内置结构/python10内置数据结构listdictset.py | 6,857 | 4.21875 | 4 | '''
关于元组的函数
以下看代码
以下函数,对list基本适用
'''
# len: 获取元组的长度
t = (1, 2, 3, 4, 5)
print(len(t))
# max,min最大值最小值
# 如果列表或元组中有多个最大最小值,则实际打印哪个
print(max(t))
print(min(t))
# tuple:转化或创建元组
l = [1, 2, 3, 4, 5]
t = tuple(l)
print(t)
t = tuple()
print(t)
'''
元组的函数¶
基本跟list通用
'''
# count:计算制定数据出现的次数
t = (2, 1, 2, 3, 45, 1, 1, 2)
pri... |
585ad05304b386c6f56ce1076780c7bb0447eb24 | a2606844292/test | /北京图灵学院习题课/课时58-66基础练习/05python运算符in和range.py | 1,075 | 3.703125 | 4 | # # 假设x=1,y=2,z=3,如何快速将三个变量的值相互交换
#
# x = 1
# y = 2
# z = 3
#
# print(x, y, z)
#
# x, y, z = z, x, y
# print(x, z, y)
#
# # 成员运算符in的用法
#
# ls = range(101)
# if 100 in ls:
# print(True)
# else:
# print(False)
#
# # range函数,输出0-10的数字,2是步长,输出结果是0,2,4.。。。。。
# ls = range(0, 10, 2)
# for i in ls:
# print(i)
#
# w... |
0f60378b6e4e6b791bf55d109db82d1a0a03ee2a | a2606844292/test | /北京图灵学院习题课/课时58-66基础练习/04基础.py | 571 | 3.53125 | 4 | # # 打印0-100的所有奇数
# for i in range(1,101):
# if i%2==1:
# print(i)
#
# #爱因斯坦曾出过一道有趣的数学题,有一个长梯阶,若每步上2阶,最后剩下2阶
# 若每步上5阶,最后剩4阶,若每步上6阶,最后剩下5阶,职业每步上7阶,最后刚好一阶不剩
x = 0
while x < 1000:
if (x % 2 == 1) \
and (x % 3 == 2) \
and (x % 5 == 4) \
and (x % 6 == 5) \
and (... |
5c900b62abd01b7ae701e7b0217ba24f10eb7ae9 | Oceane97440/Calculatrice_python | /button.py | 3,985 | 3.984375 | 4 | import tkinter as tk
# Set-up the window
window = tk.Tk()
window.title("Calulatrice")
# input chiffre 1
entry = tk.Entry()
entry.pack()
#lors du click sur le button + affectue addition
def touche_1_click():
num = 1
entry.insert(tk.END, num)
def touche_2_click():
num = 2
entry.insert(tk.END, num... |
3c78331ec43da30ffca6eb52a64be98211fe1ef4 | 19JIvan/2017-Year-10-Programming | /DoneForSchool/Dictionary.py | 503 | 3.578125 | 4 | list = []
list1 = []
D = open("Dictionary", "r")
Months = {}
for line in D:
line = line.strip('\n')
Month, Abbreviations = line.split(':')
Months[Month] = Abbreviations
#statename = input("Enter the name of the state: ")
#states[userinput] = statename
#print(states)
Userinput = inp... |
51b23940161748d54f6b12460e92c235e641396c | lanners-marshall/Sprint-Challenge--Data-Structures-Algorithms | /data_structures/ex1/binary_search_tree.py | 2,182 | 3.828125 | 4 | class BinarySearchTree:
def __init__(self, value):
self.value = value
self.left = None
self.right = None
def __str__(self):
return str(f'value: {self.value}, left {self.left}, right: {self.right}')
def depth_first_for_each(self, cb):
if self.left == None and self.right == None:
return c... |
6c94956a97ede642c6fbc3d66eefd147c8e31491 | group06-comparative-genomics/practical5 | /rndseq_modified.py | 406 | 3.78125 | 4 | #! /usr/bin/env python
"prints first argument aa sequences of length second argument to screen"
import random
import sys
number=int(sys.argv[1])#5320
length=int(sys.argv[2])#20
aas="ARNDCEQGHILKMFPSTWYV"
aa_dictionary={}
def r20():
return random.randrange(20)
id=0
for i in range(number):
s=""
for j in range... |
ca08b50b6f9aa72f31a99847437fb6199c1673ec | krhicks221/Logan-and-Kaytlyn | /Logan2.py | 155 | 4.125 | 4 | def numberfive():
n = int(input("Enter a number: "))
product = 1
while (n > 0):
product = product * n
n = n - 1
print("Your product is", product)
|
e2064d9111bc5b9d73aeaf79eb3b248c25552b54 | ash0x0/AUC-ProgrammingLanguagePython | /Assignment.1/Qa.py | 506 | 4.3125 | 4 | """This module received three numbers from the user, computes their sum and prints the sum to the screen"""
try:
# Attempt to get input and cast to proper numeric type float
x = float(input("First number: "))
y = float(input("Second number: "))
z = float(input("Third number: "))
except ValueError:
... |
1ea7e928f266a8d63ec7735333632901954a1dea | ash0x0/AUC-ProgrammingLanguagePython | /Assignment.1/Qf.py | 763 | 4.15625 | 4 | """This module receives a single number input from the user for a GPA and prints a message depending on the value"""
try:
# Attempt to get input and cast to proper numeric type float
x = float(input("GPA: "))
except ValueError:
# If cast fails print error message and exit with error code
print("Invalid... |
e6602f15842773fb74e7b883d4eceaeb84206a05 | stephenmbull/GetIncredibles | /problem2_shortest_path.py | 3,939 | 4.375 | 4 | #!/usr/bin/python
from __future__ import print_function # bring the print function from Python 3 into Python 2.6+
import csv
def shortest_path_shortcut(fname):
"""
Knowing what the data looks like and its pre-sorted order, we only need to
find the route with the longest distance and just start from the next ro... |
179d5d73c249b74a4056eaf0a6c1f9de6f4fc892 | AmandaMoen/StartingOutWPython-Chapter5 | /bug_collector.py | 1,141 | 4.1875 | 4 | # June 8th, 2010
# CS110
# Amanda L. Moen
# 1. Bug Collector
# A bug collector collects bugs every day for seven days. Write
# a program that keeps a running total of the number of bugs
# collected during the seven days. The loop should ask for the
# number of bugs collected for each day, and when the loop is
# finis... |
0f538e42c8ed0bba6c312469781f3bc9a00acd3b | dalek7/umbrella | /Python/UDPtest.py | 667 | 3.671875 | 4 | # UDP server example
import socket
import sys
server_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
if len(sys.argv) > 1:
port = int(sys.argv[1])
else:
port = 12345
server_socket.bind(("", port))
#http://stackoverflow.com/questions/166506/finding-local-ip-addresses-using-pythons-stdlib
prin... |
daaff1433424c3a617a364ec449a5ce95902c66d | sachdevavaibhav/python_practice_ex | /Customised-Dictionery/Exercise1.py | 322 | 3.625 | 4 | d1 = {"acquantince":"knowledge or experience of something",
"audacious":"showing a willingness to take surprisingly bold risks.",
"cartographer":"a person who draws or produces maps.",
"decorum":"behavior that is well-mannered"}
print("ENTER THE WORD")
var1 = input()
print("Meaning:",d1[var1])... |
31635b085596872dd221cb8913cc02be16be5482 | KantuAriastu/Discord-Bot | /test.py | 1,810 | 3.546875 | 4 | import re
from conversion import *
from random import choice
#interesting conversion
from operator import methodcaller
from random import choice
conversion_dict = {}
with open("conversionkey.txt", "r") as keys :
for lines in keys :
if lines[0] != "#":
name,factor = lines.split(",")
... |
36eac3e80744bd542e46fb65001d9b67bb2c16d3 | montoliu/locm_cec19 | /AlexStrategy/CoverLanes.py | 2,649 | 3.515625 | 4 |
# ------------------------------------------------------------
# Cover two lanes with guard
# ------------------------------------------------------------
class CoverLanes:
def __init__(self, state):
self.state = state
self.l_turn = []
self.get_turn()
def get_turn(self):
if s... |
51c89dbb57134ccc437b40c2c855d8c099927a04 | JannikScheuble/Roboter | /main.py | 4,952 | 3.578125 | 4 | #!/usr/bin/env python3
import robot_control as ctrl
from robot_ai_module import *
from board import *
from time import sleep
import ev3dev.ev3 as ev3
import copy as copy
from robot_control import *
def getOpponentInput(board):
while True:
row = 0
col = 0
# Try catch in case the user inputs a ... |
002b04f84639d3d24ea9d329bdb8847a0467a866 | apurvjain22/Section-8-Heroku | /models/item.py | 2,732 | 3.546875 | 4 | from codes.db import db
class ItemModel(db.Model): # extending to db.Model, which means we are mapping the objects(userModel & itemModel) with db
# it is creating a link b/w database and the objects.
__tablename__ = 'items' # telling sqlalchemy the table name for the ItemModel object
# creating columns w... |
2444b49346d063b9f1b677e5557aa8ca068e4793 | jdh747/xpython | /exercises/word-count/example.py | 429 | 3.59375 | 4 | from collections import Counter
# to be backwards compatible with the old Python 2.X
def decode_if_needed(string):
try:
return string.decode('utf-8')
except AttributeError:
return string
def word_count(text):
def replace_nonalpha(char):
return char.lower() if char.isalnum() else ... |
e25ef9fcc4ee159c828be0082377c2e9ac2d09d9 | happychallenge/OpenCV-Computer-Vision | /02-draw-lines-rectangles.py | 949 | 3.71875 | 4 | import numpy as np
import cv2
#define a canvas of size 300x300 px, with 3 channels (R,G,B) and data type as 8 bit unsigned integer
canvas = np.zeros((300,300,3), dtype ="uint8")
#define color
#draw the line
#arguments are canvas/image, starting point, ending point, color, thickness(optional)
#display in cv2 window
gr... |
2ebb6abe09a57a9ba5b4acdd4cf91b1a59b52545 | mkioga/17_python_Binary | /17_Binary.py | 637 | 4.375 | 4 |
# ==================
# 17_Binary.py
# ==================
# How to display binary in python
# Note that {0:>2} is for spacing. >2 means two spaces
# and on 0:>08b means 8 spaces with zeros filling the left side
# Note that adding b means to display in binary
for i in range(17):
print("{0:>2} in binary is {0:>08b... |
1fc0ac96a372bfde30770f6e493747d9063748cd | ray1007/code_templates | /python/arg_parser.py | 3,116 | 3.640625 | 4 | import argparse
"""
For each project, fill in this template for specific cmd arguments.
"""
# Put the argument parser in a function and return the args.
# Later on, import and call it in the main function.
def create_main_parser():
parser = argparse.ArgumentParser()
# TODO Add arguemnts below.
# Template... |
ab96acd191ac9f8f97ec54b2de9e08b2b62261ca | zenithude/Python-Leetcode | /7-reverseDigit.py | 1,380 | 4.21875 | 4 | # -*- coding: utf-8 -*-
"""
@author : zenithude
Given a 32-bit signed integer, reverse digits of an integer.
Example 1:
Input: 123
Output: 321
Example 2:
Input: -123
Output: -321
Example 3:
Input: 120
Output: 21
Note: Assume we are dealing with an environment which could only store
integers... |
206b2f04f6b3e9008a94c8fcc6787751d441c407 | zenithude/Python-Leetcode | /flattenDoublyLLinkedList.py | 4,503 | 4.46875 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
@author: zenithude
Flatten a Multilevel Doubly Linked List
You are given a doubly linked list which in addition to the next and
previous pointers, it could have a child pointer, which may or may not point
to a separate doubly linked list. These child list... |
32bdfbc9a0a8a1c6dac00220d7cd5a5f6932062b | zenithude/Python-Leetcode | /h-index.py | 1,936 | 4.34375 | 4 | # -*- coding: utf-8 -*-
"""
@author : zenithude
Given an array of citations (each citation is a non-negative integer) of a
researcher, write a function to compute the researcher's h-index.
According to the definition of h-index on Wikipedia: "A scientist has index
h if h of his/her N papers have at least h c... |
5cfbe5a9a4d58d7e8ade931a81696e2725eb65c1 | zenithude/Python-Leetcode | /intervalIntersection.py | 2,179 | 3.921875 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
@author: zenprog
Interval List Intersections
Given two lists of closed intervals, each list of intervals is pairwise
disjoint and in sorted order.
Return the intersection of these two interval lists.
(Formally, a closed interval [a, b] (with a <= b) denotes the s... |
8539c4137bd26e572159a7365c53c0d0f459b44a | zenithude/Python-Leetcode | /checkStraightLine.py | 1,483 | 3.75 | 4 | # -*- coding: utf-8 -*-
"""
@author : zenithude
You are given an array coordinates, coordinates[i] = [x, y], where [x,
y] represents the coordinate of a point. Check if these points make a
straight line in the XY plane.
Example 1:
Input: coordinates = [[1,2],[2,3],[3,4],[4,5],[5,6],[6,7]]
Output: true
... |
0cbefae29e6cf212a779c7da538661df56063fa5 | zenithude/Python-Leetcode | /removeAllGivenElement.py | 2,245 | 4.125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
@author: zenithude
Remove Linked List Elements
Remove all elements from a linked list of integers that have value val.
Example:
Input: 1->2->6->3->4->5->6, val = 6
Output: 1->2->3->4->5
"""
class ListNode(object):
"""List of Nodes L... |
01ceea04633bedf4ccbae64407e773771b50bb3b | zenithude/Python-Leetcode | /83-deleteDuplicate.py | 1,542 | 4.09375 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
@author: zenithude
"""
class ListNode(object):
"""List of Nodes Double Linked."""
def __init__(self, x):
"""
Initialize the list.
Parameters
----------
x : TYPE int
Returns
-... |
334ac7e247ed7f77c7c23715017fb4a608bacc9d | zenithude/Python-Leetcode | /iscousins.py | 2,344 | 4.03125 | 4 | # -*- coding: utf-8 -*-
"""
@author: zenithude
Cousins in Binary Tree
In a binary tree, the root node is at depth 0, and children of each depth k
node are at depth k+1.
Two nodes of a binary tree are cousins if they have the same depth, but have
different parents.
We are given the root of a binary tree ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.