blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
is_english
bool
ed78287dca3814f8f04d7efdf708a10f218b62d4
njerigathigi/learn-python
/dict_function.py
768
4.1875
4
# Create a dictionary containing personal information: name = input('What is your name?\n') gender = input('What is your gender?\n') profile = dict(name = name.title(), age = 16 , gender = gender.title()) print(profile) # Definition and Usage # The dict() function creates a dictionary. # A dictionary is a collection which is unordered, changeable and unindexed. # Syntax # dict(keyword arguments) # parameter Description # keyword arguments Required. As many keyword arguments you like, separated by comma: # key = value, key = value ... even_numbers = [number for number in range(0,11) if number % 2 == 0] expected_numbers = ['zero','two', 'four', 'six', 'eight'] result = dict(zip(expected_numbers, even_numbers)) print(result)
true
9348bc41e167608f612ba346f8c10bff1b591c9d
njerigathigi/learn-python
/python_json.py
2,691
4.3125
4
# JSON is a syntax for storing and exchanging data #data is sent in the form of a string. #the object itself would be too big to send thus the need for conversion #into a string. # JSON is text, written with JavaScript object notation. # Python has a built-in package called json, which can be used to work # with JSON data. # Import the json module: import json # Parse JSON - Convert from JSON to Python # If you have a JSON string, you can parse it by using the json.loads() method. # some JSON: profile = '{ "name": "John", "age":30, "city": "New York" }' # parse x: new_profile = json.loads(profile) print(new_profile) # the result is a Python dictionary: print(new_profile['age']) print() print() # Convert from Python to JSON # If you have a Python object, you can convert it into a JSON string by using # the json.dumps() method. # Convert from Python to JSON: employee = { "name": "John", "age" : 30, "city": "New York", } # convert into JSON: employee_json = json.dumps(employee) # the result is a JSON string: print(employee_json) print() print() # You can convert Python objects of the following types, into JSON strings: # dict # list # tuple # string # int # float # True # False # None # When you convert from Python to JSON, Python objects are converted into the # JSON (JavaScript) equivalent: # Python JSON # dict Object # list Array # tuple Array # str String # int Number # float Number # True true # False false # None null profile1 = { "name": "John", "age" : 30, "city": "New York", "married": True, "divorced": False, "children": ("Ann", "Billy"), "pets": None, "cars": [ {"model": "BMW 230", "mpg": 27.5}, {"model": "Ford Edge", "mpg": 24.1}, ] } print(json.dumps(profile1)) print() print() # Format the Result # The example above prints a JSON string, but it is not very easy to read, # with no indentations and line breaks. # The json.dumps() method has parameters to make it easier to read the result: # Use the indent parameter to define the numbers of indents print(json.dumps(profile1, indent = 4)) print() print() # you can also define the separators, default value is (", ", ": "), # which means using a comma and a space to separate each object, and a # colon and a space to separate keys from values: # Use the separators parameter to change the default separator: print(json.dumps(profile1, indent = 4, separators = (". ", "= "))) print() print() # Order the Result # Use the sort_keys parameter to specify if the result should be sorted or not: print(json.dumps(profile1, indent = 4, separators = (". ", "= "), sort_keys = True))
true
aaa8a488a729d8097f12199c71531b8a636e0525
AndrewPau/interview
/groupAnagrams.py
839
4.28125
4
""" Given an array of strings, group anagrams together. Return as a list of lists. An anagram is defined as words with the same characters but in different order. """ def groupAnagrams(strs): anagrams = {} # Create identifiers of anagrams through a Unicode counter string. for string in strs: chars = [0 for a in range(256)] for l in range(len(string)): chars[ord(string[l])] += 1 word = str(chars) # Use the Unicode string as a dictionary key to group anagrams. if word in anagrams: anagrams[word].append(string) else: anagrams[word] = [string] returnVal = [] for anagram in anagrams: returnVal.append(anagrams[anagram]) return returnVal strings = ["eat", "tea", "tan", "ate", "nat", "bat"] print(groupAnagrams(strings))
true
54f81decad9a26080d2d120fecd8f6122bf3308d
neal-rogers/baseball-card-inventory
/Source Files/iter-msg-format.py
951
4.34375
4
#!/usr/bin/env python # -*- coding: utf-8 -*- """This program loops through a list of tuples, gets values, and creates a new list.""" def prepare_email(appointments): """This function loops through and inserts values into a string. Args: appointment(list): List of tuples. Returns: message(list): List with formatted strings of referenced values. Example: >>> prepare_email([('Jen', '2015'), ('Max', 'March 3')]) ['Dear Jen,\nI look forward to meeting with you on /2015.\nBest,\nMe', 'Dear Max,\nI look forward to meeting with you on /March 3.\nBest,\nMe'] """ record = 0 message = [] template = 'Dear {},\nI look forward to meeting with you on {}.\nBest,\nMe' for member in appointments: member = appointments[record] name = member[0] date = member[1] record += 1 message.append(template.format(name, date)) return message
true
38a1fda6fb9d24f56adaffc7caadeca8563d9fd8
smita-09/python
/OOPs/Set3.2.py
403
4.1875
4
# How to access parent members in a subclass? # Dog class class Dog(object): def __init__(self, name): self.name = name #Dog'e breed class class GermanShephard(Dog): def __init__(self, name, speak): Dog.name = name self.speak = speak def DogSprache(self): print(Dog.name, self.speak) #Driver Code dog = GermanShephard("David", "Bhaw") dog.DogSprache()
false
7bd7f345e9a22f721ea9ed1d0d8efcc21180fdc6
Abhi848/python-basic-programs
/p13.py
306
4.1875
4
a= int(input("enter the 1st number num1:\n")) b= int(input("enter the 2nd number num2:\n")) c= int(input("enter the 3rd number num3:\n")) if (a>=b) and (a>=c): largest= a elif (b>=a) and (b>=c): largest= b else: largest= c print("the biggest of three numbers entered is:", largest)
false
36d9f987562648fd205f9ede475b97f68ea81b93
KLKln/Module12
/unit3/abstract_class.py
1,354
4.40625
4
""" Program: abstract_class.py Author: Kelly Klein Date: 07/15/2020 This program creates an abstract class method called Rider then creates three subclasses that return a statement about how it rides and how many riders """ from abc import ABC, abstractmethod class Rider(ABC): @abstractmethod def ride(self): pass def riders(self): pass class Bicycle(Rider): def __init__(self): self.ride = 'Human powered, not enclosed' self.riders = '1 or 2 if tandem or a daredevil' def ride(self): return self.ride def riders(self): return self.riders class Motorcycle(Rider): def __init__(self): self.ride = 'Engine powered, not enclosed' self.riders = '1 or 2, maybe 3 with a sidecar' def ride(self): return print(self.ride) def riders(self): return print(self.riders) class Car(Rider): def __init__(self): self.ride = 'Engine powered, enclosed' self.riders = '1 plus comfortably' def ride(self): return self.ride def riders(self): return self.riders if __name__ == '__main__': b = Bicycle() print(str(b.ride)) print(str(b.riders)) m = Motorcycle() print(str(m.ride)) print(str(m.riders)) c = Car() print(str(c.ride)) print(str(c.riders))
true
211d18057c3903f7804cf0b8a000df2cb46df993
at3hira/challenge_commit
/charenge_commit/Chap4/chap4_5.py
275
4.28125
4
""" Function to convert str to float :param x str :return x converted to float """ def conv_float(x): try: return float(x) except ValueError: print("Invalid string") float_input = input("Float Input") result = conv_float(float_input) print(result)
false
46e2cd4c8d76ffd7b6e3603eba62ec2d6ca2a632
TyDunn/hackerrank-python
/GfG/Queue/queue_via_stack.py
1,104
4.21875
4
#!/bin/python3 #!/bin/python3 class StackNode: def __init__(self, data): self.data = data self.next = None class Stack: def __init__(self): self.root = None def is_empty(self): return True if not self.root else False def push(self, data): new_node = StackNode(data) new_node.next = self.root self.root = new_node def pop(self): if self.is_empty(): print("Stack empty!") return temp = self.root self.root = self.root.next return temp.data def peek(self): if self.is_empty(): print("Stack empty!") return return self.root.data class Queue: def __init__(self): self.s1 = Stack() self.s2 = Stack() def enqueue(self, val): while not self.s1.is_empty(): self.s2.push(self.s1.pop()) self.s1.push(val) while not self.s2.is_empty(): self.s1.push(self.s2.pop()) def dequeue(self): if self.s1.is_empty(): print("queue is empty") return return self.s1.pop() if __name__ == '__main__': queue = Queue() queue.enqueue(1) queue.enqueue(2) queue.enqueue(3) print(queue.dequeue()) print(queue.dequeue()) print(queue.dequeue())
false
05ca9e8d099d0c490492a6f3bc0a19abf6e3e879
wasimashraf88/Python-tutorial
/and_or_exercise.py
460
4.125
4
# EXERCISE-WATCH COCO #Ask user's name and age #If user's name start with('a' or 'A') and age is above 10 then #Print you can watch coco movie #Else 'You cannot watch coco' #Solution............................. user_name = input("Enter your name please:") user_age = input("Enter your age please:") user_age = int(user_age) if user_age >= 10 and (user_name[0] == 'a' or user_name[0] == 'A'): print("You can watch coco") else: print("You can't watch")
true
010a815529867f4e1b8ff3b322975072d380e852
yinSpark/WebSpider-Programs
/algorithms/QuickSort.py
1,543
4.125
4
# 快速排序算法 # 算法思想 # 先从待排序的数组中找出一个数作为基准数(取第一个数即可), # 然后将原来的数组划分成两部分:小于基准数的左子数组和大于等于基准数的右子数组。 # 然后对这两个子数组再递归重复上述过程,直到两个子数组的所有数都分别有序。 # 最后返回“左子数组” + “基准数” + “右子数组”,即是最终排序好的数组。 # 算法实现 # pop() 函数用于移除列表中的一个元素(默认最后一个元素),并且返回该元素的值。 # 语法:list.pop(obj=list[-1]) # 默认为 index=-1,删除最后一个列表值。 # obj -- 可选参数,要移除列表元素的对象。 # 该方法返回从列表中移除的元素对象。 # arr = [12, 30, 5, 16, 5, 1, 20] # print(a.pop(0)) # print(a) from random import randint # 生成一个随机array def random_array(n): ''' :param n: number :return: array :description: Generate a random array ''' return [randint(0, 50) for _ in range(n)] # 进行快速排序 def quick_sort(arr): if len(arr) <= 1: return arr left, right = [], [] # 取第一个元素,pop(-1)为默认 base = arr.pop(0) for x in arr: if x < base: left.append(x) else: right.append(x) return quick_sort(left) + [base] + quick_sort(right) if __name__ == '__main__': arr = random_array(10) result = quick_sort(arr) print(result)
false
0b7bd654b5af118bd97c31d0d6e7e77d0a2ee936
cchrisgong/sRNA_plasmid
/Vector.py
2,259
4.125
4
class Vector(list): '''A list-based Vector class.''' def __add__(self, other): try: return Vector(map(lambda x, y: x + y, self, other)) except TypeError: #to do scalar addition return Vector(map(lambda x: x + other, self)) def __neg__(self): return Vector(map(lambda x: - x, self)) def __sub__(self, other): #subtraction operation of Vector try: return Vector(map(lambda x, y: x - y, self, other)) except TypeError: #to do scalar subtraction return Vector(map(lambda x: x - other, self)) def __mul__(self, other): #inner product of Vector try: return Vector(map(lambda x, y: x * y, self, other)) except TypeError: #to do scalar multiplication return Vector(map(lambda x: x * other, self)) def __div__(self, other): #division operation of Vector try: return Vector(map(lambda x, y: x / y, self, other)) except TypeError: #to do scalar division return Vector(map(lambda x: x / other, self)) def __radd__(self, other): try: return Vector(map(lambda x, y: x + y, self, other)) except TypeError: #to do scalar addtion from RHS return Vector(map(lambda x: other + x, self)) def __rsub__(self, other): #subtraction operation of Vector try: return Vector(map(lambda x, y: x - y, self, other)) except TypeError: #to do scalar subtraction from RHS return Vector(map(lambda x: other - x, self)) def __rmul__(self, other): #inner product of Vector try: return Vector(map(lambda x, y: x * y, self, other)) except TypeError: #to do scalar multiplication from RHS return Vector(map(lambda x: other * x, self)) def __rdiv__(self, other): #division operation of Vector try: return Vector(map(lambda x, y: x / y, self, other)) except TypeError: #to do scalar division from RHS return Vector(map(lambda x: other / x , self)) ''' if __name__ == "__main__": x = Vector([1,2,2]) y = Vector([1,2,4]) print x + y '''
false
ba80d6b1609d33c75922d13d359185336bf40f39
G-K-R-git/PY111-German
/Tasks/d0_stairway.py
603
4.375
4
from typing import Union, Sequence def stairway_path(stairway: Sequence[Union[float, int]]) -> Union[float, int]: """ Calculate min cost of getting to the top of stairway if agent can go on next or through one step. :param stairway: list of ints, where each int is a cost of appropriate step :return: minimal cost of getting to the top """ print(stairway) min_cost = [stairway[0], stairway[1]] for i in range(2, len(stairway)): min_cost.append(stairway[i] + min(min_cost[i-2], min_cost[i-1])) print('List of min costs: ', min_cost) return min_cost[-1]
true
28a6f0c49981ce7de938f24c027828670294251b
RafsanRifat/Python-beginning
/part-5/unpacking-operator.py
671
4.21875
4
numbers = [1, 2, 3, 4] print(*numbers) # object er namer agee * diyea prefix kore amra operator k unpacking korte pari... values = list(range(5)) print(*values) values_2 = [*range(5), *"Hello"] # we can any Iterable using * before that Iterable print(values_2) first = [1, 2] second = [2, 3] combined_list = [*first, *second] # we can combined 2 list using this. print(combined_list) first_dix = {"x": 1} second_dix = {"y": 2, "x": 10} combined_dix = {**first_dix, **second_dix} # we can combined 2 dictionary using this, but here need 2 **. # same key thakle last key sudhu dhorbe eikhane. print(combined_dix)
false
58af95a954efc7e896667e4dcaa5305e0e8de601
vivekworks/learning-to-code
/4. Discovering Computer Science/Python/Chapter 4 - Growth And Decay/Exercises 2/exercise424.py
568
4.375
4
""" Purpose : Plot the population each day Author : Vivek T S Date : 02/11/2018 """ import matplotlib.pyplot as pyplot def growth3(totalDays): population = 10 populationList = [] populationList.append(population) for day in range(0,totalDays): population = population*1.10 populationList.append(population) pyplot.plot(range(0,totalDays+1),populationList,color='green',label='Population Growth') pyplot.xlabel('Days') pyplot.ylabel('Population') pyplot.title('Population Growth vs Days') pyplot.legend() pyplot.show() def main(): growth3(30) main()
true
92ab3bc39d7e41e7694bb7abde987b4135787016
vivekworks/learning-to-code
/4. Discovering Computer Science/Python/Chapter 3 - Visualizing Abstraction/Exercises 5/exercise353.py
774
4.125
4
""" Purpose : Calculate Football team score Author : Vivek T S Date : 28/10/2018 """ def football(touchdowns, fieldGoals, safeties): """ Description : Calculate Football score Parameter Value : touchdowns - no. of touchdowns fieldGoals - no. of fieldgoals safeties - no. of safeties Return Value : team score """ return (touchdowns*7)+(fieldGoals*3)+(safeties*2) def main(): """ Description : Gets the input and calculate football team score Parameter Value : None Return Value : None """ touchdowns = int(input('Touchdowns : ')) fieldGoals = int(input('Field Goals : ')) safeties = int(input('safeties : ')) print('Team score',football(touchdowns, fieldGoals, safeties)) main() #Main Function Call
true
9b243840ca5761bd1621a19db26fde72e3a0d262
FahimFBA/Python-Data-Structures-by-University-of-Michigan
/Dictionary/Intro.py
337
4.21875
4
# Lists index their entries based on the position in the list # Dictionaries are like bages - no order # So we index the things we put in the dictionary with a "lookup tag" purse = dict() purse['money'] = 12 purse['candy'] = 3 purse['tissues'] = 75 print(purse) print(purse['candy']) purse['candy'] = purse['candy'] + 2 print(purse)
true
f23182261cd88d11e8318780698d5939577f78a7
FahimFBA/Python-Data-Structures-by-University-of-Michigan
/Tuples/2.py
374
4.1875
4
# Tuples are "immutable" # Unlike a list, once you create a tuple, you cannot alter its contents - similar to a string x = [9, 8, 7] x[2] = 6 print(x) # Output: [9, 8, 6] y = 'ABC' y[2] = 'D' print(y) # Output: TypeError: 'str' object does not support item assignment z = (5, 4, 3) z[2] = 0 print(z) # Output: TypeError: 'str' object does not support item assignment
true
d247aa0b1b28a9e53991bc665dc0626dbe13e23d
Copenhagen-EdTech/Discere
/intelligentQuestion.py
746
4.125
4
### This script takes a string that defines the subject, ### and prompts back a question for the user to explain. from random import randint #from X import X as subject # ## Defining vocabularies # vocab = "abcdefghijklmnopqrstuvwxuz" # vowls = "aeiouy" # consonants = "bcdfghjklmnpqrstvwxz" ## Defining predetirmined questions in dictionary QD ={1:"Can you elaborate on _?_", 2:"Please explain _?_", 3:"What do you mean by _?_", 4:"could you further describe _?_"} #S = "the spanish inquisition" ## Function that takes a given string input, checks for def firstQuestionMaker(subject): Q = QD[randint(1,len(QD))] # Selects one of the questions at random question = Q.replace("_?_", subject) return question
true
bee4848667dfd20a5d49481b4815f59b6c71ff88
suraj-singh12/CSE202CPPCodes
/code/After MTE/find.py
523
4.125
4
#!/usr/bin/python3 def find(find_string): file = open("content.xml",'r') # reading whole content content = file.read() # spliting into lines content = content.split('>') # for every line in content do: for line in content: # for every word in line do: for word in line.split(): # if the word matches the string to be searched, then print the whole line containing that word if(word == find_string): print(line) file.close() string = input() find(string)
true
db94e08597dbef9a284229af79980e4d180ae557
pstatkiewicz/lista-5
/Zadanie 4.py
716
4.25
4
import time def Fibonacci_iteration(n): if n<0: return False elif n<1: return 0 number1,number2=0,1 for i in range(n-1): result=number1+number2 number1=number2 number2=result return result def Fibonacci_recursion(n): if n<0: return False elif n<1: return 0 elif n<3: return 1 else: return Fibonacci_recursion(n-1)+Fibonacci_recursion(n-2) start1=time.time() Fibonacci_iteration(34) end1=time.time() start2=time.time() Fibonacci_recursion(34) end2=time.time() time1=end1-start1 time2=end2-start2 print("Czas działania metody iteracyjnej:",time1) print("Czas działania metody rekurencyjnej:",time2)
false
e61ca9df1aa86ca5680c9f8b3fa5ceaa832683ae
alecordev/image-processing
/simple/thumbnail_generator.py
942
4.125
4
""" Image.resize resizes to the dimensions you specify: Image.resize([256,512],PIL.Image.ANTIALIAS) # resizes to 256x512 exactly Image.thumbnail resizes to the largest size that (a) preserves the aspect ratio, (b) does not exceed the original image, and (c) does not exceed the size specified in the arguments of thumbnail. Image.thumbnail([256, 512],PIL.Image.ANTIALIAS) # resizes 512x512 to 256x256 Furthermore, calling thumbnail resizes it in place, whereas resize returns the resized image. thumbnail also does not enlarge the image. So e.g. an image of the size 150x150 will keep this dimension if Image.thumbnail([512,512],PIL.Image.ANTIALIAS) is called. """ from PIL import Image def main(filename: str): with Image.open(filename) as im: im.thumbnail((256, 256)) im.save(filename.split('.')[0] + '_thumbnail.jpg', "JPEG") if __name__ == '__main__': main("../generation/image_with_text.png")
true
03faa581b0a920029331bcce634b4829d8814243
DarkEnergySurvey/despymangle
/python/despymangle/EmptyMangle.py
1,458
4.1875
4
class Empty_Mangle: """ Class to mimic a Mangle object when there are 0 input polygons The class takes no arguments """ def __init__(self): pass def weight(self, ra, dec): """ Method to return the default weight (0.0) Parameters ---------- ra - float The RA of the point in degrees. dec - float The DEC of the point in degrees. Returns ------- 0.0 """ return 0.0 def polyid(self, ra, dec): """ Method to return the poly ids an array of -1's Parameters ---------- ra - list of floats A list of RA points dec - list of floats A list of DEC points Returns ------- A list of the same length as the input lists, filled with -1 """ return [-1] * len(ra) def polyid_and_weight(self, ra, dec): """ Method to return a list of poly ids and weights (-1 and 0.0) Parameters ---------- ra - list of floats A list of RA points dec - list of floats A list of DEC points Returns ------- A tuple of the same length as the input lists, filled with [-1, 0.0] """ return tuple([[-1, 0.0]] * len(ra))
true
458e5320a43f34c44c7db5d06656f21a1c4b80ca
dreaminkv/python-basics
/practical_task_7/practical_task_7_1.py
561
4.21875
4
#1: Даны два списка фруктов. Получить список фруктов, присутствующих в обоих исходных списках. # Примечание: Списки фруктов создайте вручную в начале файла. res = [] fruits_one = ['Ананас', 'Дракон', 'Банан', 'Киви', 'Мандарин'] fruits_two = ['Ананас', 'Лимон', 'Дракон', 'Мандарин'] fruits_one_two = [fruit for fruit in fruits_one if fruit in fruits_two] print(fruits_one_two)
false
2d39b163ff657e5ccfaa3cf5938ce37c2ae51c7d
dreaminkv/python-basics
/practical_task_7/practical_task_7_2.py
815
4.28125
4
# 2: Дан список, заполненный произвольными числами. Получить список из элементов исходного, удовлетворяющих следующим условиям: #Элемент кратен 3, #Элемент положительный, #Элемент не кратен 4. #Примечание: Список с целыми числами создайте вручную в начале файла. Не забудьте включить туда отрицательные числа. 10-20 чисел в списке вполне достаточно. numbers = [1, 5, -9, 10, 27, 8, 17, 45, 100, 11, -7, 12, -27] number_sorting = [number for number in numbers if number % 3 == 0 and number % 4 != 0 and number > 0] print(number_sorting)
false
687ff1bd0cc99edba3c3d4982ffef72bc4e918f5
AnkitaJainPatwa/python-assignment1
/Testapp/largest.py
246
4.25
4
list = [] num=int(input("Enter number u want to enter ")) for i in range(num): numbers=int(input("enter number")) list.append(numbers) print("Maximum number of elements :",max(list), "/n Minimum number of element in list",min(list))
true
20a961b9a44a2e227192cc40b594b00b5a976ae5
abhilive/python-development
/Data Structures/strings.py
1,285
4.3125
4
""" Strings String: String as an ordered sequence. Each element in the sequence can be accessed using an index represented by the array of numbers. """ Name= "Michael Jackson" #Indexing print(Name[0]) #first character print(Name[13]) #Character at the 14th position, because indexing starts from 0 print(Name[-1]) #first character from last #Length print(len(Name)) #Slicing print(Name[0:4]) #Chars from 0 to 4 print(Name[8:12]) #Chars from 8 to 12 #Input stride value print(Name[::2]) #Selecting every second charcter starting from index 0 #Slicing with stride print(Name[0:5:2]) #Select first five elements then use stride #Concatenate or combine strings print(Name + ' is the best') #Replicate string print(3*Name) #Escape Sequence print(" Michael Jackson \n is the best" ) # n for newline print(" Michael Jackson \t is the best" ) # t for tab print(" Michael Jackson \\ is the best" ) # To dispaly a backslash in string print(r" Michael Jackson \ is the best" ) # Other way to dispaly a backslash #Operations print(Name.upper()) #To covert lowercase to uppercase print(Name.lower()) #To covert uppercase to lowercase print(Name.replace('Michael', 'Janet')) # To replace certain part of string print(Name.find('Jack')) #To find a sub-string, retrun first index of sequence and -1 in case of sub-string is not found
true
df69f69881b2eb58a44d5baeb84ffb44a0882613
lyubadimitrova/cl-classes
/Prog1/Lösungen/blatt 05/aufg17.py
599
4.1875
4
# -*- coding: utf-8 -*- """ Created on Wed Nov 30 22:57:02 2016 @author: Asus """ def erase_stopwords(text,stopword_list): li_words=text.split() #split into words at whitespace characters li_words=[elm for elm in li_words if elm not in stopword_list] #makes a list only of the elements not in the stopword-list new_text=" ".join(li_words) #makes a string of the 'clean' list return new_text text="The man with the cat spoke of the sea" stopword_list=['The','the','of','a'] print(erase_stopwords(text,stopword_list))
true
9cf2eb9229bac7b308521a118763e2add77169f4
wfwf1990/python
/Day6/2-偏函数/偏函数.py
218
4.125
4
#二进制转换成十进制 print(int("1010",base = 2)) #偏函数 def int2(str,base = 2): return int(str,base) print(int2("1010")) import functools int3 = functools.partial(int,base = 2) print(int3("1010"))
false
41ad7a14c20383651ec25cbe47de93c1363f9ae8
wfwf1990/python
/Day5/3-迭代器.py
1,451
4.125
4
''' 可迭代对象:可以直接作用于for循环的对象统称为可迭代对象 可以用isinstance() 去判断一个对象是否是可迭代对象 可以直接作用于for的数据类型一般分两种 1丶集合数据类型,如list丶tuple丶dict丶set丶string 2丶generator,包括生成器和带yield的generator function ''' from collections import Iterable from collections import Iterator print(isinstance([],Iterable)) print(isinstance((),Iterable)) print(isinstance({},Iterable)) print(isinstance("",Iterable)) print(isinstance((x for x in range(10)), Iterable)) ''' 迭代器:不但可以作用于for循环,还可以被next()函数不断调用并返回下一个值,直到最后抛出一个StopIteration错误表示无法继续返回下一个值 可以被next()函数调用并不断返回下一个值的对象称为迭代器 可以用isinstance() 去判断一个对象是否是可迭代对象 ''' print(isinstance([],Iterator)) print(isinstance((),Iterator)) print(isinstance({},Iterator)) print(isinstance("",Iterator)) print(isinstance((x for x in range(10)), Iterator)) #迭代器 l = (x for x in range(5)) print(next(l)) print(next(l)) print(next(l)) print(next(l)) print(next(l)) #print(next(l)) #列表转换成迭代器 a = iter([1,2,3,4,5]) print(next(a)) print(isinstance(iter([]),Iterator)) print(isinstance(iter(()),Iterator)) print(isinstance(iter({}),Iterator)) print(isinstance(iter(""),Iterator))
false
7d9ec57f5b16a4952c42cc77de423e54de19eb8b
wfwf1990/python
/看书笔记/看书练习/类/electriccar.py
1,960
4.125
4
class Car(): def __init__(self,make,model,year): self.make = make self.model = model self.year = year self.odometer_reading = 0 def getDescriptiveName(self): #返回描述性信息 long_name = str(self.year) + " " + self.make + " "+ self.model return long_name.title() def getOdometerReading(self): print("This car has " + str(self.odometer_reading) + " miles on it") #通过方法接受一个里程值,并将其存储到self.odometer_reading中 def updateOdometer(self,mileage): #禁止将里程数往回调 if mileage >= self.odometer_reading: self.odometer_reading = mileage else: print("you can not roll back an odometer") def increment_odometer(self,miles): if miles >= 0: self.odometer_reading += miles else: print("you can not roll back an odometer") #创建子类:子类继承父类的属性和方法 ''' class ElectricCar(Car): #定义电动汽车子类,其中括号为父类的名称 def __init__(self,make,modle,year): #接受创建Car实例所需的信息 super(ElectricCar, self).__init__(make,modle,year) #super特殊函数,将父类和子类关联起来 my_new_car = ElectricCar("tesla","model S",2016) #子类继承了父类的属性和方法 print(my_new_car.getDescriptiveName()) ''' # #创建子类的特有属性和方法 class ElectricCar(Car): def __init__(self,make,modle,year): super(ElectricCar, self).__init__(make,modle,year) self.battery_size = 70 #创建电动汽车电瓶的容量 def describeBattery(self): #打印一条描述电瓶容量的方法 print("This car has a " + str(self.battery_size) + "-KWh battery") my_tesla = ElectricCar("tesla","model S",2016) print(my_tesla.getDescriptiveName()) my_tesla.describeBattery()
false
9730f238803f1ff1af060e0b8509f43b1ee57477
masterpranav/Samsung_Interview_Questions
/DelNode.py
834
4.3125
4
#Question Link: https://practice.geeksforgeeks.org/problems/delete-without-head-pointer/1 class Node(): def __init__(self,val=None): self.data = val self.next = None def push(head, val): newnode = Node(val) newnode.next = head.next head.next = newnode def print_list(head): temp = head.next while(temp!=None): print(temp.data, end = ' ') temp = temp.next print() def delete_node(node): if(node==None): return elif (node.next != None): node.data = node.next.data node.next = node.next.next else: node=Node() if __name__ == '__main__': head = Node() push(head,1) push(head,4) push(head,1) push(head,12) push(head,1) print('list before deleting:') print_list(head) delete_node(head.next.next.next.next.next) print('list after deleting: ') print_list(head)
false
4109dcb00627a89d81e20642d55e9a23edf0db94
nunrib/Curso-em-video-Python-3
/MUNDO 1/ex018.py
258
4.125
4
from math import sin, cos, tan, radians a = float(input('Informe a medida do ângulo: ')) print(f'A medida do seno é {sin(radians(a)):.2f}') print(f'A medida do cosseno é {cos(radians(a)):.2f}') print(f'A medida da tangente é {tan(radians(a)):.2f}')
false
e35ee128f8ce5d3473e9edffdf1efb3b7ad7893a
jonathanhockman/lc101
/chapter4/turtle/makecircle.py
689
4.28125
4
import turtle import math radius = int(input("Enter radius: ")) sides = int(input("Enter number of sides: ")) step_length = 2 * radius * math.sin(math.pi/sides) inradius = step_length/(2 * math.tan(math.pi/sides)) print(step_length) print(inradius) wn = turtle.Screen() center = turtle.Turtle() center.shape("circle") center.shapesize(1) center.color("red") circle = turtle.Turtle() circle.up() circle.goto(0, -radius) circle.down() circle.color("blue") circle.circle(radius) circle.speed(100) timmy = turtle.Turtle() 3 timmy.up() timmy.goto(-step_length/2, -inradius) timmy.down() for _ in range(sides): timmy.forward(step_length) timmy.left(360/sides) wn.exitonclick()
false
4e160523f340e001496f30cb1bfc14ff5182c291
monkeylyf/interviewjam
/dynamic_programming/leetcode_Expression_Add_Operators.py
1,840
4.125
4
"""Expression ad operators leetcode Given a string that contains only digits 0-9 and a target value, return all possibilities to add binary operators (not unary) +, -, or * between the digits so they evaluate to the target value. Examples: "123", 6 -> ["1+2+3", "1*2*3"] "232", 8 -> ["2*3+2", "2+3*2"] "105", 5 -> ["1*0+5","10-5"] "00", 0 -> ["0+0", "0-0", "0*0"] "3456237490", 9191 -> [] """ class Solution(object): def addOperators(self, num, target): """DP. :type num: str :type target: int :rtype: List[str] """ def dfs(num, i, last, acc, container, target): if i == len(num): if target == 0: container.append(''.join(acc)) return for j in xrange(i, len(num) + 1): next_num = num[i:j] if j == 1 or num[j] != "0"): # prevent "00*" as a number acc.append('+') acc.append(val) dfs(num[i:], i, acc, int(val), container, target - int(val)) acc.pop() acc.pop() acc.append('-') acc.append(val) dfs(num[i:], i, acc, -int(val), container, target + int(val)) acc.pop() acc.pop() acc.append('*') acc.append(val) dfs(num[i:], i, acc, last*int(val), container, target + last - last * int(val)) acc.pop() acc.pop() container = [] for i in xrange(len(num) + 1): dfs(num, i, num[:i], [num[:i]], container, target) return container def main(): sol = Solution() print sol.addOperators("1051", 6) if __name__ == '__main__': main()
true
6a169413bb9c2aa5919d0413f92aa0c2d12a9981
monkeylyf/interviewjam
/sort/radix_sort.py
1,472
4.21875
4
"""Radix sort https://en.wikipedia.org/wiki/Radix_sort """ def radix_sort(nums): """Radix sort. :param nums: list, of int """ max_val = max(nums) base = 1 while base <= max_val: # Sort by digit until digit position is larger than one of max value. radix_sort_util(nums, base) base *= 10 def radix_sort_util(nums, base): """Radix sort by digit. :param nums: list, of int :param base: int, base digit """ count = [0] * 10 for val in nums: digit = (val / base) % 10 count[digit] += 1 for i in range(1, 10): # Accumulate the count. After this, count[i] means how many number are # there <= nums[i], further by the index it should belong to in new arr # by count[i] - 1 count[i] += count[i - 1] # A trick here to assign the elements in the same bucket in reversed order. buckets = [None] * len(nums) i = len(nums) - 1 while i >= 0: val = nums[i] digit = (val / base) % 10 counter = count[digit] buckets[counter - 1] = nums[i] count[digit] -= 1 # Decrement by 1 so if there is another number share the same bucket # it will be assign to idx - 1 i -= 1 for i, val in enumerate(buckets): nums[i] = val def main(): nums = [170, 45, 75, 90, 802, 2, 24, 66] radix_sort(nums) assert nums == sorted(nums) if __name__ == '__main__': main()
true
6e4c9ddf1a6ca582b8e10c457e3b127c84c204c1
bstefansen/InterestCalculator
/BES_Interests.py
2,235
4.1875
4
# Filename: BES_Interests.property # Description: A program that calculates the interest on a loan # Author: Blake Stefansen # Defines the program introduction def intro(): print("") print("Welcome to the interest calculator") print("") # Checks loan input for the "$" sign def dlrTest(loanAmount): if loanAmount[0] == "$": newLoanAmount = loanAmount.replace("$", "") return newLoanAmount return loanAmount # Checks the loan input for the "," sign def commaTest(loanAmount): if "," in loanAmount: newLoanAmount = loanAmount.replace(",", "") return newLoanAmount return loanAmount # Checks the loan input for the letter "K" def kTest(loanAmount): if "K" in loanAmount: newLoanAmount = loanAmount.replace("K", "") newLoanAmount = float(newLoanAmount)*1000 return newLoanAmount return loanAmount # Checks the loan input for the "%" sign def percentTest(rate): if "%" in rate: replace = rate.replace("%", "") return replace return rate # Calculates the loan interest amount def calc(loanAmount, rate): rateDecimal = float(rate)*0.01 interest = float(loanAmount)*rateDecimal return interest # Defines the program output def output(loanAmount, rate): print("") print("Loan amount: " + str('${:,.2f}'.format(float(loanAmount)))) print("Interest rate: " + str('{:.3f}%'.format(float(rate)))) print("Interest amount: " + str('${:,.2f}'.format(float(calc(loanAmount, rate))))) print("") # Prompts the user to continue the program def again(): againAnswer = input("Continue? (y/n): ") if againAnswer == "y": main() else: print("") print("Bye!") print("") # Defines the main program sequence def main(): intro() loanAmount = str(input("Enter loan amount: ")) rate = str(input("Enter interest rate: ")) dlrTest(loanAmount) loanAmount = dlrTest(loanAmount) commaTest(loanAmount) loanAmount = commaTest(loanAmount) kTest(loanAmount) loanAmount = kTest(loanAmount) percentTest(rate) rate = percentTest(rate) calc(loanAmount, rate) output(loanAmount, rate) again() if __name__ == '__main__': main()
true
32ef8e3bd3def71aff8225e74add392357c382f5
Emmanuelraj/python-crash-course
/forloop.py
370
4.375
4
# for loop for i in range (10): print(i) # start, stop, step for loops for i in range (10, -1, -1): print(i) # dec # iterte the list list = [1,4,5,2,3,5] for i in range (len(list)): print('list',list[i]) # enumerate will provide both index and value(element) for i, element in enumerate(list): print(i,element) print('element',element)
true
cba2b9fa25f04208876d0daff15d9ce0f989b309
sdelgadillobaha/GWC
/story.py
991
4.3125
4
start = ''' Your friend has just moved to sunny California and she doesn/t know where she is. Your task is to find her before she gets even more lost. ''' keepplaying = "yes" print(start) while keepplaying == "Yes" or keepplaying == "yes": userchoice = input("Should I go left or right?") if userchoice == "left" or userchoice == "Left": print('You found your friend!') print("") keepplaying = input('Would you like to try again? Type yes or no.') if keepplaying == "no": quit() elif userchoice == "right" or userchoice == "Right": print("Your friend is no where to be seen. She will be lost forever.") keepplaying = input('Would you like to try again? Type yes or no.') if keepplaying == "no": quit() else: print("Not a valid answer. Try again.") keepplaying = input('Would you like to try again? Type yes or no.') if keepplaying == "no": quit() elif: print(start)
true
0a02bad102361cd956d5ba342cfe311fdab00701
CarsonStevens/Mines-Courses
/Mines Courses/CSCI_252/Lab 1 - Blink/blink.py
2,229
4.34375
4
#Author: Carson Stevens #Date 1/25/2018 #Description: Make an LED blink; try out different combinations import RPi.GPIO as GPIO import time #asks user for options on what to do. toDo = (input("What would you like to do? \r\n Input (1) to turn on a solid LED.\r\n Input (2) to make an LED blink. \r\n Input (3) to use a button to turn on an LED.\r\n Input (4) to turn on multiple LEDs \r\n (q) to quit. ") #Sets the GPIO mode GPIO.setmode(GPIO.BCM) #Taken out and code modified #pin = int(input("What pin would you like to use")) while(toDo != 'q'): if(toDo == 1): pin = 24 GPIO.setup(pin, GPIO.OUT) while True: GPIO.output(24, True) elif (toDo == 2): pin = 25 GPIO.setup(pin, GPIO.OUT) #amount of time between blinks toSleep = float(input("Input time to sleep:")) #amount of blinks blinks = int(input("How many times should it blink:")) counter = 0 #blinks the chosen LED for the amount of blinks set while (counter < blinks): #code for the blinking portion GPIO.output(pin, True) time.sleep(toSleep) GPIO.output(pin, False) time.sleep(toSleep) #iterates the counter for the amount of total blinks counter = counter + 1 elif (toDo == 3): pin = 26 GPIO.setup(pin, GPIO.OUT) while True: #Causes the button to work. When pressed, it causes the LED in pin 26 #to turn on if True: GPIO.output(26, True) elif (toDo == 4) pin = 24 pin2 = 25 GPIO.setup(pin, GPIO.OUT) GPIO.setup(pin2, GPIO.OUT) #Turns on the two ports with LEDs while True: GPIO.output(pin, True) GPIO.output(pin2, True) GPIO.cleanup() toDo = input("What would you like to do? \r\n Input (1) to turn on a solid LED.\r\n Input (2) to make an LED blink. \r\n Input (3) to use a button to turn on an LED.\r\n Input (4) to turn on multiple LEDs\r\n (q) to quit. ") #added again incase the 'q' command is hit in the middle of execution and thus doesn't reach the #clean up in the loop. GPIO.cleanup()
true
81e99a1d1398a332d5ed5756cf40234276638769
fashioncrazy9/HackBulgaria_0
/Week_6/strings.py
1,733
4.21875
4
def str_reverse(string): result = "" last_index = len(string) - 1 while last_index >= 0: result += string[last_index] last_index -= 1 return result print(str_reverse("Python")) def join(delimiter, items): result = "" for item in items: item = str(items) for index in range(0, len(items)): result += items[index] + delimiter return result print(join(" ", ["Radoslav", "Yordanov", "Georgiev"])) def string_to_char_list(string): result = [] for ch in string: result += [ch] return result def char_list_to_string(char_list): result = "" for ch in char_list: result += ch return result def take(n, items): if n > len(items): n = len(items) index = 0 new_list = [] while index < n: new_list = new_list + [items[index]] index += 1 return new_list def startswith(search, string): n = len(search) search_char_list = string_to_char_list(search) return take(n,string) == search_char_list print(startswith("Py", "Python")) def endswith(search,string): string = str_reverse(string) search = str_reverse(search) return startswith(search, string) print(endswith(".py", "hello.py")) def str_drop(n, string): result = "" for index in range(n, len(string)): result += string[index] return result def trim_left(string): while startswith(" ", string): string = str_drop(1, string) return string def trim_right(string): return str_reverse( trim_left(str_reverse(string))) def trim(string): result = trim_right(string) result = trim_left(string) return result print(trim(" ddd "))
true
903b95370d8c4008f59eaab498b5a404ef0458b8
mohankumarp/Training
/Python_RF_Training/Python/LAB/variable_printing.py
1,032
4.125
4
#------------------------------------------------------------------------------- # Name: module1 # Purpose: # # Author: MohanKumarP # # Created: 22/12/2015 # Copyright: (c) MohanKumarP 2015 # Licence: <your licence> #------------------------------------------------------------------------------- def main(): my_name = 'Zed A. Shaw' my_age = 35 # not a lie my_height = 74 # inches my_weight = 180 # lbs my_eyes = 'Blue' my_teeth = 'White' my_hair = 'Brown' print "Let's talk about %s." % my_name print "He's %d inches tall." % my_height print "He's %d pounds heavy." % my_weight print "Actually that's not too heavy." print "He's got %s eyes and %s hair." % (my_eyes, my_hair) print "His teeth are usually %s depending on the coffee." % my_teeth # this line is tricky, try to get it exactly right print "If I add %d, %d, and %d I get %d." % ( my_age, my_height, my_weight, my_age + my_height + my_weight) if __name__ == '__main__': main()
true
1df108e04cc677e8062140ef643cf66b35415503
Lucho-ai/holbertonschool-higher_level_programming
/0x0B-python-input_output/3-write_file.py
279
4.25
4
#!/usr/bin/python3 """ This is a module for write_file. """ def write_file(filename="", text=""): """Write a string to a text file (UTF8) and return the number of characters written.""" with open(filename, 'w') as f: chars = f.write(text) return chars
true
bb082b70b143defc2b1e336ce57b699130c94cd2
xuleichao/xlc
/py_learning/Fibonacci.py
488
4.1875
4
a=int(input('please input the number of Fibonacci')) Fibonacci_1=0 Fibonacci_2=1 count=3 if a<=0: print('please input a positive number') elif a==1: print('The {0} Fibonacci sequece is {1}'.format(a,Fibonacci_1)) else: print('Fibonacci is ') print Fibonacci_1,Fibonacci_2, while count<=a: Fibonacci_n=Fibonacci_1+Fibonacci_2 print Fibonacci_n, #update the var Fibonacci_1=Fibonacci_2 Fibonacci_2=Fibonacci_n count+=1
true
b5db81bd0f1a0a1528823e0745079615bf2e88d1
joshie-k/daily-coding-problem
/dec_23_2019.py
1,376
4.15625
4
''' Implement a stack that has the following methods: push(val), which pushes an element onto the stack pop(), which pops off and returns the topmost element of the stack. If there are no elements in the stack, then it should throw an error or return null. max(), which returns the maximum value in the stack currently. If there are no elements in the stack, then it should throw an error or return null. Each method should run in constant time. ''' ''' initial thoughts: keep track of a max value two stacks? in the second stack, if the # you are adding to is greater than the curr maximum, add the # to the stack when you pop, if the value is qaual to the current max, pop the value of the second stack as well ''' class maxStack(): def __init__(self): self.stack = [] self.stack_maxes = [] def push(self, val): self.stack.append(val) if self.max(): if val > self.max(): self.stack_maxes.append(val) else: self.stack_maxes.append(val) def pop(self): if len(self.stack) == 0: return None if self.stack[-1] == self.stack_maxes[-1]: self.stack_maxes.pop() return self.stack.pop() def max(self): if len(self.stack) == 0 or len(self.stack_maxes) == 0: return None return self.stack_maxes[-1] # sanity check print("hello") ms = maxStack() ms.push(11) ms.push(8) ms.push(9) ms.push(1) print(ms.pop()) print(ms.max())
true
6d7429cc928054e97001456b550c1376fddc07c7
Juhkim90/L5-if-elif-else-Conditional-Statement
/main.py
1,057
4.1875
4
a = 200 b = 33 if (b > a): print("b is greater than a") else: print("b is not greater than a") # Write a conditional statement that evaluates if the user input is positive or negative a = 5000 # Hard coding num = int(input("Enter a number: ")) if(num > 0): print("I see that your number is positive") elif(num == 0): print("You entered 0") else: print("It's negative") # Ask the user for their age # If they are younger than 13, tell them they can only watch PG/G Movies # If the are 13 and older but younger than 17, they can only watch PG-13/PG/G movies # If they are 17 and older, they can watch all movies age = int(input("What is your age? ")) if(age < 13): print("You can only PG/G movies") elif(17 > age >= 13): print("That means you can watch PG-13 and PG/G movies") else: print("You can watch all movies") is_Hungry = False is_Sleepy = False if(is_Hungry == True): print("You should go eat") if(is_Sleepy == True): print("You should go sleep") if(is_Sleepy == False): print("Wow you're well-rested")
true
f1d9e282ac1b2b09b486d06fbd4094feceed96c4
SreeramSP/Python-Function-Files-and-Dictionary-University-of-Michigan-
/#Write a function called change that take.py
230
4.125
4
#Write a function called change that takes any string, adds “Nice to meet you!” to the end of the argument given, and returns that new string. def change(str): return str+'Nice to meet you!' print(change('Welcome'))
true
ae0054a1dadf709d4abc959ea89134dcaa1f616d
Scott-S-Lin/Python_ittraining
/0319/eval.py
967
4.15625
4
string = input('現在輸入的是字串: ') # 以input 函數取得使用者輸入字串 print(type(string)) # 利用type() 確定取得的資料型態是str integer1 = input(' 現在我想取得兩個數字來相除,先取分子:') integer2 = input(' 再取分母:') print(type(integer1), type(integer2)) # 利用type() 確定取得的資料型態是str print(integer1/integer2) #這裡如果執行會產生錯誤 # 因input 取得的是字串,而字串不能相除 # 使用eval() 函數來轉變取得兩個數字的資料型態 integer1 = eval(input('重新取兩個數字,取分子:' )) integer2 = eval(input('取分母: ')) # 用type() 確定取得的資料型態是數值型態 print(type(integer1), type(integer2)) # 兩個數值型態的資料相除就不會出錯 print(integer1/integer2) # 預設會出現error integer = eval(input('測試eval 如果輸入不能轉變成數值的資料會如何:'))
false
5e7eaa31df89db0c76f7667bd50e86270625da60
Lopez-Samuel/PythonProjects
/DivBy3.py
656
4.25
4
def main(): totalSum=calculateSum(number) divBy3(totalSum) def calculateSum(number): 'This function calculates the sum of the individual digits of any given number' if number<10: return number else: lastDigit=number%10 sumNumber=0 count=0 while number !=0: number=(number/10) temp1=(number%10) sumNumber=temp1+sumNumber count=count+1 totalSum=lastDigit+sumNumber return totalSum def divBy3(totalSum): 'Checks to see if the total sum is divisible by 3' if totalSum%3==0: print True else: print False main()
true
5da34df0890e5ef5b82734c1d9f26991620a85ee
tipowers/Leap-Year-Calculator
/Leap Year Calculator.py
717
4.375
4
# This program asks a user to input a year and then calculates whether the year was a leap year or not # Get year user wishes to test year = int(input('Enter a year: ')) # If year is divisible by 100 and 400 # Output leap year statement if year % 100 == 0 and year % 400 == 0: print('\nIn the year', year, 'February has 29 days. It is a leap year!') # If year is not divisible by 100, but is divisible by 4 # Output leap year statement elif year % 100 != 0 and year % 4 == 0: print('\nIn the year', year, 'February has 29 days. It is a leap year!') # Output no leap year statement else: print('\nIn the year', year, 'Febuary has 28 days.', year, 'is not a leap year.') print('\nAuthor: Tim Powers')
true
9e60a6c9ec1aaebd27a73702a687500ee766f702
nishantchaudhary12/Intro-to-Algorithms-3rd-edition-CLRS
/Chapter 7/randomizedQuickSort.py
811
4.125
4
#quick sort #randomized partition import random def randomized_partition(arr, start, end): i = random.randint(start, end) arr[i], arr[end] = arr[end], arr[i] return partition(arr, start, end) def quickSort(arr, start, end): if start < end: key = randomized_partition(arr, start, end) quickSort(arr, start, key - 1) quickSort(arr, key + 1, end) def partition(arr, start, end): x = arr[end] i = start - 1 for j in range(start, end): if arr[j] <= x: i += 1 temp = arr[i] arr[i] = arr[j] arr[j] = temp arr[end] = arr[i + 1] arr[i + 1] = x return i + 1 def main(): arr = [2, 8, 7, 1, 3, 5, 6] print(arr) quickSort(arr, 0, len(arr) - 1) print('Sorted array:', arr) main()
false
3d33778d5384a8e0e8455f6ca28ef74153fcf178
AntHudovich/Repo-kraken
/Hudovich_Antanina_dz_9/task_9_3.py
2,061
4.21875
4
# 3. Реализовать базовый класс Worker (работник). # определить атрибуты: name, surname, position (должность), income (доход); # последний атрибут должен быть защищённым и ссылаться на словарь, содержащий элементы: # оклад и премия, например, {"wage": wage, "bonus": bonus}; # создать класс Position (должность) на базе класса Worker; # в классе Position реализовать методы получения полного имени сотрудника (get_full_name) # и дохода с учётом премии (get_total_income); # проверить работу примера на реальных данных: создать экземпляры класса Position, # передать данные, проверить значения атрибутов, вызвать методы экземпляров. class Worker: def __init__(self, name, surname, position, income): self.name = name self.surname = surname self.position = position self._income = income class Position(Worker): def get_full_name(self): print(self.name, self.surname) def get_total_income(self): print(self._income["wage"] + self._income["bonus"]) if __name__ == '__main__': salary_components = { "wage": 1000, "bonus": 100 } ringleader = Position('Vasiliy', 'Chapaev', 'commander', salary_components) ringleader.get_full_name() ringleader.get_total_income() assistant = Position('Peter', 'Isaev', 'assistant', salary_components) assistant.get_full_name() assistant.get_total_income() fighting_girlfriend = Position('Ann', 'the_machine_gunner', 'mastermind', salary_components) fighting_girlfriend.get_full_name() fighting_girlfriend.get_total_income() # А total_income у всех одинаковый потому что коммунизьм
false
f376acd3976f007447942ad367365564bc63f9d0
AntHudovich/Repo-kraken
/Hudovich_Antanina_dz_9/task_9_2.py
1,178
4.1875
4
# 2. Реализовать класс Road (дорога). # определить атрибуты: length (длина), width (ширина); # значения атрибутов должны передаваться при создании экземпляра класса; # атрибуты сделать защищёнными; # определить метод расчёта массы асфальта, необходимого для покрытия всей дороги; # использовать формулу: длина * ширина * масса асфальта для покрытия одного кв. метра дороги асфальтом, # толщиной в 1 см * число см толщины полотна; # проверить работу метода. # Например: 20 м*5000 м*25 кг*5 см = 12500 т. class Road: def __init__(self, length, width): self.__length = length self.__width = width def mass(self, thickness): mass = self.__length * self.__width * 25 * thickness print(mass / 1000, 'тонь :)') if __name__ == '__main__': mkad = Road(1000, 20) mkad.mass(5)
false
bb111b38333310bc181eb37fc2c5eb8ea0dd7a7b
ayumitanaka13/python-basic
/class/base9.py
785
4.125
4
# ポリモーフィズム from abc import abstractmethod, ABCMeta class Human(metaclass=ABCMeta): # 親クラス def __init__(self, name): self.name = name @abstractmethod def say_something(self): pass def say_name(self): print(self.name) class Woman(Human): def say_something(self): print('女性: 名まえは={}'.format(self.name)) class Man(Human): def say_something(self): print('男性: 名まえは={}'.format(self.name)) # ポリモーフィズム num = input('0か1を入力してください') if num == '0': human = Man('Taro') elif num == '1': human = Woman('Hanako') else: print('入力が間違っています') human.say_something()
false
fe482fb2f3d010dfd6f1a268189de6eb85debb84
Tatenda1Chataira/01_Lucky_Unicorn
/00_LU_Base_v_01.py
1,350
4.15625
4
# Functions go here... def yes_no (question): valid = False while not valid: response = input(question).lower() if response == "yes" or response == "y": response = "yes" return response elif response == "no" or response == "n": response = "no" return response else: print("Please answer yes / no") def instructions(): print("**** How to Play ****") print() print("The rules of the game go here") print() return "" def num_check(question, low, high): error = "Please enter an whole number between 1 and 10\n" valid = False while not valid: try: # ask the question response = int(input(question)) # if the amount is too low / too high give if low < response <= high: return response # output an error else: print(error) except ValueError: print(error) # Main Routine goes here.. played_before = yes_no ("Have you played the game before? ") if played_before == "no": instructions() # Ask user how much they want to play with... how_much = num_check ("How much would you like to play with? ", 0, 10) print("You will be spending ${}".format (how_much))
true
c98ea1feb5596976c2826d7fcd05087e9fa93730
leandroflima/Python
/Verificando_ordenacao.py
363
4.15625
4
numero1str = input("Digite o primeiro número: ") numero2str = input("Digite o segundo número: ") numero3str = input("Digite o terceiro número: ") numero1 = int(numero1str) numero2 = int(numero2str) numero3 = int(numero3str) if ((numero1 < numero2) and (numero2 < numero3)): print("crescente") else: print("não está em ordem crescente")
false
c14c03b9717796a8261c7663f9118545d2634950
Sardiirfan27/pwa-resto.github.io
/kal.py
331
4.15625
4
list_a = range(1,10,3) # bilang dimuulai dari angka 1 dan lebih kecil dari 10 , kemudian naik setiap +3 x = [ [a**2, a**3] for a in list_a] print(x) print("Hello World") print("Welcome to Python") a=3; print(float(a)) d = "Dicoding" d[3] x = [10,15,20,25,30] print(x[-3:]) x = 300 str(x).zfill(5) x = 'hello' print(type(x))
false
8f0230f54bdbed53b69244d07c4063687a24dc1f
rustymeepo/VSA-Python
/proj04/proj04.py
618
4.25
4
# Name: # Date: """ proj04 Asks the user for a string and prints out whether or not the string is a palindrome. """ str1 = [] print 'type in a word or phrase, and i will see if it is a palindrome.' count = 0 print wordA = raw_input() for letter in wordA: if letter != ' ': str1.append(letter) else: pass word = ''.join(str1) while word: word = word.lower() if word[0] == word[-1]: word = word[1: -1] else: print 'Sorry, that word or phrase is not a palindrome.' break if len(word) == 0 or len(word) == 1: print 'That word or phrase is a palindrome!'
true
1fd0b0b600970b933757cb5dfa1f9154e8ca1c2e
saipavani-225/phython_training
/exercise3.py
744
4.15625
4
while True: ram = input("Enter a choice (rock, paper, scissors): ") raj = input("enter a choice(rock, paper, scissors):") if ram == raj: print(ram,raj,"Both players choose the same. so It's a tie!") elif ram == "rock": if raj == "scissors": print("Rock smashes scissors! You win!") else: print("Paper covers rock! You lose.") elif ram == "paper": if raj == "rock": print("Paper covers rock! You win!") else: print("Scissors cuts paper! You lose.") elif ram == "scissors": if raj == "paper": print("Scissors cuts paper! You win!") else: print("Rock smashes scissors! You lose.") continue
true
d28bd2f741ea7f24dbb60b9dc1b4e0a6e79b80d0
FlicksAsh/python_methods
/collections/lists/tuple.py
1,396
4.1875
4
# List: [] # Dictionary: {} # Tuple: () # Tuple: immutable # List: mutable post = ('Python Basics', 'Intro guide to python', 'Some cool python content') # Tuple unpacking title, sub_heading, content = post # Equivalent to Tuple unpacking # title = post[0] # sub_heading = post[1] # content = post[2] print(title) print(sub_heading) print(content) post = ('Python Basics', 'Intro guide to python', 'Some cool python content') print(id(post)) print(id(post)) post += ('published',) print(id(post)) title, sub_heading, content, status = post print(title) print(sub_heading) print(content) print(status) post = ('Python Basics', 'Intro guide to Python', 'Some cool python content') tags = ['python', 'coding', 'tutorial'] post += (tags,) print(post[-1][1]) post = ('Python Basics', 'Intro guide to Python', 'Some cool python content', 'published') print(post[1::2]) post = ('Python Basics', 'Intro guide to Python', 'Some cool python content', 'published') # Removing elements from end post = post[:-1] # Removing elements from beginning post = post[1:] # Removing specific element (messy/not recommended) post = list(post) post.remove('published') post = tuple(post) print(post) # tuples as keys in a dictionary example priority_index = { (1, 'premier'): [1, 34, 12], (1, 'mvp'): [84, 22, 24], (2, 'standard'): [93, 81, 3], } print(list(priority_index.keys()))
true
ad0e3190b5449c4ecaa38c319afcd2473d15b65c
michaelsolimano16/binary-search-and-tries
/ms_trie.py
1,620
4.28125
4
# Michael Solimano 2020 # Practice implementing a trie class trieNode(): # create trie nodes with characters and lists to hold children nodes def __init__(self, char=None): self.char = char self.children = { 'a' : None, 'b' : None, 'c' : None, 'd' : None, 'e' : None, 'f' : None, 'g' : None, 'h' : None, 'i' : None, 'j' : None, 'k' : None, 'l' : None, 'm' : None, 'n' : None, 'o' : None, 'p' : None, 'q' : None, 'r' : None, 's' : None, 't' : None, 'u' : None, 'v' : None, 'w' : None, 'x' : None, 'y' : None, 'z' : None, } self.end_of_word = False class Trie(): #Create a trie that handles the lower_case alphabet def __init__(self): self.root = trieNode() def add_trie(self, string): #add a string onto the trie string_length = len(string) mover = self.root for letter in string: if mover.children[letter] != None: mover = mover.children[letter] print(f"{letter} already here.") else: char = trieNode(letter) mover.children[letter] = char mover = mover.children[letter] print(f"Adding {letter}.") mover.end_of_word = True def search_prefix(self, word): #search for a word in the trie. #In this method, the word can be a prefix of a larger word. tracing_node = self.root for letter in word: if tracing_node.children[letter] != None: tracing_node = tracing_node.children[letter] else: print(f"{word} isn't a valid prefix.") return print(f"{word} is here!") new = Trie() new.add_trie("testing") new.add_trie("test") new.search_prefix("testr")
false
90fe897ad4b7dc157b2806a593e28b975d45d438
jjcannone/thinkful-fizz-buzz
/fizzbuzz2.py
1,145
4.34375
4
import sys """ Project Requirements + Have a hard-coded upper line, n. + Print "Fizz buzz counting up to n", substituting in the number we'll be counting up to. + Print out each number from 1 to n, replacing with Fizzes and Buzzes as appropriate. + Print the digits rather than the text representation of the number (i.e. print 13 rather than thirteen). + Each number should be printed on a new line. + If the user supplies a value at the command line when script runs, we'll use that value. + Otherwise, we'll use the raw_input() function to get a value from the user. """ n = 0 while n < 2: try: n = int(sys.argv[1]) if int(sys.argv[1]) > 1 else 2 except (IndexError, ValueError): try: n = int(raw_input("Enter the FizzBuzz limit (an integer greater than 1): ")) except ValueError: print "Invalid input... Please enter an integer greater than 1." print "Fizz buzz counting up to {0}".format(n) for num in range(1,n): if ( num % 3 == 0 ) and ( num % 5 == 0 ): print "fizzbuzz" elif ( num % 3 == 0 ): print "fizz" elif ( num % 5 == 0 ): print "buzz" else: print "{0}".format(num)
true
40b5b313583eaaf9033378c6a22dcaf11fd8b4bf
Tenzin-sama/LabExercisesPYTHON
/Lab Exercises/Lab Exercise 2/q4.py
612
4.25
4
# Lab Exercise 2, Question 4 """Given three integers, print the smallest one. (Three integers should be user input)""" num = [0, 0, 0] # input of numbers in list num for n in range(3): print("Enter the number") num[n] = int(input()) # loop to shuffle and rearrange the list in increasing order (smallest, bigger,...) for n in range(2): if num[0] > num[1]: temp = num[0] num[0] = num[1] num[1] = temp if num[1] > num[2]: temp = num[1] num[1] = num[2] num[2] = temp print(f"The smallest number is {num[0]}") print() input()
true
4a77a992cc1f1dd699e70836953f3f12dda94c15
NipunSyn/DSA
/Data Structures/Queue/queue.py
461
4.15625
4
from collections import deque # implementation of queue datastructure class Queue: def __init__(self): self.queue = deque() def enqueue(self, item): self.queue.appendleft(item) def dequeue(self): return self.queue.pop() def peek(self): if not self.is_empty(): return self.queue[-1] def is_empty(self): return len(self.queue) == 0 def get_queue(self): return self.queue
false
d76d53515150ca6f40c14eb84884c748d745428b
brookebon05/pizzeria
/NumPy/array_exercise.py
1,672
4.125
4
## Numpy Exercise import numpy as np ## Step 1: Create a 4x3 array of all 2s print( "----------------------------------------------- STEP ONE -----------------------------------------------" ) twoArray = np.full(4, 3), 2 print(twoArray) ## Step 2: Create a 3x4 array with a range from 0 to 110 where each number increases by 10 print( "----------------------------------------------- STEP TWO -----------------------------------------------" ) tenArray = np.arange(0, 11, 10).reshape(3, 4) print(tenArray) ## Step 3: Change the layout of the above array to be 4x3, store it in a new array print( "----------------------------------------------- STEP THREE -----------------------------------------------" ) newTenArray = tenArray.reshae(4, 3) print(newTenArray) ## Step 4: Multiply every elemnt of the above array by 3 and store the new values in a different array print( "----------------------------------------------- STEP FOUR -----------------------------------------------" ) newArray = newTenArray * 3 print(newArray) ## Step 5: Multiply your array from step one by your array from step 2 print( "----------------------------------------------- STEP FIVE -----------------------------------------------" ) # print(twoArray * tenArray) ## This errored out... why? print() ## Step 6: Comment out your code from Step 5 and then multiply your array from step 1 by your array from step 3 print( "----------------------------------------------- STEP SIX -----------------------------------------------" ) # MUST BE THE SAME DIMENSION COLUMNS ## this worked! why? print()
true
6ef52d6c751e34fd1b6249c1d8c627895f302750
nelsontodd/tutoring_docs
/simple_arr.py
205
4.34375
4
#This prints all the vals in the dict newDict = {'key1':'val1','key2':'val2'} for key in newDict: print(newDict[key]) newList = [] for key in newDict: newList.append(newDict[key]) print(newList)
true
013b17e67bd90ed401b0a26e178e9265bd360623
osbetel/LeetCode
/problems/lc231 - Power of Two.py
635
4.34375
4
# Given an integer, write a function # to determine if it is a power of two. # # Example 1: # Input: 1 # Output: true # Explanation: 2^0 = 1 # # Example 2: # Input: 16 # Output: true # Explanation: 2^4 = 16 # # Example 3: # Input: 218 # Output: false def isPowerOfTwo(n): if n == 0: return False if n == 1: return True # uniquely, all powers of 2 when expressed in their bitwise form # are comprised of all zeros and a single 1. # So we can just return whether or not the sum of all the bits 0, 1 == 1 return (n & (n-1)) == 0 t = [] for x in range(257): if isPowerOfTwo(x): t.append(x) print(t)
true
34f39f90a029ed07c46a3c86e11af0f2a263ba8e
osbetel/LeetCode
/problems/lc257 - Binary Tree Paths.py
1,021
4.15625
4
# Given a binary tree, return all root-to-leaf paths. # Note: A leaf is a node with no children. # Example: # Input: # # 1 # / \ # 2 3 # \ # 5 # # Output: ["1->2->5", "1->3"] # Explanation: All root-to-leaf paths are: 1->2->5, 1->3 class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None def binaryTreePaths(root: TreeNode, currString, results): if root is None: results.append(currString[:-2]) return else: if root.left is not None: binaryTreePaths(root.left, currString + str(root.val) + "->", results) if root.right is not None: binaryTreePaths(root.right, currString + str(root.val) + "->", results) elif root.left is None and root.right is None: binaryTreePaths(None, currString + str(root.val) + "->", results) return results r = TreeNode(1) r.left = TreeNode(2) r.right = TreeNode(3) r.left.right = TreeNode(5) print(binaryTreePaths(r, "", []))
true
cb5080a08157cc7cd4ff6bf27c0ac31b8457a1bf
nrhint/PythonHTML
/test2.2/openFile.py
385
4.25
4
##This will handle opening the file that you want to open. ##It will check for existing file first. def openFile(): File = input("What is the file name: ") Exists = input("Does the file allready exist (y/n): ") if Exists == 'y': open(File, 'a') elif Exists == 'n': open(File, 'x') else: print("Enter a valid exist")
true
e7e504f0af64821dc27402bb9cf2e0623e097757
marteczkah/BAM_coding_resources
/August_4th_Advanced/functions.py
754
4.25
4
# Difference in the way objects are passed to the functions list_1 = [1, 2, 3, 4, 5] #mutable object string_1 = 'abba' #immutable object def change_list(original_list): list_len = len(original_list) if list_len == 0: original_list.append(101) else: original_list[0] = 101 def new_string(old_string): old_string = old_string + 'abba' return old_string change_list(list_1) print(list_1) new_string(string_1) print(string_1) # to actually change the string you would have to # string_1 = new_string(string_1) # print(string_1) # mutable objects are passed by REFERENCE, meaning they will be changed within the funcion # immutable objectd are passed by VALUE, meaning the actual value of the variable won't be changed
true
1b2cd7a87d27db766c3184bafc3e5f3d71f9a603
rmartinez10/CALCULADORA-BASICA
/Calculadora.py
644
4.1875
4
print(' ') print(' ') print('==================<<< C A L C U L A D O R A >>>==================') print(' ') print(' ') number_1 = int(input('Enter your first number.: ')) operacao = input('''Entre com a operação....: ''') number_2 = int(input('Enter your second number: ')) print('calculando...') print('calculando...') if operacao == '+': result = number_1 + number_2 elif operacao == '-': result = number_1 - number_2 elif operacao == '*': result = number_1 * number_2 elif operacao == '/' or operacao == '%': result = number_1 / number_2 print('O resultado da operação é: ',result) print('FIM!!!')
false
b362ce0b9da2e38636918c25f8601c43141e8035
YasPHP/recursion
/coding_monkey.py
2,281
4.90625
5
""" ===== CODING MONKEY PROBLEM ===== The term "code monkey" is sometimes used to refer to a programmer who doesn't know much about programming. This is unfair to monkeys, because contrary to popular belief, monkeys are quite smart. They have just been misunderstood. This may be because monkeys do not speak English, but only monkey language. Your job is to help humans and monkeys understand each other by writing a monkey language dictionary. For each word that is typed in, your program must determine whether it is a valid monkey language word. Unlike in English, spelling in monkey language is very simple. Every word in monkey language satisfies the following rules, and every word satisfying the following rules is a monkey language word. A monkey language word is a special type of word called an A-word, which may be optionally followed by the letter Nand a monkey language word.An A-word is either only the single letter A, or the letter B followed by a monkey language word followed by the letter S. Here are some examples: The word A is a monkey language word because it is an A-word.The word ANA is a monkey language word because it is the A-word A followed by the letter N and the monkey language word A.The word ANANA is a monkey language word because it is the A-word A followed by the letter N and the monkey language word ANA.The word BANANAS is a monkey language word because it is an A-word, since it is the letter B followed by the monkey language word ANANA followed by the letter S. Write a program which accepts words, one word on each line, and for each word prints YES if the word is a monkey language word, and NO if the word is not a monkey language word. The input word "X" indicates the program should terminate, and there is no output for word "X" (even though it is not a monkey word). Credits: https://dmoj.ca/problem/ccc05j5 """ def monkey(word: str) -> str: # no clear return, just print statement so assuming equivalency exception """ Print 'YES' if <word> is a monkey language word, and 'NO' if not. """ if word == 'X': return '' else: if word in 'BANANAS': print('YES') else: print('NO') return monkey(word) # re-check recursive call placement
true
15d319f01e6c08a04e9051b72db0a34aa8c187a3
boonchu/python3lab
/coursera.org/python4/quiz/week2/quiz-6.py
1,993
4.25
4
#! /usr/bin/env python # # # In a previous homework, we implemented an iterative method for generating permutations of a set of outcomes. Permutations can # also be generated recursively. # # Given a list outcomes of length n, we can perform the following recursive computation to generate the set of all permutations of length n: # # Compute the set of permutations rest_permutations for the list outcomes[1:] of length n-1 # For each permutation perm in rest_permutations, insert outcome[0] at each possible position of perm to create permutations of length n, # Collect all of these permutations of length n into a set and return that set. # # If p(n) is the number of permutations returned by this method, what recurrence below captures the behavior of p(n)? # # http://stackoverflow.com/questions/360748/computational-complexity-of-fibonacci-sequence # https://books.google.com/books?id=my3mAgAAQBAJ&pg=PT101&lpg=PT101&dq=The+number+of+recursive+calls+to+fib+in+the+previous+problem+grows+quite+quickly.&source=bl&ots=NTFFvYWYiM&sig=_jxsEdMlJDefMLx5CwaXlJrMzlU&hl=en&sa=X&ved=0CB4Q6AEwAGoVChMIhry89bHWyAIVA_BjCh2eeAAi#v=onepage&q=The%20number%20of%20recursive%20calls%20to%20fib%20in%20the%20previous%20problem%20grows%20quite%20quickly.&f=false # https://gist.github.com/bradmontgomery/4717521 # from collections import Counter import math count = 0 def fib(num, counter): counter['fib'] += 1 if n < 3: return 1 else: return fib(num - 1, counter) + fib(num - 2, counter) n = 2 print ("%12s%15s" % ("Problem size", "Calls")) for count in range(5): c = Counter() fib(n, c) print ("%12s%15s" % (n, c['fib'])) n *= 2 #calculate calls # T(n-1) = O(2^n-1) # T(n) = T(n-1) + T(n-2) + O(1) # T(n) = O(2^n-1) + O(2^n-2) + O(1) # T(n) ~ O(2^n) # # f(n) = f(n-1) + f(n-2) # https://en.wikipedia.org/wiki/Fibonacci_number#Closed_form_expression # # O((1/sqrt(5) * 1.618^(n+1)) = O(1.618^(n+1) #result = 1.618**(n+1) #print "estimated calls:",result
true
c697bfe16020212b0df5cf78a74c11bfec824df5
Ihsan545/datetime-Assignment
/more_fun_with_collections/date_time.py
496
4.125
4
""" Program: date_time.py Author: Ihsanullah Anwary Last date modified: 10/15/2020 This program is an example of Python datetime. """ import datetime def half_birthday(date_of_birth): """accepts datetime""" half_year = datetime.timedelta(days=365 / 2) # calculates 6 months. return date_of_birth + half_year # calculates 6 months later-half-birthday if __name__ == '__main__': birth_day = datetime.date(2020, 1, 1) print(half_birthday(birth_day)) """ calling the function."""
true
17df903a61bbefe82e2061b9071066a4630e8bb4
GeorgeKailas/python_fundamentals
/02_basic_datatypes/2_strings/02_09_vowel.py
729
4.25
4
''' Write a script that prints the total number of vowels that are used in a user-inputted string. CHALLENGE: Can you change the script so that it counts the occurrence of each individual vowel in the string and print a count for each of them? ''' #\iffalse #a = input("Write a sentence:") #count = 0 #for i in a: # if i == 'a': # elif i == 'e': # elif i == 'i': # elif i == 'u': # count = count + 1 #print(count) #\if lowercase? t_str = input("Write a sentence:") counter1 = t_str.count('e') counter2 = t_str.count('a') counter3 = t_str.count('i') counter4 = t_str.count ('o') counter5 = t_str.count('u') print(counter1+counter2+counter3+counter4+counter5)
true
d63313b22e8ae262a950349b6773ef3133349a83
GeorgeKailas/python_fundamentals
/07_classes_objects_methods/07_02_shapes.py
1,061
4.53125
5
''' Create two classes that model a rectangle and a circle. The rectangle class should be constructed by length and width while the circle class should be constructed by radius. Write methods in the appropriate class so that you can calculate the area (of the rectangle and circle), perimeter (of the rectangle) and circumference of the circle. ''' class rectangle: def __init__(self, length, width): self.length = length self.width = width def area(self): return self.length * self.width def perimeter(self): return 2*self.length + 2*self.width def __str__(self): return f"My rectangle has a length of {self.length} and a width of {self.width} which gives it an area of {self.area()}" class circle: def __init__ (self, radius): self.radius = radius def circumference(self): return self.radius * 3.14 * 2 r1 = rectangle(3, 6) print(r1.area()) print(r1.perimeter()) print(r1) r2 = rectangle(10, 11) r2.area() r2.perimeter() print(r2) c1 = circle(5) print(c1.circumference())
true
3a51e03e10c3bf22103df6b5e0dcc8b2a326cb41
GeorgeKailas/python_fundamentals
/09_exceptions/09_02_calculator.py
697
4.3125
4
''' Write a script that takes in two numbers from the user and calculates the quotient. Using a try/except, the script should handle: - if the user enters a string instead of a number - if the user enters a zero as the divisor Test it and make sure it does not crash when you enter incorrect values. ''' try: dividend = int(input("Please enter the number to be divided: ")) divisor = int(input("Please enter the divisor: ")) result = dividend / divisor print(f"The result of {dividend} divided by {divisor} is {result}") except ZeroDivisionError as zde: print("There was an error with the message: ", zde) except ValueError: print("Cannot divide using that data type")
true
f80471da85121409a05f98a127beee8d58790960
TaranMNeeld/python-practice
/Factorial.py
254
4.15625
4
# Return the factorial of a given number def factorial(num, total = 0): if num == 1: return total + 1 else: total += num num -= 1 return factorial(num, total) if __name__ == '__main__': print(factorial(6))
true
0572cb9689f39399d0b160510cd27b79d2d97450
gitgutm8/AStar-PyGame
/priorityqueue.py
1,523
4.1875
4
import heapq import itertools class PriorityQueue: """ Implementation of a priority queue, using the heapq module. """ REMOVED = '<removed-task>' def __init__(self, *init_tasks): """ Initialises a `PriorityQueue` instance, optionally takes some initial tasks. :param init_tasks: Collection of task-priority pairs """ self.heap = [] self.counter = itertools.count() self.entry_finder = {} for init_task in init_tasks: self.add_task(*init_task) def add_task(self, task, priority): """Add a new task or update the priority of an existing task""" if task in self.entry_finder: self.remove_task(task) count = next(self.counter) entry = [priority, count, task] self.entry_finder[task] = entry heapq.heappush(self.heap, entry) def remove_task(self, task): """Mark an existing task as REMOVED. Raise KeyError if not found.""" entry = self.entry_finder.pop(task) entry[-1] = PriorityQueue.REMOVED def pop_task(self): """Remove and return the lowest priority task. Raise KeyError if empty.""" while self.heap: priority, count, task = heapq.heappop(self.heap) if task is not PriorityQueue.REMOVED: del self.entry_finder[task] return task raise KeyError('pop from an empty priority queue') def __bool__(self): return bool(self.heap)
true
2f9f34c60c90e81ce5d9d59454afc8b5d13fd8dd
Tele-Pet/informaticsPython
/Homework/Week 6: Strings/bookExercise6.4_v1.py
688
4.25
4
# Exercise 6.4 There is a string method called count that is similar to the # function in the previous exercise. Read the documentation of this method at # docs.python. org/library/string.html and write an invocation that counts the # number of times the letter a occurs in 'banana'. # Notes from help() # >>> help(str.count) # Help on method_descriptor: # count(...) # S.count(sub[, start[, end]]) -> int # Return the number of non-overlapping occurrences of substring sub in # string S[start:end]. Optional arguments start and end are interpreted # as in slice notation. def countLetter(word, usrString): print word.count(usrString) countLetter('banana', 'a')
true
8983f22ad5c4324fda2de6d470fdebf16a0d4ef9
Tele-Pet/informaticsPython
/Homework/Week 6: Strings/bookExercise6.1_v1.py
408
4.53125
5
# Exercise 6.1 Write a while loop that starts at the last character in the # string and works its way backwards to the first character in the string, # printing each letter on a separate line, except backwards. myString = 'Josiah' myStringLength = len(myString) myBackwardString = -1 * myStringLength index = -1 while index >= myBackwardString: letter = myString[index] print letter index = index -1
true
4ea8c3244cbe11760a177cefc2ac658ba65b85fb
Tele-Pet/informaticsPython
/Homework/Week 6: Strings/bookExercise6.6_v1.py
986
4.125
4
#!/usr/bin/env python # -*- coding: utf-8 -*- # Exercise 6.6 # Read the documentation of the string methods at docs.python. org/lib/string-methods.html. You might want to experiment with some of them to make sure you understand how they work. strip and replace are particularly useful. # The documentation uses a syntax that might be confusing. For example, in find(sub[, start[, end]]), the brackets indicate optional arguments. So sub is required, but start is optional, and if you include start, then end is optional. # >>> help(str.replace) # Help on method_descriptor: # replace(...) # S.replace(old, new[, count]) -> string # Return a copy of string S with all occurrences of substring # old replaced by new. If the optional argument count is # given, only the first count occurrences are replaced. >>> data = 'From stephen.marquard@uct.ac.za Sat Jan 5 09:14:16 2008' >>> data.replace('@', 'google.com') 'From stephen.marquardgoogle.comuct.ac.za Sat Jan 5 09:14:16 2008'
true
5ee49f9d25b870477b10299738c1e389dc8e8e56
Tele-Pet/informaticsPython
/Homework/Week 2/bookExercises/bookExercise2.4_v1.py
687
4.4375
4
# Exercise 2.4 Assume that we execute the following assignment statements: width = 17 # height = 12.0 For each of the following expressions, write the value of # the expression and the type (of the value of the expression). # 1. width/2 # 2. width/2.0 # 3. height/3 # 4. 1 + 2 * 5 # Use the Python interpreter to check your # answers. width = 17 height = 12.0 print # print a line break for sake of it looking purdier a1 = width / 2 print 'a1 equals {0}, {1}'.format(a1, type(a1)) b1 = width / 2.0 print 'b1 equals {0}, {1}'.format(b1, type(b1)) c1 = height / 3 print 'c1 equals {0}, {1}'.format(c1, type(c1)) d1 = 1 + 2 * 5 print 'd1 equals {0}, {1}'.format(d1, type(d1))
true
c4bd456c746d0e11c5a42bb75631c0c10f73fa69
Tele-Pet/informaticsPython
/Homework/Week 5/bookExercise5.1_viaOldSkool_v1.py
842
4.21875
4
#!/usr/bin/env python # -*- coding: utf-8 -*- # Exercise 5.1 Write a program which repeatedly reads numbers until the user enters “done”. Once “done” is entered, print out the total, count, and average of the numbers. If the user enters anything other than a number, detect their mistake using try and except and print an error message and skip to the next number. # Enter a number: 4 # Enter a number: 5 # Enter a number: bad data Invalid input # Enter a number: 7 # Enter a number: done # 16 3 5.33333333333 usrInput = 0 usrSum = 0 usrCount = 0 usrAvg = 0 while usrInput != 'done': usrInput = raw_input('Enter a number: ') try: usrInput = float(usrInput) usrSum += usrInput usrCount += 1 usrAvg = usrSum / usrCount except: if usrInput == 'done': print 'User average is: ', usrAvg else: print 'Invalid input'
true
59e7ab0bb825dcb823769ce57cb960e6a3a0f9d7
j-clarisse/HighSchool-Python-Lessons
/4.MoreConditionals_TrickyInputs/student.py
466
4.21875
4
# Name: Student Sorter # Date: # Author: # Description: Write a program that determines whether the user is a senior or junior student. # (Implement Years 1-12 only but make sure your program can handle weird inputs!) # Answer: year = input("What grade are you in? ") if (int(year) > 10 and int(year) < 13): print("You are a senior student") elif (int(year) > 0 and int(year) < 11): print("You are a junior student") else: print("Wrong input, try again!")
true
c556f4fd7b20813faf09e7d19581701f2c1ae6f1
nikhil1699/cracking-the-coding-interview
/python_solutions/chapter_01_arrays_and_strings/problem_01_08_set_zero.py
2,072
4.25
4
""" Chapter 01 - Problem 08 - Set Zero - CTCI 6th Edition page 91 Problem Statement: Write an algorithm such that if an element in an MxN matrix is 0, its entire row and column are set to 0. Example: [1, 2, 0, 4, [0, 0, 0, 0, 1, 2, 3, 4, -> 0, 2, 0, 4, 0, 2, 3, 4] 0, 0, 0, 0] Solution: We will implement this with allocating constant additional space. Use two boolean variables firstZeroRow and firstZeroCol that indicate whether the first row and column must be zeroed out. Search the first row and column for zeros to determine the value of these boolean values. Next, use the first row as storage to note which columns must be zeroed. Use the first column as storage to determine which rows must be zeroed. Set matrix[i][0] and matrix[0][j] to zero whenever there's a zero in matrix[i][j]. Finally, iterate through the first row and column to zero out the rows and columns indicated. Time complexity: O(MxN). Space complexity: O(1). """ def set_zero(matrix): # most optimal solution: O(RxC) time and O(1) space R, C = matrix.shape # determine if first row and column contain zeros first_zero_row = False first_zero_col = False for c in range(C): if matrix[0, c] == 0: first_zero_row = True break for r in range(R): if matrix[r, 0] == 0: first_zero_col = True break # check the rest of the matrix for zeros and use first row and col to # store this information for r in range(1, R): for c in range(1, C): if matrix[r, c] == 0: matrix[0, c] = 0 matrix[r, 0] = 0 # look at storage and apply zeros to appropriate rows and columns for r in range(1, R): if matrix[r, 0] == 0: matrix[r, :] = 0 for c in range(1, C): if matrix[0, c] == 0: matrix[:, c] = 0 # look at first row and first col booleans to zero out first row and col if first_zero_row: matrix[0, :] = 0 if first_zero_col: matrix[:, 0] = 0 return matrix
true
2dc231883d14cc246e4c71e679eae7154a37e71d
nikhil1699/cracking-the-coding-interview
/python_solutions/chapter_10_sorting_and_searching/problem_10_01_sorted_merge.py
1,385
4.21875
4
""" Chapter 10 - Problem 01 - Sorted Merge Problem Statement: You are given two sorted arrays, A and B, where A has a large enough buffer at the end to hold B. Write a method to merge B into A in sorted order. Solution: First create 3 runner pointers: one to the last useful element of A, one to the last useful element of B, and one to the very end of A. Iterate through the elements of A and B in order from back to front, and copy the greater one to the back of A. Check the address to which the pointers point to ensure that we have not run out of A or B elements before advancing pointers. Time complexity: O(N) Space complexity: O(1) because our lists are mutable in Python, we do not send copies to the function. Thus the function does not cause more memory allocations that scale with the size of the input """ def sorted_merge(A, lastA, B, lastB): mergeA = lastA + lastB + 1 # iterate through arrays A and B from back to front performing the merge operation along the way while lastB >= 0: # note that you don't need to copy the contents of A after running out of elements of B. they are already correct. if A[lastA] > B[lastB] and lastA >= 0: # do not allow copying from A if we have run out of A values A[mergeA] = A[lastA] lastA -= 1 else: A[mergeA] = B[lastB] lastB -= 1 mergeA -= 1
true
151d1bb93b04a18273a24b945cec1138df73e526
conexaomundom/Python
/main1.py
1,766
4.40625
4
''' it is possible to create a variable inside a class called class variable and to instance this variable in this way I can print tht vc variable using instances and you can call diretly the class variable as n line 16 ''' ''' class A: vc = 123 a = A() b = A() print(a.vc,b.vc) print(A.vc) ''' '''It's possible to change the class variable using the proper class like in the line 26 and it's also possible to change the instance that its using the class variable like in line 28 that change in all instances but the changing is diffente like you can see on the dictionary out put called in lines 30, 31 and 32 ''' ''' #A.vc = 321 a.vc = 321 print(A.__dict__) print(a.__dict__) print(b.__dict__)''' ''' access modifers methods and attribuers public - they can be access inside and outside of the class _ protected/Protected - they can be access only inside of the class or by class's children __ private - it is only avaliable inside of the class (__CLASSNAME__ATTRIBUTENAME) ''' class DataBase: # constructior def __init__(self): # an empty dictionary self.data = {} def putting_customers(self, id, name): if 'customers' not in self.data: self.data['customers'] = {id: name} else: self.data['customers'].update({id: name}) def customer_list(self): for id, name in self.data['customers'].items(): print(id,name) def errase_customer(self,id): del self.data['customers'][id] # instantiating a class bd = DataBase() bd.putting_customers(1,'Marina Rodrigues') bd.putting_customers(2,'Julio Garcia') bd.putting_customers(3,'Regina Rodrigues') print(bd.data) bd.errase_customer(2) print(bd.customer_list())
true
79d4cb56ebeb8c9d23bc74780d4c847049aa82e5
TeanaShe/HomeWorksPython
/0409password.py
747
4.15625
4
"""Write a Python program to check the validity of a password (input from users). Validation : At least 1 letter between [a-z] and 1 letter between [A-Z]. At least 1 number between [0-9]. At least 1 character from [$#@]. Minimum length 6 characters. Maximum length 16 characters.""" import re user_password = input("Enter your password: ") res_lc = re.search(r'[a-z]', user_password) res_upc = re.search(r'[A-Z]', user_password) res_digit = re.search(r'\d', user_password) res_symbol = re.search(r'[$#@]', user_password) if 6 <= len(user_password) <= 16 and res_lc and res_upc and res_digit and res_symbol: print('Password validation is ok') else: print('Change your password for more secure!')
true
f52144c44adde962ee7ff7facaab8996d3c510ad
Blueflybird/Python_Study
/Python_Inty/practise_20200405_Tuple.py
570
4.375
4
""" Python3 中有六个标准的数据类型 Nummer(数字) String(字符串) List(列表) Tuple(元组) Sets(集合) Dictionary(字典) """ #List mylist=[1,2,3,4,5] #tuple mytuple=(1,2,3,4,5) # print(type(mylist)) # print(type(mytuple)) # print(len(mylist)) # print(len(mytuple)) # # print(mylist[0]) # print(mytuple[0]) # print(dir(mylist)) #dir查看功能 # print("............................") # print(dir(mytuple)) # mylist.remove(2) # print(mylist) mytuple.remove(2) # tuple不允许更改,但运载速度快,list功能更多
false
f490ff8491ca6f8a5ffd31bdba7f22337a9e3086
Blueflybird/Python_Study
/Python_Inty/practise_20200406_class_init.py
653
4.25
4
# class Students: # name='inty' # age=18 # # def walk(self): # print(self.name,'can walk') # print(self.name,'is',self.age) # # s1=Students() # s1.walk() # # s2=Students() # s2.walk() #-----------------init----------------- class Students: def __init__(self,name,age): self.name=name #Students里面的name等于要初始化的name self.age=age #self指的就是Students def walk(self): print(self.name,'can walk') print(self.name,'is',self.age) #s1=Students(name='inty',age='18') s1=Students('inty','18') #s1=Students('18','inty') s1.walk() s2=Students('James',15) s2.walk()
false
6636b049d84c0015f7b745fca6d90fae8f311d78
BishoySamuel/Mastering-Python
/Assignments/Assignment-001-Lessons-001-010.py
506
4.34375
4
#------------------------ #--Mastering Python #--First Assignment #--For Lessons 1 To 10 #------------------------ NAME = "Bishoy" AGE = 38 COUNTRY = "Egypt" # Vairable type for (Name) => Sting print(type(NAME)) # Vairable type for (Age) => Intiger print(type(AGE)) # Vairable type for (Country) => Sting print(type(COUNTRY)) print("#" * 20) print(f"Hello {NAME}, Your Age is {AGE} & Your Country is {COUNTRY}") print("Hello " + NAME + ", Your Age is " + str(AGE) + " & Your Country is " + COUNTRY)
false
6d04bde3a574f5f0954d9acedce1d1382cc94cc1
ourobouros/DeepLearning-Project2
/sequential.py
1,668
4.34375
4
"""Sequential class used to build neural network models.""" class Sequential (object) : def __init__(self, *layers): """Initializer. Args: layers: Sequence of layers that are in the desired network.""" self.layers = layers def __call__(self, input): """Overrides the call method to call the forward pass of the network. Args: input: Tensor of N * D containing the N samples. Returns: The output of the model. """ return self.forward(input) def forward(self , input): """Performs the forward pass of the network. Args: input: Tensor of N * D containing the N samples. D is the number of features per sample Returns: A N * C tensor, the output of the model for the provided samples. C is the numbers of elements outputed by the neural network. """ x = input for l in self.layers: x = l.forward(x) self.output = x return self.output def backward(self, gradwrtoutput) : """Backpropagates the gradient of the loss throughout the network. Args: gradwrtoutput: Tensor holding the gradient of the loss with respect to the output of the network. """ for l in self.layers[::-1]: gradwrtoutput = l.backward(gradwrtoutput) def parameters(self): """Returns a list containing all the parameter tensors of the model.""" params = [] for layer in self.layers: params += layer.parameters() return params
true
ef31a3b6004f172ef3f5fa56dd9092839ba5f4c6
gregmorrison/Coursework
/2020-CompPhys/Logistic map and Basics of Programming/logistic/logistic0.py
697
4.15625
4
# FUNCTION DEFINITION def logistic_calculate(r,x): #r and x are both passed by value, and cannot be updated within the function return r*x*(1-x) #this returns the new value of x. # END OF FUNCTION DEFINITION # PARAMETERS max_iterations=10000 # how many iterations to do numprint=30 #how many numbers to print to the screen r=1.4 # our choice for r. # INITIALIZATION x=0.01 # initial value for x #iteratively update the value for x. for iter in range(max_iterations): x=logistic_calculate(r,x); # x must be updated with the function by hand, since it was by value only. if max_iterations-iter<numprint: #if we have waited long enough, print to the terminal print(x);
true
f64fc3c3f55bd323230dfc21cf77c30f6117bde1
Muhammad5943/Data-Science
/tool/generator_exp.py
1,119
4.28125
4
# [2 * num for num in range(10)] (general list) # (2 * num for num in range(10)) (generator expression) """ generator = (2 * num for num in range(6)) print(generator) """ # result = (num for num in range(6)) # hasil vertikal (kurang rapi) """ for num in result: print(num) """ # hasil horizontal (rapi) """ listType = list(result) print(listType) """ """ print(next(result)) print(next(result)) print(next(result)) print(next(result)) print(next(result)) print(next(result)) """ # cara tidak efektif untuk membuat iterator dengan value yang besar # [num for num in range(10 ** 10000000)] (meemakan waktu sang sangat lama) # cara yang efektif adalah menggunakan generatot expression """ generator_exp = (num for num in range(10 ** 10000000)) print(generator_exp) """ # memunculkan nilai dari generator expression """ even_nums = (nums for nums in range(10) if nums %2 == 0) print(list(even_nums)) """ def num_sequence(n): """ generate values from 0 to n """ i = 0 while i + 1 < n: yield i i += 1 result = num_sequence(6) print(type(result)) for item in result: print(item)
false
b9b85c6567902a7f4d8c240d3dd1c2d4efbb88e1
saundera0436/CTI-110
/P2HW1_CelsiusConverter_AnthonySaunders (2).py
375
4.40625
4
# Converting Celsius temp to Fahrenheit temp # 9-25 # CTI-110 P2HW1 - Celsius Converter # Anthony Saunders # Get the temp in celsius. celsiusTemp = int(input("Enter the temp in Celsius: ")) # Calculation to convert celsius into fahrenheit. fahrenheitTemp = 9/5 * celsiusTemp + 32 # Display the temp in Fahrenheit. print ("The temp in Fahrenheit is ", fahrenheitTemp)
false
1d29853e21a2393fd3cf3aaf456d72b183d5e878
saundera0436/CTI-110
/P4HW2_CelsiusFahrenheit_AnthonySaunders.py
390
4.4375
4
#Converting Celsius to Fahrenheit #10-17-2018 #CTI-110 - Celsius to Fahrenheit #Anthony Saunders # Ask user to enter a temp in celsius celsiusTemp = float(input("Please enter a temperature in celsius: ")) # Calculate Fahrenheit temperature fahrenheitTemp = (( 9 / 5 ) * celsiusTemp ) + 32 # Display the temperature in fahrenheit print( "The temp in Fahrenheit is: ", fahrenheitTemp )
false
75ddc0be21033e03690fdf19293ec38cb2b2f361
katran009/backend-katas-functions-loops
/main.py
1,294
4.3125
4
#!/usr/bin/env python """Implements math functions without using operators except for '+' and '-' """ __author__ = "katran009" def add(x, y): a = x + y return a result = add(2,4) print(result) def multiply(x,y): # 0 multiplied with anything # gives 0 if(y == 0): return 0 # Add x one by one if(y > 0 ): return (x + multiply(x, y - 1)) # The case where y is negative if(y < 0 ): return -multiply(x, -y) # Driver code print(multiply(6, -8)) def power(a,b): if(b==0): return 1 answer=a increment=a for i in range(1,b): for j in range (1,a): answer+=increment increment=answer return answer # driver code print(power(2,8)) def factorial(x): fac = x for i in range(1, x): fac *= i return fac print(factorial(4)) FibArray = [0,1] def fibonacci(n): if n<0: print("Incorrect input") elif n<=len(FibArray): return FibArray[n-1] else: temp_fib = fibonacci(n-1)+fibonacci(n-2) FibArray.append(temp_fib) return temp_fib # Driver Program print(fibonacci(8)) if __name__ == '__main__': # your code to call functions above pass
true
682514481f3a3f70867600f8eae2ec0d4595742d
SueAli/cs-problems
/LeetCode/Implement Trie (Prefix Tree).py
1,466
4.15625
4
class Trie(object): def __init__(self): """ Initialize your data structure here. """ self.root = {} def insert(self, word): """ Inserts a word into the trie. :type word: str :rtype: void """ ptr = self.root for i in range(len(word)): w = word[i] if w not in ptr : ptr[w] = {} ptr = ptr[w] if i == len(word) -1 : ptr['#'] =None # mark word ending def search(self, word): """ Returns if the word is in the trie. :type word: str :rtype: bool """ ptr = self.root i = 0 while i < len(word) and word[i] in ptr: ptr = ptr [word[i]] i += 1 if i == len(word) and '#' in ptr: return True return False def startsWith(self, prefix): """ Returns if there is any word in the trie that starts with the given prefix. :type prefix: str :rtype: bool """ ptr = self.root i = 0 while i < len(prefix) and prefix[i] in ptr: ptr = ptr [prefix[i]] i += 1 if i == len(prefix) : return True return False # Your Trie object will be instantiated and called as such: # obj = Trie() # obj.insert(word) # param_2 = obj.search(word) # param_3 = obj.startsWith(prefix)
true
736a3cb2d3cddf5931cc1f777733c4ef8550eed9
ZSL-1024/Python-Crash-Course
/chapter_08_functions/user_albums.py
677
4.15625
4
# 8-8 def make_album(artist, title, tracks=''): """Build a dictionary containing information about an album.""" album_dict = { 'artist': artist.title(), 'title': title.title(), } if tracks: album_dict['tracks'] = tracks return album_dict title_prompt = "\nWhat album are you thinking of?" artist_prompt = "who's the artist?" # Let the user know how to quit. print("(enter 'q' at any time to quit)") while True: album_title = input(title_prompt) if title == 'q': break artist_name = input(artist_prompt) if artist == 'q': break album = make_album(artist_name, album_title) print(album) print("\nThanks for responding!")
true