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
bade7f2a29651b1ba3fd1acbd0242c31b7aa26a8
zted/imsearch-tools
/download_from_html.py
1,940
3.828125
4
""" Downloads images from html files, use after download_htmls.py Usage: python download_from_htmls.py directory/containing/query/results """ import os import socket import sys import time import urllib from bs4 import BeautifulSoup def download_images(top_directory): """ Goes into every folder, looks fo...
b04715daa29a147eb2a840cd82f418d282381fad
jinyoungch0i/Regular-Expressions
/re Module 3.py
8,209
3.6875
4
def line_break(x): print(str(x) + '---------' + str(x) + '---------' + str(x) + '---------' + str(x) + '---------') lb = line_break ''' ~appendix * this is the fourth of the four note txts on python regex * ~lb(0) : extending the use of group without the | in the parentheses ~lb(1) : capturing informat...
ccc75767e8aa24e3399ad3e23f8c9c1b4005d11b
daehee-han/kerasBook
/old/keras_MLP_toy_classification.py
2,543
3.5
4
# # Multi-layer perceptron (MLP) toy example for # classifying a simple four class dataset # import numpy as np import matplotlib.pyplot as plt from keras.models import Sequential from keras.layers.core import Dense,Activation from keras.optimizers import SGD from keras.utils import np_utils from keras.utils.visualiz...
9c7c90bda0b8a79ddfd96a9805094b9748c76a07
ClassicM/Python
/Emm-4(字典).py
2,010
4.4375
4
print('dict') print('---------------------------------') #Python内置了字典:dict的支持,dict全称dictionary,在其他语言中也称为map,使用键-值(key-value)存储,具有极快的查找速度。 d = {'Amy':90,'Bob':85,'Candy':60} print(d['Amy']) d['Denny'] = 100 print(d) print('判断key是否存在,有两种方法:1.in 2.dict的get()方法') print('---------------------------------') print('Denny' in...
730d42ed36e3a39bf708d78324f2706e0c6a7fd0
ClassicM/Python
/Emm-13(实例属性和类属性).py
1,476
4.4375
4
#由于Python是动态语言,根据类创建的实例可以任意绑定属性。 #给实例绑定属性的方法是通过实例变量,或者通过self变量: class Student(object): def __init__(self,name): self.name = name s = Student('Bob') s.score = 90 print(s.name,s.score) class Student(object): name = 'Student' s = Student() #创建实例s print(s.name) #打印name属性,因为实例并没有name属性,所以会继续查找class的name属性...
adfc851041b43fd09759344e2a5095e4bc1183e3
ClassicM/Python
/Emm-5(函数).py
624
3.828125
4
#函数 #绝对值函数abs() print(abs(10)) print(abs(-20)) #在多个参数中,返回最大值max() print(max(1,3,6,163,1426,2353457)) ''' 数据类型转换 转换为整数 int() 转换为字符串 str() 转换为浮点型 float() 转换为布尔型 bool() ''' print(int('123')) print(int(12.32)) print(str(123)) print(bool(1)) print('21.32') #函数名其实就是指向一个函数对象的引用,完全可以把函数名赋给一个变量,相当于给这个函数起了一个“别名”: a = abs pri...
8619b508ba6c0927f7207da3b2f89a3fcc97901f
yamada-miraidenshi/gittest
/index.py
1,119
3.5
4
#! /usr/bin/env python3 import sys import io # windowsにおける文字化け回避 sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8') # 以下のコードを書かないと、htmlとして読み込んでもらえない。 print("Content-type: text/html; charset=utf-8") # htmlの部分。printでHTMLコードを表示させることで、ブラウザがHTMLコードとして認識してくれる。 print( """ <html> <head> ...
402e68619eb6880a531099756809fe9f8e7f02af
dufufeisdu/algorithms
/Coursera/Stanford/dynamicProgramming/huffman/huffmantree.py
699
3.96875
4
#/usr/bin/env python3 class Huffmantree(object): def __init__(self, p): self.p = p self.left = None self.right = None self.min_depth = 0 self.max_depth = 0 def merge(self, tree1, tree2): p = tree1.p + tree2.p new_tree = Huffmantree(p) new_tree.lef...
a13f6c494104204fc369794ade9e754d125e38a0
dufufeisdu/algorithms
/Coursera/Stanford/dynamicProgramming/maxWeightIndepdentSet/mwis.py
1,140
3.65625
4
#/usr/bin/env python3 # output:Indexs of element in the max weight independent set # dynamic programming def max_weight_independent_set(): weights = [] with open("mwis.txt") as f: for line in f: weights.append([int(line), [1]]) vertice_number = weights[0][0] weights[0] = [0, [0]] ...
f3e573bcb698d9a70045500506bc29e1857139c7
Shelnard/LeetCode
/Two_Sum.py
367
3.703125
4
#给定义一个整数数组和一个目标值,找出数组中和为目标值的两个数 def two_sum(nums, target_num): result = [] nums_len = len(nums) for i in range(nums_len - 1): for j in range(i + 1, nums_len): sums = nums[i] + nums[j] if sums == target_num: result.append((i, j)) return result
c372ec23b47d2b80dd6bf9a3516ff43548b342e3
SteveWXT/MIT-6.0001
/ps1/ps1c.py
921
4.03125
4
annual_salary = float(input("Enter your starting salary: ")) down_payment = 0.25 * 1000000 left = 0 right = 10000 steps = 0 while True: mid = (left + right) / 2 steps += 1 portion_saved = mid / float(10000) current_saving = 0 months = 0 monthly_salary = annual_salary / 12 for i in range...
205eaa9103e4985a00939e0678759d726c7d3465
farkaspeti/pair_programing
/listoverlap/listoverlap_module.py
375
4.34375
4
def listoverlap(list1, list2): list3 = [] for i in list1: if i in list2 and i not in list3: list3.append(i) else: pass print(list3) return list3 def main(): a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89] b = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13] li...
d402a0f64b3c8658c1d9610cd2fd115d3d09e33a
samrao1997/practice-problems
/long_increase_subseq.py
737
3.71875
4
# Input: unsorted array of ints # Output: lenght of longest increasing substring # Example: ## [10, 9, 2, 5, 3, 7, 101, 18] --> 4 ## because the longest increasing subsequence is ## [2, 3, 7, 101] which is of length 4 def LIS(nums): n = len(nums) if n == 0: return 0 table = [1 for x...
0f27e2841163e4efb2bf385522ec1554e82df239
hlaffon/ctapipe
/ctapipe/utils/linalg.py
406
3.546875
4
from astropy.coordinates import Angle from numpy import cos, sin, array def rotation_matrix_2d(angle): """construct a 2D rotation matrix as a numpy NDArray that rotates a vector clockwise. Angle should be any object that can be converted into an `astropy.coordinates.Angle` """ psi = Angle(angle).r...
696f2d76b7950123be930876c42d42ebb915fb9d
arielvaks/games.cards
/strings/games/player.py
1,819
3.765625
4
import random from random import randint from strings.games.card import Card from strings.games.deckofcards import Deckofcards class Player: #מאתחל את השחקן def __init__(self, name, number_of_cards = 10): # def_str is variable of str if the name is not str def_str = "a" + str(randint(1, 100000000000000)) # ch...
443ffbc4dd1c56128ed794cb151394891ac8a2c4
RonaldZhao/leetcode-cn
/sources/py/125.py
568
3.640625
4
class Solution: def isPalindrome(self, s): """ :type s: str :rtype: bool """ if s == "": return True s1 = "" # 构建一个s的纯小写字母或数字组成的正序字符串 s2 = "" # 构建一个s的纯小写字母或数字组成的反序字符串 for c in s: if c in string.ascii_letters or c in string.digit...
6ca6b20a2b8f4bd943b0b79e3f8a34a3f807fe8b
RonaldZhao/leetcode-cn
/sources/py/350.py
403
3.65625
4
class Solution: def intersect(self, nums1, nums2): """ :type nums1: List[int] :type nums2: List[int] :rtype: List[int] """ result = [] for n in nums1: if n in nums2: nums2.remove(n) # 防止num1中有的元素出现次数多于在nums2出现的次数的情况 ...
e96ef65ab80ec9b361062b5ce4540cefd8972457
johnkle/FunProgramming
/Leetcode/链表/234回文链表.py
1,119
3.71875
4
# Definition for singly-linked list. # class ListNode(object): # def __init__(self, x): # self.val = x # self.next = None class Solution(object): def isPalindrome(self, head): if not head or not head.next: return True cur = head stack = [] while cur: ...
8aeefff560209f3f0556f8bef79ab5b1a8b97fa8
johnkle/FunProgramming
/Leetcode/剑指offer/04二维数组中的查找.py
1,086
3.609375
4
#在一个 n * m 的二维数组中,每一行都按照从左到右递增的顺序排序, #每一列都按照从上到下递增的顺序排序。 #请完成一个函数,输入这样的一个二维数组和一个整数, #判断数组中是否含有该整数。 class Solution(object): def findNumberIn2DArray(self, matrix, target): for item in matrix: if target in item: return True return False class Solution2(object): def f...
fbeccdb5593bdce726ec362252f9bd596febc312
johnkle/FunProgramming
/Algorithm/3_SortAdvance/mergeSort5.py
875
4.0625
4
class Solution(): #如何原地排序 def mergeSort(self,nums,left,right): if not nums: return if left > right: return if left == right: return [nums[left]] mid = left + (right-left)//2 numsl = self.mergeSort(nums,left,mid) numsr = self.mer...
200d79d5fda3da0525a969ea4917d9fc4ab08798
johnkle/FunProgramming
/Leetcode/二叉搜索树/112路径总和.py
1,219
3.921875
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 hasPathSum(self, root, sum): if not root: return False if not root.left and not root....
3bebfeb8f00bf101eb40245ba6ffc4d5c7d44f16
johnkle/FunProgramming
/Leetcode/动态规划/265. 粉刷房子 II.py
450
3.609375
4
#参考下降路径最小和1289 class Solution: def minCostII(self, costs): rows = len(costs) cols = len(costs[0]) dp = [[float('inf')]*cols for _ in range(rows)] dp[0] = costs[0] for i in range(1,rows): for j in range(cols): for k in range(cols): ...
cad34afec593a240ea2d6bd1d12521efe856c703
johnkle/FunProgramming
/Leetcode/数组字符串/692. 前K个高频单词.py
243
3.5
4
import collections class Solution: def topKFrequent(self, words, k): record = collections.Counter(words) res = sorted(record.items(),key = lambda x:(-x[1],x[0])) return [x[0] for x in res][:k] #如何最小堆实现
ec07a3e2dfc595a02462f04996081e6d270648db
johnkle/FunProgramming
/Leetcode/剑指offer/01数组中重复的数字.py
180
3.5
4
class Solution(object): def findRepeatNumber(self, nums): temp = set() for x in nums: if x in temp: return x temp.add(x)
bc11eba169028fa190cfade277914a92c171f457
johnkle/FunProgramming
/Leetcode/剑指offer/剑指 Offer 22. 链表中倒数第k个节点.py
813
3.6875
4
# Definition for singly-linked list. class ListNode(object): def __init__(self, x): self.val = x self.next = None class Solution(object): def getKthFromEnd(self, head, k): if not head or not head.next: return head slow = fast = head length = 1 while f...
a7bfb431044d2d1e8f34e4701e1067d55d047385
johnkle/FunProgramming
/Leetcode/二叉搜索树/111二叉树的最小深度.py
854
3.796875
4
# 叶子节点的定义是左孩子和右孩子都为 null 时叫做叶子节点 # 当 root 节点左右孩子都为空时,返回 1 # 当 root 节点左右孩子有一个为空时,返回不为空的孩子节点的深度 # 当 root 节点左右孩子都不为空时,返回左右孩子较小深度的节点值 # Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution(obj...
3b742b0f02dbde70d1babddf9074466528735d77
johnkle/FunProgramming
/DataStructure/05recursion/recur_basic.py
217
3.84375
4
def sum(arr): return sum1(arr,0,len(arr)-1) def sum1(arr,l,r): # if l > r: # return 0 if l==r: return arr[r] L = arr[l]+sum1(arr,l+1,r) return L arr = [1,2,3,4,5,6] print(sum(arr))
5306b4c6e2e2d590e10186dbaa7a558fb093fa3d
johnkle/FunProgramming
/Leetcode/二叉搜索树/515. 在每个树行中找最大值.py
540
3.5625
4
import collections class Solution: def largestValues(self, root): if not root: return [] res = [] deque = collections.deque([root]) while deque: cur = float('-inf') for i in range(len(deque)): node = deque.popleft() ...
b765da2f2a63797824874a1674eaf5cfbfa105ad
johnkle/FunProgramming
/DataStructure/05recursion/linkednode.py
591
3.5625
4
from node import Node class ArrNode(): def __init__(self,head): self.head = None def ArrNode(self): for count in range(1,6): #self.head = Node(count,self.head) node = Node(count) node.next = self.head self.head = node def test(self): ...
666aec2e1f6ff8f6e6670c139426911e1780dc72
johnkle/FunProgramming
/Leetcode/链表/61旋转链表.py
1,584
3.8125
4
# 先连接成环,再旋转 class ListNode(object): def __init__(self, x): self.val = x self.next = None class Solution: def rotateRight(self, head, k): if not head or not head.next: return head slow = fast = cur = head length = 0 while cur: length += 1 ...
5b489f0aa33304eaffbf345b1d43fe993f8ad6e6
johnkle/FunProgramming
/Algorithm/4_Heap/heapsort2.py
824
3.640625
4
#最大堆是一个完全二叉树 #parent=(k-1)//2 #leftchild = 2*k+1 #rightchild = 2*k+2 #最后一个非叶子节点索引(count-1)/2 #原地堆排序 def shiftdown(arr,n,k): while 2*k+1<n:#如果有左孩子则执行循环,'='别少 j = 2*k+1 #体会j的含义 if j+1<n and arr[j+1]>arr[j]: j+=1 if arr[k]>=arr[j]: break ...
9e546395591c2f3ce35d1a9889398e7108995975
SobuleacCatalina/Rezolvarea-problemelor-IF-WHILE-FOR
/problema_8_IF_WHILE_FOR.py
656
4.1875
4
""" Se dau numerele reale pozitive a,b,c. Să se verifice dacă un triunghi ale cărui laturi au lungimile (în aceeași unitate de măsură) egale cu a,b,c. În caz afirmativ, să se determine tipul triunghiului: echilteral,isoscel,scalen. """ a=int(input("Introdu numărul a: ")) b=int(input("Introdu numărul b: ")) c=int(input...
abd5453985b70c89a2096f88409f9121d904046a
Soon2003/fccss
/3rd/sources/week1/ethiopian_mul.py
624
3.9375
4
# get input with space numbers = str(input("two nums with space: ")).split() # initialize result, set num1, num2 with splited numbers result = 0 num1 = int(numbers[0]) num2 = int(numbers[1]) # repeat until num1 equal to 1 # condition: struck(num1 == even), keep(num1 == odd, add to result) # num1 divide by 2, num2 mul...
131156abb9c9de142b635f24bf71a4eb06bc2b2d
CannedFish/PythonLearn
/function/func.py
1,238
4.03125
4
#!/usr/bin/env python # -*- coding: utf-8 -*- def my_func(x): if not isinstance(x, (int, float)): raise TypeError('bad operand type'); if x >= 0: return x; else: return -x; print my_func(20); print my_func(-1); # my_func('ADe'); print def nop(): pass; def echo(s): print n...
c80c00855a308016585a2620659b44a93b218a07
kauboy26/PyEvaluator
/miscell.py
569
4.15625
4
def print_help(): print 'Type in any expressions or assignment statements you want.' print 'For example:' print '>> a = 1 + 1' print '2' print '>> a = a + pow(2, 2)' print '6' print '\nYou can also define your own functions, in the form' print 'def <function name>([zero or more comma s...
ffa9efdfde6a77021ca27340f0fcdc02b8497d82
Jackiexiong/software-testing-course
/extra-credit/Testing Tests/impl_fail-stack_only_stores_the_last_element.py
449
3.6875
4
class Stack(object): def __init__(self): self.__value = None self.__len = 0 def push(self, v): if v == None: raise ValueError("Unsupported value: {0}".format(v)) self.__value = v self.__len += 1 def pop(self): if self.__len == 0: retu...
5a9d39d34f39053774e1c754d66a5ad4356e5383
Jackiexiong/software-testing-course
/homework/Testing with Examples (Data Format)/impl-gender03.py
2,500
3.65625
4
import re class PhysicalInfo(object): def set_date(self, date): if not isinstance(date, str): raise ValueError("date should be a string") t = date.split("-") if len(t) != 3: raise ValueError("date should be in MM-DD-YYYY format") if re.search(r'[^0-9\-...
98ee6d2d5cdda315aef0cf4cb1ce9d91380fb77d
Jackiexiong/software-testing-course
/content/Intro to Python3/intro_to_python3-script.py
2,495
4.28125
4
# Intro to Python # boolean values T t True # integer values 1234 -23 0 # float values 3.14 314e-2 .1 -.1 # string values "Python's" 'she said "Python"' """String with <newline> character""" "This" "is" "one" "string" # string operators i_str = "Python" i_str[1] i_str[-1] i_str[1:3] i_str[1:7:2] i_str[7:1:-2] ...
a19f0587a8657b513f12a823ba526f8c0c792812
alexeib2014/Tests
/InventoryManagement/test_inventory_management.py
4,986
3.609375
4
import unittest from inventory_management import WareHouse, Order, OrderManager class OrderManagerTests(unittest.TestCase): def setUp(self): self.wareHouseCalifornia = WareHouse('California') self.wareHouseCalifornia.increment('APP', 500) self.wareHouseCalifornia.increment('ORG', 200) ...
3641a298e8347e3614c2d7d0b7b081b73a10c48b
Xithriub/First-Python
/оператор.if и else.py
366
3.734375
4
credit=int(input('Сколько кредитов вы взяли:')) if credit<=23: print('Студент первокурсник') elif 24<credit<53: print('Студент второкурсник') elif 54<credit<83: print('Студент учится в третьем курсе') elif 84<credit<120: print('Студент выпускник')
218fa27f2f488bacd7b523bf72d55b601e46c550
Xithriub/First-Python
/pyt.py
481
3.75
4
#def function(a,b): #return (a+b)**2 #a=int(input('Введиет число:')) #b=int(input('Введите число:')) #print(function(a,b) import random q=[] w=random.randint(-100,100) Nul=0 Plus=0 otric=0 for i in range(w): if i==0: Nul+=0 elif i>0: Plus+=1 elif i<0: otric+=1 print('Числа равны...
ddf55f0414c40849a032fce890150264cd99f2f7
Xithriub/First-Python
/practis.py
1,095
3.78125
4
def celsius_to_fahrenheit(x): return(9/5)*(x+32) def fahrenheit_to_celsius(x): return(5/9)*(x-32) temp=float(input('Введите число:')) c=input('F(ahrenheit) or C(elsius):') if c=='F': x=fahrenheit_to_celsius(temp) print(temp,'C=',x,'F') else: x=celsius_to_fahrenheit(temp) print(temp,'F=',x,'C') ...
16c9b3c13109619e80fb37eea9d02583a5ae963f
clean-exe/coctail-monaco
/main.py
5,024
3.625
4
#!/usr/bin/python3 import random """ This is a simple program that simulate a coctail monaco game. Enter a list of players, and the program will get 1 out per time. """ # global person_id class Person: """Simple person class with First and Second name.""" def __init__(self, uid, first_name, family_name): ...
56a0524b983f6573cdf782f95d947d28bd751398
ebryantd/Python-Practice-v2
/regex_practice.py
483
3.71875
4
import re """ string = "Two too." m = re.findall("t[ow]o", string, re.IGNORECASE) print(m) """ """ line = "123?34 hello?" m = re.findall("\d", line, re.IGNORECASE) print(m) """ """ t = "__one__ __two__ __three__" found = re.findall("__.*?__", t) for match in found: print(match) """ """ line = "I love $" m = ...
0e1c88f204f39de717293f091e443123b4653dcd
damvantai/parallel-programming-2017
/openmp/equation_wave_1D_openmp/plot.py
254
3.65625
4
import matplotlib.pyplot as plt import numpy as np x = np.linspace(0, 1, 10) plt.plot(x, np.sin(2 * np.pi *x), label='old') plt.plot(x, np.sin(2 * np.pi * (x + 0.1)), label='current') plt.xlabel('x label') plt.ylabel('y label') plt.legend() plt.show()
af7408d8d880c7dbde06168c6a6ed4a1f6869d7a
aphearin/rockstar_tree_walker
/simulation_column_dtype.py
1,507
3.5
4
""" Module storing function used to determine the Numpy dtype of Rockstar hlist ascii data. """ import numpy as np def simulation_column_dtype(fname='bolplanck_columns.dat'): """ Function returning the Numpy dtype given user-created ascii data that places the Rockstar hlist header information into a specific ...
76972fcaadbc52294e7e06871d1f7115e8eb6285
jabarszcz/randompasswd
/randompasswd.py
1,496
4.125
4
#!/usr/bin/env python3 import argparse import string import random # Create parser object with program description parser = argparse.ArgumentParser( description="simple script that generates a random password") # Define program arguments parser.add_argument("-a", "--lower", action='store_true', ...
b7dd685d2226a6523d445a3a7aa0d483b3cad8d5
madebydavid/wizzie-ctf
/lesson-12/get-flag.py
387
3.734375
4
#!/usr/bin/env ./../bin/python3 import hashlib def get_md5(thing_to_encode): return hashlib.md5(thing_to_encode.encode()).hexdigest() salt = 'spice' password = input('Please enter the password: ') # clue - the password is STILL a number if get_md5(salt + password) == 'c9d0da3ce98f449ef65cfa11db8508a7': with ...
147179c937d26d3634c92e99f5caec26ba9c4d66
madebydavid/wizzie-ctf
/lesson-05/encode.py
878
4.3125
4
#!/usr/bin/env ./../bin/python3 # Tool for hiding the password in the cheese import random cheese = [] with open('cheese.txt', 'r') as input_cheese: for line in input_cheese: line_list = list(line.rstrip()) cheese.append(line_list) password = input('Please enter the password to hide in the chees...
70479945a8dbc44894046c0e7d88ff69b70cc526
isaolmez/core_python_programming
/com/isa/python/chapter7/MappingFunctions.py
898
3.734375
4
## 1. Standard Type Functions: # type(), str(), cmp() d1 = {"a": "1"} print type(d1) # cmp() Compare strategy: First length, then key compare by iterating, then value compare by iterating d2 = {"a": "1", "b": "2"} print cmp(d1, d2) d1["b"] = "3" print cmp(d1, d2) d1["b"] = "2" print cmp(d1, d2) d1["c"] = "3" print cmp...
7153aaf3e83a37007acac28cb66099c8795e8606
isaolmez/core_python_programming
/com/isa/python/chapter2/Exercise_2_7.py
267
3.84375
4
input = raw_input("Enter a string: \n") counter = 0 while counter < len(input): print input[counter], counter += 1 print for i in range(len(input)): print input[i], print for c in input: print c, print for i, c in enumerate(input): print c,
7fbee6b902a11525f9d8afd0f20a343126dd51b1
isaolmez/core_python_programming
/com/isa/python/chapter6/Tuples.py
530
4.4375
4
## Tuples are very similar to lists; but they are immutable tuple1 = (1,2,3) print tuple1 # For tuples, parantheses are redundant and this expression craetes a tuple. # For lists we must use brackets tuple2 = "a", "b", "c" print tuple2 # tuple1[1] = 99 # ERROR: We cannot mutate tuple or assign new values to its elemen...
dd5647508ad4121ec3a346e5bb6744dd82340eae
isaolmez/core_python_programming
/com/isa/python/chapter11/Map.py
241
4.03125
4
## map() built-in function: gets a sequence and returns a sequence def mapFunc(num): return num + 5 print map(mapFunc, range(9)) print map(lambda num: num + 5, range(9)) # With list comprehensions print [num + 5 for num in range(9)]
1fa884d5df7eab02929fcd33f544e31328e85eeb
isaolmez/core_python_programming
/com/isa/python/chapter11/VariableLengthArgs.py
1,060
3.9375
4
## Non-Keyword Varargs - Tuple or list # Must come after formal arguments/parameters both in definition and invocation def foo(arg1, arg2=2, *arg3): print arg1, arg2, arg3 foo(1) foo(1, 2) foo(1, 2, 3, 4, 5, 6) # foo(arg2=22, arg1=11, 0,0,0,0) # Runtime Error: we cannot use keyword arguments with grouped argum...
916b10dc06df2fece2e1af6afe15b80696ea11cc
isaolmez/core_python_programming
/com/isa/python/chapter5/Exercise_5_11.py
468
4.1875
4
for item in range(0,21,2): print item, print for item in range(0, 21): if item % 2 == 0: print item, print for item in range(1,21,2): print item, print for item in range(0, 21): if item % 2 == 1: print item, print ## If you omit return type, it does not give warning but returns ...
b433ed328d118c05a67b42d8085391af87955ba7
isaolmez/core_python_programming
/com/isa/python/chapter7/SetOperators.py
899
4.21875
4
## 1. Standard Type Operators set1 = set([1, 2, 3, 3]) # Removes duplicates print set1 set2 = set("isa123") print set2 print 1 in set1 print "i" in set2 print "---- Equality test" set1Copy = set(set1) print "set1 == set1Copy", set1 == set1Copy print "set1 < set1Copy", set1 < set1Copy # Strictly must be smaller. Equa...
38f6e8c24dd6ffc9f4bff0b59f8594ebd7500287
isaolmez/core_python_programming
/com/isa/python/chapter11/LogDecorator.py
737
3.5625
4
from time import ctime def Logger(when): def log(): print "Time is: [%s]" % ctime() def logBeforeBad(func): log() return func def logBefore(func): def wrapped(): log() func() return wrapped def logAfter(func): def wrapped(): ...
7960696f3a39d90dd1dd283a86759d63555eaa04
isaolmez/core_python_programming
/com/isa/python/chapter8/Exercise_8_6.py
432
3.59375
4
def primeFactors(number): factors = [] while number != 1: divident = 2 while divident <= number / 2: if number % divident == 0: factors.append(divident) number = number / divident break else: divident += 1 ...
12048f13a4a8acd306ae7c44b3760448155812a2
isaolmez/core_python_programming
/com/isa/python/chapter6/ListOnlyFunctions.py
1,209
4.09375
4
## List only functions are defined in List type. They are called on an object. These are in fact called methods: function dependent on objects to be called. # These methods can mutate the list and mutating methods do not return any value. They return None. # In contrast, methods of immutable objects does have to return...
fade8fcd236ccbf30038d4ca49cd11dd18dae898
isaolmez/core_python_programming
/com/isa/python/chapter6/ShallowCopy.py
1,228
4.28125
4
## SHALLOW COPY person = ["name", ["savings", 100.00]] print id(person), id(person[:]) print "---- Slice copy" husband = person[:] print id(person), id(person[:]) print id(person), id(husband) # They both refer to the same string "name" as their first element and so on. print "id() of names:", id(person[0]), id(husban...
c0014804d3c647163a3cd62addaeca71ec9b9474
fujish4/AtCoder
/96_C.py
528
3.609375
4
def isDraw(s, H, W): for h in range(H): for w in range(W): if s[h][w] != "#": continue if h > 0 and s[h-1][w] == "#": continue if h < H-1 and s[h+1][w] == "#": continue if w > 0 and s[h][w-1] == "#": ...
22224570044b3012bc3d7963c1f1b2628c0ce6b2
afai/comp
/assignment1/bluesbooze.py
563
3.75
4
f = open("states.txt", "r") stateDict = {} for l in f: d = l.split(",") stateDict[d[1][:-1]] = d[0] f.close() # If the function is called with a string of states separated by a comma, # it will convert each to an abbreviation. def stateToAbbrev(stateString): stateFound = False stateSplit = stateString.sp...
7f24cba6366aaf3ea0503771323634a576d38089
joeyuan19/CodeEval
/moderate/word_chain.py
1,347
3.5
4
import sys class Node: def __init__(self,value,parent,children=[]): self.value = value self.parent = parent self.children = children def add(self, entry,l=0): print l,children r = False if entry[0] != self.value[0]: f = False for chil...
89619dbd689d964886b01296ac9dc2d14c4c552e
djotaku/pythonmorsels
/sum_timestamps/sum_timestamps.py
1,644
3.765625
4
import math def figure_out_base_sixty(number: int) -> (int, int): """Figure out the next number up if I have more than 59 seconds or minutes.""" if number > 59: return math.floor(number/60), number % 60 else: return 0, number def sum_timestamps(timestamps: list) -> str: """Accept a l...
7ca9b2057c8e6e1924fd276683183172b48915e0
hoyj/ProjectEuler
/44.py
479
3.734375
4
from math import sqrt def pen(n): return n * (3*n - 1) // 2 def isPentagonal(x): i = (sqrt(24 * x + 1) + 1) // 6 return (sqrt(24 * x + 1) + 1) / 6 == i i = 1 pList = [] # list containing p that have already been calculated while True: p = pen(i) for q in pList[::-1]: if isPentagonal(abs(p-...
17993fd4f7049e8026e5329920ce0f99989baa13
hoyj/ProjectEuler
/1.py
277
3.578125
4
''' Project Euler Problem #1 Find the sum of all multiples of 3 and multiples of 5 under 1000 ''' N = 999 max3 = N // 3 max5 = N // 5 max15 = N // 15 a = (max3 * (max3 + 1)) / 2 b = (max5 * (max5 + 1)) / 2 c = (max15 * (max15 + 1)) / 2 print('Result:', 3*a + 5*b - 15*c)
d59c9c163007d155810d140eb9f6d87f2dc0a18f
hoyj/ProjectEuler
/14.py
2,065
3.75
4
''' Project Euler Problem #14 For a positive integer n, we repeat the following process, if n is even: n -> n / 2 if n is odd: n -> 3n + 1 ex) n = 13 13 -> 40 -> 20 -> 10 -> 5 -> 16 -> 8 -> 4 -> 2 -> 1 Which starting number, under one million, produces the longest chain? ''' import time def mySeq(): '...
cfad1754d85dbf265d928e14bc09f1c37c10637b
hoyj/ProjectEuler
/48.py
221
3.625
4
def getDigits(n, exp): print(n, exp) res = 1 for _ in range(exp): res = (res * n) % (10 ** 10) return res total = 0 for i in range(1,1000): total += getDigits(i, i) print(total % 10000000000)
0c2c06e78b487259157082a78e21bdcf951a457b
Supython/SuVi
/+or-or0.py
287
4.5
4
#To Check whether the given number is positive or negative S=int(input("Enter a number: ")) if S>0: print("Given number {0} is positive number".format(S)) elif S<0: print("Given number {0} is negative number".format(S)) else: print("Given number {0} s Zero".format(S))
401b903d06dafa2c6c6761aec18f262bb1e0ce18
Cheney320/LeetCode-
/day2/859.py
1,310
4
4
""" 给定两个由小写字母构成的字符串 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" 输出: false   提示: 0 <= A.length <= 200...
b127ceb7dad79c7acf76acd1dd0747cd35d39719
Cheney320/LeetCode-
/day4/15.py
3,214
3.859375
4
""" 15.三数之和 给定一个包含 n 个整数的数组 nums,判断 nums 中是否存在三个元素 a,b,c , 使得 a + b + c = 0 ?找出所有满足条件且不重复的三元组。 注意:答案中不可以包含重复的三元组。 示例: 给定数组 nums = [-1, 0, 1, 2, -1, -4], 满足要求的三元组集合为: [ [-1, 0, 1], [-1, -1, 2] ] 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/3sum 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 """ """ 思路一: 1. 先将数组进行排序 ...
a0a68d76a5e989acec3f2fbc68d8fe9f7e0a71ec
biubiubiulol/UPGMA
/bootstrapping2.0.py
1,326
3.671875
4
''' Shaban Aagayev Executes bootstrapping on sequences Last modified: 19 November 2018 ''' from readfasta import readfasta import random def bootstrap(): sequences = readfasta("mt_homo_dna.fasta") list_original_sequences = [] for sequence in range(0, len(sequences)): #convert (list of lists) to (list o...
85a26ef76d793469a9b65526f4914415ad6eb5c1
douwings/pythonWork
/speech/speechtest.py
248
3.9375
4
# -*-coding:utf-8-*- import speech while True: say = speech.input() speech.say("你说:" + say) if say == "你好": speech.say("你好啊,主人") elif say == "天气": speech.say("今天天气晴朗,主人")
26f49524bdb9af247e702c3a78f5a0cb114eb82f
lidalan/songqinAPI
/songqinAPI/APItest/python基础/字符串.py
226
3.9375
4
str1 = 'abcdef' print(str1[-2::2]) # # # list1 = [1,2,3,4,5,6,7] # # print(list1[2]) # # str1 = 'name: Jack, weight: 130kg' # print( (3,4,5)[1:2]) list1 = [1,2,3,4,5] # list1.insert(-2,31) # print(list1) print(1,2 in list1)
52a81e4bc749dbee6da61ee95f5b29876abd5cb6
maciejkar/Fraction_class
/Fraction.py
4,934
4.15625
4
import math class Fraction(): """Class which represent fractions """ mixed = False allow_float = True float_precision = 4 def __init__(self, num, den) : """Function creat and reduse fractions @parm num: (int) numerator @parm den: (int) denominator""" # Cha...
48e8f5032095f9b885e0179c80e3dee54bab58aa
avery-logue/CPSC125
/Grade.py
412
4
4
#Avery Logue 10/25/17 def getGrade(nbr) : if(int(nbr) >= 90 and int(nbr) < 100): return 'A' elif(int(nbr) >= 80 and int(nbr) < 90): return 'B' elif(int(nbr) >= 70 and int(nbr) < 80): return'C' elif(int(nbr) >= 60 and int(nbr) < 70): return'D' else : ...
79d05dc783b656d296066020f6feedffe1d05e5a
avery-logue/CPSC125
/lab6test.py
736
4
4
# Avery Logue # 12/3/17 word = "" filename = input('Please enter a filename or X to exit\n') while(word != "X" and filename != "X"): try: with open(filename, "r") as infile: list = infile.read() list = list.split() while (word != "X"): word = ...
32945cb39ed6c83b8cba875b2444fd11e6644858
daniel1rosso/seguridadinformatica
/TP2/2.py
79
3.6875
4
frase = input("Introduce una frase: ") print("Frase invertida: " + frase[::-1])
70992cf13bd81e07c079dfd06a0c1edc7870d98c
daniel1rosso/seguridadinformatica
/TP2/9.py
386
3.671875
4
asignaturas = ['Análisis Matemático I', 'Física I', 'Física II', 'Redes de Información', 'Seguridad Informática'] notas = [] i = 0; while i != len(asignaturas): nota = input("Introduce la nota de " + asignaturas[i] + " : ") notas.append(nota) i+=1 j = 0; while j != len(asignaturas): print("En la asigna...
ef3c2c2ad7a5f1dfa5b6cf93f5e70d65be38a94f
PatrykJurczyk/Wizualizacja_Danych
/Python Ćwiczenia 5/2.py
290
3.765625
4
class Kwadrat: def __init__(self, x=0): """Konstuktor punktu.""" self.x = x def __add__(self, point): return Kwadrat(self.x + point.x) def __str__(self): return f'Kwadrat {self.x}' p1 = Kwadrat(3) p2 = Kwadrat(2) p3 = p1 + p2 print(p3)
c394c8242eff7bcdf5c7bb03cb5f8bbae8d09961
PatrykJurczyk/Wizualizacja_Danych
/Python Ćwiczenia 4/6.Zadanie_szoste.py
666
3.71875
4
class Slowa: atrybut1 = str(input("Podaj pierwsze slowo: ")) atrybut2 = str(input("Podaj drugie slowo: ")) def palindrom(self): if (self.atrybut2 == self.atrybut1[::-1]): return True return False def anagramy(self): a = sorted(self.atrybut1) ...
666919a57b5cf2597f3d6ddbb87ed9519e414c96
PatrykJurczyk/Wizualizacja_Danych
/Python Ćwiczenia 2/5.Zadanie_piate.py
583
3.859375
4
# Zad. 5 # Napisz skrypt, który pobiera od użytkownika # trzy liczby a, b i c. Sprawdza następujące warunki: # czy a zawiera się w przedziale # (0,10> oraz czy jednocześnie a>b lub b>c. # Jeśli warunki są spełnione lub nie to ma się wyświetlić # odpowiedni komunikat na ekranie a = input("Podaj pirwsza liczbe...
16945dea2f24a30bcd4051ec6aca6018edecc61f
PatrykJurczyk/Wizualizacja_Danych
/Python Ćwiczenia 2/2.Zadanie_drugie.py
510
3.609375
4
# Zad. 2 # Napisz skrypt, który pobiera od użytkownika dwie wartości i mnoży je przez siebie. # Wynik wyświetla na ekranie (użyj instrukcji readline() i write()). #Zapytać się jak zrobić mnożenie. x = input("Podaj liczbe: ") y = input("Podaj liczbe: ") e = int(x) i = int(y) z = e * i g = str(z) print(z)...
195121bb910e2ba40e59abc6d48d4b4e881a211a
Utkarsh811/workclass
/2nd.py
131
4.25
4
# program to convert celcius into fahrenheit c=float(input('Enter the temperature in celcius')) f=(c*float(9/5)+32) print(f'{f}f')
c139098a2859b272f95868d767b9c108f04d7f8f
Utkarsh811/workclass
/ASSIGNMENT_9/9.py
1,421
4.375
4
#for matrix addition matrix should have equal dimensions , means equal number of rows and columns row=int(input('Enter the number of rows of matrix-1')) cols=int(input('Enter the number of cols of matrix-1')) row1=int(input('Enter the number of rows of matrix-2')) cols1=int(input('Enter the number of columns of matrix-...
ef2d861e71b59d8e6d9c04663935cc2e093cacd2
enecatalina/Python
/Python_OOP/Animals /AnimalsMain.py
921
3.796875
4
class Animals(object): def __init__(self, name, health): self.name = name self.health = health def walk(self): self.health -= 1 return self def run(self): self.health -= 5 return self def display_health(self): print "{}'s health is {}".format(self....
6b1423929e7f5096560bfcc994e3bc8af5a13fce
enecatalina/Python
/Python_Fundamentals/FunwithFunctions.py
894
3.640625
4
# def print_odds(): # for num in range(1,256): # if num%2 !=0: # print "Number is",num # print "This is an odd number" # if num%2 == 0: # print "Number is",num # print "This is an even number" # print_odds() # #multiply numbers # my_list = [2,4,10,1...
f704fe56dd7250fe343c790f2e2e51524a9f3080
enecatalina/Python
/Python_OOP/py_oop_call.py
1,285
3.71875
4
class Call(object): id = 1 def __init__(self, caller, phonenumber, time, reason): self.id = Call.id self.caller = caller self.phonenumber = phonenumber self.time = time self.reason = reason Call.id += 1 def display_info(self): print 'uniq...
c427b991af3fe258e3125d8c109a36721a5d0235
newtoallofthis123/python-dev-bin
/bin/firstLawofMotion.py
946
3.984375
4
# v = u+at choice = str.lower(input("What do you want to calculate? (v, u, a, t)")) if choice == 'v': u = float(input("What is the value of u(m/s): ")) a = float(input("What is the value of a(ms^-2): ")) t = float(input("What is the value of t(sec): ")) print(u + a *t) elif choice == 'u': v = floa...
587beecb2e35da1660fedc07bfdf6748a818be11
newtoallofthis123/python-dev-bin
/bin/ideal_Gas_Equation_Calculator.py
477
3.828125
4
# By the way, the ideal gas equation is PV = nRT R_cal = 1.987 R_j = 8.314 R_atm = 0.0821 choice = str.lower(input("What do you want to calculate(P, V, n, R, T)")) if choice == 'p': n = int(input("What is the number of moles")) v = float(input("What is the volume of the gas")) t = float(input("Input temperature in ...
32acacd55ab98f91916ea20ad3ddad9b6e84e138
RLIndia/samplebots
/Code/script_BOTs/python_bot/python_bot.py
114
3.53125
4
print("Hello World") from datetime import date today = date.today() d = today.strftime("%A, %d %B %Y") print d
77bc1a65dfdd91b02ff4a81c11c55c5294ae233d
akshshu/BST_Python_C-
/bstprepost.py
1,257
4
4
class node: def __init__(self, data): self.data = data self.left = None self.right = None def insert(root, temp_node): if root is None: root = temp_node elif root.data > temp_node.data: if root.left is None: root.left = temp_node else: ...
a9a8ef8aa20306c0a7f943290ae2abf28f8d26ad
4bd3ss4m4d/PongArcadeGame
/main.py
2,809
3.90625
4
# Pong Game ### ''' Created by 4bd3ss4md ''' ### from turtle import Screen, listen from paddle import Paddle from ball import Ball from scoreboard import Scoreboard def main(): # Set screen screen = Screen() screen.setup(width=800, height=675) screen.bgcolor("black") screen.ti...
3cf7a6125d856402d5f286bf9589ff9a0a7a4d46
Izavella-Valencia/programacion
/Talleres/TallerHerencia.py
2,841
3.6875
4
#punto1 class Persona (): def __init__ (self, IDpersona, nombre, edad): self.idpersona = IDpersona self.nombrepersona = nombre self.edadpersona = edad def mostraratributos (self): print (f'''Mi ID es {self.idpersona}, mi nombre es {self.nombrepersona}, mi edad es {self.edadpers...
528e345293daabc200c244daa47bbd0ed62ce033
Izavella-Valencia/programacion
/Talleres/Taller2.py
1,296
4.375
4
#------preguntas------ MENSAJE_INTRODUCCION = "procederemos a hacer operaciones con numeros escogidos por ti" NUMERO_A = "escoja un numero entero del 1 al 20 :" NUMERO_B = "escoja un numero entero del 1 al 20 :" #-------codigos-------- print ("#"*15, "insertar numeros", 15*"#") print (MENSAJE_INTRODUCCION) numeroA = ...
03391a21b02bc2c137ed3dc24d5a9dc952374866
Izavella-Valencia/programacion
/Clases/edad.py
426
3.84375
4
#-----entradas----- MENSAJE_BIENVENIDA = "Hola, como estas?" PREGUNTA_EDAD = "¿cuantos años tienes? :" MENSAJE_MAYOR_EDAD = "Eres mayor de edad, puedes seguir" MENSAJE_MENOR_EDAD = "Eres menor de edad, no puedes seguir" #------entrada de codigos------ print (MENSAJE_BIENVENIDA) edad = int (input(PREGUNTA_EDAD)) isMayo...
7c52c9f202315ffc5d90cb6b81118d92051240d1
Izavella-Valencia/programacion
/Clases/Listas.py
1,763
4.1875
4
nombres = [] print (type(nombres)) print (nombres) nombres = ['Santiago', 'Samuel', 'Alejandra', 'Elsa'] print (nombres) print (nombres[2]) nombres.append ('Mauricio') print (nombres) print (nombres [2]) edades = [18,19,20,17] estaturas = [1.62, 1.80, 1.67, 1.98] #el ultimo numero print (edades [-2]) print (edades [...
950e3a13a0620dafc8798bcc33549f0071663052
debervill/kotyaFlask
/serviceFunc.py
254
3.5625
4
from datetime import date from datetime import datetime def getDays(): curdate = datetime.today() f_date = date(2017, 10, 26) l_date = date(curdate.year, curdate.month, curdate.day) delta = l_date - f_date print(delta.days) return str(delta.days)
f1e39594915a4ee6eb278b038f46b5f45b809888
cyrnicolase/leetcode
/653/653.py
1,258
3.703125
4
#!/usr/bin/python class TreeNode(object): def __init__(self, x): self.val = x self.left = None self.right = None class Solution(object): rests = [] def __init__(self): self.rests = [] def findTarget(self, root, k): result = self.doFind(root, k) re...
1fa145d23965807b61b8b1362b64baf42aeecc50
cyrnicolase/leetcode
/2/2.py
1,521
3.671875
4
# https://leetcode.com/problems/add-two-numbers/description/ # 需要注意的是,节点指针需要不断的向后移动,不然,就只能是两位数,不断的覆盖第二个节点 # Definition for singly-linked list. # class ListNode(object): # def __init__(self, x): # self.val = x # self.next = None class Solution(object): up = 0 result = None root =...