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
228c27b3406c45f10f3df2588de29e1d4ad5bfcb
AjayHao/helloPy
/demos/basic/list.py
684
4.21875
4
#!/usr/bin/python3 # 元祖 list1 = ['Google', 'Runoob', 1997, 2000] list2 = [1, 2, 3, 4, 5, 6, 7, 8] # 随机读取 print ("list1[0]: ", list1[0]) print ("list1[-2]: ", list1[-2]) print ("list2[1:3]: ", list2[1:3]) print ("list2[2:]: ", list2[2:]) # 更新 list1[2] = '123' print ("[update] list1: ", list1) # 删除 d...
a97267baf084e7e54bc75706b82fe02fcbe7f519
AjayHao/helloPy
/demos/designpatterns/creational/singleton_pattern.py
301
3.59375
4
class Singleton: def __init__(self): pass def __new__(cls): if not hasattr(Singleton, "__instance"): Singleton.__instance = super(Singleton, cls).__new__(cls) return Singleton.__instance obj1 = Singleton() obj2 = Singleton() print(obj1, obj2)
3551929bd1814c20eca69cbb80290d2ff8de8372
chaksamu/python
/venv/binarysearch.py
442
3.609375
4
pos=-1 def search(list,s): l=0 u=len(list)-1 print(l,u) while l<=u: mid=(l+u) // 2 print(mid) if list[mid]==s: globals()['pos']=mid return True else: if list[mid] < s: l=mid+1 else: u=mid-1 ...
7a5473750801417f14ab6605e911b5d5765d04b7
chaksamu/python
/venv/multithreads.py
486
3.90625
4
from time import sleep from threading import * class Hello(Thread): def run(self): #run is default method for i in range(5): print("Hello") sleep(1) t1=Hello() #t1.run() t1.start() sleep(0.5) class Hi(Thread): def run(self): for i in range(5): prin...
477250d187e782933186cb9bf8b3b4e6a9ece45c
chaksamu/python
/venv/calendar.py
595
3.90625
4
import calendar for month in calendar.month_name: print(month) for month in calendar.day_name: print(month) for month in calendar.day_name: print(month) c=calendar.TextCalendar(calendar.SUNDAY) str=c.formatmonth(2025,12) print(str) c = calendar.TextCalendar(calendar.TUESDAY) str = c.formatmonth(2025, 2) pri...
b8ad231bf1e687ee05105ea6440ed20c9f263f6f
chaksamu/python
/venv/classinsideclass.py
711
3.8125
4
class Student: def __init__(self,name,rollno): self.N = name self.R = rollno self.L = self.Laptop() def show(self): print(self.N,self.R) self.L.show() class Laptop: def __init__(self): self.brand = 'hp' self.cpu = 'i8' sel...
35d4105326e91ac51680a7a0d7e50d17a87c79d9
chaksamu/python
/venv/loops.py
594
3.921875
4
#While def main(): x=0 while (x<=5): print(x) x=x+1 #print(x) main() #For def main(): x=0 for x in range(2,7): print("The ",x) main() def main(): Months={"Jan", "Feb", "Mar"} for i in Months: print(i) main() #break def main(): y={1,2,3,4,5,6,7,8,9,1...
227ace258237b03dd4bb000ad3b4abec216c656b
chaksamu/python
/venv/bubblesort.py
305
3.828125
4
def sort(nums): print(nums) for i in range(len(nums)-1,0,-1): for j in range(i): if nums[j]>nums[j+1]: t=nums[j] nums[j]=nums[j+1] nums[j+1]=t print(nums) #print(nums) nums=[6,5,4,3,2,1] sort(nums) #print(nums)
a547e08af1445d7aa9f2ff0d95fc66d9f2a8c9db
chaksamu/python
/venv/steps/liststeps3.py
271
3.609375
4
name=str(input("Enter the Filename: ")) f=open(name,'r') #ff=f.read() #print(ff) #gg=(ff.split()) #print(gg) for line in f: if not line.startswith('From'): continue tt=line.split() print(tt[1]) yy=tt[1] zz=yy.split('@') print(zz) #4:13:00
e99b2ad952745f289c6e8e19ac756e975092606c
Akshay1997a/Python-Datastructure
/LinkedList.py
1,841
4
4
from os import system def cls(): system('clear') class Node: def __init__(self, val): self.data = val self.next = None class LinkedList: def __init__(self): self.head = None def addNode(self, list): for i in list: if self.head == None: s...
faf4ef2dab7840dfe0c778377e4998fa951ab988
quynhhgoogoo/Artificial-Intelligence
/lectures/n-grams/ngrams.py
1,105
3.625
4
from collections import Counter import math import nltk import os import sys nltk.download('punkt') def main(): '''Calculate top term frequencies for a corpus of documents''' if len(sys.argv) != 3: sys.exit("Usage: python ngrams.py n corpus") print("Loading data...") # Loading input n =...
1d2d81b28514c9d02774bab739dff207a7e619f0
nixeagle/euler
/2/flare183.py
265
3.53125
4
def fib(): x,y = 0,1 while True: yield x x,y = y, x+y def even(seq): for number in seq: if not number % 2: yield number def problem(seq): for number in seq: if number > 4000000: break yield number print sum(even(problem(fib())))
4646413619e71320a217116999fa2ba6fc4e7992
ZanderBE/Fill-in-the-Blank-Quiz
/Final-Version-Fill-In-The-Blank-Quiz.py
7,241
3.71875
4
guessCounter = 5 guessIndex = 0 outOfLives = 0 blankList = ["BLANK1", "BLANK2", "BLANK3", "BLANK4"] promptList = ['What do you think fills "BLANK1"? ', 'What do you think fills "BLANK2"? ', 'What do you think fills "BLANK3"? ', 'What do you think fills "BLANK4"? '] easyMod...
0d113719859b6ff06717d69e0bd4aee5150985ee
wrf22805656/Web-Crawler
/Scraping data - example one
555
3.640625
4
#! /user/bin/env python import re import urllib2 def download(url): print ('downloading:' "\n", url) try: html = urllib2.urlopen(url).read() except urllib2.URLError as e: print 'Downloading error:', e.reason html = None return html url =...
aeed9a1fecdf64c15fed3310d68fc54cfb839475
trallorc/Steev
/Moshe Sharat/hexmap/Render.py
7,712
3.640625
4
from abc import ABCMeta, abstractmethod import pygame import math from Map import Grid SQRT3 = math.sqrt(3) class Render(pygame.Surface): __metaclass__ = ABCMeta def __init__(self, map, radius=16, *args, **keywords): self.map = map self.radius = radius # Colors for the map s...
7c3a1cf25c041f0212a7764e4aad57abecf7f9bf
kanglicheng/GoogleCodeJam
/2019/Qualification/B/b.py
263
3.59375
4
def solve(): N = int(input()) S = input() ans = "" for c in S: ans += "E" if c == "S" else "S" return ans if __name__ == "__main__": T = int(input()) for t in range(1, T + 1): print("Case #{}: {}".format(t, solve()))
7dbb6ceb733fa90b5f1cc5ab5521cffaf24d7c0f
ryanmcfarland/file-tk-downloader
/classes/reqdl.py
937
3.5625
4
import requests import os import sys import urllib3 class RequestFile: def __init__(self, dir="", filename="", url=""): self.dir = dir self.filename = filename self.url = url ## --> check if the directory exists def check_dir_exists(self): if not os.path.exists(self.fil...
a66405eeea9904f8c4967a7789bc6a4841713f24
anumulaphani/nodejs-application
/sales enhancement.py
255
3.796875
4
sales = float(input("Enter sales: $")) while sales <= 0: print("Invalid option") sales = float(input("Enter sales: $")) if sales < 1000: bonus = sales * 0.1 print(bonus) else: bonus = sales * 0.15 print(bonus) print("good bye")
fcf2d76ad0f3015988ae7b445870405ac0e2e668
anumulaphani/nodejs-application
/practicals 2/practicals_3/value_error.py
436
4.0625
4
def get_num(lower, upper): while (True): try: user_input = int(input("Enter a number ({}-{}):".format(lower, upper))) if user_input < lower: print("Number too low.") elif user_input > upper: print("please enter a valid number") ...
977529bdb4da2c8b6a0a7d5749b57dca59ece90c
Wormandrade/Trabajo01
/eje02.py
358
4.03125
4
#Calcular el perímetro y área de un círculo dado su radio. print("========================") print("\tEJERCICIO 02") print("========================") print("Cálculo de périmetro y área de un círculo\n") radio = float(input("Ingrese el radio: \n")) pi=3.1416 print("El perímetro es: ",round(radio*pi,2)) print("El área e...
2c388737f42543942819ef22f8faac2098bff0c3
SeanLau/leetcode
/problem_167.py
1,444
3.640625
4
#!/usr/bin/env python # -*- coding:utf-8 -*- class Solution(object): def twoSum(self, numbers, target): """ 时间复杂度,O(N*logN) :type numbers: List[int] :type target: int :rtype: List[int] """ def binary_search(mlist, start, end, target): while end >...
0b303dde589390cf6795a2fc79ca473349c5e190
SeanLau/leetcode
/problem_104.py
1,203
4.125
4
#!/usr/bin/env python # -*- coding:utf-8 -*- # 此题可以先序遍历二叉树,找到最长的即可 # Definition for a binary tree node. class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: def maxDepth(self, root): """ :type root: TreeNode :r...
454512c0eacf9f9471ce330911247e85b5723d71
SeanLau/leetcode
/problem_190.py
733
3.578125
4
#!/usr/bin/env python # -*- coding:utf-8 -*- class Solution(object): """ 这里需要注意的是,切片使用的灵活性. """ def reverseBits(self, n): """ :param n: :return: """ foo = bin(n) foo_str = str(foo)[2:] foo_str = foo_str.rjust(32, "0") foo_str = list(foo_s...
6cfb4c27f0a897695d4b0bf229f64f5d0d5bb378
SeanLau/leetcode
/problem_160.py
3,348
3.75
4
# Definition for singly-linked list. class ListNode(object): def __init__(self, x): self.val = x self.next = None class Solution(object): def getIntersectionNode(self, headA, headB): """ 采用边遍历边判断的方法,实现了功能,但是提交超时 :type head1, head1: ListNode :rtype: ListNode ...
ee7fb11021cb2d237d0dcc5409c8a91461956339
vojtsek/tts-utils
/model/model.py
3,216
3.59375
4
''' A linear regression learning algorithm example using TensorFlow library. Author: Aymeric Damien Project: https://github.com/aymericdamien/TensorFlow-Examples/ ''' import tensorflow as tf import argparse from dataset import Dataset, Utterance import tensorflow.contrib.layers as tf_layers ap = argparse.ArgumentPa...
de483b8ac3b15b2472aac0ba7baf79f59c4bfb48
Aromi-s/Assignment-function
/evnorodd.py
129
4.1875
4
num=int(input("Enter a number")) mode=num%2 if mode>0: print("This is an odd number") else: print("This is an even number")
467a4efb5a3fde195fbf79387f3d3871f757a979
Vishruth-S/Hack-CP-DSA
/Hackerrank/drawingbook/solution.py
2,478
3.828125
4
#!/bin/python3 import os import sys # # Complete the pageCount function below. # def pageCount(n, p): # # Write your code here. # pages = [] count = 0 #For turing from page 1. loop_run_one = 0 #For turning from page n. loop_run_two = 0 #For storing count from page 1 and page n...
22bd9bc0d83a2d0390ad93812f48c6d8924ddee7
sberen/uninterrupted
/summarizer.py
2,179
3.53125
4
import requests def summary_from_url(url, sentences): f = open("key.txt", "r") querystring = { "key":f.read(), "sentences":sentences, "url":url } return summary(querystring) def summary_from_text(txt, sentences): f = open("key.txt", "r") querystring = { "key":f.read(), "sentences":sent...
c99bae5ac1bfa06c3796c5bb54a1d37d501a5a6a
srhternl/gaih-students-repo-example
/Homeworks/HW3.py
731
3.609375
4
def prime_first(number): # asal sayı hesaplayan 1. fonksiyonum. if number !=1 and number !=0: for i in range(2, number): if number % i == 0: break else: print("Prime numbers between 0-500:", number) def prime_second(number): # asal sayı hesaplayan 2. ...
fb7f473982a26309c9ec086f0595c25ee1df5b2f
thoftheocean/project
/python/0homework/supplement/ascii.py
226
3.984375
4
# !/usr/bin/env python # coding:utf-8 # author hx #描述:将ascii码转化为对应的字符。如65 #ascii码转字母 chr() for i in range(26): print chr(i+65), #字母转ascii码 ord() print '\n', ord('a')
4ddcc55205d7213c9e5cc51275bc953053038784
thoftheocean/project
/python/0homework/search_num.py
649
3.875
4
# !/usr/bin/env python # coding:utf-8 # author:hx ''' 实现一个函数handler_num,输入为一个任意字符串,请将字符串中的数 字取出,将偶数放入一个列表,再将奇数放入一个列表,并将两个列表返回 ''' str = raw_input('输入一串字符:') def search_num(str): even = list() odd = list() result1 = dict() for i in str: if i.isdigit(): if int(i) % 2 == 0: ...
501275ca7933a25249bda2278eca0be3fefb59ea
WiktorSa/Operating-Systems
/OS4/algorithms/equal_algorithm.py
1,895
3.609375
4
import math from algorithms.algorithm import Algorithm class EqualAlgorithm(Algorithm): def perform_simulation(self, processes: list): original_no_of_frames = self.divide_frames_at_start(processes) for i in range(len(processes)): processes[i].lru.set_original_number_of_frames(original_...
ceaf75e59c51a4374dc12cc8adee3c3f663449a7
skiranu/Python_
/Interface_Abstract_Concrete_class.py
548
3.96875
4
from abc import * #interface class Vehicle(ABC): @abstractmethod def noOfWheels(self): pass def noOfDoors(self): pass def noOfExhaust(self): pass #abstract class class Bus(Vehicle): def noOfWheels(self): return 7 def noOfDoors(self): ...
2f66a3dbe7423cbee94f32ee46a12af9262ca8d9
skiranu/Python_
/unzipping_disp.py
288
3.796875
4
from zipfile import * f=ZipFile('zippedfiles.zip','r',ZIP_STORED) content=f.namelist() for eachfile in content: k=open(eachfile,'r') print(k.read()) print('the contents of {} are displayed above'.format(eachfile)) print('unzipping and displaying of files are accomplished!!')
7907ca619c61fadfc515d1081b96da4c274954cb
skiranu/Python_
/Alpha_Ascii_Sequence_2.py
330
3.953125
4
a=input("enter the string:") #Input declaration. s=k=d=s1=' ' #Variable for loop for x in a: # loop to check the type of input(either alphabet or digit) if x.isalpha(): s=x else: s1=x k=k+s+chr(ord(s)+int(s1)) d=d+k...
688be646bf564663c8cf00b9dac769a45d2e30fb
skiranu/Python_
/Dict_Char_Count.py
190
3.765625
4
a=input("Enter the string:") b={} for x in a: b[x]=b.get(x,0)+1 print(b) #dictionary form for k,v in sorted(b.items()): print("The number of occurances of : ",k,"is:",v)
bcab985c6af25defb7fa3bb752d2c8989f89466b
ardnahcivar/Python
/Learning python/LarryArray.py
544
3.546875
4
if __name__ == "__main__": t = int(input()) for i in range(t): inversion_count = 0 n = int(input()) a = [int(i) for i in input().split()] #print(a) b = sorted(a) # print('sorted list is:', b) for i, j in enumerate(a): b = a[i+1:] ...
8e304fd05a53a20ad9bc8576c4eb8b9dc85f73c2
fly8764/LeetCode
/Tree/437 pathSum.py
2,411
3.890625
4
# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None # 题目说明,路径不一定包含根节点和叶子节点,所有,要遍历所有的可能 # 每个节点都可能 在或者不在路径中 # 单递归:从根节点遍历到每个节点时,从该节点往根节点遍历,必须包含该节点连续 # 路径中,其和满足要求的有多少条 # 双递归,包含该节点和不包含该节点,不包含该节点 又分为 左子树 右子树...
67c0a68629883bbbc5b2ebe32f5ffb832e458008
fly8764/LeetCode
/DP/121 maxProfit.py
2,308
4.09375
4
''' 思路: 方法一: 方法二:动态的选取 当前的最大收益 和当前的最小价格(为后面的服务) 当前最大收益 等于 max(当前收益,当前价格与之前最小价格差) 这个当前最大收益和当前最小价格 分别使用一个变量保存当前情况即可, 不需要保存之前的情况,保存了也用不到 ''' #second class Solution: def maxProfit(self, prices): size = len(prices) if size < 2:return 0 profit = 0 # min_price = float('-inf') #用负数来表示 ...
5f94c757a6e5feee5379278fa951e69e1fbc48a4
fly8764/LeetCode
/Tree/404 sumOfLeftLeaves.py
1,160
3.859375
4
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def __init__(self): self.ret = 0 def dfs(self,root): if not root: return if root.left and not r...
628bc364f43090ac70474469d2e708ffa27b02d8
fly8764/LeetCode
/Tree/104 maxDepth.py
683
3.90625
4
# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution1(object): def maxDepth(self, root): """ :type root: TreeNode :rtype: int """ if not root: ...
9ba3bdd359faaa10341fdd3d8eb98f5b09022945
fly8764/LeetCode
/Linked/61 rotateRight.py
2,050
3.75
4
# Definition for singly-linked list. ''' 注意点: 1. 空节点 2.k值的大小,k一般在长度范围内cnt, 如果大于长度范围cnt,要把k对cnt取余,使其在cnt范围内 取余要注意cnt = 1的特殊情况,取余无效,其实这时候就不用再算了, 长度为1的链表,怎么旋转都不会变化 3.cnt = 1,这个一上来要想到,不然后面就可能忘了 方法一:找到链表的长度,把后面k个节点一整串的拼接到开头 方法二:双指针法,也是先找到链表长度,再把后面k个节点使用双指针法 一个一个地 调换到前面 ''' class ListNode: def __init__(self, x): ...
62538b8fd6f4befdbe1fbd8635f6ed884eb50716
fly8764/LeetCode
/Tree/257 binaryTreePaths.py
1,189
3.578125
4
class Solution(object): def binaryTreePaths(self, root): if not root: return [] if not root.left and not root.right: return [str(root.val)] left, right = [], [] if root.left: left = [str(root.val) + '->' + x for x in self.binaryTreePaths(root.left...
5def0d595f79218e4cb62f249a1fa1a56dc4668d
fly8764/LeetCode
/Bit Manipulation/342 isPowerOfFour.py
877
3.640625
4
class Solution: def isPowerOfFour(self, n): #1.4的幂 最高位的1 都在奇数位上,所以判断最高位的1是否在奇数位, #2.或者奇数位只有一个1 #1.0x5 0101 &(0100)(4)== 0100(num) 判断奇数位上的1 #2.16进制 a:1010 都在偶数位上,(0100)(4)&(1010)(a)== 0 表示在奇数位上 #0xaaaaaaaa&n == 0 # return n > 0 and not n&(n-1) and n&(0x55555555) == n ...
19af6699431a5b3892d415b2941aa893a8c1bdea
fly8764/LeetCode
/Linked/92 reverseBetween.py
7,775
4.15625
4
# Definition for singly-linked list. ''' 方法一:递归法 问题:反转前N个节点 第N+1个节点,successor节点 递归解决,当N=1时,记录successor节点,successor = head.next 和全部反转不同,最后一个节点的next要指向 successor;head.next = successor 问题:反转第m到第n个节点 递归 一直到m= 1,则此时相当于反转前N个节点, 然后把之前的节点拼接起来 这里的递归返回的节点不像 全部反转或反转前N个节点, 这里返回的是正常的节点,相当于才重新拼接一下 方法二:双指针法 in-place 找到第m-1个节点pre,和第m...
4d6575ccd0f71b77f94f037547af970f1d1a4ce4
fly8764/LeetCode
/sort/386 lexicalOrder.py
895
3.515625
4
class Solution: # def __init__(self): # self.res = [] # # def find(self,m,n): # if m > n: # return # self.res.append(m) # # t = m*10 # for i in range(10): # self.find(t+i,n) # # def lexicalOrder(self, n): # res = [] # ...
443f43d8573c1f93becc0c91150fcc81f5a82634
fly8764/LeetCode
/sort/insert_sort.py
9,983
3.5625
4
class Solution1: def __init__(self): self.size = 0 def insetSort(self,nums): #T(n) = n**2 #从前往后遍历 size = len(nums) if size < 2: return nums for i in range(1,size): j = i-1 temp = nums[i] #扫描,从后往前扫描 whil...
c2d2c20ed5eab1db361735ead1d82573231ccdf5
fly8764/LeetCode
/Tree/429 levelOrderN.py
1,255
3.625
4
""" # Definition for a Node. class Node: def __init__(self, val, children): self.val = val self.children = children """ class Solution1: def levelOrder(self, root): if not root: return [] res = [] parent = [root] while parent: child = [...
911f7a55fcbe555fab00846892307a841e906bc5
fly8764/LeetCode
/Linked/328 oddEvenList.py
1,088
3.78125
4
# Definition for singly-linked list. ''' 大致思路: 把奇偶位置的节点分开,各自串接自己一类的节点,最后在拼接起来 使用双指针,一个是奇数节点,一个是偶数节点 在开头别忘了使用一个临时节点,保存第一个偶数节点,后面把其拼接在奇数尾节点的后面 ''' class ListNode: def __init__(self, x): self.val = x self.next = None class Solution: def oddEvenList(self, head): if not head or not head.next...
22a46ad25d160525a0137a0ef1833d2845b89aff
AmrEsam0/HackerRank
/python3/2d_Array_DS.py
709
3.609375
4
#!/bin/python3 def list_sum(l): total = 0 for i in range(len(l)): total = total + l[i] return total def hourglassSum(arr): max = -1000 s= [] sub_array = [] for m in range(4): for col in range(4): for row in range(3): s...
e3fc26f817596ff52cf7a97933ea0c192c5cef42
dsintsov/python
/labs/lab1/lab1-1_7.py
989
4.125
4
# № 7: В переменную Y ввести номер года. Определить, является ли год високосным. """ wiki: год, номер которого кратен 400, — високосный; остальные годы, номер которых кратен 100, — невисокосные (например, годы 1700, 1800, 1900, 2100, 2200, 2300); остальные годы, номер которых кратен 4, — високосные """ # Checking the ...
0d6c52bea723ecd9bd447f2b0962b4fb2f8876c5
Kenjal1992/Kenjal_Python
/Assignment_6.py
365
3.9375
4
def CheckNumber(no): if no>0: print("{} is Positive Number".format(no)) elif no<0: print("{} is Negative Number".format(no)) else: print("{} is Zero".format(no)) def main(): print("Enter the number:") n=int(input()) CheckNumber(n...
61108fc4bf8d95401c043bf945d49567192ed9f3
Kenjal1992/Kenjal_Python
/Assignment_7.py
216
3.765625
4
def Printstar(no): for i in range (0,no): print("*") def main(): print("Enter the number:") n=int(input()) Printstar(n) if __name__=="__main__": main()
c608249eb220babe22952f716e4c378ec3501ea4
jjalomo93/Python-Analysis
/PyRamen/main.py
5,151
3.921875
4
#!/usr/bin/env python # coding: utf-8 # In[1]: # import libraries from pathlib import Path import csv # In[2]: # Read in `menu_data.csv` and set its contents to a separate list object. # (This way, you can cross-reference your menu data with your sales data as you read in your sales data in the coming steps.) # ...
663b7ccb52e70b73824fe5f431fdc48c4e1e649a
MKerbleski/Data-Structures
/linked_list/linked_list.py
2,989
3.75
4
""" Class that represents a single linked list node that holds a single value and a reference to the next node in the list """ class Node: def __init__(self, value=None, next_node=None): self.value = value self.next_node = next_node def get_value(self): return self.value def get_next(self): retu...
b263615206c83b6d159fa7e138052a007b3940b9
billdonghp/Python
/variable.py
514
3.8125
4
''' 变量的作用域 ''' salary = 7000 def raiseSalary(salary): #salary形参 salary += salary * 0.08 raiseSalary(salary) print("raiseSalary加薪后:%d"%(salary)) def raiseSalaryII(salary): #通过返回值影响 salary += salary * 0.08 return salary salary = raiseSalaryII(salary) print("raiseSalaryII加薪后:%d"%(salary)) def raise...
24ef3ae3700fb03f7376673ee39067c362eee76a
billdonghp/Python
/stringDemo.py
877
4.25
4
''' 字符串操作符 + * 字符串的长度 len 比较字符串大小 字符串截取 [:] [0:] 判断有无子串 in not in 查找子串出现的位置 find() index() 不存在的话报错 encode,decode replace(old,new,count)、count(sub,start,end) isdigit()、startswith split、join '-'.join('我爱你中国') 隔位截取str1[::2] = str1[0:-1:2] start 和end不写时为全部;step=2 如果 step为负数时,倒序截取; ''' str1 = 'hello' a = 'a' b = 'b'...
a38739c2fa2c242811821ac1232993c8abf52047
billdonghp/Python
/Person.py
787
3.890625
4
''' 封装人员信息 Person类 ''' class Person: #属性 name = "林阿华" age = 20 rmb = 50.0 #构造方法 外界创建类的实例时调用 #构选方法是初始化实例属性的最佳时机 def __init__(self,name,age,rmb): print("老子被创建了") self.name = name self.age = age self.rmb = rmb # def __str__(self): re...
79cae2d6bab2e3f3ae2bdd46882a0546c6f44b5e
izmailovpavel/gplib
/gplib/covfun/cov_base.py
2,322
3.5
4
import numpy as np from abc import ABCMeta, abstractmethod from .utility import pairwise_distance, stationary_cov class CovarianceFamily: """This is an abstract class, representing the concept of a family of covariance functions""" __metaclass__ = ABCMeta @abstractmethod def covariance_function(self,...
fbf161851509a46fda44a240008bbe87d399d90b
pythonmentor/charles-p3
/maze.py
1,854
3.734375
4
#!/usr/bin/python3 # coding: utf-8 import pygame from pygame.locals import * from graphic_level import GraphicLevel from level import Level from inputs import inputs def screen_loop(picture): """ Welcome screen """ # Opening the Pygame window (660x600 corresponds # to a maze of 15x15 squares of 40x40 p...
504efd209634a4f0c4b34995a7cdef6bc5dcdfe7
namle-gamer/DP_CS_Code
/Tools Files/toolsNL.py
2,832
3.96875
4
''' isEven takes a single integer paramenter a >= 0 returning True if a is even then return true otherwise turn false ''' def isEven(a): if a % 2 == 0: return True return False ''' missing_char will take a letter away from a word in a given position ''' def missing_char(str, n): newStr = "" #create an...
962f447a73ebaa7f9c501e2acaca7dc2a71d6a58
t0rx/friendly-schedule
/friendlyschedule/scheduleparser.py
8,088
3.59375
4
"""Class to parse a textual schedule into a usuable structure.""" from datetime import date, datetime, time, timedelta import re from typing import List from .schedule import Schedule from .scheduletypes import ScheduleEntry, ScheduleEvent class Invalid(Exception): """Raised when there is a parsing error.""" ...
33f20b00560ce5050b419684c709bec347aba42e
tymefighter/AI
/gridMDP/gridMDP2.py
6,054
3.71875
4
import numpy as np import math """ 0: (r-1, c): up 1: (r+1, c): down 2: (r, c-1): left 3: (r, c+1): right """ def print_mat(a): for row in a: s = '' for x in row: s += ' ' + str(x) print(s) def print_grid(grid): for row in grid: s = '' for x in row: ...
144aadab9b2167c896838ae99747d606b91834a3
skad00sh/algorithms-specialization
/Divide and Conquer, Sorting and Searching, and Randomized Algorithms/0.4 week1 - bubble-sort.py
691
4.21875
4
def bubble_sort(lst): """ ------ Pseudocode Steps ----- begin BubbleSort(list) for all elements of list if list[i] > list[i+1] swap(list[i], list[i+1]) end if end for return list end BubbleSort ------ ...
fbcb252e38b6a91f947100d88f8828802bec1856
carmsanchezs/datacademy
/python_basic/diccionarios.py
532
3.78125
4
def main(): poblacion_paises = { 'Argentina': 44938712, 'Brasil': 210147125, 'Colombia': 50372424 } print(poblacion_paises['Argentina']) # imprime 44938712 #print(poblacion_paises['Mexico']) # KeyError for pais in poblacion_paises.keys(): print(pais) for...
b39e3d3e69f8a8452d6d5d4c8031a84d3b3b7c70
carmsanchezs/datacademy
/python_basic/recorrer.py
150
3.765625
4
def main(): frase = input('Escribe una frase: ') for letra in frase: print(letra.upper()) if __name__ == '__main__': main()
ada8e3b64923945dd7c82f9767b587ed40e377fb
abhyuday10/NEA-Intelligent-Car
/car.py
9,189
3.65625
4
"""Car module to manage all data for one car. Each car represents a solution in the environment. Performance of car in environment determines the strength of that solution.""" import pygame import math import environment as env import constants class Car(pygame.sprite.Sprite): """Defining the car class which inh...
73b64affd060589fbe25c5a49efcf9e41ad81993
DorianKucharski/big-data-vehicle-traffic
/Data/data_preparing.py
2,800
3.53125
4
""" Przygotowanie danych pobranych z Kaggle """ import random import pandas def generate_year(df_tmp: pandas.DataFrame, year: int) -> pandas.DataFrame: """ Generuje dane na zadany rok, posługując się przekazanymi danymi w obiekcie DataFrame. Generowanie obdywa się poprzez kopiowanie wpisów z...
9fd432ad1b1ee73e07698c9ab1c83312bebfb922
thinkphp/collatz
/collatz.py
205
3.859375
4
def Collatz(n): while True: yield n if n == 1: break if n & 1: n = 3 * n + 1 else: n = n // 2 for j in Collatz(1780): print(j, end = ' ')
379a186bc1a21dc591556d80a5298ceca9b77a80
mfigand/start_with_python
/07 - Error handling/logic.py
130
3.90625
4
x = 206 y = 42 if x < y: print(str(y) + ' is greater than ' + str(x)) else: print(str(x) + ' is greater than ' + str(y))
650c122e59fe918a01e76c0a01f794432e621279
shubh4197/Python
/PycharmProjects/day4/program1.py
934
3.671875
4
def outer(a): print("This is outer") def inner(*args, **kwargs): # inner function should be generic print("This is inner") for i in args: if type(i) != str: print("Invalid") break else: for i in kwargs.values(): ...
6179fa6cf1814016ab7b13e6cbb4dcf0d7e2833a
shubh4197/Python
/PycharmProjects/day4/program4.py
500
3.671875
4
class InvalidCredential(Exception): def __init__(self, msg="Not found"): Exception.__init__(self, msg) try: dict = {"Sachin": "ICC", "Saurav": "BCCI"} username = input("Enter username:") password = input("Enter password:") if username not in dict: raise InvalidCredential ...
52603c0b3bda574f3d6225bee89492e87df8b79e
EvanShui/interview_prep
/sort/selection_sort.py
483
3.6875
4
def selection_sort(A): for i in range(len(A)): min_idx = i for j in range(i+1, len(A)): if A[min_idx] > A[j]: min_idx = j print("swapping [idx: {}, val: {}] with [idx: {}, val: {}]".format(i, A[i], min_idx, A[min_idx])) A[i], A[min_idx] = A[min...
3bd6fa3a0e8d61e0fd0c10304a79d883c6471aae
deepakmatam/content_summary
/hack_gui.py
2,534
3.625
4
import Tkinter from tkFileDialog import askopenfilename m = Tkinter.Tk() m.title('News categorizer ') m.minsize(width=566, height=450) def choosefile(): filename = askopenfilename() # show an "Open" dialog box and return the path to the selected file label = Tkinter.Label( m, text = filename ) label.pack()...
b970b5e47e71e96495d5a7fef82af57309da2599
jffist/pyfoo
/pyfoo/mathfun.py
352
3.546875
4
import numpy as np def scale(x): """ Centers the vector by subtracting it's mean and scales by the standart error :param x: numeric vector :type x: numpy.array or list of numbers :returns: scaled vector of the same length with zero mean and deviation equal to 1 :rtype: numpy.array """ retu...
a2848e9c028940ce1147501710bef4dbcc147f59
darshind/python_intermediate_project
/q03_create_3d_array/build.py
230
3.90625
4
# Default Imports import numpy as np # Enter solution here def create_3d_array(): N = 28 random_array = np.arange(N-1) reshaped_array = random_array.reshape((3,3,3)) return reshaped_array print create_3d_array()
bf2cd8065542e92a19b392ab44b5bd8038077b07
helani04/EulerProjects
/16/1_Multiples of 3 or 5 below 1000 .py
87
3.640625
4
a=1 s=0 while (a<1000): if(a%3==0 ) or (a%5==0): s = s+a a=a+1 print (s)
d193d76fbd81a2e83bdbc76d62fc5f44726c4b55
helani04/EulerProjects
/16/19-Counting Sundays.py
482
3.734375
4
import time start = time.time() year=1901 day=6 firsts=1 count=0 while year<=2000: if year%400==0 or (year%4==0 and year%100!=0): feb=29 else: feb=28 months=0 NoOfDaysInMonths=[31,feb,31,30,31,30,31,31,30,31,30,31] while months<12: if day==firsts: count+=1 ...
5d9044a28fd1cbeeb0178f4be8abba86875ff2eb
marekhaba/addwidgets
/addwidgets/scrollable_frame.py
2,629
3.671875
4
import tkinter as tk from tkinter import ttk class ScrollableFrame(ttk.Frame): """ for adding widgets into the frame use .scrollable_frame, do NOT add widgets directly. use width and height to enforce size. for modifing the forced size use change_size. """ #borroved from "https://blog.tecla...
f7b532d7e46b5ffc609da81fcc795d85bbaadf19
danielabar/python-practice
/solutions/pick_word.py
414
3.578125
4
#!/usr/bin/envn python """Pick a random word from text file. Usage: python pick_word """ import random def pick_word(): with open('sowpods.txt', 'r') as sowpods: lines = sowpods.readlines() num_lines = len(lines) some_line_num = random.randint(0, num_lines - 1) print('Your ...
9be81cae09ef9b0c9401efc4f9edbbe43758bd24
mac912/python
/dictonary4.py
242
3.875
4
d={'d1':{'name':'zoro','age':21,'country':'japan'},'d2':{'name':'jerry','age':21,'country':'uk'},'d3':{}} print(d) print(d['d1']) print(d['d1']['name']) print(d['d2']['country']) d['d3']['name']='henry' d['d3']['age']=21 print(d)
60cff1227d0866a558d88df56dad871a8d189d9e
mac912/python
/calender.py
1,021
4.3125
4
# program to print calender of the month given by month number # Assumptions: Leap year not considered when inputed is for February(2). Month doesn't start with specific day mon = int(input("Enter the month number :")) def calender(): if mon <=7: if mon%2==0 and mon!=2: for j in range(1,31...
e7921ad0ba8990d2dafb5c39d2804463820cb46d
mac912/python
/dictonary.py
310
3.859375
4
dict1 = {1:'start', 'name':'saini', 'age':10} print(dict1) print(dict1['name']) #or print(dict1.get('age')) print(dict1.get(1)) print("After making some changes") print() dict1[1] = 'end' dict1['name']= 'manish' dict1['age'] = 20 print(dict1[1]) print(dict1['name']) print(dict1['age'])
24e2224dd8d882665643ddaf11800f602e81027e
scarint/usingpython
/exercises/14 python-inventory-program.py
2,075
4.03125
4
# http://usingpython.com/python-lists/ # Write a program to store items in an inventory for an RPG computer game. # Your character can add items (like swords, shields, and various potions) # to their inventory, as well as 'use' an item, that will remove it from the # inventory list. # You could even have other variable...
c4fd4291d7c6ff4ebe40d28579192478fb776e80
bisharma/Binay_Seng560
/converter.py
622
4.03125
4
import math # This will import math module # Now we will create basic conversion functions. def decimal_to_binary(decimal_num): result = bin(decimal_num) return result def binary_to_decimal(binary_num): result = int(binary_num) return result def decimal_to_octal(decimal_num): ...
b7fa421982e1756aca5ca2afc4c743d1bd7b7d0d
YuyangMiao/IBI1_2019-20
/Practical5/collatz.py
491
3.875
4
# -*- coding: utf-8 -*- """ Created on Wed Mar 11 09:54:34 2020 @author: joe_m """ #import an integer n n=7 #Judge if n=1 #If yes: print n and stop #If no: # print n # Repeat: # If n is even: n=n/2, print n # If n is odd: n=3n+1, print n # If n==1, stop if n==1: print (n) else: prin...
60363908ab9baed3f64f207efce46e44165d896f
Hyeeein/ClassLion_Python_2
/Week_2_Q9.py
532
3.546875
4
# Q9. 첫 번째 줄에 사람 수 N을 입력받고, 두 번째 줄에 N개의 정수를 공백으로 구분되어 입력받음 # 마피아 1명을 찾기 위해 투표를 하게 되는데 참가하는 사람의 수는 N명, 두 번째 줄은 차례로 마피아 의심자 번호를 적음 # 표 많이 받은 사람 퇴장 / 표 많이 받은 사람 2명 이상이면 skipped / 무효표 > 많이 받은 사람인 경우, 표를 가장 많이 받은 사람 퇴장 N = int(input()) data = list(map(int, input().split()))
8edf41423eeb9a977ad8f378c0b325d415470459
ryanbergner/nba-playoff-predictions
/Nba-Merge-df.py
1,216
3.578125
4
import pandas as pd import numpy as np # data from https://www.basketball-reference.com/leagues/NBA_2020.html # First, we will rename the columns in the opponent dataframe so we can tell the difference between the columns in the team dataframe and the opponent dataframe dfteam = pd.read_csv("NbaTeamData.csv") dfop...
3c70d4ae169d4f9a4523648aae1ac89137ca0c74
rakuishi/deep-learning-from-scratch
/ch04/error_functions.py
627
3.59375
4
# coding: utf-8 import numpy as np # 2 乗和誤差 def mean_squared_error(y, t): return 0.5 * np.sum((y-t)**2) # 交差エントロピー誤差 def cross_entropy_error(y, t): delta = 1e-7 return -np.sum(t * np.log(y + delta)) # 2 を正解とする t = [0, 0, 1, 0, 0, 0, 0, 0, 0, 0] y1 = [0.1, 0.05, 0.6, 0.0, 0.05, 0.1, 0.0, 0.1, 0.0, 0.0] y2 = [...
76199c07a591052fa6309227c134850017f0fc5a
aomi/battlesnake-python
/app/astar.py
3,227
3.6875
4
#Determines distance via manhattan style def manhattanWeight(current, goal): return abs(current.x - goal.x) + abs(current.y - goal.y) def astar(start, goal): print("start: ", start.x, start.y) print("goal: ", start.x, start.y) start.netWeight = 0 lastTurnWeight = 0 openList = [start] close...
375c3c159d03fef9573d88b80e29b7bd532544a4
c3forlive/uip-prog3
/Tareas/Tarea2.py
543
3.796875
4
#Tarea2 #License by : Karl A. Hines #Velocidad #Crear un programa en Python que resuelva el siguiente problema #de física: #Una ambulancia se mueve con una velocidad de 120 km/h y #necesita recorrer un tramo recto de 60km. #Calcular el tiempo necesario, en segundos, #para que la ambulancia llegue a su destino. ...
47e4b1b02962b4264cc9836d2733dd0c5ea674f6
nixil/python_study
/insertion_sort.py
340
3.984375
4
def insertionSort(ar): for j in range(1, len(ar)): key = ar[j] i = j - 1 while i >= 0 and ar[i] > key: ar[i + 1] = ar[i] i -= 1 print " ".join([str(x) for x in ar]) ar[i + 1] = key print " ".join([str(x) for x in ar]) return ar insertionS...
6ba56f86733692c643f7c7e7e1808773a56d23f3
nancypareta/Dice-Roll-Game
/dice roll game .py
477
3.53125
4
import tkinter import random root=tkinter.Tk() root.geometry('600x600') root.title('Roll Dice') l1=tkinter.Label(root,text='',font=('Helvetica',260)) def rolldice(): dice=['\u2680','\u2681','\u2682','\u2683','\u2684','\u2685'] l1.configure(text=f'{random.choice(dice)}{random.choice(dice)}') ...
d332a00c6b70b60c577c65af2257d7bd6437c280
ruben-fuertes/rosalind
/mmch.py
595
3.703125
4
from sys import argv from math import factorial file = open(argv[1]) seq = '' for line in file: line = line.rstrip().upper() if not line.startswith('>'): seq+=line # seq = 'CAGCGUGAUCACCAGCGUGAUCAC' def maxmatches(sec): '''This function takes a RNA sequence and calculates the number of different max matche...
ef81ba52131119c1e7052aa18f9cecda63883f1c
zhangdzh/GWC_Projects
/RandomMenu.py
1,317
4.09375
4
from random import * entrees=["burger", "chicken", "steak", "pasta"] sides=["macaroni and cheese", "salad", "fries", "biscuit", "coleslaw", "fruit"] desserts=["sundae", "cheesecake", "strawberry shortcake", "pie"] drinks=["soda", "smoothie", "milkshake", "water"] print("Here's your random menu:") EntreeIndex=...
8e5865daf077399e2e57f53532c0600611a6f717
dr2moscow/GeekBrains_Education
/I четверть/Основы языка Python (Вебинар)/Lesson-1/hw_1_6.py
2,173
3.75
4
''' # 6 Спортсмен занимается ежедневными пробежками. В первый день его результат составил a километров. Каждый день спортсмен увеличивал результат на 10 % относительно предыдущего. Требуется определить номер дня, на который результат спортсмена составит не менее b километров. Программа должна принимать значения парамет...
01ed5a8e3395ce7ca90b82ee6d4a8c9f1d1ab67a
dr2moscow/GeekBrains_Education
/I четверть/Основы Python (Видеокурс)/Python_1_7/Task_1_7_1.py
749
3.625
4
# Задание # 1 # # Даны два списка фруктов. Получить список фруктов, присутствующих в обоих исходных списках. # Примечание: Списки фруктов создайте вручную в начале файла. list_1 = ['Апельсин', 'Ананас', 'Манго', 'Маракуйя', 'Фейхуа', 'Банан', 'Помело', 'Апельсин'] list_2 = ['Апельсин', 'Яблоко', 'Груша', 'Грейпфрут', ...
839276f68d78539ebce39b5cbd8de329282fd68e
dr2moscow/GeekBrains_Education
/I четверть/Основы языка Python (Вебинар)/Lesson-2/homework_2.py
4,143
4.0625
4
# print("***********************************************************************") # print(" Задание № 1") # print("***********************************************************************") # ''' # # 1 # Даны два произвольные списка. Удалите из первого списка элементы присутствующие во втором с...
44db1bec51190545210fd7565518ad602e33b937
dr2moscow/GeekBrains_Education
/I четверть/Основы языка Python (Вебинар)/lesson-5/hw_5_5.py
2,192
3.78125
4
# Задание # 5 # # Создать (программно) текстовый файл, записать в него программно набор чисел, # разделенных пробелами. Программа должна подсчитывать сумму чисел в файле и выводить ее на экран. from random import randint def cat_numbers(file_object): # Генератор, который считыват "слова" разделенные пробелами и,...
773d9211d4e6037aff180f87f135d11e0f660d7e
dr2moscow/GeekBrains_Education
/I четверть/Основы языка Python (Вебинар)/lesson-3/hw_3_3.py
696
4.15625
4
''' Задание # 3 Реализовать функцию my_func(), которая принимает три позиционных аргумента, и возвращает сумму наибольших двух аргументов. ''' def f_max_2_from_3(var_1, var_2, var_3): return var_1 + var_2 + var_3 - min(var_1, var_2, var_3) my_vars = [] for count in range(3): try: var = float(input(f...