blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
3a448e5e06a0567d8e94364228315a05e77f3a3f
KostadinHamanov/HackBG-Programming101-3
/week03/2-Retrospective/Fractions_test.py
1,119
3.921875
4
import unittest from fractions import Fraction class FractionTest(unittest.TestCase): def setUp(self): self.a = Fraction(1, 2) self.b = Fraction(2, 4) def test_is_instance(self): self.assertTrue(isinstance(self.a, Fraction)) self.assertTrue(isinstance(self.b, Fraction)) def test_gcd(self): self.assertEqual(self.a.numerator, 1) self.assertEqual(self.b.denominator, 2) def test_str(self): self.assertEqual(str(self.a), "1/2") self.assertEqual(str(self.b), "1/2") def test_repr(self): self.assertEqual(repr(self.a), "Fraction(1, 2)") self.assertEqual(repr(self.b), "Fraction(1, 2)") def test_equals(self): self.assertTrue(self.a == self.b) def test_addition(self): self.assertEqual(self.a + self.b, 1) def test_substraction(self): self.assertEqual(self.a - self.b, 0) def test_multiplication(self): self.assertEqual(self.a * self.b, 1/4) def test_division(self): self.assertEqual(self.a / self.b, 1) if __name__ == '__main__': unittest.main()
0b30f11faa64486634310a93db3aee9d47ecc71c
skaspy/pythonCollection
/amount_of_words_file.py
152
4
4
# Counting the amount of words in a text file file = open(input('File name: '), 'r') text = file.read() output = text.split() print(len(output))
6f5d10a2a589fa77aff58b35a46432256f58f203
jamiejamiebobamie/Herd_Immunity
/Herd_Immunity_Project/logger.py
5,563
3.90625
4
class Logger(object): ''' Utility class responsible for logging all interactions of note during the simulation. _____Attributes______ file_name: the name of the file that the logger will be writing to. _____Methods_____ __init__(self, file_name): write_metadata(self, pop_size, vacc_percentage, virus_name, mortality_rate, basic_repro_num): - Writes the first line of a logfile, which will contain metadata on the parameters for the simulation. log_interaction(self, person1, person2, did_infect=None, person2_vacc=None, person2_sick=None): - Expects person1 and person2 as person objects. - Expects did_infect, person2_vacc, and person2_sick as Booleans, if passed. - Between the values passed with did_infect, person2_vacc, and person2_sick, this method should be able to determine exactly what happened in the interaction and create a String saying so. - The format of the log should be "{person1.ID} infects {person2.ID}", or, for other edge cases, "{person1.ID} didn't infect {person2.ID} because {'vaccinated' or 'already sick'}" - Appends the interaction to logfile. log_infection_survival(self, person, did_die_from_infection): - Expects person as Person object. - Expects bool for did_die_from_infection, with True denoting they died from their infection and False denoting they survived and became immune. - The format of the log should be "{person.ID} died from infection" or "{person.ID} survived infection." - Appends the results of the infection to the logfile. log_time_step(self, time_step_number): - Expects time_step_number as an Int. - This method should write a log telling us when one time step ends, and the next time step begins. The format of this log should be: "Time step {time_step_number} ended, beginning {time_step_number + 1}..." - STRETCH CHALLENGE DETAILS: - If you choose to extend this method, the format of the summary statistics logged are up to you. At minimum, it should contain: - The number of people that were infected during this specific time step. - The number of people that died on this specific time step. - The total number of people infected in the population, including the newly infected - The total number of dead, including those that died during this time step. ''' def __init__(self, file_name): self.file_name = file_name self.saved = 0 def write_metadata(self, pop_size, vacc_percentage, virus_name, mortality_rate, basic_repro_num): with open(self.file_name, "w+") as f: f.write(str(pop_size) + " " + str(vacc_percentage) + " " + str(virus_name) + " " + str(mortality_rate) + " " + str(basic_repro_num) + " \n") f.closed def log_interaction(self, person1, person2, did_infect=None, person2_vacc=None, person2_sick=None): with open(self.file_name, "a") as f: if did_infect == True: f.write(str(person1._id) +" infects " + str(person2._id) + ".\n") elif did_infect == False and person2_vacc != True and person2_sick == None: f.write(str(person1._id) +" does not infect " + str(person2._id) + ".\n") elif person2_vacc == True: f.write(str(person1._id) + " does not infect " + str(person2._id) + ", because he is vaccinated.\n") self.saved += 1 elif person2_sick != None: f.write(str(person1._id) + " does not infect " + str(person2._id) + ", because he is already infected.\n") f.closed def log_time_step(self, time_step_number): next_time_step = time_step_number + 1 with open(self.file_name, "a") as f: f.write("Time step " + str(time_step_number) + " ending, beginning time step " + str(next_time_step) + "...\n") f.closed def log_death(self, person): with open(self.file_name, "a") as f: f.write(str(person._id) + " has died.\n") f.closed def log_survivor(self, person): with open(self.file_name, "a") as f: f.write(str(person._id) + " survived and is now vaccinated!\n") f.closed def master_stats(self, NumDead, NumSurvived, TotalVacc, TotalInfected, NewlyInfected, LivingPop): with open(self.file_name, "a") as f: f.write("# Killed by Contagion: " + str(NumDead) + ", # Lived through the Virus: " + str(NumSurvived) + ", # Vaccinated: " + str(TotalVacc) + ", # of INSTANCES Someone was Saved by being Vaccinated: " + str(self.saved) + ", Total # Infected by Virus Overall: " + str(TotalInfected) + ", # Newly-Infected: " + str(NewlyInfected) + ", The # of People Living: " + str(LivingPop) + "\n") f.closed #self.logger.master_stats(self.died, self.saved, self.total_infected, len(self.newly_infected), self.uninfected, (len(self.population) - self.dead)) # NOTE: Stretch challenge opportunity! Modify this method so that at the end of each time # step, it also logs a summary of what happened in that time step, including the number of # people infected, the number of people dead, etc. You may want to create a helper class # to compute these statistics for you, as a Logger's job is just to write logs!
83d63125b3c9cfaf26037b1a0736d8ebf9032701
nguy2261/portfolio
/PythonProject/gradeAnalyzer.py
2,679
3.75
4
from os import path import math import sys def openfile(): fname = input("Enter filename: ") count = 0 while not path.isfile(fname) and count < 2: count += 1 fname = input("File not found. Please re-enter: ") if path.isfile(fname): opfile = open(fname,'r') return opfile else: return None #////////////////////////////////////////////////////////////////////////////////////////////////////////// def fieldindex(ifile): #Find the requested fieldname fieldname = input("Enter fieldname: ") count = 0 index = -1 stringname = '' fline = ifile.readline().split(',') check = False while check == False and count < 2: for i in range(len(fline)): if fieldname.lower().replace(" ","") == fline[i].replace(" ",'').replace("\n",'').lower(): check = True index = i stringname = fline[i].strip() break if check == False: count +=1 fieldname = input(fieldname +" does not match any field. Please re-enter: ").lower() try: last = ifile.tell() r = ifile.readline().split(',') if r[index].isalpha() == True: raise TypeError except TypeError: print(fieldname + " is not a numeric field!\nprogram terminated.") sys.exit() ifile.seek(last) return (str(index), stringname) #////////////////////////////////////////////////////////////////////////////////////////////////////////// def stdev(vlist): mean = sum(vlist)/len(vlist) sumstd = 0 for num in vlist: sumstd += (num - mean)**2 std = (sumstd/len(vlist))**0.5 return round(std,2) #////////////////////////////////////////////////////////////////////////////////////////////////////////// def median(vlist): vlist.sort() if len(vlist) % 2 == 0: result = round((float(vlist[len(vlist)//2] + vlist[len(vlist)//2-1]))/2.0,2) else: result = round(vlist[len(vlist)//2]) return round(result,2) #////////////////////////////////////////////////////////////////////////////////////////////////////////// #-----------------------------MAIN------------------------------- f = openfile() #Open the filed if f != None: i = -1 i, field = fieldindex(f) i = int(i) r = f.readline().split(',') data = [] while len(r) > i: data.append(int(r[i])) r = f.readline().split(',') print("\t" + field + " Summary Data") print("________________________________________________________________\n") print("\tNumber of scores: "+str(len(data))) print("\tMean: "+str(round(sum(data)/len(data),2))) print("\tStandard Deviation: " + str(stdev(data))) print("\tMedian: " + str(median(data))) print("\tMin: " + str(min(data))) print("\tMax: " + str(max(data)))
9c45008a1ab3cdb30730fd0d91d5ab615ea29bbf
ivan-yosifov88/python_advanced
/list_as_stack_and_queues_exercise/fashion_boutique.py
364
3.59375
4
clothes_in_box = [int(number) for number in input().split()] capacity = int(input()) rack = 1 clothes_for_current_rack = 0 while clothes_in_box: clothes = clothes_in_box.pop() if clothes_for_current_rack + clothes <= capacity: clothes_for_current_rack += clothes else: clothes_for_current_rack = clothes rack += 1 print(rack)
906848aea8fe923f6779d30ca6f549935bc06fa0
anusharp97/Leetcode
/longestSubarray.py
1,271
3.96875
4
''' 1493. Longest Subarray of 1's After Deleting One Element Given a binary array nums, you should delete one element from it. Return the size of the longest non-empty subarray containing only 1's in the resulting array. Return 0 if there is no such subarray. Example 1: Input: nums = [1,1,0,1] Output: 3 Explanation: After deleting the number in position 2, [1,1,1] contains 3 numbers with value of 1's. Example 2: Input: nums = [0,1,1,1,0,1,1,0,1] Output: 5 Explanation: After deleting the number in position 4, [0,1,1,1,1,1,0,1] longest subarray with value of 1's is [1,1,1,1,1]. Example 3: Input: nums = [1,1,1] Output: 2 Explanation: You must delete one element. Example 4: Input: nums = [1,1,0,0,1,1,1,0,1] Output: 4 Example 5: Input: nums = [0,0,0] Output: 0 ''' def longestSubarray(self, nums: List[int]) -> int: left = 0 maxLen = 0 count = 0 i = 0 n = len(nums) idx = -1 # corner case - if all the elements equal to 1 if sum(nums) == n: return n-1 # sliding window approach while i<n: if nums[i]==0: count += 1 while count>1: if nums[left]==0: count-=1 left+=1 idx = left else: maxLen = max(maxLen,i-idx) i+=1 return maxLen
f13e406886053a811a91494788ad7edd3e21f46e
MinaPecheux/Advent-Of-Code
/2015/Python/day13.py
4,178
4.125
4
### ============================================= ### [ ADVENT OF CODE ] (https://adventofcode.com) ### 2015 - Mina Pêcheux: Python version ### --------------------------------------------- ### Day 13: Knights of the Dinner Table ### ============================================= from itertools import permutations # [ Input parsing functions ] # --------------------------- def parse_input(data): '''Parses the incoming data into processable inputs. :param data: Provided problem data. :type data: str :return: List of placements. :rtype: dict(str, tuple(str, int)) ''' placements = {} for line in data.strip().split('\n'): words = line.split() effect = int(words[3]) if 'lose' in words: effect = -effect person = words[0] neighbor = words[-1].replace('.', '') if person in placements: placements[person].append((neighbor, effect)) else: placements[person] = [ (neighbor, effect) ] return placements # [ Computation functions ] # ------------------------- def compute_configuration_happiness(placements, configuration): '''Computes the total amount of happiness for this configuration (by checking the amount of happiness for every person depending on their two neighbors). :param placements: List of placements. :type placements: dict(str, tuple(str, int)) :param configuration: Placement order for everyone. :type configuration: list(str) :return: Total happiness. :rtype: int ''' n = len(configuration) happiness = 0 for i, person in enumerate(configuration): prev = configuration[(i-1) % n] next = configuration[(i+1) % n] for neighbor, happ in placements[person]: if neighbor == prev or neighbor == next: happiness += happ return happiness def find_optimal_configuration(placements): '''Gets the optimal configuration that maximizes everyone's happiness and calculates its total happiness change. :param placements: List of placements. :type placements: dict(str, tuple(str, int)) :return: Total happiness change. :rtype: int ''' persons = list(placements.keys()) configurations = permutations(persons, len(persons)) return max([ compute_configuration_happiness(placements, configuration) \ for configuration in configurations ]) # [ Base tests ] # -------------- def make_tests(): '''Performs tests on the provided examples to check the result of the computation functions is ok.''' ### Part I placements = parse_input( '''Alice would gain 54 happiness units by sitting next to Bob. Alice would lose 79 happiness units by sitting next to Carol. Alice would lose 2 happiness units by sitting next to David. Bob would gain 83 happiness units by sitting next to Alice. Bob would lose 7 happiness units by sitting next to Carol. Bob would lose 63 happiness units by sitting next to David. Carol would lose 62 happiness units by sitting next to Alice. Carol would gain 60 happiness units by sitting next to Bob. Carol would gain 55 happiness units by sitting next to David. David would gain 46 happiness units by sitting next to Alice. David would lose 7 happiness units by sitting next to Bob. David would gain 41 happiness units by sitting next to Carol.''') assert find_optimal_configuration(placements) == 330 if __name__ == '__main__': # check function results on example cases make_tests() # get input data data_path = '../data/day13.txt' placements = parse_input(open(data_path, 'r').read()) ### PART I solution = find_optimal_configuration(placements) print('PART I: solution = {}'.format(solution)) ### PART II # . add myself to the list with null happiness change for everyone persons = list(placements.keys()) placements['Me'] = [] for p in persons: placements['Me'].append((p, 0)) placements[p].append(('Me', 0)) # . find the new optimal placement solution = find_optimal_configuration(placements) print('PART II: solution = {}'.format(solution))
5d08d5887bdbec0e53503488d9269b79d1c1754e
andres4423/Andres-Arango--UPB
/Numpy/Ejercicio19.py
840
4.4375
4
print("Write a NumPy program to get the unique elements of an array.") print("Expected Output: Original array: [10 10 20 20 30 30] Unique elements of the above array: [10 20 30] Original array: [[1 1] [2 3]] Unique elements of the above array: [1 2 3]") print("Escriba un programa NumPy para obtener los elementos únicos de una matriz.") print("Resultado esperado: Matriz original: [10 10 20 20 30 30] Elementos únicos de la matriz anterior: [10 20 30] Matriz original: [[1 1] [2 3]] Elementos únicos de la matriz anterior: [1 2 3 ]") import numpy as np x = np.array([10, 10, 20, 20, 30, 30]) print("Original array:") print(x) print("Unique elements of the above array:") print(np.unique(x)) x = np.array([[1, 1], [2, 3]]) print("Original array:") print(x) print("Unique elements of the above array:") print(np.unique(x))
6cca3d87639c73171ce363ef55350fd64d95c3a7
MattSi98/1110-Space-Invaders
/a7/Invaders/models.py
14,172
3.8125
4
""" Models module for Alien Invaders This module contains the model classes for the Alien Invaders game. Anything that you interact with on the screen is model: the ship, the laser bolts, and the aliens. Just because something is a model does not mean there has to be a special class for it. Unless you need something special for your extra gameplay features, Ship and Aliens could just be an instance of GImage that you move across the screen. You only need a new class when you add extra features to an object. So technically Bolt, which has a velocity, is really the only model that needs to have its own class. With that said, we have included the subclasses for Ship and Aliens. That is because there are a lot of constants in consts.py for initializing the objects, and you might want to add a custom initializer. With that said, feel free to keep the pass underneath the class definitions if you do not want to do that. You are free to add even more models to this module. You may wish to do this when you add new features to your game, such as power-ups. If you are unsure about whether to make a new class or not, please ask on Piazza. Matthew Simon mls498 Nicholas Robinson nar73 12/3/17 """ from consts import * from game2d import * # PRIMARY RULE: Models are not allowed to access anything in any module other than # consts.py. If you need extra information from Gameplay, then it should be # a parameter in your method, and Wave should pass it as a argument when it # calls the method. class dLine(GPath): """ A class to represent the defense line. """ # GETTERS AND SETTERS (ONLY ADD IF YOU NEED THEM) # INITIALIZER TO CREATE A NEW dLine def __init__(self, points = [0,DEFENSE_LINE,GAME_WIDTH,DEFENSE_LINE], linewidth = 2, linecolor = 'grey'): """ Initializes a GPath object. Parameter points: the two points the line will go between Precondition: list of x/y values like [x1,y1,x2,y2] that are int types Parameter linewidth: the width of the line in pixels Precondition: linewidth is an int Parameter linecolor: the color of the line Precondition: a valid color (RGB,CMYK,colormodel,etc.) """ super().__init__(points = points, linewidth = linewidth, linecolor = linecolor) class Ship(GImage): """ A class to represent the game ship. At the very least, you want a __init__ method to initialize the ships dimensions. These dimensions are all specified in consts.py. You should probably add a method for moving the ship. While moving a ship just means changing the x attribute (which you can do directly), you want to prevent the player from moving the ship offscreen. This is an ideal thing to do in a method. You also MIGHT want to add code to detect a collision with a bolt. We do not require this. You could put this method in Wave if you wanted to. But the advantage of putting it here is that Ships and Aliens collide with different bolts. Ships collide with Alien bolts, not Ship bolts. And Aliens collide with Ship bolts, not Alien bolts. An easy way to keep this straight is for this class to have its own collision method. However, there is no need for any more attributes other than those inherited by GImage. You would only add attributes if you needed them for extra gameplay features (like animation). If you add attributes, list them below. LIST MORE ATTRIBUTES (AND THEIR INVARIANTS) HERE IF NECESSARY _dead = determines if the ship is dead[Boolean] """ # GETTERS AND SETTERS (ONLY ADD IF YOU NEED THEM) def getX(self): """ Returns the ship's x attribute value. """ return self.x def getY(self): """ Returns the ship's y attribute value. """ return self.y def setDead(self): self._dead = True def getDead(self): return self._dead # INITIALIZER TO CREATE A NEW SHIP def __init__(self, x = GAME_WIDTH/2 , y = SHIP_HEIGHT/2 + SHIP_BOTTOM , source = 'ship.png',dead=False): """ Initilializes a ship object. Parameter x: the x value for the center of the ship Precondition: x is a float or an int Parameter y: the y value for the center of the ship Precondition: y is a float or an int Parameter source: the image file for the ship - what it looks like Precondition: source is a valid png file Parameter dead: boolean that tells you if the ship is dead or not Precondition: dead is a boolean Parameter width: the width of the ship Precondition: width is a float Parameter height: the height of the ship Precondition: height is a float """ super().__init__(x = x , y = y , width = SHIP_WIDTH , height = SHIP_HEIGHT, source = source) self._dead = dead # METHODS TO MOVE THE SHIP AND CHECK FOR COLLISIONS def collides(self,bolt): """ Returns: True if the bolt was fired by the alien and collides with this ship. Parameter bolt: The laser bolt to check Precondition: bolt is of class Bolt """ fourCorners = bolt.findBoltCorners() for x in fourCorners: if self.contains(x) and not bolt.getSBolt(): return True def moveShipRight(self, movement): """ This method moves the ship right by changing its x attribute value. Parameter movement: the amount to move the ship Precondition: movment is an int (plus or minus SHIP_MOVEMENT) """ self.x = self.x + movement if self.x + SHIP_WIDTH/2 > GAME_WIDTH: self.x = GAME_WIDTH - SHIP_WIDTH/2 def moveShipLeft(self, movement): """ This method moves the ship left by changing its x attribute value. Parameter movement: the amount to move the ship Precondition: movment is an int (plus or minus SHIP_MOVEMENT) """ self.x = self.x - movement if self.x - SHIP_WIDTH/2 < 0: self.x = 0 + SHIP_WIDTH/2 class Alien(GImage): """ A class to represent a single alien. At the very least, you want a __init__ method to initialize the alien dimensions. These dimensions are all specified in consts.py. You also MIGHT want to add code to detect a collision with a bolt. We do not require this. You could put this method in Wave if you wanted to. But the advantage of putting it here is that Ships and Aliens collide with different bolts. Ships collide with Alien bolts, not Ship bolts. And Aliens collide with Ship bolts, not Alien bolts. An easy way to keep this straight is for this class to have its own collision method. However, there is no need for any more attributes other than those inherited by GImage. You would only add attributes if you needed them for extra gameplay features (like giving each alien a score value). If you add attributes, list them below. LIST MORE ATTRIBUTES (AND THEIR INVARIANTS) HERE IF NECESSARY """ # GETTERS AND SETTERS (ONLY ADD IF YOU NEED THEM) def moveLeft(self): """ This method moves the alien left by changing its x attribute value, determined by the const ALIEN_H_WALK. """ self.x-= ALIEN_H_WALK def moveDown(self): """ This method moves the alien down by changing its y attribute value, determined by the const ALIEN_V_WALK. """ self.y-=ALIEN_V_WALK def moveRight(self): """ This method moves the alien right by changing its x attribute value, determined by the const ALIEN_H_WALK. """ self.x+=ALIEN_H_WALK def getX(self): """ Returns the x attribute value of the alien. """ return self.x def getY(self): """ Returns the y attribute value of the alien. """ return self.y # INITIALIZER TO CREATE AN ALIEN def __init__(self, x = (ALIEN_H_SEP + ALIEN_WIDTH/2) , y = (GAME_HEIGHT - (ALIEN_CEILING + ALIEN_HEIGHT/2)), source = 'alien1.png'): """ Initiliaizes an alien object. Parameter x: the x value for the center of the alien Precondition: x is a float or an int Parameter y: the y value for the center of the alien Precondition: y is a float or an int Parameter source: the image file for the alien - what it looks like Precondition: source is a valid png file Parameter width: the width of the alien Precondition: width is a float Parameter height: the height of the alien Precondition: height is a float """ super().__init__(x = x , y = y , width = ALIEN_WIDTH, height = ALIEN_HEIGHT, source = source) # METHOD TO CHECK FOR COLLISION (IF DESIRED) def collides(self,bolt): """ Returns: True if the bolt was fired by the player and collides with this alien Parameter bolt: The laser bolt to check Precondition: bolt is of class Bolt """ fourCorners = bolt.findBoltCorners() for x in fourCorners: if self.contains(x) and bolt.getSBolt(): return True class Bolt(GRectangle): """ A class representing a laser bolt. Laser bolts are often just thin, white rectangles. The size of the bolt is determined by constants in consts.py. We MUST subclass GRectangle, because we need to add an extra attribute for the velocity of the bolt. The class Wave will need to look at these attributes, so you will need getters for them. However, it is possible to write this assignment with no setters for the velocities. That is because the velocity is fixed and cannot change once the bolt is fired. In addition to the getters, you need to write the __init__ method to set the starting velocity. This __init__ method will need to call the __init__ from GRectangle as a helper. You also MIGHT want to create a method to move the bolt. You move the bolt by adding the velocity to the y-position. However, the getter allows Wave to do this on its own, so this method is not required. INSTANCE ATTRIBUTES: _velocity: The velocity in y direction [int or float] _SBolt: determines whether the bolt is from the ship LIST MORE ATTRIBUTES (AND THEIR INVARIANTS) HERE IF NECESSARY """ def getBoltVelocity(self): """ Returns the _velocity attribute value of the bolt. """ return self._velocity def moveBoltShip(self): """ This method moves a bolt upward (because it was fired from the ship), it does this by changing the y attribute value of the bolt. """ self.y += self._velocity def moveBoltAlien(self): """ This method moves a bolt downward (because it was fired from the aliens), it does this by changing the y attribute value of the bolt. """ self.y-=self._velocity def getSBolt(self): """ Returns the _SBolt attribute value of the bolt. """ return self._SBolt def getY(self): """ Returns the y attribute value of the bolt. """ return self.y def getX(self): """ Returns the x attribute value of the bolt. """ return self.x # INITIALIZER TO SET THE VELOCITY def __init__(self,x,y,ship,width=BOLT_WIDTH,height=BOLT_HEIGHT, speed=BOLT_SPEED, lcolor = 'red',fcolor= 'red'): """ Inilitalizes a bolt object. Parameter x: the x value for the center of the bolt Precondition: x is a float or an int Parameter y: the y value for the center of the bolt Precondition: y is a float or an int Parameter ship: determines if the ship shot the bolt(True) Precondition: Boolean Parameter width: the width of the bolt Precondition: width is a float Parameter height: the height of the bolt Precondition: height is a float Parameter speed: how many pixels the bolt will travel each update Precondition: speed is an int Parameter lcolor: the line color Precondition: a valid color (RGB,CMYK,colormodel,etc.) Parameter fcolor: the fill color Precondition: a valid color (RGB,CMYK,colormodel,etc.) """ super().__init__(x=x,y=y,width =width, height = height, fillcolor=fcolor) self._SBolt = ship self.linecolor = 'red' self._velocity = speed # ADD MORE METHODS (PROPERLY SPECIFIED) AS NECESSARY def findBoltCorners(self): """ Returns the four corners of a bolt object as a list of the tuples of (x,y). ie [(x1,y1),(x2,y2),(x3,y3),(x4,y4)] This method finds the four corners of a bolt object in coordinate form (x,y). """ rightX = self.getX() + BOLT_WIDTH/2 leftX = self.getX() - BOLT_WIDTH/2 topY = self.getY() + BOLT_HEIGHT/2 botY = self.getY() - BOLT_HEIGHT/2 # corners are (rightX,topY), (leftX,topY), (rightX,boty), (leftX, botY) corners = [] topRight =(rightX, topY) topLeft = (leftX, topY) botRight = (rightX, botY) botLeft = (leftX, botY) corners.append(topRight) corners.append(topLeft) corners.append(botRight) corners.append(botLeft) return corners # IF YOU NEED ADDITIONAL MODEL CLASSES, THEY GO HERE
9aed0e027cf4075bc17dec9df3230396d1251d18
aayushmanntiwari/-AutomationwithPython
/Functions/Add.py
772
3.515625
4
import openpyxl as xl # Add function def Add(): wb = xl.load_workbook('') # write the spreedsheet(.xlsx) file name here you to Update sheet = wb['Sheet1'] y = int(input("Enter the targeted row where value start: ")) z = int(input("Enter the target column where these value belong: ")) m = int(input("Enter where you want to import this Updated Value: ")) for row in range(y, sheet.max_row + 1): x = int(input(f"Enter the value you want to Add for Row {row} with the origianl value: ")) cell = sheet.cell(row, z) corrected_cell_price = cell.value + x corrected_cell = sheet.cell(row,m) corrected_cell.value = corrected_cell_price wb.save('') # You can save the file formate with any name
67f8d75315e3015d56024e9651be2c5fb347e214
janlee1020/Python
/shapeCalculator.py
2,086
4.3125
4
#shapeCalculator.py from math import pi def rectArea(length, width): area=length * width return area def circleArea(radius): area=pi*radius*radius return area def welcome(): print("Welcome to the shape calculator!") name=input("What is your name? ") return name def askDimension(dimension): value = float(input("what is the " + dimension +"? ")) return value def triangleArea(altitude, base): x=altitude y=base area=(1/2)*altitude*base return area def squareArea(side): s=length area=s**2 return area def main(): name = welcome() print(name+", ", end="") x = askDimension("length") #enter 4 y = askDimension("width") #enter 3 print("The area of the rectangle is " + str(rectArea(x,y))) rad = askDimension("radius") #enter 10 a= circleArea(rad) print("The area of the circle is {0:0.5} sq. cm.".format(a)) print("The area of the triangle is " + str(triangleArea(x,y))) print("The area of the square is " + str(rectArea(x, x))) #Compute and print area of a square from dimList dimList=[5, 3, 7, 2] sqarea=int(dimList[0]) ** 2 print("The area of the square from dimList is ", sqarea) #Compute and print area of a circle from dimList circarea= (int(dimList[1])**2)*pi print("The area of the circle from dimList is ", circarea) #Compute and print area of a rectangle from dimList recarea=int(dimList[2])* int(dimList[3]) print("The area of the rectangle from dimList is ", recarea) main() ##Output ##Welcome to the shape calculator! ##What is your name? Janet ##Janet, what is the length? 4 ##what is the width? 3 ##The area of the rectangle is 12.0 ##what is the radius? 10 ##The area of the circle is 314.16 sq. cm. ##The area of the triangle is 6.0 ##The area of the square is 16.0 ##The area of the square from dimList is 25 ##The area of the circle from dimList is 28.274333882308138 ##The area of the rectangle from dimList is 14
dcc8400d291da0c1f1d18801e9997c1858cf3454
merlin0509/MiniProjects01
/hangman.py
671
3.828125
4
def find(s, ch): return [i for i, ltr in enumerate(s) if ltr == ch] def hangman(): word="secret" turns=len(word) guess=["_" for i in range(turns)] print(" You have ",turns,"turns") print("Start guessing the word*****") while(turns>0): uchar=input("Enter guess \n") turns=turns-1 if uchar not in word: print("The guess is wrong") else: for i in find(word,uchar): guess[i] = uchar s = '' for i in guess: s+=i print('The guessed word is ', s) if s==word: print('You got the word right !!') break if(turns==0): print('out of turns sucker !') hangman()
945ab29af0a66c1f38423affec72e58e22e2f778
minwinmin/Atcoder
/ABC175/B.py
1,248
3.671875
4
""" 三角形の成立条件 https://mathtrain.jp/seiritu 三角形の成立条件(存在条件):三辺の長さが a,b,c である三角形が存在する必要十分条件は, a+b>c かつ b+c>a かつ c+a>b http://physics.thick.jp/Mathematics_A/Section5/5-3.html abs(L[i]-L[j])<L[k]<L[i]+L[j] """ def listExcludedIndices(data, indices=[]): return [x for i, x in enumerate(data) if i not in indices] N = int(input()) L = list(map(int, input().split())) """ 重複なし組み合わせの導出例 https://qiita.com/BlueSilverCat/items/77f4e11d3930d7b8959b がとても参考になった """ n = len(L) c = 0 result = [] for i in range(n): for j in range(i+1, n): for k in range(j+1, n): if L[i]!=L[j] and L[j]!=L[k] and L[i]!=L[k]: if L[i]+L[j]>L[k] and L[j]+L[k]>L[i] and L[i]+L[k]>L[j]: #print(L[i], L[j], L[k]) c += 1 print(c) """ #memo import sys # B - Making Triangle import itertools N = int(input()) L = list(map(int, input().split())) combis = list(itertools.combinations(L, 3)) ans = 0 for combi in combis: a, b, c = combi if a != b and b != c and c != a: if a + b > c and b + c > a and c + a > b: ans += 1 print(ans) """
0de144e280a53a01b0ffe4eb0bed3dd559fd5b27
GigaVision/CrowdCountingTools
/cc_evaluate_tools.py
1,365
3.734375
4
import math ''' Tool to calculate 3 metrics of crowd counting results. The crowd distribution of this crowd counting task is represented by crowd number vector. First, the whole image will be divided into 1x1, 4x4, 8x8 blocks. After that, the number of human in each block will be estimated. Finally, the crowd number vector is generated from the estimate human number of these blocks. Input: order: image division order. et: crowd number vector predicted by model. It is a vector of size order * order. gt: ground truth crowd number vector. It is a vector of size order * order. Return: 3 evaluation results: mae, mse, evaluate_error ''' def evaluate(et, gt, order): mae = 0.0 mse = 0.0 evaluate_error = 0.0 for i in range(order): for j in range(order): mae += abs(et[i][j] - gt[i][j]) mse += (et[i][j] - gt[i][j]) * (et[i][j] - gt[i][j]) evaluate_error += _evaluate_error_patch(et[i][j], gt[i][j]) mae = mae / math.pow(order, 2) mse = math.sqrt(mse / math.pow(order, 2)) return mae, mse, evaluate_error def _evaluate_error_patch(et, gt): # calculate error of each little box if abs(gt - 0) < 0.0005: if et > 1: d = 1 else: d = 0 else: d = min(abs(et - gt) / gt, 1) return d
0ed4a67a26ddd7b7182f0d3fcfb5a9d42f740fc1
jeffreytzeng/Dcoder
/easy/003. Learning User Input with Natural Numbers/sum_numbers.py
90
3.8125
4
integer = int(input()) total = 0 for i in range(1, integer+1): total += i print(total)
0e8054f2045c8d185646e8969b1b94c9f13d1041
Nahida-Jannat/testgit
/bubble_sort.py
730
4.125
4
# Bubble Sort Implementation # n = 5 # for i in range(0, n): # print('Loop 1: i-%d\n-----------' % i) # for j in range(0, n-i-1): # print('j-', j) def bubble_sort(data_list): n = len(data_list) for i in range(0, n): # n=5 (0, 5) --> 0, 1, 2, 3, 4 print('Loop 1: i-%d\n-----' %i) for j in range(0, n-i-1): print('j-', j) if data_list[j] > data_list[j+1]: # Swap temp = data_list[j] data_list[j] = data_list[j+1] data_list[j+1] = temp if __name__ == '__main__': data_list = [5,7,6,4,2] bubble_sort(data_list) print('Bubble Sorted List:', data_list)
6b1868571e93d4604d9e57f7b0d01f3b75f83e89
nishantchaudhary12/Starting-with-Python
/Chapter 8/gasPrices.py
3,506
3.734375
4
#Gas Prices def average_price_per_year(): file = open("GasPrices.txt", "r") price = file.readline() price = price.strip('\n') price_dict = dict() while price != '': price_list = price.split(':') year = price_list[0].split('-') if year[2] in price_dict: price_dict[year[2]].append(float(price_list[1])) else: price_dict[year[2]] = [float(price_list[1])] price = file.readline() price = price.strip('\n') print('Average price per year: ') for each in price_dict: average = sum(price_dict[each])/len(price_dict[each]) print(each, ':', format(average, '.2f')) file.close() def average_price_per_month(): file = open("GasPrices.txt", "r") price = file.readline() price = price.strip('\n') price_dict = dict() while price != '': price_list = price.split(':') date = price_list[0].split('-') month_year = date[0] + '-' + date[2] if month_year in price_dict: price_dict[month_year].append(float(price_list[1])) else: price_dict[month_year] = [float(price_list[1])] price = file.readline() price = price.strip('\n') print('\n') print('Average price per month: ') for each in price_dict: average = sum(price_dict[each])/len(price_dict[each]) print(each, ':', format(average, '.2f')) file.close() def highest_and_lowest_per_year(): file = open("GasPrices.txt", "r") price = file.readline() price = price.strip('\n') price_dict = dict() while price != '': price_list = price.split(':') year = price_list[0].split('-') if year[2] in price_dict: price_dict[year[2]].append(float(price_list[1])) else: price_dict[year[2]] = [float(price_list[1])] price = file.readline() price = price.strip('\n') print('\n') print('Maximum and Minimum price per year: ') for each in price_dict: print(each) print('Maximum:', max(price_dict[each])) print('Minimum:', min(price_dict[each])) file.close() def highest_to_lowest(): file = open("GasPrices.txt", "r") price = file.readline() price = price.strip('\n') price_dict = dict() while price != '': price_list = price.split(':') price_dict[price_list[0]] = (float(price_list[1])) price = file.readline() price = price.strip('\n') price_dict_sorted = sorted(price_dict.items(), key=lambda x:x[1]) file.close() file = open("highest_to_lowest.txt", "w") for key, value in price_dict_sorted: file.write('%s : %s\n' % (key, value)) file.close() def lowest_to_highest(): file = open("GasPrices.txt", "r") price = file.readline() price = price.strip('\n') price_dict = dict() while price != '': price_list = price.split(':') price_dict[price_list[0]] = (float(price_list[1])) price = file.readline() price = price.strip('\n') price_dict_sorted = sorted(price_dict.items(), key=lambda x:x[1] ,reverse=True) file.close() file = open("lowest_to_highest.txt", "w") for key, value in price_dict_sorted: file.write('%s : %s\n' % (key, value)) file.close() def main(): average_price_per_year() average_price_per_month() highest_and_lowest_per_year() highest_to_lowest() lowest_to_highest() main()
9b1472191a7e5334f2e93cb29e2e32c5509f5f75
ShriBuzz/IW-PythonLogic
/Assignment I/Functions/15.py
145
4.03125
4
# Write a Python program to filter a list of integers using Lambda. lis = [2,3,4,1,6] even = list(filter(lambda x: x%2 == 0, lis)) print(even)
2fa1202df4a280fb46cbf6f4c37efcfe097bb268
scimaksim/Python
/tax.py
953
4.4375
4
# ----------------------------------------------------------------------------- # Name: Tip # Purpose: Tip calculator # # Author: Maksim Nikiforov # Date: 09/129/2016 # ----------------------------------------------------------------------------- """ Tip calculator assuming an 8.75% tip rate Prompt the user for the cost of their meal. Print the tip amount and the total cost. """ TAX_RATE = 0.0875 # regional tax rate at the time of calculation Meal_Price_String = input("Enter the price in $: ") Meal_Price = float(Meal_Price_String) # convert string input to a float Sales_Tax = Meal_Price * TAX_RATE # calculate sales tax Sales_Tax = round(Sales_Tax, 2) # round the tax to 2 decimals print("Sales Tax: $", Sales_Tax, sep='') # suppress space separator Total_Cost = Meal_Price + Sales_Tax # calculate total price of meal Total_Cost = round(Total_Cost, 2) print("Total Cost: $", Total_Cost, sep='')
650aab5e0ee73a1ef99735fe82f4f23aea4e8ed1
Jian-jobs/Jian-leetcode_python3
/Solutions/165_ Compare Version Numbers.py
3,187
3.96875
4
''' 165. Compare Version Numbers https://leetcode.com/problems/compare-version-numbers/ Compare two version numbers version1 and version2. If version1 > version2 return 1; if version1 < version2 return -1; otherwise return 0. You may assume that the version strings are: non-empty and contain only digits and the . character. The . character does not represent a decimal point and is used to separate number sequences. For instance, 2.5 is not "two and a half" or "half way to version three", it is the fifth second-level revision of the second first-level revision. You may assume the default revision number for each level of a version number to be 0. For example, version number 3.4 has a revision number of 3 and 4 for its first and second level revision number. Its third and fourth level revision number are both 0. Example 1: Input: version1 = "0.1", version2 = "1.1" Output: -1 Example 2: Input: version1 = "1.0.1", version2 = "1" Output: 1 Example 3: Input: version1 = "7.5.2.4", version2 = "7.5.3" Output: -1 Example 4: Input: version1 = "1.01", version2 = "1.001" Output: 0 Explanation: Ignoring leading zeroes, both “01” and “001" represent the same number “1” Example 5: Input: version1 = "1.0", version2 = "1.0.0" Output: 0 Explanation: The first version number does not have a third level revision number, which means its third level revision number is default to "0" Note: Version strings are composed of numeric strings separated by dots . and this numeric strings may have leading zeroes. Version strings do not start or end with dots, and they will not be two consecutive dots. ''' def compareVersion(self, version1, version2): """ :type version1: str :type version2: str :rtype: int """ # 学学 version1 = [int(val) for val in version1.split(".")] version2 = [int(val) for val in version2.split(".")] if len(version1) > len(version2): min_version = version2 max_version = version1 else: min_version = version1 max_version = version2 # Compare up to min character for i in range(len(min_version)): if version1[i] > version2[i]: return 1 elif version1[i] < version2[i]: return -1 if len(version1) == len(version2): return 0 for j in range(i + 1, len(max_version)): if max_version[j] > 0: return 1 if max_version == version1 else - 1 return 0 class Solution: def compareVersion(self, version1: str, version2: str) -> int: s1 = version1.split('.') s2 = version2.split('.') # Ailgning them if len(s1) >= len(s2): s2.extend('0' * (len(s1) - len(s2))) else: s1.extend('0' * (len(s2) - len(s1))) c = [int(s1[i]) - int(s2[i]) for i in range(len(s1))] for item in c: if item < 0: return -1 elif item > 0: return 1 return 0 # refernece: # https://leetcode.com/problems/compare-version-numbers/discuss/311157/Python-Easy-to-Understand-O(n) # https://leetcode.com/problems/compare-version-numbers/discuss/51008/Concise-Python-code
c70e3556de2243ce710cc0e31b2e035e324b2371
Minkov/python-oop-2021-02
/inheritance/lab/stack.py
420
3.71875
4
class Stack: def __init__(self): self.data = [] def push(self, value): self.data.append(value) def pop(self): return self.data.pop() def peek(self): return self.data[-1] def is_empty(self): return len(self.data) == 0 def __repr__(self): return f"[{', '.join(reversed(self.data))}]" ss = Stack() [ss.push(x) for x in range(1, 10)] print(ss)
f4d6433206f3ba0dfdea1af14baea7b98f58b596
JuDa-hku/ACM
/leetCode/116PopulatingNextRightPointersinEachNode.py
668
3.859375
4
# Definition for binary tree with next pointer. # class TreeLinkNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None # self.next = None class Solution: # @param root, a tree link node # @return nothing def connect(self, root): if not root: return None while root: tmp = root if tmp.left: while tmp: tmp.left.next = tmp.right if tmp.next: tmp.right.next = tmp.next.left tmp = tmp.next root = root.left
63322cf6e40e4efbf21c9116d11f5ffa24deb3dd
glushenkovIG/PythonTasks
/class/Poly-2.py
17,293
3.609375
4
import copy import copy class Fraction: def __init__(self, x = '', y = 0): if type(x) == Fraction: self.a = x.a self.b = x.b elif x == '' and y == 0: self.a = 0 self.b = 1 elif y == 0: if '/' in str(x): self.a, self.b = list(map(int, x.split('/'))) elif ' ' in str(x): self.a, self.b = list(map(int, x.split())) else: self.a = int(x) self.b = 1 else: self.a = x self.b = y self.reduce() def __str__(self): self.reduce() if self.b != 1: return str(str(self.a) + '/' + str(self.b)) return str(self.a) def reduce(self): a, b = self.a, self.b while b: a, b = b, a % b self.a //= a self.b //= a def __lt__(self, other): if type(other) == Fraction: if self.b < 0: self.b = -self.b self.a = -self.a if other.b < 0: other.b = -other.b other.a = -other.a b1, b2 = self.b, other.b a1, a2 = self.a, other.a return a1 * b2 < a2 * b1 elif type(other) == int or type(other) == float: self.reduce() b, a = self.b, self.a return a < other * b def __le__(self, other): if type(other) == Fraction: if self.b < 0: self.b = -self.b self.a = -self.a if other.b < 0: other.b = -other.b other.a = -other.a b1, b2 = self.b, other.b a1, a2 = self.a, other.a return a1 * b2 <= a2 * b1 elif type(other) == int or type(other) == float: self.reduce() b, a = self.b, self.a return a <= other * b def __eq__(self, other): if type(other) == Fraction: if self.b < 0: self.b = -self.b self.a = -self.a if other.b < 0: other.b = -other.b other.a = -other.a b1, b2 = self.b, other.b a1, a2 = int(self.a), int(other.a) return a1 * b2 == a2 * b1 elif type(other) == int or type(other) == float: self.reduce() b, a = self.b, self.a return a == other * b def __ne__(self, other): if type(other) == Fraction: b1, b2 = self.b, other.b a1, a2 = self.a, other.a return a1 * b2 != a2 * b1 elif type(other) == int or type(other) == float: self.reduce() b, a = self.b, self.a return a != other * b def __gt__(self, other): if type(other) == Fraction: b1, b2 = self.b, other.b a1, a2 = self.a, other.a return a1 * b2 > a2 * b1 elif type(other) == int or type(other) == float: self.reduce() b, a = self.b, self.a return a > other * b def __ge__(self, other): if type(other) == Fraction: b1, b2 = self.b, other.b a1, a2 = self.a, other.a return a1 * b2 >= a2 * b1 elif type(other) == int or type(other) == float: self.reduce() b, a = self.b, self.a return a >= other * b def __int__(self): return self.a // self.b def __float__(self): return self.a / self.b def __round__(self, x = 0): return round(self.a / self.b, x) def __pos__(self): return Fraction(+self.a, self.b) def __abs__(self): return Fraction(abs(self.a), abs(self.b)) def __neg__(self): self = Fraction(self) return Fraction(-self.a, self.b) def __add__(self, other): if type(other) == Poly: return NotImplemented elif type(other) == float: return self.a / self.b + other elif type(self) == float: return other.a / other.b + self else: self, other = Fraction(self), Fraction(other) b1, b2 = self.b, other.b a1, a2 = self.a, other.a A = Fraction() A.a, A.b = a1 * b2 + a2 * b1, b1 * b2 return A def __radd__(self, other): if type(other) == Poly: return NotImplemented elif type(other) == float: return self.a / self.b + other elif type(self) == float: return other.a / other.b + self else: self, other = Fraction(self), Fraction(other) b1, b2 = self.b, other.b a1, a2 = self.a, other.a A = Fraction() A.a, A.b = a1 * b2 + a2 * b1, b1 * b2 return A def _iadd__(self, other): if type(other) == float: self = self.a / self.b + other return self elif type(self) == float: self = other.a / other.b + self return self else: self, other = Fraction(self), Fraction(other) b1, b2 = self.b, other.b a1, a2 = self.a, other.a self.a, self.b = a1 * b2 + a2 * b1, b1 * b2 return A def __sub__(self, other): if type(other) == float: return self.a / self.b - other elif type(self) == float: return -other.a / other.b + self else: self, other = Fraction(self), Fraction(other) b1, b2 = self.b, other.b a1, a2 = self.a, other.a A = Fraction() A.a, A.b = a1 * b2 - a2 * b1, b1 * b2 return A def __rsub__(self, other): if type(other) == float: return -self.a / self.b + other elif type(self) == float: return -other.a / other.b + self else: self, other = Fraction(self), Fraction(other) b1, b2 = self.b, other.b a1, a2 = self.a, other.a A = Fraction() A.a, A.b = -a1 * b2 + a2 * b1, b1 * b2 return A def _isub__(self, other): if type(other) == float: self = self.a / self.b - other return self elif type(self) == float: self = -other.a / other.b + self return self else: self, other = Fraction(self), Fraction(other) b1, b2 = self.b, other.b a1, a2 = self.a, other.a self.a, self.b = a1 * b2 - a2 * b1, b1 * b2 return A def __mul__(self, other): if type(other) == float: return self.a / self.b * other other = Fraction(other) A = (Fraction(self.a * other.a, self.b * other.b)) A.reduce() return A def __rmul__(self, other): if type(other) == float: return self.a / self.b * other self, other = Fraction(self), Fraction(other) A = (Fraction(self.a * other.a, self.b * other.b)) A.reduce() return A def __imul__(self, other): if type(other) == float: return self.a / self.b * other other = Fraction(other) self = (Fraction(self.a * other.a, self.b * other.b)) self.reduce() return self def __truediv__(self, other): if type(other) == float: return self.a / self.b / other other = Fraction(other) A = (Fraction(self.a * other.b, self.b * other.a)) A.reduce() return A def __rtruediv__(self, other): if type(other) == float: return other / (self.a / self.b) self, other = Fraction(self), Fraction(other) A = (Fraction(self.b * other.a, self.a * other.b)) A.reduce() return A def __itruediv__(self, other): if type(other) == float: return self.a / self.b / other other = Fraction(other) self = (Fraction(self.a * other.b, self.b * other.a)) self.reduce() return self class Poly(): def __init__(self, x = [0]): if type(x) in [int, Fraction, float]: self.x = [x] elif type(x) == list: self.x = copy.deepcopy(x) elif type(x) == str: b = [] for elem in x.split(): b.append(eval(elem)) self.x = b elif x == [0]: self.x = [0] elif type(x) == Poly: self.x = copy.deepcopy(x.x) elif type(x) == tuple: self.x = list(x) def __str__(self): A = '' for i in range(len(self.x) - 1, -1, -1): factor = self.x[i] if factor != 0 and factor != 0.0: if factor > 0 and len(A) != 0: A += ' + ' elif len(A) != 0: A += ' - ' factor = -factor if factor != 1 or i == 0: if type(factor) == float: factor = round(factor, 3) if type(factor) == Fraction: frac = factor.a / factor.b if frac == int(frac): factor = int(frac) else: if (i == len(self.x) - 1 or A == '') and frac < 0: factor = -factor factor = '-' + '(' + str(factor) + ')' else: factor = '(' + str(factor) + ')' A += str(factor) if i != 0: A += 'x' for elem in str(i): pow = int(elem) if pow == 2 or pow == 3: A += chr(176 + pow) elif pow != 1: A += chr(8304 + pow) elif pow == 1 and i != 1: A += chr(185) if A != '': return A return '0' def __add__(self, other): poly = self if type(other) in [int, float, Fraction]: poly.x[0] += other elif type(other) == Poly: min_poly = Poly() if len(poly.x) < len(min_poly.x): poly, min_poly = min_poly, poly for i in range(len(min_poly.x) - 1): poly.x[i] += min_poly.x[i] return poly def __radd__(self, other): print(self, other) poly = self if type(other) in [int, float, Fraction]: poly.x[0] += other elif type(other) == Poly: min_poly = Poly() if len(poly.x) < len(min_poly.x): poly, min_poly = min_poly, poly for i in range(len(min_poly.x) - 1): poly.x[i] += min_poly.x[i] return poly def __iadd__(self, other): if type(other) in [int, float, Fraction]: self.x[0] += other elif type(other) == Poly: if len(self.x) < len(other.x): self, other = other, self for i in range(len(other.x) - 1): self.x[i] += other.x[i] return self import sys exec(sys.stdin.read()) import random random.seed(837283918) __count = 0 def TEST(title = ''): global __count __count += 1 print() print('=====================================') print('Подтест ', __count, ':', title) def randInt(): return random.randint(-1000, 1000) def randFloat(): return random.random() * 2000 - 1000 def randFraction(): a = random.randint(-1000, 1000) b = random.randint(-1000, 1000) while b == 0: b = random.randint(-1000, 1000) return Fraction(a, b) def randZero(): return random.choice([0, 0.0, Fraction(0)]) def Zero(): return 0 def randCoeff(genFunc = [randInt, randFloat, randFraction, randZero]): return random.choice(genFunc)() def randIntPoly(n=100): L = [randInt() for j in range(random.randint(1, n))] while L[-1] == 0: L[-1] = randInt() return Poly(L) def randFractionPoly(n=100): L = [randFraction() for j in range(random.randint(1, n))] while L[-1] == 0: L[-1] = randFraction() return Poly(L) def randFloatPoly(n=100): L = [randFloat() for j in range(random.randint(1, n))] while L[-1] == 0: L[-1] = randFloat() return Poly(L) def randPoly(n=100): L = [randCoeff() for j in range(random.randint(1, n))] while L[-1] == 0: L[-1] = randCoeff() return Poly(L) print('Тестируются сложение многочленов') TEST('Метод __add__ для Poly + Poly') _A = Poly([2, 3, 1, 3, 4, 5, 1, 2]) _B = Poly([1, 5, 7, 1, 2]) _C = _A + _B print(_C) _A = Poly([-2, 3, -1, -5, 1, -2]) _B = Poly([1, -5, -7, 1, -2, 3, -3, -1, 2]) _C = _A + _B print(_C) _A = Poly([1, 2, 3]) _B = Poly([1, 2, -3]) _C = _A + _B print(_C) TEST('Метод __add__ для Poly + int') _A = Poly([2, 3, 1, 3, 4, 5, 1, 2]) _B = -7 _C = _A + _B print(_C) _A = Poly([2, 0, 1]) _B = -2 _C = _A + _B print(_C) _A = Poly([Fraction(12, 7), 0, 1]) _B = 1 _C = _A + _B print(_C) _A = Poly([1.5, 0, 1]) _B = 1 _C = _A + _B print(_C) TEST('Метод __add__ для Poly + Fraction') _A = Poly([2, 3, 1, 3, 4, 5, 1, 2]) _B = Fraction(19, 4) _C = _A + _B print(_C) _A = Poly([2, 0, 1]) _B = Fraction(-6, 3) _C = _A + _B print(_C) _A = Poly([Fraction(12, 7), 0, 1]) _B = Fraction(-18, 5) _C = _A + _B print(_C) _A = Poly([1.5, 0, 1]) _B = Fraction(14, 9) _C = _A + _B print(_C) TEST('Метод __add__ для Poly + float') _A = Poly([2, 3, 1, 3, 4, 5, 1, 2]) _B = 12.35 _C = _A + _B print(_C) _A = Poly([2, 0, 1]) _B = -2.0 _C = _A + _B print(_C) _A = Poly([Fraction(12, 7), 0, 1]) _B = 13.24 _C = _A + _B print(_C) _A = Poly([1.5, 0, 1]) _B = 17.81 _C = _A + _B print(_C) TEST('Метод __iadd__ для Poly + Poly') _A = Poly([2, 3, 1, 3, 4, 5, 1, 2]) _B = Poly([1, 5, 7, 1, 2]) _A += _B print(_A) _A = Poly([-2, 3, -1, -5, 1, -2]) _B = Poly([1, -5, -7, 1, -2, 3, -3, -1, 2]) _A += _B print(_A) _A = Poly([1, 2, 3]) _B = Poly([1, 2, -3]) _A += _B print(_A) TEST('Метод __iadd__ для Poly + int') _A = Poly([2, 3, 1, 3, 4, 5, 1, 2]) _B = -7 _A += _B print(_A) _A = Poly([2, 0, 1]) _B = -2 _A += _B print(_A) _A = Poly([Fraction(12, 7), 0, 1]) _B = 1 _A += _B print(_A) _A = Poly([1.5, 0, 1]) _B = 1 _A += _B print(_A) TEST('Метод __iadd__ для Poly + Fraction') _A = Poly([2, 3, 1, 3, 4, 5, 1, 2]) _B = Fraction(19, 4) _A += _B print(_A) _A = Poly([2, 0, 1]) _B = Fraction(-6, 3) _A += _B print(_A) _A = Poly([Fraction(12, 7), 0, 1]) _B = Fraction(-18, 5) _A += _B print(_A) _A = Poly([1.5, 0, 1]) _B = Fraction(14, 9) _A += _B print(_A) TEST('Метод __iadd__ для Poly + float') _A = Poly([2, 3, 1, 3, 4, 5, 1, 2]) _B = 12.35 _A += _B print(_A) _A = Poly([2, 0, 1]) _B = -2.0 _A += _B print(_A) _A = Poly([Fraction(12, 7), 0, 1]) _B = 13.24 _A += _B print(_A) _A = Poly([1.5, 0, 1]) _B = 17.81 _A += _B print(_A) TEST('Метод __radd__ для Poly + int') _A = Poly([2, 3, 1, 3, 4, 5, 1, 2]) _B = -7 _C = _B + _A print(_C) _A = Poly([2, 0, 1]) _B = -2 _C = _B + _A print(_C) _A = Poly([Fraction(12, 7), 0, 1]) _B = 1 _C = _B + _A print(_C) _A = Poly([1.5, 0, 1]) _B = 1 _C = _B + _A print(_C) TEST('Метод __radd__ для Poly + Fraction') _A = Poly([2, 3, 1, 3, 4, 5, 1, 2]) _B = Fraction(19, 4) _C = _B + _A print(_C) _A = Poly([2, 0, 1]) _B = Fraction(-6, 3) _C = _B + _A print(_C) _A = Poly([Fraction(12, 7), 0, 1]) _B = Fraction(-18, 5) _C = _B + _A print(_C) _A = Poly([1.5, 0, 1]) _B = Fraction(14, 9) _C = _B + _A print(_C) TEST('Метод __radd__ для Poly + float') _A = Poly([2, 3, 1, 3, 4, 5, 1, 2]) _B = 12.35 _C = _B + _A print(_C) _A = Poly([2, 0, 1]) _B = -2.0 _C = _B + _A print(_C) _A = Poly([Fraction(12, 7), 0, 1]) _B = 13.24 _C = _B + _A print(_C) _A = Poly([1.5, 0, 1]) _B = 17.81 _C = _B + _A print(_C) TEST('Специальные тесты на корректность реализации __iadd__') _A = Poly([1, 1, 1]) _B = Poly([1, 1]) _D = _A _A += _B print(_D) _A += _B print(_D) _A += _B print(_D) _A += 1 print(_D) _A += Fraction(1, 2) print(_D) _A += 1.2 print(_D) for i in range(100): TEST('Большой случайный тест') if i % 4 == 0: _A = randPoly() _B = randPoly() _x = randCoeff() elif i % 4 == 1: _A = randIntPoly() _B = randIntPoly() _x = randInt() elif i % 4 == 2: _A = randFractionPoly() _B = randFractionPoly() _x = randFraction() elif i % 4 == 3: _A = randFloatPoly() _B = randFloatPoly() _x = randFloat() _C = _A + _B _D = Poly(_A) _D += _B _E = _A + _x _F = Poly(_A) _F += _x _G = _x + _A print("Source data:") print("A = ", _A) print("B = ", _B) print("x = ", _x) print("Result:") print("C = ", _C) print("D = ", _D) print("E = ", _E) print("F = ", _F) print("G = ", _G) print(Poly('1 2 2 2 2 2 2 -1.1 ') * Poly('3 3 3 5 5 6 7 8 8 8 7 6 6 ')) '''import sys exec(sys.stdin.read())'''
f22101e69a4d805d8852fdf0aa5e3d907a987cb1
PrzemoPoz/p1
/zjazd2/funkcje/slack5.py
557
3.890625
4
# Napisz program, który wczyta od użytkownika liczbę X, a następnie wyświetli TRÓJKĄT prostokątny o długości przyprostokątnej X,np.: 5 -> # * # * * # * * # * * # * * * * * def trojkat_prostokatny(x): i = 1 while i <= x: j = 1 napis = '' while j <= x: if i == x or j==1 or i == j: napis += '* ' else: napis += ' ' j += 1 i += 1 print(napis) return '' x = int(input("podaj X, ziomku: ")) print(trojkat_prostokatny(x))
2842f4bfd62fe8f900ad916c47f26259e66cf3af
Moreland-J/CS4099
/cs4099/src/csvSort.py
1,502
3.75
4
import csv db = [] def run(): readDB() quickSort(1, (len(db) - 1)) writeCSV() readDB() def readDB(): # https://realpython.com/python-csv/ print() with open('database/db.csv') as file: reader = csv.reader(file, delimiter = ',') count = 0 for col in reader: db.append([]) if count == 0: db[count].append(col[0]) db[count].append(col[1]) count += 1 else: db[count].append(col[0]) db[count].append(col[1]) print(str(count) + " " + db[count][0] + " " + db[count][1]) count += 1 print() return # https://www.geeksforgeeks.org/quick-sort/ def quickSort(low, high): if low < high: pivot = partition(low, high) quickSort(low, pivot - 1) quickSort(pivot + 1, high) return # MOVES SMALLER VALUES TO THE LEFT def partition(low, high): pivot = db[high][0] i = low - 1 for j in range(low, high): if db[j][0] < pivot: i += 1 db[i][0], db[j][0] = db[j][0], db[i][0] db[i][1], db[j][1] = db[j][1], db[i][1] db[i + 1][0], db[high][0] = db[high][0], db[i + 1][0] db[i + 1][1], db[high][1] = db[high][1], db[i + 1][1] return i + 1 def writeCSV(): file = open('database/db.csv', 'w', newline="") with file: writer = csv.writer(file) writer.writerows(db) print("Complete!") run()
d1afc84041d9bc3259ab058f911f4babcc1ca6be
Santigre/Basic_pythons
/python/hero_game/hack_slash.py
2,297
3.78125
4
''' Python 2 Author: Santiago Beltran Going to make a text game where there is a hero fighting off an infinante amount of monsters ''' import random, hero_class def start(hero = "", health = 10, attack = 3): hero = intro_game(hero, health, attack) smonster = intro_monsters(smonster = "", smhealth = 3, smattack = 1) def intro_game(hero, health, attack): if hero != "": #if statment print('Welcome back hereo {}!'.format(hero)) #Printing out a value with .format print('Your current stats are (health:{}, attack{})').format(health,attack) else: new_hero= True while new_hero: if hero == "": hero = raw_input('\nWhat is your name hero?').capitalize() print('\nWelcome Hero {}!').format(hero) print('\nThis world is filled with monsters that require slaying') print('\nThe world looks to you for your stragnth') print('\nYou have {} health and {} attack').format(health,attack) print('\nThe further you get, the stronger you will become') new_hero = False return hero monster_tuple = ("Bat", "Cub", "Grunt", "Goblin"); # def intro_monsters(smonster, smhealth, smattack): print("\nAt your current state you can only handle these foes: {}" ).format(monster_tuple) start() ''' This is a tuple that contain the name of the monsters you will fight. I have an idea of having diffrent dificulties of monsters. but for now just this one set until i have more time and figure out how to do this. ''' '''monster_tuple = ("Bat", "Cub", "Grunt", "Goblin"); # Tuple def fight(hero, health, attack): for monster in monster_tuple: print('\nYou are attacked by a {}.').format(random.choice(monster_tuple)) battle_option = raw_input("Do you wish to fight? y/n: ") if battle_option == ('y'): print('\nYou strike the {} and do {} damage').format(random.choice(monster_tuple),attack) print('\nBut you also substain 1 damage') elif battle_option == ('n'): print('\nYou flee the scene') ''' ''' bob = hero_class.hero("bob") print jim.name jim.get_name() print jim.healt'''
45ab6e9350008ba2139154efcf0efd8c37362a99
typd/basicplib
/basicplib/util/timeutil.py
710
3.640625
4
import time import datetime #curr_time_int = lambda: int(time.time()) def curr_time_int(): return int(time.time()) def format_duration(duration): if duration < 60: return '0:{0:02d}'.format(duration) elif duration < (60 * 60): minutes = duration // 60 seconds = duration - (minutes * 60) return '{0:d}:{1:02d}'.format(minutes, seconds) else: hours = duration // (60 * 60) minutes = (duration - (hours * 60 * 60)) // 60 seconds = (duration - (hours * 60 * 60) - (minutes * 60)) return '{0:d}:{1:02d}:{2:02d}'.format(hours, minutes, seconds) def shift_datetime(target, **kargs): return target + datetime.timedelta(**kargs)
21f5f6eda4c9f566a71fa6e0bf10ff275e2b5b3e
RossMeikleham/DailyProgrammer
/Easy/Challenge227/Challenge227.py
3,145
4.09375
4
import math from decimal import Decimal def getPoint(s, n) : if n > (s**2) or n <= 0 or (s & 0x1 != 0x1): print("Error expected n > 0 and n < s^2, and s to be odd") else: #Obtain co-ordinates for center of the spiral center = (s + 1) / 2 #Next obtain the "level" that the given n is in, #Low represents the lowest value, and high the highest # e.g. level 0 is for n =1, #level 1 is between 2 and 9, then level 2 is between 10 and 25 etc. high = (math.ceil(math.sqrt(n)))**2 low = 0 #Highest must be a square number must be the next square number #above or equal to n which is odd if (high & 0x1 != 0x1): high = (math.sqrt(high) + 1)**2 sqrtHigh = math.sqrt(high) low = (sqrtHigh - 2)**2 + 1 sideLength = (high - low + 1)/4 offset = (sqrtHigh - 1)/2 # Offset from center where the perimiter is # End Of Spiral if (n == high): return (center + offset, center + offset) # Right side of spiral elif (n <= low + sideLength - 1): y = low - n + ((sqrtHigh - 3)/2) return (center + offset, center + y) # Top side of spiral (excluding top right positon) elif (n <= low + (sideLength * 2) - 1): x = low - n + sideLength + ((sqrtHigh - 3)/2) return (center + x, center - offset) # Left side of spiral (excluding top left positon) elif (n <= low + (sideLength * 3) - 1): y = low - n + (2 * sideLength) + ((sqrtHigh - 3)/2) return (center - offset, center - y) # Bottom side of spiral (excluding bottom left position) else: x = low - n + (3 * sideLength) + ((sqrtHigh - 3)/2) return (center - x, center + offset) def getN(s, x, y): if (x < 1 or x > s) or (y < 1 or y > s) or (s & 0x1 != 0x1): print("Error, expected 1 <= x,y <= s, and s to be odd") else: center = Decimal((s + 1)/2) #Use Chebyshev distance to work out how many "levels" out the point is level = Decimal(max(abs(x - center), abs(y - center))) squareLevel = Decimal(2 * level + 1) # Before Top Left Corner if (x > y): low = Decimal((squareLevel - 2)**2 + 1) n = Decimal(low + squareLevel - 2 - ((x - center) + (y - center))) return n # After Top Left Corner elif (y > x): low = Decimal((squareLevel - 1)**2 + 2) n = Decimal(low + squareLevel - 2 + ((x - center) + (y - center))) return n ##On the main Diagonal else: if (y < center): return (squareLevel - 1)**2 + 1 elif (y > center): return squareLevel ** 2 else: return 1 def points(): s = int(input()) n = int(input()) print(getPoint(s, n)) def n(): s = int(input()) x = int(input()) y = int(input()) print(getN(s, x, y)) n()
0d5f75734fb927cfe4cf591d2af71e91ab0dddf1
sevo/FLP-2020
/5/cvicenie/sections/module_3.py
3,072
4
4
# # Module 3. Simple exercises including I/O ( Input/Output ) # # Simple exercises to use I/O functins and the `re` module. # Documentation for input and output in python can be found in the following link. # http://docs.python.org/2/tutorial/inputoutput.html # import re, time, random # from module_1 import is_palindrome_advanced, char_freq # 32. Find palidromes. # Scans a file line by line findind palidromes in it # and return an array with the palindromes found. def find_palidromes( filename = 'data/palidromes-32.md' ): pass # 33. Semordnilap. # A semordnilap is a word that when spelled backwards, produces other word. # E.G. # # strssed -> desserts # # This function, gets all the words in a file and finds all the words # that when spelled backwards, are equal to other words in the file. # def find_semordnilaps( filename = 'data/words-33.md' ): pass # 34. Character frequency table. # Prints a table showing how many characters of each # charachter there are in a text file def char_freq_table( filename = 'data/the-dream.md' ): pass # 35. Speak ICAO # # Given a string, this function will translate it to ICAO # giving a speach of each letter's corresponding tranlation according ICAO dictionary. # The pause betweet each spoken translated letter and each word can be set. # # ( 'Hello', 0, 1 ) -> Will speach -> 'hotel' `wait 0 seconds`, 'echo' `wait 0 seconds`, 'lima' `wait 0 seconds`, # 'lima' `wait 0 seconds`, 'oscar' `wait 0 seconds` `and then wait 1 second` # # Note: In order for this function to work you should have available `pyttsx` package # instructions and download can be found in the following link # https://github.com/parente/pyttsx # def speak_ICAO( string, letter_pause, word_pause ): pass # 36. Hapax legomenon # Finds words that happen to be used only once in a text. def find_hapax_legomenons( filename = 'data/the-dream.md' ): pass # 37. Add line numbers. # Given a text file, this function will create a new text file # in which all the lines from the original file are numbered # from 1 to n. def copy_file_count_lines( filename = 'data/text.txt' ): pass # 38. Average_word_length. # Calculates the average word length in a text file # passed by the user. def average_word_length( filename = 'data/the-dream.md' ): pass # 39. Guess the number game. # Command line game that will randomly select a number from 1 to 20 # and will ask the user to guess it. def guess_the_number_game(): pass # 40. Anagram # Command line game that given a list of colours will pick one, # make an Anagram with it and ask the user to decript it. def anagram_game( words ): pass # 41. Lingo function # Given two words, this function will compare them and show # clues on the second one, that may lead to guess the first one. def lingo( word, guess ): pass # 41 Lingo Game # Lingo is a game for guessing a hidden 5 characters word. # Users enter a word and it is compared with the one to guess # and clues are show for the user to finally guess the word. def lingo_game(): pass
a8bcb0a86719ca5fde3b603af951445495d16fdd
AdamZhouSE/pythonHomework
/Code/CodeRecords/2533/60660/235296.py
234
3.8125
4
orgstr=input()[1:-1].split(',') org=[int(orgstr[i]) for i in range(len(orgstr))] odd=[] even=[] for num in range(len(org)): if not org[num]%2==0: odd.append(org[num]) else: even.append(org[num]) print(even+odd)
b7fd5bf1ef532bdb8e0b0eae5a69a19c54c9de82
davidissimo/pythonProject1
/Mood_checker.py
207
3.84375
4
mood = "uau" #Nervous if mood == "happy": print("It is great to see you happy!") elif mood == "Nervous": print("Take a deep breath 3 times.") else: print("I don't recognize this mood")
4e6923255b547a9ed4a34e70ea30b3be2251a4ea
ankitbrahmbhatt1997/Python-Datastructures-and-ALgorithms
/codility/sieve_of_eratosthenes/factorization.py
613
3.609375
4
def pre_factorization(n): sieve = [0]*(n+1) i=2 while i*i <= n: if sieve[i] == 0: if sieve[i] == 0: k = i*i while k <= n: if sieve[k] == 0: sieve[k] = i k+=i i+=1 return sieve def factorization(n): preFactorizedArray = pre_factorization(n) primeFactors = set() while preFactorizedArray[n] > 0: primeFactors.add(preFactorizedArray[n]) n //= preFactorizedArray[n] primeFactors.add(n) return primeFactors print(factorization(75) )
b57066bb9c770b831aa7c04e5a54fe3043d58a60
sonam2905/My-Projects
/Python/Leetcode/88_merge_sorted_array.py
658
3.828125
4
class Solution: def merge(self, nums1: [int], m: int, nums2: [int], n: int) -> None: """ Do not return anything, modify nums1 in-place instead. """ last = m + n - 1 while n > 0 and m > 0: if nums1[m - 1] > nums2[n - 1]: nums1[last] = nums1[m-1] m -= 1 else: nums1[last] = nums2[n-1] n-=1 last -= 1 while n > 0: nums1[last] = nums2[n-1] n-=1 last-=1 return nums1 opt = Solution() print(opt.merge([1,2,3,0,0,0], 3, [2,5,6], 3))
a9c8f176519c63c8fc90c07fc244e903fd1bfb07
aka5hkumar/python
/cb3157.hw3.q3.py
735
4.34375
4
print('Please input 3 values for the equation ax^2 +bx + c') a = float(input('Enter value for a: ')) b = float(input('Enter value for b: ')) c = float(input('Enter value for c: ')) discriminant = b**2 - 4*a*c root1 = -b / 2*a #In calculus, the discriminant this tells us of nature of quadratic roots if (a == 0 and b == 0 and c == 0): print('There are infinitely many solutions to this equation') elif (a == 0 and b == 0 and c != 0): print('There are no solutions') if (discriminant == 0): print("This quadratic equation has 1 solution and this solution is x =", root1) elif (discriminant > 0): print('This equation has 2 real roots') elif (discriminant < 1): print('This equation has no real roots')
c8a7bb8c1e4adeec219be47bc3f33d38eff47496
dslachar/data-vis
/assignments/assignment1/assignment1.py
3,201
3.828125
4
# David LaCharite import numpy as np import pandas as pd import math # Part 1 print('-----------------------PART 1-----------------------') # Read Elements CSV into a pandas data frame df_elements = pd.read_csv('elements.csv') # add ninth and tenth elements to dataframe df_elements.loc[len(df_elements)]=['Fluorine','F', 9] df_elements.loc[len(df_elements)]=['Neon','Ne', 10] # add a column with the atomic weights rounded to the nearest inetger df_elements['atomic_weight'] = ['1','4','7','9','11','12','14','16','19','20'] print(df_elements) # Part2 print('-----------------------PART 2-----------------------') # Make a list of strings for nine Greek letters, ‘alpha’, for example. # Make that list such that they are not in alphabetic order greekLetters = ['delta','alpha','phi','iota','lambda', 'gamma','eta','tau','epsilon'] # Make two 9-element numpy arrays of random floating-point numbers with the # estimated mean 10 and standard deviation 1.5 mu = 10 sigma = 1.5 NPTS = 9 random1 = [sigma * x + mu for x in np.random.randn(NPTS)] random2 = [sigma * x + mu for x in np.random.randn(NPTS)] # Make an array of nine elements ranging from zero to two times pi range_low = 0 range_high = 2*math.pi angle = np.random.uniform(range_low, range_high, NPTS) # Make another array holding the cosine of that ‘angle’ array. cosine = [math.cos(x) for x in angle] # Construct a dictionary from all of the above d = {'Letter':greekLetters, 'Random_1':random1, 'Random_2':random2, 'Angle' : angle, 'Cosine' : cosine} # Form a DataFrame from that dictionary and print it out df_letters = pd.DataFrame(d) print(df_letters) # Sort the DataFrame ascending on the Greek letters, trimmed_df = df_letters.sort_values(by=['Letter']) # drop two columns of your choice trimmed_df.drop(['Random_2', 'Cosine'], axis=1, inplace=True) # drop one of the rows trimmed_df.drop(trimmed_df[trimmed_df['Letter'] == 'eta'].index, inplace=True) # and print that out print(trimmed_df) # Part 3 print('-----------------------PART 3-----------------------') # Write a program in Python to create and print out the first twelve Fibonacci numbers numFibs = 12 fibsList = [0, 1] while len(fibsList) < numFibs: fibsList.append(sum(fibsList[-2:])) print(fibsList) # iterate over the last five numbers to build another list with the ratio of each number to its predecessor numRatios = 5 ratioList = [] for i in range(numFibs - numRatios, numFibs): ratioList.append(fibsList[i] / fibsList[i-1]) print(ratioList) # What do you observe about this latter list? #The latter list is a convergent sequence with a limit of 1.618 which is ≈ the Golden Ratio. # Part 4 print('-----------------------PART 4-----------------------') # Provide a function that converts temperature in Kelvin to Rankine def kelvin_to_rankin(K): return K * 1.8 # Make a list of five Kelvin temperatures and print out their values in Rankine kelvinTemps = [0, 223, 283, 333, 373] print(kelvinTemps) rankinTemps1 = [kelvin_to_rankin(K) for K in kelvinTemps] print(rankinTemps1) # Repeat using a lambda function. rankinTemps2 = list(map(lambda x: x * 1.8, kelvinTemps)) print(rankinTemps2)
39b1e5309b0c38cbfbc472a9cdbac8653ad61b12
anshi9061/Python
/oops.py
1,345
4.21875
4
#class class simple: def hai(self): print("hai") a=simple() a.hai() #constructor class welcome: def __init__(self,name): self.name=name def display(self): print("name:" +self.name) x=welcome("Ansheena") x.display() #destructors class world: def __init__(self): print("Amazing world") def __del__(self): print("destructed called,world deleted") obj=world() del obj #simple inheritance class Baseclass: def display(self): print("hello") class subclass(Baseclass): def welcome(self): print("welcome") y=subclass() y.display() y.welcome() #multiple inheritance class first: def display(self): print("first") class second: def display_second(self): print("second") class third(first,second): def display_third(self): print("third") x=third() x.display_third() x.display_second() x.display() #hierarchial class calculator: def sum(self,a,b): return a+b class derived1(calculator): def mul(self,a,b): return a*b class derived2(calculator): def div(self,a,b): return a/b ob1=derived1() ob2=derived2() print(ob1.sum(2,3)) print(ob1.mul(2,3)) print(ob2.div(2,3)) print(ob2.sum(2,3))
93748cf25f84e647ef4c2ea60b54baa1e57a503b
SuYOUNGgg/JavaStudy
/Python/0525/test.py
718
4.15625
4
colors = ['white','red','green','blue'] print(colors) colors.sort() print(colors) print(sorted(['white','red','green','blue'])) def mysort(x): return x[-1] print(mysort('white'),mysort('red')) colors2 = ['white','red','green','blue'] colors2.sort(key=mysort) print(mysort('white'),mysort('red'),mysort('green'),mysort('blue')) colors2.sort(key=len) print(colors2) a = 10 b = 'test' c = ['1234','1234','222'] def test(): return 0 d= test d() #얕은복사, 깊은 복사 a1 = 1 b1 = a1 print(a1,b1) list1 = [1,2,3] list2 = list1 print(list1,list2) print(id(list1),id(list2)) print(id(a1), id(b1)) # shallow copy s = list1[:] print(list1, s) s.append([5,5]) print(list1,s) s[0] = [1,2,3] print(list1, s)
2e5747a1ef29105c0aa7acecbf41dbd6f1e84a8f
Lucakurotaki/ifpi-ads-algoritmos2020
/Iteração FOR/Fabio 03/f03_q15_sequencia_n.py
247
3.921875
4
def main(): n = int(input("Digite um número positivo: ")) if n < 1: print("Erro. Digite um número maior do que 0.") else: num = 1 for i in range(2, n+2): print(num) num += i main()
051b7c8dedb0ece874975f10c4dd90fe8e23f13d
johnkim9/python_crash_course
/rivers.py
1,353
4.28125
4
rivers = { 'nile':'egypt', 'seine':'france', 'han':'korea', 'potomac':'us', 'rhine':'germany' } for name, country in rivers.items(): print("The " + name.title() + " runs through " + country.title() + ".") #Nesting alien_0 = {'color':'green','points':5} alien_1 = {'color': 'yellow','points':10} alien_2 = {'color':'red','points':15} aliens = [alien_0, alien_1, alien_2] for alien in aliens: print (alien) #Make an empty list for storing aliens aliens = [] #Make 30 green aliens. for alien_number in range(30): #range() returns a set of numbers, which just tells Python how many times we want the loop to repeat. new_alien = {'color':'green', 'points':5, 'speed':'slow'} #each time the loop runs we create new alien aliens.append(new_alien) #append each new alien to the list aliens. #using slice to show the first 5 aliens. for alien in aliens[:5]: print(alien) print("...") #Show how many aliens have been created. print("Total number of alins:" + str(len(aliens))) #print the length of the list to prove we've actually generated the full fleet of 30 aliens. for alien in aliens[0:3]: if alien['color']=='green': alien['color'] = 'yellow' alien['speed'] = 'medium' alien['points'] = 10 elif alien['color'] == 'yellow': alien['color'] = 'red' alien['speed'] = 'fast' alien['points'] = 15 #A list in a dictionary
eca89a8874e72505a0b88ce26b133158ab22cfde
taylor-swift-1989/PyGameExamplesAndAnswers
/examples/minimal_examples/pygame_minimal_rotate_to_target_intersect_laser.py
6,134
3.671875
4
# pygame.transform module # https://www.pygame.org/docs/ref/transform.html # # Shooting a bullet in pygame in the direction of mouse # https://stackoverflow.com/questions/60464828/calculating-direction-of-the-player-to-shoot-pygame # # GitHub - PyGameExamplesAndAnswers - Move towards target - Move towards target Shoot a bullet in a certain direction - Rotate player and shoot bullet towards faced direction # https://github.com/Rabbid76/PyGameExamplesAndAnswers/blob/master/documentation/pygame/pygame_move_towards_target.md import math import pygame class Player(pygame.sprite.Sprite): def __init__(self, x, y, player): super().__init__() self.image = player self.is_shooting = False self.original_player_image = player self.rect = self.original_player_image.get_rect(center = (x, y)) self.angle = 0 def rotate_to(self, to_x, to_y): rel_x, rel_y = to_x - self.rect.x, to_y - self.rect.y self.angle = (180 / math.pi) * -math.atan2(rel_y, rel_x) - 90 self.image = pygame.transform.rotate(self.original_player_image, round(self.angle)) self.rect = self.image.get_rect(center = self.rect.center) class Enemy(pygame.sprite.Sprite): def __init__(self, x, y): super().__init__() self.image = pygame.Surface((30, 30), pygame.SRCALPHA) self.image.fill((0, 0, 0, 0)) self.rect = self.image.get_rect(center = (x, y)) self.hit = False def update(self): color = (255, 128, 0) if self.hit else (0, 255, 0) pygame.draw.circle(self.image, color, (15, 15), 15) class Laser(pygame.sprite.Sprite): def __init__(self, start_x, start_y): super().__init__() self.original_image = pygame.Surface((5, 150)) self.original_image.set_colorkey((0, 0, 0)) self.original_image.fill((255, 0, 0)) self.copy_image = self.original_image.copy() self.copy_image.set_colorkey((0, 0, 0)) self.rect = self.copy_image.get_rect(center = (start_x, start_y - 75)) self.image = pygame.Surface((5, 150)) def rotate(self, anker_rect, angle): # get rectangle of player and laser, as if the angle would be 0 laser_rect = self.original_image.get_rect(midbottom = anker_rect.midtop) pos = anker_rect.center pivotPos = [pos[0] - laser_rect.x, pos[1] - laser_rect.y] # calcaulate the axis aligned bounding box of the rotated image w, h = self.original_image.get_size() box = [pygame.math.Vector2(p) for p in [(0, 0), (w, 0), (w, -h), (0, -h)]] box_rotate = [p.rotate(angle) for p in box] min_box = (min(box_rotate, key=lambda p: p[0])[0], min(box_rotate, key=lambda p: p[1])[1]) max_box = (max(box_rotate, key=lambda p: p[0])[0], max(box_rotate, key=lambda p: p[1])[1]) # calculate the translation of the pivot pivot = pygame.math.Vector2(pivotPos[0], -pivotPos[1]) pivot_rotate = pivot.rotate(angle) pivot_move = pivot_rotate - pivot # calculate the upper left origin of the rotated image origin = (pos[0] - pivot[0] + min_box[0] - pivot_move[0], pos[1] + pivot[1] - max_box[1] + pivot_move[1]) # get a rotated image self.image = pygame.transform.rotate(self.original_image, angle) # get new rectangle self.rect = self.image.get_rect(topleft = (round(origin[0]), round(origin[1]))) def collideLineLine(l1_p1, l1_p2, l2_p1, l2_p2): # normaliced direction of the line and start of the line P = pygame.math.Vector2(*l1_p1) line1_vec = pygame.math.Vector2(*l1_p2) - P R = line1_vec.normalize() Q = pygame.math.Vector2(*l2_p1) line2_vec = pygame.math.Vector2(*l2_p2) - Q S = line2_vec.normalize() # normal vectors to the lines RNV = pygame.math.Vector2(R[1], -R[0]) SNV = pygame.math.Vector2(S[1], -S[0]) # distance to the intersection point QP = Q - P t = QP.dot(SNV) / R.dot(SNV) u = QP.dot(RNV) / R.dot(SNV) return t > 0 and u > 0 and t*t < line1_vec.magnitude_squared() and u*u < line2_vec.magnitude_squared() def colideRectLine(rect, p1, p2): return (collideLineLine(p1, p2, rect.topleft, rect.bottomleft) or collideLineLine(p1, p2, rect.bottomleft, rect.bottomright) or collideLineLine(p1, p2, rect.bottomright, rect.topright) or collideLineLine(p1, p2, rect.topright, rect.topleft)) pygame.init() window = pygame.display.set_mode((500, 500)) clock = pygame.time.Clock() player_image = pygame.Surface((30, 30), pygame.SRCALPHA) player_image.fill((0, 0, 0, 0)) pygame.draw.circle(player_image, (128, 128, 255), (15, 15), 15) pygame.draw.line(player_image, (0, 0, 0), (15,0), (15,30)) original_player_image = pygame.Surface((30, 30), pygame.SRCALPHA) original_player_image.fill((128, 128, 255)) player = Player(window.get_width() // 2, window.get_height() - 100, player_image) laser = Laser(player.rect.centerx + player_image.get_width() // 2, player.rect.centery - 75) enemy = Enemy(window.get_width() // 2, 200) group = pygame.sprite.Group([player, laser, enemy]) run = True while run: clock.tick(60) for event in pygame.event.get(): if event.type == pygame.QUIT: run = False keys = pygame.key.get_pressed() player.rect.x += (keys[pygame.K_d] - keys[pygame.K_a]) * 10 player.rect.y += (keys[pygame.K_s] - keys[pygame.K_w]) * 10 player.rect.clamp_ip(window.get_rect()) player.rotate_to(*pygame.mouse.get_pos()) laser.rotate(player.original_player_image.get_rect(center = player.rect.center), player.angle) angle = player.angle + 360 if player.angle < 0 else player.angle if angle < 90 or (angle > 180 and angle < 270): laserline = [laser.rect.topleft, laser.rect.bottomright] else: laserline = [laser.rect.bottomleft, laser.rect.topright] enemy.hit = colideRectLine(enemy.rect, *laserline) enemy.update() window.fill((127, 127, 127)) group.draw(window) pygame.display.flip() pygame.quit() exit()
ec01cb4afa6305f04c402a32589a857cf7844dcb
duochen/Python-Beginner
/Lecture05/Homework/solution04.py
268
3.9375
4
class Circle(): def __init__(self, r): self.radius = r def area(self): return self.radius**2*3.14 def perimeter(self): return 2*self.radius*3.14 c = Circle(8) print(c.area()) # => 00.96 print(c.perimeter()) # => 50.24
a54b42d101997996c9cc029285c11510a1596a42
rosemincj/PythonLearning
/regex.py
951
3.859375
4
import re sample_str = 'an example word:cat!!' match = re.search(r'word:\w\w\w', sample_str) # If-statement after search() tests if it succeeded if match: # 'found word:cat' print('found', match.group()) else: print('did not find') # found, match.group() == "iii" match = re.search(r'iii', 'piiig') print(match.group()) # not found, match == None # match = re.search(r'igs', 'piiig') # print(match.group()) # . = any char but \n # found, match.group() == "iig" match = re.search(r'..g', 'piiig') print(match.group()) # \d = digit char, \w = word char # found, match.group() == "123" match = re.search(r'\d\d\d', 'p123g') print(match.group()) # found, match.group() == "abc" match = re.search(r'\w\w\w', '@@abcd!!') print(match.group()) # To find if it is a email sample_str1 = 'purple [email protected] monkey dishwasher' match = re.search(r'\w+@\w+', sample_str1) if match: # 'b@google' print(match.group())
57c5cefdff0bba9047bb990a0eb0eac75df1e508
DCWhiteSnake/Data-Structures-and-Algo-Practice
/Chapter 2/Creativity/C-2.32.py
483
3.578125
4
import math from Progression import Progression class ProgressionEx(Progression): def __init__(self, first = 65536): """Extends the Progression class each value in the progression is the square root of the previous progression """ super().__init__(first) self._count = 0 def _advance(self): self._current = math.pow(self._current, 1/2) if __name__ == '__main__': px = ProgressionEx() px.print_progression(10)
21345b80a0e6c3748f8319b5b99683fed18ce6dd
dontbitme/lodowka
/lodówka.py
2,511
3.640625
4
# -*- coding: utf-8 -*- class Lodowka(object): def __init__(self): self.products = [] self.temperature = None self.status = False def find_products_index(self, product_name): for index in range(len(self.products)): if self.products[index].name == product_name: return index def add_product(self, product): index = self.find_products_index(product.name) if index != None: self.products[index].weight += product.weight else: self.products.append(product) def delete_product(self, product_name): index = self.find_products_index(product_name) if index != None: self.products.remove(self.products[index]) else: print "there is no product with this name.." def show_products(self): print "------ PRODUCTS ------" for product in self.products: print '- ', product.name, product.price, product.weight, product.expiration_date print "----------------------" def turn_on(self): self.status = True def turn_off(self): self.status = False def show_status(self): return self.status def set_temp(self, temp): self.temperature = temp def show_temperature(self): return self.temperature def total_price(self): hajs = 0 for x in self.products: hajs += x.price print hajs def take_out(self, product): for a in self.products: if a.name == product.name: self.products.remove(a) print "Product " + a.name +" was taken out..." else: print "There is no product with this name..." def najwiecej(self): lis=[] for s in self.products: self.products.index(s.name) #NIE ZROBI�EM class Produkt(object): def __init__(self, name, price, weight, expiration_date): self.name = name self.price = price self.weight = weight self.expiration_date = expiration_date p = Produkt('banan', 3, 0.5, '01.03.2013') p1 = Produkt('jablko', 3, 0.5, '01.03.2013') p2 = Produkt('cytryna', 3, 0.5, '01.03.2013') l = Lodowka() l.add_product(p) l.add_product(p1) l.add_product(p2) l.show_products() l.delete_product("banan") l.show_products()
9a345fbace167725b8fdaf61cb761f12acea2283
N66630/hyLib
/myFirst/015_class.py
5,618
3.984375
4
# -*- coding: utf-8 -*- """ Created on Sun Nov 12 23:11:58 2017 @author: Administrator """ print ('\nclass 用大寫字母開頭命名 (function 用小寫字母)') class Turtle: #屬性 color = 'green' weight = 23 legs = 4 #方法 def climb(self): print ('我正在爬') def run(self): print ('我正在跑') def jump(self): print ('我正在跳') print ('\nclass : 屬性、方法') print ('OO物件導向 : 封裝、繼承、多型') print ('實作 class 就會產生 object (object is class instance)') print ('\n封裝 : ') o = Turtle() o.jump() print ('\n繼承 : ') class MyTurtle(Turtle): pass o = MyTurtle() o.climb() print ('\nclass impletement (object)') class Robot: def setName(self, name): self.name = name def run (self): print ('%s 開始在跑了' % self.name) a = Robot() a.setName('R1') b = Robot() b.setName('R2') c = Robot() c.setName('R3') a.run() c.run() print ('\n建構函數 (__init__(self))') class Robot: def __init__(self, name): self.name = name def run (self): print ('%s 開始在跑了' % self.name) a = Robot('Robot1') a.run() print ('\npublic and private') print ('屬性與方法都是 public') class Person: name = 'Roy' p = Person() print (p.name) print ('python 利用 namgling 技術處理私有變變 (在變數或函數前開頭加上 __ 即可)') class Person: __age = 28 name = 'Roy' def getAge(self): return self.__age p = Person() print ('無法得到私有變收的值 __age') # print (p.__age) --> 會報錯 print ('利用 public 方法 (getAge) 取得 age') print (str(p.getAge())) print ('python 的 namgling 技術其實只是隱藏而已而不是真的的私有 (偽私有) (__ 其實是 _類別__變數)') print (str(p._Person__age)) import random as r print ('\n\n\n繼承時覆寫建構函數 (Shark 的覆寫了建構函數, 所以沒有 x, y 座標了, 執行 move() 函數會錯') class Fish: def __init__(self): self.x = r.randint(0, 10) self.y = r.randint(0,10) def move (self): self.x -= 1 print ('我目前的位置 : ', self.x, self.y) class Goldfish(Fish): pass class Garp(Fish): pass class Salmon(Fish): pass class Shark(Fish): def __init__(self): self.hungry = True def eat(self): if self.hungry == True: print ('好餓') self.hungry = False else: print ('好飽') self.hungry = True fish = Fish() fish.move() goldfish = Goldfish() goldfish.move() goldfish.move() goldfish.move() shark = Shark() shark.eat() shark.eat() shark.eat() # shark.move() --> 會錯, 因為 Shark 的覆寫了建構函數, 所以沒有 x, y 座標了 print ('\n繼承時覆寫建構函數, 但同時保留父類建構函數中的部分') print ('--> 調用未綁定的父類方法') class Fish: def __init__(self): self.x = r.randint(0, 10) self.y = r.randint(0,10) def move (self): self.x -= 1 print ('我目前的位置 : ', self.x, self.y) class Shark(Fish): def __init__(self): Fish.__init__(self) # 新增這行就可以保留父類的建構函數 self.hungry = True def eat(self): if self.hungry == True: print ('好餓') self.hungry = False else: print ('好飽') self.hungry = True shark = Shark() shark.move() # 可以執行了 shark.move() # 可以執行了 shark.move() # 可以執行了 print ('\n繼承時覆寫建構函數, 也可以宣告完後, 將子類的 object 帶入父類的建構函數中, 以保留父類的建構函數工作') print ('--> 調用未綁定的父類方法') class Fish: def __init__(self): self.x = r.randint(0, 10) self.y = r.randint(0,10) def move (self): self.x -= 1 print ('我目前的位置 : ', self.x, self.y) class Shark(Fish): def __init__(self): self.hungry = True def eat(self): if self.hungry == True: print ('好餓') self.hungry = False else: print ('好飽') self.hungry = True shark = Shark() Fish.__init__(shark) # 也可以宣告完後, 將子類的 object 帶入父類的建構函數中 shark.move() # 可以執行了 shark.move() # 可以執行了 shark.move() # 可以執行了 print ('\n繼承時覆寫建構函數, 但可以利用 super() 同時保留全部父類建構函數中的部分') print ('--> 使用 super() 函數') class Fish: def __init__(self): self.x = r.randint(0, 10) self.y = r.randint(0,10) def move (self): self.x -= 1 print ('我目前的位置 : ', self.x, self.y) class Shark(Fish): def __init__(self): super().__init__() # 新增這行就可以保留父類的建構函數 self.hungry = True def eat(self): if self.hungry == True: print ('好餓') self.hungry = False else: print ('好飽') self.hungry = True shark = Shark() shark.move() # 可以執行了 shark.move() # 可以執行了 shark.move() # 可以執行了 print ('\n\n多重繼承') print ('class DerivedClassName(BVase1, Base2, Base3, ..) : ...') class Base1: def foo1(self): print ('Base 1 foo 1') class Base2: def foo2(self): print ('Base 2 foo 2') class C(Base1, Base2): pass c = C() c.foo1() c.foo2() print ('\n\nPool') class Bird: num
10c0276024fec46d387d215db1d3d3b189fd6588
EverydayQA/prima
/pytools/other/fsample/hello.py
56
3.578125
4
name = input('xxx') print name # print("Hello " + name)
b6084466d8570d3e36d426cac046451a9e49ad88
Easyjuhl/ConsoleCardcasterDeck
/ConCardCast.py
2,561
3.671875
4
from random import randrange from utils import CardlistWork CardcasterLvl = int(input("What is your cardcaster level: ")) HandSizeMax = 1 MajArcPla = 2 if CardcasterLvl > 9: MajArcPla = 8 elif CardcasterLvl > 7: MajArcPla = 7 elif CardcasterLvl > 5: MajArcPla = 6 elif CardcasterLvl > 3: MajArcPla = 5 elif CardcasterLvl > 2: MajArcPla = 4 elif CardcasterLvl > 1: MajArcPla = 3 if CardcasterLvl > 18: HandSizeMax = 6 elif CardcasterLvl > 14: HandSizeMax = 5 elif CardcasterLvl > 10: HandSizeMax = 4 elif CardcasterLvl > 5: HandSizeMax = 3 elif CardcasterLvl > 2: HandSizeMax = 2 Hand = [] Cardlist = CardlistWork.CardlistReset(CardcasterLvl) print(*Cardlist, sep=", ") while True: HandSize = len(Hand) print(""" To draw a card write: Draw To cast a card write: Cast To discard a card write: Discard To reset write: Reset To quit write quit """) slct = input("Command: ").lower() if slct == "draw": if HandSize <= HandSizeMax: try: Cardslct = randrange(len(Cardlist)) except ValueError: print("Out of cards\n") print("Your hand:") print(*Hand, sep=", ") continue Hand.append(Cardlist[Cardslct]) print(Cardlist[Cardslct]) Cardlist.remove(Cardlist[Cardslct]) print("Your hand:") print(*Hand, sep=", ") else: print("Your hand is full\nDiscard a card to continue\n") print("Your hand:") print(*Hand, sep=", ") continue elif slct == "cast": if MajArcPla > 0: print(*Hand, sep=", ") dis = input("Choose a card to cast: ") try: Hand.remove(dis) except ValueError: print("Error: Your input {} is invalid\nRemember to capitalize the correct letters".format(dis)) continue print(*Hand, sep=", ") elif slct == "discard": print(*Hand, sep=", ") dis = input("Choose a card to discard: ") try: Hand.remove(dis) except ValueError: print("Error: Your input {} is invalid\nRemember to capitalize the correct letters".format(dis)) continue print(*Hand, sep=", ") elif slct == "reset": Cardlist = CardlistWork.CardlistReset(CardcasterLvl) Hand = [] elif slct == "quit": break else: print("Error: Invalid input")
e3fd15381b8f09265bbb34ea6f07390211645b7f
Sametcelikk/Edabit-Solutions-Python
/Medium/3-) Right Shift by Division.py
713
4.71875
5
""" The right shift operation is similar to floor division by powers of two. Sample calculation using the right shift operator ( >> ): 80 >> 3 = floor(80/2^3) = floor(80/8) = 10 -24 >> 2 = floor(-24/2^2) = floor(-24/4) = -6 -5 >> 1 = floor(-5/2^1) = floor(-5/2) = -3 Write a function that mimics (without the use of >>) the right shift operator and returns the result from the two given integers. Examples shift_to_right(80, 3) ➞ 10 shift_to_right(-24, 2) ➞ -6 shift_to_right(-5, 1) ➞ -3 shift_to_right(4666, 6) ➞ 72 shift_to_right(3777, 6) ➞ 59 shift_to_right(-512, 10) ➞ -1 """ from math import floor def shift_to_right(x, y): return floor(x / 2 ** y) print(shift_to_right(4666, 6))
820917ba3285af00bf124db0e9bc6d9ed491cf9c
chaehyeon119/Python
/CollectionList/python05_12_CollectionList09_김채현.py
369
3.765625
4
#python05_12_CollectionList09_김채현 # 리슽트에 포함된 요소 x의 개수 세기(count) a=[1,2,3,1] print(a.count(1)) print('-'*15) ''' 리스트 확장(extend) extend(x)에서 x에는 리스트만 올 수 이씅며 원래의 a 리스트에 x리스트를 더한다. ''' a=[1,2,3] a.extend([4,5]) print(a) #[1,2,3,4,5] #a.extend([4,5])는 a+=[4,5]와 동일
75aff426166b04a8a72d4520aed1e938ee0afae3
rubens-lavor/projeto-final-E.D.O.
/teste.py
562
4
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue Sep 17 09:45:28 2019 @author: rubens """ """ faça um programa que leia um número qualquer e mostre o seu fatorial""" from math import factorial f=factorial(5) print (f) """ outra forma """ fat=1 n=5 #n= int(input('digite um número para calcular o fatorial: ')) c=n while c>0: print('{}'.format(c), end='') print(' x ' if c > 1 else ' = ',end='') fat=fat*c c=c-1 print('{}'.format(f), end='') """com for fat=1 n=5 for i in range (1,n+1): fat=fat*i print (fat) """
ee4de305c27cad23fa889eaf9d0e1ae76f868c47
shwetakharche/Vlink-Codes-
/question2_shwetaKharche.py
402
3.734375
4
def Prefix( a): length = len(a) if (length == 0): return "" if (length == 1): return a[0] a.sort() end = min(len(a[0]), len(a[length - 1])) i = 0 while (i < end and a[0][i] == a[length - 1][i]): i += 1 pre = a[0][0: i] return pre if __name__ == "__main__": List=[] n=int(input()) for i in range(0, n): item = input(" ") List.append(item) print(Prefix(List))
cc2312f4db0a8a0e6faae7ad7065d66d89864c8d
eazapata/python
/Ejercicios python/PE3/PE3E2.py
329
3.984375
4
#PE2E2 Eduardo Antonio Zapata Valero #Pida al usuario el espacio recorrido por un coche y el tiempo que ha tardado en #horas y que calcule a qué velocidad media había realizado el recorrido. km=float(input("Cuanto espacio ha recorrido en KM ")) tmp=float(input("Cuantas horas ha tardado ")) vel=(km/tmp) print("La velocidad media es de ", vel)
ba87b64ba49f151c62636b858f7cddacab0618e5
mariuspodean/CJ-PYTHON-01
/lesson_21/mapping_mihaela.py
247
3.953125
4
import itertools items = [1, 2, 3, 4, 5] def multiply(x): return x * x def add(x): return x + x my_list = list(map(lambda x: (add(x), multiply(x)), items)) my_new_list= list(itertools.chain.from_iterable(my_list)) print(my_new_list)
993902cd5cda4fb045be591cb08ab8fbbfa72389
tenmilliondollars/PythonHW
/hw5.py
257
3.5625
4
a=input('Введите целые неотрицательные числа:\n') a=a.strip() a=a.split(" ") for i in range(len(a)): a[i]=int(a[i]) a=sorted(a) b=1 for i in range(len(a)): if b not in a: break else: b=b+1 print(b)
5b03ef61eccfff6df06c7eb422bf65dccea359d8
luisoto076/Redes2017
/practica1/Code/ScientificCalculator.py
1,216
3.890625
4
#! /usr/bin/env python # -*- coding: utf-8 -*- from Constants import Constants as cons import Calculator ''' Clase para la funcionalidad de la calculadora cientifica Extiende a la clase Calculator ''' class ScientificCalculator(Calculator.Calculator): ''' Metodo que obtiene el resultado de la operacion solicitada op : el codigo de operacion a : primer operando b : segundo operando ''' def operar(self,op,a,b): if op == cons.PLUS : return a+b if op == cons.MINUS : return a-b if op == cons.PROD : return a*b if op == cons.DIV : return a/b if op == cons.MOD : return a%b if op == cons.POW : return pow(a,b) return a*b ''' Metodo que obtiene el opcode de una operacion segun el simbolo que se encuentra en la posicion i de la cadena cadena : la expresion de la que se optendra el operador i: posicion del operador a examinar en la cadena ''' def operador(self,cadena,i): if cadena[i] == '+' : return cons.PLUS if cadena[i] == '-': return cons.MINUS if cadena[i] == '*': return cons.PROD if cadena[i] == '/': return cons.DIV if cadena[i] == '%': return cons.MOD if cadena[i] == '^': return cons.POW return cons.ERROR
78880c898ea3d72fd7ed8de75e6ad3d75b0291fa
qtvspa/offer
/List/linklist_base.py
2,415
3.921875
4
# -*- coding:utf-8 -*- class ListNode(object): """ 链表节点类 """ # p即模拟所存放的下一个结点的地址, 为了方便传参, 设置p的默认值为None def __init__(self, data, p=None): self.data = data self.next = p class LinkList(object): """ 简单的单链表类 """ def __init__(self): self.head = None # 链表初始化函数 def init_list(self, data): # 创建头结点 if len(data) > 0: self.head = ListNode(data[0]) p = self.head # 逐个为 data 内的数据创建结点, 建立链表 for i in data[1:]: node = ListNode(i) p.next = node p = p.next else: self.head = None # 链表判断是否为空 def is_empty(self): if self.head.next == 0: print("Empty List!") return True else: return False # 链表长度 def get_length(self): if self.is_empty(): exit(0) p = self.head l = 0 while p: l += 1 p = p.next return l # 遍历链表 def travel_list(self): if self.is_empty(): exit(0) p = self.head while p: print(p.data) p = p.next # 插入数据 def insert_elem(self, key, index): if self.is_empty(): exit(0) if index < 0 or index > self.get_length() - 1: exit(0) pre = None p = self.head i = 0 while i <= index: pre = p p = p.next i += 1 #遍历找到索引值为 index 的结点后, 在其后面插入结点 node = ListNode(key) pre.next = node node.next = p # 删除数据 def delete_elem(self, index): if self.is_empty(): exit(0) if index < 0 or index > self.get_length()-1: exit(0) i = 0 p = self.head pre = None # 遍历找到索引值为index的结点 while p.next: pre = p p = p.next i += 1 if i == index: pre.next = p.next return True # p的下一个结点为空说明到了最后一个结点, 删除之即可 pre.next = None
0eea426a667f15f23a6fcbb2362fb2e3766768f4
ShowenPeng/vyper-by-example
/memo/events.py
591
3.984375
4
""" pseudo code to list all authorized addresses python3 events.py """1 events = [{ "block": 1, "addr": "0x01", "approved": True }, { "block": 2, "addr": "0x02", "approved": True }, { "block": 3, "addr": "0x03", "approved": True }, { "block": 4, "addr": "0x01", "approved": False }] # set of all authorized addresses authorized = set() for event in events: if event["approved"]: authorized.add(event["addr"]) else: if event["addr"] in authorized: authorized.remove(event["addr"]) print(list(authorized))
20a0db86cd1177dce49b981c3a64e4511fea7d93
daniellopes04/uva-py-solutions
/list5/10168 - Summation of Four Primes.py
978
3.875
4
# -*- coding: UTF-8 -*- import math def checkIsPrime(num): s = int(math.sqrt(num)) for i in range(2, s + 1): if (num % i == 0): return False return True def getPrimes(num): primes = [0, 0] for i in range(2, int(num / 2) + 1): if (checkIsPrime(i) and checkIsPrime(num - i)): primes[0] = i primes[1] = num - i return primes def main(): while True: try: n = int(input()) if(n <= 7): print("Impossible.") if (n % 2 != 0): primes = getPrimes(n - 5) if (primes): print("2 3", primes[0], primes[1]) else: primes = getPrimes(n - 4) if (primes): print("2 2", primes[0], primes[1]) except(EOFError): break if __name__=='__main__': main()
82f454a01455f08fe95a0a41f5cb619e11114fb6
SsmallWinds/leetcode
/codes/69_sqrtx.py
824
4.375
4
""" 实现 int sqrt(int x) 函数。 计算并返回 x 的平方根,其中 x 是非负整数。 由于返回类型是整数,结果只保留整数的部分,小数部分将被舍去。 示例 1: 输入: 4 输出: 2 示例 2: 输入: 8 输出: 2 说明: 8 的平方根是 2.82842...,   由于返回类型是整数,小数部分将被舍去。 见图 newton.png, 牛顿迭代法 平方根即为方程 f(x) = x^2 + a 的正数解 不断的计算 下一个Xn, 即可慢慢逼近正确值 Xn+1 = Xn - f(Xn)/f'(Xn) 带入f(x) 可得 Xn+1 = Xn - (Xn - a / Xn) / 2 => Xn+1 = (Xn + a/Xn) / 2 """ def my_sqrt(a:int) -> float: res = a last = 0 while abs(res - last) > 0.00000001: last = res res = (res + a/res) / 2 return res if __name__ == "__main__": print(my_sqrt(8))
4b25976982cfd87ed2830e860f7ab54c2d196500
pradpalnis/Machine-Learning
/Python/Python_Example/Inheritance.py
3,221
4.125
4
# -*- coding: utf-8 -*- """ Created on Tue Mar 5 12:40:05 2019 @author: PP00495588 """ # A Python program to demonstrate inheritance # Base or Super class. Note object in bracket. # (Generally, object is made ancestor of all classes) # In Python 3.x "class Person" is # equivalent to "class Person(object)" class Person(object): # Constructor def __init__(self, name): self.name = name # To get name def getName(self): return self.name # To check if this person is employee def isEmployee(self): return False # Inherited or Sub class (Note Person in bracket) class Employee(Person): # Here we return true def isEmployee(self): return True # Driver code emp = Person("Geek1") # An Object of Person print(emp.getName(), emp.isEmployee()) emp = Employee("Geek2") # An Object of Employee print(emp.getName(), emp.isEmployee()) # Python example to check if a class is # subclass of another class Base(object): pass # Empty Class class Derived(Base): pass # Empty Class # Driver Code print(issubclass(Derived, Base)) print(issubclass(Base, Derived)) d = Derived() b = Base() # b is not an instance of Derived print(isinstance(b, Derived)) # But d is an instance of Base print(isinstance(d, Base)) # Python example to show working of multiple # inheritance class Base1(object): def __init__(self): self.str1 = "Geek1" print("Base1") class Base2(object): def __init__(self): self.str2 = "Geek2" print("Base2") class Derived(Base1, Base2): def __init__(self): # Calling constructors of Base1 # and Base2 classes Base1.__init__(self) Base2.__init__(self) print("Derived") def printStrs(self): print(self.str1, self.str2) ob = Derived() ob.printStrs() # Python example to show that base # class members can be accessed in # derived class using super() class Base(object): # Constructor def __init__(self, x): self.x = x class Derived(Base): # Constructor def __init__(self, x, y): ''' In Python 3.x, "super().__init__(name)" also works''' super(Derived, self).__init__(x) self.y = y def printXY(self): # Note that Base.x won't work here # because super() is used in constructor print(self.x, self.y) # Driver Code d = Derived(10, 20) d.printXY() class X(object): def __init__(self,a): self.num = a def doubleup(self): self.num *= 2 class Y(X): def __init__(self,a): X.__init__(self, a) def tripleup(self): self.num *= 3 obj = Y(4) print(obj.num) obj.doubleup() print(obj.num) obj.tripleup() print(obj.num) # Base or Super class class Person(object): def __init__(self, name): self.name = name def getName(self): return self.name def isEmployee(self): return False # Inherited or Subclass (Note Person in bracket) class Employee(Person): def __init__(self, name, eid): ''' In Python 3.0+, "super().__init__(name)" also works''' super(Employee, self).__init__(name) self.empID = eid def isEmployee(self): return True def getID(self): return self.empID # Driver code emp = Employee("Geek1", "E101") print(emp.getName(), emp.isEmployee(), emp.getID())
a810350bc0e9c5c0c0d8e9c8248766da135c724f
fopineda/ShopTracker
/ShopTracker.py
2,047
4.21875
4
from array_queue import ArrayQueue """ Tracks a shop's list of clients using a queue """ """ By Felipe Pineda 4/2/16 """ """ <[email protected] """ class ShopTracker: def __init__(self): self._listQueue = ArrayQueue() def startDay(self): """ Starts the day off by starting the listing process """ alpha = raw_input("Please enter the name (Enter End when done): ") while alpha != "End": self._listQueue.enqueue(alpha) alpha = raw_input("Please enter the name (Enter End when done): ") print len(self._listQueue) , "client(s) left" def addMore(self): """ Restarts the listing process again to add more names """ alpha = raw_input("Please enter the name (Enter End when done): ") while alpha != "End": alpha = raw_input("Please enter the name (Enter End when done): ") self._listQueue.enqueue(alpha) print len(self._listQueue) , "client(s) left" def endDay(self): """ Ends the day by clearing out the queue""" while len(self._listQueue) != 0: self._listQueue.dequeue() print len(self._listQueue) , "client(s) left" def getLength(self): """ Return length of elements in queue """ return len(self._listQueue) def primero(self): """ Prints out the first name in the queue (will not remove) """ if len(self._listQueue) == 0: #raise Empty('Queue is empty') print "You have no client(s) left" else: return self._listQueue.first() def getNext(self): """ Return the first name in the queue (will remove) """ if len(self._listQueue) == 0: #raise Empty('Queue is empty') print "You have no client(s) left" else: return self._listQueue.dequeue() class Empty(Exception): """Error attempting to access an element from an empty container.""" print "list is empty" s = ShopTracker()
f80ddc2e20cdff8fb0fb755368a81f2b6933cf2a
v0dro/scratch
/python_shizzle/roads-and-libraries.py
1,337
3.765625
4
import copy # https://www.cs.cmu.edu/afs/cs/academic/class/15210-f14/www/lectures/mst.pdf # graph can have many spanning trees, but all have|V|vertices and|V|−1 edges. def make_adjacency_list(n, cities): matrix = {} for i in range(n): matrix[i] = dict() for i, j in cities: matrix[i-1][j-1] = True matrix[j-1][i-1] = True return matrix def path_exists(node1, node2, graph): return (node2 in graph[node1]) def get_road_cost(graph, city, c_road): visited = set([city]) queue = [city] while queue: first = queue.pop() for c in graph[first].keys(): if path_exists(first, c, graph) and not (c in visited): queue.insert(0, c) visited.add(c) return (len(visited) - 1) * c_road, visited def roadsAndLibraries(n, c_lib, c_road, cities): if c_lib < c_road: return c_lib * n visited = set([]) graph = make_adjacency_list(n, cities) total_cost = 0 for city in range(0, n): if city not in visited: road_cost, visited_nodes = get_road_cost(graph, city, c_road) visited.update(visited_nodes) total_cost += road_cost + c_lib return total_cost print(roadsAndLibraries(3, 2, 1, [[1,2], [3,1], [2, 3]])) print(roadsAndLibraries(6, 3, 2, []))
9ce753fba0f2840fd9b734b203bfe4da87aff978
Lusarom/progAvanzada
/ejercicio94.py
444
3.890625
4
from random import randint SHORTEST = 7 LONGEST = 10 MIN_ASCII = 33 MAX_ASCII = 126 def randomPassword(): randomLength = randint(SHORTEST, LONGEST) result = '' for i in range(randomLength): randomChar = chr(randint(MIN_ASCII, MAX_ASCII)) result += randomChar return result def main(): print("Your random password is: ", randomPassword()) if __name__ == "__name__": main()
6459c19c2fdaaa32029f071247093ae5c86cded9
duanwenhuiIMAU/my_code
/al.py
7,810
3.5625
4
class Node: def __init__(self,list = [],parent = None): self.list = list self.parent = parent def up(self): listchild = self.list.copy() for i in range(len(listchild)): if(listchild[i]==0 and i>2): temp = listchild[i] listchild[i] = listchild[i-3] listchild[i-3] = temp break if listchild == self.list: return [] else: return listchild def down(self): listchild = self.list.copy() for i in range(len(listchild)): if(listchild[i]==0 and i<6): temp = listchild[i] listchild[i] = listchild[i+3] listchild[i+3] = temp break if listchild == self.list: return [] else: return listchild def right(self): listchild = self.list.copy() for i in range(len(listchild)): if(listchild[i]==0 and i%3!=0): temp = listchild[i] listchild[i] = listchild[i-1] listchild[i-1] = temp break if listchild == self.list: return [] else: return listchild def left(self): listchild = self.list.copy() for i in range(len(listchild)): if(listchild[i]==0 and (i+1)%3!=0 ): temp = listchild[i] listchild[i] = listchild[i+1] listchild[i+1] = temp break if listchild == self.list: return [] else: return listchild def showMarix(self): slice = self.list print(' ',slice[0:3]) print(' ',slice[3:6]) print(' ',slice[6:9]) def track(self): node = self track = [] #track.append(node) while node.parent != None: track.append(node) node = node.parent track.append(node) return track def showInfo(self): track = self.track() track.reverse() for item in track: item.showMarix() print(' it\'s child below ') def getLevel(self): return len(self.track()) def check(self): if self.list == []:# 查其是否为空 return False elif self.parent.parent != None:# 其父是否与其子一样 if self.list == self.parent.parent.list: return False else: return True else: return True def isEqual(self,list): return True if self.list == list else False def isEmpty(self): return True if self.list == [] and self.parent == None else False def getChild(self,list_begin): if self.isEmpty(): self = Node(list_begin,parent = None) return self.getChild(list_begin) ## 递归一次 else : squeues = [] # up up = self.up().copy() new_up = Node(up,self) if new_up.check(): squeues.append(new_up) #down down = self.down().copy() new_down = Node(down,self) if new_down.check(): squeues.append(new_down) #right right = self.right().copy() new_right = Node(right,self) if new_right.check(): squeues.append(new_right) #left left = self.left().copy() new_left = Node(left,self) if new_left.check(): squeues.append(new_left) return squeues def inversion(self,list): temp = list.copy() count = 0 while temp: first = temp.pop(0) for item in temp: if first > item: count += 1 return count def getAnswer(self,list_begin,list_end,uncle): inv = self.inversion(list_begin) if inv%2 == 0: childs = uncle check = 0 cousin = [] for item in childs: if item.isEqual(list_end): item.showInfo() check == 1 return uncle if check == 0: print('this is',childs[0].getLevel() + 1,'level') for item in childs: cousin.extend(item.getChild(item.list)) self.getAnswer(list_begin,list_end,cousin) else: return False def diff(self,list_end): temp = self.list count = 0 for i in range(len(list_end)): if temp[i] != list_end[i] and temp[i] != 0: # if temp[i] != list_end[i]: count += 1 return count + self.getLevel() - 1 # return count def getIndex(self,list): min = list[0] for value in list: if value < min: min = value for i in range(len(list)): if list[i] == min: return i break def rank(self,list_end,nodeSeq): rank = [] new = [] seq = nodeSeq.copy() for item in seq: rank.append(item.diff(list_end)) while seq: minIndex = item.getIndex(rank) new.append(seq.pop(minIndex)) rank.pop(minIndex) return new def getAnswerLoop(self,list_begin,list_end): inv = self.inversion(list_begin) if inv%2 == 0: open = [] close = [] seq = self.getChild(list_begin) # 插入 S open.append(seq[0].parent) # 对 S 操作 work = open.pop(0) if work.isEqual(list_end): work.showInfo() print('it is open') for i in open: i.showMarix() print(' ') print('it is close') for i in close: i.showMarix() print(' ') else: close.append(work) open.extend(seq[0].rank(list_end,seq)) while 1: work = open.pop(0) if work.isEqual(list_end): work.showInfo() print('it is open') for i in open: i.showMarix() print(' ') print('it is close') for i in close: i.showMarix() print(' ') break else: temp = [] temp.extend(open) temp.extend(work.getChild(work.list)) temp.append(work) while open: open.pop(0) open.extend(temp[0].rank(list_end,temp)) work = open.pop(0) close.append(work) print('this is',work.getLevel(),'level') else: return False if __name__ == '__main__': #begin = [ 2,0, 3, 1, 8, 4, 7, 6, 5 ] be = [ 1,0, 3, 7, 2, 4, 6, 8, 5 ] end = [1, 2, 3, 8, 0, 4, 7, 6, 5 ] node = Node() # print('盲目') # uncle = node.getChild(begin)# 要生成第一,二层 # # a = node.getAnswer(begin,end,uncle)# 检查第二层,无要得到的数则生成下一层 # uncle = node.getChild(be)# 要生成第一,二层 # b = node.getAnswer(be,end,uncle) # # print(type(a)) # print(type(b)) print('启发式') node.getAnswerLoop(be,end)
994d23b5f69d1fa674a609b9a3e2d88b37d7a8b0
caiolucasw/pythonsolutions
/exercicio2.py
490
3.828125
4
def fatorial(numeros): fatoriais = [] num = 1 lista = converteInteiro(numeros) for i in lista: for numero in range(1,i+1): num *= numero fatoriais.append(str(num)) num = 1 print(','.join(fatoriais)) def converteInteiro(lista): listaInt = [] for item in lista: listaInt.append(int(item)) return listaInt valor = input("Números para calcular o fatorial ") lista = valor.split(' ') fatorial(lista)
f7a6b53e7eecd5911c1bf9e0929636f57325d65e
coder-hello2019/Stanford-Algorithms
/Week 3/quicksort1.py
2,547
4.0625
4
""" Implementation of quicksort for week 3 of Stanford's algorithms course, which also counts the number of comparison in the given quicksort iteration. In this iteration (for part 1 of pset 3), the pivot is always the first element of the unsorted array. """ import random def quicksort(unsorted): if len(unsorted) <= 1: return (unsorted, 0) pivot = unsorted[0] #initiate i,j to the first array element which isn't the pivot i = 1 counter = len(unsorted) - 1 # look at each element in the array except for the pivot and partition the array for j in range (1, len(unsorted)): #print(f"Current i and j: {i}, {j}") if unsorted[j] > pivot: # we don't need to do anything other than advancing the j pointer pass # need to swap the jth element with the last element in the 'less than pivot' portion of the list and advance the i pointer elif unsorted[j] < pivot: unsorted[i], unsorted[j] = unsorted[j], unsorted[i] i += 1 # put pivot in the correct place in the list by swapping the pivot with the last element of the 'smaller than pivot list' unsorted[i - 1], unsorted[0] = unsorted[0], unsorted[i - 1] # section of array with nums less than pivot leftList = unsorted[0:i - 1] # section of array with nums greater than pivot rightList = unsorted[i:] # call function recursively on the partitioned portions of the list # i think the prob here is that we're calling this on copies of the list as opposed to doing the partitioning sub-routine on the same list left = quicksort(leftList) right = quicksort(rightList) counter += left[1] counter += right[1] leftList = left[0] rightList = right[0] sorted = [] sorted.extend(leftList) sorted.append(pivot) sorted.extend(rightList) """ if len(sorted) == 10: print(f"Sorted array: {sorted}") print(f"Counter: {counter}") """ return (sorted, counter) # function to generate test lists def testGenerator(): list = [] while len(list) < 10: randomNum = random.randrange(0, 100) if randomNum not in list: list.append(randomNum) return list """ Testcases test1 = [3,6,7,2,1] test2 = testGenerator() print(f"Test2: {test2}") """ def main(): qfile = open("quicksort.txt", "r") numsList = [] for item in qfile.read().splitlines(): numsList.append(int(item)) qfile.close() print(quicksort(numsList)) main()
f2a81481ccc9626de8b7718f99686bf8eae2a383
PatrickNgare/Python-lati-game
/paridome.py
128
4.15625
4
name=input("enter a string") name2=name[::-1] if name==name2: print("is a paridrome") else: print("is not a paridrome")
93427d777bc38e85449277c260b26d47f9c015f9
Wbonney88/Tech-Academy-Projects
/Python/Item_62.py
1,080
3.546875
4
import datetime class EST(datetime.tzinfo): def utcoffset(self, dt): return datetime.timedelta(hours=-4) def dst(self, dt): return datetime.timedelta(0) class UTC1(datetime.tzinfo): def utcoffset(self, dt): return datetime.timedelta(hours=+1) def dst(self, dt): return datetime.timedelta(0) portland = datetime.datetime.now().time() newYork = datetime.datetime.now(EST()).time() london = datetime.datetime.now(UTC1()).time() openHours = datetime.time(9) closeHours = datetime.time(18) def checkLondon(london,openHours,closeHours): if london > openHours and london < closeHours: print("\nThe London office is currently open") else: print("\nThe London office is currently closed") def checkNewYork(newYork,openHours,closeHours): if newYork > openHours and newYork < closeHours: print("\nThe New York office is currently open") else: print("\nThe New York office is currently closed") checkLondon(london,openHours,closeHours) checkNewYork(newYork,openHours,closeHours)
1abcbe7b77828f5f1b76d490e1ec548ea447ab11
Aliena28898/Programming_exercises
/CodeWars_exercises/The falling speed of petals.py
925
3.90625
4
''' When it's spring Japanese cherries blossom, it's called "sakura" and it's admired a lot. The petals start to fall in late April. Suppose that the falling speed of a petal is 5 centimeters per second (5 cm/s), and it takes 80 seconds for the petal to reach the ground from a certain branch. Write a function that receives the speed (in cm/s) of a petal as input, and returns the time it takes for that petal to reach the ground from the same branch. Notes: The movement of the petal is quite compilcated, so in this case we can see the velocity as a constant during its falling. Pay attention to the data types. If the initial velocity is non-positive, the return value should be 0 ''' #SOLUTION: Test.assert_equals(sakura_fall(5), 80) Test.assert_equals(sakura_fall(10), 40) Test.assert_equals(sakura_fall(-1), 0) Test.assert_equals(sakura_fall(0), 0) #TESTS: def sakura_fall(v): return 400/v if v > 0 else 0
f0618d37529d75675ca971edef5b41f12918c855
jiangorbit/Rhymego
/seq_search.py
507
3.828125
4
#!/usr/bin/env python3 def sequence_search(sequence, target): #for i in range(len(sequence)): # if target == sequence[i]: # return i # else: # return None i = 0 while i <= len(sequence): if target == sequence[i]: return i else: i += 1 if i == len(sequence): return None if __name__ == '__main__': sequence = [99,12,33,74,521,13,14] target = 44 print(sequence_search(sequence, target))
7a4eb01f16e2822c84f2a4fb531ef74dc11b0340
minirgb2019/Classification_Titanic
/Classification Titanic2.py
15,455
4.15625
4
#!/usr/bin/env python # coding: utf-8 # In[1]: #Classification Project # In this project you will perform a basic classification task. # You will apply what you learned about binary classification and tensorflow to implement a Kaggle project without much guidance. The challenge is to achieve a high accuracy score when trying to predict which passengers survived the Titanic crash. After building your model, you will upload your predictions to Kaggle and submit the score that you receive. # In[ ]: ## Titanic: Machine Learning from Disaster # [Kaggle](https://www.kaggle.com) has a [dataset](https://www.kaggle.com/c/titanic/data) containing the passenger list for the Titanic voyage. The data contains passenger features such as age, gender, and ticket class, as well as whether or not they survived. # Your job is to load the data and create a binary classifier using TensorFlow to determine if a passenger survived or not. Then, upload your predictions to Kaggle and submit your accuracy score at the end of this colab, along with a brief conclusion. # In[12]: ## Exercise 1: Create a Classifier # 1. Download the [dataset](https://www.kaggle.com/c/titanic/data). # 2. Load the data into this Colab. # 3. Look at the description of the [dataset](https://www.kaggle.com/c/titanic/data) to understand the columns. # 4. Explore the dataset. Ask yourself: are there any missing values? Do the data values make sense? Which features seem to be the most important? Are they highly correlated with each other? # 5. Prep the data (deal with missing values, drop unnecessary columns, transform the data if needed, etc). # 6. Split the data into testing and training set. # 7. Create a `tensorflow.estimator.LinearClassifier`. # 8. Train the classifier using an input function that feeds the classifier training data. # 9. Make predictions on the test data using your classifier. # 10. Find the accuracy, precision, and recall of your classifier. get_ipython().system('pip install pyserial') # In[16]: get_ipython().system('pip install pandas') # In[44]: get_ipython().system('pip install matplotlib') # In[46]: get_ipython().system('pip install seaborn') # In[47]: # First load data into Colab import pandas as pd import matplotlib.pyplot as plt import seaborn as sns titanic_train = pd.read_csv('./train.csv') titanic_train.head() # In[48]: # Look at description of dataset titanic_train.describe() # In[51]: #Data Exploration # In[49]: # Let's see shape of data print("dimension of titanic training data: {}".format(titanic_train.shape)) # In[50]: # See if all data types make sense titanic_train.dtypes # In[52]: # See how many NaN values per column titanic_train.isnull().sum() # In[53]: # We can see a visual representation of the missing values sns.heatmap(titanic_train.isnull(),yticklabels=False,cbar=False) plt.show() # In[ ]: # Now let's look at the percentage of people that survived based on class # In[55]: titanic_train[["Sex", "Survived"]].groupby(['Sex'], as_index=False).mean().sort_values(by='Survived', ascending=False) # In[56]: sns.set_style('whitegrid') sns.countplot(x='Survived',hue='Sex',data=titanic_train,palette='RdBu_r') plt.show() # In[57]: # Look at distribution of age sns.distplot(titanic_train['Age'].dropna(),kde=False,color='darkred',bins=30) plt.show() # In[58]: # Look at distribution of fares on board titanic_train['Fare'].hist(color='blue',bins=40,figsize=(8,4)) plt.show() # In[ ]: # We know many values for age are missing so well impute those based on mean for each class # In[59]: # box-and-whisker plots of age based on class plt.figure(figsize=(12, 7)) sns.boxplot(x='Pclass',y='Age',data=titanic_train,palette='winter') plt.show() # In[61]: # Create function to impute age def impute_age(cols): Age = cols[0] Pclass = cols[1] if pd.isnull(Age): if Pclass == 1: return 37 elif Pclass == 2: return 29 else: return 24 else: return Age # In[62]: # Impute age titanic_train['Age'] = titanic_train[['Age','Pclass']].apply(impute_age,axis=1) # In[63]: # Let's see if there are nay duplicate rows titanic_train.duplicated().sum() > 0 # In[64]: # Let's take a look at the correlation matrix #Create Correlation df corr = titanic_train.corr() #Plot figsize fig, ax = plt.subplots(figsize=(10, 10)) #Generate Color Map colormap = sns.diverging_palette(220, 10, as_cmap=True) #Generate Heat Map, allow annotations and place floats in map sns.heatmap(corr, cmap=colormap, annot=True, fmt=".2f") #Apply xticks plt.xticks(range(len(corr.columns)), corr.columns); #Apply yticks plt.yticks(range(len(corr.columns)), corr.columns) #show plot plt.show() # In[ ]: ## Preparing the Data # In[65]: # Need to turn categorical variables into numerical values from sklearn.preprocessing import LabelEncoder # Encode sex le = LabelEncoder() le.fit(titanic_train.Sex) titanic_train.Sex = le.transform(titanic_train.Sex) # # Encode Embarked # le = LabelEncoder() # le.fit(titanic_train.Embarked) # titanic_train.Embarked = le.transform(titanic_train.Embarked) # titanic_train.head() ########################################################################## dummy = pd.get_dummies(titanic_train['Embarked']) # Create a new_df which now contains dummy variables titanic_train = pd.concat([titanic_train, dummy], axis=1) titanic_train.drop(['Embarked'], axis=1, inplace=True) titanic_train.head() # In[66]: # Correlation matrix again #Create Correlation df corr = titanic_train.corr() #Plot figsize fig, ax = plt.subplots(figsize=(10, 10)) #Generate Color Map colormap = sns.diverging_palette(220, 10, as_cmap=True) #Generate Heat Map, allow annotations and place floats in map sns.heatmap(corr, cmap=colormap, annot=True, fmt=".2f") #Apply xticks plt.xticks(range(len(corr.columns)), corr.columns); #Apply yticks plt.yticks(range(len(corr.columns)), corr.columns) #show plot plt.show() # In[67]: # Now according to the corr matrix, we'll only use # sex, age, and fare as our features final_df = titanic_train[['Sex', 'Pclass', 'Age', 'Survived']] # took out fare, put age back in final_df.head() final_df.columns[0] #final_df.shape # In[68]: # Lets see value counts for how many people survived and how many died final_df.Survived.value_counts() # In[ ]: ## Split data for model # In[69]: from sklearn.model_selection import train_test_split # X = final_df.iloc[:,:4] # y = final_df.iloc[:, 4] # #X.head() # X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42) train_df, test_df = train_test_split( final_df, stratify=final_df['Survived'], test_size=0.2, ) # In[ ]: # Now we'll create our feature columns # In[70]: from tensorflow.feature_column import numeric_column from tensorflow.feature_column import categorical_column_with_identity feature_columns = [] for column_name in final_df.columns[:2]: #eature_columns.append(numeric_column(str(column_name))) feature_columns.append(categorical_column_with_identity(column_name, 3 if column_name=='Sex' else 2, default_value=1)) for column_name in final_df.columns[2:-1]: feature_columns.append(numeric_column(column_name)) feature_columns # In[ ]: # Find the number of classes # In[71]: # We know there are 2 classes class_count = len(final_df['Survived'].unique()) class_count # In[ ]: ## Create classifier # In[77]: get_ipython().system('pip install tensorflow') # In[78]: from tensorflow.estimator import LinearClassifier classifier = LinearClassifier(feature_columns=feature_columns, n_classes=class_count) # In[ ]: ## Train classifier # In[79]: import tensorflow as tf from tensorflow.data import Dataset # Instead of creating a df like in sklearn, # in tf we have to create a function which returns a # tensorflow training dataset features1 = ["Sex", "Pclass", "Age"] # took out age, fare target = "Survived" def training_input(): features = {} # here set key and value is all values for that column in train_df for i in train_df[features1]: features[i] = train_df[i] labels = train_df[target] training_ds = Dataset.from_tensor_slices((features, labels)) training_ds = training_ds.shuffle(buffer_size=10000) training_ds = training_ds.batch(100) training_ds = training_ds.repeat(5) #Maybe increase???? return training_ds classifier.train(training_input) # In[ ]: ## Make Test Predictions # In[80]: # create tf testing dataset def testing_input(): features = {} for i in train_df[features1]: features[i] = test_df[i] return Dataset.from_tensor_slices((features)).batch(1) predictions_iterator = list(classifier.predict(testing_input)) predictions_iterator # In[81]: pred_probs = [] for p in predictions_iterator: pred_probs.append([p['probabilities'][0], p['probabilities'][1]]) print(pred_probs) # In[ ]: ## Accuracy, Precision, and Recall # In[82]: for p in predictions_iterator: print(p.keys()) print(p['logits']) print(p['probabilities']) print(p['class_ids']) print(p['classes']) break # In[83]: predictions_iterator = classifier.predict(testing_input) predictions = [p['class_ids'][0] for p in predictions_iterator] # In[84]: from sklearn.metrics import precision_score from sklearn.metrics import recall_score from sklearn.metrics import accuracy_score prec = precision_score(test_df['Survived'], predictions) recall = recall_score(test_df['Survived'], predictions) accuracy = accuracy_score(test_df['Survived'], predictions) print('Precision score: {}'.format(prec)) print('Recall score: {}'.format(recall)) print('Accuracy: {}'.format(accuracy)) # In[ ]: ## Exercise 2: Upload your predictions to Kaggle # In[ ]: # 1. Download the test.csv file from Kaggle and re-run your model using all of the training data. # 2. Use this new test data to generate predictions using your model. # 3. Follow the instructions in the [evaluation section](https://www.kaggle.com/c/titanic/overview/evaluation) to output the preditions in the format of the gender_submission.csv file. Download the predictions file from your Colab and upload it to Kaggle. # **Written Response** # Write down your conclusion along with the score that you got from Kaggle. # In[85]: # Download the new test.csv file titanic_test = pd.read_csv('./test.csv') titanic_test.head() # In[ ]: # Now re-run the model using all of the training data # In[86]: # Re-running model using all training data import tensorflow as tf from tensorflow.data import Dataset # Instead of creating a df like in sklearn, # in tf we have to create a function which returns a # tensorflow training dataset features1 = ["Sex", "Pclass", "Age"] # took out fare, put age back in target = "Survived" def training_input(): features = {} # here set key and value is all values for that column in train_df for i in final_df[features1]: features[i] = final_df[i] labels = final_df[target] training_ds = Dataset.from_tensor_slices((features, labels)) training_ds = training_ds.shuffle(buffer_size=10000) training_ds = training_ds.batch(100) training_ds = training_ds.repeat(5) #Maybe increase???? return training_ds classifier.train(training_input) # In[ ]: ## Clean test data # In[87]: # See how many NaN values per column titanic_test.isnull().sum() # In[88]: # box-and-whisker plots of age based on class plt.figure(figsize=(12, 7)) sns.boxplot(x='Pclass',y='Age',data=titanic_test,palette='winter') plt.show() # In[89]: # Create function to impute age def impute_age(cols): Age = cols[0] Pclass = cols[1] if pd.isnull(Age): if Pclass == 1: return 37 elif Pclass == 2: return 29 else: return 24 else: return Age # In[90]: # Impute age titanic_test['Age'] = titanic_test[['Age','Pclass']].apply(impute_age,axis=1) # In[91]: # Let's see if there are any duplicate rows titanic_test.duplicated().sum() > 0 # In[92]: # Need to turn categorical variables into numerical values from sklearn.preprocessing import LabelEncoder # Encode sex le = LabelEncoder() le.fit(titanic_test.Sex) titanic_test.Sex = le.transform(titanic_test.Sex) dummy = pd.get_dummies(titanic_test['Embarked']) # Create a new_df which now contains dummy variables titanic_test = pd.concat([titanic_test, dummy], axis=1) titanic_test.drop(['Embarked'], axis=1, inplace=True) titanic_test.head() # In[93]: # Store the passenger ids in separate df pass_id = titanic_test['PassengerId'] pass_id.head() # In[94]: # Just checking it stored all ids for i in pass_id: print(i) # In[95]: # Now only keep the features that we need for model final_test_df = titanic_test[['Sex', 'Pclass', 'Age']] # took out fare, put age back in final_test_df.head() # In[96]: # Now that the test data is clean , we will use it to generate predictions using your model. # In[97]: # Use test.csv for testing dataset def testing_input(): features = {} for i in final_df[features1]: features[i] = final_test_df[i] ######################## changed test_def return Dataset.from_tensor_slices((features)).batch(1) predictions_iterator = list(classifier.predict(testing_input)) predictions_iterator # In[98]: predictions_iterator = classifier.predict(testing_input) predictions = [p['class_ids'][0] for p in predictions_iterator] # In[99]: # Make sure I have a prediction for every id print(len(predictions)) print(pass_id.shape) # In[100]: # Store ids in a list for later use final_csv = [] pair = [] ids = [] for i in range(len(predictions)): ids.append(pass_id[i]) # In[101]: # Use id and predictions arrays to make dictionary final_csv_dict = {'PassengerId': ids, 'Survived': predictions} # Turn dictionary into df final_csv_df = pd.DataFrame.from_dict(final_csv_dict) final_csv_df.head() # In[102]: # create csv to submit to kaggle final_csv_df.to_csv('predictions.csv', encoding='utf-8', index=False) # In[103]: ## Exercise 3: Improve your model # In[104]: # The predictions returned by the LinearClassifer contain scoring and/or confidence information about why the decision was made to classify a passenger as a survivor or not. Find the number used to make the decision and manually play around with different thresholds to build a precision vs. recall chart. # In[105]: y_test = [] for i in test_df['Survived']: y_test.append(i) print(y_test) # In[106]: print(len(y_test)) print(len(pred_probs)) # In[107]: y_score = [x[1] for x in pred_probs] # In[108]: from sklearn.metrics import average_precision_score, auc, roc_curve, precision_recall_curve average_precision = average_precision_score(y_test, y_score) print('Average precision-recall score RF: {}'.format(average_precision)) # In[109]: from sklearn.metrics import precision_recall_curve import matplotlib.pyplot as plt precision, recall, _ = precision_recall_curve(y_test, y_score) plt.step(recall, precision, color='b', alpha=0.2, where='post') plt.fill_between(recall, precision, step='post', alpha=0.2, color='b') plt.xlabel('Recall') plt.ylabel('Precision') plt.ylim([0.0, 1.05]) plt.xlim([0.0, 1.0]) plt.title('2-class Precision-Recall curve: AP={0:0.2f}'.format( average_precision)) # In[ ]: Kaggle score was: 0.765555
bbe1872a39d2710e533562a61ad3b6608aeef04c
Kawser-nerd/CLCDSA
/Source Codes/CodeJamData/11/31/5.py
775
3.515625
4
#!/usr/bin/env python3.1 from __future__ import division import sys def calc(numLines, line): ok = True while ok: ok = False for i in range(len(line)): f = line[i].find("#") if f >= 0: if i == len(line) - 1 or f == len(line[i]) - 1 or line[i][f:f+2] != "##" or line[i+1][f:f+2] != "##": print "Impossible" return line[i] = line[i][:f] + "/\\" + line[i][f+2:] line[i+1] = line[i+1][:f] + "\\/" + line[i+1][f+2:] ok = True break for l in line: print l def getints(): return [int(x) for x in sys.stdin.readline().strip().split(" ")] numTestCases = getints()[0] for i in range(numTestCases): numLines = getints() print("Case #%d:" % (i+1)) result = calc(numLines, [sys.stdin.readline().strip() for x in range(numLines[0])])
88867f5b67d62feabf85cf160b9f551a86c5e765
Nisar-1234/Data-structures-and-algorithms-1
/Heaps (or Priority Queue)/Running Median of an Integer Stream.py
1,193
3.71875
4
# User function Template for python3 global min_heap min_heap = [] global max_heap max_heap = [] class Solution: def balanceHeaps(self): if len(max_heap) > len(min_heap) + 1: topElement = heapq.heappop(max_heap) heapq.heappush(min_heap, -1 * topElement) elif len(min_heap) > len(max_heap) + 1: topElement = heapq.heappop(min_heap) heapq.heappush(max_heap, -1 * topElement) def getMedian(self): if len(max_heap) > len(min_heap): currMedian = -1 * max_heap[0] return currMedian elif len(min_heap) > len(max_heap): currMedian = min_heap[0] return currMedian elif len(max_heap) == len(min_heap): currMedian = (-1 * max_heap[0] + min_heap[0]) // 2 # NOTE: if the test case wants integer values then use '//' return currMedian # else use '/' to get float values def insertHeaps(self, x): if len(max_heap) == 0 or -1 * max_heap[0] > x: heapq.heappush(max_heap, -1 * x) else: heapq.heappush(min_heap, x)
afa6d83c8fb677699211a0929bf5eaa8926c4afd
rubychen0611/LeetCode
/Problemset/word-pattern/word-pattern.py
701
3.765625
4
# @Title: 单词规律 (Word Pattern) # @Author: rubychen0611 # @Date: 2021-01-23 15:15:11 # @Runtime: 36 ms # @Memory: 14.9 MB class Solution: def wordPattern(self, pattern: str, s: str) -> bool: map1 = {} map2 = {} strs = s.split() if len(pattern) != len(strs): return False for ch, word in zip(pattern, strs): if ch not in map1.keys() and word not in map2.keys(): map1[ch] = word map2[word] = ch elif ch not in map1.keys() or word not in map2.keys(): return False elif map1[ch] != word or map2[word] != ch: return False return True
dc20c32cc670dba4af8170d57706ed3ad892f4dc
fwparkercode/ProgrammingPygame
/Problem Sets/ps_04.py
3,521
4.40625
4
''' Chapter 04 Problem Set (21pts)") Instructions: For each of the following, enter your answer below the numbered problem. Ensure the code runs properly without errors. Make sure your file executes before you submit it! If a single problem is not working properly, please comment it out of your code. If a question is commented out, it will receive partial credit. Non working or broken code will not receive any credit for that problem. ''' ################################# # Problem 1 (2pts) #Write a Python program that will use a for loop to print your name 5 times on separate lines, and then the word \"Done\" on the last line. ''' Sample Run: Francis Francis Francis Francis Francis Done ''' ################################# # Problem 2 (2pts) #Write a Python program that will use a for loop to print your first name 3 times and then your last name 3 times. Repeat this pattern (3 first followed by 3 lasts) 10 times. ''' Sample Run Francis Francis Francis Parker Parker Parker Above repeated 10 times ''' ################################# # Problem 3 (Multiples of seven - 2pts) ''' Write a Python program that will use a for loop to print multiples of seven from 21 to 70. (70 must be included) ''' ################################# # Problem 4 (Countdown - 2pts) #Write a Python program that will use a while loop to count from 10 down to 1. Then print the words \"Blast off!\" Remember, this time we will use a WHILE loop, don't use a FOR loop. ################################# # Problem 5 (Random ints - 2pts) #Write a program that prints a random integer from 1 to 10. Put it in a loop so that it prints a different random integer 10 times ''' Sample Run 4 2 5 9 10 1 8 4 3 3 ''' ########################### # Problem 6 (Random floats - 2pts) # Write a program that prints a random floating point number somewhere between 1 and 10 (inclusive). Do not make the mistake of generating a random number from 0 to 10 instead of 1 to 10. Put it in a loop to print a differnt random float 10 times. ''' Sample Run 2.987862719820445 6.870129734673759 4.434092587298322 9.929302003474453 6.0609415060503515 8.428599151662887 6.715550409049674 1.083673547723635 7.917120042736795 8.982349679748726 ''' ################################# # Problem 7 (Coin Flipper - 4pts) ''' Make a Coin flipper: * Start by creating a program that will print a random 0 or 1. * Then, instead of 0 or 1, make it print heads or tails. * Add a loop so that the program does this 100 times. * Print the total number of heads flipped, and the number of tails. If done properly, you will likely have around half heads and half tails. ''' ################################# # Problem 8 (Rock Paper Scissors - 5pts) '''Write a program that plays rock, paper, scissors: * Create a program that randomly prints 0, 1, or 2. * Expand the program so it randomly prints rock, paper, or scissors using if statements. Don't select from a list, as shown in the chapter. This random selection will be the computer's choice. * Add to the program so it first asks the user their choice.(It might be easier if you have them enter a number instead of rock, paper, or scissors. See sample run) * Add conditional statement to figure out who wins and print back the result to the user. ''' ''' Sample run: Welcome to rock paper scissors: Enter your choice (0 for rock, 1 for paper, or 2 for scissors): 1 Player chooses paper. Computer chooses rock. Congratulations, you win. '''
63fcb32b1526fab64e6f405bed4356e724fe6f0d
aniketverma-7/CO_OS_LAB
/ROUND_ROBIN_ZERO_AT.py
1,998
3.84375
4
''' Author : ANIKET VERMA Enroll : 0827CO191012 FCFS with zero arrivial timw takeInput() -> takes input form user waiting() -> calculate total waiting time turntime -> calculate turn around time printData() -> print all process with waiting and turn around time in tabular form. makecopy() -> make copy of list Process -> represent class of all process Round Robin -> represent class of all operation performed on RR process ''' class Process: def __init__(self,id,bt): self.id=id self.bt=bt class RoundRobin: def takeInput(self): temp = [] total=0 n = int(input("Enter No. of Process : ")) q = int(input("Time Quantum : ")) for i in range(n): print("Process ID :",i+1) bt = int(input("Burst Time : ")) total+=bt p = Process(i+1,bt) temp.append(p) return temp,total,q def printData(self,process,turn,wait,sumW,sumT): n = len(process) print("Process ID Burst Time Turnaround Time Waiting Time") for i in range(n): print(process[i].id,"\t\t",process[i].bt,"\t\t",turn[i],"\t\t",wait[i]) print("Average Waiting Time : ",sumW/n) print("Average Turn Around Time : ",sumT/n) def turntime(self,process,total,tq): sumT = 0 x=0 n=len(process) turn = [0]*n temp=0 while temp!=total: for i in range(n): if process[i].bt>0: if process[i].bt > tq: temp+=tq process[i].bt-=tq else: temp+=process[i].bt turn[i] = temp sumT+=turn[i] process[i].bt=0 return sumT,turn def waiting(self,turn,process): n = len(process) wait=[0]*n sumW=0 for i in range(n): wait[i] = turn[i]-process[i].bt sumW+=wait[i] return sumW,wait def makeCopy(self,process): copy = [0]*(len(process)) for i in range(len(process)): copy[i] = Process(process[i].id,process[i].bt) return copy r = RoundRobin() process,total,q = r.takeInput() copy=r.makeCopy(process) sumT,turn = r.turntime(copy,total,q) sumW,wait = r.waiting(turn,process) r.printData(process,turn,wait,sumW,sumT)
8404a23099a3bafc86f4f307cc3d01454e311757
smohapatra1/scripting
/python/practice/start_again/2021/01252021/power_of_nums.py
368
4.53125
5
#Python Program to find Power of a Number #Write a Python Program to find Power of a Number For Loop, While Loop, and pow function with an example. from math import pow def main(): a = int(input("Enter a number: ")) b = int(input("Enter the exonent value: ")) print ("{}' exponent of {} is : {}".format(b,a, pow(a,b))) if __name__ == "__main__": main()
03aa65c6c68842156f69587884694b48fc9c23d0
AMY-ABOUGHAZY/udacity-bertelsmann-data-science-challenge-scholarship-2018
/control_flow_lesson_25/while_loops.py
1,459
4.4375
4
# while Loops # 1.Practice: Water Falls # Print string vertical. print_str = "Water falls" # initialize a counting variable "i" to 0 i = 0 # write your while header line, comparing "i" to the length of the string while i < len(print_str): #print out the current character from the string print(print_str[i]) #increment counter variable in the body of the loop i = i + 1 #print(print_str) # 2.Practice: Factorials with While Loops """ Find the Factorial of a Number, using While Loop. A factorial of a whole number is that number multiplied by every whole number between itself and 1. For example, 6 factorial (written "6!") equals 6 x 5 x 4 x 3 x 2 x 1 = 720. So 6! = 720. We can write a while loop to take any given number, and figure out what its factorial is. Example: If number is 6, your code should compute and print the product of 720: """ number = 6 product = number while number > 1: number = number - 1 product = product * number print(product) # 3.Practice: Factorials with For Loops # Now use a For Loop to Find the Factorial! number = 6 # We'll start with the product equal to the number product = number # Write a for loop that calculates the factorial of our number for num in range(1, number): if num > 1: number = number - 1 product = product * number print(product) # another solution without if statement for num in range(1, number): product *= num print(product)
748576177972b466ca45f6ce4b3ae97b245b78cb
martin-chobanyan/rl-playground
/scripts/maze_solver/main.py
866
4.1875
4
"""A demo example for both the Dijkstra and Value Iteration solutions to a random maze""" import matplotlib.pyplot as plt from dijkstra import dijkstra_solution from generate_maze import MazeGenerator from maze_utils import plot_maze from value_iter import MazeEnvironment, value_iteration_solution if __name__ == '__main__': # create the maze GRID_HEIGHT = 40 GRID_WIDTH = 40 create_maze = MazeGenerator() maze = create_maze(GRID_HEIGHT, GRID_WIDTH) # gather both solutions d_solution = dijkstra_solution(maze) v_solution, *_ = value_iteration_solution(MazeEnvironment(maze)) # plot the solutions fig, (ax1, ax2) = plt.subplots(1, 2) ax1 = plot_maze(ax1, maze, d_solution) ax2 = plot_maze(ax2, maze, v_solution) ax1.set_title('Dijkstra Solution') ax2.set_title('Value Iteration Solution') plt.show()
6477c735889aff7d2370ab8d4d6074b91c4be172
Threesome2/pythonstudy
/Liaoxuefengbiji/D8.13/code12.py
741
3.6875
4
#code12.py def trim(strs): if strs=='': return strs i=0 while strs[i] == ' ': if i == len(strs)-1: return '' i+=1 j=-1 while strs[j] == ' ': j-=1 # print(i ,j) str_trim=strs[i:len(strs)+j+1] print(str_trim) return str_trim # strs=trim(' asda sd') # print(strs,'1') if trim('hello ') != 'hello': print('测试失败!') elif trim(' hello') != 'hello': print('测试失败!') elif trim(' hello ') != 'hello': print('测试失败!') elif trim(' hello world ') != 'hello world': print('测试失败!') elif trim('') != '': print('测试失败!') elif trim(' ') != '': print('测试失败!') else: print('测试成功!')
51b3b1f6b5e9fca80ee2acc0bb46d8ab92e89aeb
maicon-silva/vccode
/Lista de exercicios 1/Exercício 12.py
592
4.15625
4
# Crie um algoritmo que calcule a área de uma esfera, sendo que o comprimento do raio é informado pelo usuário. # A área da esfera é calculada multiplicando-se 4 vezes pi e o raio ao quadrado. # Mostra as informações necessáras a tarefa print("Para efetuarmos o cálculo da área da esfera, precisamos saber o valor do raio.") # Importar a biblioteca matemática. import math # Variavel raio raio_esfera = float(input("Insira o valor do raio da esfera: ")) area_esfera = 4 * math.pi * (raio_esfera**2) area_esfera = round(area_esfera, 4) print(f"A área da esfera é {area_esfera}.")
6b754d76bd200c2cdc55d7680dff90da33620545
Arvindpawar0345/Rolling-dices-for-beginners
/Simple Code.py
1,055
3.625
4
import random print('Welcome to Rolling Dies') x="y" while x=="y": number = random.randint(1,6) if number==1: print('--------') print('| |') print('| 0 |') print('| |') print('--------') if number==2: print('--------') print('| 0 |') print('| 0 |') print('| |') print('--------') if number==3: print('--------') print('| 0 |') print('| 0 |') print('| 0 |') print('--------') if number==4: print('--------') print('| 0 0 |') print('| |') print('| 0 0 |') print('--------') if number==5: print('--------') print('| 0 0 |') print('| 0 |') print('| 0 0 |') print('--------') if number==6: print('--------') print('| 0 0 0 |') print('| 0 0 0 |') print('| 0 0 0 |') print('--------') x=input('you want continune press y or n')
2193e0c65a2795e490e4a8e7efd304f32162a52b
VaishnaviReddyGuddeti/Python_programs
/Python_Keywords/from.py
190
3.640625
4
# To import specific parts of a module # Import only the time section from the datetime module, and print the time as if it was 15:00: from datetime import time x = time(hour=15) print(x)
a6f61271c69408ce7a7a1360cdd0884a446fa52f
fdomuma/Password-tips
/interface.py
1,627
3.625
4
from tkinter import * import pandas as pd root = Tk() root.title("Password manager") # Search feature searchBox = Entry(root, width=50, borderwidth=5) searchBox.insert(0, "Look for place!") searchBox.grid(row=0, column=1, columnspan=2) def searchPlace(): db = pd.read_csv("pass_db.csv", sep=";") keys = searchBox.get() rowIndex = db["Place"].str.contains(keys, case=False) if len(rowIndex) > 1: rowIndex = rowIndex[0] global structure, place, keyword structure, place, keyword = db.iloc[rowIndex.index[0]].values structureValue = Label(root, text=structure) placeValue = Label(root, text=place) keywordValue = Label(root, text=keyword) structureValue.grid(column=1, row=1, columnspan=2) placeValue.grid(column=1, row=2, columnspan=2) keywordValue.grid(column=1, row=3, columnspan=2) searchButton = Button(root, text="Search", command=searchPlace) searchButton.grid(row=0, column=0) # Showing attributes structureKey = Label(root, text="Structure: ") placeKey = Label(root, text="Place: ") keywordKey = Label(root, text="Keyword: ") structureKey.grid(column=0, row=1) placeKey.grid(column=0, row=2) keywordKey.grid(column=0, row=3) # Features newButton = Button(root, text="Create password", bg="green", padx=8, pady=8) editButton = Button(root, text="Edit", padx=8, pady=8, width=12) deleteButton = Button(root, text="Delete", bg="red", padx=8, pady=8, width=12) freeRow = Label(root, text="") freeRow.grid(column=0, row=4, columnspan=3) newButton.grid(column=0, row=5) editButton.grid(column=1, row=5) deleteButton.grid(column=2, row=5) root.mainloop()
aabbb469f273f95d97f6fa28a768bc6dc9ccfb64
xiaoxue11/machine_learning
/ex2/plotDecisionBoundary.py
1,139
3.5625
4
# -*- coding: utf-8 -*- """ Created on Thu Nov 15 22:34:07 2018 @author: 29132 """ from plotData import plotData import numpy as np import matplotlib.pyplot as plt from mapf import mapFeature def plotDecisionBoundary(theta,X,y): plotData(X[:,1:3], y) if X.shape[1] <= 3: # Only need 2 points to define a line, so choose two endpoints plot_x = np.array([np.min(X[:,1])-2, np.max(X[:,1])+2]) plot_y=(-1/theta[2])*(theta[1]*plot_x+theta[0]) plt.plot(plot_x, plot_y) plt.legend(labels=['Admitted', 'Not admitted','Decision Boundary']) plt.axis([30, 100, 30, 100]) else: # Here is the grid range u = np.linspace(-1, 1.5, 50); v = np.linspace(-1, 1.5, 50); z = np.zeros((np.size(u), np.size(v))) # Evaluate z = theta*x over the grid for i in range(np.size(u)): for j in range(np.size(v)): z[i,j] = np.dot(mapFeature(u[i],v[j]),theta); z = z.T; # important to transpose z before calling contour # Plot z = 0 # Notice you need to specify the range [0, 0] plt.contour(u, v, z,[0,1])
12711bb519946f76b9b25258edac051ad3b4e321
dantefung/Python-Codebase
/study_sample/test_scope.py
1,406
3.84375
4
r''' 作用域 在一个模块中,我们可能会定义很多函数和变量,但有的函数和变量我们希望给别人使用, 有的函数和变量我们希望仅仅在模块内部使用。在Python中,是通过_前缀来实现的。 正常的函数和变量名是公开的(public),可以被直接引用,比如:abc,x123,PI等; 类似__xxx__这样的变量是特殊变量,可以被直接引用,但是有特殊用途, 比如上面的__author__,__name__就是特殊变量,hello模块定义的文档注释也可以用特殊变量__doc__访问, 我们自己的变量一般不要用这种变量名; 类似_xxx和__xxx这样的函数或变量就是非公开的(private),不应该被直接引用,比如_abc,__abc等; 之所以我们说,private函数和变量“不应该”被直接引用,而不是“不能”被直接引用, 是因为Python并没有一种方法可以完全限制访问private函数或变量,但是,从编程习惯上不应该引用private函数或变量。 private函数或变量不应该被别人引用,那它们有什么用呢?请看例子: ''' def _private_1(name): return 'Hello, %s' % name def _private_2(name): return 'Hi, %s' % name def greeting(name): if len(name) > 3: return _private_1(name) else: return _private_2(name) print(greeting(input('请输入你的名字:')))
10d86c8edcdf85ee0a9f0c4b2c6f78f76eb5fb62
chris7seven/DU-Projects
/COMP-3006/Project 3/project3.py
4,990
4.4375
4
#Christopher Seven #Project 3 import random #The card game that will be implemented is blackjack. The player will be playing against a dealer, and will be able to decide to hit or stay #Since the game is blackjack, the suits of each card will not be kept track of, as they will not be used #A deal function is necessary to pull random cards from the deck to simulate 'dealing' in a casino def deal(deck): #This is a reference from hand to an empty list hand = [] #The deck is shuffled. random.shuffle(deck) for i in range(0, 2): #Here is a reference from card to the last element in list 'deck' card = deck.pop() hand.append(card) return hand #This function simulatees the act of a dealer "hitting" the hand of the player, by adding an additional card to the player's hand def hit(hand, deck): #Once again, a reference from card to the last element in the list 'deck' card = deck.pop() hand.append(card) return hand #A function that tallies up the score of a hand to determine if it is winning or not def score(hand): #Reference from score to 0 score = 0 #Loop through each card in the hand and assign it a score, which is added to variable score for card in hand: if card == "J": score += 10 elif card == "Q": score += 10 elif card == "K": score += 10 elif card != "A": score += card # We want the Ace to be evaluated last, since it has 2 values dependent on the total score elif card == "A": if score > 10: score += 1 elif score <= 10: score += 11 #The ace must be evaluated again in case the total score goes over 21, and the ace is the first card in the hand if "A" in hand and score > 21: #Self reference, score points to its own value minus 10 score = score - 10 return score #This function will be used to determine if the player or dealer has struck blackjack in the first 2 cards def blackjack(playerhand, dealerhand): if score(playerhand) == 21: print("Blackjack! You win.The dealer's cards were " + str(dealerhand)) exit() if score(dealerhand) == 21: print("Blackjack! The dealer wins. The dealer's cards were " + str(dealerhand)) exit() #This function determines whether the dealer or player won the match. Multiple cases are included for ties def winner(playerhand, dealerhand): if score(playerhand) == 21 and score(dealerhand) == 21: print("Double blackjack! You tie the dealer.") elif score(playerhand) == 21: print("Blackjack! You win.") elif score(dealerhand) == 21: print("Blackjack! The dealer wins.") elif score(playerhand) > 21 and score(dealerhand) > 21: print("You both busted. Unfortunately, the dealer wins.") elif score(playerhand) > 21: print("You busted. Game over.") elif score(dealerhand) > 21: print("The dealer busted. You win.") elif score(dealerhand) < score(playerhand): print("You win!") elif score(dealerhand) > score(playerhand): print("You lose.") elif score(playerhand) == score(dealerhand): print("Tie game.") #This is where the code is actually executed, and the other functions are pulled in def main(): #Reference from vals to all possible card values in a deck vals = [2, 3, 4, 5, 6, 7, 8, 9, 10, "J", "Q", "K", "A"] #Deck would be considered a deep copy of vals, since changing a element of deck or vals would not modify the other deck = vals * 4 print("Take a seat at the table. Blackjack has now begun.") #Reference from dealerhand to 2 cards from the deck dealerhand = deal(deck) #Reference from playerhand to 2 cards from the deck. playerhand = deal(deck) print("The dealer's faceup card is " + str(dealerhand[1])) print("Your hand is " + str(playerhand)) blackjack(playerhand, dealerhand) #Reference from choice to user input of h or s choice = input("Would you like to hit or stay?(h/s)") #While the player chooses to keep hitting, they will loop until they choose to stay while choice == "h": hit(playerhand, deck) print("Hit! Your new card is " + str(playerhand[-1])) print("Your hand is " + str(playerhand)) #Same reference as before choice = input("Would you like to hit or stay?(h/s)") #The dealer will always hit below a score of 17 while score(dealerhand) < 17: print("The dealer hits, adding a card to his hand.") hit(dealerhand, deck) print("Your hand is " + str(playerhand) + " and your score is " + str(score(playerhand))) print("The dealer's hand is " + str(dealerhand) + " and his score is " + str(score(dealerhand))) winner(playerhand, dealerhand) main()
965112f18693815fb9e59fd1040609e58d880d5f
sharda2001/Saral_AmaR
/day_1_task2_1.py
428
4.09375
4
year=int(input('enter the year ')) if year%4==0: print("leap year") if year%100==0: print('century year') if year%400==0: print('century leap year') else: print('leap year') # year=int(input("enter your year")) # if year %4==0: # if year%100==0: # if year%400==0: # print("sentury leap year") # else: # print("sentuary leap year nhi hai") # else: # print("century year") # else: # print("leap year")
f8da4fd2c23d05b67f6f1c8e0f239e7b5e507487
qmnguyenw/python_py4e
/geeksforgeeks/python/python_all/46_4.py
2,514
4.53125
5
Compute the inner product of vectors for 1-D arrays using NumPy in Python Python has a popular package called NumPy which used to perform complex calculations on 1-D and multi-dimensional arrays. To find the inner product of two arrays, we can use the inner() function of the NumPy package. > **Syntax:** numpy.inner(array1, array2) > > **Parameters:** > > **array1, array2:** arrays to be evaluated > > **Returns:** Inner Product of two arrays > > > > > > **Example 1:** ## Python3 __ __ __ __ __ __ __ # Importing library import numpy as np # Creating two 1-D arrays array1 = np.array([6,2]) array2 = np.array([2,5]) print("Original 1-D arrays:") print(array1) print(array2) # Output print("Inner Product of the two array is:") result = np.inner(array1, array2) print(result) --- __ __ **Output:** Original 1-D arrays: [6 2] [2 5] Inner Product of the two array is: 22 **Example 2:** ## Python3 __ __ __ __ __ __ __ # Importing library import numpy as np # Creating two 1-D arrays array1 = np.array([1,3,5]) array2 = np.array([0,1,5]) print("Original 1-D arrays:") print(array1) print(array2) # Output print("Inner Product of the two array is:") result = np.inner(array1, array2) print(result) --- __ __ **Output:** Original 1-D arrays: [1 3 5] [0 1 5] Inner Product of the two array is: 28 **Example 3:** ## Python3 __ __ __ __ __ __ __ # Importing library import numpy as np # Creating two 1-D arrays array1 = np.array([1,2,2,8]) array2 = np.array([2,1,0,6]) print("Original 1-D arrays:") print(array1) print(array2) # Output print("Inner Product of the two array is:") result = np.inner(array1, array2) print(result) --- __ __ **Output:** Original 1-D arrays: [1 2 2 8] [2 1 0 6] Inner Product of the two array is: 52 Attention geek! Strengthen your foundations with the **Python Programming Foundation** Course and learn the basics. To begin with, your interview preparations Enhance your Data Structures concepts with the **Python DS** Course. My Personal Notes _arrow_drop_up_ Save
419e747f62e8c7acd8066c147be6f82f7e52585b
santhoshpemmaka/epamDS1
/middle.py
660
4.125
4
# your task is to complete this function # function should return index to the any valid peak element # finding middle element in a linked list def findMid(head): # Code here # firstly check the head is Nonereturn 0 if head == None: return 0 # In case first and second assign to the head of the linked list first = head second = head # checking second and second next present in the linked list # If the logic useful to the linked list no the elements either even or odd numbers while second and second.next: first = first.next second = second.next.next # return will be of the middle in the linked list return first
4c701cf7215e3e1d46950b6dad953b6d03639b08
ArshanKhanifar/eopi_solutions
/tests/manual_tests/mtest_find_anagrams.py
3,858
3.78125
4
import collections def find_anagrams(dictionary): sorted_string_to_anagrams = collections.defaultdict(list) for s in dictionary: sorted_string_to_anagrams[''.join(sorted(s))].append(s) # join had to be used since sort returns list return [group for group in sorted_string_to_anagrams.values() if len(group) > 1] # I had to use a tuple here of size 26 for all the letters since I couldn't use a dict as a key def fast_find_anagrams(dictionary): letter_count_to_anagrams = collections.defaultdict(list) for s in dictionary: letter_count_to_anagrams[count_num_of_each_letter_in_tuple(s)].append(s) return [group for group in letter_count_to_anagrams.values() if len(group) > 1] """ this used less memory since we don't have to use a 26 letter list. We can convert the dict to a list of tuples and then to a frozenset so that it is hashable and can be used as a key that doesn't care about order """ def fast_find_anagrams_with_dict(dictionary): letter_count_to_anagrams = collections.defaultdict(list) for s in dictionary: key = frozenset(count_num_of_each_letter(s).items()) letter_count_to_anagrams[key].append(s) return [group for group in letter_count_to_anagrams.values() if len(group) > 1] def fast_find_anagrams_with_hash_class(dictionary): letter_count_to_anagrams = collections.defaultdict(list) for s in dictionary: key = LetterCount(count_num_of_each_letter(s)) letter_count_to_anagrams[key].append(s) return [group for group in letter_count_to_anagrams.values() if len(group) > 1] # wowawewa def count_num_of_each_letter_with_offset(s, offset): def constant_factory(value): return lambda: value d = collections.defaultdict(constant_factory(offset)) for l in s: d[l] += 1 return d # amazing!!! def count_num_of_each_letter(s): d = collections.defaultdict(int) for l in s: d[l] += 1 return d def count_num_of_each_letter_in_tuple(s): result = [0] * 26 start = ord('a') for l in s: list_idx = ord(l) - start result[list_idx] += 1 return tuple(result) # lame def old_count_num_of_each_letter(s): d = {} for l in s: if d.get(l) is not None: d[l] += 1 else: d[l] = 1 return d class LetterCount(object): def __init__(self, letter_count_dict): self.letter_count_dict = letter_count_dict def __hash__(self): return hash(frozenset(self.letter_count_dict.items())) def __eq__(self, other): return set(self.letter_count_dict.items()) == set(other.letter_count_dict.items()) class ContactList(object): def __init__(self, names): self.names = names def __hash__(self): return hash(frozenset(self.names)) def __eq__(self, other): return set(self.names) == set(other.names) def merge_contact_lists(contacts): return list(set(contacts)) if __name__ == "__main__": s = 'mississauga' print(count_num_of_each_letter(s)) print(old_count_num_of_each_letter(s)) print(count_num_of_each_letter_with_offset(s, 1)) print(count_num_of_each_letter_with_offset(s, 0) == count_num_of_each_letter(s)) print(count_num_of_each_letter_in_tuple(s)) input = ['debitcard', 'elvis', 'silent', 'badcredit', 'lives', 'freedom', 'listen', 'levis', 'money'] print(f'\n#############################################\n') print(find_anagrams(input)) print(fast_find_anagrams(input)) print(fast_find_anagrams_with_dict(input)) print(fast_find_anagrams_with_hash_class(input)) print(f'\n#############################################\n') c1 = ContactList(['a', 'b', 'c', 'a']) c2 = ContactList(['b', 'c', 'd', 'b']) c3 = ContactList(['b', 'c', 'a']) print(merge_contact_lists([c1, c2, c3]))
54371fc70e5788498233030aac1467ca9ff7ef99
kanxul/masterarbeit
/oops_basics_02.py
741
3.859375
4
# OOP in Pyhton class My_Calc: # Class Attributes/Variables # Class Constructor/Initializer (Method with a special name) def __init__(self, num1, num2): # Object Attributes/Variables self.num1 = num1 self.num2 = num2 # Methods def total(self): return self.num1 + self.num2 def diff(self): return self.num1 - self.num2 def get_result(self): print("Total = {}".format(self.total())) print("Diff = {}".format(self.diff())) def main(): print("Hello from the main() method") calc1 = My_Calc(20,20) calc2 = My_Calc(-5,20) calc1.get_result() calc2.get_result() if __name__ == '__main__': main()
1536fbd4c9f567227c01e219dac5e21b0931e5a6
pratikoct15/PhythonDivideby3and5
/main.py
603
4.0625
4
def divideCheck(x): if x % 3 == 0 and x % 5 == 0: print('divisble by both 3 and 5') elif x % 3 == 0: print('divisble by 3') elif x % 5 == 0: print('divisble by 5') else: print('Number not divisble by 3 or 5') def loopNum(x): if ',' in x: print('list') # convert to list x = x.split(',') for el in x: # convert to int el = int(el) divideCheck(el) else: x = int(x) divideCheck(x) num = input('Enter a single number or a list of numbers: ') loopNum(num)
f7852bb7c98b76da9c85ae5b098a0ad1aa6b69c3
Armando1234/python
/test.py
498
3.53125
4
from sys import getsizeof # Generators provide data one item at a time # This is a comment #naive function - technical name def stupidfunction(): pies = [] for _ in range(10000000): pies.append("3.141592") return pies #lazy function - technical name def smartfunction(): for _ in range(10000000): yield "3.141592" pies = smartfunction() converted = map(float,pies) print("Sum : {}".format(sum(converted))) print("Size : {}".format(getsizeof(converted)))
65621a135fa3303b43776e9037e8bf5890cd9997
GTxx/leetcode
/algorithms/096. Unique Binary Search Trees/main.py
518
3.6875
4
class Solution(object): def numTrees(self, n): """ :type n: int :rtype: int """ if n <= 1: return 1 elif n == 2: return 2 else: res = [1,1,2] for i in range(3, n+1): total = 0 for j in range(i): total += res[j] * res[i-1-j] res.append(total) return res[-1] if __name__ == "__main__": s = Solution() print(s.numTrees(3))
7e329011debe7762aab71ef7684eeff83f0e7c2a
hechenkuan/code
/variables.py
222
3.609375
4
""" 变量 """ # 整数 a = 1 print(a) print(type(a)) # 浮点数 a = 1/3 print(a) print(type(a)) a = a*3-1 print(a) # 布尔值 a = True print(a) print(type(a)) # 字符串 a = '乐德学堂' print(a) print(type(a))
c4f4557cbb397639f7274b97fa3835435aea5fbf
harperpack/Harper-s-Practice-Repository
/media.py
618
3.78125
4
# This file contains code for the class Movie, which holds # information about different movies. Class Movie shows # key details about movies to a user. import webbrowser class Movie(): """Class Movie holds information about different movies""" def __init__(self, movie_title, movie_plot, movie_poster, movie_trailer): self.title = movie_title self.storyline = movie_plot self.poster_image_url = movie_poster self.trailer_youtube_url = movie_trailer def show_trailer(self): webbrowser.open(self.trailer_youtube_url) def detail_plot(self): print (self.storyline)
a1e289edfb9ddf639c97ab945b631edf99212f6f
sammersheikh/python
/numeric.py
388
3.828125
4
num = 1 num += 1 #equivalent to num = num + 1 print(abs(-3)) #absolute value (get positive number) print(round(3.75, 1)) #round to nearest digit, second number means round to the first digit after the decimal num_1 = '100' num_2 = '200' #these are strings, not integers num_1 = int(num_1) #prefacing with int() casts the string to that type num_2 = int(num_2) print(num_1 + num_2)
4174fe9fb169f1d87f7dd71ca4f255a9adc21c20
rafatmunshi/Data-Structures-Algorithms-using-Python
/BinaryTree.py
2,909
3.8125
4
class Node: def __init__(self, key): self.left = None self.right = None self.key = key def preordertraversal(self): print(self.key, end=' ') if self.left: self.left.preordertraversal() if self.right: self.right.preordertraversal() def inordertraversal(self): if self.left: self.left.inordertraversal() print(self.key, end=' ') if self.right: self.right.inordertraversal() def postordertraversal(self): if self.left: self.left.postordertraversal() if self.right: self.right.postordertraversal() print(self.key, end=' ') def insert(root, key): if not root: root = Node(key) return root q = [root] while len(q): temp = q[0] q.pop(0) if not temp.left: temp.left = Node(key) break else: q.append(temp.left) if not temp.right: temp.right = Node(key) break else: q.append(temp.right) return root def deleteLowestRightmost(root, nodetodelete): q = [] q.append(root) while (len(q)): temp = q.pop(0) if temp is nodetodelete: temp = None return if temp.right: if temp.right is nodetodelete: temp.right = None return else: q.append(temp.right) if temp.left: if temp.left is nodetodelete: temp.left = None return else: q.append(temp.left) def deleteNode(root, key): if root is None: return None if root.left is None and root.right is None: if root.key == key: return None else: return root nodetodelete = None q = [root] while len(q): temp = q.pop(0) if temp.key == key: nodetodelete = temp if temp.left: q.append(temp.left) if temp.right: q.append(temp.right) if nodetodelete: k = temp.key deleteLowestRightmost(root, temp) nodetodelete.key = k return root root= Node(1) root.left= Node(2) root.left.left= Node(3) root.left.right= Node(4) root.right= Node(5) root.right.left= Node(6) root.right.right= Node(7) # 1 # 2 5 # 3 4 6 7 # root.inordertraversal() root= insert(root, 8) # 1 # 2 5 # 3 4 6 7 # 8 # root.inordertraversal() root= deleteNode(root, 5) # 1 # 2 8 # 3 4 6 7 root.inordertraversal()
3030f393d868573217e8e85a09b413a38f0708ed
AndreasLH/3-ugers-projekt-Ham-n-spam
/clean_data_enron.py
3,181
3.578125
4
# -*- coding: utf-8 -*- """ This code is meant to be used to clean a csv-dataset and make the necessary normalization (punctuation, removing, stopwords etc.). Finally it will export the clean dataset as a csv-file. Link to dataset: https://www.kaggle.com/karthickveerakumar/spam-filter/version/1 """ # Import libraries import pandas as pd from nltk.tokenize import RegexpTokenizer from nltk.corpus import stopwords from nltk.stem import PorterStemmer def clean_data(csv_file): """ Function: Loads data and prepares data (feature transformation) Input: cvs-file with messages and class (spam = 1 or not spam = 0 ) Output: pd-DataFrame-object """ # Get raw data and remove unnessecary email-related tags from text data = pd.read_csv(csv_file) data['text'] = data['text'].str.strip('fw :') data['text'] = data['text'].str.strip(' re : ') # Load stop-words, define tokenizer and stemmer #onlinecoursetutorials.com/nlp/how-to-remove-punctuation-in-python-nltk/ # https://riptutorial.com/nltk/example/27285/filtering-out-stop-words # https://www.geeksforgeeks.org/python-stemming-words-with-nltk/ stop_words = set(stopwords.words('english')) tokenizer = RegexpTokenizer(r'\w+') ps = PorterStemmer() numb_mails = len(data.text) # Loops through each message (email) for message in range(numb_mails): # make message lower case text = data.text[message] # Substitute special tokens with descriptive strings #(before removed ny tokenizer) text = text.replace('$', 'DOLLAR') text = text.replace('@', 'EMAILADRESS') text = text.replace('https', 'URL') text = text.replace('www', 'URL') # Remove unescessary information text = text.replace('Subject', '') text = text.replace('cc', '') # Make text lower case text = text.lower() # Tokenize + remove punctuation tokens1 = tokenizer.tokenize(text) # Remove stop-words tokens2 = [w for w in tokens1 if not w in stop_words] #https://riptutorial.com/nltk/example/27285/filtering-out-stop-words # Stemming tokens numb_tokens = len(tokens2) for token in range(numb_tokens): tokens2[token] = ps.stem(tokens2[token]) # Sustitute number (special token) with 'NUMBER' #(numbers can be split by with space) for token in range(numb_tokens): try: int(tokens2[token]) tokens2[token] = "NUMBER" except: pass last_token = "" for token in reversed(range(numb_tokens)): if (last_token == tokens2[token]) and (last_token=='NUMBER'): del tokens2[token+1] last_token = tokens2[token] # Collect tokens to string and assign to dataframe prepared_string = " ".join(tokens2) data.at[message,'text'] = prepared_string # https://stackoverflow.com/a/13842286/12428216 return data result = clean_data('dataset\emails.csv') result.to_csv('processed_emails.csv', encoding='utf-8', index = False) print(len(result.text))