text
stringlengths
37
1.41M
def editDistanceRec(str1, str2, m, n): if n == 0: return m if m == 0: return n if str1[m-1] == str2[n-1]: return editDistanceRec(str1, str2, m-1, n-1) return 1 + min(editDistanceRec(str1, str2, m-1, n), editDistanceRec(str1, str2, m, n-1), editDistanceRec(str1, str2, m-1, n-1)) def editDistanceDp(str1, str2): """ O(mn) """ dp = [[0] * (len(str1) + 1) for _ in xrange(len(str2) + 1)] for i in xrange(len(str2)+1): for j in xrange(len(str1)+1): if i == 0: dp[i][j] = j elif j == 0: dp[i][j] = i elif str1[j-1] == str2[i-1]: dp[i][j] = dp[i-1][j-1] else: dp[i][j] = 1 + min(dp[i-1][j-1], dp[i-1][j], dp[i][j-1]) for row in dp: print(row) return dp[-1][-1] if __name__ == "__main__": str1 = "sunday" str2 = "saturday" print editDistanceRec(str1, str2, len(str1), len(str2)) print editDistanceDp(str1, str2)
"""Housing functions""" import numpy as np import pandas as pd a = pd.DataFrame([1,2,3,np.NaN]) print(a)
# -*- coding: iso-8859-1 -*- """ Blatt 11: Yahtzee Thomas Hofmann, Yannic Boysen Version 1.0 (26.01.18, 18:41): # Diese Version kann ein komplettes Kniffel Spiel simulieren # Das Programm berlsst alle Entscheidungen dem Zufall. Version 2.0 (30.01.18, 19:29): # Das Programm trifft nun informierte Entscheidungen """ import random # used to turn on and off detailed output for each game verbose = 0 if verbose: def verbosePrint(*args): # Print each argument separately so caller doesn't need to # stuff everything to be printed into a single string for arg in args: print arg, print else: def verbosePrint(*args): None # Class that represents a set of 5 dice class Dice: def __init__(self): self.dictOfOpt = {} self.counts = {} self.dice = [] self.possibleRows = [] self.roll() self.update() # function to update all fields after a dice roll def update(self): # self.ones = self.dice.count(1) # self.twos = self.dice.count(2) # self.threes = self.dice.count(3) # self.fours = self.dice.count(4) # self.fives = self.dice.count(5) # self.sixes = self.dice.count(6) # dict(Counter(self.dice)) for x in range(1, 7): self.counts[str(x)] = self.dice.count(x) self.checkAll() self.possibleRows = [str(x) for x in range(1, 7)] + ['ch'] for key in self.dictOfOpt.keys(): if self.dictOfOpt[key] is True: self.possibleRows.append(key) # initialize set of dice def roll(self): self.dice = sorted([random.randint(1, 6) for _ in range(5)]) self.update() # second or third roll def rollAgain(self, keep): # remove = [d for d in self.dice if d not in keep] for d in keep: if d not in self.dice: keep.remove(d) self.dice = sorted(keep + [random.randint(1, 6) for _ in range(5 - len(keep))]) self.update() def printOut(self): verbosePrint(self.dice) def countOf(self, digit): return self.counts[digit] # all following functions are there to check presence of the different score requirements def checkAll(self): # dictOfOpt holds all possible Options and their utility (points) self.dictOfOpt['3k'] = self.hasThreeOfAKind() self.dictOfOpt['4k'] = self.hasFourOfAKind() self.dictOfOpt['fh'] = self.hasFullHouse() self.dictOfOpt['ss'] = self.hasSmallStraight() self.dictOfOpt['ls'] = self.hasLargeStraight() self.dictOfOpt['ya'] = self.hasYahtzee() def hasThreeOfAKind(self): for value in self.counts.itervalues(): if value > 2: return True return False def hasFourOfAKind(self): for value in self.counts.itervalues(): if value > 3: return True return False def hasFullHouse(self): triple, double = False, False for value in self.counts.itervalues(): if value == 2: double = True elif value == 3: triple = True return triple and double def hasSmallStraight(self): counters = [] counter = 0 for i in range(1, 4): for x in range(i, i + 4): if x in self.dice: counter += 1 counters.append(counter) counter = 0 return x > 4 in counters def hasLargeStraight(self): counters = [] counter = 0 for x in range(1, 6): if x in self.dice: counter += 1 counters.append(counter) counter = 0 for x in range(2, 7): if x in self.dice: counter += 1 counters.append(counter) return x > 5 in counters def hasYahtzee(self): return len(set(self.dice)) == 1 # class representing the Score Sheet class Score: def __init__(self): self.sheet = { '1': None, '2': None, '3': None, '4': None, '5': None, '6': None, '3k': None, '4k': None, 'fh': None, 'ss': None, 'ls': None, 'ya': None, 'ch': None } self.bonusGiven = False self.openRows = [] self.total = 0 self.update() def roomOnSheet(self): self.update() return not all(self.sheet.values()) def printOut(self): verbosePrint(self.sheet, "-> Bonus:", "Yes." if self.bonusGiven else "No.") # update total after score is added def update(self): self.total = 0 upperKeys = [key for key in self.sheet.keys() if len(key) == 1] if not self.bonusGiven and sum(self.sheet[x] for x in upperKeys if self.sheet[x] is not None) >= 63: self.total += 35 self.bonusGiven = True self.total += sum(x for x in self.sheet.values() if x is not None) self.openRows = [key for key in self.sheet.keys() if self.sheet[key] is None] # add score in specific row def addScore(self, dice, row): score = Logic.calcUtility(dice, row) # verboseprint score self.sheet[row] = score # self.openRows.remove(row) self.update() # a game instance class Game: def __init__(self): self.dice = Dice() self.score = Score() self.rollsLeft = 39 def play(self, untilRound=13): verbosePrint("STARTING GAME...") for _ in range(untilRound): self.playRound() print "\nFINAL SCORE:", self.score.total print self.score.sheet, self.score.bonusGiven def playRound(self): verbosePrint("\nNext round: ") verbosePrint("Rolling dice...") self.rollsLeft -= 1 # = 3 self.dice.roll() self.dice.printOut() while (self.rollsLeft % 3) != 0: keepers = Logic.bestKeepers(self) verbosePrint("Keeping:", keepers) verbosePrint("PR:", self.dice.possibleRows) self.dice.rollAgain(keepers) verbosePrint("Rolling remaining dice...") self.dice.printOut() self.rollsLeft -= 1 verbosePrint("PR:", self.dice.possibleRows) # DEBUGGING optimalRow = Logic.findOptimalRow(self) verbosePrint("Adding Score in", optimalRow) self.score.addScore(self.dice, optimalRow) verbosePrint("Score Sheet State: ") self.score.printOut() # helper class to make decisions during game time class Logic: fixedScore = { 'fh': 25, 'ss': 30, 'ls': 40, 'ya': 50, } # return best dice to keep between rolls for current game state @staticmethod def bestKeepers(game): keep = [] optimalRow = Logic.findOptimalRow(game) verbosePrint(optimalRow) if optimalRow in ['ya', 'ch', '3k', '4k', 'fh']: keep = game.dice.dice elif optimalRow == 'ss': if all(x in sorted(game.dice.dice) for x in [1, 2, 3, 4]): keep = [1, 2, 3, 4] if all(x in sorted(game.dice.dice) for x in [2, 3, 4, 5]): keep = [2, 3, 4, 5] if all(x in sorted(game.dice.dice) for x in [3, 4, 5, 6]): keep = [3, 4, 5, 6] elif optimalRow == 'ls': if sorted(game.dice.dice) == [1, 2, 3, 4, 5]: keep = [1, 2, 3, 4, 5] if sorted(game.dice.dice) == [2, 3, 4, 5, 6]: keep = [2, 3, 4, 5, 6] elif int(optimalRow) in range(1, 7): countOfOR = game.dice.countOf(optimalRow) while countOfOR > 0: keep.append(int(optimalRow)) countOfOR -= 1 return keep # return random.sample(game.dice.dice, random.randint(1, 5)) # find the optimal row to score in @staticmethod def findOptimalRow(game): choices = [] openRows = game.score.openRows possibleRows = game.dice.possibleRows for key in game.score.sheet.keys(): if (key in openRows) and (key in possibleRows): choices.append(key) choices.sort(key=(lambda x: Logic.expectedUtility(game, x)), reverse=True) if len(choices) > 0: return choices[0] else: return openRows[0] # calculating the expected utility (at this point only for the upper section @staticmethod def expectedUtility(game, row): rollsLeft = game.rollsLeft % 3 if len(row) == 1: countOfRow = game.dice.countOf(row) diceLeft = 5 - countOfRow eU = Logic.calcUtility(game.dice, row) for x in range(diceLeft + 1): probability = Logic.calcDigitProbability(diceLeft, rollsLeft, x) normalUtility = int(row) * probability bonusUtility = ((x + countOfRow) - 3) * 35 * ((float(row)*3) / 63) * probability # print bonusUtility eU += (normalUtility + bonusUtility) return eU # elif row == "ya": # countOfRow = max(game.dice.counts.values()) # diceLeft = 5 - countOfRow # return 50 * Logic.calcDigitProbability(diceLeft, rollsLeft, diceLeft) else: return Logic.calcUtility(game.dice, row) @staticmethod def calcProbability(dice, row): return # Magic function to calculate the probability to get exactly x specific digits with y dice and z rolls left. @staticmethod def calcDigitProbability(diceLeft, rollsLeft, digitsLeftToGet=1): diceLeft, rollsLeft = float(diceLeft), float(rollsLeft) if rollsLeft == 0: return 0 elif digitsLeftToGet == 0: return 1 else: P = 0 for x in range(digitsLeftToGet+1): tempP = diceLeft * (1.0/6.0)**(digitsLeftToGet - x) * (5.0/6.0)**(diceLeft-(digitsLeftToGet-x)) if x > 0: tempP *= Logic.calcDigitProbability(diceLeft-(digitsLeftToGet-x), rollsLeft - 1, x) P += tempP # print P return 1 if P > 1 else P # calculating the utility for the different score rows (=score) @staticmethod def calcUtility(dice, row): if row not in dice.possibleRows: score = 0 elif len(row) == 1: score = dice.countOf(row) * int(row) elif row in ['3k', '4k', 'ch']: score = sum(dice.dice) else: score = Logic.fixedScore[row] return score # Run the game a specific amount of times and calculate stats totals = [] runs = 133 for _ in range(runs): gameOfYahtzee = Game() gameOfYahtzee.play() totals.append(gameOfYahtzee.score.total) print "\nPlayed", runs, "games, with following results:" print "Highest:", max(totals), "| Lowest:", min(totals), "| Average Score:", sum(totals) / len(totals) ### TESTING ### # for i in range(5): # print Logic.calcDigitProbability(3, 2, i), "\n" # # print Logic.calcDigitProbability(3, 1, 1) # g = Game() # g.dice = Dice() # g.rollsLeft = 2 # g.dice.printOut() # print Logic.expectedUtility(g, "3")
#welcome to chương trình phòng vệ toàn cầu. aliens= 2 password = "nguyenthao" print("Nhanh lên! Người ngoài hành tinh đang xâm chiếm đấy!") print("Bạn cần bật hệ thống phòng vệ toàn cầu lên ngay!") print("Hy vọng bạn biết mật khẩu, vì tương lai Trái Đất...") print() print(".....................................................") print(" CHÀO MỪNG TỚI HỆ THỐNG PHÒNG VỆ TOÀN CẦU ") print("-----------------------------------------------------") print() guess = input("Xin hãy điền mật khẩu:".upper()) while guess != password: print() print("Mật khẩu sai.") print() aliens = aliens **2 print("Có", aliens,"người ngoài hành tinh xâm nhập Trái Đất. Làm ơn, hãy nhập lại.") if aliens > 7400000000: break print() print("Gợi ý mật khẩu : thứ đang tấn công chúng ta") print() guess = input("Nhanh nào.Nhập lại mật khẩu:".upper()) if aliens > 7400000000: print("Khôôông ! Người ngoài hành tinh nhiều hơn loài người chúng ta.CHúng ta thua rồi") else: print("Chúng ta đã chiến thắng. Cả thế giới được giải cứu rồi.")
import random import sys from io import StringIO import unittest from Circle import Circle from DrawingProgram import DrawingProgram from Rectangle import Rectangle from Square import Square from Triangle import Triangle from ShapeFactory import ShapeFactory from DrawingProgramIterator import DrawingProgramIterator class MyTests(unittest.TestCase): """ This class contains unit tests to ensure proper functionality of the programs for Assignment 4. """ """ 1) DrawingProgram class functionality tests """ """Adding shapes. Also demonstrates different types of shapes can be properly created.""" def test_add_shape_one_shape(self): """Demonstrates that one shape can be added.""" shape = Square("Square", 30) drawing_program = DrawingProgram() drawing_program.add_shape(shape) self.assertIs(shape, drawing_program.get_shape(0), "one shape not added to the drawing program properly") def test_add_shape_multiple_shapes(self): """Demonstrates thtat multiple shapes can be added.""" shape_1 = Square("Square", 30) shape_2 = Circle("Circle", 50) shape_3 = Triangle("Triangle", 30, 40, 50) shape_list = [shape_1, shape_2, shape_3] drawing_program = DrawingProgram() for shape in shape_list: drawing_program.add_shape(shape) for i in range(len(shape_list)): self.assertIs(shape_list[i], drawing_program.get_shape(i), "multiple shapes not added to drawing program properly") def test_add_shape_duplicated_shapes(self): """Demonstrates that duplicated shapes can be added.""" shape_1 = Square("Square", 30) shape_2 = Square("Square", 30) shape_3 = Square("Square", 30) shape_list = [shape_1, shape_2, shape_3] drawing_program = DrawingProgram() for shape in shape_list: drawing_program.add_shape(shape) for i in range(len(shape_list)): self.assertIs(shape_list[i], drawing_program.get_shape(i), "duplicated shapes not added to drawing program properly") """Removing shapes.""" def test_remove_shape_one_shape(self): """Demonstrates that one shape can be removed.""" shape_1 = Square("Square", 30) shape_2 = Circle("Circle", 50) shape_3 = Triangle("Triangle", 30, 40, 50) shape_4 = Circle("Circle", 80) shape_list = [shape_1, shape_2, shape_3, shape_4] drawing_program = DrawingProgram() for shape in shape_list: drawing_program.add_shape(shape) self.assertEqual(drawing_program.remove_shape(shape_2), 1, "shapes not removed properly") remain_shapes = [drawing_program.get_shape(i) for i in range(3)] removed_shapes = list(filter(lambda shape: shape not in remain_shapes, shape_list )) self.assertIs(removed_shapes[0], shape_2) def test_remove_shape_duplicated_shapes(self): """Demonstrates that duplicated shapes can be removed.""" shape_1 = Square("Square", 30) shape_2 = Circle("Circle", 50) shape_3 = Triangle("Triangle", 30, 40, 50) shape_4 = Circle("Circle", 50) shape_list = [shape_1, shape_2, shape_3, shape_4] drawing_program = DrawingProgram() for shape in shape_list: drawing_program.add_shape(shape) self.assertEqual(drawing_program.remove_shape(shape_2), 2, "shapes not removed properly") remain_shapes = [drawing_program.get_shape(i) for i in range(2)] removed_shapes = list(filter(lambda shape: shape not in remain_shapes, shape_list)) self.assertIs(removed_shapes[0], shape_2) self.assertIs(removed_shapes[1], shape_4) """Printing shapes.""" def test_print_shape(self): """Demonstrates shapes can be printed.""" shape_1 = Square("Square", 30) shape_2 = Circle("Circle", 50) shape_3 = Triangle("Triangle", 30, 40, 50) shape_4 = Circle("Circle", 50) shapes = [shape_1, shape_2, shape_3, shape_4] msgs = ["Square, area: 900, perimeter: 120", "Circle, area: 7853.98, perimeter: 314.16", "Triangle, area: 600.0, perimeter: 120", "Circle, area: 7853.98, perimeter: 314.16"] saved_stdout = sys.stdout drawing_program = DrawingProgram() for shape in shapes: drawing_program.add_shape(shape) try: for idx in range(len(shapes)): out = StringIO() sys.stdout = out shapes[idx].draw() msg = out.getvalue().strip() out.close() self.assertEqual(msg, msgs[idx], "shapes not printed properly") finally: sys.stdout = saved_stdout """Testing given index.""" def test_get_shape_negative_index(self): """Demonstrates proper handling of a negative index for get_shape.""" drawing_program = DrawingProgram() try: drawing_program.get_shape(-1) self.assertEqual(True, False, "index out of range") except ValueError as value_error: self.assertEqual(True, True) def test_get_shape_valid_index(self): """Demonstrates get_shape is functional when given a valid index.""" shape_1 = Square("Square", 30) shape_2 = Circle("Circle", 50) shape_3 = Triangle("Triangle", 30, 40, 50) shape_4 = Circle("Circle", 50) shapes = [shape_1, shape_2, shape_3, shape_4] drawing_program = DrawingProgram() for shape in shapes: drawing_program.add_shape(shape) for idx in range(len(shapes)): self.assertEqual(shapes[idx], drawing_program.get_shape(idx), "shapes not got properly") def test_set_shape_negative_index(self): """Demonstrates proper handling of a negative index for set_shape.""" drawing_program = DrawingProgram() try: drawing_program.set_shape(-1, Square("Square", 30)) self.assertEqual(True, False, "should not have got here, set_shape took a negative index") except ValueError as value_error: self.assertEqual(True, True) def test_set_shape_valid_index(self): """Demonstrates functionality of set_shape when given a valid index.""" shape_1 = Square("Square", 30) shape_2 = Circle("Circle", 50) shape_3 = Triangle("Triangle", 30, 40, 50) shape_4 = Circle("Circle", 50) shapes = [shape_1, shape_2, shape_3, shape_4] drawing_program = DrawingProgram() for shape in shapes: drawing_program.add_shape(shape) drawing_program.set_shape(2, shape_3) self.assertEqual(shape_3, drawing_program.get_shape(2), "shapes not set properly") """Sorting shapes. Also demonstrates proper use of of comparing functions.""" def test_sort_operates_on_empty_list_of_shapes(self): """Demonstrates sorting an empty list of shapes.""" drawing_program = DrawingProgram() drawing_program.sort_shape() self.assertEqual("", drawing_program.__str__()) def test_sort_one_shape(self): """Demonstrates sorting of a list of one shape.""" shape_1 = Square("Square", 30) drawing_program = DrawingProgram() drawing_program.add_shape(shape_1) shapes = [shape_1] drawing_program.sort_shape() self.assertEqual(shapes[0], drawing_program.get_shape(0), "should be None for drawing program") def test_multiple_shapes_ascending_order(self): """Demonstrates sorting of a list of multiple shapes with ascending order.""" shape_1 = Circle("Circle", 30) shape_2 = Rectangle("Rectangle", 30, 50) shape_3 = Rectangle("Rectangle", 30, 60) shape_4 = Square("Square", 30) shapes = [shape_1, shape_2, shape_3, shape_4] drawing_program = DrawingProgram() for shape in shapes: drawing_program.add_shape(shape) drawing_program.sort_shape() for i in range(len(shapes)): self.assertEqual(shapes[i], drawing_program.get_shape(i), "shapes not sorted properly") def test_multiple_shapes_descending_order(self): """Demonstrates sorting a list of multiple shapes with descending order.""" shape_1 = Circle("Circle", 30) shape_2 = Rectangle("Rectangle", 30, 50) shape_3 = Rectangle("Rectangle", 30, 60) shape_4 = Square("Square", 30) shapes = [shape_1, shape_2, shape_3, shape_4] drawing_program = DrawingProgram() for shape in reversed(shapes): drawing_program.add_shape(shape) drawing_program.sort_shape() for i in range(len(shapes)): self.assertEqual(shapes[i], drawing_program.get_shape(i), "shapes not sorted properly") def test_multiple_shapes_random_order(self): """Demonstrates sorting a list of multiple shapes with random order.""" shape_1 = Circle("Circle", 30) shape_2 = Rectangle("Rectangle", 30, 50) shape_3 = Rectangle("Rectangle", 30, 60) shape_4 = Square("Square", 30) shapes = [shape_1, shape_2, shape_3, shape_4] drawing_program = DrawingProgram() random_shapes = shapes[:] random.shuffle(random_shapes) for shape in random_shapes: drawing_program.add_shape(shape) drawing_program.sort_shape() for i in range(len(shapes)): self.assertEqual(shapes[i], drawing_program.get_shape(i), "shapes not sorted properly") """ 2) DrawingProgramIterator class functionality tests Demonstrating the program's ability to iterate across a collection of no shapes, one shape, or multiple shapes. """ def test_looping_no_shapes(self): lst = [] iter_0 = DrawingProgramIterator(lst) with self.assertRaises(StopIteration): next(iter_0) def test_looping_one_shapes(self): lst = [] lst.append(1) iter_1 = DrawingProgramIterator(lst) self.assertEqual(next(iter_1), 1) with self.assertRaises(StopIteration): next(iter_1) def test_looping_5_shapes(self): lst = [] lst.append(1) lst.append(2) lst.append(3) lst.append(4) lst.append(5) iter_5 = DrawingProgramIterator(lst) self.assertEqual(next(iter_5), 1) self.assertEqual(next(iter_5), 2) self.assertEqual(next(iter_5), 3) self.assertEqual(next(iter_5), 4) self.assertEqual(next(iter_5), 5) with self.assertRaises(StopIteration): next(iter_5) """ 3) Functionality of Shapes Testing negative and zero values demonstrates proper validation. Testing perimeter and area ensures proper shape creation. """ """Shape""" def test_get_name(self): shape = ShapeFactory.create_shape("Circle", 1.0) self.assertEqual(shape.name, "Circle", "shape name not got properly") shape = ShapeFactory.create_shape("Square", 1.0) self.assertEqual(shape.name, "Square", "shape name not got properly") shape = ShapeFactory.create_shape("Rectangle", 1.0, 2.0) self.assertEqual(shape.name, "Rectangle", "shape name not got properly") shape = ShapeFactory.create_shape("Triangle", 3.0, 4.0, 5.0) self.assertEqual(shape.name, "Triangle", "shape name not got properly") """Circles.""" def test_circle_radius_negative_value(self): """Demonstrates proper handling given a negative radius.""" try: Circle("Circle", -1.0) self.assertEqual(True, False, "circle radius is negative") except ValueError as value_error: self.assertEqual(True, True) def test_circle_radius_zero_value(self): """Demonstrates proper handling given a radius of zero.""" try: Circle("Circle", 0.0) self.assertEqual(True, False, "circle radius is zero") except ValueError as value_error: self.assertEqual(True, True) def test_circle_perimeter(self): try: circle_perimeter = Circle.perimeter(Circle("Circle", 1.0)) self.assertEqual(round(circle_perimeter, 2), 6.28, "circle perimeter is wrong") except ValueError as value_error: self.assertEqual(True, True) def test_circle_area(self): try: circle_area = Circle.area(Circle("Circle", 1.0)) self.assertEqual(round(circle_area, 2), 3.14, "circle area is wrong") except ValueError as value_error: self.assertEqual(True,True) """Squares.""" def test_square_side_length_negative_value(self): """Demonstrates proper handling given negative side length.""" try: Square("Square", -1.0) self.assertEqual(True, False, "square length is negative") except ValueError as value_error: self.assertEqual(True, True) def test_square_side_length_zero_value(self): """Demonstrates proper handling given a side length of zero.""" try: Square("Square", 0.0) self.assertEqual(True, False, "square length is zero") except ValueError as value_error: self.assertEqual(True, True) def test_square_perimeter(self): try: square_perimeter = Square.perimeter(Square("Square", 1.0)) self.assertEqual(square_perimeter, 4.0, "square perimeter is wrong") except ValueError as value_error: self.assertEqual(True, True) def test_square_area(self): try: square_area = Square.area(Square("Square", 1.0)) self.assertEqual(square_area, 1.0, "square area is wrong") except ValueError as value_error: self.assertEqual(True,True) """Rectangles.""" def test_rectangle_side_lengths_negative_value(self): """Demonstrates proper handling given negative side length.""" try: Rectangle("Rectangle", -1.0,-1.0) self.assertEqual(True, False, "rectangle length is negative") except ValueError as value_error: self.assertEqual(True, True) def test_rectangle_side_lengths_zero_value(self): """Demonstrates proper handling given side length of zero.""" try: Rectangle("Rectangle", 0.0, 0.0) self.assertEqual(True, False, "rectangle length is zero") except ValueError as value_error: self.assertEqual(True, True) def test_rectangle_perimeter(self): try: rectangle_perimeter = Rectangle.perimeter(Rectangle("Rectangle", 1.0, 2.0)) self.assertEqual(rectangle_perimeter, 6.0, "rectangle perimeter is wrong") except ValueError as value_error: self.assertEqual(True, True) def test_rectangle_area(self): try: rectangle_area = Rectangle.area(Rectangle("Rectangle", 1.0, 2.0)) self.assertEqual(rectangle_area, 2.0, "rectangle area is wrong") except ValueError as value_error: self.assertEqual(True,True) """Triangles.""" def test_triangle_side_lengths_negative_value(self): """Demonstrates proper handling given negative side lenghths.""" try: Triangle("Triangle", -1.0, -1.0, -1.0) self.assertEqual(True, False, "triangle length is negative") except ValueError as value_error: self.assertEqual(True, True) def test_triangle_side_lengths_zero_value(self): """Demonstrates proper handling given side lenghts of zero.""" try: Triangle("Triangle", 0.0, 0.0, 0.0) self.assertEqual(True, False, "triangle length is zero") except ValueError as value_error: self.assertEqual(True, True) def test_triangle_side_lengths_invalid(self): try: Triangle("Triangle", 2.0, 1.0, 3.0) self.assertEqual(True, False, "input lengths can't make a triangle") except ValueError as value_error: self.assertEqual(True, True) def test_triangle_perimeter(self): try: triangle_perimeter = Triangle.perimeter(Triangle("Triangle", 2.0, 3.0, 4.0)) self.assertEqual(triangle_perimeter, 9.0, "triangle perimeter is wrong") except ValueError as value_error: self.assertEqual(True, True) def test_triangle_area(self): try: triangle_area = Triangle.area(Triangle("Triangle", 2.0, 3.0, 4.0)) self.assertEqual(round(triangle_area, 2), 2.90, "triangle area is wrong") except ValueError as value_error: self.assertEqual(True,True) """ 4) Shape Factory Tests """ def test_returns_circle(self): """Ensures circles can be created.""" shape = ShapeFactory.create_shape("Circle", 1.0) self.assertEqual(vars(shape), vars(Circle("Circle", 1.0)), "Shape factory does not return Circle") def test_returns_square(self): """Ensures squares can be created.""" shape = ShapeFactory.create_shape("Square", 1.0) self.assertEqual(vars(shape), vars(Square("Square", 1.0)), "Shape factory does not return Square") def test_returns_rectangle(self): "Ensures rectangles can be created.""" shape = ShapeFactory.create_shape("Rectangle", 1.0, 1.0) self.assertEqual(vars(shape), vars(Rectangle("Rectangle", 1.0, 1.0)), "Shape factory does not return Rectangle") def test_returns_triangle(self): """Ensures triangles can be created.""" shape = ShapeFactory.create_shape("Triangle", 3.0, 4.0, 5.0) self.assertEqual(vars(shape), vars(Triangle("Triangle", 3.0, 4.0, 5.0)), "Shape factory does not return Triangle")
# Authors: Brent van Dodewaard, Jop van Hest, Luitzen de Vries. # Heuristics programming project: Protein pow(d)er. # This file implements an random algorithm which randomly builds up the protein chain. import random from classes.amino import Amino from functions.GetLegalMoves import get_legal_moves from functions.GetMatrix import get_matrix from functions.GetScore import get_score # This functions build a protein with random fods (but always legal) def random_search(protein): while protein.char_counter < len(protein.amino_string): char = protein.amino_string[protein.char_counter] # Get the location the last amino folded to. # Note: an index of -1 gets the last object in a list. amino_xy = protein.chain.chain_list[-1].get_fold_coordinates() # Last amino always has fold of 0. if protein.char_counter + 1 == len(protein.amino_string): fold = 0 # Determine which fold to pick else: illegal_folds = None fold = fold_selector(amino_xy, char, protein.chain, illegal_folds) # If no legal moves are available, the last move needs to be reversed. if not fold: redo_last_fold(protein) continue # Adds amino to the protein chain. protein.chain.chain_list.append(Amino(char, fold, amino_xy)) protein.char_counter += 1 protein.matrix, protein.chain.chain_list = get_matrix(protein.chain.chain_list) # The actual algo for selecting the fold the chain will make. def fold_selector(xy, char, chain, illegal_moves): legal_moves = get_legal_moves(xy, chain.chain_list) # Remove illegal moves from legal moves list. if illegal_moves: for move in illegal_moves: if move in legal_moves: legal_moves.remove(move) # Selects a random move if at least 1 legal moves exists. Returns False for no ideal_chain found. if legal_moves: return random.choice(legal_moves) # If no legal moves exist, return False return False def redo_last_fold(protein): # Store the illegal fold in the amino class. last_amino = protein.chain.chain_list[-1] last_amino.illegal_folds.append(last_amino.fold) # Get new move with illegal moves excluded. protein.chain.chain_list[:-1] fold = fold_selector(last_amino.coordinates, last_amino.atype, protein.chain, last_amino.illegal_folds) # Replace the previous illegal fold with a new fold last_amino.fold = fold # If still no fold found, also redo move before that. Char loop in init needs to go back 1 step. if not fold: protein.chain.chain_list.remove(last_amino) protein.char_counter -= 1 redo_last_fold(protein)
""" common Implement a number of functions which we will use repeatedly throughout the course. """ from matplotlib import rc, pyplot as plt import seaborn as sns import numpy as np from IPython.core.display import HTML def initialize_figures(): """ initialize_figures() Set the common pyplot.rc paramters for the figures. This includes setting the font and figure size, etc. """ rc('text', usetex=True) rc('font', family='serif') rc('xtick', labelsize=18) rc('ytick', labelsize=18) rc('figure', figsize=(15, 15)) rc('patch', edgecolor='none') sns.set(style='white', palette='muted') HTML(""" <style> .output_png { display: table-cell; text-align: center; vertical-align: middle; } </style> """) def scatter_plot(x, y, labels=None, ax=None): """ scatter_plot() Operates much like the normal scatter plot, just gives us some conveniences. Returns the list of plot handles. """ if ax is None: plt.figure(1, figsize=(10, 10)) ax = plt.gca() # Get the number of classes if labels is not None: classes = np.unique(labels) else: classes = np.array([1,]) labels = np.ones(len(x)) # Find data ranges... used to set axes center_x = np.mean(x) radius_x = max(center_x - min(x), max(x) - center_x) radius_x *= 1.025 center_y = np.mean(y) radius_y = max(center_y - min(y), max(y) - center_y) radius_y *= 1.025 for cls in classes: ax.plot(x[labels == cls], y[labels == cls], 'o', label="Class {}".format(cls)) # Turn off labelling ax.tick_params(axis='x', which='both', bottom='off', top='off', labelbottom='off') ax.tick_params(axis='y', which='both', left='off', right='off', labelleft='off') ax.set_xlim((center_x - radius_x, center_x + radius_x)) ax.set_ylim((center_y - radius_y, center_y + radius_y)) # Create Legend plt.legend(bbox_to_anchor=(1, 0.5), loc='center left', ncol=1, fontsize=18)
def WER(X,Y): """ returns the lavenshtein distance between X and Y X and Y are 2 strings of arbitrary lengths, represented as arrays. """ # if any of the string is empty # return the length of the other if len(X)*len(Y) == 0: return max(len(X), len(Y)) # if zeroth elements are same, # no need to make changes if X[0] == Y[0]: return WER(X[1:], Y[1:]) if len(X) == len(Y): return 1+WER(X[1:], Y[1:]) if len(X) > len(Y): return 1 + min(WER(X[1:], Y[:]), WER(X[1:], Y[1:])) if len(X) < len(Y): return 1 + min(WER(X[:], Y[1:]), WER(X[1:], Y[1:])) A = list("abcde") B = list("be") print(WER(A, B))
# ===== Problem Statement ===== # Given the array nums, for each nums[i] find out # how many numbers in the array are smaller than it. # That is, for each nums[i] you have to count the number # of valid j's such that j != i and nums[j] < nums[i]. # # Return the answer in an array. class Solution: # Runtime: 280 ms # Memory: 14.1 MB def smallerNumbersThanCurrentBrute(self, nums): result = [] for i in nums: count = 0 for j in nums: # No need to check if j != i because # j < i already implies != if j < i: count += 1 result.append(count) return result # Runtime: 56 ms # Memory: 14 MB def smallerNumbersThanCurrent(self, nums): nums_s = sorted(nums) result = [] # Store a dict that keeps the count # of elements less than an i'th # element in nums d = {} for i in range(len(nums_s)): # say "not in d" to prevent from # looking at the same element if nums_s[i] not in d: d[nums_s[i]] = i for e in nums: result.append(d[e]) return result if __name__ == "__main__": x = Solution() nums = [8,1,2,2,3] result = x.smallerNumbersThanCurrentBrute(nums) #result = x.smallerNumbersThanCurrent(nums) print(result)
from typing import List # ===== Problem Statement ===== # You are given the array paths, where paths[i] = [cityAi, cityBi] # means there exists a direct path going from cityAi to cityBi. Return # the destination city, that is, the city without any path outgoing to # another city. It is guaranteed that the graph of paths forms a line # without any loop, therefore, there will be exactly one destination city. class Solution: # . Goal: Look for the node with no outgoing edges # . Note that the keys of graph are source nodes # and the values are destination nodes. If a # destination node is not also a source node, # then that is your destination city # Runtime: 52 ms # Memory: 14.1 MB def approach1(self, paths: List[List[str]]) -> str: # Set approach graph = {} for e in paths: graph[e[0]] = e[1] return list(set(graph.values()).difference(graph.keys()))[0] # Runtime: 52 ms # Memory: 13.6 MB def approach2(self, paths: List[List[str]]) -> str: # list comp approach: graph = {} for e in paths: graph[e[0]] = e[1] return [n for n in graph.values() if n not in graph.keys()][0] # Runtime: 52 ms # Memory: 13.9 MB def approach3(self, paths: List[List[str]]) -> str: # . This is a pretty good one because it takes advantage # of the guarantee given by the problem (see NOTE below) # and because we can potentially return early. Morever, # we don't have to build a dict and call methods on that dict... # . Again, don't always go for list comprehensions because you # might miss out on opportunities to bail out early... # . Hmm, despite how optimized this version looks, it still # has similar runtime and memory use to the previous approaches... s = set(p[0] for p in paths) for p in paths: if p[1] not in s: return p[1] #destCity = approach1 #destCity = approach2 destCity = approach3 # NOTE: # Guaranteed to have only one destination city, # which means that the resulting container that # you make in the methods up there^ will always # have a single element that you can index # return [n[0] for n in graph if not n[1]][0] if __name__ == "__main__": paths = [["London","New York"],["New York","Lima"],["Lima","Sao Paulo"]] sol = Solution() print(sol.destCity(paths))
from typing import List # ===== Problem Statement ===== # Given an array arr, replace every element in that array # with the greatest element among the elements to its right, # and replace the last element with -1. # After doing so, return the array. class Solution: # Runtime: 124 ms # Memory: 14.9 MB def replaceElements(self, arr: List[int]) -> List[int]: cur_max = arr[-1] prev_max = cur_max # Loop from the back and keep a running max to # replace the guys along the way to the front for i in range(len(arr)-1, -1, -1): if arr[i] > cur_max: cur_max = arr[i] arr[i] = prev_max prev_max = cur_max else: arr[i] = cur_max arr[-1] = -1 return arr if __name__ == "__main__": sol = Solution() arr = [17,18,5,4,6,1] print(sol.replaceElements(arr))
# 'Write'- A basic text editor in python # made using tkinter import tkinter as tk from tkinter.filedialog import * # Setting up the window try: window=tk.Tk() window.minsize(800,500) window.title('Write') text=Text(window) text.pack(expand=True,fill=BOTH) # Defining Save,Open and New commands def save(): file=open(asksaveasfilename(),'w') file.write(text.get('1.0',END+'-1c')) file.close() def my_open(): file=open(askopenfilename(),'r') text.delete(1.0,END+'-1c') for line in file: text.insert(END,line) file.close() def new_file(): text.delete(1.0,END+'-1c') # Adding required commands to the File menu file_menu=Menu(font=("open",10),tearoff=0) file_menu.add_command(label="New File",command=new_file) file_menu.add_command(label="Open File",command=my_open) file_menu.add_command(label="Save",command=save) main_menu=Menu() main_menu.add_cascade(label="File",menu=file_menu) # Main loop for the Editor window.config(menu=main_menu) window.mainloop() except KeyboardInterrupt: quit()
def c_to_f(cel): return int((cel * 1.8) +32) c_to_f(-10) print("Water freezing at {} C, {} F".format(0, c_to_f(0))) print("Coldest recorded temperatura is {} C, {} F".format(-79, c_to_f(-79))) print("Coldest temperatura possible {} C, {} F".format(-273, c_to_f(-273)))
#string = "This is a string with bunch of words" #print(string[8]) #print(len(string)) #for i in range(0, len(string)): # print(i) #for i in string: # print(i) # for i in range(0, len(string)): # for j in string: # print("This is index {} this is a char {}".format(i, string[i])) #string = "this sample string exercercize" #for i in range(0, len(string)): #if string[i] == ' ': # print("This is an index {} of the character SPACE".format(i)) #else: # print("This is an index {} of the character {}".format(i, string[i])) #list = [1, 1.4, 'hello', True] #for i in #list = [] #number = input("Please give a number:") #list.append(number) #print(list) #list = [] #for i in range(0, 5): # name = input ("Please give your name:") # list.append(name) #print(list) #for name in list: # print("Hello, {}".format(name)) list = [] for i in range(0, 2): name = input("Please give your name:") list.append(name) print(list) for name in list: if 'A' in name: print("Name has A") elif 'a' in name: print("Name has a") else: print("This name has no A or a")
numbers = [123, 54, 2, -1, 43, 22333, 1, 99, 883423] numbers_len = len(numbers) max_number = numbers[0] for i in range(1, numbers_len): if max_number < numbers[i]: max_number = numbers[i] print("This is the largest: {}".format(max_number)) numbers_len = len(numbers) min_number = numbers[0] for i in range(1, numbers_len): if min_number > numbers[i]: min_number = numbers[i] #print(max(numbers)) short cut #print(min(numbers)) print("This is lowest: {}".format(min_number))
#Task1 #write a function which calculates factorial of a number #Functions has to accept a single argument, integer #Factorial formula #Factorial of n is #n! = 1 * 2 * 3 ... n def factorial(number): result = 1 for i in range(1, number+1): result = result * i print("Factorial of {} is {}".format(number, result)) for i in range(1, 11): factorial(i)
print("Bien venido al mundo virtual, el menu:\n") while (True): print("""Acciones del menu principal 1.- Saludar 2.- Sumar dos numeros 3.- Salir""") respuesta = int(input("Por favor ingrese una opcio: ")) if respuesta == 1: print("Hola amigos desde Debian-Python") elif respuesta == 2: num_1 = float(input("Ingresa el primer numero: \n")) num_2 = float(input("Ingresa el segundo numero: \n")) print("El resultado de la suma es: {suma}".format(suma=num_1+num_2)) elif respuesta == 3: print("Hasta la proxima") break else: print("La opción ingresada no existe")
import random import string def gen(LengthPassword): s = list(string.ascii_uppercase) + list(string.ascii_lowercase) + list(string.digits) + list(string.punctuation) random.shuffle(s) password = "".join(s[0:LengthPassword]) return password LenPass = int(input("Enter the Length of Password:")) print("Your Password is: \n" + gen(LenPass))
import networkx as nx from __helpers_general__ import print_res def centralities(graph, decrease_dictionary, no_of_nodes): """ Given a network x graph and information about the polarization finds the closeness, betweenness and Eigen centrality of the nodes that were connected and had the biggest and the smallest decrease -------------------------------------------------------------------------------- :param graph: network x graph :param decrease_dictionary: dictionary that has information about the polarization for every edge addition :param no_of_nodes: number of nodes that the function will print for biggest and smallest decrease :return: 1. list of edges with the biggest polarization index decrease 2. list of edges with the smallest polarization index decrease example: ['6,30', '7,30', '17,26', '17,24', '17,30'] """ sorted_dict = sorted(decrease_dictionary) smallest_decrease = sorted_dict[:no_of_nodes] biggest_decrease = sorted_dict[-no_of_nodes:] top_decrease_nodes = [] small_decrease_nodes = [] biggest_decrease_edges = [] smallest_decrease_edges = [] for value in biggest_decrease: decrease = decrease_dictionary[value] edge_added = decrease['addition'].replace('->', ',') biggest_decrease_edges.append(edge_added) nodes = edge_added.split(',') top_decrease_nodes.append(nodes[0]) top_decrease_nodes.append(nodes[1]) for value in smallest_decrease: decrease = decrease_dictionary[value] edge_added = decrease['addition'].replace('->', ',') smallest_decrease_edges.append(edge_added) nodes = edge_added.split(',') small_decrease_nodes.append(nodes[0]) small_decrease_nodes.append(nodes[1]) # remove duplicate nodes top_decrease_nodes = list(dict.fromkeys(top_decrease_nodes)) small_decrease_nodes = list(dict.fromkeys(small_decrease_nodes)) # map the to int so they can be sorted and accessed top_decrease_nodes = list(map(int, top_decrease_nodes)) small_decrease_nodes = list(map(int, small_decrease_nodes)) top_decrease_nodes = sorted(top_decrease_nodes[:no_of_nodes]) small_decrease_nodes = sorted(small_decrease_nodes[:no_of_nodes]) # holds centrality values of every node closeness_c = nx.closeness_centrality(graph) betweenness_c = nx.betweenness_centrality(graph) eigen_centrality = nx.eigenvector_centrality(graph) top_node_closeness_c = [closeness_c[node] for node in top_decrease_nodes] top_node_betweenness = [betweenness_c[node] for node in top_decrease_nodes] top_node_eigen = [eigen_centrality[node] for node in top_decrease_nodes] small_node_closeness_c = [closeness_c[int(node)] for node in small_decrease_nodes] small_node_betweenness = [betweenness_c[int(node)] for node in small_decrease_nodes] small_node_eigen = [eigen_centrality[node] for node in small_decrease_nodes] print_res(top_decrease_nodes, top_node_closeness_c, top_node_betweenness, top_node_eigen, 'Largest') print_res(small_decrease_nodes, small_node_closeness_c, small_node_betweenness, small_node_eigen, 'Smallest') return biggest_decrease_edges, smallest_decrease_edges def edges_centralities(graph, dictionary, no_of_nodes, mode): """ Computes the edge centralities of the graph and returns the top #no_of_nodes with the biggest and the smallest polarization decrease after removing an edge in their graph. :param graph: netrowkx graph :param dictionary: holds the decrease of the polarization with edge removals for every available edge in the graph :param no_of_nodes: number of bigger/smaller decrease with removal in polarization that I want to keep :param mode: Boolean-> True for decrease, False for increase :return: 1 dictionary for increase or decrease with edge centralities """ sorted_dict = sorted(dictionary, reverse=mode) sorted_dict = sorted_dict[:no_of_nodes] betweenness_c = nx.edge_betweenness_centrality(graph) dictionary_to_return = {} top = {} for value in sorted_dict: decrease = dictionary[value] edge_removed = decrease['edge_removal'] top[value] = {'edge_removed': edge_removed} for value in top: edge_to_get_val = top[value]['edge_removed'] edge_bet_centrality = betweenness_c[edge_to_get_val] sign = dictionary[value]['multiplication'] addition = dictionary[value]['addition'] dictionary_to_return[value] = {'edge_removed': edge_to_get_val, 'edge_centrality': edge_bet_centrality, 'sign': sign, 'addition': addition} return dictionary_to_return
# -*- coding: utf-8 -*- #!/usr/bin/python #批量将一个目录下的文件复制或移动到另一目录 #复制或移动的过程中,可以对文件进行重命名操作 #src_dir为源目录 dst_dir为目标目录 import os,shutil from random import randint root_path = os.getcwd() #获取当前根目录的路径 src_dir = r"E:\Examples_in_Python\Docs" dst_dir = r"E:\Examples_in_Python\Copytest" files = os.listdir(src_dir) def move_file(srcfile,dstfile): if not os.path.isfile(srcfile): print("%s not exist!"%(srcfile)) else: fpath,fname=os.path.split(dstfile) #分离文件名和路径 if not os.path.exists(fpath): os.makedirs(fpath) #创建路径 shutil.move(srcfile,dstfile) #移动文件 print("Move %s \nTo: %s"%(srcfile,dstfile)) def copy_file(srcfile,dstfile): if not os.path.isfile(srcfile): print("%s not exist!"%(srcfile)) else: fpath,fname=os.path.split(dstfile) #分离文件名和路径 if not os.path.exists(fpath): os.makedirs(fpath) #创建路径 shutil.copyfile(srcfile,dstfile) #复制文件 print("copy %s -> %s"%( srcfile,dstfile)) with open(r"E:\Examples_in_Python\统计年级段各班级人数和学生信息\计专1701班.txt","r") as fp: while(True): header = fp.readline().strip().replace("\t","+") print(header) if(header): filename = header+"+第二次.doc" index = randint(0,len(files)-1) srcfile = os.path.join(src_dir,files[index]) dstfile = os.path.join(dst_dir,filename) copy_file(srcfile,dstfile) else: break
""" phrase = input("Your phrase:") if len(phrase) < 1 : phrase = "Hello world" print(phrase) lst, lst_backwards = list(), list() for i in phrase: if i == " " : continue lst.append(i.lower()) ind = len(lst) - 1 # 10 - 1 while ind >= 0: lst_backwards.append(lst[ind]) ind -= 1 if lst == lst_backwards: print("Your phrase is a palindrome!") else: print("Your phrase isn't a palindrome!") """ # the shortest solution: inp = input("Your phrase:") if inp.lower() == inp[::-1].lower() : print("{} is a palindrome.".format(inp)) else: print("{} is not a palindrome.".format(inp))
import time,sys def typingPrint(text): for character in text: sys.stdout.write(character) sys.stdout.flush() time.sleep(0.05) def typingInput(text): for character in text: sys.stdout.write(character) sys.stdout.flush() time.sleep(0.05) value = input() return value game_still_going = True def meet_mady(player): typingPrint('You collected all pieces of eight! ') typingPrint('After a long voyage at sea, you arrive at a small island. Within that island is a deep cave! ') typingPrint('Captain Mady emerges from the shadows and shouts that you must present your eight of pieces! ') typingPrint(f'You present your pieces of eight and Captain Mady gives you her treasure! Congratulations {player.promotion}! Youve conquered the seas! ') def battle(player): typingPrint("\n") typingPrint("""Hurry! A pirate ship approaches! What do we do! """) print("\n") print("1: Load the cannons, turn the ship North by North East to have our starboard to their angle, prepare for battle!") print("2: We're not here to fight! Raise the sails! Turn the ship opposite their direction! Then lower the sails and put them to the wind, we're out of here!") print("3: Climb to the crows nest pronto! Raise the White Flag, we can sail these seas in an alliance!") scenario_input = input("Enter your choice:") responses_dict = { "1": "The enemy ship wanted to be friends, but they raised the white flag too late... or maybe we chose to not see it. Either we sunk their ship and have more treasure in our collection. ", "2": "A cowardice play! You survived but with no respect for the Pirate Code! ", "3": "You got lucky the enemy ship was new to the seas, a seasoned crew might have wanted your treasures for themselves. They joined the alliance and you will not split loots. " } if scenario_input == '1': typingPrint("\n") typingPrint(responses_dict["1"]) player.add_piece_of_eight() typingPrint("\n") typingPrint(f"You now have {player.piece_of_eight} of eight pieces") typingPrint("\n") elif scenario_input == '2': typingPrint("\n") typingPrint(responses_dict["2"]) elif scenario_input == '3': typingPrint("\n") typingPrint(responses_dict["3"]) global game_still_going game_still_going = False def treasure(player): typingPrint("\n") typingPrint("""A treasure map was found on the ship! The crew looks a little closer... an 'x' on an island! This seems unrelated to Mady's pieces of eight. What do you do: """) print("\n") print("1: Go to the island and plunder it until you find the treasure!") print("2: Forget the map, Mady's Treasure is priority!") print("3: Continue on your journey, if you pass that island along the way, you can drop anchor then.") scenario_input = input("Enter your choice:") responses_dict = { "1": "You found the treasure! Now you'll have more loot for when your adventure is over! ", "2": "A captain can make a wrong decisions sometimes. A pirate would gather more treasure than he could hold no matter the cost.", "3": "You continued to follow the wind, unfortunately it never brought you to the island with free loot." } if scenario_input == '1': typingPrint("\n") typingPrint(responses_dict["1"]) player.add_piece_of_eight() typingPrint("\n") typingPrint(f"You now have {player.piece_of_eight} of eight pieces") typingPrint("\n") elif scenario_input == '2': typingPrint("\n") typingPrint(responses_dict["2"]) elif scenario_input == '3': typingPrint("\n") typingPrint(responses_dict["3"]) if player.piece_of_eight == 8: global game_still_going game_still_going = False else: battle(player) def crash_landing(player): typingPrint("\n") typingPrint("The ship has crashed! You've scraped a hole into the bottom of the brig! Are you really worthy of being a Captain? The only wood that can be used is from the barrel of rum... but it still half full! Do you: ") print("\n") print("1: Take apart that scoundrelous barrel and hurry up and fix the ship before we sink to the depths and meet Davy Jones Locker for good.") print("2: Pass around that barrel make sure everyone gets their serving, not a drop to spare!") print("3: Argue about who gets to drink the most rum, this way maybe you can have a chance to drink most of it yourself!") scenario_input = input("Enter your choice:") responses_dict = { "1": "You CHOSE to spill rum? The life at sea does not call to you. You may have saved the ship but you lost your pirate heart.", "2": "You're buzzed and tipping around the ship as you fix her well, you might have barely the hole before she sunk, but you're still on the voyage ahead!", "3": "As you argue around someone broke the barrel to fix the ship, now nobody got the taste of a good grog." } if scenario_input == '1': typingPrint("\n") typingPrint(responses_dict["1"]) elif scenario_input == '2': typingPrint("\n") typingPrint(responses_dict["2"]) player.add_piece_of_eight() typingPrint("\n") typingPrint(f"You now have {player.piece_of_eight} of eight pieces") typingPrint("\n") elif scenario_input == '3': typingPrint("\n") typingPrint(responses_dict["3"]) if player.piece_of_eight == 8: global game_still_going game_still_going = False else: treasure(player) def far_seas(player): typingPrint("\n") typingPrint("The sense a sinister beast from below the waves, the crew looks overboard and alas! You're under attack by the Kraken! You raise your sails and prepare for battle..... What is this feeling....? So lost... Davy Jones has stolen your soul! He summoned the beast to distract you! As an empty vessel now do you: ") print("\n") print("1: If Davy Jones stole my soul it means his hideaout is nearby! Forget the Kraken, an impossible beast to conquer, set sail to the nearest island!") print("2: Davy Jones lives with the kraken under the sea, load the cannons, kill the beast and use him to travel beneath the waves") print("3: He must have escaped and is sailing away to his ship! Climb to the crow's nest and search for his direction to follow.") scenario_input = input("Enter your choice:") responses_dict = { "1": "You've become a soulless crew, no heart to fight, Davy Jones made way with your soul.", "2": "The Kraken had a weakness in its eye! One cannon shot and he lent us his power! It sent us to Davy Jones Locker, retrieved our souls and we freed many others.", "3": "You climbed up, scouted the all of your surroundings and found nothing, you barely managed to escape the Kraken too." } if scenario_input == '1': typingPrint("\n") typingPrint(responses_dict["1"]) elif scenario_input == '2': typingPrint("\n") typingPrint(responses_dict["2"]) player.add_piece_of_eight() typingPrint("\n") typingPrint(f"You now have {player.piece_of_eight} of eight pieces") typingPrint("\n") elif scenario_input == '3': typingPrint("\n") typingPrint(responses_dict["3"]) if player.piece_of_eight == 8: global game_still_going game_still_going = False else: crash_landing(player) def starving_crew(player): typingPrint("\n") typingPrint("""The crew is starving! With scurvvy on the brink of the horizon, do you: """) print("\n") print("""1: Sail to the nearest island, we need fruits!""") print("""2: Begin to fish in the waters, there's plenty of food in the sea.""") print("""3: We dont need food, just more rum! """) scenario_input = input("Enter your choice:") responses_dict = { "1": "A seasoned pirate who knows the dangers of sailing the seas without proper feast.", "2": "You've settled your hunger but still too young for the sea, she will soon consume you! Scurvvy only happens when you dont eat fruit in proper time. Now you're slowly dying.", "3": "A pirate at heart, you knew what scurvvy could do and doomed your crew with it. Although on purpose to die at seas like a true legend on their last journey." } if scenario_input == '1': typingPrint("\n") typingPrint(responses_dict["1"]) player.add_piece_of_eight() typingPrint("\n") typingPrint(f"You now have {player.piece_of_eight} of eight pieces") typingPrint("\n") elif scenario_input == '2': typingPrint("\n") typingPrint(responses_dict["2"]) elif scenario_input == '3': typingPrint("\n") typingPrint(responses_dict["3"]) if player.piece_of_eight == 8: global game_still_going game_still_going = False else: far_seas(player) def overboard_sailer(player): typingPrint("\n") typingPrint("I'm so glad those sirens didn't kill you. Maybe the pizza helped. You're calmly sailing the seas continuing on your adventure when avast! Your crew has spotted a man overboard to the east! Do you: ") print("\n") print("1: Forget the man, because he's out in the open sea proves he was unable to handle her wrath and will do no good to our crew.") print("2: Finish him off, put him out of his misery, he's been sunburned far beyond our help anyway.") print("3: Save him! Bring him aboard, take his loot, help him heal.") scenario_input = input("Enter your choice:") responses_dict = { "1": "The Pirate Code says to help your fellow pirates, have you fogotten?", "2": "Maybe a good deed, but even a weak body is an able body in combat.", "3": "You Truly follow the Pirate Code, or do you just seize opportunity in gaining extra hands on your voyage? It doesnt matter, either way he is the newest addition to the crew." } if scenario_input == '1': typingPrint("\n") typingPrint(responses_dict["1"]) elif scenario_input == '2': typingPrint("\n") typingPrint(responses_dict["2"]) elif scenario_input == '3': typingPrint("\n") typingPrint(responses_dict["3"]) player.add_piece_of_eight() typingPrint("\n") typingPrint(f"You now have {player.piece_of_eight} of eight pieces") typingPrint("\n") if player.piece_of_eight == 8: global game_still_going game_still_going = False else: starving_crew(player) def boat_voyage(player): typingPrint("\n") typingPrint(" You've finally made it aboard the thie ship on your first sailing voyage! Just as you begin to relax you begin hearing a lovely sound from the distance. The sound is alluring and seems to beckoning you to sail in that direction.") typingPrint("You begin to follow the lovely sound. As you get closer you notice some strange beings in the water. Wait....are those sirens?") typingPrint("Three beautiful mermaids are bathing on a rock! They introduce themselves as Kate, Lea, and Trevor.") typingPrint("Kate says that she knows the way to Captain Mady's treasure. Lea begins singing about being part of your world. Trevor pulls out a slice of pizza and begins to stare away. Which siren will you ask for help?") print("\n") print("1: Kate") print("2: Lea") print("3: Trevor") scenario_input = input("Enter your choice:") responses_dict = { "1": "Smart choice!! Kate gives you two peices of eight and whipsers a hint about how to find Captain Mady!", "2": "Lea says that her sister Ariel has what you're looking for and gives you two peices of eight and whipsers a hint to find Captain Mady!", "3": "Well...you tried. That counts for something. Trevor gives you some lint from his belly button and swims off." } if scenario_input == '1': typingPrint("\n") typingPrint(responses_dict["1"]) player.add_piece_of_eight() typingPrint("\n") typingPrint(f"You now have {player.piece_of_eight} of eight pieces") typingPrint("\n") elif scenario_input == '2': typingPrint("\n") typingPrint(responses_dict["2"]) elif scenario_input == '3': typingPrint("\n") typingPrint(responses_dict["3"]) if player.piece_of_eight == 8: global game_still_going game_still_going = False else: overboard_sailer(player) def parting_home(player): print("\n") typingPrint("You're through with Mady's meddling ruffian. It's time to begin the adventure! You head to the shores and you're met with a man selling Brigantines', perfect size ship for your adventure you think to yourself. So do you: ") print("\n") print("1: Wait until night to board the ship quietly and set sail away without notice.") print("2: Approach the man and tell him standing between you and your calling is a dangerous move.") print("3: Go back to the island, work for your gold and pay the man his share for his fair ship.") scenario_input = input("Enter your choice:") responses_dict = { "1": "You're coward of a pirate one who doesnt plunder as he pleases!", "2": "A pirate Lord has been born! The seas face a new threat, any pirate out in the water should tremble in their boots before you and your new awakening", "3": "A man who earns his fair share has no right to be a pirate, might as well work for the state and begone with this treacherous pirate journey." } if scenario_input == '1': typingPrint("\n") typingPrint(responses_dict["1"]) elif scenario_input == '2': typingPrint("\n") typingPrint(responses_dict["2"]) player.add_piece_of_eight() typingPrint("\n") typingPrint(f"You now have {player.piece_of_eight} of eight pieces") typingPrint("\n") elif scenario_input == '3': typingPrint("\n") typingPrint(responses_dict["3"]) if player.piece_of_eight == 8: global game_still_going game_still_going = False else: boat_voyage(player) def begin_game(player): typingPrint("\n") typingPrint(f"Ahoy, {player.name}! You're about to embark on an amazing voyage to obtain Captain Mady's treasure! If you know anything about Captain Mady, then you know this won't be easy. This voyage will be long and tedious. In order to obtain Captain Mady's treasure, you must collect all pieces of eight and present them to her. ") typingPrint("Throughout your journey, fun adventures await. Your decisions are important. Choosing the right reponses will ensure that you collect enough pieces to receive her treasure. ") typingPrint("Good luck! ") print("\n") typingPrint("You've just entered Rigi Town! Wow what an exciting place to be! There are wanted posters for Captain Mady all over the town. Rumor is she stole another pirate's booty! Can you believe it? I certainly can. I guess somethings just never change! ") typingPrint("Look alive! One of Mady's ruffians just approached you! ") typingPrint("What will you do? ") print("\n") print("1: Greet her with a nice and warm smile") print("2: Run away") print("3: Kick her butt!") scenario_input = input("Enter your choice:") responses_dict = { "1": "Are you serious? This is one of Captain Mady's goons we're talking about! She just kicked your butt and sent you packing!", "2": "How did you become a pirate???", "3": "I mean....she did deserve it! Great job beating up Mady's goon. You picked up two pieces of eight from the ground next to the goon's swollen face!" } if scenario_input == '1': typingPrint("\n") typingPrint(responses_dict["1"]) elif scenario_input == '2': typingPrint("\n") typingPrint(responses_dict["2"]) elif scenario_input == '3': typingPrint("\n") typingPrint(responses_dict["3"]) player.add_piece_of_eight() typingPrint("\n") typingPrint(f"You now have {player.piece_of_eight} of eight pieces") if player.piece_of_eight == 8: global game_still_going game_still_going = False else: parting_home(player) def play(): print(""""" __ ____ ____ ______ ____ ____ ____ / ] / || \ | | / || || \ / / | o || o )| || o | | | | _ | / / | || _/ |_| |_|| | | | | | | / \_ | _ || | | | | _ | | | | | | \ || | || | | | | | | | | | | | \____||__|__||__| |__| |__|__||____||__|__| ___ ___ ____ ___ __ __ __ _____ | | | / || \ | | || | / ___/ | _ _ || o || \ | | ||_ |( \_ | \_/ || || D || ~ | \| \__ | | | || _ || ||___, | / \ | | | || | || || | \ | |___|___||__|__||_____||____/ \___| ____ ___ __ __ ___ ____ ______ __ __ ____ ___ / || \ | | | / _]| \ | || | || \ / _] | o || \ | | | / [_ | _ || || | || D ) / [_ | || D || | || _]| | ||_| |_|| | || / | _] | _ || || : || [_ | | | | | | : || \ | [_ | | || | \ / | || | | | | | || . \| | |__|__||_____| \_/ |_____||__|__| |__| \__,_||__|\_||_____| """"") while game_still_going: player_name = input('Hurry up and enter your scallywags name: ').capitalize() guideList = ['Sayeda', 'Esteban', 'Eric']; guide_List = ['Sayeda', 'Esteban', 'Eric']; for item in guide_List: print(item) input('Who will be your guide?') class Pirate: def __init__(self): self.name = 'Bootleg ' + player_name self.promotion = 'Captain ' + player_name self.piece_of_eight = 0 def add_piece_of_eight(self): self.piece_of_eight = self.piece_of_eight + 2 player = Pirate() begin_game(player) if player.piece_of_eight == 8: meet_mady(player) else: typingPrint("\n") typingPrint('After a long voyage at sea, you arrive at a small island. Within that island is a deep cave! ') typingPrint('Captain Mady emerges from the shadows and shouts that you must present your eight of pieces! ') typingPrint(f"You only have {player.piece_of_eight} pieces. You don't have enough!" ) typingPrint("Captain Mady takes you a prisoner and you are never seen again!") typingPrint('The End!') play()
import math import matplotlib.pyplot as plt from .GeneralDistribution import Distribution class Binomial(Distribution): """ Binomail dist'n class for calculating and visualizing binomial dist'n. Attributes: mean (float) representing the mean value of the distribution stdev (float) representing the standard deviation of the distribution data (list of floats) a list of floats extracted from the data file p (float) the probability of success n (int) the toal number of trials """ def __init__(self, prob=0.5, size=20): self.p = prob self.n = size Distribution.__init__(self, self.calculate_mean(), self.calculate_stdev()) def __add__(self, other): try: assert self.p == other.p, 'p values are not equal' except AssertionError as error: raise result = Binomial() result.n = self.n + other.n result.p = self.p result.calculate_mean() result.calculate_stdev() return result def __repr__(self): """Function to output the characteristics of the Binomial instance Args: None Returns: string: characteristics of the Gaussian """ return "mean {}, standard deviation {}, p {}, n {}".\ format(self.mean, self.stdev, self.p, self.n)
<<<<<<< HEAD banjang = input('반장의 이름을 입력하세요') print("우리반 반장 이름은", banjang) number1 = input("첫번째 문자를 입력하세요") number2 = input("두번째 문자를 입력하세요") print(number1+number2) number1 = int(input("첫번째 문자를 입력하세요")) number1 = int(input("두번째 문자를 입력하세요")) ======= banjang = input('반장의 이름을 입력하세요') print("우리반 반장 이름은", banjang) number1 = input("첫번째 문자를 입력하세요") number2 = input("두번째 문자를 입력하세요") print(number1+number2) number1 = int(input("첫번째 문자를 입력하세요")) number1 = int(input("두번째 문자를 입력하세요")) >>>>>>> 5ded89c44aea57f1f3a7fa3eb42722f5bf1f79fc print(number1+number2)
N = list(input()) n = 0 for x in N: n += int(x) if n % 9 == 0: ans = "Yes" else: ans = "No" print(ans)
S = input() a = str(S.count('A')) b = str(S.count('B')) c = str(S.count('C')) d = str(S.count('D')) e = str(S.count('E')) f = str(S.count('F')) print(a+' '+b+' '+c+' '+d+' '+e+' '+f) #print(*[a,b,c,d,e,f])でいい ################## s=input() print(*[s.count(x) for x in 'ABCDEF'])
S = input() ans = "No" if len(S) % 2 == 0: if S == ("hi" * (len(S) // 2)): ans = "Yes" print(ans)
# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution(object): def isValidBST(self, root): """ :type root: TreeNode :rtype: bool """ self.data = [] self.step(root) if len(self.data) == 0: return True for i in range(0, len(self.data) - 1, 1): if self.data[i] >= self.data[i + 1]: return False return True def step(self, root): if root is None: return if root.left is None and root.right is None: self.data.append(root.val) return if root.left is not None: self.step(root.left) self.data.append(root.val) if root.right is not None: self.step(root.right)
""" Monte Carlo Tic-Tac-Toe Player """ import random import poc_ttt_gui import poc_ttt_provided as provided # Constants for Monte Carlo simulator # You may change the values of these constants as desired, but # do not change their names. NTRIALS = 10 # Number of trials to run SCORE_CURRENT = 1.0 # Score for squares played by the current player SCORE_OTHER = 1.0 # Score for squares played by the other player # Add your functions here. def mc_trial(board, player): """ Function to take in board and play games with random moves. """ current_player = player winner = None while winner == None: empty_spaces = board.get_empty_squares() move_space = random.choice(empty_spaces) board.move(move_space[0], move_space[1], current_player) winner = board.check_win() provided.switch_player(current_player) def mc_update_scores(scores, board, player): """ Function to take a grid of scores and updates the scores grid. """ winner = board.check_win() for col in range(board.get_dim()): for row in range(board.get_dim()): if winner == provided.DRAW: scores[row][col] += 0 elif winner == player and board.square(row, col) == player: scores[row][col] += SCORE_CURRENT elif winner == player and board.square(row, col) != player and board.square(row, col) != provided.EMPTY: scores[row][col] -= SCORE_OTHER elif winner != player and board.square(row, col) == player: scores[row][col] -= SCORE_CURRENT elif winner != player and board.square(row, col) != player and board.square(row, col) != provided.EMPTY: scores[row][col] += SCORE_CURRENT elif board.square(row, col) == provided.EMPTY: scores[row][col] += 0 def get_best_move(board, scores): """ Takes in a board and grid of scores, finds empty squares and chooses the best move. """ best_score = -50000000 # iterates through board spaces and finds the max score for col in range(board.get_dim()): for row in range(board.get_dim()): if scores[row][col] > best_score and board.square(row, col) == provided.EMPTY: best_score = scores[row][col] # finds any empty space that matches the best score empty_spaces = board.get_empty_squares() move_list = [] for space in empty_spaces: if scores[space[0]][space[1]] == best_score: move_list.append(space) best_move = random.choice(move_list) row = best_move[0] col = best_move[1] return row, col def mc_move(board, player, trials): """ Takes in a board, which player the machine player is and runs trials via the monte carlo method """ scored_board = [[0 for dummy_col in range(board.get_dim())] for dummy_row in range(board.get_dim())] for dummy_num in range(trials): clone_board = board.clone() mc_trial(clone_board, player) mc_update_scores(scored_board, clone_board, player) return get_best_move(board, scored_board) # Test game with the console or the GUI. Uncomment whichever # you prefer. Both should be commented out when you submit # for testing to save time. # provided.play_game(mc_move, NTRIALS, False) # poc_ttt_gui.run_gui(3, provided.PLAYERX, mc_move, NTRIALS, False)
import itertools # the letters a through f stand for the numbers 1-9 # d+b=c b+e=f the digits "abc" = the digits "ad" squared for x in itertools.permutations( range(1,10) ,6): if x[3] + x[1] == x[2] and x[1] + x[4] == x[5]: if pow(x[0] * 10 + x[3],2) == (x[0] * 100) + (x[1] * 10) + x[2]: print(list(zip( ['a','b','c','d','e','f'], x )))
#sectet nuber exercise secret_number = 9 guess_count = 0 guess_limit = 3 while guess_count < guess_limit: guess = int(input(f'{guess_count + 1} Guess: ')) guess_count += 1 if guess == secret_number: print('You won') break # so this else is tricky. if this else is after if then it will be printed after every guess, but when after while it will be once when while completed else: print('you guessed wrong')
#!/usr/bin/env python2.5 """ Problem 6 from Project Euler Find the difference between the sum of the squares of the first one hundred natural numbers and the square of the sum. """ n = 100 def sumsquares(n): total = 0 for i in range(1, n+1): total += i**2 return total def squaresum(n): total = 0 for i in range(1, n+1): total += i ss = total**2 return ss print squaresum(n) - sumsquares(n)
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Problem 30 from Project Euler Find the sum of all the numbers that can be written as the sum of fifth powers of their digits. """ powlen = 5 fpl = [] def splitb10(x): """Split into a tuple of the ones, tens, hundreds, etc""" sl = () while x != 0: sl += (x%10,) x/=10 return tuple(reversed(sl)) def applypow(l): sl = () for i in l: sl += (pow(i, powlen),) return sl for i in xrange(2, int("9"*(powlen+1))): if i == sum(applypow(splitb10(i))): fpl.append(i) print fpl print sum(fpl)
#!/usr/bin/env python2.5 """ Problem 9 from Project Euler There exists exactly one Pythagorean triplet for which a + b + c = 1000. Find the product abc. """ from math import sqrt l = [] n = 1000 #Find all the Pythagorean triplets for i in range(1, n+1): for j in range(1, n+1): k = sqrt(i**2 + j**2) if k % 1 == 0: l.append([i, j, int(k)]) #Go through the list of triplets, and find the one that adds to 1000 for i, j, k in l: if i + j + k == n: s = i*j*k print s
# Create a UName and Pwd in the code. # Collect credentials from user as input # match to see if the credentials are correct s1 = "sdfsdf" s2 = "sdfsdf" if s1 == s2: print ("Strings are same ") else : print ("Strings are different ") u1 = "Hemant" u2 = "Scott" u3 = "Tim" p1 = "romeo1" p2 = "romeo2" p3 = "romeo3" x = input("Enter UName") y = input("Enter Pswd") if ((x == u1) and (y == p1)) : print ("User ", x, " signed in") else : print("Unable to sign user ", x) if x == u1 and y == p1 : print("START of TRUE") print ("User ", x, " signed in") print("End of TRUE") else : print("Unable to sign user ", x) print("End of FALSE") print("This is out of IF Statement")
# Take a variable. # Put a day in it (Mon, Tue, Wed ... ) # Say if it is weekday or a weekend myDay = "Sun" """ if myDay == "Mon" : print ("Not a weekend") else : if myDay == "Tue" : print("Not a weekend") else myDay == "Wed" : print("Not a weekend") """ if myDay == "Tue" : print("Not a weekend") # myDay = input() myDay = input("Enter the day") if (myDay == "Mon") : print("Not a weekend") elif (myDay == "Tue") : print("Not a weekend") elif (myDay == "Wed") : print("Not a weekend") elif (myDay == "Thu") : print("Not a weekend") elif (myDay == "Fri") : print("Not a weekend") elif (myDay == "Sat") : print("Weekend") elif (myDay == "Sun") : print("Weekend") else : print ("Did'nt recognize your entry") if (myDay == "Sun" or myDay == "Sat") : print("Weekend") else : print("Weekday")
from datetime import datetime def get_userName(): n = raw_input("Whats your Name? ... ") return n def greet_user(name): print 'welcome {}'.format(name) def get_dob(): dob = raw_input("What's your date of birth in format m/d/y") #ask user to input data and return the date return dob def calculate_generation(year): gen = 'N/A' #Logic # if year is between 1966 - 1976 return X # if year is between 1977 - 1994 return Y # if year is between 1995 - 2012 return Z if year in range(1966,1976): return 'generation X' if year in range(1977,1994): return ' generation Y' if year in range (1995,2012): return 'generation Z' return gen user_name = get_userName() #to store the result from the fucntion into user_name greet_user(user_name) user_dob = get_dob() print user_dob # Greet user # call method get_dob to get user date of birth and store in a varabale user_dob user_year = datetime.strptime(user_dob,'%m/%d/%Y').year user_gen = calculate_generation(user_year) # Pass year to the method calculate_generation to findout generation same the retult in user_gen print 'Your name :' + user_name print 'Your DOB :' + user_dob print 'Your Generation:' + user_gen
class HeadSnakeLessThanTailSnake(Exception): def __init__(self, snake: "Snake") -> None: self.snake = snake def __str__(self) -> str: return f"{self.snake.head} less than {self.snake.tail}" class HeadSnakeEqualTailSnake(Exception): def __init__(self, snake: "Snake") -> None: self.snake = snake def __str__(self) -> str: return f"{self.snake.head} equal {self.snake.tail}" class HeadEqualStartPoint(Exception): def __init__(self, snake: "Snake") -> None: self.snake = snake def __str__(self) -> str: return f"{self.snake.head} equal start point" class SnakeSyntaxInputError(Exception): def __init__(self, snake: "Snake") -> None: self.snake = snake def __str__(self) -> str: return f"{self.snake.head} or {self.snake.tail} is Negative number or zero"
def bracket_matcher(input): # empty stack catch = [] # all the brackets brackets = {'[':']', '{':'}', '(':')'} # loop through input for i in input: # catch the keys and append to stack if i in brackets.keys(): catch.append(i) # look for other side of brackets if i in brackets.values(): # if not brackets pop outa catch and return false if brackets[catch.pop()] != i: return False if len(catch) != 0: return False else: return True print(bracket_matcher('abc(123)')) # returns true print(bracket_matcher('a[b]c(123')) # # returns false -- missing closing parens # print(bracket_matcher('a[bc(123)]')) # # returns true # print(bracket_matcher('a[bc(12]3)')) # # returns false -- improperly nested # print(bracket_matcher('a{b}{c(1[2]3)}')) # # returns true # print(bracket_matcher('a{b}{c(1}[2]3)))')) # # returns false -- improperly nested # print(bracket_matcher('())')) # # returns true # print(bracket_matcher('[]')) # # returns false - no opening bracket to correspond with last character # print(bracket_matcher('abc123yay')) # # returns true -- no brackets = correctly matched
import random print("\nLet's play Rock Paper Scissors!\n") win = 0 lose = 0 tie = 0 while True: n = random.randint(0, 2) print("Rock, Paper or Scissors?\n") RPS = input("") if RPS.upper() == "ROCK" and n == 0: tie += 1 print("\nYou played Rock, and the computer played Rock. It's a draw!\n" "\nYour current W/L/T record is: " + str(win) + "/" + str(lose) + "/" + str(tie) + ".\n") elif RPS.upper() == "ROCK" and n == 1: lose += 1 print("\nYou played Rock, and the computer played Paper. You lose!\n" "\nYour current W/L/T record is: " + str(win) + "/" + str(lose) + "/" + str(tie) + ".\n") elif RPS.upper() == "ROCK" and n == 2: win += 1 print("\nYou played Rock, and the computer played Scissors. You win!\n" "\nYour current W/L/T record is: " + str(win) + "/" + str(lose) + "/" + str(tie) + ".\n") elif RPS.upper() == "PAPER" and n == 0: win += 1 print("\nYou played Paper, and the computer played Rock. You win!\n" "\nYour current W/L/T record is: " + str(win) + "/" + str(lose) + "/" + str(tie) + ".\n") elif RPS.upper() == "PAPER" and n == 1: tie += 1 print("\nYou played Paper, and the computer played Paper. It's a draw!\n" "\nYour current W/L/T record is: " + str(win) + "/" + str(lose) + "/" + str(tie) + ".\n") elif RPS.upper() == "PAPER" and n == 2: lose += 1 print("\nYou played Paper, and the computer played Scissors. You lose!\n" "\nYour current W/L/T record is: " + str(win) + "/" + str(lose) + "/" + str(tie) + ".\n") elif RPS.upper() == "SCISSORS" and n == 0: lose += 1 print("\nYou played Scissors, and the computer played Rock. You lose!\n" "\nYour current W/L/T record is: " + str(win) + "/" + str(lose) + "/" + str(tie) + ".\n") elif RPS.upper() == "SCISSORS" and n == 1: win += 1 print("\nYou played Scissors, and the computer played Paper. You win!\n" "\nYour current W/L/T record is: " + str(win) + "/" + str(lose) + "/" + str(tie) + ".\n") elif RPS.upper() == "SCISSORS" and n == 2: tie += 1 print("\nYou played Scissors, and the computer played Scissors. It's a draw!\n" "\nYour current W/L/T record is: " + str(win) + "/" + str(lose) + "/" + str(tie) + ".\n") else: print("\nInvalid Response, please answer with the word 'rock' 'paper' or 'scissors'\n")
# ISBN def isValidISBN(isbn): # Comprobamos la longitud del isbn if len(isbn) != 10: return False # Suma de los primeros 9 dígitos # Sumatoria de la multiplicación del valor de cada caracter en el isbn por # cada elemento de la "lista orden descendente del 10 al 1" _sum = sum([(int(isbn[i])*(10 - i)) for i in range(len(isbn)-1)]) # Verificamos si el último elemento del isbn es una X, # si true, sumamos su valor (10), sino, la sumatoria es hasta el elemento 9 _sum += 10 if isbn[9] == 'X' else int(isbn[9]) print(_sum) # Retornamos true si la suma de los dígitos es divisible por 11 return (_sum % 11 == 0) isValidISBN('007462542X')
""" Program goals: 1. Get user input 2. Convert the input to input 3. Add input to list 4. Fill values from specific input positions """ #create functions that will perform those actions above import random myList = [] unique_list = [] def mainProgram(): print ("Hello! Let's work with some cool list functions. Edit your list first so you actually have data to work with.") while True: try: print("Choose one of the following options. Type numbers ONLY!") choice = input("""1. Edit List 2. Return the value at an index position 3. Random choice 4. Linear Search 5. Recursive Binary Search 6. Iterative Binary Search 7. Print List 8. Clear List 9. End Program """) if choice == "1": editList() elif choice == "2": indexValues() elif choice == "3": randomSearch() elif choice == "4": linearSearch() elif choice == "5": binSearch = input("What number are you looking for? ") recursiveBinarySearch(unique_list, 0, len(unique_list)-1, int(binSearch)) elif choice == "6": binSearch = input("What number are you looking for? ") result = iterativeBinarySearch(unique_list, int(binSearch)) #output of the search is equal to the variable result. if result != -1: #if does not equal is the ! print("Your number is at index position {}".format(result)) else: print("Your number was not found in that list, buddy!") elif choice == "7": printList() elif choice =="8": clearList() else: print("Goodbye!") break except: print("An error occurred") """ editList() Function description: The user is given 3 choices for which to edit their list, option 1 and 2 call functions as described below. The 3rd choice allows the user to remove a value from the sorted list. (I would want to allow the user to choose which list to remove an item from). We create an input of the value the user wants to remove, force that value into an integer (using int() function), and then create a while loop so that we go through the list removing the desired value each time it appears. Using the .pop() function, we remove the desired value. """ def editList(): print("""Here are the ways you can edit your list. Type in the number that correlates to your desire.""" ) edit = input(""" 1.Add a single value 2.Add multiple values 3.Remove a value""" ) if edit == "1": addToList() elif edit == "2": addABunch() else: byeBye = input("What value do you want to remove?") byeBye = int(byeBye) #now remove a value isn't working... unique_list.pop(byeBye) print("{} has been removed from your list".format(byeBye)) """ addToList() Function Description: We let the user choose which list they want to add to. Then an input lets the user add a single value to their desired list. If they want to add to the sorted list, the values automatically get sorted using the .sort() function. Otherwise the values are added in no specific order. """ def addToList(): change = input("Which list do you want to add to, sorted or unsorted?") if change.lower() == "sorted": newItem = input("Please type an integer") unique_list.append(int(newItem)) unique_list.sort() see = input("Do you want to see your list? Y/N") if see.lower() == "y": print(unique_list) else: pass else: newItem = input("Please type an integer") myList.append(int(newItem)) look = input("Do you want to see your list? Y/N") if look.lower() == "y": print(myList) """ addABunch() Function Description: We create an input for the distance and range that the user wants to add to their list. Then, from 0 to the number of values the user wants to add, the function adds random VALUES that go up to the desired range of the user. Then we take an extra step to create a seperate list that is sorted, and contains only unique numbers that appeared once when you generated the random numbers. Then we allow the user to print their compleated list. """ def addABunch(): print("We're gonna add a bunch of numbers.") numToAdd = input("How many integers do you want to add? ")#numbers numRange = input("And how high would you like these numbers to go? ")#range the things that we need for x in range (0, int(numToAdd)): myList.append(random.randint(0, int(numRange))) for x in myList: if x not in unique_list: unique_list.append(x) unique_list.sort() print("Your list is now complete!") showMe = input("Type 'print' to print your list") if showMe.lower() == "print": printList() else: pass """ clearList() Function Description: Using the .clear() function, we remove everything from the list. """ def clearList(): unique_list.clear() print("Your list is now cleared, nothing is stored in it now.") """ printList() Function Description: If there is nothing in the sorted list, then we print the unsorted list. But if there are values in both lists, we give the user a choice of which list they want to print. """ def printList(): if len(myList) == 0: print("Your list is empty!") elif len(unique_list) == 0: print(myList) else: whichOne = input("Which list? Sorted or un-sorted?") if whichOne.lower() == "sorted": print(unique_list) else: print(myList) """ indexValues() Function Explanation: we created a variable called 'indexPos',and stored the result of an input function inside it. We then force the value stored in indexPos into an integer (using the int() function) and used that variable to call a value at a specific index position. """ def indexValues(): indexPos = input("At what index position would you like to see? ") print(myList[int(indexPos)-1]) """ randomSearch() Function Description: We generate a random number from myList using the random library. The parameters are that the random number must be in myList, between 0 and the lenght of the list. If there are values stored in unique_list, we do the same thing, printing a random value. We have to be sure to subtract 1 from the number of values (len() function) so we have the correct number of intex values. """ def randomSearch(): print("Here's a random value from your list") print(myList[random.randint(0,len(myList)-1)]) if len(unique_list) > 0: print(unique_list[random.randint(0,len(unique_list)-1)]) """ linearSearch() Function Description: We create a for loop that runs through the lenght of myList, and each time that the value you are searching for is found, we add to indexCount to keep track of how many times the value appears. """ def linearSearch(): print("we're going to search through the list IN THE WORST WAY POSSIBLE!") searchItem = input("What are you looking for? Number-wise. ") indexCount = 0 for x in range (len(myList)): if myList[x] == int(searchItem): indexCount = indexCount + 1 print("Your item is at index {}" .format(x)) print("You're number appreadred {} times in the list ". format(indexCount)) """ recursiveBinarySearch() Function Description: In this function we call unique_list, low, high and x, and then by comparing the defined mid variable to x, the value you are searching for, we make the list smaller and smaller, eliminating the part of the list that does not have our value, until we eventually find our value. If the value does not exist, then the user is notified of that. """ def recursiveBinarySearch (unique_list, low, high, x): if high >= low: mid = (high + low) //2 if unique_list[mid] == x: print("Oh, what luck. Your number is at postion {}".format(mid)) elif unique_list[mid] > x: return recursiveBinarySearch(unique_list, low, mid -1, x) else: return recursiveBinarySearch(unique_list, mid + 1, high, x) else: print("Your number isn't here!") """ iterativeBinarySearch() Function Description: We create 3 variables, low, mid and high, as defined at the top and using coditinals, we run through a while loop that compares the desired value to the value of mid. If the desired value is lower than mid, we are able to eliminate the whole upper half of the list because we know we only have to search through part of the list. We do this until the desired value is found. """ def iterativeBinarySearch(unique_list, x): #how to use this search method to remove all doubled items from the list? low = 0 high = len(unique_list)-1 mid = 0 while low <= high: mid = (high + low) //2 if unique_list[mid] < x: low = mid + 1 elif unique_list[mid] > x: high = mid - 1 else: return mid return -1 #return makes something available to the user. almost like an output that the computer uses again. Used recursively. Truthy and falsey statements. if __name__ == "__main__": mainProgram()
"""Ejercicio 9: Crear un programa que pregunte al usuario 5 números enteros y devuelva una lista con ellos.""" lista_numeros = [] numero1 = int(input('1er número: ')) lista_numeros.append(numero1) numero2 = int(input('2do número: ')) lista_numeros.append(numero2) numero3 = int(input('3er número: ')) lista_numeros.append(numero3) numero4 = int(input('4to número: ')) lista_numeros.append(numero4) numero5 = int(input('5to número: ')) lista_numeros.append(numero5) print(lista_numeros)
""" AVL trees Invariant: - lenght of left/right for every node differ at most +/- 1 Details: - each node attr is height - rotate avl on each operation (left rotate / right rotate) Implement: - delete - rotateLeft - rotateRight - rebalance """ from typing import Optional from dataclasses import dataclass from queue import Queue def height(node): if node: return node.height return 0 def update_height(node): node.height = max(height(node.left), height(node.right)) + 1 @dataclass class Node: """ Node class """ parent: Optional['Node'] left: Optional['Node'] right: Optional['Node'] height: int value: int def insert(self, value): if value < self.value: if self.left: return self.left.insert(value) else: self.left = Node(self, None, None, 0, value) return self.left elif value > self.value: if self.right: return self.right.insert(value) else: self.right = Node(self, None, None, 0, value) return self.right def find_next_larger(self): """ 1. if right find min 2. go up """ if self.right: return self.right.find_min() else: current = self while current.parent and current is current.parent.right: current = current.parent return current.parent def find_min(self): if self.left: return self.left.find_min() return self def delete(self): """ 1. no child 2. one child 3. both childs """ if self.left == None and self.right == None: if self is self.parent.left: self.parent.left = None elif self is self.parent.right: self.parent.right = None return self elif self.left == None or self.right == None: if self is self.parent.left: self.parent.left = self.right or self.left elif self is self.parent.right: self.parent.right = self.right or self.left return self else: node = self.find_next_larger() node.value, self.value = self.value, node.value node.delete() return node def find(self, value): if value == self.value: return self elif value < self.value: if self.left: return self.left.find(value) elif value > self.value: if self.right: return self.right.find(value) ### Utility class functions def _str(self): """Internal method for ASCII art.""" label = str(self.value) if self.left is None: left_lines, left_pos, left_width = [], 0, 0 else: left_lines, left_pos, left_width = self.left._str() if self.right is None: right_lines, right_pos, right_width = [], 0, 0 else: right_lines, right_pos, right_width = self.right._str() middle = max(right_pos + left_width - left_pos + 1, len(label), 2) pos = left_pos + middle // 2 width = left_pos + middle + right_width - right_pos while len(left_lines) < len(right_lines): left_lines.append(' ' * left_width) while len(right_lines) < len(left_lines): right_lines.append(' ' * right_width) if (middle - len(label)) % 2 == 1 and self.parent is not None and \ self is self.parent.left and len(label) < middle: label += '.' label = label.center(middle, '.') if label[0] == '.': label = ' ' + label[1:] if label[-1] == '.': label = label[:-1] + ' ' lines = [' ' * left_pos + label + ' ' * (right_width - right_pos), ' ' * left_pos + '/' + ' ' * (middle-2) + '\\' + ' ' * (right_width - right_pos)] + \ [left_line + ' ' * (width - left_width - right_width) + right_line for left_line, right_line in zip(left_lines, right_lines)] return lines, pos, width def __str__(self): return '\n'.join(self._str()[0]) def print(self): if self.left: self.left.print() print(self.value, ':', self.height) if self.right: self.right.print() def check_ri(self): """ Check binary tree invariant """ if self.left: assert self.left.parent == self assert self.value > self.left.value self.left.check_ri() if self.right: assert self.right.parent == self assert self.value < self.right.value self.right.check_ri() @dataclass class Tree: root: Node def insert(self, value): if self.root is None: self.root = Node(None, None, None, 0, value) else: new_node = self.root.insert(value) self.rebalance(new_node) def delete(self, value): self.root.find(value).delete() def print(self): self.root.print() self.root.check_ri() def get_next_larger(self, value): node = self.root.find(value) return node.find_next_larger() def rotate_right(self, nodeb): """ - find node - rotate in 3 steps as diagram """ print('kek_R', nodeb.value) nodea = nodeb.parent # 1. update parents link if nodea.parent is None: self.root = nodeb else: if nodea is nodea.parent.left: nodea.parent.left = nodeb else: nodea.parent.right = nodeb nodeb.parent = nodea.parent # 2. update right nodea.left = nodeb.right if nodea.left: nodea.left.parent = nodea # 3. Link a<->b nodea.parent = nodeb nodeb.right = nodea update_height(nodea) update_height(nodeb) def rotate_left(self, nodeb): """ - find node - rotate in 3 steps as diagram """ print('kek_L', nodeb.value) nodea = nodeb.parent # 1. update parents link if nodea.parent is None: self.root = nodeb else: if nodea is nodea.parent.left: nodea.parent.left = nodeb else: nodea.parent.right = nodeb nodeb.parent = nodea.parent # 2. update right nodea.right = nodeb.left if nodea.right: nodea.right.parent = nodea # 3. Link a<->b nodea.parent = nodeb nodeb.left = nodea update_height(nodea) update_height(nodeb) def rebalance(self, node): # return while node is not None: update_height(node) if height(node.left) >= height(node.right) + 2: if height(node.left.left) > height(node.left.right): self.rotate_right(node.left) else: self.rotate_left(node.left.right) self.rotate_right(node.left) elif height(node.right) >= height(node.left) + 2: if height(node.right.left) > height(node.right.right): self.rotate_right(node.right.left) self.rotate_left(node.right) else: self.rotate_left(node.right) node = node.parent def show_tree(self): from binarytree import build queue = Queue() queue.put(self.root) result = [] while not queue.empty(): item = queue.get() if item: result.append(item.value) if item.left: queue.put(item.left) else: queue.put(None) if item.right: queue.put(item.right) else: queue.put(None) else: result.append(item) print(result) print(build(result)) if __name__ == '__main__': """ __10___ / \ 8 _35_ \ / \ 9 34 901 """ tree = Tree(None) tree.insert(10) tree.insert(8) tree.insert(9) tree.insert(7) tree.insert(6) tree.insert(5) tree.insert(4) tree.insert(35) tree.insert(34) tree.insert(901) print(tree.root) # exit() # print(tree.root.find(35).value) # print(tree.root.find_min().value) # print(tree.get_next_larger(9).value) # # tree.delete(9) # tree.show_tree() # tree.print() # tree.rotate_right(tree.root.find(34)) # tree.rotate_left(tree.root.find(35)) # tree.root.check_ri() # tree.show_tree() # tree.root.check_ri()
class Car: #Define a class """My first Python class.""" def __init__(self,make,model,year): #Init method of the class, though it is not necessary but recommended if using OOP """Initialize attributes for a car.""" self.make = make #This and below attributes are initialized based on the parameters provided at the time of initializing class self.model = model self.year = year self.odo_reading = 0 #Attributes with a default value def get_descriptive_name(self): #A method to print car name """Return a formatted name.""" long_name = f"{self.year} {self.make} {self.model}" return long_name.title() def update_odo(self,mileage): """ Set the odometer reading to the given value. Reject the change if it attempts to roll the value back. """ if mileage >= self.odo_reading: self.odo_reading = mileage else: print("You can not roll back the odo reading.") my_new_car = Car('audi','a4',2019) #Creating an instance of class "car" print(my_new_car.get_descriptive_name()) #Calling the method of class car. print(my_new_car.odo_reading) #Printing a attribute my_new_car.odo_reading = 10 #Assigning a new value to the attribute print(my_new_car.odo_reading) #Changing odo reading using class method my_new_car.update_odo(9) #This will print "You can not roll back the odo reading." print(my_new_car.odo_reading) #This will print old value which is 10 my_new_car.update_odo(12) print(my_new_car.odo_reading)
class CrclArea: """Class to calclate the area of a circle.""" def __init__(self, pi, radius): self.pi = pi self.radius = radius def crcl_area(self): area = self.pi * (self.radius)**2 return area pi = '' radi = 2 file = 'pi_digits.txt' with open(file) as file_object: lines = file_object.readlines() for line in lines: pi += line.strip() print(f"pi value given in the file is '{pi}'.") calc_area = CrclArea(float(pi),radi) print(f"Area of circle is '{calc_area.crcl_area()}'.")
#Inheritance Example showing passing a class instance as attributes #Super Class (or Parent class) class Car: #Define a class """My first Python class.""" def __init__(self,make,model,year): #Init method of the class, though it is not necessary but recommended if using OOP """Initialize attributes for a car.""" self.make = make #This and below attributes are initialized based on the parameters provided at the time of initializing class self.model = model self.year = year self.odo_reading = 0 #Attributes with a default value def get_descriptive_name(self): #A method to print car name """Return a formatted name.""" long_name = f"{self.year} {self.make} {self.model}" return long_name.title() def read_odo(self): print(f"This car has {self.odo_reading} miles on it.") def update_odo(self,mileage): """ Set the odometer reading to the given value. Reject the change if it attempts to roll the value back. """ if mileage >= self.odo_reading: self.odo_reading = mileage else: print("You can not roll back the odo reading.") def incre_odo(self,miles): self.odo_reading += miles #Same as self.odo_reading = self.odo_reading + miles #Sub Class (or child class) class Battery: """A simple example to model a battery for an electric car.""" def __init__(self,battery_size=75): """Initialize the battery's attributes.""" self.battery_size = battery_size def desc_battery(self): """Print a statement desc the battery size.""" print(f"This car has a {self.battery_size}-kWh battery.") def get_range(self): """Print a statement about the range this battery provides.""" range = 0 if self.battery_size == 75: range = 260 elif self.battery_size == 100: range = 315 print(f"This car can go about {range} miles on a full charge.") class ElectricCar(Car): """Represent aspects of a car, specific to electric vehicles.""" def __init__(self, make, model, year): """Initialize attributes of the parent class.""" super().__init__(make, model, year) self.battery = Battery() #Passing a Battery class instance as attribute my_tesla = ElectricCar('tesla','model s', 2019) print(my_tesla.get_descriptive_name()) my_tesla.battery.desc_battery() my_tesla.battery.get_range()
#grocery = {"flour":10,"rice":10,"sugar":5,"pulse1":2,"pulse2":2,"pulse3":3} #print (grocery) #for key,val in grocery.items(): # if(key == "rice"): # print(val) #del grocery # ............... new program grocery = {} no_of_items = int(input("enter the number of items to be inserted\n")) for i in range(0,no_of_items): item = input("enter the item name\n") price = float(input("enter the item price per KG.\n")) grocery[item] = price # print(grocery) def look(item): send = 0 for key,value in grocery.items(): if(key==item): print("price of ", key ," is Rs.", value,"/kg \n") send = 1 return send return send item = input("enter the name of item to be searched\n") if(not (look(item))): print("item not found\n")
*** program for n= 5 to print pattern like #@@@@@ ### ##### ### @@@@@# *** n=5 m=n x=1 for i in range(n//2+1): print(" "*m,end='') #same as using for loop print("x"*x,end='') if(i==0):print("@"*n,end='') m-=1 x+=2 print("") m+=1 x-=2 for i in range(n//2): if(i==n//2-1):print("@"*n,end="") else:print(" "*m,end='') x-=2 print("x"*x,end='') print("")
# the code below uses a static array where none value denotes that node has not child(left/right) ''' the binary tree for the array below will be 1 / \ 2 3 / \ / \ 4 5 6 7 / \ 8 9 ''' arr = [1,2,3,4,5,6,7,None,None,8,9,None,None,None,None] l = 0 index = 0 maxArray = [1] maxArrayValue = 0 while(index < len(arr)): for i in range(0,pow(2,l)): if (2*index + 2) < len(arr) and arr[index] != None: if arr[2*index + 1] != None: maxArrayValue = maxArrayValue + 1 if arr[2*index + 2] != None: maxArrayValue = maxArrayValue + 1 index = index + 1 maxArray.append(maxArrayValue) maxArrayValue = 0 l = l + 1 print("The maximumwidth is :",max(maxArray))
#!/bin/python3 import math import os import random import re import sys # # Complete the 'pickingNumbers' function below. # # The function is expected to return an INTEGER. # The function accepts INTEGER_ARRAY a as parameter. # def pickingNumbers(a): # Write your code herere count = 1 newAr = {} tempAr = [] a.sort() for i in range (0,len(a)): tempAr.append(a[i]) kFlag = 0 for j in range (0,len(a)): if i != j : if abs(a[i] - a[j]) == 0 or abs(a[i] - a[j]) == 1 : # checking that new number has 1 or 0 abs value for k in range(0,len(tempAr)): if abs(tempAr[k] - a[j]) == 0 or abs(tempAr[k] - a[j]) == 1 : kFlag = 0 else : kFlag = 1 break if kFlag == 0 : tempAr.append(a[j]) if len(tempAr) > count : count = len(tempAr) tempAr.clear() return count if __name__ == '__main__': fptr = open(os.environ['OUTPUT_PATH'], 'w') n = int(input().strip()) a = list(map(int, input().rstrip().split())) result = pickingNumbers(a) fptr.write(str(result) + '\n') fptr.close()
# REVIEWING LOOPS #-----> GENERAL STUCTURE OF FOR LOOPS USING A COLLECTION: # for <temporary variable> in <collection>: # <action> # A for keyword indicates the start of a for loop. # A <temporary variable> that is used to represent the value of the element in the collection the loop is currently on. # An in keyword separates the temporary variable from the collection used for iteration. # A <collection> to loop over. In our examples, we will be using a list. # An <action> to do anything on each iteration of the loop. # Write a for loop that prints each sport and game in the lists: board_games = ["Settlers of Catan", "Carcassone", "Power Grid", "Agricola", "Scrabble"] sport_games = ["football", "hockey", "baseball", "cricket"] for game in board_games: print(game) for sport in sport_games: print(sport) # Add students from list A to list B: students_period_A = ["Alex", "Briana", "Cheri", "Daniele"] students_period_B = ["Dora", "Minerva", "Alexa", "Obie"] for student in students_period_A: students_period_B.append(student) print(student) print(students_period_B) #------> GENERAL STRUCTURE OF FOR LOOPS USING A RANGE FUNCTION # for <temporary variable> in <list of length 6>: # print("Learning Loops!") # Notice temp variable is not used in the function body but we can use temp + 1 to see how many iterations. # We use range directly in our for loops as the collection to perform a number of given steps. # Print out the provided promise five times: promise = "I will finish the python loops module!" for sentence in range(5): print(promise) #-----> GENERAL STRUCTURE FOR A WHILE LOOP: # while <conditional statement>: # <action> # count = 0 # while count <= 3: # # Loop Body # print(count) # count += 1 # Similar to for loops, Python allows us to write elegant one-line while loops. Here is our previous example in a single line: # count = 0 # while count <= 3: print(count); count += 1 # Note: Here we separate each statement with a ; to denote a separate line of code. # Complete a countdown and Liftoff sequence countdown = 10 while countdown >= 0: print(countdown) countdown -= 1 print("We have liftoff!") # -----> GENERAL STURCTURE OF WHILE LOOPS WITH LISTS # We can use while loops to iterate through a list # We can then use this length in addition to another variable to construct the while loop: # length = len(ingredients) # index = 0 # while index < length: # print(ingredients[index]) # index += 1 # Iterate over the list and print out topics python_topics = ["variables", "control flow", "loops", "modules", "classes"] # NOTE: It's like javascript forloop and while loop takes a takes a start and stop, but the iteration part is added manually later in the code, after the action is taken. #Your code below: length = len(python_topics) index = 0 while index < length: print(f"I am learning about {python_topics[index]}") index +=1 #-----> GENERAL STUCTURE FOR LOOP CONTROL: BREAK # When the program hits a break statement it immediately terminates a loop. # It’s often the case that we want to search a list to check if a specific value exists. But once it's found we don't want to waste resources checking the rest of the items in the list. # items_on_sale = ["blue shirt", "striped socks", "knit dress", "red headband", "dinosaur onesie"] # for item in items_on_sale: # if item == "knit dress": # print("Found it") # Search for the dog bread you want, then use break to stop the loop: dog_breeds_available_for_adoption = ["french_bulldog", "dalmatian", "shihtzu", "poodle", "collie"] dog_breed_I_want = "dalmatian" for dog_breed in dog_breeds_available_for_adoption: print(dog_breed) if dog_breed == dog_breed_I_want: print("They have the dog I want!") break #-----> GENERAL STUCTURE FOR LOOP CONTROL: CONTINUE # Used to skip the current iteration/index in the loop. The following skips iterations less than 1 and outputs positive numbers. #Continue is usually paired with a conditional (if/else/elif) # big_number_list = [1, 2, -1, 4, -5, 5, 2, -9] # for num in big_number_list: # if num <= 0: # continue # print(num) # If an entry is less than 21 skip it and move on to the next entry, otherwise print age. ages = [12, 38, 34, 26, 21, 19, 67, 41, 17] for i in ages: if i < 21: continue print(i) #-----> NESTED LOOPS # We may want to access data inside a nested loop # We must iterate over the outer loop, then the inner loop # project_teams = [["Ava", "Samantha", "James"], ["Lucille", "Zed"], ["Edgar", "Gabriel"]] # # Loop through each sublist # for team in project_teams: # # Loop elements in each sublist # for student in team: # print(student) # Iterate over the nested loop and caluclate the total scoop sales. sales_data = [[12, 17, 22], [2, 10, 3], [5, 12, 13]] scoops_sold = 0 for location in sales_data: for sale in location: scoops_sold += sale print(location) print(scoops_sold) #-----> GENERAL STRUCTURE FOR LIST COMPREHENSION # new_list = [<expression> for <element> in <collection>] # numbers = [2, -1, 79, 33, -45] # doubled = [num * 2 for num in numbers] # print(doubled) # Scale grades based on highest score: grades = [90, 88, 62, 76, 74, 89, 48, 57] scaled_grades = [grade + 10 for grade in grades] print(scaled_grades) #-----> GENERAL STRUCTURE FOR LIST COMPREHENSION WITH CONDITIONALS: # numbers = [2, -1, 79, 33, -45] # negative_doubled = [num * 2 for num in numbers if num < 0] # print(negative_doubled) # If there is more than one condition, such as an else, it all comes before the for loop. # numbers = [2, -1, 79, 33, -45] # doubled = [num * 2 if num < 0 else num * 3 for num in numbers ] # print(doubled) #If a rider is taller than 161 centimeters thy can ride the ride. Print a list for those that can ride: heights = [161, 164, 156, 144, 158, 170, 163, 163, 157] can_ride_coaster = [height for height in heights if height > 161] print(can_ride_coaster) # -----> FINAL REVIEW <--------- # Create a list that consists of numbers 0 to 9 single_digits = range(0, 10) # Loop through single_digits for digit in single_digits: print(digit) # square each digit in the list and return list squares = [] for digit in single_digits: print(digit) squares.append(digit ** 2) print(squares) # List comprehension to the third power cubes = [digit ** 3 for digit in single_digits] print(cubes)
array = ['a', 'b', 'c', 'd', 'e'] print(array[::-1]) ##내일
import csv class Nation: def __init__(self, name, staticData): self.name = name self.data = {} for prop in staticData: self.data[prop] = staticData[prop] def addYearData(self, year, yearData): self.data[year] = yearData def getGDP(self, year, perCap = False): data = self.data if year not in data or 'gdp_percap' not in data[year] or 'population' not in data[year]: return False else: data = data[year] try: return round(float(data['gdp_percap']) * float(data['population'] if not perCap else 1)) except ValueError: return False class World: def __init__(self): self.totalNations = 0 self.earliestYear = False self.latestYear = False self.allProps = ['iso2c','iso3c','country','year','gdp_percap','life_expect','population','birth_rate','neonat_mortal_rate','region','income'] self.staticProps = ['iso2c','iso3c','region'] self.yearlyProps = ['gdp_percap', 'life_expect', 'population', 'birth_rate','neonat_mortal_rate', 'income'] self.filePath = './data/datavis/nations.csv' self.nations = self.processCSV() print('total nation count: '+str(self.totalNations)) print('earliest year: '+str(self.earliestYear)) print('latest year: '+str(self.latestYear)) def processCSV(self): output = {} def getSubData(data, yearly = False): if yearly: props = self.yearlyProps else: props = self.staticProps outputData = {} for prop in props: outputData[prop] = data[prop] return outputData print('csv process initalized...') with open(self.filePath, newline='') as csvfile: nations = csv.reader(csvfile) props = [] for row in nations: if len(props) < 1: props = row else: nationData = {} for i in range(len(props)): nationData[props[i]] = row[i] country = nationData['country'] year = nationData['year'] if not self.earliestYear or int(year) < self.earliestYear: self.earliestYear = int(year) if not self.latestYear or int(year) > self.latestYear: self.latestYear = int(year) if country not in output: self.totalNations += 1 output[country] = Nation(country, getSubData(nationData, False)) output[country].addYearData(year, getSubData(nationData, True)) print('csv process finished.') return output def allTheNations(self): for nation in self.nations: print(self.nations[nation].name) def worldPop(self, year): pop = 0 nations = self.nations for nation in nations.values(): if year in nation.data and nation.data[year]['population']: pop += round(float(nation.data[year]['population'])) return pop def showAllGDP(self, year, perCap = False): def fnRanking(nation): GDP = self.nations[nation].getGDP(year, perCap) if GDP: return GDP else: return 0 ranked = sorted(self.nations, key=fnRanking, reverse=True) rank = 1 for nation in ranked: nationInst = self.nations[nation] GDP = nationInst.getGDP(year, perCap) if not GDP: text = '----' else: text = str(GDP) print(str(rank).ljust(4), nationInst.name.ljust(34), text) rank += 1
def Sort(d): sorted_values = list({k: int(v) for k, v in sorted(d.items(), key=lambda item: int(item[1]), reverse=True)}.values()) sorted_dict = {} while sorted_values: keys_with_same_value = [] value = sorted_values[0] for k in d.keys(): if int(d[k]) == value: keys_with_same_value.append(k) keys_with_same_value.sort() for k in keys_with_same_value: sorted_values.pop(0) sorted_dict[k] = value return sorted_dict def PrintKeyValue(d): for k, v in d.items(): print(k, v) def Print(d): for k in d.keys(): print(k) def main(): list_of_tuples = [ ('Russia', '25'), ('France', '132'), ('Germany', '132'), ('Spain', '178'), ('Italy', '162'), ('Portugal', '17'), ('Finland', '3'), ('Hungary', '2'), ('The Netherlands', '28'), ('The USA', '610'), ('The United Kingdom', '95'), ('China', '83'), ('Iran', '76'), ('Turkey', '65'), ('Belgium', '34'), ('Canada', '28'), ('Switzerland', '26'), ('Brazil', '25'), ('Austria', '14'), ('Israel', '12') ] d = dict(list_of_tuples) d = Sort(d) Print(d) #PrintKeyValue(d) if __name__ == '__main__': main()
# CODE IS FROM https://www.digitalocean.com/community/tutorials/how-to-make-a-simple-calculator-program-in-python-3 # LICENSED Attribution-NonCommercial-ShareAlike # 4.0 International (CC BY NC-SA 4.0) # CODE IS NOT OWNED BY ME # Improved certain sections and added various other functions import math def mode(): mode = True while mode == True: try: return {"1":1,"2":2}[input(''' ========================== MODE 1 - Default Calculator | MODE 2 - Conversion | =========================== Type 1 or 2 ONLY Mode Number : ''')] except (ValueError,TypeError,KeyError): print("Please select only 1 or 2.") mode() def calculator(): number_1 = float(input('Please enter the first number: ')) operation = input(''' Please type in the math operation you would like to complete: =========================== + for addition - for subtraction * for multiplication / for division ^ for power sqrt for squareroot degtorad for Degree to Radian Conversion radtodeg for Radian to Degree Conversion pi/ - Number 1 / pi pi* - Number 1 * pi fact - Factorial of a no1 =========================== Enter operator: ''') if operation =='degtorad': print('{} deg converted to ='.format(number_1),end='') print(math.radians(number_1),'radians') elif operation =='fact': print("{}'s factorial is {}".format(number_1,math.factorial(number_1))) elif operation =='radtodeg': print('{} rad converted to ='.format(number_1),end='') print(math.degrees(number_1),'degrees') elif operation =='sqrt': print('{} square root = '.format(number_1), end='') print(math.sqrt(number_1)) elif operation == 'pi/': print('{} / pi = '.format(number_1), end='') print(number_1 / math.pi) elif operation == 'pi*': print('{} * pi = '.format(number_1), end='') print(number_1 * math.pi) elif operation != 'sqrt' or 'degtorad' or 'radtodeg' or 'pi/' or 'pi*': number_2 = int(input('Please enter the second number: ')) if operation == '+': print('{} + {} = '.format(number_1, number_2), end='') print(number_1 + number_2) elif operation == '-': print('{} - {} = '.format(number_1, number_2), end='') print(number_1 - number_2) elif operation == '*': print('{} * {} = '.format(number_1, number_2), end='') print(number_1 * number_2) elif operation == '/': print('{} / {} = '.format(number_1, number_2), end='') print(number_1 / number_2) elif operation == '^': print('{} ^ {} = '.format(number_1, number_2), end='') print(number_1 ** number_2) else: print('You are not typed a valid operator, please run the program again.') # Add again() function to calculate() function again() def again(): calc_again = input(''' Do you want to calculate again? Please type Y for YES or N for NO. ENTER HERE: ''') if calc_again.upper() == 'Y': calculator() elif calc_again.upper() == 'N': print('See you later.') else: again() calculator()
class BST: def __init__(self, value): self.value = value self.left = None self.right = None def __str__(self): result = '' result += str(self.value) result += ' ' if self.left: result += str(self.left) if self.right: result += str(self.right) result += ' ' return result # Average O(log(n)) time | O(1) space # Worst O(n) time | O(1) space def insert(self, value): curr = self while True: if value < curr.value: if curr.left is None: curr.left = BST(value) break else: curr = curr.left else: if curr.right is None: curr.right = BST(value) break else: curr = curr.right return self # Average O(log(n)) time | O(1) space # Worst O(n) time | O(1) space def contains(self, value): curr = self while curr is not None: if value < curr.value: curr = curr.left elif value > curr.value: curr = curr.right else: return True return False def minimum(self): curr = self while True: if curr.left is None: return curr.value else: curr = curr.left return self def maximum(self): curr = self while True: if curr.right is None: return curr.value else: curr = curr.right return self # Average O(log(n)) time | O(1) space # Worst O(n) time | O(1) space def remove(self, value, parent = None): curr = self while curr is not None: if value < curr.value: parent = curr curr = curr.left elif value > curr.value: parent = curr curr = curr.right else: # here we have found the value that we want to delete if curr.right is not None and curr.left is not None: curr.value = curr.right.minimum() curr.right.remove(curr.value, curr) elif parent is None: if curr.left is not None: curr.value = curr.left.value curr.right = curr.left.right curr.left = curr.left.left elif curr.right is not None: curr.value = curr.right.value curr.left = curr.right.left curr.right = curr.right.right else: curr.value = None elif parent.left is curr: parent.left = curr.left if curr.left is not None else curr.right elif parent.right is curr: parent.right = curr.left if curr.left is not None else curr.right break return self root = BST(10) root.insert(4) root.insert(3) root.insert(7) root.insert(12) root.insert(15) root.insert(20) print(root.__str__()) root.remove(10) print(root.__str__()) print('minimum:', root.minimum()) print('maximum:', root.maximum()) print(root.contains(20))
# Write a function that takes in an array of unique integers and returns its powerset. # The powerset P(X) of a set X is the set of all subsets of X. # For example, the powerset of [1,2] is [[], [1], [2], [1,2]]. # Note that the sets in the powerset do not need to be in any particular order. # O(2^n*n) TIME | O(2^n*n) SPACE def powerset(array): subsets = [[]] for element in array: for i in range(len(subsets)): currentSubset = subsets[i] subsets.append(currentSubset + [element]) return subsets def powersetRecursive(array, idx = None): if idx is None: idx = len(array) - 1 elif idx < 0: return [[]] element = array[idx] subsets = powersetRecursive(array, idx - 1) for i in range(len(subsets)): currentSubset = subsets[i] subsets.append(currentSubset + [element]) return subsets
#2020/12/31 def solution(priorities, location): array1 = [c for c in range(len(priorities))] array2 = priorities.copy() i = 0 while True: if array2[i] < max(array2[i + 1:]): array1.append(array1.pop(i)) array2.append(array2.pop(i)) else: i += 1 if array2 == sorted(array2, reverse = True): break return array1.index(location) + 1 def solution2(priorities, location): queue = [(i,p) for i,p in enumerate(priorities)] answer = 0 while True: cur = queue.pop(0) if any(cur[1] < q[1] for q in queue): queue.append(cur) else: answer += 1 if cur[0] == location: return answer
# input: hand (list of strings, the last character of each string representing the suite) # return: boolean value representing whether or not a pair was found def pair(hand): # first we build a list of the values of the cards in the hand, i.e. forget the suite list_of_values = [] for card in hand: value = card[:-1].lower() # strips the suite from the card. E.g. "As" become "A". # also converts the value of the card to lower case for easy comparison list_of_values.append(value) # add value for the card to the list of values # a fast way to do the above is through a Python "list comprehension": # list_of_values = [card[:-1].lower() for card in hand] if len(list_of_values) == len(set(list_of_values)): # set(list) turns a list into a set, in particular, # it removes duplicates in a list! return False # if the size of hand stays the same after # removing duplicates then there were no dupicates! else: return True # input: hand (list of strings, the last character of each string representing the suite) # return: boolean value representing whether or not three of a kind was found def three_of_a_kind(hand): # see the comments and code in the "pair" function for explanation # and the long way of doing this list_of_values = [card[:-1].lower() for card in hand] # removes duplicates from the list of values list_of_distinct_values = list(set(list_of_values)) # makes a list of the number of times each distinct value is duplicated in the hand # e.g. a 3 in list_of_duplicates means that there were 3 cards with the same value # in the hand list_of_duplicates = [list_of_values.count(value) for value in list_of_distinct_values] # checks if there were 3 cards with the same value in the hand if 3 in list_of_duplicates: return True else: return False # input: hand (list of strings, the last character of each string representing the suite) # return: boolean value representing whether or not four of a kind was found def four_of_a_kind(hand): # see the comments and code in the "pair" function for explanation # and the long way of doing this list_of_values = [card[:-1].lower() for card in hand] # removes duplicates from the list of values list_of_distinct_values = list(set(list_of_values)) # makes a list of the number of times each distinct value is duplicated in the hand # e.g. a 4 in list_of_duplicates means that there were 4 cards with the same value # in the hand list_of_duplicates = [list_of_values.count(value) for value in list_of_distinct_values] # checks if there were 4 cards with the same value in the hand if 4 in list_of_duplicates: return True else: return False # input: hand (list of strings, the last character of each string representing the suite) # return: boolean value representing whether or not two pairs was found def two_pair(hand): # see the comments and code in the "pair" function for explanation # and the long way of doing this list_of_values = [card[:-1].lower() for card in hand] # removes duplicates from the list of values list_of_distinct_values = list(set(list_of_values)) # makes a list of the number of times each distinct value is duplicated in the hand # e.g. a 4 in list_of_duplicates means that there were 4 cards with the same value # in the hand list_of_duplicates = [list_of_values.count(value) for value in list_of_distinct_values] # checks if there were more than 1 value that is duplicated in the hand if list_of_duplicates.count(2) > 1: return True else: return False # input: hand (list of strings, the last character of each string representing the suite) # return: boolean value representing whether or not a full house was found def full_house(hand): # see the comments and code in the "pair" function for explanation # and the long way of doing this list_of_values = [card[:-1].lower() for card in hand] # removes duplicates from the list of values list_of_distinct_values = list(set(list_of_values)) # makes a list of the number of times each distinct value is duplicated in the hand # e.g. a 4 in list_of_duplicates means that there were 4 cards with the same value # in the hand list_of_duplicates = [list_of_values.count(value) for value in list_of_distinct_values] # checks if there were 3 cards with the same value and 2 others with the same value in the hand if 3 in list_of_duplicates and 2 in list_of_duplicates: return True else: return False # input: hand (list of strings, the last character of each string representing the suite) # return: boolean value representing whether or not a flush was found def flush(hand): # first we build a list of the suites represented in the hand # see the comments and code in the "pair" function for explanation # and the long way of doing this list_of_suites = [card[-1].lower() for card in hand] # removes duplicates from the list of suites list_of_distinct_suites = set(list_of_suites) # if there are more than one suite in the hand, then it's not a flush if len(list_of_distinct_suites) > 1: return False else: return True
#Jung Kim #CS-21 #Project #2 - Basic grade book def gradebook(): #creates the grade book as an empty list roster = [] return roster def add_student(roster): #a function to add students to the roster created in gradebook() user_confirm, confirm = confirming() #local confirm feature to increase efficiency while user_confirm in confirm: #a loop that allows user to input any number of students into the grade book roster.append({"first":input("First name: "), "last":input("Last name: "), "id":input("Student ID: "), "test_grades":{"midterm":input("Midterm grade: "),"final":input("Final exam grade: ")}, "overall_grades":{"course_grade":"","letter_grade":""}}) user_confirm = input("\nContinue?: ") #conditional to either stop or continue loop def calculate_individual_grade(roster): #calculates students' grade in the class based on the two exams, grading scale taken from class syllabus for student in roster: #a loop that goes through all the students in roster student["overall_grades"]["course_grade"] = (int(student["test_grades"]["midterm"]) + int(student["test_grades"]["final"])) / len(student["test_grades"]) #calculates the course grade if student["overall_grades"]["course_grade"] >= 0: #used a nested conditional to give a letter representation of student's grade student["overall_grades"]["letter_grade"] = "F" if student["overall_grades"]["course_grade"] >= 60: student["overall_grades"][" letter_grade"] = "D-" if student["overall_grades"]["course_grade"] >= 64: student["overall_grades"]["letter_grade"] = "D" if student["overall_grades"]["course_grade"] >= 67: student["overall_grades"]["letter_grade"] = "D+" if student["overall_grades"]["course_grade"] >= 70: student["overall_grades"]["letter_grade"] = "C-" if student["overall_grades"]["course_grade"] >= 74: student["overall_grades"]["letter_grade"] = "C" if student["overall_grades"]["course_grade"] >= 77: student["overall_grades"]["letter_grade"] = "C+" if student["overall_grades"]["course_grade"] >= 80: student["overall_grades"]["letter_grade"] = "B-" if student["overall_grades"]["course_grade"] >= 84: student["overall_grades"]["letter_grade"] = "B" if student["overall_grades"]["course_grade"] >= 87: student["overall_grades"]["letter_grade"] = "B+" if student["overall_grades"]["course_grade"] >= 90: student["overall_grades"]["letter_grade"] = "A-" if student["overall_grades"]["course_grade"] >= 94: student["overall_grades"]["letter_grade"] = "A" def calculate_class_avg(roster): #calculated the class average of each test and then calculated overall class grade class_midterm = [] #puts all the midterm scores in roster into a new list to allow easier calculation class_final = [] #same as above for student in roster: #loop to put every midterm and final score into the lists above class_midterm = class_midterm + [int(student["test_grades"]["midterm"])] class_final = class_final + [int(student["test_grades"]["final"])] class_midterm_average = sum(class_midterm) / len(class_midterm) #calculates the midterm by taking the sum of the list and dividing by the number of items in the list class_final_average = sum(class_final) / len(class_final) #same as above overall_course_grade = (class_midterm_average + class_final_average) / 2 #takes the average of midterm and final average for course average return (class_midterm_average, class_final_average, overall_course_grade) #returns the value to print later def search(roster): #a search function that allows users to search by first name, last name or id number user_confirm, confirm = confirming() move_on = False #set conditional to False to allow loop to work as long as user wants to continue searching while user_confirm in confirm: search = input("\nPlease enter the first or last name of the student or the student's ID you wish to search:\n") #enter only the last name, first name or the id; the function to parse inputs has not yet been implemented for student in roster: if (search.lower() == student["first"].lower() #if user inputs matches a first name, last name or id anywhere in the roster, it will print the searched student's information or search.lower() == student["last"].lower() or search == student["id"]): print("\nName: ", student["last"], ", ", student["first"], "\nStudent ID: ", student["id"], "\nScores: ", student["test_grades"]["midterm"], "% Midterm, ", student["test_grades"]["final"], "% Final", "\nCourse grade: ", int(student["overall_grades"]["course_grade"]), "%, ", student["overall_grades"]["letter_grade"],"\n", sep='') user_confirm = input("Would you like to search for another student?:\n") move_on = True break else: #if no one was found using the above method, the code will move on to the next conditional move_on = False if move_on == False: #if no one was found, the code will print necessary information and allow user to search again print("No matching student has been found.\n") user_confirm = input("Would you like to search for another student?:\n") def confirming(): #a confirm function used throughout the code to increase efficiency user_confirm = "yes" confirm = ["yes"] return(user_confirm, confirm) def access_roster(roster): #a menu function (idea credited to Eric Liu, code was done individually) to allow users to add, search and print test averages user_confirm, confirm = confirming() menu_interface = input("Please enter the digit corresponding to the action you would like performed:\n(1) Add students to grade book\n(2) Search for students by name or ID\n(3) Print overall test averages\n") #a menu interface using number values while user_confirm in confirm: if int(menu_interface) == 1: #1 allows users to add students and automatically calculates the grades for each student and all the averages of all the students added thus far; if new students are added, new calculations are made and immediately updated add_student(roster) calculate_individual_grade(roster) calculate_class_avg(roster) elif int(menu_interface) == 2: #2 allows users to search for any student so long as there is at least 1 entry in the roster if len(roster) > 0: search(roster) else: print("There are no students in the grade book.\n") #if there are no entries in the roster, the code will send user back to the main menu elif int(menu_interface) == 3: #3 allows users to print the midterm avg, final avg and course avg of the whole class so long as there is at least 1 entry in the roster if len(roster) > 0: class_midterm_average, class_final_average, overall_class_grade = calculate_class_avg(roster) print("\nThe average score for the midterm exam is: ", int(class_midterm_average), "%", sep = '') print("The average score for the final exam is: ", int(class_final_average), "%", sep = '') print("The average grade overall in the class is: ", int(overall_class_grade), "%", sep = '') else: print("There are no students in the grade book.\n") else: print("That feature is not implemented yet.") #if user input is anything other than 1,2 or 3, user will be returned to main menu user_confirm = input("\nWould you like to return to the main menu?: \n") if user_confirm in confirm: menu_interface = input("Please enter the digit corresponding to the action you would like performed:\n(1) Add students to grade book\n(2) Search for students by name or ID\n(3) Print overall test averages\n") def main(): roster = gradebook() access_roster(roster) main()
#Jung Kim #CS-21 Intro to programming #Coding lab 4 - flagging suspicious e-mails #It will output various information outlined in the lab instructions #The program has been generalized for any text files written in standard e-mail format def open_email(): #simple function to open e-mails textfile = input("") #please input a text file to test file = open(textfile, "r") return file #returns the text file it opened def read_email(): #function reads and duplicates e-mail file = open_email() #sets variable for return value of open email function email_copy = [] #creates the template for the duplicate x = ['\n'] #step to get rid of the newlines; somewhat redundant as it could have been included in "special_characters" variable and removed all unwanted characters in email x = x[0].rstrip('\n') n = 0 #an arbitrary counter for the newline for line in file: #creates the duplicate email without newlines email_copy = email_copy + [line.rstrip('\n')] while x in email_copy: #deletes remaining newlines if (email_copy[n] == x): del email_copy[n] n = n + 1 #increasing counter to allow loop to cycle through the duplicate email line by line file.close() #closes original file as it is now unneeded return(email_copy) #returns the duplicate email for all the other functions to use def body_email(email): #this identifies the body of the email word_count = [] #creates a list to count words sentence_count = [] #creates a list to count sentences signature = ['Regards,', 'Best,', 'Sincerely,', 'Thank you,'] #common signatures people usually use; need manual input of various signatures, unnavoidable flaw(?) for n in range(0,len(email)): #the next two for loops identifies various "keywords" to help locate the body of the paragraph if (email[n].find('To:') != -1): receiver_index = n for n in range(0,len(email)): if (email[n] in signature): signature_index = n for n in range(receiver_index+2,signature_index): #uses the "keywords" to separate the body of the paragraph from rest of email word_count = word_count + email[n].rsplit(None) #the length of the entire body of the paragraph sentence_count = sentence_count + [email[n]] return(word_count, sentence_count) #returns the body of the paragraph separated into words and sentences def count_email(email): #this function counts the words and sentences in the email cleaned_sentence_count = {} #a dictionary to completely clean up the entire email of all unnecessary characters, could have been moved to read_email(), again somewhat redundant. will be revised later x = ['\n'] #same as read_email() x = x[0].rstrip('\n') word_count, sentence_count = body_email(email) annoying_delimiters = [',',' ','@','#','$','%','^'] #the annoying delimiters and special characters that will be removed except for '.', '!' and '?' as they signify the end of a sentence for n in range(0,len(annoying_delimiters)): #clean up cleaned_sentence_count[str(n)] = " ".join(sentence_count) cleaned_sentence_count[str(n)] = cleaned_sentence_count[str(n)].rsplit(annoying_delimiters[n]) sentence_count = cleaned_sentence_count[str(n)] for n in range(0,len(sentence_count)): #gets a list of sentences in the body of the email sentence_count = sentence_count[n].replace('?','.').replace('!','.').rsplit('.') #the function returns errors when multiple '!' and/or '?' and/or ellipses are present. need help with revision for n in range(len(sentence_count)): #gets rid of the newline here as well, the clean up with the annoying delimiter left a '' character which was leftover from a newline character if (sentence_count[n] == x): del sentence_count[n] print("The length of the E-mail is", len(word_count),"words.") #reports the word count print("The E-mail contains", len(sentence_count),"sentences.") #and the sentence count def extract_names(email): #a function to find the names & email of the sender/receiver, only took into account 1 receiver. multiple receiver would require further revision sender_email = "" sender = "" receiver_email = "" receiver = "" for n in range(0, len(email)): #sets multiple indicators for locating both sender and emails, will not work if email is not in standard format. if (email[n].find('<') != -1): if 'To' in email[n]: receiver_index = n receiver_email_index = email[n].index('<') receiver_email_end = email[n].index('>') receiver_indicator = email[n].index(':') else: sender_index = n sender_email_index = email[n].index('<') sender_email_end = email[n].index('>') for n in range(1, sender_email_end - sender_email_index): #sender's email sender_email = sender_email + email[sender_index][sender_email_index+n] for n in range(1, receiver_email_end - receiver_email_index): #receiver's email receiver_email = receiver_email + email[receiver_index][receiver_email_index+n] for n in range(0, sender_email_index - 1): #sender's name sender = sender + email[sender_index][n] for n in range(receiver_indicator + 2, receiver_email_index - 1): #receiver's name receiver = receiver + email[receiver_index][n] print("Sender's name: ",sender,"\nSender's e-mail address: ",sender_email) print("Recipient's name: ",receiver,"\nRecipient's e-mail address: ",receiver_email) def extract_title(email): #simple function; however subject of email relies on email being in standard format. will require revision otherwise print("Subject: ",email[0]) for n in range(0, len(email)): #locates time-stamp of the email using the ':' present in time of day and 'AM' or 'PM' if(email[n].find(':') != -1): if ('AM' in email[n] or 'PM' in email[n]): time_stamp = n print(email[time_stamp]) def flag_email(email): #flags the email for suspicious activity body_length, sentence_count = body_email(email) #calls the body_email functions to later determine what is "high frequency" email_vocab = [] #a list of all the words in the email flagged_term = [] #a list of all the words in the email that has been flagged as 'dangerous' unique_flagged_term = [] #unique flagged terms prevents the program from reporting duplicates (when there are multiple of the same flagged word, it would report each of them however many times they appeared in the email, ie it will report 'bomb appeared x times' x many times) cleaned_email = {} #clean up using same method as before, could probably make this a separate function total_flag_counter = 0 flagged_term_index = 0 priority = 0 flag_terms = ["dolor", "bomb", "bombs", "arms", "explosives"] #volatile word list, requires manual input special_characters = [',','.','?','!','@','#','$','%','^'] for n in range(0,len(special_characters)): cleaned_email[str(n)] = " ".join(email) cleaned_email[str(n)] = cleaned_email[str(n)].rsplit(special_characters[n]) email = cleaned_email[str(n)] for n in range(0, len(email)): #adds every word in the email to the list email_vocab = email_vocab + email[n].rsplit(None) for n in range(0,len(email_vocab)): #adds to the flagged word counter each time it appears, used for determining high frequency if (email_vocab[n].lower() in flag_terms): total_flag_counter = total_flag_counter + 1 for i in range (0,len(flag_terms)): #adds the flagged word into the list if (email_vocab[n].lower() == flag_terms[i]): flagged_term = flagged_term + [email_vocab[n].lower()] for n in range(0,len(flagged_term)): #determines how often a flagged term appears, the if/else statement is purely for grammatical correction if flagged_term[n] not in unique_flagged_term: unique_flagged_term = unique_flagged_term + [flagged_term[n]] if (flagged_term.count(flagged_term[n]) == 1): print("The word '",flagged_term[n],"' appeared once.", sep='') elif flagged_term.count(flagged_term[n]) == 2: print("The word '",flagged_term[n],"' appeared twice.", sep='') else: print("The word '",flagged_term[n],"' appeared ",flagged_term.count(flagged_term[n])," times", sep='') for n in range(0,3000): #equating priority to 'high frequency' if (total_flag_counter == n): priority = n if (priority <= len(body_length) * .02): #if the priority of the email (which is equal to the frequency of a flagged term) is only 2% the length of the body of the email then the email is tagged as low-priority (it is still necessary to check this email of suspicious activities!) print ("This E-mail has been flagged with low priority.") elif (priority <= len(body_length) * .05): #if the priority is 5% the length of the body of the email, then it is set to medium priority print ("This E-mail has been flagged with medium priority.") elif (priority <= len(body_length) * .9): #if the priority is 9% the length of the body of the email, then it is set to a high priority print ("This E-mail has been flagged with high priority.") else: #if the priority is greater than 9% of the body, then it requires immediate attention print ("This E-mail requires immediate attention.") def main(): #yay for modularity! email = read_email() extract_title(email) extract_names(email) count_email(email) flag_email(email) main() #the volatile word list (in flag_email(email)) is somewhat short, I only added a few thus far for testing reasons only, likewise with the signatures in body_email(email).
# a=float(input('Side A:')) # b=float(input('Side B:')) # c=float(input('Side C:')) a,b,c = input('Please enter 3 sides: ').split() a=float(a) b=float(b) c=float(c) print(a,b,c) p = (a+b+c)/2 triang = (p*(p-a)*(p-b)*(p-c))**0.5 print(triang)
# # str =input('enter Stroka palindrom: ') # str1 = str.replace(' ','') # print(str1) # # mylist = list(str1) # print(mylist) # # mylist.reverse() # newstr = '' # for i in mylist: # newstr = newstr+i # # if str1==newstr: # print('URA !!!', str+' = '+newstr) # else: # print('Fig Vam....') entry = 'never odd or even' # if entry.lower().replace(' ','') == entry.lower().replace(' ','')[::-1]: entry = entry.lower().replace(' ','') if entry == entry[::-1]: print('Ura') else: print('Uvi')
import time def insertionSort(vetor): n = len(vetor) inicio = (time.time() * 1000) for i in range(2, n): atual = vetor[i] j = i - 1 while j>0 and vetor[j]>atual: #Move os elementos menores para o inicio do vetor vetor[j+1] = vetor[j] j = j - 1 vetor[j+1] = atual fim = (time.time() * 1000) return str(round(fim - inicio, 4)) def shellsort(vetor): inicio = (time.time() * 1000) n = len(vetor) gap = n//2 #Começa com um grande pedaço do vetor e vai diminuindo ordenando-os while gap > 0: for i in range(gap, n): temp = vetor[i] j = i while j >= gap and vetor[j-gap] > temp: vetor[j] = vetor[j-gap] j -= gap vetor[j] = temp gap //= 2 fim = (time.time() * 1000) return str(round(fim - inicio, 4)) def exampleInsertions(v, v2): # v = [4, 6, 2, 60, 10, 33, 88, 9] # v2 = [4, 6, 2, 60, 10, 33, 88, 9] tempo = insertionSort(v) print("INSERTIONSORT") print(v) print(" Tempo: "+ tempo + " ms") print() print("SHELLSORT") tempo = shellsort(v2) print(v2) print(" Tempo: "+ tempo + " ms")
import time def mergeSort(vetor): if len(vetor) > 1: mid = len(vetor) // 2 # Encontrando o meio do vetor L = vetor[:mid] # Dividindo os elementos do vetor no meio R = vetor[mid:] mergeSort(L) # Ordenando a primeira metade mergeSort(R) # Ordenando a segunda metade i = j = k = 0 # Copiando os dados para os vetores temporários L[] and R[] while i < len(L) and j < len(R): if L[i] < R[j]: vetor[k] = L[i] i += 1 else: vetor[k] = R[j] j += 1 k += 1 # Verificando se algum elemento foi deixado while i < len(L): vetor[k] = L[i] i += 1 k += 1 while j < len(R): vetor[k] = R[j] j += 1 k += 1 def exampleIntercalations(vetor): # vetor = [99, 55, 33, 109, 23, 89, 21, 2, 30, 55, 78, 90, 400] # print("Vetor inicial:") # print(vetor) inicio = (time.time() * 1000) mergeSort(vetor) fim = (time.time() * 1000) print("MERGESORT:") print(vetor) print("Tempo: "+ str(round(fim - inicio, 4))+" ms")
import re regexp = r'"(?:[^\\]| "' print re.findall(regexp,'"I say, \\"hello.\\""') == ['"I say, \\"hello.\\""'] print re.findall(regexp,'"\\"') != ['"\\"']
# input_shape(2,2)의 lstm from keras.models import Sequential from keras.layers import Dense, LSTM, Dropout, BatchNormalization from sklearn.model_selection import train_test_split import numpy as np x = np.array(range(1,101)) y = np.array(range(1,101)) size = 8 def split_10(seq, size): aaa = [] for i in range(len(seq) - size +1): subset = seq[i:(i+size)] aaa.append([item for item in subset]) return np.array(aaa) dataset = split_10(x,size) # print(dataset.shape) # (93,8) x_train = dataset[:,0:4] y_train = dataset[:,4:] # print(x_train.shape) # (93,4) # print(y_train.shape) # (93,4) x_train, x_test, y_train, y_test = train_test_split( x_train, y_train, random_state=66, train_size = 0.6 ) x_train = x_train.reshape((x_train.shape[0],x_train.shape[1]//2,2)) x_test = x_test.reshape((x_test.shape[0],x_test.shape[1]//2,2)) print(x_train.shape) # (55,4,1) print(x_test.shape) # (38,4,1) print(y_train.shape) # (55,4) print(y_test.shape) # (38,4) model = Sequential() model.add(LSTM(32, input_shape=(2,2))) # inpurt_shape를 변경할 경우 두값의 곱은 항상 같아야 한다. # Dense 결합 model.add(Dense(5, activation='relu')) # model.add(Dense(5, activation='relu')) # model.add(Dense(5, activation='relu')) model.add(Dense(4)) # 4개의 출력 다:다 모델 model.compile(loss='mse', optimizer='adam', metrics=['mse']) from keras.callbacks import EarlyStopping early_stopping = EarlyStopping(monitor='loss', patience=30, mode='auto') model.fit(x_train, y_train, epochs=100, batch_size=1, verbose=1, callbacks=[early_stopping]) loss,acc = model.evaluate(x_test,y_test) y_predict = model.predict(x_test) x_predict = split_10(x,size) x_predict = x_predict[:,0:4] x_predict = x_predict.reshape((x_predict.shape[0], x_predict.shape[1]//2,2)) print(x_predict.shape) y_predict = model.predict(x_predict) # print(y_predict.shape) print('loss:', loss) print('acc:', acc) # print(y_predict) from sklearn.metrics import mean_squared_error def RMSE(y_test, y_predict): # 평균 제곱근 오차 return np.sqrt(mean_squared_error(y_test, y_predict)) # root(mean((y_test - y_predict)^2)) # 루트를 씨우는 이유 # 값을 작게 만들기 위해 print('RMSE: ', RMSE(y_test, y_predict)) # 작을 수록 좋다. # R2 구하기 from sklearn.metrics import r2_score # 0.95 만들기 r2_y_predict = r2_score(y_test, y_predict) # 1에 가까울수록 좋음 print('R2:', r2_y_predict)
import openpyxl #carregando o arquivo book = openpyxl.load_workbook('planilhadecompras.xlsx') #slecionando uma página frutas_page = book['Frutas'] #imprimindo os dados de cada linha for rows in frutas_page.iter_rows(min_row=2, max_row=5): for cell in rows: print(cell.value)
# x = 1 # speed = 1 # y = 1 # def setup(): # size(1500, 1500) # background(255) # def draw(): # global x # global y # background(255) # fill(255) # rect(x,100,50,25) # fill(0) # x = x + 1 # while y != 100: # if y % 5 == 0: # rect(10,100,50,25) # fill(0) # y = 1 + 1 # def draw(): # background(204) # s = second() # m = minute() # h = hour() # line(s, 0, s, 33) # line(m, 33, m, 66) # line(h, 66, h, 100) # time = "000" # initialTime = 0 # interval = 1000 # bg = color (255) # def setup(): # size(300, 300) # font = createFont("Ariel", 30) # background(255) # fill(0) # initialTime = millis() # frameRate(30) # def draw(): # global bg # global initialTime # global time # background(bg) # if (millis() - initialTime > interval): # time = nf(int(millis()/1000), 3) # initialTime = millis() # bg = color (random(255), random(100), random(255)) # text(time, width/2, height/2) # stuff = [] # i = second() # def setup(): # size(300, 300) # background(255) # def draw(): # global i # background(255) # fill(255) # if i == 1: # i = 0 # rect(x, 23, 200, 200) # fill (0) # print(i) # class Enemy(): # def __init__(self,xPos, yPos, l, h, speed): # self.x = xPos # self.y = yPos # self.l = l # self.h = h # self.speed = speed # def display(self): # fill(255) # rect(self.x, self.y, self.l, self.h) # def drive(self): # self.x += self.speed # enemies = Enemy(1, 50, 50, 50, 5) # enemies_list = [enemies] * 25 # x = 0 # i = 0 # time = "010" # t = 0 # interval = 10 # def setup(): # size(300, 300) # font = createFont("Arial", 30) # background(255) # fill(0) # def draw(): # global interval # global x # global i # global enemies_list # background(255) # x = x + 1 # t = interval-int(millis()/1000) # time = nf(t , 2) # if(t % 5 == 0): # i = i + 1 # enemies_list[i] # enemies.display() # interval+=1 def draw(): m = millis() noStroke() fill(m % 255) rect(25, 25, 50, 50)
import pickle # load the previous score if it exists try: with open('score.dat', 'rb') as file: score = pickle.load(file) except: score = 0 print ("High score: %d" % score) # your game code goes here score = 10 # save the score with open('score.dat', 'wb') as file: pickle.dump(score, file)
from collections import namedtuple Point = namedtuple("Point", ["lat", "long"]) class Region(object): def __init__(self, firstPoint, *args): self._nw = firstPoint self._se = firstPoint map(self.include_point, args) def northmost(self): return self._nw.lat def eastmost(self): return self._se.long def southmost(self): return self._se.lat def westmost(self): return self._nw.long def centre(self): return Point((self._nw.lat + self._se.lat) / 2, (self._nw.long + self._se.long) / 2) def contains_point(self, point): if self._nw.long <= self._se.long: # The "normal" case return (point.lat <= self._nw.lat and point.lat >= self._se.lat and point.long >= self._nw.long and point.long <= self._se.long) else: raise Exception("Not implemented") def include_point(self, point): if self.contains_point(point): # Check whether there is any work to do return # First, the easy one. Figure out if we need to expand the # region in the latitude direction self._nw = Point(max(point.lat, self._nw.lat), self._nw.long) self._se = Point(min(point.lat, self._se.lat), self._se.long) if self.contains_point(point): # Nothing left to do return # Longitude is the trickier one # Normally the westward edge will be <= than the eastward, but # not it the region crosses the -180 line if self._nw.long <= self._se.long: # The "normal" case west = self._nw.long - point.long if west < 0: west += 360 east = point.long - self._se.long if east < 0: east += 360 if west < east: self._nw = Point(self._nw.lat, point.long) else: self._se = Point(self._se.lat, point.long) else: raise Exception("Not implemented")
# Printing current date and time import datetime time = datetime.datetime.now() print("Current Date and Time", end=': ') print(time.strftime("%Y-%m-%d %H:%M:%S"))
proceeds = int(input("Введите значение выручки в рублях:")) costs = int(input("Введите значение издержек в рублях:")) if proceeds > costs: print("Вы отработали прибылью") profitability = proceeds / costs print(f"{profitability:.2f}") human = int(input("Введите количество сотрудников:")) print(f"{proceeds/human:.2f} - Прибыль фирмы в расчете на одного сотрудника") else: print("Вы работаете в убыток")
#creating employee class class Employee: print('Common base class for all employees') empCount = 0 #creating constructor def __init__(self, name, salary, age, bloodgroup): self.name = name self.salary = salary self.age = age self.bloodgroup = bloodgroup Employee.empCount += 1 def displayCount(self): print("Total Employee %d" % Employee.empCount) def displayEmployee(self): print("name :", self.name,"Salary:", self.salary,"age:", self.age,"bloodgroup:", self.bloodgroup) #displaying information print("This would create first object of Employ class") emp1 = Employee("Zara", 2000, 30, "A+") print("This would create second object of Employ class") emp2 = Employee("Manni", 5000, 33, "B-") emp1.displayEmployee() emp2.displayEmployee() print("Total Employee %d" % Employee.empCount)
def is_greater(x, y): if x > y: val = True return val else: return False assert not is_greater(4, 7) assert is_greater(8, 7)
import unittest from classes.room import Room from classes.guest import Guest from classes.song import Song class TestRoom(unittest.TestCase): def setUp(self): self.room = Room("Utahime", 100, "Karaoke Bar") self.guest_1 = Guest("Akira Nishikiyama", 200) self.guest_2 = Guest("Goro Majima", 300) def test_room_has_name(self): self.assertEqual("Utahime", self.room.name) def test_room_has_cost(self): self.assertEqual(100, self.room.cost) def test_room_has_theme(self): self.assertEqual("Karaoke Bar", self.room.theme) def test_room_has_guest_list(self): self.assertEqual(0, self.room.guest_list()) def test_check_in_guest(self): self.room.check_in_guest(self.guest_1) self.room.check_in_guest(self.guest_2) self.assertEqual(2, self.room.guest_list()) def test_check_in_group(self): group = [self.guest_1, self.guest_2] self.room.check_in_group(group) self.assertEqual(2, self.room.guest_list()) def test_check_out_guest(self): self.room.check_in_guest(self.guest_1) self.room.check_in_guest(self.guest_2) self.room.check_out_guest(self.guest_1) self.assertEqual(1, self.room.guest_list()) def test_check_out_group(self): group = [self.guest_1, self.guest_2] self.room.check_out_group(group) self.assertEqual(0, self.room.guest_list()) def test_song_in_the_list(self): self.assertEqual(0, self.room.song_list()) def test_add_song_in_the_list(self): song_1 = Song("Bakamitai", "Yakuza 0") self.room.add_song_in_the_list(song_1) self.assertEqual(1, self.room.song_list())
""" from sys import argv script, filename = argv # use argv to get filename txt = open(filename) # opens filename print "Here's %r..." % filename print txt.read() # do the read command with no params """ print "Enter file to open:" # print "Type the filename again:" file_again = raw_input("> ") txt_again = open(file_again) print txt_again.read() txt_again.close()
#Assignment 5, Group Work: Creating XML Files #Brett Byron; Group 1 import csv, os, xml.etree.ElementTree as ET #Add class to xml file def add_xml_class(dept, abbr, num, name, credit, days, seats, building, room): root = ET.parse(source="classes.xml") elements = root.getiterator() class_list = elements[0] new_class = ET.SubElement(class_list, "Class") department = ET.SubElement(new_class, "department") department.text = dept department.set("abbr", abbr) title = ET.SubElement(new_class, "title") class_num = ET.SubElement(title, "number") class_num.text = num class_name = ET.SubElement(title, "name") class_name.text = name class_cred = ET.SubElement(new_class, "credits") class_cred.text = credit class_days = ET.SubElement(new_class, "days") class_days.text = days class_seats = ET.SubElement(new_class, "class") class_seats.set("building", building) class_seats.set("room", room) root.write("classes.xml") print "New class added: " + abbr + " " + num classes = open(os.path.join(os.getcwd(), "classes.csv"), "r") read = csv.reader(classes) read.next() for row in read: abbr, number = row[0].split() department = row[1] name = row[2] credit = row[3] days = row[4] seats = row[-1] building, room = row[5].split() add_xml_class(department, abbr, number, name, credit, days, seats, building, room)
import brainteaser import random info = True def findout(): value1 = random.randint(1, 10) value2 = random.randint(1, 10) answer = input('What is {0} + {1}: '.format(value1, value2)) result = value1 + value2 if answer == result: print('Your answer is correct') else: print('Your answer is incorrect') def add(x, y): """ Add two numbers :param x: :param y: :return: """ return x+y def main(): num1 = 10 num2 = 20 result = add(num1, num2) num2 = 30 print(result) if __name__ == '__main__': findout()
import random def dictionary_words(num): file = open("/usr/share/dict/words", "r") words_list = (file.read().split('\n')) #.read gives whole file, .split splits a string into a list # print(words_list) new_list = [] # for word in range(num): # new_list.append(random.choice(words_list)) # return(' '.join(new_list)) for word in range(num): rand_num = random.randint(0, num) new_word = words_list[rand_num] print(rand_num) print(new_word) # new_list.append(new_word) if __name__ == '__main__': print(dictionary_words(3))
import time as t #import the time module #https://docs.python.org/3/library/time.html#time.time def bench(func): start_time = t.time() end_time = t.time() total_run_time = end_time - start_time return total_run_time #define functions # def test_function(): # sum = 0 # for i in range(100): # sum += i # return sum #record the time before running the code # start_time = t.time() #call the function # test_function() #record the time after the code has finished running # end_time = t.time() #The total time in seconds is differece between the start time and the end time # total_run_time = end_time - start_time
class Node(object): def __init__(self, data, next_node=None, prev_node=None): ''' Initialize previous node for doubly linked list''' self.next_node = next_node self.prev_node = prev_node self.data = data def __repr__(self): ''' Return a string representation of node''' return 'Node({!r})'.format(self.data) class Doubly(object): def __init__(): self.head = head self.tail = tail self.
import sample def markov(source): chain = {} current = None prev = None for word in source: current = word if not chain: chain[current] else: chain[prev] += current prev = current return chain if __name__ == '__main__': source = 'one fish two fish blue fish' print(markov(source))
import urllib.request #Importing necessary libraries from urllib.parse import urlparse from bs4 import BeautifulSoup url= input( "Enter the Url : ") #Input the URL page = urllib.request.urlopen(url) print("Total Size of web page is: " , len(page.read()), "bytes") #Outputting size of web page in bytes links=[] domains=[] page = urllib.request.urlopen(url) soup = BeautifulSoup(page ,'html.parser') for link in soup.find_all('a'): links.append(link.get('href')) #Adding all links to list named "Links" parsed_uri = urlparse(link.get('href')) #Parsing the URL for domain name domains.append('{uri.scheme}://{uri.netloc}/'.format(uri=parsed_uri)) #Appending parse url to list named "Domains" print("The links present are:") print(links) # Printing all links print ("Total number of links in web page are : ", len(links) , "Links") #Printing the total number of links count_dict = {i:domains.count(i) for i in domains} for c in count_dict: print("count of domain name ", c ,"=", domains.count(c)) #Printing Count of links pointing to same domain
import math class Joint: ''' A joint. ''' def __init__(self, n, loc, pred=None, suc=None, weight=1, angle=0): ''' Initialized joint object. ''' self.ID = n self.location = loc self.pred = pred self.suc = suc self.weight = weight self.angle = angle def findnextpos(self, interval): ''' Moves next joint to new location based on movement of current joint. INPUT: interval: *float* Angle by which each joint needs to move on every iteration. ''' ang = self.angle LENGTH = 100 a = LENGTH * math.cos(math.radians(ang)) + self.location[0] b = LENGTH * -math.sin(math.radians(ang)) + self.location[1] local = (a, b) self.suc.location = local self.suc.angle += interval
# -*- coding: utf-8 -*- """ Created on Fri Nov 29 20:58:20 2019 @author: axelb """ import socket import random import string s = socket.socket() port = 3000 s.connect(('127.0.0.1',port)) print("Recieved :-") temp = "" while True: data = s.recv(1024).decode("utf-8") if(temp is not data): temp = data print(temp) print("Do you want to create a file Y/N?") ch = input() if(ch == 'y' or ch == 'Y'): ch = "" file = open("data.txt","a") if(temp == "int"): print("Enter the number of integer values") x = int(input()) for i in range(x): res = random.randint(0,10) file.write(str(res) + "\n") elif(temp == "float"): print("Enter the number of float values") x = int(input()) for i in range(x): res = random.random() file.write(str(res)+"\n") elif(temp == "string"): print("Enter the number of strings") x = int(input()) for i in range(x): res = ''.join(random.choices(string.ascii_uppercase + string.digits, k = 7)) file.write(str(res) + "\n") elif(temp == "boolean"): print("Enter a boolean value") file.close() s.send(bytes("200","utf-8")) else: print("Enter input from the client : ") str1 = input() s.send(bytes(str1,"utf-8")) s.close()
#oefening09, gokken #we raden een getal tussen 1 en 20 import random #we laten onze appliccatie een getal kiezen te_raden_getal = random.randint(1,20) print(te_raden_getal) succes = False aantal_pogingen = 0 #we gaan op zoek naar het getal while succes == False : aantal_pogingen +=1 gokje = int(input(f"Doe een gokje tussen 1 en 20: >")) if gokje == te_raden_getal: print(f"Proviciat !") print(f"Je hebt {aantal_pogingen} pogingen nodig gehad.") succes = True #<-- noodzakelijk elif gokje > te_raden_getal: print(f"Het gezochte getal is groter. Prober opnieuw!") else: print(f"Het gezochte getal is groter. Probeer opnieuw!")
def matmul(A): a={} for i in range(len(A)-1): for j in range(0,len(A)-i-1): if i==0: b=(j,j) a[b]=0 elif i==1: b=(j,j+1) a[b]=A[j]*A[j+1]*A[j+2] else: b=(j,j+i) a[b]=float('inf') for k in range(j,j+i): hold=a[(j,k)]+a[(k+1,j+i)]+A[j]*A[k+1]*A[j+i+1] if hold<a[b]: a[b]=hold print(a[(0,len(A)-2)]) print(a) a=[1,2,3,4] matmul(a)
def main(): T = int(input()) for case in range(T): grade = list(map(int, input().split())) N = grade.pop(0) avg = sum(grade) / N cnt = 0 for i in grade: if i > avg: cnt+=1 persent = round((cnt/N)*100,3) print("{:.3f}%".format(persent)) if __name__=="__main__": main()
import sys def main(): while True: string = sys.stdin.readline() if string[0] == '#': break stack = [] for i in range(len(string)): if string[i] == '<': idx = i elif string[i] == '>': tag = string[idx:i+1] if len(stack) == 0 or '/' not in tag: stack.append(tag) elif tag[1] != '/': continue else: before = stack[-1].split() if tag[2:-1] in before[0]: stack.pop() else: break if len(stack) == 0 : print("legal") elif len(stack)>0: print("illegal") if __name__=="__main__": main()
#TODO def main(): N = int(input()) arr = [] arr_len =[] answer=[] for _ in range(N): k = list(input()) arr.append(k) arr_len.append(len(k)) print(arr) print(arr_len) for _ in range(N): idx = arr_len.index(min(arr_len)) answer.append(arr[idx]) arr_len.pop(idx) arr.pop(idx) arr = answer[:] print(answer) if __name__=="__main__": main()
# Love Calculator class LoveCalculate: lover_name = "Hello" partner_name = "World" def __init__(self, lover_name, partner_name): self.lover_name = lover_name self.partner_name = partner_name @staticmethod def remove_space(sentence): return sentence.replace(" ", "").lower() @staticmethod def generate_lists(sentence): lists = [] while len(sentence): first_letter = sentence[0] first_letter_count = sentence.count(first_letter) lists.append(first_letter_count) sentence = sentence.replace(first_letter, "") return lists def generate_sentence(self): return self.lover_name + ' loves ' + self.partner_name def calculate(self): sentence = self.generate_sentence() computing_sentence = self.remove_space(sentence) computing_lists = self.generate_lists(computing_sentence) return computing_lists lover_name = input("Your Name: ") partner_name = input("Partner Name: ") love_calculator = LoveCalculate(lover_name, partner_name) print(love_calculator.calculate())
# Object Oriented class Number: price = 1 def __init__(self, price): self.price = price def check_odd_even(self): if self.price % 2: return str(self.price) + " is Odd Number" else: return str(self.price) + " is Even Number" number = int(input("Enter a Number: ")) numObject = Number(number) print(numObject.check_odd_even())
# fibonacci series def fibonacci(x): sequence_list = [] current = 0 another = 1 for i in range(x): sequence_list.append(current) current = another if i > 0: another = sequence_list[i] + current else: another = 1 return sequence_list # produces a sum for the kth fibonacci number def print_fibonacci(x): print(str(fibonacci(x))) length = int(input('Length of Fibonacci Series: ')) print_fibonacci(length)
#Emerging Technologies #Python Fundatmentals Problem Sheet #Ríona Greally - G00325504 #8.Write a function that merges two sorted lists into a new sorted list. [1,4,6],[2,3,5] → [1,2,3,4,5,6]. #creating 2 lists list1 = [3,4,9] list2 =[2,5,6] #using sorted function to merge and sort the lists print(sorted(list1 + list2))
from simpleimage import SimpleImage DEFAULT_FILE = 'countries.jpg' def main(): print("\nHello! My name is Coffee Taster, and I will help you navigate through the world of coffee :)") print("It's grown in many countries, and its taste differs depending on the climate.") print("Tell me what coffee you like, and I will show countries that grow it!") answer = input("\nPress ENTER to continue. Type 'all' to see the map. Type 'q' to quit. ") while answer != 'q': if answer == '': color = get_taste() countries = filter_color(color) describe(color) countries.show() elif answer == 'all': SimpleImage(DEFAULT_FILE).show() answer = input("\nPress ENTER to continue. Type 'all' to see the map. Type 'q' to quit. ") def get_taste(): # input: a word from user (acidic, sweet, bitter/dark) # output: a color corresponding to a taste taste = input("\nWhat coffee do you like: acidic, sweet, or bitter? ") taste_palette = {'acidic': 'green', 'sweet': 'red', 'bitter': 'blue'} while taste_palette.get(taste) == None: taste = input("Please, type one of these words: acidic, sweet, or bitter. ") color = taste_palette.get(taste) return color def filter_color(color): """ this function leaves only pixels of given and black color and returns a map """ image = SimpleImage(DEFAULT_FILE) for px in image: green = px.green < (px.red + px.blue) red = px.red < (px.blue + px.green) blue = px.blue < (px.green + px.red) average = (px.red + px.green + px.blue) / 3 if average > 75: if color == 'blue' and blue == True: px.red = 255 px.green = 255 px.blue = 255 elif color == 'red' and red == True: px.red = 255 px.green = 255 px.blue = 255 elif color == 'green' and green == True: px.red = 255 px.green = 255 px.blue = 255 return image def describe(color): # input: taste of coffee: acidic, sweet or bitter # output: list of countries on the map, three descriptors if color == 'blue': print("\nYemen, India, Indonesia, Peru, and Brazil grow coffee that you like! \nCoffee from these countries tastes somewhat heavy and nutty.") elif color == 'red': print("\nRwanda, Uganda, Kenya, China, Vietnam, Thailand, and Colombia grow coffee that you like! \nCoffee from these countries tastes like fruit or chocolate.") elif color == 'green': print("\nEthiopia and Burundi grow coffee that you like! \nCoffee from these countries tastes like candied fruit or berry.") if __name__ == '__main__': main()
s = input("Enter your string : ") m = {i:s.count(i) for i in s} m_length = len(m) m_value = list(m.values()) m_max = max(m_value) m_new = [m_max - m_value[i] for i in range(m_length)] if(m_new.count(0)==m_length or m_new.count(1)==1): print("This is My String") else: print("This Is not my string")
#CODE FOR Q1: def isStrDigit(x): #Check if a string is number of not for i in range(len(x)): if x[i]=='0' or x[i]=='1' or x[i]=='2' or x[i]=='3' or x[i]=='4' or x[i]=='5' or x[i]=='6' or x[i]=='7' or x[i]=='8' or x[i]=='9' : continue else: return False break return True def readNumber(s,i) : x = i while (x < len(s)): if (isStrDigit(s[x]) or s[x] == '.') : x += 1 else : break number = float(s[i:x]) return number, x def evalParan(s, i): #This function is used to evaluate the value inside a given parenthesis. assert s[i] =='(' and s[len(s)-1] == ')',"Operation not in parenthesis" #This assertion makes sure that input is within parenthesis if (isStrDigit(s[i + 1])) : a, j = readNumber(s, i + 1) else : a, j = evalParan(s, i + 1) if (isStrDigit(s[j + 1])) : b, k = readNumber(s, j + 1) else : b, k = evalParan(s, j + 1) assert s[j]!= '('or s[j]!= ')',"Invalid operation defined" if (s[j] == '+') : ans = a + b elif (s[j] == '-') : ans = a - b elif (s[j] == '*') : ans = a * b elif (s[j] == '/') : ans = a / b return ans, k + 1 def evaluate (s) : # Function here gives the evaluated value after all the calculations above. if (s[0] != ')' or s[len(s) - 1] != ')' ) : s = '(' + s + ')' x, y = evalParan(s, 0) return x print(evaluate("1+1")) print(evaluate("(((2*3)*4)*5)+99")) print(evaluate("1+(((123*3)-69)/100)")) #CODE FOR Q2 def sumSequence(n): arr = [1,2] k = arr[-1]+1 # Outermost loop runs till length of array < n but when length is n-1 we append another k then it becomes n and loop finishes. while len(arr)<n : assert len(arr)<n,"Limit over" count =0 #Initially count of possiible combinations to give k is 0. for i in range(len(arr)-1): for j in range(i+1,len(arr)): assert k > arr[i] and k > arr[j],"Not possible" if arr[i]+ arr[j]==k: count+=1 if count>1: break if count==1: #Since the count is 1, k appended, and we can represent k as a unique combination of two elements, else k=k+1. arr.append(k) k+=1 print(arr) sumSequence(50) #CODE FOR Q3 def minLength(A,n): k = len(A) #Initial min length is set to len(A)+1, because we do not know that even if we add all the elements, we get a val > n length = len(A)+1 for i in range(len(A)): if A[i]>n: return 1 val = A[i] for j in range(i+1,len(A)): val+=A[j] if j-i+1 < length and val > n: length= j-i+1 if length<=len(A): return length else: return -1 print(minLength([0,1,1,0], 2)) print(minLength([3,-1,4,-2,-7,2], 4)) print(minLength([4,5,8,2,-1,3], 9) ) #CODE FOR Q4 def mergeContacts(arr): #Changing a tupled list to list of list [(),()]->[[],[]] def tupleToList(arr): ans=[] for i in range(len(arr)): ans.append(list(arr[i])) return ans #'a' is the list of list form of tupled list arr a= tupleToList(arr) #'ks' is an empty list which gets updated with the first element of all elements in 'a' as the loop proceeds ks = [] for i in range(len(a)): ks.append((a[i][0])) #'ls' is a sublist of 'ks' which doesn't contain all elements in 'ks' without repetition ls=[] for i in ks: if i not in ls: ls.append(i) #'xs' is a list which will have all the email addresses corresponding to the same name correctly merged xs=[] i=0 while len(a)!=0 and i <len(a) : j=i+1 ys = [] ys.append(a[i][1]) while j <len(a): if a[i][0]==a[j][0] and j <len(a): ys.append(a[j][1]) a.pop(j) j+=1 xs.append(ys) i+=1 #combining 'ls' and 'xs' with proper ordering kept fixed def listToTupledList(l1, l2): return list(map(lambda x, y:(x,y), l1, l2)) ans = listToTupledList(ls,xs) return ans arr =[("RN","narain@cse"), ("HS","saran@cse"), ("RN","Rahul.Narain@iitd"),("HS","[email protected]"),("RN","[email protected]")] print(mergeContacts(arr))
""" convolutional neural network flow of the convolutional network for example, 256*256 RGB photo, the width and height are compressed into smaller size of arrays and the depth is increased during stride: the pixels for one step 2 key methods: 1. valid padding: the resultant size after striding > original size 2. same padding: the resultant size after striding = original size pooling is for solving large stride which will make the loss of the msg of orginal photo. Pooling: max pooling avg pooling images -> convolution -> max pooling -> convolution -> max pooling -> fully connected -> fully connected -> classifier """ import tensorflow as tf from tensorflow.examples.tutorials.mnist import input_data import numpy as np import matplotlib.pyplot as plt tf.set_random_seed(1) np.random.seed(1) train_size = 500 acc_no = 1000 learning_rate = 0.0001 def compute_accuracy(v_xs, v_ys): global prediction global acc_no y_pre = sess.run(prediction, feed_dict={xs: v_xs, keep_prob: 1}) correct_prediction = tf.equal(tf.argmax(y_pre,1), tf.argmax(v_ys,1)) accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32)) result = sess.run(accuracy, feed_dict={xs: v_xs, ys: v_ys, keep_prob: 1}) # print('result: {}'.format(np.argmax(v_ys, 1))) # print('predic: {}'.format(np.argmax(y_pre, 1))) return result xs = tf.placeholder(tf.float32, [None, 784], name='x_in') ys = tf.placeholder(tf.float32, [None, 10], name='y_in') keep_prob = tf.placeholder(tf.float32, name='keep_prob') x_image = tf.reshape(xs, [-1, 28, 28, 1]) #print(x_image.shape) mnist = input_data.read_data_sets('MNIST_data', one_hot=True) def conv_layer(input, channel_in, channel_out, strides = 2, name='conv'): with tf.name_scope(name): # shape=[patch x's size, patch y'size, input height , output height] with tf.name_scope('Weight'): W_conv = tf.Variable(tf.truncated_normal(shape=[5,5,channel_in,channel_out], stddev = 0.1), name = 'W') #patch 5*5 tf.summary.histogram(name + '/Weights', W_conv) with tf.name_scope('Bias'): b_conv = tf.Variable(tf.constant(0.1, shape =[channel_out]), name = 'B') tf.summary.histogram(name + '/Bias', b_conv) with tf.name_scope('conv_layer'): h_conv =tf.nn.relu(tf.nn.conv2d(input, W_conv, strides=[1,1,1,1], padding='SAME') + b_conv) #28*28*32 with tf.name_scope('Pooling_layer'): h_pool = tf.nn.max_pool(h_conv, ksize = [1,2,2,1],strides=[1,strides,strides,1], padding='SAME') #14*14*32 return h_pool def fc_layer(input, channel_in, channel_out, name='fc_layer'): with tf.name_scope(name): with tf.name_scope('Weight'): W_f = tf.Variable(tf.truncated_normal([channel_in,channel_out], stddev = 0.1), name='W') tf.summary.histogram(name + '/Weights', W_f) with tf.name_scope('Bias'): b_f = tf.Variable(tf.constant(0.1, shape =[channel_out]), name='B') tf.summary.histogram(name + '/Bias', b_f) with tf.name_scope('fc_layer'): output = tf.matmul(input, W_f)+b_f tf.summary.histogram(name + '/weights', output) return output ## conv1 conv1 = conv_layer(x_image, 1, 32, name='conv1') ## conv2 conv2 = conv_layer(conv1, 32, 64, name = 'conv2') #func1 layer with tf.name_scope('func1'): h_pool2_flat = tf.reshape(conv2,[-1,7*7*64]) #[n_sampes, 7, 7, 64] ->>> [n_samples, 7*7*64] h_f1 = tf.nn.relu(fc_layer(h_pool2_flat, 7*7*64, 1024)) h_f1_drop = tf.nn.dropout(h_f1, keep_prob) #func2 layer with tf.name_scope('prediction'): prediction = tf.nn.softmax(fc_layer(h_f1_drop, 1024, 10)) with tf.name_scope('cross_entropy'): cross_entropy=tf.reduce_mean(-tf.reduce_sum(ys*tf.log(prediction),reduction_indices=[1])) tf.summary.scalar('cross_entropy', cross_entropy) with tf.name_scope('train'): train_step=tf.train.AdamOptimizer(learning_rate).minimize(cross_entropy) sess=tf.Session() merged = tf.summary.merge_all() writer = tf.summary.FileWriter("logs/", sess.graph) sess.run(tf.global_variables_initializer()) for i in range(train_size): batch_xs, batch_ys = mnist.train.next_batch(100) sess.run(train_step, feed_dict={xs: batch_xs, ys:batch_ys , keep_prob: 0.5}) if i %50 == 0: ce = sess.run(merged, feed_dict={xs: batch_xs, ys:batch_ys , keep_prob: 0.5}) writer.add_summary(ce, i) print(i, ' accuracy: ',compute_accuracy(mnist.test.images[:acc_no], mnist.test.labels[:acc_no])) sess.close()