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
a80bbacac2d663c7d12921ec1a912eca94650c95
myarasi8/Python_Project
/project.py
9,659
4.125
4
def clean_text(txt): """Takes the txt and removes all the punctuation""" s = txt.lower() for ch in s: if ch in ['.', '!', '?', ',', ':', ';']: s = s. replace(ch, '') return s def sample_file_write(filename): """A function that demonstrates how to write a Python dictiona...
05cbd49c51ece6720534abc3add6c2a99cbc418d
nandansn/pythonlab
/learnings/oops/class/accesmodifierexample.py
310
3.8125
4
class Employee(object): name="" salary=0.0 def __init__(self,name,salary): self.name = name self.salary = salary def getName(self): return self.name def printEmployee(self): print("Employee => {Name:+"+self.getName()+",Salary:"+str(self.salary)+"}")
b0bdc1aef3cbdb35b9d6745ef02046a1449d389a
nandansn/pythonlab
/Learning/tutorials/chapters/operators/bitwise.py
477
4.3125
4
# Bitwise operators act on operands as if they were string of binary digits. It operates bit by bit, hence the name. x = input("enter number x:") y = input("enter number y:") x = int(x) y = int(y) print("bitwise {} and {}".format(x,y), x & y) print("bitwise {} or {}".format(x,y), x | y) print("bitwise not of {} "....
cbe34666044b33debf9dfcd89708b862233cce44
nandansn/pythonlab
/learnings/codingbat/list/max_end3.py
306
3.90625
4
def max_end3(nums=[]): replaceNum = -1 if nums[0] > nums[len(nums)-1] : replaceNum = nums[0] else: replaceNum = nums[len(nums)-1] for i in range(0,len(nums)): nums.remove(nums[0]) nums.append(replaceNum) return nums print(max_end3([1,2,3]))
208f239eae59b3c31659330d70ef06fbc8888281
nandansn/pythonlab
/learnings/oops/class/Account.py
528
3.703125
4
class Account(object): # private __name="" __balance=0.0 def __init__(self): self def setName(self, name): self.__name = name def getName(self): return self.__name def setBalance(self, balance): self.__balance = balance def getBalance(sel...
536b48aec333a66511de76e1670a4ae1e7c02f5a
nandansn/pythonlab
/durgasoft/chapter7/is-operator.py
379
3.859375
4
''' is operator used to check the reference value ''' x=10 y=10 print(x is y) x=256 y=256 print(x is y) x=258055555555555555555555555555555555555555555555555 y=258055555555555555555555555555555555555555555555555 print(x, y ) print(x is y) x=123.67 y=123.67 print ( x is y) x=True y=Tru...
81fea0f822b359e4bf423db2d154619d6c361a5a
nandansn/pythonlab
/durgasoft/chapter77/overriding-example.py
340
3.546875
4
class Parent: def Marry(self): print('arranged marriage') def Property(self): print('Parent property') class Child(Parent): def Marry(self): print('love marriage') def arranged(self): super().Marry() c1 = Child() c1.Property() c1.Marry() c2 = Ch...
760a8d4a8943f96c22c8637c0942fbaf515720fd
nandansn/pythonlab
/durgasoft/chapter72/example-multiple-inheritance.py
238
3.515625
4
class Father: def m1(self): print('height is 6 feet') class Mother: def m1(self): print('color is brown') class Child(Father, Mother): def m1(self): super().m1() c = Child() c.m1()
83e8412a46c0f05b0d7c37a92f90bd768ddb073f
nandansn/pythonlab
/Learning/tutorials/chapters/operators/comparison.py
556
4.125
4
x = input("enter number x:") y = input("enter number y:") x = int(x) y = int(y) #check equal print("check {} and {} are equal".format(x,y),x == y) #check not equal print("check {} and {} are not equal".format(x,y),x != y) #check less than print("check {} is less than {} ".format(x,y),x <y) #check greater than pri...
a15aa28ac9f40f41a1b9c49ba70254c10d224139
nandansn/pythonlab
/durgasoft/chapter35/dict.py
797
4.25
4
''' update dictionary, ''' d = {101:'durga',102:'shiva'} d[103] = 'kumar' #if key not there, new value will be added. d[101]='nanda' #if key already available, new value will be updated. print(d) ' how to delete elements from the dictionary ' del d[101] # if the key present, then the key and value w...
8b67e1aee1467cbba4c11d2994662e5a0db9bc0c
nandansn/pythonlab
/learnings/lambda/lambdawithmap.py
202
3.796875
4
numbers =[10,12,13,14] f = lambda num: num * 2 def displayNums(nums): for num in nums: print(num) t = map(f,numbers) displayNums(t) t = map(lambda x: x + 2, numbers) displayNums(t)
802008bee9c47bb84f28f4566466101b00c96d9a
nandansn/pythonlab
/learnings/List/reuse.py
452
3.890625
4
def readData(): count = input("How many? ") return count def displayList(names=[]): for name in names: print(name) def createNameList(count=0): names = [] for i in range(0,int(count)): name = input("Enter name:") names.append(name) return names def searchName(name="",n...
1e523cd3074b4db0945b7056db18e1e1d1310aa3
nandansn/pythonlab
/durgasoft/chapter77/example.py
408
3.609375
4
class Employee: def __init__(self, name, perDayWage): self.name = name self.perDayWage = perDayWage def __mul__(self, timesheet): return self.perDayWage * timesheet.daysWorked class TimeSheet: def __init__(self, daysWorked): self.daysWorked = daysWorked e = E...
b7ab016754340006bee4707760d7313471eafd43
nandansn/pythonlab
/Learning/tutorials/chapters/objandclass/inheritance/Employee.py
417
3.734375
4
import tutorials.chapters.objandclass.inheritance.Person as P class Employee(P.Person): orgName ="" salary ="" def __init__(self,name,age,orgName,salary): self.__init__(name,age) self.orgName = orgName self.salary = salary def getEmployee(self): return self def ge...
b002c745c7813fb63f8ab1b327697342df62cbd7
nandansn/pythonlab
/durgasoft/chapter47/random-example.py
427
4.15625
4
from random import * for i in range(10): print(random()) for i in range(10): print(randint(i,567)) # generat the int value, inclusive of start and end. for i in range(10): print(uniform(i,10)) #generate the float value, within the range. not inclusive of start and end values. for i in range(1...
0ae6f55a75131d2558fb657b0e320be2b2bde003
nandansn/pythonlab
/durgasoft/chapter32/list-slice.py
332
3.59375
4
''' slice = [begin:end:step] step can be either positive or negative, if step is positive, we need to move towards forward sirection, if step is negative, then we have to move reverse direction, being from end +1 end: if 0 or negative, then result is always empty string. ''' s ='01234567890' print(s[-2:-5:-1...
0a9211678d40ae79d821cc8ab219b08a7906fa8f
nandansn/pythonlab
/telusko-learning/map-function.py
236
4.03125
4
''' One of the common things we do with list and other sequences is applying an operation to each item and collect the result. ''' numList = eval(input('Enter numbers:')) results =list(map(lambda n: n * 2, numList)) print(results)
8acb4581d0fd725b4195214e38c461edad0fac74
nandansn/pythonlab
/learnings/codingbat/string/double_char.py
133
3.84375
4
def double_char(str): newStr ="" for c in str: newStr = newStr + (c * 2) return newStr print(double_char("The"))
a3985f381834d34385765884a3d64da73da00212
nandansn/pythonlab
/learnings/Loops/string_splosion.py
158
3.5625
4
def string_splosion(str): newStr ="" for i in range(len(str)+1): newStr = newStr + str[0:i] return newStr print(string_splosion('code'))
89bad08e5b41e99386f42b0913f5434a4f6e9845
nandansn/pythonlab
/Learning/tutorials/chapters/operators/identity.py
331
4.28125
4
# is and is not are the identity operators in Python. # They are used to check if two values (or variables) are located on the same part of the memory. x ="hello" y ="hello" print("x is y", x is y) y = "Hello" print("x is y", x is y) print(" x is not y", x is not y) x = [1,2,3] y = [1,2,3] print("x is not y", x...
0cba119db0fd232e66accba2f5190a158f7aec25
nandansn/pythonlab
/Learning/tutorials/workouts/square_root_of_a_number.py
95
3.765625
4
number = input('enter the number:') squareRoot = int(number) * int(number) print(squareRoot)
7c628628d02af37ba950ef8d9dbc4e4593f4c9c2
nandansn/pythonlab
/learnings/Loops/simplewhile.py
377
3.734375
4
i = 10; #While, if and break while i < 20: i+=1 print("nanda") if i == 20 : print("limit reached") break; else: print("limit not reached") #While, if and continue while i < 30: i+=2; print(i) if i == 30: i = 29 continue #While, else while i < 40: ...
9bc318e4200010d27ddbedfa435e9f65145062e8
nandansn/pythonlab
/durgasoft/chapter51/case-1.py
2,293
3.703125
4
''' try: stmt-1 stmt-2 stmt-3 try: stmt-4 stmt-5 stmt-6 except expression as identifier: stmt-7 finally: stmt-8 stmt-9 except expression as identifier: stmt-10 finally: stmt-11 stmt-12 1. if no exception: stmt-1,2,3,...
8bcf665c3e7bdeebafa7ce242db6203a3b6c40e4
nandansn/pythonlab
/learnings/lambda/lambdaexampleone.py
168
3.921875
4
f = lambda display: print(name) sum = lambda x,y: x + y name = input("Enter Name:") f(name) a = int(input("Enter a:")) b = int(input("Enter b:")) print(sum(a,b))
a5efff5d413bc3274fe10573134351cc6edf8043
nandansn/pythonlab
/learnings/codingbat/warmup2/front_times.py
97
3.515625
4
def front_times(str,n): str = str[0:3] * n return str print(front_times('Chocolate',2))
f8a5e33a4951bad6b2c6bf4e1b448310cfbbd205
nandansn/pythonlab
/durgasoft/chapter37/positional-args.py
248
3.703125
4
''' actual arguments are passed as per the actual argument position. number and order of args, must be matched. ''' def add(a,b,c): print(a+b+c) add(1,2,3) # add(1,2,3,4) TypeError: add() takes 3 positional arguments but 4 were given
20fde4ae652feef6eca4d69dbb116d740b9a2e28
nandansn/pythonlab
/Learning/forloopexample.py
311
4.1875
4
week_days = ['monday','tuesday','wednessday','thursday','friday'] week_ends= ['saturday','sunday'] count = 10; for c in range(count): print(c) for day in week_days: print(day) else: for day in week_ends: print(day) employees = {'name':'nanda'} for emp in employees: print(emp)
12fe67f6785b89a35ace0769e2733d45660b6b23
nandansn/pythonlab
/durgasoft/chapter33/functions_of_tuple.py
395
4.34375
4
''' functions of tuple: ''' 'len()' t = tuple(input('enter tuple:')) print(t) print(len(t)) 'count occurence of the elelement' print(t.count('1')) '''sorting: natural sorting order ''' t=(4,3,2,1) print(sorted(t)) print(tuple(sorted(t))) print(tuple(sorted(t,reverse=True))) 'min and ma...
f7e56a302177e43fb1da63f96ed0961cc336063f
nandansn/pythonlab
/problems/patternproblems/pattern36.py
227
3.65625
4
intMaxRows = int(input('Enter max rows:')) spaceCount = intMaxRows * 2 - 2 for i in range(1,intMaxRows*2+1,2): print('{}{}{}'.format(' '*int(spaceCount/2),str(i)*i,' '*int(spaceCount/2))) spaceCount = spaceCount - 2
38c501e6e1589c168ab1465059368289253ed11b
nandansn/pythonlab
/durgasoft/chapter31/list-comprehensions.py
452
4.03125
4
'apply the expression on each value on the range and return the list.' l=[x*x for x in range(1,11)] print(l) 'adding condition [expression for x in range if condition] and if condition is true apply the expression' l2 = [x*x for x in range(1,21)if x%2==0] print(l2) 'applying multiple expressions' l...
f1dd9fa0507cbc637bcb52db16520d9207ae939f
nandansn/pythonlab
/problems/patternproblems/pattern29.py
186
3.640625
4
''' ***** **** *** ** * ''' maxNumber = int(input('Enter input number:')) spaceCount = 0 for i in range(maxNumber,0,-1): print(' '*spaceCount+'*'*i) spaceCount += 1
13477e55ca09f571ac8ed4a1d2c0bf8ee6b87a45
nandansn/pythonlab
/durgasoft/chapter15/using-eval-function.py
716
4.1875
4
print(""" we can use eval function to read data, when we use eval function no need to make type conversion""") #a,b,c,d,e=eval([x for x in input("Enter data:").split()]) a = eval(input("enter a:")) b = eval(input("enter b:")) c = eval(input("enter c:")) d = eval(input("enter d:")) e = eval(input("enter e:")) print(...
1768974e8d6899bfe75320252c1de3bc6f120a18
nandansn/pythonlab
/learnings/codingbat/string/count_code.py
286
3.765625
4
def count_code(str=""): countCode = 0; for i in range(0,len(str)-3): newStr = str[i:i+4] print(newStr) if ( newStr.startswith("co") and newStr.endswith("e")): countCode = countCode + 1 return countCode print(count_code('aaacoeebbbcode'))
9ff3e6deb0e613d1832d8dff9cda8c4a0897e0b7
nandansn/pythonlab
/learnings/codingbat/string/left2.py
161
3.59375
4
def left2(str): if len(str) > 2: return str[2:len(str)] + str[0:len(str) - len(str[2:len(str)])] else: return str print(left2("he"))
41a80c40bff8e60d9978d4dd075ae32793406945
nandansn/pythonlab
/durgasoft/chapter63and64/del-example.py
337
3.546875
4
class Person: def __init__(self,name,age,phone): self.name = name self.age = age self.phone = phone def display(self): print(self.__dict__) def del_name(self): del self.name p = Person('Nanda',32,2345678) p.display() p.del_name() p.display() del p.p...
581ad96b03b49138a25783d9cacd4bb132984259
nandansn/pythonlab
/durgasoft/chapter13/shiftoperators.py
272
4.53125
5
print(""" shift operators how it works""") print (1 << 2) # Rotate left most 2 bits to the right most. print ( 10 >> 2) # Rotate right most 2 bits to the left most. # for positive numbers left most bit is 0 # for negative numbers right most bit is 1 print (-10 >> 2)
439c4f350024fe08e2da75fa8093af8d43e1849c
nandansn/pythonlab
/myworkouts/officetools/dis/dbConsoleDisplay.py
1,546
3.609375
4
class Display: @staticmethod def create(): print(''' Create table from existing table or new table? 1. From existing table. 2. New table ''') createOption = int(input('Enter create table option: ')) if createOption == 1: ...
9ff4380dbf6e147c1ed42a320aa4fc16a123b92c
nandansn/pythonlab
/durgasoft/chapter35/functions-in-dict.py
1,274
4.5
4
'function: to create empty dict' d = dict() 'function: to create dict, by using list of tuples' d= dict([(100,'nanda'),(200,'kumar'),(300,'nivrithi'),(400,'valar')]) print(d) '''functions: dict() list of tuples, set of tuples, tuple of tuples. ''' 'fucntion:length of dict' print(len(d)) prin...
65c681ee41fec083cb972a9369a9574a254bb0b0
nandansn/pythonlab
/durgasoft/chapter25/replace-string.py
113
3.75
4
''' replace string with new string ''' name ='nandakumar' print(name.replace('nanda','g')) print(name)
0edbc7c2b0ea807af2625371b9f0cf4fd9dc912e
nandansn/pythonlab
/durgasoft/chapter66/example-2.py
470
3.703125
4
class Car: def outerClassCar(self): print('car outer class method') def startCar(self): self.e = Car.Engine() self.e.startEngine() print('car started...') class Engine: def innerClassEngine(self): print('engine inner class method') def ...
97fe155ecfde7b6a5f3672aa4a35127eb2667ed4
nandansn/pythonlab
/problems/patternproblems/pattern26.py
197
3.75
4
maxNumber = int(input('Enter max number:')) spaceCount = maxNumber -1 for i in range(1,maxNumber+1): printPattern = str(i) * i print((' ' * spaceCount) + printPattern) spaceCount -= 1
12ce3055d8595e5e0be0910da1498e92cad8256e
nandansn/pythonlab
/durgasoft/chapter15/read-data.py
256
4.3125
4
print("""We have input function to read data from the console. The data will be in str type we need to do type conversion.""") dataFromConsole = input("Enter data:") print("type of input is:", type(dataFromConsole)) print(type(int(dataFromConsole)))
3196fc10e2dcb9806dd6db1f40b8630276cf5ff9
nandansn/pythonlab
/durgasoft/oops/ch8/static-method.py
253
3.765625
4
class Calculator: @staticmethod def add(x,y): print("sum is {}".format(x+y)) @staticmethod def average(*x): average =sum(x)/len(x) print("average is {}".format(average)) Calculator.average(10,20,30)
6e46866c466b521e7ca577e301aed066cc0f7c47
snow-king/software-engineering
/Task_two/custom_math.py
233
3.546875
4
class Calculate(object): @staticmethod def difference(a, b): try: a, b = int(a), int(b) return a - b except ValueError: print("input string contains letters or is empty ")
ca5af9fee83c047ecce7df3a506a0bcaf779ee7c
ziGFriedman/Useful_code_snippets
/Strings/Is_lower_case.py
314
4.21875
4
'''Преобразует строку в верхний регистр при помощи метода str.lower() и сравнивает ее с оригиналом.''' def is_lower_case(str): return str == str.lower() print(is_lower_case('abc')) print(is_lower_case('a3@$')) print(is_lower_case('Ab4'))
ee9fc501e4c9ad89a817bd7c8efbafdeab2a3b1b
ziGFriedman/Useful_code_snippets
/Strings/Capitalize_every_word.py
245
3.9375
4
'''Делает первую букву заглавной каждого слова строки. Используется str.title.''' def capitalize_every_word(string): return string.title() print(capitalize_every_word('hello world!'))
8b747601f10131996032aecdfc6375f4c2e99c4e
ziGFriedman/Useful_code_snippets
/Mathematics/Factorial.py
638
4.53125
5
'''Вычисляется факториал числа.''' # Используется рекурсия. Если num меньше или равно 1, возвращается 1, а # иначе – произведение num и factorial из num — 1. Сработает исключение, # если num будет отрицательным или числом с плавающей точкой. def factorial(num): if not ((num >= 0) & (num % 1 == 0)): raise Ex...
5bbf01abca5f0789ee344a27b7157889942e0da8
ziGFriedman/Useful_code_snippets
/Strings/Byte_size.py
297
3.75
4
'''Возвращает длину строки в байтах. Заданная строка кодируется utf-8, а потом находится ее длина.''' def byte_size(string): return(len(string.encode('utf-8'))) print(byte_size('😀')) print(byte_size('Hello World'))
6d32c60dac55c86ac9a3bcdedc52b89369a9bf00
kaustubhjoshi1910/PythonForEverybody
/Using-Python-2-Access-Web-Data/Following-Links-in-Python.py
2,694
3.953125
4
# Following Links in Python # Liu Li # 2015-11-20 ''' In this assignment you will write a Python program that expands on http://www.pythonlearn.com/code/urllinks.py. The program will use urllib to read the HTML from the data files below, extract the href= vaues from the anchor tags, scan for a tag that is in a particu...
0f2ca28d33474b03bf2f5b30d82754793588bcb1
sagalpreet/CS202-Assignments
/Lab 5/Submission/ReverseString.py
342
4.03125
4
def reverseString(theString): words = list(map(str, theString.split(' '))) reversedString = '' for i in range(len(words)-1, -1, -1): reversedString = reversedString + words[i] + ' ' return reversedString print ("Enter a long string (extra spaces will be ignored):") theString = input() print(rev...
f3c22640ec779b541e4d71f37500e790b0041750
GamergeeK8510/python_stuff
/mock_business.py
2,901
3.5625
4
import random2 class Employee: total_employees = 0 employees = [] def __init__(self, first, last, job, time): self.first = first self.last = last self.t = int(time) self.email = first + "." + last + "@pythoncomp.org" if job == "jan": jo...
0e3fc3561c9b9fe6ac3af8c7ac47736d27e0a531
abramn7103/cti110
/P2HW2_TipTaxTotal_AbramNoah.py
463
4.03125
4
#CTI-110 #P2HW2 - Distance Traveled #Noah Abram #2/18/18 # Get the projected total sales. total_price = float (input ( 'Enter the price of your food: ')) #Calculate the tip as 18 percent of total price. tip = total_price * 0.18 #Calculate the tax as 7 percent of total price. tax = total_price * 0.07 ...
873eaa7414fc431c2de457cf4933db6517545217
edger1212/cti110
/P3LAB1_Smallest_EdgeRichard.py
199
3.875
4
#input in descending order #n1=7 #n2=15 #n3=3 n1 = int(input()) n2 = int(input()) n3 = int(input()) smallest=n1 if n2<smallest: smallest = n2 if n3 < smallest: smallest = n3 print(smallest)
93f9aeb58ee5cf84661384df0fe87cb5a90dd14e
edger1212/cti110
/P2LAB2_Variables_EdgeRichard.py
631
3.84375
4
user_int = int(input('Enter integer (32 - 126):\n')) # FIXME (1): Finish reading other items into variables, then output the four values on a single line separated by a space user_float = float(input('Enter float:\n')) # FIXME (2): Output the four values in reverse user_char = input('Enter character:\n') # FIXME ...
53fc6145b5f382a8db41a4085ce1c6f41b7acb07
Amey-Chaudhari/random-number-game
/random number game.py
720
4
4
import random import math print('Enter number range') lower = int(input("Enter Lower Number: ")) upper = int(input("Enter Upper Number: ")) x = random.randint(lower, upper) print("\n\tYou've only ", round(math.log(upper-lower + 1, 2)), "chances to guess the integer!\n") count = 0 while count < math.log(upper - lower...
55c97c4cb3405bd030cdbee7f63a9b556b7430a6
anilectjose/S1-A-Anilect-Jose
/Python Lab/17-02-2021/5.py
849
3.890625
4
class Publisher: def __init__(self, name1): self.name = name1 def show(self): pass class Book(Publisher): def __init__(self, title1, author1, name1): self.title = title1 self.author = author1 Publisher.__init__(self, name1) def show(self): ...
d667e5a3f4185900a22a751283b9346b5af2613d
aalabi/learningpy
/addition.py
233
4.1875
4
# add up the numbers num1 = input("Enter first number ") num2 = input("Enter second number ") # sum up the numbers summation = num1 + num2 # display the summation print("The sum of {0} and {1} is {2}".format(num1, num2, summation))
6e806969ed249e836e558a416dde4b0ec2c4a939
mbcrump/CallAWebsite
/CallAWebsite/CallAWebsite.py
1,388
4.03125
4
## Day 5 - Make a call to an API or scrap web data import requests #from bs4 import BeautifulSoup as soup import bs4 def main(): print_the_header() city = input("What is your city?\t") state = input("What state (use state code such as AL, WA, TX)\t") html = get_html(state, city) report = get_we...
cfe147a06b7064b6dc01f84f88e659506fb83346
tjdwjdgus99/Python-study
/example 15.2.py
760
3.78125
4
#설정된 숫자에 다각형 그리기 import cv2 image = cv2.imread('digit_image.jpg') image = cv2.resize(image, None, fx=0.5, fy=0.5, interpolation=cv2.INTER_AREA)#이미지 줄이기 image_gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) ret, thresh = cv2.threshold(image_gray, 230, 255, 0) thresh = cv2.bitwise_not(thresh) contours = cv2.findContours...
6aec1bc942da8dabada4cee222cfdd75a719d94d
sdberthoud/linkedin
/CS1/strip_word.py
266
3.59375
4
def strip_word( w ): w = replace( w, ".", "" ) w = replace( w, ",", "" ) w = replace( w, ";", "" ) w = replace( w, ":", "" ) w = replace( w, "'", "" ) w = replace( w, "&", "" ) w = replace( w, "\n", "" ) w = w.lower() return( w )
e8bd20876fa69b5bffca34bd88396470ae98ec83
sdberthoud/linkedin
/CS1/Labs/Lab 1/pong.py
7,665
4.21875
4
''' filename: pong.py name: shane berthoud date: september 23rd? 2014 course: CS1 file purpose: lab 1 and to play a fully functional pong game ''' from cs1lib import * #set changeable window height WINDOW_HEIGHT = 400 #set dimensions of paddles and how much they move PADDLE_WIDTH = 20 PADDLE_HEIGHT = 80 PADDLE_MOVE...
c1d6781253438c930aeb3108e22aa55dce103f45
sdberthoud/linkedin
/CS1/Short Assignments/SA 6/timer_driver.py
913
3.75
4
''' filename: timer_driver.py name: shane berthoud date: october 15th 2014 purpose: to test the timer class ''' # imports the Timer class and the Counter class from timer import * myTimer = Timer(1, 30, 30) # creates an instance of the Timer class, making myTimer a Timer object. print myTimer ...
0088ca79019ee18041d4bae53a507d9c1248d482
sdberthoud/linkedin
/CS1/Labs/Lab 3/visualize_cities.py
1,707
3.796875
4
''' filename: visualize_cities.py name: shane berthoud date: november 6th 2014 course: cs1 purpose: draws the 50 most populated cities in order.''' from cs1lib import * WINDOW_WIDTH = 720 # sets variables for variables that will not change WINDOW_HEIGHT = 360 DOT_SIZE = 7 def main(): im...
bd579a57ace8cd2ced4d320a9d287a38a56d8a89
gerimage23/python_exercises
/sum.py
563
4.03125
4
# Define a function sum() and a function multiply() that sums and multiplies (respectively) all # the numbers in a list of numbers. # For example, sum([1, 2, 3, 4]) should return 10, and multiply([1, 2, 3, 4]) should return 24. def sum2(list_of_numbers): add = 0 for number in list_of_numbers: add = ad...
7308ba28fdc57381643de87af0c575f8160f642c
admdev8/coxeter
/coxeter/shapes/convex_polyhedron.py
6,607
4.0625
4
"""Defines a convex polyhedron.""" import numpy as np from scipy.spatial import ConvexHull from .polyhedron import Polyhedron from .sphere import Sphere class ConvexPolyhedron(Polyhedron): """A convex polyhedron. A convex polyhedron is defined as the convex hull of its vertices. The class is a simple e...
2443310e84aca59b05900926e5ff93233466a8aa
dandan224/list-sort-coding
/dedup_II.py
360
3.53125
4
class Solution(object): def dedup(self, array): """ input: int[] array return: int[] """ # write your solution here if not array or len(array) == 0 or len(array) == 1: return array i, n = 2, len(array) while i < n: if array[i] == array[i - 2]: del array[i] n...
afb74671e5bacf7ade5f03cc435d296062782687
elinxaaa/python-projects
/turtle graphics/random-walk.py
446
3.859375
4
import turtle as t from random import choice, randint t.colormode(255) toe = t.Turtle() def rand_colour(): red = randint(0, 255) green = randint(0, 255) blue = randint(0, 255) rgb = (red, green, blue) return rgb toe.pensize(10) toe.speed(10) direction = [0, 2, 3, 1] for _ in range(100): to...
f81a8d7c98c8c520158b2e4d33c9999d396722aa
prithvi1617/Coding-Questions
/string/5. Find the smallest window in a string containing all characters of another string.py
175
3.703125
4
def window(str1,str2): len1=len(str1) len2=len(str2) if len2>len1: return 'no substring' str1='abcdefg' str2='ad' print(window(str1,str2))
bff19873431b28990a4252353a716e3f820bdc28
prithvi1617/Coding-Questions
/basic question/90.C Program for Perfect number.py
193
3.515625
4
def perfect(n): count=1 for i in range(2,n//2+1): if (n%i==0): count+=i if count==n: return 'yes' else: return 'no' n=6 print(perfect(n))
d3601681c475d0e0f93ddc9239453f1382f3818f
prithvi1617/Coding-Questions
/Array/5. Algorithm to rotate array of size 'n' by 'd' elements.py
216
3.6875
4
# O(n*d) def rotate(a,len,d): l=0 r=len-1 for i in range(d): temp=a[0] for j in range(len-1): a[j]=a[j+1] a[r]=temp print(a) a= [1,2,3,4,5] d=3 rotate(a,len(a),d)
d99757877dbc86572650bf97123b8bfd95f60942
AnhKun/data-analysis-with-python-summer2021
/part05-e06_suicide_fractions/src/suicide_fractions.py
319
3.78125
4
#!/usr/bin/env python3 import pandas as pd def suicide_fractions(): df = pd.read_csv("src/who_suicide_statistics.csv") df2 = df.groupby('country') return df2.apply(lambda df2: (df2['suicides_no']/df2['population']).mean()) def main(): print(suicide_fractions()) if __name__ == "__main__": main()
4c14349584a26e8f561f8d24d3b52ce0b625f3ca
AnhKun/data-analysis-with-python-summer2021
/part02-e12_row_and_column_vectors/src/row_and_column_vectors.py
492
3.59375
4
#!/usr/bin/env python3 import numpy as np def get_row_vectors(a): list_row = [row.reshape(1,a.shape[1]) for row in a] return list_row def get_column_vectors(a): list_columns = [column.reshape(a.shape[0],1) for column in a.T] return list_columns def main(): np.random.seed(0) a=np.random.randi...
5b9952d1d96cea533a6f0b622e5467cab963b4cb
5h3rr1ll/CodeWars
/Pete_the_baker.py
1,027
3.875
4
#!/usr/bin/env python # -*- coding: utf-8 -*- def cakes(recipe, available): lstRecipe = list(recipe) lstAvailable = list(available) allAvaiable = True possibelAmount = [] for i in lstRecipe: if i in lstAvailable and available[i] >= recipe[i]: possibelAmount.append(available[i] ...
868f7c2771e64071d718a388416bc36525441ea4
5h3rr1ll/CodeWars
/Mumbling.py
275
3.609375
4
#! /usr/bin/env python # -*- coding: utf-8 -*- def accum(s): down = len(s) string = "" for i in s: string += i * (len(s) + 1 - down) + "-" string = string.title() down -= 1 string = string[:-1] print(string) accum("ZpglnRxqenU")
54d4a25a30022d491e40772d75fac0a09857284e
freebz/Learning-Python
/ch13/ex13-17.py
365
3.71875
4
# 루프 코딩 기법/기술 # 루프 카운터: range list(range(5)), list(range(2, 5)), list(range(0, 10, 2)) # ([0, 1, 2, 3, 4], [2, 3, 4], [0, 2, 4, 6, 8]) list(range(-5, 5)) # [-5, -4, -3, -2, -1, 0, 1, 2, 3, 4] list(range(5, -5, -1)) # [5, 4, 3, 2, 1, 0, -1, -2, -3, -4] for i in range(3): print(i, 'Pythons') # 0 Pythons # 1 P...
196073070ad418ff499d16c3fdd2daeb7ff30d1b
freebz/Learning-Python
/ch32/ex32-27.py
1,327
3.828125
4
# 클래스 메서드를 이용하여 인스턴스 개수 세기 class Spam: numInstances = 0 # 정적 메서드 대신에 클래스 메서드 사용 def __init__(self): Spam.numInstances += 1 def printNumInstances(cls): print("Number of instances: %s" % cls.numInstances) printNumInstances = classmethod(printNumInstances) from spam_class impo...
dc960026b6bf21e3bedc2a1ec880f85cbcb35558
freebz/Learning-Python
/ch32/ex32-37.py
660
3.75
4
# super의 장점: 트리를 변경하고 할당함 # 런타임 클래스 변경과 super class X: def m(self): print('X.m') class Y: def m(self): print('Y.m') class C(X): # X로부터 상속받은 것으로 시작 def m(self): super().m() # 여기에 클래스 이름ㅇ르 하드코딩할 수 없음 i = C() i.m() # X.m C.__bases__ = (Y,) # 런타임에 클래스 이름을 변경! i.m() # Y.m ...
0c916b0310411416250a3f36859d7387712b5818
freebz/Learning-Python
/ch38/ex38-16.py
1,754
3.828125
4
# 첫 번째 예제 class Person: # 2.X와 3.X에서 모두 실행됨 def __init__(self, name): # Person() 실행 시 호출됨 self._name = name # __setattr__ 호출! def __getattr__(self, attr): # obj.undefined 호출 시 실행됨 print('get: ' + attr) if attr == 'name': ...
c34ca4fddd496d8014ca9c193f363d060aa0b858
freebz/Learning-Python
/ch38/desc-state-desc.py
1,116
3.859375
4
class DescState: # 인스턴스 상태를 이용. 2.X에서는 (object) def __init__(self, value): self.value = value def __get__(self, instance, owner): # 속성을 가져올 때 실행됨 print('DescState get') return self.value * 10 def __set__(self, instance, value): # 속성을 할당할 때 실행 print('Des...
d93a5b425c6e3129ab761f8c98ea0bc42d8d294e
freebz/Learning-Python
/ch32/ex32-11.py
1,305
3.578125
4
# 충돌에 대한 명시적 해결 class A: attr = 1 # 고전 클래스 class B(A): pass class C(A): attr = 2 class D(B, C): attr = C.attr # <== 오른쪽에 있는 C를 선택 x = D() x.attr # 새로운 형식의 순서처럼 동작(모든 3.X) # 2 class A(object): attr = 1 # 새 형식 클래스 class B(A): pass class C(A): attr = 2 cl...
4a37f2ed0f9f93a47cd00bf07d85ae3f28541baf
freebz/Learning-Python
/ch35/ex35-7.py
1,036
3.59375
4
# 사용자 정의 출력 디스플레이 class MyBad(Exception): pass try: raise MyBad('Sorry--my mistake!') except MyBad as X: print(X) # Sorry--my mistake! raise MyBad('Sorry--my mistake!') # Traceback (most recent call last): # File "<stdin>", line 1, in <module> # __main__.MyBad: Sorry--my mistake! class MyBad(Exception)...
15547063f5266081c0d4d4e0cdafd0c6a6300666
freebz/Learning-Python
/ch19/ex19-3.py
160
3.5
4
# 반복문 vs 재귀 L = [1, 2, 3, 4, 5] sum = 0 while L: sum += L[0] L = L[1:] sum # 15 L = [1, 2, 3, 4, 5] sum = 0 for x in L: sum += x sum # 15
cf83683423290eec8421e0c9c6204f10d5fe8ee1
freebz/Learning-Python
/ch32/ex32-43.py
2,892
3.765625
4
# 결합: 혼합 클래스에의 적용 # 혼합 클래스는 메서드 집합들 간에 공통 요소가 없을 때 동작함 class A: def other(self): print('A.other') class Mixin(A): def other(self): print('Mixin.other'); super().other() class B: def method(self): print('B.method') class C(Mixin, B): def method(self): print('C.method'); super().other(); super().method...
d44d3eeb55983b933bc672c6836e12b742e3e4e8
freebz/Learning-Python
/ch31/ex31-7.py
1,372
3.796875
4
# 유사개별 클래스 속성 # 이름 맹글링 개요 # 왜 유사개별 속성을 사용하는가? class C1: def meth1(self): self.X = 88 # 나는 X는 내 것이라 가정 def meth2(self): print(self.x) class C2: def metha(self): self.X = 99 # 나도 def methb(self): print(self.X) class C3(C1, C2): ... I = C3() # I에 X는 하나만! ...
c47583888a6ee6a545cfb24605453b3eb8909727
freebz/Learning-Python
/ch13/ex13-24.py
578
3.921875
4
# zip을 이용한 딕셔너리 구성 D1 = {'spam':1, 'eggs':3, 'toast':5} D1 # {'spam': 1, 'eggs': 3, 'toast': 5} D1 = {} D1['spam'] = 1 D1['eggs'] = 3 D1['toast'] = 5 keys = ['spam', 'eggs', 'toast'] vals = [1, 3, 5] list(zip(keys, vals)) # [('spam', 1), ('eggs', 3), ('toast', 5)] D2 = {} for (k, v) in zip(keys, vals): D2[k] = v...
3fdf46f6503e275d1f9fefdce301a3883a3cd2ee
freebz/Learning-Python
/ch29/ex29-8.py
668
3.75
4
# 추상 슈퍼클래스 class Super: def delegate(self): self.action() def action(self): assert False, 'action must be defined!' # 이 버전이 호출되면 오류 발생 X = Super() X.delegate() # AssertionError: action must be defined! class Super: def delegate(self): self.action() def action(self): ...
55ad250261bb74f0cfdc3b98045b900105145821
freebz/Learning-Python
/ch11/ex11-20.py
639
3.515625
4
# 더 생각해 볼 주제: print와 stdout class FileFaker: def write(self, string): # string에 담긴 출력된 텍스트로 작업을 수행 import sys sys.stdout = FileFaker() print(someObjects) # 클래스 write 메서드로 보내기 myobj = FileFaker() # 3.X: 한 번의 인쇄를 위해 객체로 리다이렉트 print(someObjects, file=myobj) # sys.stdout을 재설정하지 않음 ...
22cc6a51d2caf138080f31a62d98c83b5a96e0fa
freebz/Learning-Python
/ch20/ex20-29.py
356
3.765625
4
# 더 생각해 볼 주제: 일회성 반복 def myzip(*args): iters = map(iter, args) while iters: res = [next(i) for i in iters] yield tuple(res) list(myzip('abc', 'lmnop')) # [('a', 'l'), ('b', 'm'), ('c', 'n')] def myzip(*args): iters = list(map(iter, args)) # 여러 번 탐색 가능 ...나머지는 그대로...
33c43d038703a0f92de8927bd3642700a4ae36c5
freebz/Learning-Python
/ch04/ex4-24.py
714
3.734375
4
# 코드의 유연성을 깨트리는 방법 # 파이썬 2.X type(L) # 타입: L의 타입은 리스트 타입 객체 # <type 'list'> type(type(L)) # 심지어 type도 객체 # <type 'type'> # 파이썬 3.X type(L) # 3.X: 타입은 클래스이며, 반대도 마찬가지 # <class 'list'> type(type(L)) # 클래스 타입에 대해서는 32장 참조 # <class 'type'...
eb07ff33315157a3b4ba2fd5766a7f33cd7508ad
freebz/Learning-Python
/ch28/ex28-18.py
900
3.828125
4
# 단계 6: 내부 검사 도구 사용하기 from person import Person bob = Person('Bob Smith') bob # bob의 __repr__(__str__이 아니라)을 보여줌 # [Person: Bob Smith, 0] print(bob) # 위와 같음: print => __str__ 또는 __repr__ # [Person: Bob Smith, 0] bob.__class__ # bob의 class와 그 이름을 보여 줌 ...
80b84bd7369a182106ccb5f4da2b1570e9861110
freebz/Learning-Python
/ch35/ex35-2.py
1,218
3.5
4
# 클래스 기반 예외 # 예외 클래스 코딩하기 class General(Exception): pass class Specific1(General): pass class Specific2(General): pass def raiser0(): X = General() # 슈퍼클래스 인스턴스 발생 raise X def raiser1(): X = Specific1() # 서브클래스 인스턴스 발생 raise X def raiser2(): X = Specific2() ...
d49722b953035afdf9d5eb822adf13cf1a0b3ad1
freebz/Learning-Python
/ch36/ex36-2.py
1,149
3.890625
4
# 예제: 구문적 중첩 try: try: action2() except TypeError: # 가장 최근의 매칭되는 try문 print('inner try') except TypeError: # 여기, 중첩된 핸들러가 다시 일어날 때만 print('outer try') try: try: raise IndexError finally: print('spam') finally: print('SPAM') # spam # SPA...
601802e7edf71a7f55c7baf15d59b4a2cff1177a
freebz/Learning-Python
/ch30/squares.py
529
3.671875
4
# squares.py 파일 class Squares: def __init__(self, start, stop): # 생성될 때 상태 정보 저장 self.value = start - 1 self.stop = stop def __iter__(self): # iter 호출 시, 반복자 객체 가져오기 return self def __next__(self): # 매 반복 때마다 제곱값 반환 if self.value == self.st...
a726ce5038f0308ad06aecce3b48693f932f341f
freebz/Learning-Python
/ch20/ex20-32.py
1,094
3.796875
4
# 집합과 딕셔너리 컴프리헨션 이해하기 {x * x for x in range(10)} # 컴프리헨션 # {0, 1, 64, 4, 36, 9, 16, 49, 81, 25} set(x * x for x in range(10)) # 제너레이터와 타입 이름 # {0, 1, 64, 4, 36, 9, 16, 49, 81, 25} {x: x * x for x in range(10)} # {0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64, 9: 81} dict((x, x * x) for x in range(1...
dd611355309bd9249f303ba3950aa568db0f65de
freebz/Learning-Python
/ch19/ex19-19.py
686
3.515625
4
# 반복 객체의 아이템들을 결합하기: reduce from functools import reduce # 3.X에서만 임포트 reduce((lambda x, y: x + y), [1, 2, 3, 4]) # 10 reduce((lambda x, y: x * y), [1, 2, 3, 4]) # 24 L = [1,2,3,4] res = L[0] for x in L[1:]: res = res + x res # 10 def myreduce(function, sequence): tally = sequence[0] for next in seq...
d24abe84b4129a68373faa057671327a73ce95b9
freebz/Learning-Python
/ch07/ex7-5.py
733
3.515625
4
# 문자열의 실제 동작 # 기본 동작 len('abc') # 길이: 아이템 수 # 3 'abc' + 'def' # 연결: 새로운 문자열 생성 # 'abcdef' 'Ni!' * 4 # 반복: 'Ni!' + 'Ni!' + ...와 같음 # 'Ni!Ni!Ni!Ni!' print('------ ...생략... ---') # 80대시. 어려운 방법 print('-' * 80) # 80대시. 쉬운 방법 myjob = "hacker...
603eac2936336475d3c9044bebcd89d0ceecf0be
freebz/Learning-Python
/ch13/ex13-5.py
268
3.84375
4
# continue x = 10 while x: x = x - 1 # 또는 x -= 1 if x % 2 != 0: continue # 홀수는 건너뜀 print(x, end=' ') x = 10 while x: x = x - 1 if x % 2 == 0: # 짝수인 경우 출력 print(x, end=' ')
28b6bc1e83a73b0ad71888ff3eb2b3e7672e9f66
freebz/Learning-Python
/ch13/ex13-6.py
314
3.953125
4
# break while True: name = input('Enter name:') # 2.X에서 raw_input() 사용 if name == 'stop': break age = input('Enter age: ') print('Hello', name, '=>', int(age) ** 2) # Enter name:bob # Enter age: 40 # Hello bob => 1600 # Enter name:sue # Enter age: 30 # Hello sue => 900 # Enter name:stop
fdb1b5c36f729af35872cc1d68b83b8ce6892463
freebz/Learning-Python
/ch30/ex30-5.py
508
3.53125
4
# 파이썬 2.X에서의 슬라이싱과 인덱싱 # py -2 class Slicer: def __getitem__(self, index): print index def __getslice__(self, i, j): print i, j def __setslice__(self, i, j, seq): print i, j, seq Slicer()[1] # 3.X처럼 __getitem__을 정수와 함께 실행 # 1 Slicer()[1:9] # 만약 존재하면 __getsli...
99de4aea1a7aa8e79108b367deae61bac81944a3
freebz/Learning-Python
/ch11/ex11-14.py
1,284
3.578125
4
# 파이썬 3.X print 함수 # c:\python36\python print() # 빈 라인 출력 x = 'spam' y = 99 z = ['eggs'] print(x, y, z) # 기본 옵션으로 세 개의 객체 출력 # spam 99 ['eggs'] print(x, y, z, sep='') # 구분자 제거 # spam99['eggs'] print(x, y, z, sep=', ') # 사용자 정의 구분자 # spam, 99, ['eggs'] pri...