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
e204ae69a4217a1ab8035a21fbe8c2350656d62b
Frayn-code/Python-Algorithm
/DataStructure/dynamic/multipliMatrix.py
1,175
3.609375
4
def multipliMatrix(r): ''' 矩阵连乘算法 :param r: :return: ''' n=len(r) m=[[1e9 for i in range(n)] for j in range(n)] s = [[0 for i in range(n)] for j in range(n)] for i in range(n): m[i][i]=0 # print(m) # d为差距 i和j之间距离 for d in range(1,n-1): for i in range(1,n-d...
ecd2779ef9fa64b3ac9530276c4475fc71dbf66a
DaniyarML/Algorithms_and_Data_Structures
/DynamicProgramming/8_unique_path.py
864
4.0625
4
# A robot is located at the starting point(0,0) and it needs to reach the mxn point. # Robot can move to the bottom or to the right # how many unique pathes to the point. Grid have obstacles # given a grid # Time complexity: m*n # Space complexity: m*n # F(i,j) = F(i,j-1)+F(i-1,j) def unique_path(grid) -> int: m...
1b3b1075ac5122f6b241eae646841b6e957d29bd
Phrancus/Wincademy_oefeningen
/voetbal.py
2,311
3.515625
4
'''Oefening met Strings van data types and operations. ''' scorer1 = 'Demyanenko' scorer2 = 'Lytovchenko' scorer3 = 'Jan Wouters' scorer4 = 'Khidiyatullin' scorer5 = 'Berry van Aerle' goaltime1 = '31' goaltime2 = '33' goaltime3 = '37' goaltime4 = '42' goaltime5 = '50' # dit moet handiger kunnen met een 1 tot 5 telle...
0f6205bf8e4432b22c20604aaa51b26729f31682
ktp-forked-repos/leetcodely
/python/606_construct _string_from_binary_tree.py
766
3.796875
4
"""Created by sgoswami on 8/7/17.""" """You need to construct a string consists of parenthesis and integers from a binary tree with the preorder traversing way. The null node needs to be represented by empty parenthesis pair "()". And you need to omit all the empty parenthesis pairs that don't affect the one-to-one ...
b7c5a18af9c56dfcdd18288393a4d4a169ba0116
ktp-forked-repos/leetcodely
/python/617_merge_two_binary_trees.py
1,116
3.828125
4
"""Created by sgoswami on 8/6/17.""" """Given two binary trees and imagine that when you put one of them to cover the other, some nodes of the two trees are overlapped while the others are not. You need to merge them into a new binary tree. The merge rule is that if two nodes overlap, then sum node values up as the ...
fd838f61dcc2476682727bc2c085f5b565218488
lmorinishi/leetcode-practice
/solutions/lc_344_revString.py
620
3.796875
4
class Solution: def reverseString(self, s: List[str]) -> None: """ Do not return anything, modify s in-place instead. """ # list reverse # s.reverse() # list slice # s[::-1] # iterate half list, swap for i in range(int(len(s)/2)): ...
c1e7781479f5d16af3d250a5cb3f51a74d736a8d
lmorinishi/leetcode-practice
/solutions/lc_021_mergeTwoSortedLists.py
773
3.53125
4
class Solution: def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode: curr = step = out = None if l1 is None: return l2 if l2 is None: return l1 while l1 and l2: if l1.val < l2.val: curr = l1 l1 = l1.next...
32a780249aad461634e7ebab626107bfd21a34e0
yaserahmedn/Leetcode--June-Challenge
/Two_City_Scheduling.py
1,716
3.765625
4
''' There are 2N people a company is planning to interview. The cost of flying the i-th person to city A is costs[i][0], and the cost of flying the i-th person to city B is costs[i][1]. Return the minimum cost to fly every person to a city such that exactly N people arrive in each city. Example 1: Input: [[10,20]...
9a688c70e1ac742b9bfb9ecb242da623afc54931
phuuda/Infosearch
/reverse_index.py
427
3.5
4
from collections import Counter, defaultdict doc_1 = ['Madam', 'I', 'I', 'am', 'Adam'] doc_2 = ['Adam', 'love', 'Madam'] doc_3 = ['I', 'am', 'banana'] collection = [doc_1, doc_2, doc_3] def reverse_id(collection): dic = defaultdict(set) # wont create key duplicates for i, doc in enumerate(collectio...
b7799ec5f04e3e95a73ea0f2e123d65c927abee8
Cathy-Wu/python_code
/practice_code_py/python课后习题19-001(参数和乘).py
553
3.84375
4
'''计算打印所有的参数的和乘以基数3的结果\ 如果最后一个参数为5,则基数为5,基数不参与求和计算\ def fun(*a): result = 0 for each in a: result += each if a ==5: b=(result-5)*5 print('计算打印所有参数的和乘以基数5的结果:',b) else: print('计算打印所有参数的和乘以基数3的结果:',result*3)''' def mfun(*a,base=3): result = 0 for each in a:...
b0ea646ea65469db67ba4171d04968964867f4ee
Cathy-Wu/python_code
/practice_code_py/python课后习题25-01(字符串的分割方法).py
189
3.671875
4
date = '1000,Cathy,女' mydict = {} (mydict['id'],mydict['name'],mydict['sex']) = date.split(',') print('id:' + mydict['id']) print('name:' + mydict['name']) print('sex:' + mydict['sex'])
71a8a163a73b40be98c6ff568b631c32bc30291b
Cathy-Wu/python_code
/practice_code_py/python课后习题22-01(求阶乘).py
505
3.859375
4
'''求阶层:非递归版本 def recur(n): result = n for i in range(1,n): result *= i return result number = int(input('请输入一个正整数:')) result = recur(number) print('%d的阶乘是:%d'%(number,result))''' '''求阶层:递归版本''' def factorial(n): if n == 1: return 1 else: return n * factorial(n-1) ...
b905976ad2c0a6bb50ab0c392abaf65f8c626d7e
Cathy-Wu/python_code
/practice_code_py/python课后习题36-02(定义一个person类并生成类实例对象).py
294
3.921875
4
'''定义一个person类并生成类实例对象''' '''属性:姓名(默认姓名'小甲鱼') 方法:打印姓名 属性:方法中对属性的引用形式需加上self,如self.name''' class Person(): name = '小甲鱼' def print_name(self): print(self.name)
42c36c2272e4d0f62109fb7ab8af8c11e86e9288
Cathy-Wu/python_code
/practice_code_py/Python第四堂课002(再猜一次0.py
448
3.796875
4
print('......再来一次......') temp=input('猜是哪个数:') guess=int(temp) n=2 while guess !=8 and n>0: n=n-1 temp=input('猜错了请重新输入吧:') guess=int(temp) if guess ==8: print('对的,你猜对了!') print('猜对了也木有奖励的') else: if guess>8: print('哥哥,大了大了') else: print('小了小了')...
7d9e1cc040a0e29b712734f741957538262e4c84
Cathy-Wu/python_code
/practice_code_py/python课后习题15-001(编写进制转化程序).py
350
3.640625
4
print('编写一个进制转化程序') q=1 while q: num = input('请输入一个整数:') if num != q: num = int(num) print('十进制->十六进制:%d -> 0x%x'%(num,num)) print('十进制->八进制:%d -> 0o%o'%(num,num)) print('十进制->二进制:%d ->'% num,bin(num)) else: q=0
0885d546e17130afa24a751778411f5a7c0e0e09
LemonZR/myWorkStation
/test/hanoi.py
652
3.9375
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # 利用递归函数计算阶乘 # N! = 1 * 2 * 3 * ... * N print "我是被调用模块: ",__name__ def fact(n): if n == 1: return 1 return n * fact(n-1) # 利用递归函数移动汉诺塔: def move(n, a, b, c): #print __name__ if n == 1: print('move', a, '-->', c) else: move(n...
07ed697ce41cfd7bdfb561f1de7620255e18cf3c
LemonZR/myWorkStation
/Utils/getDate.py
566
3.625
4
#coding:utf8 import time,datetime def getToday(): return time.strftime('%Y%m%d',time.localtime(time.time())) def getTime(): return time.strftime('%Y%m%d%H%M%S',time.localtime(time.time())) def getMMtime(): mm = int(time.time()*1000).__str__()[-3:] t = time.strftime('%Y%m%d%H%M%S', time.localtime(tim...
0adc8e05c38e52d54f8667a0fc8e4a99337941ed
traines3812/traines3812.github.io
/range_demo.py
605
4.5625
5
# The range function generates a sequence of integers a_range = range(5) print('a_range ->', a_range) print('list(a_range) ->', list(a_range)) # It is often used to execute a "for"loop a number of times for i in range (5): print(i, end= ' ') # executed five times print() # It is similar to the slice functio...
a7ded509af21ecd1ebef9027fe4c8bcc2533f288
liuxianqiang/learn-python
/w3school/06-for.py
579
3.9375
4
#!/usr/bin/python # -*- coding: UTF=8 -*- #循环(while, for, break, continue, pass) #while, while:else total = 0 i = 1 while (i < 10): total = total + i i = i + 1 else: print 'while is finished' print total #for for letter in 'Python': # First Example print 'Current Letter :', letter fruits = ['ban...
770e5fe76629051b9ffe97fe5d47606a519e80a9
saurabh9495/Python_Advanced
/Searching/linearsearch.py
175
3.640625
4
def linear_search(list, target): for i,j in enumerate(list): if j == target: return i return None print(linear_search([1,2,3,4,5,6,7,8,9,10], 5))
d7f0fe17059b7c55a5ffdf267014aa04610da4e6
lovelight24/Python
/armstrong.py
361
4
4
import math import os def check_armstrong(Num): Result = 0; str_num = str(Num) for i in str_num: b = math.pow(int(i),3) print(b," ", i) Result += b if Result==Num: print("Numer is Armstrong.") else: print("Number is Not armstrong.") if __name__ == "__main__": os.system("cls") Num = int(input("Please E...
8e22faac5afc463383a8f2e30ab46297377011c4
lovelight24/Python
/grid.py
401
3.5
4
from tkinter import * win = Tk() label1 = Label(win,text="Name") label2 = Label(win,text="Password") entry1 = Entry(win) entry2 = Entry(win,show="*") label1.grid(row=0,sticky=E,ipadx=20,ipady=10) label2.grid(row=1,sticky=E,ipadx=20,ipady=10) entry1.grid(row=0,column=1,padx=10) entry2.grid(row=1,column=1,padx=10) c = ...
ef00df4c5832eace67d13132c9997bd09945137d
Beckat/Tic-Tac_toe
/GameBoard.py
2,914
3.953125
4
import numpy as np class TicTacToe: """ Initializes the game board """ def __init__(self, num_players = 1): self.tic_tac_toe_grid = [ ['.']*3 for i in range(3)] self.tic_tac_toe_grid = np.asarray(self.tic_tac_toe_grid) def reset_board(self): """ Sets all squares ba...
19c5d19aaa41a9bd4013d3975ddad40f5a35c643
Aibek1986/lessons
/lesson3/billing.py
781
3.640625
4
# coding=utf-8 menu = [{'' 'name' : 'Lagman', 'price' : 160, 'weight' : 200}, {'name' : 'Kofe', 'price' : 40, 'weight' : 100 }] quantity = input('Количество порций: ') select = raw_input('Блюдо: ') service = 15 balance = 1000 discount = 20 for m in menu: ...
e02d4fc9ce0a714b8ceedb7b9500280f2d34c925
PlayPython/homework
/mengyouyong/python_basic_1.py
7,731
3.9375
4
import random import math import time import collections # 打印π print(math.pi) ##数值类型练习 # - 使用循环和算数运算,生成0到20的偶数 for i in range(0, 21, 2): print(i) # - 使用循环和算数运算,生成0到20的奇数 for i in range(1, 21, 2): print(i) # - 写一个函数,判断一个数是否被另外一个数整除 def divide_exactly(x, y): if x % y == 0: print("yes") else: ...
1bc275cd138b7a2bf19af5c342d928093debbb31
PlayPython/homework
/zhaoger/practice.py
5,387
3.875
4
#数值类型练习 #使用循环和算数运算,生成0到20的偶数 print([i for i in range(0, 21) if i % 2 == 0]) #使用循环和算数运算,生成0到20的奇数 print([j for j in range(0, 20) if j % 2 == 1]) #写一个函数,判断一个数是否被另外一个数整除 def a(x, y): if x % y == 0: print("%s能被%s整除" % (x, y)) #print('(0)能被(1)整除'.formate(x,y)) else: print('%s不能被%s整除' % (x, y)...
95cc851ac350ca5f59f9c2709efeb878177a794b
PlayPython/homework
/chengqianlong/homework/test2.py
394
3.90625
4
#创建一个字典,把字典中的键按照字母顺序显示出来 dict={'d':1,'b':2,'h':3,'z':4} a=dict.keys() print(sorted(a)) #根据已经排序好的字母的键,显示这个字典中的键和值 d=sorted(a) for i in d: s=dict.get(i) print(s) #使用随机数模块生成一个随机数集合A和B,每个集合是0到9的随机数集合。生成之后显示结果A|B和A&B
9124a6e59c2a82797a9a8362b350a1edba4322c5
PlayPython/homework
/chengqianlong/homework/test.py
1,160
3.71875
4
import random #使用循环和算数运算,生成0到20的偶数 print([i for i in range(0,21) if i % 2]) #使用循环和算数运算,生成0到20的奇数 print([i for i in range(0,21) if i % 2 ==0]) #写一个函数,判断一个数是否被另外一个函数整除 def work(i,j): if i % j == 0: print("%d能被%d整除"%(i,j)) else: print("%d不能被%d整除"%(i,j)) #work(6,3) #work(6,4) #判断一个数字是否为素数 def test()...
a2859e5d0bc3d0f1d67bc24d5c546e745eceed97
PlayPython/homework
/huangjian/lianxi20180506.py
1,775
4.0625
4
# 异常和错误练习 # 使用try-except处理文件打开异常,打开一个不存在的文件,打印提示信息,但是程序不中断 def try_except_open(): try: f = open("huang", "r") except FileNotFoundError as a: print(a) print("打开的文件不存在") try_except_open() # 使用raise强制抛出异常,input()只接受正整数的输入,否则中断程序,强制抛出异常 def raise_input(): try: num = int(input...
baab97095549d2a4f919c871f47e6749aa54a899
PlayPython/homework
/sheldon/dictionary_practice.py
823
3.875
4
# - 创建一个字典,把字典中的键按照字母顺序显示出来 # - 根据已经排序好的字母的键,显示这个字典中的键和值 # - 使用随机数模块生成一个随机数集合A和B,每个集合是0到9的随机数集合。生成之后显示结果A|B和A&B import random a = {'a': 1, 'A': 10, 'b': 2, 'c': 3, 'C': 30} a_key = a.keys() print(sorted(a_key)) print("=" * 20) for key in a_key: print(a[key]) print("=" * 20) # create random numbers A_random_list...
076ff0226f0613521ff0451e268f262e18c59ea4
PlayPython/homework
/joyfulc/except_2018.05.06.py
832
4.09375
4
#- 使用try-except处理文件打开异常,打开一个不存在的文件,打印提示信息,但是程序不中断 def except_test(): try: f = open("haha.txt",'r') except FileNotFoundError as e: print(e) print("文件可能不存在") #- 使用raise强制抛出异常,input()只接受正整数的输入,否则中断程序,强制抛出异常 def raise_except_test(s1): try: if isinstance(int(s1), int) and int(s...
40eaa4c57aa6b87951e12e730e853ea514072505
PlayPython/homework
/mdl/first_test/string_list_practice.py
759
3.578125
4
# -*- coding: utf-8 -*- # @Time : 2018/4/1 21:32 # @Author : mdl # @Email : 1271737949@qq.com # @File : string_list_practice.py # @Software: PyCharm '''字符串和列表''' # - 创建一个函数,除去字符串前面和后面的空格 def str_strip(): r=" rrrsdf fff " print(r.strip()) # str_strip() # - 输入一个字符串,判断是否为回文 def palindrome(): s=...
a1c81c59d556c26c7d5657ebf821b4108e07b4ac
codeforcauseorg-archive/DSA-Live-Python-Jun-0621
/lecture-22/minDiffInBST.py
1,621
3.75
4
# https://leetcode.com/problems/minimum-distance-between-bst-nodes/ # Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def minDiffInBST(self, root: Optional[T...
a136cb5457dc633d947c462fd6a67cd4acc0941d
codeforcauseorg-archive/DSA-Live-Python-Jun-0621
/lecture-25/carPooling.py
2,634
3.78125
4
class Heap: def __init__(self, compare=None): self.__data = [] if compare: self.compare = compare else: self.compare = lambda first, second: first - second def insert(self, value): self.__data.append(value) self.up_heap(len(self.__data) - 1) ...
0916d39a2e9f4862d33901c104571f37b25243a8
codeforcauseorg-archive/DSA-Live-Python-Jun-0621
/lecture-28/Fibbo.py
867
3.734375
4
def fibo(num): if num < 2: return num return fibo(num-1) + fibo(num-2) def fiboDP(num, memory): if num < 2: return num if num in memory: return memory[num] memory[num] = fiboDP(num-1, memory) + fiboDP(num-2, memory) return memory[num] def fiboDPIter(number): m...
b53fb27016d732c08a7869d38d13162383b30b32
codeforcauseorg-archive/DSA-Live-Python-Jun-0621
/lecture-27/AdjListGraph.py
2,095
3.796875
4
class Vertex: def __init__(self, value): self.value = value self.neighbours = {} class AdjListGraph: def __init__(self): self.vertices = dict() def add_vertex(self, value): if value not in self.vertices: self.vertices[value] = Vertex(value) def add_edge(se...
31ef70774b514ddcb6d711d68150706572415881
codeforcauseorg-archive/DSA-Live-Python-Jun-0621
/lecture-23/balanceBST.py
4,002
3.8125
4
# https://leetcode.com/problems/balance-a-binary-search-tree class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right class Solution: def balanceBST(self, root: TreeNode) -> TreeNode: self.data = [] self.bala...
003657d42d0c97db4e20884b1bbe2c93139ca8d6
codeforcauseorg-archive/DSA-Live-Python-Jun-0621
/lecture-03/salaries.py
170
3.859375
4
# sal < 5000 then bonus is 500 # else bonus is 1000 salary = int(input("Enter Salary = ")) if salary < 5000: salary += 500 else: salary += 1000 print(salary)
dae584609228895cd3738016baddaf630213f585
codeforcauseorg-archive/DSA-Live-Python-Jun-0621
/lecture-21/BT.py
928
3.71875
4
class Node: def __init__(self, value): self.value = value self.left = None self.right = None class BinaryTree: def __init__(self): self.__root = None def add_node(self, direction, value): self.__root = self.__add_node_rec(self.__root, direction, value) def _...
f44062e0038d4f1a6edd6c6bf2ae5721b9d3d572
codeforcauseorg-archive/DSA-Live-Python-Jun-0621
/lecture-08/stringpool.py
90
3.546875
4
first = "vtvtuyvoyvoytctcgyocifcygcgcvugvgybhbvvyv" second = "vtvtuyvoyvoytctcgyocifcygcgcvugvgybhbvvyv" print(first is second) print(first[2:5] == second[2:5])
6d2f76e45c112a7ba8e897d44810f804d2989e6b
vividwang/python-start
/7-6.py
297
4
4
age = '' while age != 'quit': age = input('How old are ya?') if age == 'quit': break if int(age) < 3: print('You are for free.') elif int(age) > 3 and int(age) < 12: print('You have to pay 10 dollers.') else: print('You have to pay 15 dollers.')
8f900ac77411ea4adda9e72238b11531f5b9bb8e
vividwang/python-start
/6-11.py
493
3.71875
4
cities = { 'London':{ 'country':'England', 'population':12000000, 'fact':'enconomy', }, 'Paris':{ 'country':'French', 'population':10000000, 'fact':'art', }, 'ShangHai':{ 'country':'China', 'population':25000000, 'fact':'beauty'...
627252d91b7fbb651517f97e4621c1b38e712af1
vividwang/python-start
/5-4.py
157
3.765625
4
alien_color = 'red' if alien_color == 'green': print('You got 5 point for killing a alien.') elif alien_color != 'green': print('You got 10 point!')
de2be9f3ee52d1900f4e1729f395d257cfd73df3
vividwang/python-start
/Use_matplotlib/15-2.py
415
3.5
4
import matplotlib.pyplot as plt xValues = list(range(0,5000)) yValues = [x**3 for x in xValues] plt.scatter(xValues,yValues,c=yValues,cmap=plt.cm.Blues,s=40) #设置图表标题,并给坐标轴加上标签 plt.title('Square Number',fontsize = 24) plt.xlabel('Value',fontsize = 14) plt.ylabel("Square of Value",fontsize = 14) #设置刻度标记的大小 plt.tick_p...
f736d3ab281d5799f2b23400437c7350861afc1a
vividwang/python-start
/5-10.py
327
4
4
currentUsers = ['Eric','Jamme','Sonde','Vanke','Loude'] newUsers = ['Eric','James','Mark','Vanke','kerry'] for newUser in newUsers: for currentUser in currentUsers: if newUser.lower() == currentUser.lower(): print('You need find another name!') else: print('You can use this ...
7717cbb874ff761cd3fcabe1c2e9e3ba81543382
vividwang/python-start
/8-7.py
263
3.53125
4
def makeAlbum(singer,album,songs=''): Album = {'singer':singer,'album':album} if songs: Album['songs'] = songs return Album print(makeAlbum('Taylor Swift','Red')) print(makeAlbum('Sia','Cheap thrills',1)) print(makeAlbum('Ed Sheeran','Shape of you',1))
65af04ff2e2a9d3dba61f9d72ce5927b2d3bc480
vividwang/python-start
/9-7.py
685
3.765625
4
class User(): def __init__(self,firstName,lastName): self.firstName = firstName self.lastName = lastName def describeUser(self): print("User name was " + self.firstName.title() + ' ' + self.lastName.title() + ".") def greetUser(self): print("Hi " + self.firstName.title() + ...
6d73e0f1767e51ec2d63acccd98d306c0e8a7361
vividwang/python-start
/7-10.py
405
4.03125
4
stopFlag = False data = {} while not stopFlag: name = input("what's your name?") place = input("If you could visit one place in the world,where would you go?") data[name] = place repeat = input("Would you like to let another person respond?(yes/no)") if repeat == 'no': stopFlag = True fo...
98a13c143420d971cd6509caba6503b0588e9081
naveen5a0/TradingSystem
/trading system/main.py
2,268
3.515625
4
from trading_system import TradingSystem from trading_system import StockClass import sys import datetime ''' Sample stocks related data present in data.txt. This script uses that data for testing and printing the result. future Stock list (i.e) the function set_stocks stores the stocks list in stocks.txt Analysis of ...
7e68cc367f5124ffefc81355b0f17c5841d73b95
Botany-Downs-Secondary-College/mathsquiz-rasooli0ali
/mathQuiz323.py
5,555
3.75
4
from tkinter import* class MathQuiz: def __init__(self, parent): #first Welcome frame self.welcome = Frame(parent) self.welcome.grid(row=0, column=0) self.Titlelabel = Label(self.welcome, bg="black", fg="white",width=20,padx=30,pady=10, te...
8f88dd9d9d31ef8356522600ed52252125405880
dewaldabrie/algorithmic_toolbox
/week3_greedy_algorithms/4_collecting_signatures/covering_segments.py
1,620
3.921875
4
# Uses python3 import sys from collections import namedtuple from typing import List Segment = namedtuple('Segment', 'start end') def is_covered(segment: Segment, points: List[int]): covered = False for point in points: if segment.start <= point <= segment.end: return True return cover...
c3a2eb5007824606e531c3a722ecbf0e7ba7cc98
peircechow/cpy5p4
/q3_find_gcd.py
135
3.625
4
#q3_find_gcd.py def gcd(m,n): if m%n==0: return n else: return gcd(n,m%n) print(gcd(24,16)) print(gcd(255,25))
eb308c1871953c77fdc4a14d4ff7d11e1bc61ad6
watefeenex/Creatures
/All_files/Creatures.py
19,934
4.28125
4
import turtle import hashlib """This class represents a creature""" class Creature: # A creature stores its position and direction and its "DNA" - the list of instructions it follows def __init__(self, row, col, dna, direction): self.direction = direction self.row = row self.col = col ...
8383500443114805bbbc4babdabb45c0cb47e53b
letsdrinkit/python
/02_file2.py
802
3.640625
4
f = open("01_html.html", "r", encoding="utf-8") data = f.readline() f.close() #첫줄 print(data) print("-"*30) #불필요한 요소 제거 data = data.replace("\n", "").replace("<", "").replace(">", "").replace("!", "") print(data) print("-"*30) #반복문을 이용한 문자열 분리 words = data.split(" ") for word in words : print(wor...
a2049b8b9b71bfb8178d91435aea32d01aa37d4c
Manash-git/Python-Turtle-Graphics
/pattern/resource/circles.py
934
3.984375
4
import random import time import turtle t = turtle.Pen() win = turtle.Screen() win.bgcolor("black") win.title("Circling") def mycircle(red, green, blue): t.speed(0) t.color(red, green, blue) t.begin_fill() x = random.randint(10,100) t.circle(x) # draw a circle of random radius t.end_fill() t...
dfd46819d93ece5ad0557bdc334fe464ce5c7b5e
Manash-git/Python-Turtle-Graphics
/pattern/multiple_ring.py
344
3.703125
4
import turtle draw=turtle.Turtle() color_pallet = ["yellow","purple","cyan","pink"] draw.penup() draw.goto(200,0) draw.pensize(4) for i in range(4): draw.pendown() draw.begin_fill() draw.fillcolor(color_pallet[i]) draw.circle(100) draw.end_fill() draw.penup() draw.backward(100) turtl...
72426f5aa5b3e949c57d9ba81ebe66e125ac42d0
mbebiano/exercicios-python
/exerciciocoursera/vogal.py
185
3.703125
4
def vogal(vogal1): if vogal1 in 'aeiouAEIOU': a = True else: a = False return a vogal1 = input('Digite um caractere para verificar: ') print(vogal(vogal1))
03ea3f66d0b5877ac456866cf54cf08ba53dd86d
mbebiano/exercicios-python
/exerciciocoursera/ImprimirSomaDigitos.py
209
3.796875
4
#Imprimir soma dos digitos de um número. n = input('Digite um número inteiro: ') count = 0 acumulador = 0 while count < len(n): acumulador = int(n[count]) + acumulador count+=1 print(acumulador)
132913466ab713c225b90d0787dab306ba2d5def
mbebiano/exercicios-python
/exerciciocoursera/faatorial.py
217
3.890625
4
# Imprimir Fatorial Number = int(input("Digite o valor de n: ")) Count = Number - 1 if Number == 0: print(1) else: while Count >= 1: Number = Number * Count Count= Count-1 print(Number)
8968afd9e65a3b8b2560fe902e0391503cc13e36
mbebiano/exercicios-python
/exerciciocoursera/buzz.py
335
3.671875
4
#Verificar se um número é Divisível por 5 import random def mensagemRandomizada(): arquivo = open('mensagensEnvio.txt', 'r') lista = arquivo.readlines() # readlinesssssss arquivo.close() mensagemAleatoria=random.choice(lista) return mensagemAleatoria; i=0; while(i<10): print(tempoAleatorio(...
5c863de5b2dcbb988039b67a97f3e995a7d05500
ngouzy/smartchangelog
/smartchangelog/datetools.py
231
3.53125
4
from datetime import datetime date_format = "%Y-%m-%d %H:%M:%S %z" def str2date(string: str) -> datetime: return datetime.strptime(string, date_format) def date2str(dt: datetime) -> str: return dt.strftime(date_format)
4b44a1bc5b4847c09e79d1825b6f2df40b4202e0
eangulee/python
/stock/test.py
1,038
3.53125
4
#-*- coding:UTF-8 -*- import math import stock years = 10 multiple = 3 # 倍数 currentFlow = 20 profits = 20 growthRate = 0.1 # 未来增长率 r = stock.calcDiscountRate(years,multiple) print str(years) +"年"+ str(multiple) +"倍贴现率:"+str(r) stock.calcInterValue(currentFlow,growthRate,r) # total = stock.calcCashFlow(profits,year...
03b8718eb3cdbe344d7f7b7413d0bfc03108ca6b
Abacn/AlgorithmParadigm
/LabHW-1/Part1/readNumbers.py
337
3.546875
4
# read interger numbers from files def readNumbers(filename): with open(filename, 'r') as fin: line = fin.read() numbers = [int(n) for n in line.split(',')] return numbers if __name__ == '__main__': # Test readNumbers method filename = '../test/A1.txt' numbers = readNumbers(filename) ...
33659189996c5f824182e4b4acbb2bbc7477e77a
1124418652/Machine_Learning
/KNN_algorithm.py
3,042
4.0625
4
# -*- coding: utf-8 -*- import os import sys import numpy as np import operator def filetodata(filename): """ the filetodata function is used to extra data from file the function has one parameter: filename: the name of the file that contains training data and each line is splited by tab """ with ...
52ce7b8609a86025da3e1ee3e6867cd81023ab6c
lalalalaluk/python-zerojudge-practice
/a024最大公因數.py
248
3.515625
4
import sys import math for inputValue in sys.stdin: number1 , number2 = inputValue.split() print(math.gcd(int(number1),int(number2))) #最小公倍數 #print(str(int(int(number1) * int(number2) / math.gcd(int(number1),int(number2)))))
f2061dea8fb1902ded6955f41ca998bf060cdb34
lalalalaluk/python-zerojudge-practice
/a053Sagit's 計分程式.py
422
3.578125
4
import sys for inputValue in sys.stdin: result = 0 inputValue = int(inputValue) if inputValue <= 10: result = str(inputValue * 6) elif inputValue > 10 and inputValue <= 20: result = str(60 + (inputValue-10) * 2) elif inputValue > 20 and inputValue <= 40: result = str(80 + (i...
e90acb673b0ef9264ebf127ebf0754cea694d650
mycodesrb/Deep_Learning_Algorithms_And_Analysis_Python_My_Codes
/ANN_Implementation_Keras_Mnist_Dataset_Building_Image_Recognition_And_Prediction_Model.py
3,855
4.21875
4
#!/usr/bin/env python # coding: utf-8 # Here, I have used the mnist dataset from Keras library. We will load this data, split in train and test and process the data # in order to make it in a proper format to input to the ANN model. Then we will train the model and we will check the loss # and accuracy of the ANN mode...
50108d83443226a485361c240295a866caf44716
marcuusmelo/mm_snippets
/flatten_json/json_to_csv.py
1,287
3.90625
4
"""General function for turning a json into a header and value lists""" def get_flat_json(json_data, header_string, header, row): """Parse json files with nested key-vales into flat lists using nested column labeling""" for root_key, root_value in json_data.items(): if isinstance(root_value, dict): ...
a10c1875dd3959bd23afd7525b8072093140b32e
andymbryant/ai50
/project0/tictactoe/helper.py
870
3.5625
4
X = "X" O = "O" EMPTY = None def count_value(board, value): count = 0 for row in board: for cell in row: if cell == value: count += 1 return count def get_positions_of_value(board, value): positions = set() for i, row in enumerate(board): for j, cell in ...
d7c010ac581bc648817f5fb17792a2bfd30ca774
PatrickNorton/Python-projects
/brainfuckinterpreter.py
1,599
3.515625
4
from mod import Mod code = input('Enter BF code here: ') tape = [Mod(0, 256)] pointerloc = 0 codepos = 0 stack = [] def interpret(code, tape, pointerloc, codepos, stack): currcode = code[codepos] currtape = tape[pointerloc] if currcode == '>': pointerloc += 1 elif currcode == '<': poin...
ffdafb0f724e62fbb96303ef0afc18afdacb3f20
PatrickNorton/Python-projects
/War.py
1,542
3.65625
4
class card: def __init__(self, number, suit): self.number = number+1 self.suit = suit def __str__(self): return str(self.number if self.number < 10 else 'tjqk'[self.number-10])+'♠♣♡♢'['schd'.index(self.suit)] def __eq__(self, other): return self.number == other.number ...
7fea623eb32b3b2fbb1b8ef06f61ff42a4f5aeeb
HumayraFerdous/Coursera_Python_Basics
/Week4.py
1,728
4.125
4
#Methods mylist=[] mylist.append(5) mylist.append(27) mylist.append(3) mylist.append(12) print(mylist) mylist.insert(1,12) print(mylist) print(mylist.count(12)) print(mylist.index(3)) print(mylist.count(5)) mylist.reverse() print(mylist) mylist.sort() print(mylist) mylist.remove(5) print(mylist) lastitem=mylist.p...
33c556c7f36355f3735523e7cde0cf12868de8ae
Viniciusli/basic-of-python
/5.poo/e6.py
1,500
4.15625
4
# crie uma clsse Elevador. # attrs: andar atual, total de andares (exluindo terreo), capacidade do elevador, # e quantidade de pessoas presentes nele # métodos: incializa, recebe a capacidade, total de andares, entra, acrescenta uma pessoa # sai, subtrae uma pessoa, sobe, sobe um andar, desce, desce um andar # nesse ex...
f257d5e04c22f4b4ae4c193912ed4aaabc1abe63
Viniciusli/basic-of-python
/4.funcoes_e_matrizes/e5.py
266
3.671875
4
# Exercício 5 - Abaixo você encontra duas listas. Faça com que cada elemento da listaA # seja elevado ao elemento correspondente na listaB. listaA = [2, 3, 4] listaB = [10, 11, 12] resultado = list(map(lambda x, y: pow(x, y), listaA, listaB)) print(resultado)
99bbf8e3d0816d3e7585a73a0bc5495d4c379b91
Viniciusli/basic-of-python
/4.funcoes_e_matrizes/e8.py
221
3.796875
4
# Exercício 8 - Considere o código abaixo. Obtenha o mesmo resultado usando o pacote time. import time import datetime print(datetime.datetime.now().strftime("%d/%m/%Y %H:%M")) print(time.strftime("%d/%m/%Y %H:%M"))
8ab5b7d8b7625d9a4401f9fff431dafc67627cf2
Viniciusli/basic-of-python
/3.lambdas/e12.py
265
4.125
4
# Exercício 2 - Crie uma função que receba uma string como argumento e retorne a mesma # string em letras maiúsculas. Faça uma chamada à função, passando como parâmetro uma # string def str_upper(str): return str.upper() print(str_upper("exemplo"))
3d8545dcc423c2be48466f432c09f071e0b2b26f
Viniciusli/basic-of-python
/3.lambdas/e2.py
276
4.09375
4
# Exercício 2 - Crie uma lista de 5 frutas e verifique se a fruta 'Morango' faz parte da # lista frutas = ["abacaxi", "banana", "maracuja", "cupuaçu", "morango"] if "morango" in frutas: print("Na sua lista tem morango") else: print("Na sua lista não tem morango")
7be57e3082efb5526e8f6274431923ebeaa28124
MoonJinhan/DocFile_Programming_note
/python/점프투파이썬 COPY/함수_test.py
2,210
4.09375
4
Q1.주어진 자연수가 홀수인지 짝수인지 판별해 주는 함수(is_odd)를 작성해 보자. def is_odd(): for i in input(): i=int(i) if i%2 == 0: print('짝수') elif i%2 != 0: print('홀수') return (i) print(is_odd()) Q2. 입력으로 들어오는 모든 수의 평균 값을 계산해 주는 함수를 작성해 보자. (단 입력으로 들어오는 수의 개수는 정해져 있지 않다.) 나의 답 def cal(...
2cc34374cc0297babc979e883907bde84b069e3b
JRGeneGarrigos/MIT-ZLog_Thesis
/MIT-Zaragoza_Thesis/load_network.py
4,058
3.609375
4
# -*- coding: utf-8 -*- """ Created on Fri May 5 18:18:15 2017 @author: JRGene """ from nodes_graph import WeightedEdge, SmartDigraph, SmartNode def load_Network(Filename): """ Parses the map file and constructs a directed graph Parameters: mapFilename : name of the map file Assumes: ...
96bf134d00802ad032852d9f789349fc358b042f
Jennykuma/coding-problems
/codewars/Python/invert.py
368
4.15625
4
''' Invert Values Level: 8 kyu Given a set of numbers, return the additive inverse of each. Each positive becomes negatives, and the negatives become positives. invert([1,2,3,4,5]) == [-1,-2,-3,-4,-5] invert([1,-2,3,-4,5]) == [-1,2,-3,4,-5] invert([]) == [] You can assume that all values are integers. ''' def invert(...
632516a8bb4db90d5a6cadb141db46400b3e947b
leequant761/Fluent-python
/15-context-mngr/else.py
973
3.546875
4
# else라 쓰고 then이라 읽는다. # for,while 루프가 완전히 실행된 후에(break 걸리면 안됨) else 블록 실행 for item in [1, 2, 3, 4]: if item == 5: break else: raise ValueError('No 5 found') # try 블록에서 예외가 발생하지 않으면 else블록으로 실행(else블록 예외는 except가 안잡음) import random def dangerous_call(): if random.randint(1,3) == 3: raise ...
f1a5cba866e8de5121878cc419175d556b418c43
CarolineXiao/InterviewAlgorithmPractice
/06.PrintLinkedlistReversely.py
1,485
3.921875
4
# Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: def reversePrint(self, head: ListNode) -> List[int]: # 1. append to left # if head == None: # return [] # result = [] # w...
9ab7c4181a3444407b0a2cc973799e1a83406eaa
AcidicNic/CS1.3
/circularbuffer.py
2,918
3.6875
4
class CircularBuffer: def __init__(self, max_size): self.max = max_size self.size = 0 self.list = [None] * max_size # index of head & tail self.head = None self.tail = None def __str__(self): """ Returns a string representation of this CircularBuffer ...
1935512981e39c884319a50eab0acf34657dbbd4
samanalishiri/python-tutorial-basic
/step_a_basic/datastructure/sort.py
790
3.609375
4
from itertools import groupby from operator import itemgetter # Saman Alishiri samanalishiri@gmail.com rows = [ {'address': '5412 N CLARK', 'date': '07/01/2012'}, {'address': '5148 N CLARK', 'date': '07/04/2012'}, {'address': '5800 E 58TH', 'date': '07/02/2012'}, {'address': '2122 N CLARK', 'date': '...
b291cb1d9502acd7423a8bea0c75cc18086a5a0a
samanalishiri/python-tutorial-basic
/step_g_database/sqlite.py
1,052
3.65625
4
import sqlite3 class ConnectionPool: def __init__(self): self.connection = sqlite3.connect(':memory:') def get(self): return self.connection class Person: def __init__(self, name, surname): self.name = name self.surname = surname def fullname(self): return '...
19dafa017664568e7c80d0f1f158d82190b490e2
samanalishiri/python-tutorial-basic
/step_a_basic/text/regularexpression.py
272
3.5
4
import re email_pattern = re.compile('[\w.\-_]+@\w+\.\w+') email_fullmatch_pattern = re.compile('[\w.\-_]+@\w+\.\w{2,3}') with open('emailsample.txt') as file: [print(email) for email in email_pattern.findall(file.read()) if email_fullmatch_pattern.fullmatch(email)]
27c4b0cb33de27d776ac556bbdc54f42462d0e29
shubhamjain31/Competitive_Coding
/Data_Structure/DS_Using_Python/Tree.py
1,499
4
4
class Tree: def __init__(node,value): node.value = value node.right = None node.left = None def createNode(node,value): if (node.value is None): node.value = value else: if( value < node.value ): if (node.left is None): ...
8dbf70683faba81be6a4feb58ab229f24140a6bf
shubhamjain31/Competitive_Coding
/Python/Find_Height_Of_Tree.py
1,305
4.09375
4
class BinaryTree: def __init__(self, data): self.data = data self.left = None self.right = None def inOrder(self, tree): if tree is None: return self.inOrder(tree.left) print(tree.data, end=' ') self.inOrder(tree.right) def getHeight(self, root): if root == None: return -1 ...
78802c5888738f3c891a62e60e5cc4f991dbbde3
shubhamjain31/Competitive_Coding
/Data_Structure/DS_Using_Python/Merge_PointofTwo_LinkedList.py
1,497
3.921875
4
class Node: def __init__(self, data): self.data = data self.next = None class findPointOfMerge: def __init__(self): self.head = None def printList(self): if self.head is None: print('List has no element') return else: temp = self.head while(temp): print(temp.data, end=' ') temp = ...
a138745482b36f58c12a320f919afdabfc9ae645
shubhamjain31/Competitive_Coding
/Python/Lowest_Common_Ancestor.py
927
3.921875
4
class BinaryTree: def __init__(self, data): self.data = data self.left = None self.right = None def inOrder(self, tree): if tree is None: return self.inOrder(tree.left) print(tree.data, end=' ') self.inOrder(tree.right) def lca(self, root, n1, n2): if root is None: return None # If ...
b2e51ed17a40817959fe174d85b76289c24b132f
shubhamjain31/Competitive_Coding
/Python/Kadane's_ Algorithm.py
582
3.8125
4
#Maximum Subarray Problem def maxSumarray(nums, size): max_ending_here = 0 max_sum_so_far = 0 for i in range(0, size): max_ending_here = max_ending_here + nums[i] if max_ending_here < 0: max_ending_here = 0 if max_sum_so_far < max_ending_here: max_sum_so_far = max_ending_here return max_sum_so_far ...
ee6bd877093ea83199dee3f6159ba4e6441e2b83
shubhamjain31/Competitive_Coding
/Data_Structure/DS_Using_Python/Deletion_Singly_LinkedList.py
2,399
4.0625
4
class Node: def __init__(self, data): self.data = data self.next = None class SinglyLinkedList: def __init__(self): self.head = None def printList(self): if self.head is None: print('List has no element') return else: temp = self.head while(temp): print(temp.data, end=' ') temp = t...
1d2e8e7dca049ae7be0702742ebab2451f3f40f9
shubhamjain31/Competitive_Coding
/Data_Structure/DS_Using_Python/Stack_Using_LinkedList.py
1,065
4.0625
4
class Node: def __init__(self, data): self.data = data self.next = None class Stack: def __init__(self): self.head = None def isEmpty(self): if self.head == None: return 1 else: return 0 def peek(self): if self.isEmpty(): print('Stack is empty') return return self.head.data def...
6f415a65884ff4b6d2bd47c35d4b16759954ffc9
JoeSamyn/Grocery_List_App
/groceryListApp.py
2,040
4.09375
4
import os def clear_list(): os.system("cls" if os.name == "nt" else "clear") def show_help(): print("What should we pick up at the store?") print("Enter 'DONE' to stop adding items.") print("Enter 'HELP' for help window.") print("Enter 'PRINT LIST' to print your entire list.") print("Enter 'R...
9b5bee6a7da2e798ce43ada78574499085fa0eab
smpcole/tic-tac-toe
/main.py
635
3.640625
4
from Board import * from Player import * def main(): board = Board() humanFirst = raw_input("Do you want to go first? (y/n) ") players = [ComputerPlayer('x', board), HumanPlayer('o', board)] if humanFirst == 'y': players.reverse() turnNum = 0 currentPlayer = None while not board.end...
bd60bb9140beee6158f0c2e40f8635822bf0049d
MasoniteFramework/core
/masonite/helpers/sign.py
1,021
3.5
4
from masonite.auth import Sign def sign(value): """Shortcut for Sign class. Arguments: value {string} -- The value that is going to be encrypted Returns: string -- The string value after encryption. """ return Sign().sign(value) def encrypt(value): """Shortcut for Sign clas...
945e385385740a8d676bdb6c3b7282d1b6d368c2
MasoniteFramework/core
/masonite/helpers/structures.py
5,501
3.71875
4
"""A Module For Manipulating Code Structures.""" import inspect import pydoc from orator.support.collection import Collection as collect class Dot: def dot(self, search, dictionary, default=None): """The search string in dot notation to look into the dictionary for. Arguments: sear...
da946d3a624f826791a0fab5508e0feb72cb1f16
EdwinMelendez/Lab2CardGame
/Deck.py
2,188
3.625
4
import random # Adapted from Andy's text book class Deck: def create_deck(self): # creates dictionary of cards and their values # stored as key-value pairs deck = {'Ace of Spades': 1, '2 of Spades': 2, '3 of Spades': 3, '4 of Spades': 4, '5 of Spades': 5, '6 of Spades': ...
39d7a894a7bfd33d34adf405a0024df776b2bdba
harshadwaghmare/test
/perfectnumber.py
297
3.546875
4
#!/usr/bin/python3 def isperfectnum(num): sumofdivisors = 0 for i in range(1, (num // 2) + 1): if not (num % i): sumofdivisors += i return sumofdivisors == num if __name__ == '__main__': for i in range (1000): if isperfectnum(i): print (i)
71c2a447814f3c916acebd27f9abb616a4526096
harshadwaghmare/test
/wordspacing.py
667
3.53125
4
#!/usr/bin/python3 def wordspacesp(sentstr, dict): returnstr = '' for i in dict: if i in sentstr: returnstr += i + ' ' print (returnstr) def wordspacegn(sentstr, dict): returnstr = '' j = 0 for i in range (len(sentstr) + 1): if sentstr[j:i] == ' ': i += ...