blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
is_english
bool
a3b988261743a290910d8c3110733d393ef01512
wolverinez/T_Mud
/dice.py
1,099
4.15625
4
"""this module contains functions for rolling dice from a cointoss to a one hundred sided dice the funtions are named with the letter 'd' and then a number forinstance the function to simulate a d20 is simply named d20(pluss=0) where the pluss argument makes it possible to modify the roll """ import random as R def d2(pluss=0): """Simulates a coin toss""" return R.randint(1, 2) + pluss def d3(pluss=0): """Simulates a threesided dice""" return R.randint(1, 3) + pluss def d4(pluss=0): """Simulates a four sided dice""" return R.randint(1, 4) + pluss def d6(pluss=0): """Simulates a six sided dice""" return R.randint(1, 6) + pluss def d8(pluss=0): """Simulates a eight sided dice""" return R.randint(1, 8) + pluss def d10(pluss=0): """Simulates a ten sided dice""" return R.randint(1, 10) + pluss def d12(pluss=0): """Simulates a twelve sided dice""" return R.randint(1, 12) + pluss def d20(pluss=0): """Simulates a twenty sided dice""" return R.randint(1, 20) + pluss def d100(pluss=0): """Simulates a hundred sided dice""" return R.randint(1, 100) + pluss
true
4125db8aaa60416d0ccd30d7c23fea23b20c4246
divir94/Python-Projects
/Algorithms Practice/Reducible Word.py
1,572
4.15625
4
# http://www.greenteapress.com/thinkpython/thinkpython.pdf # Exercise 12.6 def make_word_dict(): d = dict() fin = open('../Data/English Wordlist.txt') for line in fin: word = line.strip().lower() d[word] = word return d """memo is a dictionary that maps from each word that is known to be reducible to a list of its reducible children. It starts with the empty string.""" memo = dict() memo[''] = '' def children(word, word_dict): res = [] for i in range(len(word)): child = word[:i] + word[i+1:] if child in word_dict: res.append(child) return res def is_reducible(word, word_list): if word in memo: return memo[word] res = [] for child in children(word, word_dict): t = is_reducible(child, word_dict) if t != []: res.append(child) memo[word] = res return res def all_reducibles(word_list): words = [] for word in word_list: t = is_reducible(word, word_dict) if t != []: words.append((len(word), word)) return words def print_long_reducibles(word_list): words = all_reducibles(word_list) words.sort(reverse = True) for length, word in words[:5]: print length, print_order(word) print '\n' def print_order(word): if len(word) == 0: return print word, child = is_reducible(word, word_dict) print_order(child[0]) word_dict = make_word_dict() print_long_reducibles(word_dict) #print_order('ambulance', word_dict)
false
2b953aeab24e60b0a44915565b05b7cb3f1a4dd6
kosskiev/University-of-Michigan
/turtle_and_color_figure.py
873
4.46875
4
#Write a program that asks the user for the number of sides, the length of the side, the color, and the fill color of a regular polygon. #The program should draw the polygon and then fill it in. import turtle number_side = int(input('How many sides would you like?(Сколько сторон у вашей фигуры?) ')) angle = 360 / number_side length_side = int(input('How long length side?(Какая будет длина стороны?) ')) color = input('Which color line do you want?(Каким цветом рисовать линии?) ') fill_color = input('What color to sketch your figure?(Каким цветом закрасить вашу фигуру?) ') wm = turtle.Screen() turtle.color(color, fill_color) turtle.begin_fill() for i in range(number_side): turtle.fd(length_side) turtle.lt(angle) turtle.end_fill() turtle.exitonclick()
true
429a1d0562b5385edfa9a443c0732272e82bef4d
hutor04/UiO
/in1000/oblig_3/ordbok.py
1,197
4.34375
4
# The program initiates a dictionary with product names as keys and their prices as values. It then prints out the list # Then the program asks the user to input a new product and its price two times. # It ads new products to the dictionary and then prints a new dictionary. # We create a dictionary that holds product names as keys and their prices as values. products = {'melk': 14.90, 'brød': 24.90, 'yoghurt': 12.90, 'pizza': 39.90} # We print the dictionary print(products) # We enter the for-loop with two repetitions. for i in range(2): # We ask for a product name product = input('Please, provide the name of a product: ') # We are going to handle the exception that rises if the user inputs not a number on the next step try: # We ask the user to enter the price price = float(input('Provide the price of the product (digits , please): ')) # We then ad a new product to the dictionary products[product] = price except ValueError: # We print this if the user enters price with alphabetic characters. And we don't add this value to the list. print('We expected a digit here.') # We print the list again print(products)
true
215b78a3a4ae410b55ea532938f4d337b338ee1f
hutor04/UiO
/in1000/oblig_1/hei_student.py
361
4.21875
4
# The following program prints salutation, asks the user to input its name. # Then it prints out salutation and the name that was provided by the # user. # Prints to screen the first salutation print('Hei Student!') # Asks to input the name of the user navn = input('Scriv navnet ditt nå: ') # Prints to screen new salutation with the name print('Hei', navn)
true
e4279841462864909d41865df0c27e91b156831d
CharlieHuang95/Algorithms
/Sorting/quick_sort.py
1,188
4.25
4
# Quicksort works by randomly selecting an element to be its pivot, and shifting # smaller elements to its left side, and larger elements to its right side. # At the end of all the shifting, the pivot should ultimately be in the correct # location. import random def quick_sort_helper(array, left, right): if left >= right: return pivot = array[left] l = left + 1 r = right while l < r: while l < r and array[l] < pivot: l += 1 while l < r and array[r] > pivot: r -= 1 if l < r: array[l], array[r] = array[r], array[l] if array[l] <= pivot: array[left], array[l] = array[l], array[left] boundary = l else: array[left], array[l-1] = array[l-1], array[left] boundary = l - 1 quick_sort_helper(array, left, boundary - 1) quick_sort_helper(array, boundary + 1, right) def quick_sort(array): quick_sort_helper(array, 0, len(array) - 1) if __name__=="__main__": for _ in xrange(10): array = [] for _ in xrange(10): array.append(random.randrange(0, 100)) quick_sort(array) assert sorted(array) == array
true
fd2a94cec38175d7ff35a93814bc5815df69dcd0
MeenaRepo/augustH2K
/DictionaryTest.py
1,285
4.1875
4
sampleDictionary = { "Warm":"Red", "Cold":"Baige", "Nuetral":"Grey", "Common":"Black", } print(sampleDictionary) print(sampleDictionary["Cold"]) print(sampleDictionary.get("Warm")) # Add - replaces the old value sampleDictionary["Warm"] = "Blue" print(sampleDictionary) # Membership if "Nuetral" in sampleDictionary: print(" Nuetral color is : ", sampleDictionary.get("Nuetral")) if "Black" in sampleDictionary.values(): print(" Black exists in the Dictionary : ", sampleDictionary.get("Common")) # pop sampleDictionary.pop("Common") print(sampleDictionary) # popitem - Remove the last item in the list sampleDictionary.popitem() print(sampleDictionary) #iterate with Keys for eachkey in sampleDictionary: print(eachkey, sampleDictionary.get(eachkey)) #iterate with Key-Value pairs for eachkey, eachvalue in sampleDictionary.items(): print(eachkey, eachvalue) # iterate with only values for eachvalue in sampleDictionary.values(): print(eachvalue) # you can even add a list as one of the key value pair in dictionary sampleDictionary["List_item"] = ["apple", "pineapple", "grapes","lotus"] sampleDictionary["Cold"]="Yellow" sampleDictionary["Common"] = "White" print(sampleDictionary)
true
10cd5c0f8f3bf6fae6e03e1e740a115f505a1aba
duthaho/python-design-patterns
/creational/builder.py
2,288
4.15625
4
from abc import abstractmethod from typing import Optional class Car: def __init__(self): self.seat = 0 self.engine = "" self.trip_computer = False self.gps = False def info(self): print(f"Car: {self.seat} - {self.engine} - {self.trip_computer} - {self.gps}") class Builder: def __init__(self): self._car = None self.reset() @abstractmethod def reset(self) -> "Builder": pass @abstractmethod def set_seat(self, seat: int) -> "Builder": pass @abstractmethod def set_engine(self, engine: str) -> "Builder": pass @abstractmethod def set_trip_computer(self) -> "Builder": pass @abstractmethod def set_gps(self) -> "Builder": pass @abstractmethod def get(self) -> Car: pass class CarBuilder(Builder): def reset(self) -> "Builder": self._car = Car() return self def set_seat(self, seat: int) -> "Builder": self._car.seat = seat return self def set_engine(self, engine: str) -> "Builder": self._car.engine = engine return self def set_trip_computer(self) -> "Builder": self._car.trip_computer = True return self def set_gps(self) -> "Builder": self._car.gps = True return self def get(self) -> Car: return self._car class Director: def __init__(self): self._builder: Optional[Builder] = None @property def builder(self) -> Builder: return self._builder @builder.setter def builder(self, builder: Builder): self._builder = builder def build_sport_car(self) -> Car: self._builder.reset().set_seat(2).set_engine("sport").set_trip_computer().set_gps() return self._builder.get() def build_suv(self) -> Car: self._builder.reset().set_seat(4).set_gps() return self._builder.get() class Application: def make_car(self): director = Director() car_builder = CarBuilder() director.builder = car_builder car = director.build_suv() car.info() car = director.build_sport_car() car.info() if __name__ == "__main__": app = Application() app.make_car()
true
e3eacc2e7aef6a075a6b3c6a9810739b1ff6e15e
VandalTryHard/Test-Task-for-work
/Consult_Test_task/task3.py
559
4.125
4
"""3. Создать процедуру обратного отражения порядка строк (сортировки по номеру строки в обратном порядке. Например номер строки был 1 ae1234 2 bc5678 стал 10000 ae1234 9999 bc5678""" import csv with open('file_task3.csv', 'r') as textfile: for row in reversed(list(csv.reader(textfile))): #reversed возвращает в обратной последовательности весь документ print (', '.join(row))
false
259d53c7b2581e146cc8b1c5c9d75da5f04ee845
joelbd/CSC110
/convertmiles.py
244
4.3125
4
# File: convertmiles.py # This program converts distance in miles to distance in kilometers # Day def main(): miles = eval(input("Enter the distance in miles:")) kilometers = miles * 1.60934 print("The distance is:",kilometers,"km") main()
true
a80ddf31a4e28b238ebd83d30c80ef432bd25a16
Raktacharitra/TrueCaller-search
/truecaller.py
1,022
4.125
4
from sys import argv choice = input("Tell us if you want to 'search' a particular contact or 'add' a contact (s / a): ") if choice.lower() == "s" or choice.lower() == "search": with open(argv[1], "r") as phone_book: search_type = input("search by name or number: ") try: a = int(search_type) for line in phone_book: bucket = line.split(":") if int(bucket[1]) == a: print(bucket[0]) except ValueError: for line in phone_book: bucket = line.split(":") if bucket[0].lower() == search_type.lower(): print(bucket[1]) elif choice.lower() == "a" or choice.lower() == "add": with open(argv[1], "a") as phone_book: name = input("enter person's name: ") number = int(input("enter person's number: ")) phone_book.writelines(f"\n{name}:{number}") else: print("You need to type 'search' or 'add' to perform the desired operation!" )
true
b25989f7358daf4ac3813f19a9aaf9f065fc0c44
rogeriosilva-ifpi/teaching-tds-course
/programacao_estruturada/20192_186/Bimestral1_186_20192/ANTONIO_FRANCISCO_OLIVEIRA___EDRAS/negativo_para.py
218
4.21875
4
numero = int(input('Digite um numero')) contador1 = 1 while (numero > 0): contador = numero contador1 = contador1 + 1 numero = int(input('Digite o próximo numero')) print(contador, contator/contador1)
false
edd06834320697ac884f503a1dc4c756443aa72b
rogeriosilva-ifpi/teaching-tds-course
/programacao_estruturada/20192_186/Bimestral1_186_20192/FRANCISCO ROBERTO E REGINALDO JOSE - TURMA 186N/angulo.py
412
4.125
4
print('Qual o quadrante do angulo?') # entrada angulo = float(input('Digite o valor do angulo entre 0° e 360°: ')) # processamento if angulo < 90: print('este angulo percente ao 1° quadrante') elif 90 < angulo < 180: print('este angulo percente ao 2° quadrante') elif 180 < angulo < 270: print('este angulo percente ao 3° quadrante') else: print('este angulo percente ao 4° quadrante')
false
1f527d83890651daeebb1874a70225fa013d07e4
louisbranch/hello-py
/ProblemSet3/ps3_newton.py
1,757
4.21875
4
# 6.00x Problem Set 3 # # Successive Approximation: Newton's Method # # Problem 1: Polynomials def evaluatePoly(poly, x): ''' Computes the value of a polynomial function at given value x. Returns that value as a float. poly: list of numbers, length > 0 x: number returns: float ''' s = 0.0 for i in range(len(poly)): s += poly[i] * x ** i return s # Problem 2: Derivatives def computeDeriv(poly): ''' Computes and returns the derivative of a polynomial function as a list of floats. If the derivative is 0, returns [0.0]. poly: list of numbers, length &gt; 0 returns: list of numbers (floats) ''' list = [] if len(poly) <= 1: list = [0.0] for i in range(len(poly)): if i == 0: continue if abs(poly[i]) == 0: list.append(0.0) else: list.append(poly[i] * i) return list counter = 0 # Problem 3: Newton's Method def computeRoot(poly, x_0, epsilon): ''' Uses Newton's method to find and return a root of a polynomial function. Returns a list containing the root and the number of iterations required to get to the root. poly: list of numbers, length > 1. Represents a polynomial function containing at least one real root. The derivative of this polynomial function at x_0 is not 0. x_0: float epsilon: float > 0 returns: list [float, int] ''' # FILL IN YOUR CODE HERE... global counter rootX = evaluatePoly(poly, x_0) if abs(rootX) > epsilon: x_1 = x_0 - (rootX / evaluatePoly(computeDeriv(poly), x_0)) counter += 1 return computeRoot(poly, x_1, epsilon) else: old = counter + 0 counter = 0 return [x_0, old]
true
ae069876ea6409ad4a9ff29f1fb23a915d707e01
priyankagoma/learningpython
/src/python_scripts/print_examples/printexamples.py
290
4.15625
4
#below are few examples that how we can print numbers. print(2 + 8) print(3 * 5) print(6 - 3) #Example of a string. print("The end", "it should be nice", "we will able to make it") #Exapme of integers. print(1, 2, 3, 4, 5) #Example of words. print("one two three four five cat dog")
true
df53ec293bedda6a6954334daca394536dc0e02b
Junhee-Kim1/RandomNumber
/RandomNumberGuesser.py
442
4.15625
4
import random print("number Guessing Game!") number=random.randint(1,9) chance=0 print("guess number") while chance<5: guess=int(input("enter your guess!: ")) if guess == number: print("you win!") break elif guess<number: print("your number is too low") else: print("your number is too High") chance=chance+1 if not chance<5: print("you lose the number was" , number)
true
2c4da32e1420daae3f9401ca78d4be75b6af5f9d
prathmesh2606/DSA_LU
/a1q1.py
344
4.4375
4
# Assignment 1 - Q1 # Write a python program that takes two numbers as the input such as X and Y and print the result # of X^Y(X to the power of Y). # Taking input x,y = [int(i) for i in input("Enter base value and then power value by giving space between them (eg: 2 3 ans: 8): ").split()] print(f"{x} to the power of {y} is: {x**y}")
true
b1b7f0de711f5d40447d83553dc3e8c4bbe3209f
charliettaylor/CSA231
/Projects/4/project4.py
2,286
4.28125
4
# Turtle Project by Charlie Taylor from turtle import * import random as rand SCALE = "Enter the size of the spiral (recommend 1-10): " LOW = "Enter low bound of shake (rec. negative or 0): " HIGH = "Enter high bound of shake (rec. positive or 0): " def draw_c(t) -> None: ''' draws letter C ''' t.down() for i in range(2): t.fd(100) t.left(90) t.fd(100) t.up() def draw_t(t) -> None: ''' draws letter T ''' t.down() t.fd(100) t.left(90) t.fd(75) t.back(150) t.up() def initials(t: Turtle) -> None: ''' draws initials from any starting position ''' t.setheading(180) draw_c(t) t.fd(100) t.left(90) draw_t(t) def shake(low, high) -> int: ''' returns an int to modify the degrees in spiral should be a negative number for low and positive for high to make effect look good ''' return rand.randint(low, high) def spiral(t, degrees, n, scale, low=0, high=0) -> None: ''' Draws a spiral based on degrees and number of iterations entered t : Turtle object degrees : should be 1 less than interior angle of regular polygon n : number of iterations Keyword arguments low : lower bound of shake that varies degrees high : upper bound of shake that varies degrees ''' size = 2 t.down() for i in range(n): t.fd(size) t.left(degrees + shake(low, high)) size += scale t.up() def main(): print("Welcome to the spiral maker by Charlie Taylor") done = False while not done: try: scale = float(input(SCALE)) low = int(input(LOW)) high = int(input(HIGH)) done = True except ValueError: print("Enter a positive non zero integer") wn = Screen() wn.bgcolor("black") wn.title("Turtle") t = Turtle() t.speed(0) t.setposition(0, 0) t.pencolor("green") spiral(t, 119, 300, scale, low, high) t.pencolor("salmon") t.setposition(0, 0) spiral(t, 89, 300, scale, low, high) t.pencolor("orange") t.setposition(0, 0) spiral(t, 71, 300, scale, low, high) t.pencolor('white') t.setposition(0, 0) initials(t) if __name__ == "__main__": main()
true
e307eb42c7b796d5e927e7f03720a4b3abfca74b
NankuF/PythonKnowledge
/classes/1.py
596
4.125
4
# Определите класс car с двумя атрибутами: color и speed. # Затем создайте экземпляр и верните speed """ class Car: color = 'red' speed = 20 car_ex = Car() print(car_ex.speed) """ class Car: def __init__(self, color, speed): self.color = color self.speed = speed def __str__(self): return self.color def run(self): print('RUUUN!') car_ex = Car('Blue', speed=25) print(car_ex.speed) print(car_ex.__dir__()) class Mycar(Car): pass mcar = Mycar('red', 200) mcar.run()
false
101cedb9b67c9004b1a4a5af955197ed7b71a4b9
yingl910/MongoDB
/Basics/mdb_update.py
1,899
4.25
4
'''These are examples of MongoDB example codes of save and update, two methods for updating''' '''update method one: save''' # a method on collection objects # find_one just returns the first document it finds city = db.cities.find_one({'name':"munchen",'country':'Germany'}) city['isoCountryCode'] = 'DEU' db.cities.save(city) # a method on collection objcects #if the object we pass already have a _id and a document with that id already in the collection ->replacement #if there is no document with _id or the object we're passing does not have _id -> create '''update method two: update''' #update : a method on collection objects; a query document as 1st parameter #2nd parameter: an update document: specify what operations mongodb should perform on the document matching this query #by default, update operates on just one document(first found) #if the field is not exsit -> create; exist -> update city = db.cities.update({'name':"munchen",'country':'Germany'}, {'$set':{ 'isoCountryCode':'DEU' }}) '''inverse of $set: $unset''' # if the field is not exsit -> no effect; exist -> remove city = db.cities.update({'name':"munchen",'country':'Germany'}, {'$unset':{ 'isoCountryCode':'' }}) '''PAY ATTENTION: IT'S REALLY EASY TO FORGET $SET AND $UNSET OPERATOR''' # what happens here is the document matching this query will be replaced so that it contains the _id and #'iscountrycode' field ONLY city = db.cities.update({'name':"munchen",'country':'Germany'}, {'isoCountryCode':'DEU'}) '''update multiple documents at once''' db.cities.update({'country': 'Germany'}, {'$set': { 'isoCountryCode': "DEU" } }, multi = True)
true
cd890912e0574154ac18385ac92f43fdd68f430d
PrabhudevMishra/PRO-97
/numberGuessingGame.py
497
4.15625
4
import random number = random.randint(0,10) chances = 0 while chances < 5 : guess = int(input("Enter your guess")) chances = chances + 1 if guess < number: print('Your guess is too low') if guess > number: print('Your guess is too high') if guess == number: break if guess == number: print('CONGRATULATIONS!! You guessed the number correct.') else: print("You lost!! Please try again.")
true
c43c7f51aff65b851a591bf7d00c96a0d8a160be
shivesh01/Python-Basics
/Project&problems/Example_30.py
425
4.28125
4
# Shuffle Deck of cards import random # In the program, we used the product() function in itertools module to create a deck of cards. This function performs the Cartesian product of the two sequences. from itertools import product deck = list(product(range(1, 14), ["Spade", "Heart", "Club", "Diamond"])) random.shuffle(deck) print(" Your picked card is: ") for i in range(5): print(deck[i][0], "of", deck[i][1])
true
65e62f4761054c0cf0ac8911e1715c5537608c7c
shivesh01/Python-Basics
/Project&problems/Example_10.py
233
4.375
4
# check number +,- or 0 num = float(input("Enter number")) if num == 0: print("your entered number is zero") elif num > 0: print("You have entered a positive number") else: print("You have entered a negative number")
true
918af8577d167cb37357196e2509ea35569e4682
shivesh01/Python-Basics
/Datatype/datatype_explict_3.py
327
4.21875
4
num_int = 123 num_str = "456" print("data type of num_int",type(num_int)) print("data type of num_str",type(num_str)) num_str = int(num_str) print("data type of num integer after typecasting:",type(num_str)) num_sum= num_int + num_str print("sum of num_int and num_str ",num_sum) print("data type of num_sum",type(num_sum))
false
dd701404bbf09b357bdd5faec5512de7093ca871
lmjim/year1
/cs210/p61_testfunc_key.py
1,584
4.21875
4
""" CIS210 Project 6-1 Fall 2017 Author: [Solution] Credits: N/A Implement a function to test the string reverse functions from project 5 (iterative and recursive). Practice: -- user-defined test functions -- functions as parameters """ import p52_stringreverse_key as p5 def test_reverse(f): '''(function) -> None Test function f (one of the string reverse functions). Report results for each test. > test_reverse(p5.strReverseR) <report results> > test_reverse(p5.strReverseI) <report results> ''' test_cases = ( ('', ''), ('a', 'b'), ('xyz', 'zyx'), ('testing123', '321gnitset'), ('hello, world', 'dlrow ,olleh') ) for test in test_cases: # parse the arguments arg1 = test[0] expected_result = test[1] # report test case print('Checking {}({}) ...'.format( f.__name__, str(arg1)), end='') # execute the test actual_result = f(arg1) # report result if (actual_result == expected_result): print('its value {} is correct!'.format(actual_result)) else: print('Error: has wrong value {}, expected {}.'.format(actual_result, expected_result)) return None def main(): '''calls string reverse test func 2x''' test_reverse(p5.strReverseR) test_reverse(p5.strReverseI) return None if __name__ == '__main__': #print(doctest.testmod()) main()
true
826fb885f233ea03edffde38cb2342bda0236dea
dudulydesign/python_web_pratice
/webserver/py_though/bubble sort.py
747
4.15625
4
#Bubble Sort sampleList = [6,5,4,3,2,1] def bubbleSort(sourceBubbleSortList): #how long the list listLength = len(sourceBubbleSortList) i = 0 # the i here to count how many value not in while i < listLength-1: j = listLength - 1 # here to compare two value while j > i: print(" sourceBubbleSortList = " + str(sourceBubbleSortList)) #compare two value, replace it if here are diffrent big, and continute to compare until finish all of it if sourceBubbleSortList[j] < sourceBubbleSortList[j-1]: tempNum = sourceBubbleSortList[j] sourceBubbleSortList[j] = sourceBubbleSortList[j-1] sourceBubbleSortList[j-1] = tempNum j = j - 1 i = i + 1 return sourceBubbleSortList
true
62f8410ff45e2352f7ac48cf8327c35a62371895
geraldfan/Automate-The-Boring-Stuff
/Chapter_9_Organizing_Files/selectiveCopy.py
699
4.25
4
#! python3 # selectiveCopy.py - Walks through a folder tree, then searches and copies for files with a particular extension (i.e. .jpg) import shutil, os folder = input('Enter the absolute filepath of' ' the directory you wish to copy from: ') extension = input("Enter the extension you'd like to copy: ") destination = input("Enter destination folder's absolute filepath: ") for foldername, subfolders, filenames in os.walk(folder): for filename in filenames: if filename.endswith(extension): shutil.copy(os.path.join(foldername, filename), destination) print("Selective copy of %s extension from %s to %s is complete" %(extension, folder, destination))
true
8b0e1fb5a628c393ee871205478499cf48cf5306
rodrigosantosti01/LingProg
/Exercicio3/atv11.py
1,054
4.1875
4
# 11. Faça um programa que faça 5 perguntas para uma pessoa sobre um crime. As perguntas são: # "Telefonou para a vítima?" # "Esteve no local do crime?" # "Mora perto da vítima?" # "Devia para a vítima?" # "Já trabalhou com a vítima?" # O programa deve no final emitir uma classificação sobre a participação da pessoa # no crime. Se a pessoa responder positivamente a 2 questões ela deve ser classificada como "Suspeita", # entre 3 e 4 como "Cúmplice" e 5 como "Assassino". Caso contrário, ele será classificado como "Inocente". score = 0 respostas = [ input("Telefonou para a vítima? (s/n): "), input("Esteve no local do crime? (s/n): "), input("Mora perto da vítima? (s/n): "), input("Devia para a vítima? (s/n): "), input("Já trabalhou com a vítima? (s/n): ") ] for resposta in respostas: if resposta == "s": score += 1 if score == 2: print("Suspeita") elif score >= 3 and score <= 4: print("Cúmplice") elif score == 5: print("Assassino") else: print("Inocente")
false
860f2ff85024e2668c3268b1f98012f86fbc8863
rodrigosantosti01/LingProg
/Exercicio4/atv01.py
389
4.1875
4
# 1 Menor de dois pares: Escreva uma função que retorne o menor de dois números # dados se ambos os números forem pares, mas retorna o maior se um dos dois for # ímpar. Exemplo: # menor_de_dois_pares(2,4) --> 2 # menor_de_dois_pares (2,5) --> 5 def f(a,b): if a%2==0 and b%2==0: if a<b: return a return b else: if a<b: return b return b print(f(2,4)) print(f(2,5))
false
578494d75a99a79091946b96a93a13fc485c6c50
Szkeller/TDD_lab
/FizzBuzz.py
867
4.125
4
class FizzBuzz: ''' This is for TDD sample Author: Keller Zhang create date: 04/27 description: FizzBuzz Quiz When given number just can be divided by 3, then return 'Fizz'; When given number just can be divided by 5, then return 'Buzz'; When given number just can be divided by 3 and 5, then return 'FizzBuzz'; otherwise return given number itself. ''' def fizz_buzz(self, number): result = '' if number % 15 == 0: result = 'FizzBuzz' elif number % 5 == 0: result = 'Buzz' elif number % 3 == 0: result = 'Fizz' else: result = str(number) return result if __name__ == '__main__': fizzbuzz = FizzBuzz() for i in range (1,101): print(fizzbuzz.fizz_buzz(i))
true
383c7b66d2e6c025f09270cf1e547d64556954aa
Shilinana/LearnPythonTheHardWayPractices
/ex18.py
633
4.3125
4
""" @Author:ShiLiNa @Brief:The exercise18 for Learn python the hard way @CreatedTime:28/7/2016 """ # this one is like your scripts with argv def print_two(*args): arg1, arg2 = args print "arg1:%r, arg2:%r" % (arg1, arg2) # ok, that *arg is actually pointless, we can just do this def print_two_again(arg1, arg2): print "arg1:%r, arg2:%r" % (arg1, arg2) # this just takes one argument def print_one(arg1): print "arg1:%r" % arg1 # this one takes no arguments def print_none(): print "I got nothin'." print print_two("Zed", "Shaw") print print_two_again("Zed", "Shaw") print_one("First!") print_none()
true
89768748cf4abc99b56f383e025fe37a851579f8
justinelai/Sorting
/src/iterative_sorting/iterative_sorting.py
2,598
4.5625
5
def insertion_sort(list): for i in range(1, len(list)): # copy item at that index into a temp variable temp = list[i] # iterate to the left until reaching correct . # shift items to the right j = i while j > 0 and temp < list[j-1]: list[j] = list[j-1] j -= 1 list[j] = temp return list # TO-DO: Complete the selection_sort() function below # How many loops will be needed to complete this algorithm? # How do we know how many items should be shifted over to the right? # What do we need to do so that we don't overwrite the value we are `inserting`? # What, if anything needs to be returned? """ For every index in the collection from 0 to length-2: Compare the element at the current index, i, with everything on its right to identify the position of the smallest element Swap the element at i with the smallest element i++ Algorithm Start with current index = 0 For all indices EXCEPT the last index: a. Loop through elements on right-hand-side of current index and find the smallest element b. Swap the element at current index with the smallest element found in above loop """ """ test = [ 4, 3, 1, 2, 5, 6 ] def selection_sort( arr ): # loop through n-1 elements for i in range(0, len(arr) - 1): cur_index = i smallest_index = cur_index for j in range(i + 1, len(arr)): if arr[j] < arr[smallest_index]: smallest_index = j arr[smallest_index], arr[cur_index] = arr[cur_index], arr[smallest_index] print(arr) selection_sort(test) """ # TO-DO: implement the Bubble Sort function below # If `elements` is a collection, remember it will be passed by reference, not value # We only need to loop through `elements` until we make a pass that leads to 0 swaps. How do we keep track of whether or not any swaps have occurred? # Do we always need to loop through all elements? # Depending on how our loop was set up, which neighbors should be compared? # Can we do swaps in Python without a `temp` variable? # What, if anything needs to be returned? test1 = [ 4, 3, 1, 2, 5, 6 ] def bubble_sort(arr): swapped = True while swapped: swapped = False for i in range(0, len(arr)-1): if(arr[i+1] < arr[i]): arr[i+1], arr[i] = arr[i], arr[i+1] swapped = True print(arr) return arr bubble_sort(test1) """ # STRETCH: implement the Count Sort function below def count_sort( arr, maximum=-1 ): return arr """
true
2851a656bd9f2bdc1b7877c587dd09a17e0fe219
Tech-Amol5278/Python_Basics
/c5 - list/c5_more_methods_to_add_data.py
626
4.15625
4
# count # sort method # sorted function # reverse # clear # copy # Count: Counts the string available in list fruits = ['apple','orange','banana','grapes','apple','apple','guava'] print(fruits.count('apple')) # Sort: sort the list contains in alphabetical/numeric order fruits.sort() print(fruits) numbers = [3,51,8,4,67,12] numbers.sort() print(numbers) # Sorted function: sort the return from list instead sorting the actual list num = [10,2,5,7,4] print(sorted(num)) print(num) # Clear: clears the list num1 = [5,6,2,19,25] num1.clear() print(num1) # Copy: Copying of list num_copy=num.copy() print(num_copy)
true
43bce6c540aa4ad249c33ab9650e4e1b739a73cb
Tech-Amol5278/Python_Basics
/c5 - list/c5e4.py
522
4.4375
4
# define a function which returns a lists inside list, inner lists are odd and even numbers # for example # input : [1,2,3,4,5,6,7,8] # returns : [[1,3,5,7],[2,4,6,8]] ####### Sol ############################################### num1 = [1,2,3,4,5,6,7,8] def separate_odd_even(list1): sep_list = [] odd = [] even = [] for i in list1: if i%2==0 : even.append(i) else: odd.append(i) sep_list = [odd,even] return(sep_list) print(separate_odd_even(num1))
true
f383537b4da9f340610aaa7e4ee2e1fbf5b73147
Tech-Amol5278/Python_Basics
/c2 - strings methods/c2e2.py
218
4.21875
4
# ask username and print back username in reverse order # note: try to maje your program in 2 lines using string formatting #### Sol ##########################3 u_name = input("Enter your name: ") print(u_name[::-1])
true
4e09df38fd41bfaa63801dffa2f1a822878deab4
Tech-Amol5278/Python_Basics
/c17 - debugging and exceptions/else and finally.py
675
4.28125
4
# Else and fianlly while True: ## Loop to accept input til true comes try: age = int(input("Enter a number: ")) except ValueError: # valueerror : optional only if we know the error which can come print("Please enter age only in integer ") except: # when error is unpredictable print("Unexpected error") else: # executes when there is no exception print(f"You entered {age}") break finally: # this executes in both the cases, errors and no errors print("finally blocks......") if age > 18: print("Welcome to play game") else: print("You cant play this game")
true
e3a71a4f1447e3fc0e6bf03654df9c63e1af56f2
Tech-Amol5278/Python_Basics
/c16 - oops/property and setter decorator.py
2,526
4.21875
4
# property and setter decorator # the below code from last slide it has below problems # 1. this accepts the negative amount for price # sol: write a validation not to accept negative numbers # using getter(),setter() # 2. After changing the price , complete specification shows the old price. # sol: write those specification in seprate function # OR using property decorator # class Phone: # def __init__(self,brand,model_name,price): # self.brand = brand # self.model = model_name # self._price = price # self.complete_spefic = f" {self.brand} {self.model_name} and price {_price}" # def make_a_call(self,phone_num): # print(f"Calling {phone_num} .....") # def full_name(self): # print(f"{self.brand} {self.model}") # phone1 = Phone('nokia','1100',5600) # print(phone1._price) ################################################################################################### class Phone: def __init__(self,brand,model_name,price): self.brand = brand self.model = model_name if price >= 0: self._price = price else: self._price = 0 ### or use below line # self._price = max(price,0) ## this checks for the maximum number between given number and 0 and returns the max number either given number or 0 # self.complete_spefic = f" {self.brand} {self.model} and price {self._price}" def make_a_call(self,phone_num): print(f"Calling {phone_num} .....") def full_name(self): print(f"{self.brand} {self.model}") def specs(self): return f" {self.brand} {self.model} and price {self._price}" # @Property- using this decorator we can use this function as method and we can call this method as attribute @property def property_spec(self): return f" {self.brand} {self.model} and price {self._price}" # getter(), setter() for price validation @property def price(self): return self._price @price.setter def price(self,new_price): self._price = max(new_price,0) phone1 = Phone('nokia','1100',-5600) phone1._price = 2200 print(phone1._price) print(phone1.specs()) print(phone1.property_spec) ## see here we are not given parenthesis() ### to set the new price from getter and setter phone1.price = 3400 print(phone1.price) # used price instead of _price print(phone1.property_spec) ## see here we are not given parenthesis()
true
1990af0b8f76c76eaa907f985d091f44a32cad62
Tech-Amol5278/Python_Basics
/c5 - list/c5_list_intro.py
649
4.5
4
# Data Structures # List # List is ordered collection of items # We can store anything in lits like int, float, string numbers = [1,2,3,4] print(numbers) ## to print 2 from list print(numbers[1]) ## to access only and 1 and 2 print(numbers[:2]) ## to reverse the elements in list print(numbers[::-1]) ## to access only last element i.e 4 print(numbers[-1]) words = ["word1",'word2','word3'] print(words) mixed = [1,2,3,4,"five","six",None] print(mixed) ## to update the elements in list such as 2 > "two" mixed[1] = "two" print(mixed) mixed[1:] = "two" ## considered new list t , w, o print(mixed) mixed[1:] = ["three","four"] print(mixed)
true
19eb4162a092c37319cccc4e1743978ac34653ed
ITlearning/ROKA_Python
/2021_03/03_14/CH04_Problem/029_If_string02.py
519
4.125
4
# 이 문제를 해결하려면 다음과 같이 코딩한다. # if 조건문과 여러 줄 문자열(3) number = int(input("정수 입력 > ")) if number % 2 == 0 : print("""입력한 문자열은 {}입니다.\n{}는 짝수입니다.""".format(number,number)) else : print("""입력한 문자열은 {}입니다.\n{}는 홀수입니다.""".format(number,number)) # 이렇게 하면 코드가 다행히 잘 보이긴 하는데, 길게 적음으로 인해 다소 복잡해보일수가 있다.
false
240bf5eb01603c73b773ae7bda168bc2407e28a5
0gravity000/IntroducingPython
/06/0609.py
1,114
4.3125
4
# 6.9 非公開属性のための名前のマングリング # Pythonは、クラス定義の外からが見えないようにすべき属性の命名方法を持っている # 先頭にふたつのアンダースコア__を付ける class Duck(): def __init__(self, input_name): self.__name = input_name #外からアクセスできないプロパティ @property def name(self): #ゲッター print('inside the getter') return self.__name @name.setter def name(self, input_name): #セッター print('inside the setter') self.__name = input_name # オブジェクト(インスタンス)を作る fowl = Duck('Howard') # ゲッター fowl.name # inside the getter # 'Howard' # セッター fowl.name = 'Donald' # inside the setter fowl.name # inside the getter # 'Donald' # __name属性にはアクセスできない fowl.__name # エラー ''' Traceback (most recent call last): File "<stdin>", line 1, in <module> AttributeError: 'Duck' object has no attribute '__name' ''' # これだとアクセスできる fowl._Duck__name # 'Donald'
false
b8d0130e85142df007aed7951d6ec07988bddc9a
0gravity000/IntroducingPython
/04/040601.py
1,312
4.3125
4
# 4.6.1 リスト内包表記 number_list = [] for number in range(1, 6): number_list.append(number) number_list number_list = list(range(1, 6)) number_list # リスト内包表記を使った Pythonらしいコード # [ expression for item in iterable ] number_list = [number for number in range(1, 6)] number_list number_list = [number -1 for number in range(1, 6)] number_list # リスト内包表記には条件式も追加できる # [ expression for item in iterable if condition] a_list = [number for number in range(1, 6) if number % 2 == 1] a_list # 上記は以下と一緒 a_list = [] for number in range(1, 6): if number % 2 == 1: a_list.append(number) a_list # 内包表記ではfor節を複数使うことができる # 内包表記を使って結果を(row, col)形式のタプルにしてcells変数に代入 rows = range(1, 4) cols = range(1, 3) cells = [(row, col) for row in rows for col in cols] for cell in cells: print(cell) # 上記は以下と一緒 rows = range(1, 4) cols = range(1, 3) for row in rows: for col in cols: print(row, col) # なおタプルのアンパックを使って、cellsリストを反復処理しながら # タプルからrow,colの値を引き抜くこともできる for row, col in cells: print(row, col)
false
9fe26472b3e65060b858040cdacc132387283fbd
mansi135/mansi_prep
/practice/new_problems.py
2,850
4.1875
4
# Given two sorted lists, return the interesection (ie the common elements b/w the two sorted lists) # For example given l1 = [1, 2, 3] and l2 = [2, 3, 5, 10] (they can be different sizes) # return [2, 3] # LINEAR TIME # 4 def get_intersection(l1, l2): pass # given two sorted lists l1 and l2, merge them such that the result is also sorted # use no helper methods # For example given l1 = [1, 2, 3] and l2 = [2, 3, 5, 10] (they can be different sizes) # return [1, 2, 2, 3, 3, 5, 10] # return [1, 2, 3, 5, 10] # LINEAR TIME # 5 def merge(l1, l2): pass # return true iff the string has a repeated substring. # for example: "I ate not so late today" has a repeated substring ate. So it would return true for that # but if I gave "Have not eaten", it would return false. # 3 def has_repeated_substring(s): pass # Given a string s, and an index i, return the index of the # space, or end of string, that terminates the word starting at s[i]. For example given # s = "monkey ate my banana", i = 0, returns 6. And i = 14 (returns 20) # 1 def find_word_boundary(s, i): pass # Given a string s that has single-space separated words like "I am a fool" # Print the words in order, with their characters reversed # Try not to use any helper methods like split # For example, the result for "I am a fool" would be "I ma a loof" # You may consider using the above helper method find_word_boundary # 2 def reverse_words_in_list(s): pass # Given a 2D array board, that represents a square board of size n # find if its a winning combination # ie, that there is either a horizontal, vertical or any of the two diagnols are streams of 1 or 0 # example: # board[0] = [1, 0, 0], board[1] = [0, 1, 0], board[2] = [0, 0, 1] # and you call this method with board and n = 3, then it would return true (because there is a diagnol streak of 1) # 0 def is_winning(board, n): pass # Find two indices i, j in the list (that may be the same) such that l[i] + l[j] == n # Return that as a tuple def find_two_nums_summing(l, n): pass # Print the first n fibonacci numbers. # The numbers are defined as: # a_1 = 1 # a_2 = 1 # a_n = a_{n-1} + a_{n-2} def fibonacci(n): pass # a is a 2D matrix (array of arrays). Return true iff n exists in a def find_element_in_matrix(a, n): pass # Check if the substring sub exists in s. For example, find_substring("hello buffalo", "o b") == True def find_substring(s, sub): pass # is a string containing just '(' or ')'. For example it could be ((())) or (()()()) or ((() or )(() # Check if the string contains 'matched' paranthesis (matched as in it would be mathematically correct use of paranthesis). For example the last two examples aren't matched # Hint: Use the list methods append and pop. You can also read about "Stack datastructure" online def is_paranthesis_matched(s): pass
true
bf5541aff5d60357f0a736f7689cfeb3aa8b46e7
snidarian/Algorithms
/factorial_recursion.py
429
4.46875
4
#! /usr/bin/python3 # Factorial recursive algorithm import argparse parser = argparse.ArgumentParser(description="Returns factorial of given integer argument") args = parser.add_argument("intarg", help="Int to be factored", type=int) args = parser.parse_args() def factorial_recursive(n): if n == 1: return 1 else: return n * factorial_recursive(n - 1) print(factorial_recursive(args.intarg))
true
aa952649de3e87a99472f6cc2b92e7b2b8bf57ea
Factumpro/HackerRank
/Python/Practice/Sets/intersection.py
535
4.15625
4
''' Set .intersection() Operation https://www.hackerrank.com/challenges/py-set-intersection-operation/problem ''' ''' The .intersection() operator returns the intersection of a set and the set of elements in an iterable. Sometimes, the & operator is used in place of the .intersection() operator, but it only operates on the set of elements in set. The set is immutable to the .intersection() operation (or & operation). ''' _, x = input(), set( input().split()) _, y = input(), set( input().split()) print(len(x.intersection(y)))
true
9cd9cb9efd74fd3e3ff798b3865ace2590249fa4
Factumpro/HackerRank
/Python/Practice/Sets/union.py
481
4.1875
4
''' Set .union() Operation https://www.hackerrank.com/challenges/py-set-union/problem ''' ''' The .union() operator returns the union of a set and the set of elements in an iterable. Sometimes, the | operator is used in place of .union() operator, but it operates only on the set of elements in set. Set is immutable to the .union() operation (or | operation). ''' not_need1 =input() a = set(input().split()) not_need2 = input() b = set(input().split()) print(len(a.union(b)))
true
42d6fba978a62e664aad1dbb1aa10fe161d51fab
Epic-R-R/Round-robin-tournament
/main.py
1,536
4.125
4
from pprint import pprint as pp def make_day(num_teams, day): # using circle algorithm, https://en.wikipedia.org/wiki/Round-robin_tournament#Scheduling_algorithm assert not num_teams % 2, "Number of teams must be even!" # generate list of teams lst = list(range(1, num_teams + 1)) # rotate day %= (num_teams - 1) # clip to 0 .. num_teams - 2 if day: # if day == 0, no rotation is needed (and using -0 as list index will cause problems) lst = lst[:1] + lst[-day:] + lst[1:-day] # pair off - zip the first half against the second half reversed half = num_teams // 2 return list(zip(lst[:half], lst[half:][::-1])) def PrintTable(schedule): days = [f"Day {i+1}" for i in range(len(schedule))] for i in range(len(schedule)): print(f"|Day {i+1}: ", end="") for j in schedule[i]: print("{} - {}| ".format(j[0], j[1]), end="") if len(schedule) == 5: print(f"\n{'-'*28}") else: print(f"\n{'-'*71}") def make_schedule(num_teams): """ Produce a one round schedule """ # number of teams must be even if num_teams % 2: num_teams += 1 # add a dummy team for padding # build round-robin schedule = [make_day(num_teams, day) for day in range(num_teams - 1)] return schedule def main(): num_teams = int(input("How many teams? ")) schedule = make_schedule(num_teams) PrintTable(schedule) # pp(schedule) if __name__ == "__main__": main()
true
9f815235eb7c74e01c17cd19ef5622bd843c8f1d
Elsie0312/pycharm_code
/two_truths-lie.py
584
4.15625
4
print('Welcome to Two Truths and a Lie! /n One of the following statements is a lie...you need to identify which one!') print('1. I have a donkey living in my backyard.') print('2. I have three fur babies') print('3. I speak 4 languages') truth_or_lie = input('Now put in the number of the statement you think is the lie!') conv_truth_or_lie = int(truth_or_lie) if conv_truth_or_lie == 1: print('Congrats, you have identified the lie correctly!') elif conv_truth_or_lie == 2: print('That is not the one!') elif conv_truth_or_lie == 3: print('Sorry, you have to try again')
true
21078417d8209bf5d35ba40a0e351750f28d8d36
GABIGOLeterno/CursoemV-deoExerc-cios
/desafio33.py
277
4.15625
4
while True: num = str(input("Digite três valores: ").strip()) num2 = num.split() if len(num2) == 3: maxi = max(num2) mini = min(num2) print("O valor máximo é {}.".format(maxi)) print("O valor mínimo é {}.".format(mini))
false
2492520b1fc91cf095c964e1b178c483046766b6
besslwalker/algo-coding-practice
/4.1 Quicksort/quicksort.py
1,534
4.125
4
# Quicksort # Bess L. Walker # 2-21-12 import random def quicksort(unsorted): real_quicksort(unsorted, 0, len(unsorted)) def real_quicksort(unsorted, low, high): if high - low <= 1: return pivot_index = partition(unsorted, low, high) real_quicksort(unsorted, low, pivot_index) real_quicksort(unsorted, pivot_index + 1, high) def partition(unsorted, low, high): pivot_index = random.randint(low, high - 1) # inclusive of high bound pivot_value = unsorted[pivot_index] # Put pivot value at the end of the partition to keep it out of the way unsorted[pivot_index] = unsorted[high - 1] unsorted[high - 1] = pivot_value lowest_high_index = low # the lowest index of the higher-than-pivot values for index in range(low, high - 1): # don't go through the pivot if unsorted[index] < pivot_value: # then put it at the end of the lower-than-pivot section # unless it is already there if not index == lowest_high_index: temp = unsorted[lowest_high_index] unsorted[lowest_high_index] = unsorted[index] unsorted[index] = temp lowest_high_index += 1 # The low index of the higher-than-pivot section is where the pivot goes unsorted[high - 1] = unsorted[lowest_high_index] unsorted[lowest_high_index] = pivot_value return lowest_high_index permut_1 = [0, 1, 2, 3, 4 ,5] print permut_1 quicksort(permut_1) print permut_1 print permut_2 = [5, 4, 3, 2, 1, 0] print permut_2 quicksort(permut_2) print permut_2 print permut_3 = [3, 2, 21, 8, 4, 4] print permut_3 quicksort(permut_3) print permut_3
true
c7c008011e3694dae55fa8a676721bd8e9f5e78b
jaypsingh/PyRecipes
/String_n_Text/Str_n_Txt_07.py
710
4.4375
4
''' This program demonstrates how can we specify a regular expression to search shortest possible match. By Default regular expression gives the longest possible match. ''' import re myStr = 'My heart says "no." but mind says "yes."' # Problem demonstration ''' Here we ar etrying to match a text inside a quote. So i expect an answer as 'yes.' and 'no.' Lets see what it returns. ''' myProblemPat = re.compile(r'\"(.*)\"') print (myProblemPat.findall(myStr)) # Python returns ['no." but mind says "yes.'] # Solution ''' To fix this, we just need to add a ? after the * This will force python to search in a non gready way. ''' mySolutionPat = re.compile(r'\"(.*?)\"') print (mySolutionPat.findall(myStr))
true
8132dc8fd2f2ed88fab536995f8acc2968700ed2
jaypsingh/PyRecipes
/DS_and_Alg/DS_and_Alg_12.py
1,562
4.3125
4
''' This program demos the use of Counter class from collections module. Counter objects are very helpful in any case where you need to tabulate or count the data. ''' from collections import Counter mySong = ['I', 'wanna', 'be', 'your', 't-shirt', 'when', 'it', 'is', 'wet', 'I', 'wanna', 'be', 'the', 'shower', 'when', 'you', 'sweat', 'I', 'got', 'to','be', 'the', 'tattoo', 'on', 'your', 'skin', 'You', 'lemme', 'be', 'your', 'bed', 'baby', 'when', 'you', 'climb'] #More Lyrics moreLyrics = ['I', 'wanna', 'be', 'your', 'lipstick', 'when', 'you', 'lick', 'it', 'I', 'wanna', 'be', 'your', 'high', 'heels,', 'ah,', 'when', 'you', 'kick', 'it', 'I', 'wanna', 'be', 'sweet', 'love', 'babe,', 'yeah,', 'when', 'you', 'make', 'it', 'From', 'your', 'feet', 'up', 'to', 'your', 'hair,', 'more', 'than', 'anything', 'I', 'swear', 'I', 'wanna', 'be', 'your', 'underwear'] # Create the word count object wordCount = Counter(mySong) #under the hood word count is a dictonary # For example print (wordCount["wanna"]) print (wordCount["lemme"]) # moset_common() method. topThree = wordCount.most_common(3) print (topThree) '''to update the wordCount variabe we cn do two ways:''' #Approach 1 <most common which we usually take> for word in moreLyrics: wordCount[word] = +1 # Approach 2 <more efficient which counter object gives us> wordCount.update(moreLyrics) ''' #Undocumented freature of counter instance, is that you can do armetical operations like addition or substraction on two counter instances. eg wordCount1 + wordCount2 wordCount1 - wordCount2 '''
false
f8d563e8c1ce87996fe1f0df6ebe05e65ff8a543
jaypsingh/PyRecipes
/String_n_Text/Str_n_Txt_05.py
445
4.1875
4
''' This function demonstrates how can we search and replace strings ''' import re myStr = "Today is 03/09/2016. Game of Thrones starts 21/07/2017" # Simple replace using str.replace() print (myStr.replace('Today', 'Tomorrow')) # Replace using re.sub() - Approach 1 print(re.sub(r'(\d+)/(\d+)/(\d+)', r'\3\-2\-1', myStr)) # Replace using re.sub() - Approach 2 newStr = re.compile(r'(\d+)/(\d+)/(\d+)') print(newStr.sub(r'\3\-2\-1', myStr))
true
c8913860b13c4619cd5119cacdce93fce0e6bcb7
DHSZ/programming-challenge-2
/seven-seg-words.py
300
4.40625
4
def longest_word(): longest_word = "" ## Write your Python3 code inside this function. ## Remember to find words that only use the following letters: ## A, B, C, E, F, H, I, J, L, N, O, P, S, U, Y ## Good luck!! return longest_word print(longest_word())
true
5f4313bc5806a145daf721c578f7120dd2755c01
HarrisonPierce/Python-Class
/pierce-assignment2.py
1,258
4.28125
4
##Harrison Pierce ##This program calculates the factorial of a user defined number ##Set factorial variable to 1 factorial = 1 k = int(input('Enter a postitive integer: ')) ##Ask user for an integer and set equal to the variable k for k in range(1,k + 1): ##start for loop for k. while between 1 and the number entered continue to stay in loop factorial = factorial * k ##multiply the number entered by k and each time add 1 to k ##until the numbner entered by the user is reached. print("The factorial of the number entered is ", factorial) ##Print the product of the factorial. ##------------------------------------------------------------------------------ ##Question 2 ##Create variable i and set equal to user input for number of rows desired i = int(input('Enter the number of rows: ')) ##create for loop that stays in loop until i is reached for row in range(i): ##print a pound sign for the column on the left print('#', end='', sep='') ##this loop prints the appropriate number of spaces for the current iteration in the ##outter for loop. for spacenum in range(row): ##print a space print(' ', end='', sep="") ##print the pound sign after reaching the appropriate number of spaces for the row print('#', sep='')
true
a9f0b22836ca6ae81e7d60383386fffdc7ef8011
Rayansh14/Term-1-Project
/rock paper scissors.py
2,289
4.25
4
import random score = 0 def generate_random(): return random.choice(["rock", "paper", "scissors"]) def is_valid(user_move): if user_move in ["rock", "paper", "scissors", "r", "p", "s"]: return True return False def result(comp_move, user_move): if comp_move == user_move: return "tie" if comp_move == "rock": if user_move == "paper": return "user" else: return "comp" elif comp_move == "paper": if user_move == "rock": return "comp" else: return "user" elif comp_move == "scissors": if user_move == "rock": return "user" else: return "comp" def scorekeeper(comp_choice, user_input): global score my_result = result(comp_choice, user_input) if my_result == "user": print(f"You chose {user_input} and the computer chose {comp_choice}, so you won.") score += 1 print(f"Score: {score}") elif my_result == "comp": print(f"You chose {user_input} and the computer chose {comp_choice}, so you lost.") score -= 1 print(f"Score: {score}") elif my_result == "tie": print(f"You chose {user_input} and the computer chose {comp_choice}, so it was a tie.") print(f"Score: {score}") print("This is a game of Rock-Paper-Scissors") print("Your possible moves are: rock, paper, scissors, r, p or s") print("Write 'quit' to terminate") print("Score: 0\n") while True: user_input = input("What's your move: ").lower() if user_input == "quit": if score < 0: print(f"The Computer won by {score} points!") elif score > 0: print(f"Congratulations! You won by {score} points!") else: print("The game was a tie!") break if not is_valid(user_input): print("Invalid Move") print("Your possible moves are: rock, paper, scissors, r, p or s\n") continue if user_input == "r": user_input = "rock" elif user_input == "s": user_input = "scissors" elif user_input == "p": user_input = "paper" comp_choice = generate_random() scorekeeper(comp_choice, user_input) print()
true
b3e22b635a04c95e29734074c2296ffb64226552
Julian-J0/MadlibProject
/main.py
1,692
4.15625
4
from random import randint uinput = input("Choose from 1-2 or type random: " ) def story_1(): Title_1 = input("Input a title: ") Name_1 = input("Input a name: ") Adjective_1 = input("Input an adjective: ") Group_1 = input("Input a group, ex. soldiers: ") Verbed_1 = input("Input a verb ending in -ed: ") Feeling_1 = input("Input a feeling: ") Verb_1 = input("Insert a verb ending with s: ") print ("Story 1:") print ("Once upon a time, there was a (", Title_1,"). Their name was (", Name_1, "), and they were (", Adjective_1,"). They had (", Group_1, ") full of people and they were they were (", Name_1, ") to command. One day, they (", Verbed_1, ") all day long as training, and they felt (", Feeling_1, ")about it. They ended their day doing (", Verb_1, "). The End!") def story_2(): MrMs_2 = input("Enter Mr or Ms: ") Lname_2 = input("Input a last name:") Adjective_2 = input("Input an adjective: ") Verb_2 = input("Input a verb ending with -ing: ") print ("Story 2:") print ("Hello (", MrMs_2,")(", Lname_2, "), We are writing to you to inform you about your childs(", Adjective_2, ")behavior. While we are aware that you have limited time, we suggest that you start(", Verb_2, ")with your child so they can build more character. Thank you (", MrMs_2,")(", Lname_2, "), have a good day." ) def randomc(): rando = randint(1,2); print (rando) if rando == 1: return (story_1()) elif rando == 2: return (story_2()) def u_choice(): if uinput == ("1"): return (story_1()); elif uinput ==("2"): return (story_2()); elif uinput ==("R"): return (randomc()); else: print (input("Please enter 1-2 or (R)andom ")); u_choice()
false
1bd93d500350c63fca4ba7e6a8ed3e1fb80bd1fe
UnKn0wn27/PyhonLearning-2.7.13
/ex11.py
505
4.21875
4
#raw_input() presents a prompt to the user(the optional arg of raw_intput([arg]) #gets input from the user and returns the data input by the user in a string. #Exemple: # name = raw_input("What is your name?") # print "Hello, %s." % name #raw_input was renamed input() in Python 3 print "How old are you?", age = raw_input() print "How tall are you", height = raw_input() print "How much do you weight?", weight = raw_input() print "So, you're %r old, %r tall and %r heavy." %( age, height, weight)
true
4d7eb9d814d4cd5db77400c7a96e1c18900eb00f
cantayma/web-caesar
/caesar.py
1,197
4.21875
4
import string def alphabet_position(letter): """ receives a letter, returns 0-based numerical position in the alphabet; case-sensitive; assumes letters only input """ if letter in string.ascii_uppercase: position = string.ascii_uppercase.find(letter) elif letter in string.ascii_lowercase: position = string.ascii_lowercase.find(letter) return position def rotate_character(char, rot): """ recieves a string, char, and an integer, rot, and returns a new string that is the character after it is rotated through the alphabet by rot """ if char in string.ascii_uppercase: newChar = string.ascii_uppercase[(alphabet_position(char) + rot) % 26] elif char in string.ascii_lowercase: newChar = string.ascii_lowercase[(alphabet_position(char) + rot) % 26] else: newChar = char return newChar def encrypt(text, rot): """ receives a string, text and an int, rot, and returns the encrypted text by rotating each character in text by rot positions """ encryptedText = "" for aLetter in text: encryptedText += rotate_character(aLetter, rot) return encryptedText
true
00585bc27141ada23149b8f272f33ab23710a2ee
tlananthu/python-learning
/98_tools/training_ram/day1/ex4.py
529
4.25
4
#fizzbuzz problem # take number as input (1-100) # if divisible by 3 print Fizz # if divisible number is divisible by 5 print buzz # if both print fizzbuzz # none: print number num=int(input('Number between 1 to 100: ')) # if num%3 == 0 and num%5 == 0: # print('FizzBuzz') # elif num%5 == 0: # print('Buzz') # elif num%3 == 0: # print('Fizz') # else: # print('Number is ',num) #print("Even" if n%==2 else "Odd") #print("FizzBuzz" if num%==3 and num%5==5 else "Fizz" if num%3 else num%5 "Buzz" else "Number" )
false
36d1432db82c986858bf650aa2c8281d494e01ac
tlananthu/python-learning
/00_simple_examples/06_maths.py
336
4.1875
4
number1=int(input('Please input a number')) number2=int(input('Please input another number')) operation=input('Please input an operation. +-/*') if operation=='+': print(number1+number2) elif operation=='-': print(number2-number2) elif operation=='/': print(number2/number2) elif operation=='*': print(number2*number2)
true
90094aafd436e093d00d2300a8278938caa788c1
Shwebs/Python-practice
/BasicConcepts/3.strings/string-multiplication.py
567
4.15625
4
#Strings can also be multiplied by integers. This produces a repeated version of the original string. # The order of the string and the integer doesn't matter, but the string usually comes first. print("spam" * 3) #O/p:spamspamspam print (4 * '2') #O/p: 2222 #Strings can't be multiplied by other strings. #Strings also can't be multiplied by floats, even if the floats are whole numbers. print ('17' * '87') #TypeError: can't multiply sequence by non-int of type 'str' print ( 'pythonisfun' * 7.0) #TypeError: can't multiply sequence by non-int of type 'float'
true
28b923b625a0d8e716f3a85b98cfea1ac81d285b
Shwebs/Python-practice
/ControlStructure/List/List-method-count.py
305
4.125
4
#list.count(obj): Returns a count of how many times an item occurs in a list letters = ['p', 'q', 'r', 's', 'p', 'u'] print(letters.count('r')) #O/P:-1 print(letters.count('p')) #O/P:-2 # index method finds the "first occurrence" of a list item and returns its index print(letters.count('z')) #O/P:-0
true
2fd82e086ef9fd6b383c2055f70ced123c94963d
Shwebs/Python-practice
/BasicConcepts/3.strings/string-methods/split.py
489
4.21875
4
#Splits string according to delimiter string, returns list of substrings. #Default delimiter is ' ' . str='Test My Skill' output=str.split() print(output) #o/p:- ['Test', 'My', 'Skill'] for x in output: print(x) #o/p:-Test # My # Skill #Delimiter can be changed in the split() argument str="02-May-2018" output=str.split('-') for x in output: print(x) time="12:00:05" output=time.split(':') for x in output: print(x)
true
e21cba589f4928a7ad09bd7ad84d786b5a4fb73c
Shwebs/Python-practice
/ControlStructure/range/basic-range.py
727
4.75
5
#The range function creates a sequential list of numbers. #The call to list is necessary because range by itself creates a range object, # and this must be converted to a list if you want to use it as one. #If range is called with one argument, it produces an object with values from 0 to that argument. numbers = list(range(5)) print(numbers) #If it is called with two arguments, it produces values from the first to the second. num = list(range(3, 8)) print(num) print(range(20) == range(0, 20)) nums1 = list(range(5, 8)) print(len(nums1)) #range can have a third argument, which determines the interval of the sequence produced. This third argument must be an integer. numbers = list(range(5, 20, 2)) print(numbers)
true
909325fdb03654071ecb54104d622e35e96a3497
Shwebs/Python-practice
/python-fundamentals-by-pluralsight/Object_Reference.py
1,065
4.25
4
#Pass by Object Reference #The value of the reference is copied , not the value of the object # Helpful Link https://robertheaton.com/2014/02/09/pythons-pass-by-object-reference-as-explained-by-philip-k-dick/ m = [9, 15, 24] def modify(k): """Appending a value to function. Args: A any literal can be added. Returns: If you want to modify a copy of a object it the responsiblity of the function to do the coping it. The literal will be appended at the end of the list. """ k.append(41) print("Value of k =", k) print("Value of m before function call=", m) modify(m) print("Value of m after function call=", m) # # f = [9, 15, 24] def replace(g): """Creating a new list. Args: A any literal can be added. Returns: If you want to modify a copy of a object it the responsiblity of the function to do the coping it. The literal will be appended at the end of the """ g = [17, 22, 35] print("Value of g =", g) print("Value of f before function call=", f) replace(f) print("Value of f after function call=", f)
true
79699f6e7d3ab0c9ad08ad75dcf510fae492166d
Shwebs/Python-practice
/ControlStructure/List/List-operation.py
1,186
4.53125
5
#The item at a certain index in a list can be reassigned. #In the below example , we are re-assigned List[2] to "Bull" nums = [7, 8, 9, 10, "spring"] nums[2] = "Bull" print(nums) print("===================================") #What is the result of this code? nums = [1, 2, 3, 4, 5] nums[3] = nums[1] # We are re-assigning nums[3] = 2 print(nums[3]) print(nums + [4, 5, 6]) print(nums * 3) print("===================================") ##Lists can be added and multiplied in the same way as strings. nums = [1, 2, 3] nums2 = [11,22,33] #print("nums * nums2", nums * nums2) #TypeError:can't multiply sequence by non-int of type 'list' print(nums[1] * nums2[1]) # We have multiplied 2 numbers. char = ["a","b","c"] char2 = ["x","y","z"] print ("char + char2", char + char2) #print ("char * char2", char * char2) #TypeError:can't multiply sequence by non-int of type 'list' print("Multiplying Number with Character list",nums[2]*char) # O/p:-2 * [a,b,c]=[a,b,c,a,b,c] print("Multiplying indexed Number with Character index list",nums[2]*char[2]) #O/P:- ccc #Lists and strings are similar in many ways - strings can be thought of as lists of characters that can't be changed.
true
18f795a10eb2da066a1599fd909069e2d00216fc
Shwebs/Python-practice
/ControlStructure/List/List-method-insert.py
797
4.25
4
#The insert method is similar to append, #except that it allows you to insert a new item at any position in the list, #as opposed to just at the end. words = ["Python", "fun"] index = 1 words.insert(index, "is") print (words) print("================================") nums = [1,2,3,5,6,7] index = 3 nums.insert(index,4) # it allows you to insert a new item at any position print("We have added 4 to the list ", nums) nums.append(8) print("We have added 8 (at the end) to the list ", nums) #it allows you to insert a new item only at end of the list. print("================================") #What is the result of this code? nums = [9, 8, 7, 6, 5] nums.append(4) #O/P:- [9, 8, 7, 6, 5, 4] print(nums) nums.insert(2, 11) #O/P:-[9, 8, 11, 7, 6, 5, 4] print(nums) print(len(nums)) #O/P:-7
true
fba81294a158815848dded2ca40206fb46b6ccd5
Shwebs/Python-practice
/BasicConcepts/3.strings/string-methods/string-is-check.py
1,386
4.21875
4
str=input("Enter a String: ") #isalnum() #Returns true if string has at least 1 character and all characters are alphanumeric and false otherwise. print('Checking If it is an alphanumeric :-',str.isalnum()) #isalpha() #Returns true if string has at least 1 character and all characters are alphabetic and false otherwise. print('Checking If it is analphabestic :-',str.isalpha()) #isdigit() #Returns true if string contains only digits and false otherwise. print('Checking If it is numeric :-',str.isdigit()) #islower() #Returns true if string has at least 1 cased character and all cased characters are in lowercase and false otherwise. print('Checking If string has character in lowercase :-',str.islower()) #isnumeric() #Returns true if a unicode string contains only numeric characters and false otherwise. print('Checking If string has numeric :-',str.isnumeric()) #isspace() #Returns true if string contains only whitespace characters and false otherwise. print('Checking If it is string has white space :-',str.isspace()) #istitle() #Returns true if string is properly "titlecased" and false otherwise. print('Checking If it is character in numeric :-',str.istitle()) #isupper() #Returns true if string has at least one cased character and all cased characters #are in uppercase and false otherwise. print('Checking If string has character in uppercase :-',str.isupper())
true
292b8675c84630e557c9282cf2fc4567a3cd68c5
alessandrogums/Desafios-Python_Variaveis_compostas-listas-
/Exercicio.86_CV.py
468
4.25
4
# Crie um programa que declare uma matriz de dimensão 3×3 e preencha com valores lidos pelo teclado. # No final, mostre a matriz na tela, com a formatação correta. matriz=[[],[],[]] for l in range(0,3): for c in range(0,3): num=int(input('digite um número:')) matriz[c].append(num) print('='*15) for c in range(0,3): cont=0 while not cont ==3: print(f'[{matriz[c][cont]}]',end=' ') cont+=1 print() print('='*15)
false
7a33ee3d407ac8ec09a4898cd2cfd53eca320f1f
Abeelha/Udemy
/Curso Udemy/ex1.py
1,334
4.25
4
#Idade Idade = int(input("Digite sua idade ")) #Condição da idade if Idade >= 18: print("Maior de idade") elif 0 < Idade < 18: print ("Menor de idade") else: print("idade inválida") #Notas Nota1 = float(input("Digite sua nota em Matemática ")) Nota2 = float(input("Digite sua nota em Filosofia ")) #Média media = (Nota1 + Nota2)/2 print ("Sua média é ", media) if media >=6: print ("Aprovado!") else: print ("Reprovado!") #Equação de 2ndo grau a = float(input("Digite valor de A ")) b = float(input("Digite valor de B ")) c = float(input("Digite valor de C ")) delta = b**2 - (4*a*c) raiz_delta = delta**0.5 x1 = (-b+raiz_delta)/(2*a) x2 = (-b-raiz_delta)/(2*a) print(x1) print(x2) #Operaçao com input num1 = float(input("Digite o primeiro Número: ")) operador = input("Digite o operador: ") num2 = float(input("Digite o segundo Número: ")) #Soma if operador == "+": resultado = num1 + num2 #Subtração elif operador == "-" : resultado = num1 - num2 #Divisão elif operador == "/": resultado = num1 / num2 #Multiplicação elif operador == "*": resultado = num1 * num2 #Potencia elif operador == "**": resultado = num1 ** num2 #Módulo elif operador == "%": resultado = num1 % num2 else: print("Uma falha aconteceu :/") print (resultado)
false
9539c945b6063ffdcd398710f03d371056ec52f7
IlyaTroshchynskyi/python_education_troshchynskyi
/algoritms/algoritms.py
2,512
4.125
4
# -*- coding: utf-8 -*- """calc Implements algorithms: - Binary search - Quick sort (iterative) - Recursive factorial """ def factorial(number): """ Define factorial certain number. """ if number <= 0: return 1 return number * factorial(number-1) print(factorial(50)) test_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11] def binary_search(input_list, number): """ Look for index of certain number by using algorithms binary search. Return None if number out of list. """ start = 0 stop = len(input_list) - 1 while start <= stop: middle = (stop + start) // 2 guess = input_list[middle] if guess == number: return middle if guess > number: stop = middle - 1 else: start = middle + 1 return None print(binary_search(test_list, 10)) def partition(my_list, start_index, end_index): """ Elements less than the last will go to the left of array and elements more than the last will go to the right of array """ start_index_1 = (start_index - 1) last_element = my_list[end_index] for j in range(start_index, end_index): if my_list[j] <= last_element: start_index_1 = start_index_1 + 1 my_list[start_index_1], my_list[j] = my_list[j], my_list[start_index_1] my_list[start_index_1 + 1], my_list[end_index] = my_list[end_index], my_list[start_index_1 + 1] return start_index_1 + 1 def quick_sort(my_list, start_index, end_index): """ Sort array in ascending order by using algorithms quick sort. """ size = end_index - start_index + 1 stack = [0] * size top = -1 top = top + 1 stack[top] = start_index top = top + 1 stack[top] = end_index while top >= 0: end_index = stack[top] top = top - 1 start_index = stack[top] top = top - 1 res_partition = partition(my_list, start_index, end_index) if res_partition - 1 > start_index: top = top + 1 stack[top] = start_index top = top + 1 stack[top] = res_partition - 1 if res_partition + 1 < end_index: top = top + 1 stack[top] = res_partition + 1 top = top + 1 stack[top] = end_index test_list = [4, 3, 5, 2, 1, 3, 2, 3] quick_sort(test_list, 0, len(test_list) - 1) for i, value in enumerate(test_list): print(f"Index: {i} Element:{value}")
true
cb912718e0b5494a24bde392beee25915729e409
IlyaTroshchynskyi/python_education_troshchynskyi
/python_advanced/iterator_.py
687
4.125
4
# -*- coding: utf-8 -*- """ Implements simple iterator """ class MyIterator: """ Implements simple iterator """ def __init__(self, value): self.data = value self.index = 0 def __getitem__(self, index): return self.data[index] def __iter__(self): return self def __next__(self): if self.index == len(self.data): raise StopIteration item = self.data[self.index] self.index += 1 return item def __contains__(self, item): return item in self.data my_iterator = MyIterator([1, 2, 3, 4, 5]) print(3 in my_iterator) for element in my_iterator: print(element)
false
e4b018aa44483d0eeed003818634cd3d785c2714
Zahidsqldba07/python_exercises-1
/exercise_7.py
348
4.4375
4
''' Write a Python program to accept a filename from the user and print the extension of that. Go to the editor Sample filename : abc.java Output: java ''' file_name = input('Enter file name with extension, example: abc.java') if file_name == '': file_name = 'abc.java' name = file_name.split('.')[0] ext = file_name.split('.')[-1] print(ext)
true
5f6bb76bc267af3a1ada99721556bc61637bc229
anhuafeng123/python
/王者荣耀1.py
336
4.125
4
num = 0 while num<3: weizhi = input("请输入一个位置") if weizhi == "ABC": print("后裔,黄忠,虞姬") elif weizhi == "肉盾": print("程咬金,亚瑟") elif weizhi =="法师": print("王昭君,妲己") elif weizhi == "刺客": print("兰陵王,阿科") num+=1
false
31e0794ad9981a270497e4cd91c2b9dbe52ea0f3
tohungsze/Python
/other_python/palindrome.py
869
4.1875
4
''' check if a given word is a palindrome ''' def main(): input = ['abcba', 'abc1cba', 'abcba ', 'abc1cba1'] for word in input: if is_palindrome(word): print('\'%s\' is a palindrome'%word) else: print('\'%s\' is a NOT palindrome'%word) def is_palindrome(input): # takes a string as input (cannot take list) input_list = list(input) input_reverselist = input_list # input_list and input_reverselist both points to same object input_reverselist.reverse() input_list = list(input) # now input_list and input_reverselist point to different object result = True for i in range(len(input_list)): if input_list[i] == input_reverselist[i]: continue else: result = False break return result if __name__ == '__main__': main()
true
9ce0cec8b92e20b92a39e6e5d1af707c3db4fb27
tohungsze/Python
/other_python/fibonacci.py
1,139
4.28125
4
# demonstrate fibonacci with and without caching ''' # this is really slow, can't handle more than 30 ish numbers def fibonacci_n(n): if n == 0 or n ==1: return 1 else: return fibonacci_n(n-1) + fibonacci_n(n-2) for i in range(1, 11): print("fibonacci(", i, ") is:", fibonacci_n(i)) ''' ''' cache_dict = {} # manual caching def fibonacci_mc(n): # mc = manual cache global cache_dict if n in cache_dict: return cache_dict[n] if n == 1 or n == 2: #cache_dict[n]=1 result = 1 else: result = fibonacci_mc(n-1) + fibonacci_mc(n-2) cache_dict[n] = result return result for i in range(1, 1001): print("fibonacci(", i, ") is:", fibonacci_mc(i)) ''' # using functools lru # with lru, originally slow simple calculation is fast! # each function will have own cache from functools import lru_cache @lru_cache(maxsize = 1000) #default is 128 def fibonacci_lru(n): if n == 0 or n == 1: return 1 else: return fibonacci_lru(n - 1) + fibonacci_lru(n - 2) for i in range(1, 10001): print("fibonacci(", i, ") is:", fibonacci_lru(i))
true
ff7c0a83280f5080fcef88e288d96fbeda29289e
prashantkgajjar/Machine-Learning-Essentials
/16. Hierarchical Clustering.py
2,929
4.15625
4
# Hierarchical Clustering ''' 1. Agglomerative Hierarchical Clustering (Many single clusters to one single cluster) 1. Make each data point as a single point Cluster. 2. Take the two closest datapoints, and make them one cluster. 3. Take to closest clusters, and make them one cluster. 4. Repeat STEP 3 unitll there is only one cluster. ''' ''' ******** Distance between two clusters:******* Option 1: Measure Distance between two closest points Option 2: Measure Distance between two farthest points Option 3: Take the average of the all points of clusters Option 4: Measure the distance between two centroids of clusters. ''' ''' ******** Dendograpms *********** It is a diagram that shows the Hierarchical relationship between two clusters or data points To optimize the clustering, selecting the Dendograms with the Highest Distance is considered as a optimal limit of number of cluster. ''' # Importing the libraries import numpy as np import matplotlib.pyplot as plt import pandas as pd # Importing the dataset dataset = pd.read_csv('Mall_Customers.csv') X = dataset.iloc[:, [3, 4]].values # Using the dendrogram to find the optimal number of clusters import scipy.cluster.hierarchy as sch dendrogram = sch.dendrogram(sch.linkage(X, method = 'ward')) plt.title('Dendrogram') plt.xlabel('Customers') plt.ylabel('Euclidean distances') plt.show() ''' From the above plot, it can be understood that the length(line) with highest gap between the clusters is the first line orangge one. From that line, 5 others such line are passsing, so we can conclude that there are 5 such clusters. ''' # Training the Hierarchical Clustering model on the dataset from sklearn.cluster import AgglomerativeClustering hc = AgglomerativeClustering(n_clusters = 5, affinity = 'euclidean', linkage = 'ward') y_hc = hc.fit_predict(X) # Visualising the clusters plt.scatter(X[y_hc == 0, 0], X[y_hc == 0, 1], s = 100, c = 'red', label = 'Cluster 1') plt.scatter(X[y_hc == 1, 0], X[y_hc == 1, 1], s = 100, c = 'blue', label = 'Cluster 2') plt.scatter(X[y_hc == 2, 0], X[y_hc == 2, 1], s = 100, c = 'green', label = 'Cluster 3') plt.scatter(X[y_hc == 3, 0], X[y_hc == 3, 1], s = 100, c = 'cyan', label = 'Cluster 4') plt.scatter(X[y_hc == 4, 0], X[y_hc == 4, 1], s = 100, c = 'magenta', label = 'Cluster 5') plt.title('Clusters of customers') plt.xlabel('Annual Income (k$)') plt.ylabel('Spending Score (1-100)') plt.legend() plt.show() ''' From the cluster, it can be concluded that::: Cluster 1: Red Color -- They spend less, despite earning high Cluster 2: Blue Color -- Average customer, those who has average income & average spends Cluster 3: Green Color -- They earn more, spend more. Perfect to target for advertisements Cluster 4: Light Blue Colo -- They earn less, but mostly spends high at the mall. cLUSTER 5: Pink Color -- Thay ean less & spends less '''
true
a37060def6b1333ff99fef976a78199d6b9603da
Jahishigh/TTR-python
/For Loop.py
724
4.25
4
# for prend une condition en variable, à chaque passage de la loop la variable va changer jusqu'à arriver à la condition # la variable après le for peut avoir n'importe quel nom, c'est la condition final qui compte for letter in "Hello": print(letter) list_de_value = [1, 2, 3] for value_in_list in list_de_value: print(value_in_list) for chiffre in range(6): print(chiffre) # Si on reprend l'exemple de notre liste 2d (voir plus haut) # Ici on affiche tous le tableau 2d tableau_en_2d = [ [1, 2, 3], [4, 5, 6], [7, 8, 9] ] for ligne in tableau_en_2d: print(ligne) # Ici on print chaque élément individuelement for ligne in tableau_en_2d: for colonne in ligne: print(colonne)
false
5f4d01e512104db3e264784891663d304937ed96
HsiaoT/Python-Tutorial
/data_structure/Sorting/Selection_sort.py
802
4.28125
4
# The selection sort algorithm sorts an array by repeatedly finding the # minimum element (considering ascending order) from unsorted part and # putting it at the beginning. The algorithm maintains two subarrays in a given array. # Time complexity (average): O(n^2) # Time complexit (best): O(n^2) (list already sorted) # Space complexity: O(1) import random init_random_Data = random.sample(range(100), 10) print("Init list:") print(init_random_Data) def selection_sort(nums): for i in range(len(nums)): min_index = i for j in range(i+1, len(nums)): # Find the minimum if nums[min_index] > nums[j]: min_index = j nums[i], nums[min_index] = nums[min_index], nums[i] return nums sorted_Data = selection_sort(init_random_Data) print("\nsorted list:") print(sorted_Data)
true
d9bc14d8ae35cb2475bb92bcc8d99446694bc590
sunDalik/Information-Security-Labs
/lab1/frequency_analysis.py
2,879
4.3125
4
import argparse # Relative letter frequencies in the English language texts # Data taken from https://en.wikipedia.org/wiki/Letter_frequency theory_frequencies = {'A': 8.2, 'B': 1.5, 'C': 2.8, 'D': 4.3, 'E': 13.0, 'F': 2.2, 'G': 2.0, 'H': 6.1, 'I': 7.0, 'J': 0.15, 'K': 0.77, 'L': 4.0, 'M': 2.4, 'N': 6.7, 'O': 7.5, 'P': 1.9, 'Q': 0.095, 'R': 6.0, 'S': 6.3, 'T': 9.1, 'U': 2.8, 'V': 0.98, 'W': 2.4, 'X': 0.15, 'Y': 2.0, 'Z': 0.074} def main(): # Reads encrypted text from file by name [filename] and outputs result to stdout usage = 'frequency_analysis.py filename' parser = argparse.ArgumentParser(usage=usage) parser.add_argument('filename', action='store') args = parser.parse_args() # Data to Theory letters mapping dtt = {letter: 0 for letter in theory_frequencies} # Number of english alphabet characters encountered data_len = 0 # File contents data = "" # Step 1. Read file and count how many of each letters there are with open(args.filename) as message: while True: # Process text file char by char c = message.read(1) # Stop reading file when it ends if not c: break data += c if c in dtt: data_len += 1 dtt[c] += 1 continue # Step 2. Get letter frequencies by dividing the amount of each letter by data length and multiplying it by 100 for k in dtt: dtt[k] = dtt[k] / data_len * 100 # Step 3. Create mapping between encrypted letters and real letters for k in dtt: best_letter = "" best_diff = 999 # Compare every encrypted letter to every real letter to find the best correlation for m in theory_frequencies: # Calculate frequency difference between current encrypted letter and real letter diff = abs(theory_frequencies[m] - dtt[k]) # If this is the lowest difference and this real letter was not yet assigned to any encrypted letter # then we found a mapping if diff <= best_diff and m not in dtt.values(): best_diff = diff best_letter = m # Map our best real letter candidate to the current encrypted letter dtt[k] = best_letter # Debug # print(dtt) # Output decrypted message by mapping every encrypted alphabet character to the real counterpart decrypted_message = "" for char in data: if char in dtt: decrypted_message += dtt[char] else: # If a character is not present in the alphabet then output it without any changes decrypted_message += char print(decrypted_message) main()
true
50d5314cda34ce36b4af6d37acdc81b3a87a17f8
luckychummy/practice
/queueUsingStack.py
1,222
4.28125
4
from queue import LifoQueue class MyQueue(object): def __init__(self): """ Initialize your data structure here. """ self.q1=LifoQueue() self.q2=LifoQueue() def push(self, x): """ Push element x to the back of queue. :type x: int :rtype: None """ while(not self.q2.empty()): self.q1.put(self.q2.get()) self.q2.put(x) while(not self.q1.empty()): self.q2.put(self.q1.get()) def pop(self): """ Removes the element from in front of queue and returns that element. :rtype: int """ return self.q2.get() def peek(self): """ Get the front element. :rtype: int """ item=self.q2.get() self.q2.put(item) return item def empty(self): """ Returns whether the queue is empty. :rtype: bool """ return self.q2.empty() #Your MyQueue object will be instantiated and called as such: obj = MyQueue() obj.push(5) obj.push(6) obj.push(7) obj.push(8) param_2 = obj.pop() param_3 = obj.peek() param_4 = obj.empty()
true
0490aadbd1ad9867125da762b31557a61d901434
tony-ml/algs200x-4
/fibonacci-sum-last-digit/solution.py
587
4.1875
4
def fibonacciSumLastDigit(n): KNOWN_VALUES = [0, 1, 2, 4, 7, 2, 0, 3, 4, 8, 3, 2, 6, 9, 6, 6, 3, 0, 4, 5, 0, 6, 7, 4, 2, 7, 0, 8, 9, 8, 8, 7, 6, 4, 1, 6, 8, 5, 4, 0, 5, 6, 2, 9, 2, 2, 5, 8, 4, 3, 8, 2, 1, 4, 6, 1, 8, 0, 9, 0] equivalent_n = n while equivalent_n > len(KNOWN_VALUES): equivalent_n = equivalent_n % len(KNOWN_VALUES) return KNOWN_VALUES[equivalent_n] if __name__ == '__main__': n = int(raw_input()) print fibonacciSumLastDigit(n)
false
34f84a9883b3d57911b30aea2ab4470efa57e482
AsharGit/Python-ICP
/Source/ICP-3/Employee.py
1,137
4.28125
4
class Employee: num_employees = 0 total_salary = 0 def __init__(self, name, family, salary, department): self.emp_name = name self.emp_family = family self.emp_salary = salary self.emp_dept = department self.increment(salary) # Increment num_employees and total_salary def increment(self, salary): self.__class__.num_employees += 1 self.__class__.total_salary += salary # Return the average salary of employees def avg_salary(self): return self.total_salary / self.num_employees class FulltimeEmployee(Employee): # Increment num_employees and total_salary in parent class def increment(self, salary): Employee.num_employees += 1 Employee.total_salary += salary # Initialize an employee and a full time employee emp1 = Employee('Bob', 'Smith', 40000, 'health') emp2 = FulltimeEmployee('Linda', 'Smith', 80000, 'health') print(emp1.emp_name) print(emp1.emp_salary) print(emp2.emp_name) print(emp2.emp_salary) print(emp1.num_employees) print(emp2.num_employees) print(emp1.avg_salary()) print(emp2.avg_salary())
true
e50d45dda524f0471a01371f202cb2f7384ca07f
stompingBubble/Asteroids
/shape.py
2,492
4.15625
4
# -*- coding: utf-8 -*- """ Gruppuppgift: Asteroids - Objektorienterad Programmering Nackademin IOT 17 Medverkande: Isa Sand Felix Edenborgh Christopher Bryant Stomme källkod: Mark Dixon """ from abc import ABC, abstractmethod import math from point import Point class Shape(ABC): def __init__( self, x=0, y=0, rotation=0 ): self.position = Point(x,y) self.rotation = rotation self.pull = Point(0,0) self.angular_velocity = 0.0 @abstractmethod def draw(self, screen): pass def update(self, width, height): """ Update the position and orientation of the shape :param width: screen width to confine the shape to :param height: screen height to confine the shape to :return: """ # Update the position and orientation of the shape # position is modified by "pull" - how much it should move each frame # rotation is modified by "angular_velocity" - how much it should rotate each frame self.position += self.pull self.rotation += self.angular_velocity # Use modulus to ensure that the object never vanishes from the screen # Position is wrapped to always be between (0,0) and (width,height) # Rotation is wrapped to always be between 0 and 360 degrees self.position.x %= width self.position.y %= height self.rotation %= 360 def accelerate(self, acceleration): """ Cause the object to start moving by giving it a little push :param acceleration: ammount to accelerate the shape by, if 0 then the shape is slowed down instead """ # if acceleration==0: self.pull.x *=0.9 self.pull.y *=0.9 else: self.pull.x += (acceleration * math.cos(math.radians(self.rotation))) self.pull.y += (acceleration * math.sin(math.radians(self.rotation))) def rotate(self, degrees): """ Rotation the shape by a specific amount :param degrees: angle in degrees for the shape to be rotated by """ self.rotation = ( self.rotation + degrees ) % 360; @abstractmethod def contains(self, point): if point: return True """ Abstract base class to perform collission detection - should return true if a point is inside the shape :param point: Point to test for collission :return: True or False """ return False
true
ffd1c6706c107f8fa4ca74bf33d36650046d0608
thechemist54/PYth0n-and-JaVa
/Area calculation.py
1,663
4.4375
4
#printing the options print("Options:") print("-"*8) print("1. Area of Rectangle") print("2. Area of Triangle") print("3. Area of Circle") print("4. Quit") #assigning a value to flag flag = False #analyzing responses and displaying the respective information #looping statement while flag == False: #asking to make a choice from the option choice = int(input("\nMake a selection from the option menu: ")) if choice == 1: #asking for height and width height = float(input ("\nEnter height: ")) width = float(input ("Enter width: ")) area_rectangle = (height * width) #calculating area print ("Area of rectangle is","{0:,.2f}".format(area_rectangle)) elif choice == 2: #asking for the base and height base = float(input("\nEnter base: ")) height_triangle = float(input ("Enter height of triangle: ")) area_triangle = ((1/2) * base * height_triangle) #calculating area print ("Area of triangle is","{0:,.2f}".format(area_triangle)) elif choice == 3: #asking for the radius of a circle radius = float(input("\nEnter the radius of a circle: ")) area_circle = (3.141592)*(radius**2)#calculating area of circle print ("Area of circle is","{0:,.2f}".format(area_circle)) elif choice == 4: #assigning flag as true flag = True else: #displaying the error message print("\nYou did not enter a proper number.")
true
b116a4dad9540ecd3ca827cc96f1748ddb2ad20a
kasapenkonata/python
/13_09/task9.py
384
4.21875
4
import turtle import math #осталось центрировать turtle.shape('turtle') def draw(n): R = 10*n a = 2 * R * math.sin(2 * math.pi / n) turtle.penup() turtle.goto(-a/2, R) turtle.pendown() for i in range(n): turtle.forward(a) turtle.right(360/n) return(0) for i in range(5): draw(i+3) x = input()
false
a948e2106b7150b3a41ae7486415a8dc17842292
AndrejLehmann/my_pfn_2019
/Vorlesung/src/Basic/example4_2.py
769
4.65625
5
#!/usr/bin/env python3 # Example 4-2 Concatenating DNA # store two DNA sequences into two variables called dna1 and dna2 dna1 = 'ACGGGAGGACGGGAAAATTACTACGGCATTAGC' dna2 = 'ATAGTGCCGTGAGAGTGATGTAGTA' # print the DNA onto the screen print('Here are the original two DNA sequences:') print(dna1) print(dna2) # concatenate DNA sequences into a 3rd var with format dna3 = '{}{}'.format(dna1, dna2) print('concatenation of the first two sequences (version 1):') print(dna3) # alternative way using the concatenation operator +: dna3 = dna1 + dna2 print('Concatenation of the first two sequences (version 2):') print(dna3) # print the same thing without using the variable dna3 print('Concatenation of the first two sequences (version 3):') print(dna1 + dna2) exit(0)
true
e2802f46eeb773f497cab112e4a74fe96b763f8f
pravalikavis/Python-Mrnd-Exercises
/finaltest_problem3.py
2,052
4.34375
4
__author__ = 'Kalyan' max_marks = 25 problem_notes = ''' For this problem you have to implement a staircase jumble as described below. 1. You have n stairs numbered 1 to n. You are given some text to jumble. 2. You repeatedly climb down and up the stairs and on each step k you add/append starting k chars from the text you have (and remove them from the text). 3. You repeat this process till you finish the whole text. 4. Finally you climb up from step 1 and collect all chars to get the jumbled text. E.g. if the text is "Ashokan" and n = 2. You have the following text on the steps. First you drop "As" on step 2, then "h" on step 1, then you get to the ground and you climb back again droping "o" on step 1 and "ka" on step2 and finally "n" on step2 (since you have run out of chars and you dont have 2 chars). So sequence of steps is 2, 1 then 1, 2 then 2, 1 and so on... (step2)As;ka;n ---- (step 1)|h;o ---- Final jumbled text is hoAskan (all text on step1 followed by all text on step2, the ; is shown above only to visually distinguish the segments of text dropped on the stair at different times) Notes: 1. Raise ValueError if n <= 0 2. Raise TypeError if text is not a str 3. Note that spaces, punctuation or any other chars are all treated like regular chars and they will be jumbled in same way. ''' def jumble(text, n): if type(text).__name__ != 'str': raise TypeError if n <= 0: raise ValueError c = n l = [] o = 0 while text != "": l.append((text[:c], c)) text = text[c:] if o == 0: c = c - 1 if c == 0: c = 0 o = 1 if o == 1: if c == n: o = 0 continue c = c + 1 l.sort(key=lambda x: x[1]) res = "" for a in l: res = res + a[0] return res def test_jumble(): assert "hoAskan" == jumble("Ashokan", 2)
true
2873efc5e996028da3dbe1d1a3a70e8046511c65
pankajdahilkar/python_codes
/prime.py
268
4.1875
4
def isPrime(a=0): i=2 if a==0 : return 0 while(i<a): if a%i==0: return 0 i=i+1 return 1 x=int(input("Enter The number : ")) if(isPrime(x)): print(x, "is Prime number ") else : print(x," is not Prime number")
true
b87ef01cecfa2e6d4b86866f75cfd256b24bac5f
SMKxx1/Very-Very-Very-Basic-1-Plus-1-1-Plus-0-Program
/Very Very Very Basic 2.py
2,798
4.21875
4
def student1(eng_marks1, acc_marks1, ip_marks1): dic_std_name1 = {'eng':eng_marks1,'accounts':acc_marks1,'ip':ip_marks1} av1 = (eng_mark1 + ip_mark1 + acc_mark1) / 3 return av1 #Return command is explained in line 43 def student2(eng_marks2, acc_marks2, ip_marks2): dic_std_name2 = {'eng':eng_marks2,'accounts':acc_marks2,'ip':ip_marks2} av2 = (eng_mark2 + ip_mark2 + acc_mark2) / 3 return av2 def student3(eng_marks3, acc_marks3, ip_marks3): dic_std_name3 = {'eng':eng_marks3,'accounts':acc_marks3,'ip':ip_marks3} av3 = (eng_mark3 + ip_mark3 + acc_mark3) / 3 return av3 print() std_name1 = input("Enter the name of the student:") eng_mark1 = int(input("Enter marks in english: ")) ip_mark1 = int(input("Enter marks in ip: ")) acc_mark1 = int(input("Enter marks in accounts: ")) print() print() std_name2 = input("Enter the name of the student:") eng_mark2 = int(input("Enter marks in english: ")) ip_mark2 = int(input("Enter marks in ip: ")) acc_mark2 = int(input("Enter marks in accounts: ")) print() print() std_name3 = input("Enter the name of the student:") eng_mark3 = int(input("Enter marks in english: ")) ip_mark3 = int(input("Enter marks in ip: ")) acc_mark3 = int(input("Enter marks in accounts: ")) print() av1 = student1(eng_mark1,acc_mark1,ip_mark1) av2 = student2(eng_mark2,acc_mark2,ip_mark2) av3 = student3(eng_mark3,acc_mark3,ip_mark3) ''' let me explain def function and return properly for instence we have a program to find sum of two numbers def sum(x,y): z = x + y return z Now the function requires 2 variables (the x and y given in the parenthesis) so lets create two variables num1 = 5 num2 = 10 Finally lets run the function the_sum_of_the_numbers = sum(num1,num2) what happenes here is num1 and num2 replaces x and y. also, the_sum_of_the_numbers will take the value of z because thats what we are returning or spitting out (probably returning is a better word) ''' x = 0 while x < 3: average = [av1,av2,av3] avx = average[x] if avx >= 90: print("Average of",avx,"A grade") elif avx >= 70 and avx <= 89: print("Average =",avx,"B grade") elif avx >= 50 and avx <= 69: print("Average =",avx,"C grade") else: print("Average =",avx,"E grade") x += 1 min = max = mid = 0 if av1 < av2 and av1 < av3: if av2 < av3: min,mid,max = av1,av2,av3 else: min,mid,max = av1,av3,av2 elif av2 < av1 and av2 < av3: if av1 < av3: min,mid,max = av2,av1,av3 else: min,mid,max = av2,av3,av1 else: if av1 < av2: min,mid,max = av3,av1,av2 else: min,mid,max = av3,av2,av1 print() print("The topper is",max) if max == av1: print(std_name1,"is the topper") elif max == av2: print(std_name1)
false
6ec568987a0315308f70ea53a710a341e15a5a2a
Camilo1318/EjerciciosPython
/Cadenas/ejercicio3.py
645
4.625
5
#Escribir un programa que pregunte el nombre del usuario en la consola y después de que el usuario lo introduzca muestre por pantalla <NOMBRE> tiene <n> letras, donde <NOMBRE> es el nombre de usuario en mayúsculas y <n> es el número de letras que tienen el nombre. #Cristian Pérez nombre = input("Ingrese su nombre: ") print(f""" Nombre: {nombre.upper()} Cantidad de letras: {len(nombre)} """) #Juan Diego nombre = input("Introduzca su nombre: ") print(f""" Nombre : {nombre.upper()} Numero de letras: {len(nombre)} """) #Juan David nombre = input("¿cual es su nombre?: ") print((nombre.upper()) + (" Y tiene ") + str(len(nombre)) + (" letras"))
false
44894e050247f38dc88e2184ed65b8e7fc3e868e
pravishbajpai06/Projects
/6.py
1,483
4.1875
4
#6-Change Return Program - The user enters a cost and then the amount of money given. The program will figure out the change and the number of quarters, dimes, nickels, pennies needed for the change. import math cent=0.01 penny=0.01 nickel=0.05 dime=0.1 quarter=0.25 do=1 cost=float(input("Enter the costt")) amount=float(input("Enter amount paid")) if cost>amount: change=cost-amount s=round((change/cent),2) p=round((change/cent),2) n=round((change/nickel),2) d=round((change/dime),2) q=round((change/quarter),2) de=round((change/do),2) print("U can pay ur left amount by paying",s,"cents OR ",p,"pennies OR ", n,"nickels OR", d,"dimes OR",q,"quarters OR", de,"dollars" ) elif amount>cost: change=amount-cost if change>0: s=round((change/cent),2) p=round((change/cent),2) n=round((change/nickel),2) d=round((change/dime),2) q=round((change/quarter),2) de=round((change/do),2) print("How would you like to have your change",(s),"cents \n OR \n",p,'pennies \n OR \n"',n,"nickels \n OR \n",d,"dimes \n OR \n",q,"quarters \n OR \n",de,"dollars") elif cost==amount: print("Thanks for your purchase \n change left=0")''' #-Print hex oct...... '''number=int(input()) width = len('{:b}'.format(number)) for i in range(1,number+1): print(str.rjust(str(i),width),str.rjust(str(oct(i)[2:]),width),str.rjust(str(hex(i).upper()[2:]),width),str.rjust(str(bin(i)[2:]),width))
true
b2b10777497bf79f6353bd04ac19ddb0d69fc281
0x0all/coding-challenge-practices
/python-good-questions/reverse_vowels.py
542
4.28125
4
""" The Problem: Write a function to reverse the vowels in a given string Example: input -> output "hello elephant" -> "halle elophent" "abcde" -> "ebcda" "abc" -> "abc" """ def reverse_vowels(s): vowels = 'aeiou' res = list(s) pos = [index for index, char in enumerate(s) if char in vowels] reversed_pos = pos[::-1] for index in range(len(pos)): res[pos[index]] = list(s)[reversed_pos[index]] return ''.join(res) if __name__ == '__main__': print reverse_vowels("hello elephant")
true
d8b0261cbd5a4534ef7012794164d4c063cc2ecc
Shilla-crypto/Simple-BMI-calculator
/app.py
1,638
4.28125
4
import datetime print('Hello world!') print('*' * 25) print("Python-3.7.3") print("*" * 25) def print_python(): print("__") print("L"), print("__") print("I"), print("__") print("N"), print("__") print("U"), print("__") print("X"), print("__") print_python() now = datetime.datetime.now() if now.hour < 12: print("Good Morning!") else: if 12 <= now.hour < 17: print("Good Afternoon!") else: if now.hour >= 17: print("Good Evening!") name = input("Hi! What's your name? ") colour = input("What's your favourite colour? ") print(name.capitalize() + " likes " + colour.casefold()) birth_year = input("What's your birth year? ") age = now.year - int(birth_year) print(name.capitalize() + " is " + str(age)) if age <= 12: print(name.capitalize() + " is a child~ ") else: if 12 < age <= 18: print(name.capitalize() + " is a teenager~ ") else: if 18 < age <= 21: print(name.capitalize() + " is a young adult~ ") else: if age > 21: print(name.capitalize() + " is an adult~ ") weight_kg = input("How many kg(s) do you weight? ") weight_pound = int(weight_kg) * 2.205 print(str(weight_pound) + " lbs ") height_cm = input("What's your height(cm)? ") height_m = int(height_cm) / 100 print(str(height_m) + " m ") BMI = int(weight_kg) / (height_m * height_m) print("BMI: " + str(BMI)) if BMI < 18.5: print("-Underweight-") else: if 25.0 < BMI < 30.0: print("-Overweight-") else: if BMI >= 30.0: print("-Obese-") else: print("-Healthy-")
false
6736443ed68910ee2e4d2d665da47667024e19c3
vasanth9/10weeksofcp
/basics/classesandobjects.py
1,491
4.21875
4
#classes and objects """ Python is an object oriented programming language. Almost everything in Python is an object, with its properties and methods. A Class is like an object constructor, or a "blueprint" for creating objects. """ class myclass: x=5 p1=myclass() print(p1.x) """ All classes have a function called __init__(), which is always executed when the class is being initiated. Use the __init__() function to assign values to object properties, or other operations that are necessary to do when the object is being created: """ class Person: def __init__(self,name,age): self.name=name self.age=age def printname(self): print("my name is",self.name) p1=Person("vasanth",19) print(p1.name," ",p1.age) p1.printname() #change values p1.age=40 print(p1.age) #del del p1.age print(p1) print(p1.name) """ print(p1.age) gives error age was deleted Traceback (most recent call last): File "classesandobjects.py", line 32, in <module> print(p1.age) AttributeError: 'Person' object has no attribute 'age' """ del p1 #object deletion """ 5 vasanth 19 my name is vasanth 40 <__main__.Person object at 0x7f3d8d87d8e0> vasanth """ #inheritance class Student(Person): def __init__(self, name, age, year): super().__init__(name, age) self.graduationyear = year def welcome(self): print("Welcome", self.name, "to the class of", self.graduationyear) s1=Student("Amulya",18,2038) s1.welcome() #Welcome Amulya to the class of 2038
true
6bc780d508f837ca9c0428fa160e72932b2060c8
futurice/PythonInBrowser
/examples/session1/square.py
837
4.5625
5
# Let's draw a square on the canvas import turtle ##### INFO ##### # Your goal is to make the turtle to walk a square on the # screen. Let's go through again turtle commands. # this line creates a turtle to screen t = turtle.Turtle() # this line tells that we want to see a turtle shape t.shape("turtle") # this line moves turtle 100 steps forward t.forward(100) # here the turtle turns 90 degrees to the left t.left(90) # And again turtle moves forward t.forward(50) ##### EXERCISE ##### # What do you need to add to have the turtle walk a square # and return where he started? # TIP: you can always hit 'Run' to check what you're about to draw. # add code here: ##### Additional exercise ##### # how would you need to change the commands to have the # turtle draw a diamond (square with tip towards the top) instead?
true
14207390dc1852453b97d8922b1f8b3607f26e64
futurice/PythonInBrowser
/examples/session1/wall.py
998
4.46875
4
# Goal: help the turtle to find a hole in the wall # We need to remember to import a turtle every time we want # to use it. import turtle ##### INFO ##### # The following code draws the wall and the target. You can # look at the code but to get to the actual exercise, scroll # down. # Here we create a wall to the middle of the screen wall = turtle.Turtle() wall.hideturtle() wall.speed("fastest") wall.width(4) wall.penup() wall.setx(100) wall.sety(110) wall.pendown() wall.sety(-500) wall.penup() wall.sety(140) wall.pendown() wall.sety(500) wall.penup() wall.right(90) wall.forward(420) wall.setx(200) # create a red dot wall.dot(20, "red") # here we create new turtle, with name Joe joe = turtle.Turtle() joe.shape("turtle") # joe is taking a stroll here joe.right(120) joe.forward(100) joe.right(90) joe.forward(50) ##### EXERCISE ##### # Hit 'Run' and see where Joe is about to go. # What do you need to add to have Joe walk to the red dot? # Don't touch the wall! # add code here:
true
5f66bea9207f8a7149844204245dc09345a636aa
futurice/PythonInBrowser
/examples/session3/function.py
2,912
4.8125
5
# Computing with functions import turtle t = turtle.Turtle() ##### INFO ##### # Fucntions can be used for computing things. # # As an example, let's consider computing an area of a # circle. You may remember form a math class that the area # of a circle is computed by multiplying the radius of the # circle by itself and by the number pi. # # Pi is a mathematical constant. It's approximate value is # below: pi = 3.14159265359 # We can compute the area of a circle with radius of 15 as # follows: area15 = pi * 15 * 15 t.circle(15) print 'Area of circle with radius 15 is ' + str(area15) # Area of a bit larger circle that has radius 22 is: area22 = pi * 22 * 22 t.circle(22) print 'Area of circle with radius 22 is ' + str(area22) ##### EXERCISES ##### ##### EXERCISE 1 ##### # What is the area of a circle that has radius of 30? ##### EXERCISE 2 ##### # Let's define a function for computing the area of a # circle: def circle_area(radius): return pi * radius * radius # "return" means that the function finishes execution and # the value of the expression after the "return" is computed # and passed out of the function back to the program that # called the function. # # The circle_area function, which we just defined above, # takes one parameter called radius. We need to specify a # value for the parameter by writing the value in # parenthesis after the function name like this: # circle_area(15). In this example, the radius variable in # the function will be 15 when the function is executed. # # We can use the function to compute the area of circle with # radius 15 (again) and assign the returned value to a # variable called area15_with_function, and the print its # value: area15_with_function = circle_area(15) print 'Area of circle with radius 15 computed by a function is ' + str(area15_with_function) # 1. Check that the value you got here is the same as the # first value we computed in this exercise. They should be # the same because they both are the area of a circle with # radius 15. # 2. Compute the area of circle with radius 22 using the # function. # 3. Compute the area of circle with radius 30 using the # function. ##### ADDITIONAL EXERCISE ##### # Functions can also manipulate strings. This function # counts the number of vowels in a text string. def count_vowels(text): count = 0 for letter in text: if letter.lower() in u"aeiouyöä": count = count + 1 return count # For example, the following code will count the number of # vowels in the word "Python". Remove the comment mark from # the line below. # # print 'Number of vowels in the word "Python": ' + str(count_vowels("Python")) # 1. Can you come up the words that contain 5 vowels? What # about 6 or even more? # 2. Write a function that counts the number of consonants # (letters that are not vowels). Try to come up with words # that contain as many consonants as possible.
true
35c92a9c66af8bcf6ee2eeec1eb9f3743e375091
ShaneKoNaung/Python-practice
/stack-and-queue/linked_list_queue.py
1,222
4.25
4
''' implementing queue using linked-list''' class LinkedListQueue(object): class Node(object): def __init__(self, data, next=None): self._data = data self._next = next def __init__(self): self._head = None self._tail = None self._size = 0 def __len__(self): ''' return the number of element in the queue''' return self._size def is_empty(self): ''' return True if the queue is emtpy''' return self._size == 0 def first(self): ''' return the first element in the queue ''' return self._head._data def dequeue(self): ''' remove the first element in the queue ''' if self.is_empty(): raise IndexError("queue is empty") answer = self._head._data self._head = self._head._next self._size -= 1 if self.is_empty(): self._tail = None return answer def enqueue(self, e): ''' add an element at the end of the queue''' node = self.Node(e) if self.is_empty(): self._head = node else: self._tail._next = node self._tail = node self._size += 1
true
2f9976e9ae634c5d370e0a45e4484a9c63e7d363
ShaneKoNaung/Python-practice
/stack-and-queue/linked_list_stack.py
1,171
4.125
4
''' Implementation of stack using singly linked list ''' class LinkedListStack(object): class Node(object): def __init__(self, data, next=None): self._data = data self._next = next def __init__(self): ''' create an empty stack ''' self._head = None self._size = 0 def __len__(self): ''' return Number of elements in the list ''' return self._size def is_empty(self): ''' return True if the list is empty''' return self._size == 0 def push(self, e): ''' add element at the top of the stack ''' self._head = self.Node(e, self._head) self._size += 1 def top(self): ''' return the element at the top of the stack''' if self.is_empty(): raise IndexError("Stack is empty") else: return self._head._data def pop(self): ''' remove and return the element at teh top of the stack''' if self.is_empty(): raise IndexError("stack is empty") answer = self._head._data self._head = self._head._next self._size -= 1 return answer
true